Check if stream is on or off TWITCH API using PHP

Question: The following ifalways return "Stream is Online!", even when "Stream is Offline!"
Could anyone point me the error?
    <?php
    $opts    = array(
        'http' => array(
            'method' => "GET",
            'header' => "Client-id: clientidhere\r\n" . "Accept: application/vnd.twitchtv.v5+json\r\n"
        )
    );
    $context = stream_context_create($opts);
    $file    = file_get_

contents('https://api.twitch.tv/kraken/streams/somestreaming', false, $context);
$json    = json_decode($file);

if (($json->stream === "NULL") || ($json->stream === "null")) {
    echo "Stream is Offline!";
} else {
    echo "Stream is Online!";
}

?>

Comment: `$json->stream === "NULL"` explictly equalling a string of null seems super strange from an API
Comment: what does `var_dump($json);` say?
Comment: @Progman it dumps correctly with the respective information..
Comment: For example, it dumped this: object(stdClass)#1 (1) { ["stream"]=> NULL } but it says the stream is online
Answer: For me, I write as follows.
    if (empty($http_response_header)){
        echo "Stream is Offline!\n";
    } else {
        echo "Stream is Online!\n";
    }

Note: $http_response_header is not empty when first request was succeeded then second request was failed, so you should need to empty $http_response_header before each requests.
$http_response_header = '';
file_get_contents(...);

Comment: Being unable to communicate with an API isni't indictaive of the stream state is it?
Comment: @Scuzzy, you are 100% right, however in other cases, I think you should look at `$ http_response_header`. For example, when an error occurs in `json_decode` or when the response type is `application/xml`.


Cheating in the Olympics

Question: Cameron van der Burgh of South Africa won the gold medal and set a world record in the 100m breaststroke at London 2012, but has since admitted to cheating after the Austrialian swim team accused him of taking more dolphin kicks than allowed by the rules.
Reports claim that he will not be stripped of his gold medal because the time to submit an appeal has long passed, and there is no appeal system in place to warrant such an action. However, medals have been stripped from those that took performance-enhancing drugs.
If this is the case, then how does the IOC/governing bodies have power to strip medals from those who admitted/proved to doping but not from those who admitted/proved to such cheating?
Comment: I'd have to assume that there are rules for doping, but not for this type of cheating/rule-bending.
Comment: Not even a "catch-all" to consider such cases?
Answer: The individual Federations, in this case FINA, make all decisions of this nature, not the IOC. Only FINA could strip someone of a medal, following whatever rules they have for the particular situation. As noted, the appeal period has passed so this result will stand according to the rules that all FINA sanctioned events are run under.
As part of the requirements to be considered an Olympic sport, all Federations must adhere to the rules around doping as stipulated by WADA. These are pretty tough, including the retrospective stripping of medals that goes far beyond most other forms of cheating or dubious actions.
For the record, in this situation the rules, or the enforcement of them, are to blame and not the athlete(s). van der Burgh is guilty only of excess honesty (and this is coming from an Australian). This is on par with say basketball players bending the rules on travelling but getting away with it due to a relaxed interpretation from the umpires. Is that cheating? I wouldn't think so, it's just optimising performance within the imposed constraints.
Comment: +1 Good answer. Good point about "enforcing" rules vs. "cheating." If it's "relaxed," players will take as much advantage as they can of such a rule.
Comment: See [this](http://sports.stackexchange.com/questions/1025/what-happens-if-there-is-a-tie-during-an-olympic-race/1027#1027) question regarding a tie at the 2012 US Trials for track and field....similar situation in terms of "lack" of a rule to enforce such a situation.
Comment: Note, FINA has experimented with underwater cameras to catch these kinds of offenses, I think we will be seeing them coming into play in the next few years. Either that or they they will loosen the rules on breast stroke again.

Cheating in the Olympics


Is there a Python function to repeat string patterns to get faster multiple columns in different dataframes

Question: I'm new in Python, I need to get many variables in multiple dataframes:
I wrote this code but I need a long time to configure it for many excersises.
This is the code:
import pandas as pd

df = pd.concat([df1[df1.columns[0]], df2[df1.columns[0]], df1[df1.columns[1]],
                df2[df1.columns[1]], df1[df1.columns[2]], df2[df1.columns[2]],
                df1[df1.columns[3]], df2[df1.columns[3]], df1[df1.columns[4]],
                df2[df1.columns[4]], df1[df1.columns[5]], df2[df1.columns[5]],
                df1[df1.columns[6]], df2[df1.columns[6]]], axis=1)

The number of dataframes and columns can be much bigger. Thanks.
Comment: What I have done is to write a simple program to create the text you need.
Comment: A program in Python? How?
Comment: Please specify your input and desired output
Answer: It looks like what you're trying to do is: for all of the columns in one dataframe, combine the columns from that dataframe with those from another with the same columns, into a single dataframe with two of every column in the same original order.
In your case:
df1 = DataFrame([['a','b','c'], ['d','e','f']])
df2 = DataFrame([['g','h','i'], ['j','k','l']])

df = concat([s for ss in [(df1[c], df2[c]) for c in df1.columns] for s in ss], axis=1)

print(df)

Result:
   0  0  1  1  2  2
0  a  g  b  h  c  i
1  d  j  e  k  f  l


View restricted to a specific taxonomy term

Question: I have a custom content type called Property with taxonomy term fields set up for example for vocabularies Train Station, Style, and Area.
I would like to create a view showing only those Properties with a specific term within the taxonomy for example only the ones with the term London Bridge in the Train Station vocabulary.
I assumed this would be Filter Criteria in the view, however the only related option I can see is Content:Has taxonomy term which brings in all Properties that has Train Station - but I cant see how I can add the extra filter of only London Bridge within Train Station
Any ideas?
Comment: Can you clarify what vocabularies you have and what terms you have in those vocabularies. You can always ctrl-click terms in the term list to add more than one filter, but if you're looking for something more dynamic than building several views one by one by hand, you would likely be using contextual filters. There are many possibilities there, so you need to explain in more detail what it is you're trying to do.
Comment: I have a content type called property, and a term reference field called Train Station.= which calls upon the taxonomy Train Station. By example the Taxonomy calls in 2 terms London Bridge and Victoria. I am trying to create 2 pages - 1 which pulls in teasers of all properties in Victoria and 1 with London Bridge. These will be fixed landing pages showing properties for each and eventually will have a block at the top with unique copy for each page
Comment: If you go to admin/structure/taxonomy/property you get a list of all the terms as links to each term's teaser listing, like taxonomy/term/1 so the basic version is already in there, in core. If you want more control, you can clone the Taxonomy term view that comes with Views module, and modify that.
Comment: No at all. I edited your question heavily, please check it. I also put in answer, trying to answer just what you asked, realizing that what you eventually want to build will be more.
Answer: Assuming I understand the question correctly - potentially the easiest way to achieve this is to add a 'Term Reference' field to your 'Property' content type.
This needs to point at the taxonomy 'Train Station', and you can have multiple term references if you need other terms to describe properties.
You can then use this term reference field as a view filter. You'll be looking for "Content:term_reference_field_name" as opposed to "Content:Has taxonomy term" This will allow you to filter on a particular taxonomy term.
Good luck!
Comment: I have train station as a term reference field for property, and what you suggest sounds like it should work, however in Filter Criteria 'Content:term_reference_field_name' does not come up as an option. Any ideas?
Comment: by adding a relationship - Content: Tags (field_tags) i get other options and have added the filter Taxonomy term: Term (= London Bridge), a page is create but shows an empty page - I can confirm that I have properties with this Taxonomy though
Comment: Cracked it, thanks - I was using the wrong relationship
Answer: What you are looking for is very basic functionality in Drupal. By default, if you go to a term's page, for example taxonomy/term/1, what you get is indeed a teaser list for all nodes that have that term.


Armazenar retorno Javascript em variável php

Question: Galera estou precisando muito armazenar um retorno Javascript em uma variável php.
no meu arquivo js eu tenho o elemento javascript que me retorna o id da minha categoria como mostrado abaixo:
document.getElementById("editcategoria").     value = resposta['dados'].Categoria_Prod_idCategoria;

no php eu recupero o value em um input com o id="editcategoria":
<input type="text" id="editcategoria"  name="editcategoria">

Quando executo no navegador está funcionando perfeitamente, mas para atender a minha necessidade eu preciso que ao ser retornado a informação para o php em vez de ser armazenado em um input, eu possa armazenar em uma variável php por exemplo:
<?php $variavelphp = retorno do javascript
      echo $variavelphp;?>

Já fiz várias pesquisas a respeito mas sem sucesso, caso precisem de mais informações estou a disposição!
Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Answer: Submetendo o formulário contendo o input com atributo name="editcategoria", o valor do input será recebido pelo PHP como $_POST['editcategoria'] ou $_GET['editcategoria'], dependendo se o método de envio do formulário for post ou get.
Antes de submeter de volta para o servidor, o php não sabe o que está acontecendo no lado do cliente.


Are scales usually 7 notes in Middle-Eastern music?

Question: I noticed that the Phrygian dominant (aka hijaz maqam) is used a lot in Middle-Eastern music. I also noticed that the oud, which is capable of playing microtonal intervals, is used a lot too.
Although the oud can play microtonal intervals, does Middle-Eastern music still usually use scales that are made up of 7 diatonic notes (such as the Phrygian), that can be played on "non-microtonal" instruments such as the piano? In other words, are the scales that are used in the Middle East usually just a "mode" of Western scales?
Answer: No. Often, they are not modes of Western scales. On my algerian mandole, I really do need the 1/4 tone frets to play some of the mini scales that (when combined) produce a maqam.
It really gives a distinctive (uncomparable to western scales) colour to the sound.
Although some of these mini scales perfectly fit the western Major or Minor tri/tetra chords... others (which are my prefered) just do not fit at all.
On my instrument there are only two 1/4 tone frets, and I think it the case for all algerian mandole. So it is nowhere as versatile as an Aoud you are refering to, but it is far sufficient to give access to a bunch of those micro tonal mini scales, which are NOT AVAILABLE for a standard western guitar fretted neck.
I don't remember the names of those musical forms.
I have to search through my notes/links. I will update this answer accordingly with relevant names and information.
Comment: thanks for your reply, how many notes are these scales usually?
Comment: We combine mini-scales of 3, 4 or 5 notes. They are called Jins/Ajnas. One Jins is one form of 3 - 4  or 5 notes. Ajnas is the arabic plural of Jins. Several Jins contains notes which are not accessible for a piano keyboard. I will post some examples when I'll edit my answer.
Comment: Do you also play Maqams, such as hijaz maqam?
Comment: @foreyez The one that I used to play most on western guitars, is the addition of two consecutive jins hijaz. (E F G# A) + (B C D# E). Which is what attracted me to learn Flamenco music at first, the use of this scale, which is the descent of Hijaz Maqam are you refering to. I think the traditional up movement is (E F G# A) + (B C D E). The combinations are really complex, good for improvisation, I'm still learning. And for learning, I have to decompose them in Jins. There exists MORE than 80 maqams in Middle Eastern music (IIRC).
Answer: You are really asking two questions here:
"Are scales in middle eastern music usually 7 notes?"
"Can most middle eastern music be played typical on Western instruments?"
The answer to the first question is "kind of."  You can conceptualize most (though not all) Arabic music in terms of 7-note scales if you want.
It's a pretty rough appoximation though.
It's not how the music actually works and ends up being misleading.
The longer answer requires understanding that "scales" in the Western sense are not really a generative or organizing principle in Arabic music.  The underlying principle is the jins (pl. ajnas), as noted by Stephane in his comments. These are smaller, localized groups of notes that are combined to create maqam music.   Most music uses multiple ajnas starting on different notes throughout the piece, in ways that can't be described in a simple scale concept.  The closest we come to this in western music would be the way the melodic minor scale is used.
The answer to the second question is categorically "no" - the two most common maqamat in middle eastern music are the Rast family (which has microtonal 3rd and 7th degrees at least) and the Bayati/Ussak family (which has microtonal 2nd and 6th degrees at least).  Very few pieces of middle eastern music avoid microtonality entirely. Even in pieces that more or less correspond to a mode that we have in Western music (Nahawand/Buselik = Minor, Kurd = Phyrgian, Ajam = major), there are usually sections that are in a microtonal jins.  But there are definitely some pieces which are possible to play without microtones, such as Lamma Bada Yatathanna, or Bint al Shalabiyya.
The violin family, being fretless, is certainly capable of playing these scales (it is popular in middle eastern music), but most Western violinists cannot do it (unless they have studied middle eastern music). Other instruments can do it to some extent with practice: trumpet, clarinet, saxophone all have flexible pitch and a musician with good ears who works on it can do it.
A good resource on this is the website www.maqamworld.com.
One of the authors of that site has an excellent (and peer-reviewed) book "Inside Arabic Music" if you really want a deeper exploration of the music theory.
Comment: Trombone is typically called out in discussions of tuning in European music as an instrument that, like fretless strings, has infinite pitch variability.  I'm unaware of its use in "middle eastern" music, but the possibility is intriguing.


Handling panics of external libraries

Question: I am new to Rust and have come to understand Rust defaults to panics and not exceptions.
I have a rust project that depends on external libraries.
I have handled all unwraps and ?'s in my code using match statements, but I am not sure how to handle a panic by external libraries.
In other languages I would just catch an exception thrown by the library.
As Rust defaults to panics, the libraries don't return an exception but panic and thus abort execution of the thread.
I would ideally want to log and continue execution, not panic and abort.
I have tried the following:

catch_unwind, but this looks like something I can't use on an external library.
log-panics crate, which logs the panic using a panic hook. I am able to log the panic, but not prevent aborts.
Answer: DON'T PANIC
I mean, that's the real solution: you must avoid panics, not try to recover from them when they happen.
Some languages casually use exceptions to deal with conditions preventing some operations, and manage them without crashing.
In Rust, those unsupported conditions are managed with errors, not panics.
A panic in Rust is

most often a bug, usually temporary because you've put an unwrap in your first prototyping
or a very extraordinary condition

As the Book says:

When code panics, there's no way to recover

The various utilities like catch_unwind are, at best, aiming at more gracefully quitting, they don't let your program run as if nobody happened.
When a crate you use panics, first check you're using the function as expected (and if you can't check that without panicking that's a bug in that lib), then either have it fixed or fix it yourself if you can.
There's no reasonable way to deal with a casual panic, apart from crashing as fast as possible. A panic isn't casual in the life of your program.
Comment: Sorry, I always wanted to write "don't panic" in large friendly letters.
Comment: May I suggest emphasizing that if a library provides no way to handle (or check for) a situation without panicking, that's a bug in the library's API design?
Comment: This is a non-answer. In my case something in web_sys or wasm_bindgen_futures is panicing, I can't rewrite these libraries and the panic is very hard to reproduce so it's also nearly impossible to produce a decent report for those teams. If I could simply catch the panic, I think it could just be ignored, instead of now have a poisoned mutex to deal with.
Comment: @ClaytonRabenda No, you shouldn't try to handle panics as what some other languages call exceptions. As the rust book [says](https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html) "When code panics, there's no way to recover".
Comment: @KevinReid Trying to put that in the answer.

Handling panics of external libraries


Ionic app assinado não instala manualmente

Question: Galera, eu criei o app release no ionic certinho, criei a chave, assinei o app, passei ele pelo zipaligh e ficou pronto. Problema é que quando eu vou instalar ele manualmente no celular (sem colocar na loja) ele tenta instalar, mas no fim da uma mensagem de que o app não foi instalado. Queria saber se é algum problema com o app ou se somente n instala dessa maneira?
Comment: Eu sempre instalo no meu. Verifique se já tem o app ou algum app instalado com o mesmo package. Você também pode habilitar a instalação de fontes desconhecidas >>> https://www.tecmundo.com.br/como-fazer/25728-android-como-habilitar-a-instalacao-de-fontes-desconhecidas.htm
Answer: Se você tinha a versão antiga não assinada no celular, vc deve excluir e então depois disso pode instalar a versão assinada.


How to interpret F-measure values?

Question: I would like to know how to interpret a difference of f-measure values. I know that f-measure is a balanced mean between precision and recall, but I am asking about the practical meaning of a difference in F-measures.
For example, if a classifier C1 has an accuracy of 0.4  and another classifier C2 an accuracy of 0.8, then we can say that C2 has correctly classified the double of test examples compared to C1. However, if a classifier C1 has an F-measure of 0.4 for a certain class and another classifier C2 an F-measure of 0.8, what can we state about the difference in performance of the 2 classifiers ? Can we say that C2 has classified X more instances correctly that C1 ?
Comment: I'm not sure you can say much since the F-measure is function of both precision and recall: http://en.wikipedia.org/wiki/F1_score. You can do the math though and hold one (either precision or recall) constant and say something about the other.
Answer: I cannot think of an intuitive meaning of the F measure, because it's just a combined metric.  What's more intuitive than F-mesure, of course, is precision and recall.
But using two values, we often cannot determine if one algorithm is superior to another. For example, if one algorithm has higher precision but lower recall than other, how can you tell which algorithm is better?
If you have a specific goal in your mind like 'Precision is the king. I don't care much about recall', then there's no problem. Higher precision is better. But if you don't have such a strong goal, you will want a combined metric. That's F-measure. By using it, you will compare some of precision and some of recall.
The ROC curve is often drawn stating the F-measure. You may find this article interesting as it contains explanation on several measures including ROC curves:
http://binf.gmu.edu/mmasso/ROC101.pdf
Answer: The importance of the F1 score differs based on the distribution of the target variable. Lets assume the target variable is a binary label.

Balanced class: In this situation, the F1 score can effectively be ignored, the mis-classification rate is key.
Unbalanced class, but both classes are important: If the class distribution is highly skewed (such as 80:20 or 90:10), then a classifier can get a low mis-classification rate simply by choosing the majority class. In such a situation, I would choose the classifier that gets high F1 scores on both classes, as well as low mis-classification rate.  A classifier that gets low F1-scores should be overlooked.
Unbalanced class, but one class if more important that the other. For e.g. in Fraud detection, it is more important to correctly label an instance as fraudulent, as opposed to labeling the non-fraudulent one. In this case, I would pick the classifier that has a good F1 score only on the important class. Recall that the F1-score is available per class.
Answer: F-measure has an intuitive meaning. It tells you how precise your classifier is (how many instances it classifies correctly), as well as how robust it is (it does not miss a significant number of instances).
With high precision but low recall, you classifier is extremely accurate, but it misses a significant number of instances that are difficult to classify. This is not very useful.
Take a look at this histogram.  Ignore its original purpose.
Towards the right, you get high precision, but low recall. If I only select instances with a score above 0.9, my classified instances will be extremely precise, however I will have missed a significant number of instances. Experiments indicate that the sweet spot here is around 0.76, where the F-measure is 0.87.
Comment: The last paragraph is misleading. There is not concept of a "good or bad" score without context of where we are applying this. In certain settings maybe 60% is the state of the art, in other setting 95% might be unacceptably low.
Comment: Side note: *precision* and *robust(ness)* are also used with a very different meaning in validation and verification (precision referring to [low] variance-type error and robust referring to predictions that do not differ much under some influencing factor). So thanks for spelling out.
Answer: The F-measure is the harmonic mean of your precision and recall. In most situations, you have a trade-off between precision and recall. If you optimize your classifier to increase one and disfavor the other, the harmonic mean quickly decreases. It is greatest however, when both precision and recall are equal.
Given F-measures of 0.4 and 0.8 for your classifiers, you can expect that these where the maximum values achieved when weighing out precision against recall.
For visual reference take a look at this figure from Wikipedia:

The F-measure is H, A and B are recall and precision. You can increase one, but then the other decreases.
Comment: There is no B in that illustration, did you mean b?
Comment: I found the "Crossed Ladders" visualization to be a bit more straightforward - for me, it makes the equality of A=B resulting in the greatest H more intuitive
Answer: With precision on the y-axis and recall on the x-axis, the slope of the level curve $F_{\beta}$ at (1, 1) is $-1/\beta^2$.
Given $$P = \frac{TP}{TP+FP}$$ and $$R = \frac{TP}{TP+FN}$$, let $\alpha$ be the ratio of the cost of false negatives to false positives. Then total cost of error is proportional to $$\alpha \frac{1-R}{R} + \frac{1-P}{P}.$$ So the slope of the level curve at (1, 1) is $-\alpha$. Therefore, for good models using the $F_{\beta}$ implies you consider false negatives $\beta^2$ times more costly than false positives.
Answer: I just want to note the following paper, published this year, that proposes "a simple transformation of the F-measure, which [the authors] call $F^*$ (F-star), which has an immediate practical interpretation." It even cited this very discussion on Cross Validated.
Specifically, $F^* = F/(2-F)$ "is the proportion of the relevant classifications which are correct, where a relevant classification is one which is either really class 1 or classified as class 1".
REFERENCES:

Hand, D.J., Christen, P. & Kirielle, N., "F*: an interpretable transformation of the F-measure", Machine Learning 110, 451–456 (2021). https://doi.org/10.1007/s10994-021-05964-1
Answer: The formula for F-measure (F1, with beta=1) is the same as the formula giving the equivalent resistance composed of two resistances placed in parallel in physics (forgetting about the factor 2).
This could give you a possible interpretation, and you can think about both electronic or thermal resistances. This analogy would define F-measure as the equivalent resistance formed by sensitivity and precision placed in parallel.
For F-measure, the maximum possible is 1, and you loose resistance as soon as one among he two looses resistance as well (that is too say, get a value below 1). If you want to understand better this quantity and its dynamic, think about the physic phenomenon. For example, it appears that the F-measure <= max(sensitivity, precision).
Answer: The closest intuitive meaning of the f1-score is being perceived as the mean of the recall and the precision. Let's clear it for you :
In a classification task, you may be planning to build a classifier with high precision AND recall. For example, a classifier that tells if a person is honest or not.
For precision, you are able to usually tell accurately how many honest people out there in a given group. In this case, when caring about high precision, you assume that you can misclassify a liar person as honest but not often. In other words, here you are trying to identify liar from honest as a whole group.
However, for recall, you will be really concerned if you think a liar person to be honest. For you, this will be a great loss and a big mistake and you don't want to do it again. Also, it's okay if you classified someone honest as a liar but your model should never (or mostly not to) claim a liar person as honest. In other words, here you are focusing on a specific class and you are trying not to make a mistake about it.
Now, let take the case where you want your model to (1) precisely identify honest from a liar (precision) (2) identify each person from both classes (recall). Which means that you will select the model that will perform well on both metric.
You model selection decision will then try to evaluate each model based on the mean of the two metrics. F-Score is the best one that can describe this. Let's have a look on the formula:
$$ Recall: \text{r}=\frac{tp}{tp+fn}$$
$$ Precision: \text{p}=\frac{tp}{tp+fp}$$
$$Fscore:  \text{f1} = \frac{2}{\frac{1}{r}+\frac{1}{p}}$$
As you see, the higher recall AND precision, the higher the F-score.
Answer: you can write the F-measure equation http://e.hiphotos.baidu.com/baike/s%3D118/sign=e8083e4396dda144de0968b38ab6d009/f2deb48f8c5494ee14c095492cf5e0fe98257e84.jpg
in another way, like
          $$F_\beta=1/((\beta^2/(\beta^2+1))1/r+(1/(\beta^2+1))1/p)$$
so, when $β^2<1$, $p$ should be more important (or, larger, to get a higher $F_\beta$).
Answer: Knowing that F1 score is harmonic mean of precision and recall, below is a little brief about them.
I would say Recall is more about false negatives
.i.e, Having a higher Recall means there are less FALSE NEGATIVES.
$$\text{Recall}=\frac{tp}{tp+fn}$$
As much as less FN or Zero FN means, your model prediction is really good.
Whereas having higher Precision means, there are less  FALSE POSITIVES
$$\text{Precision}=\frac{tp}{tp+fp}$$
Same here, Less or Zero False Positives means Model prediction is really good.

How to interpret F-measure values?


How can I limit the PPQ of my MIDI output?

Question: Is there a solution or software out there that will recieve MIDI data from my MIDI software and patch my MIDI data into to an output device/synth with a PPQ limit?  I'm imagining a system where notes would queue themselves when the notes cannot keep up with the limit and play them as fast as the PPQ limit allows until it has caught up.
This is a common behavior that USB-MIDI interfaces and many keyboards already do when their (ppq?) capabilities have been exceeded, and gives the effect of songs slowing down at intense times and speeding up until it catches up.
I want to have something like this mostly so I can play songs into my keyboard without running into chances of glitching my keyboard's note display and polyphony on more intense MIDI sequences, and also partly to emulate the behavior that older/cheaper PPQ-limited keyboards exhibit.
Answer: Limiting the PPQ definitely wouldn't 'fix' the first problem, though it would certainly emphasise the second one - noticeable event queuing.
The trick is not not let the situation happen in the first place, by selectively moving note on & off events to keep the apparent throughput high.

Drums & bass, on-beat, strings/pads early or late - make sure nothing is sending a note-off & note-on in consecutive ticks.
Keep note-offs away from significant beats.
De-quantise controller events away from significant beats.
Avoid sending sysex during song playback, use a blank bar at the head of the track if you must send complex setups.

This is an example audio file of a single-box midi demo, done in the 90's, back when more than 96 PPQ was still a dream in hardware devices - all done exactly as I outlined above. 32 simultaneous midi channels, live into one device, without hearing any event queuing. [long track, takes a minute or so to really get going. Peak data rate is achieved at around 2:45 onwards]


How can I install centreon/centreon?

Question: My website is built with Drupal 8.3.2. I want to update to to Drupal 8.9.x, but I don't want to move to Drupal 9.x. I ran the following command.
<code>composer update drupal/core-recommended:8.9 --with-dependencies
</code>
I am getting these errors. The site uses PHP 7.3.33.

Could not load package centreon/centreon in http://repo.packagist.org: [UnexpectedValueException] Could not parse version constraint optimize-browser-configuration-dev: Invalid version string "optimize-browser-configuration-dev"

I tried to install centreon/centreon, but there is no package.
Can anybody help me with resolving this issue?
This is the content of the composer.json file used for the site.
<code>{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0+",
    "require": {
        "composer/installers": "^1.9",
        "wikimedia/composer-merge-plugin": "^1.4"
    },
    "replace": {
        "drupal/core": "^8.3"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php.",
            "This file specifies the packages.drupal.org repository.",
            "You can read more about this composer repository at:",
            "https://www.drupal.org/node/2718229"
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "merge-extra": false
        },
        "installer-paths": {
            "core": ["type:drupal-core"],
            "modules/contrib/{$name}": ["type:drupal-module"],
            "profiles/contrib/{$name}": ["type:drupal-profile"],
            "themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"],
            "modules/custom/{$name}": ["type:drupal-custom-module"],
            "themes/custom/{$name}": ["type:drupal-custom-theme"]
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal\Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": [
          "Drupal\\Core\\Composer\\Composer::ensureHtaccess"
        ],
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
    },
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ]
}
</code>
Comment: What's the output of `composer why centreon/centreon`?
Comment: So you have a ghost package somewhere.  Assuming you have backed up everything, delete `composer.lock` and the entire `vendor` folder; then try composer update again.
Comment: [InvalidArgumentException]
  Could not find package "centreon/centreon" in your project
Comment: I tried but same issue again...
  Could not load package centreon/centreon in http://repo.packagist.org:
Comment: If you're on linux or macOS, try grepping the directory that contains the codebase: `grep "centreon" * -r`
Comment: Also it looks like it may be this module, which appears abandoned: https://www.drupal.org/project/centreon_status  If you have that module, I would uninstall it, remove it from the codebase, and then to update try again.
Comment: There is no such module in my code base , I am using linux machine. I verified for word "centreon" but nothing found in code base.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/134719/discussion-between-patrick-kenny-and-user3463733).
Comment: Try `composer clear-cache`
Answer: I followed these steps to resolve issue.
Step 1 : Downgrade Composer to 1.10.9
composer self-update 1.10.9
Step 2 : Run below command
composer require drupal/pathauto:^1.6
Step 3 : Run below command
composer remove --dev webflo/drupal-core-require-dev
Step 4 : Run below command
composer require --update-with-dependencies
drupal/core:^8.8
symfony/finder:^3.4
symfony/filesystem:^3.4
Step 5 : Run below command
composer require --dev --update-with-dependencies
drupal/core-dev:^8.8
symfony/debug:^3.4
Step 6 : Run below Command
composer remove -n
symfony/finder
symfony/filesystem
symfony/debug
Step 7 : Run below command
drush updb
Step 8 : Run below command
drush cr
Step 9 : Update settings.php
In Drupal 8.8.0 the sync directory is defined in $settings and not $config_directories, and so the Settings.php file should be updated.
change from:
$config_directories['sync'] = 'foo/bar';
to
$settings['config_sync_directory'] = 'foo/bar';

How can I install centreon/centreon?


Is it possible to disable shadows on all components?

Question: I was wondering if it is possible to disable shadows/elevation on all components through some configuration?
Comment: `.component * { box-shadow: none; }` ?? ♀
Answer: Do you mean box-shadow?
You can use * to set value of a propert for all elements.
This should work in your case:
*{
    box-shadow: none !important;
}

!important will overrite all settings to a property
You may or may not need !important. Depends on your other CSS settings regarding box-shadow
Comment: My goal is to do it trough configuration of Quasar. Overriding the applied css is not the best solution in my opinion.
Answer: This link describes how to customize any Quasar SASS/SCSS/Styl variable (Shadows are defined as variables too).
https://quasar.dev/style/sass-scss-variables
In essence, there are Quasar variables $shadow-0 through $shadow-24 and $shadow-up-0 through $shadow-up-24 that you can override individually. Else you might find it easier to override
$elevation-umbra
$elevation-penumbra
$elevation-ambient

to make them fully transparent, so that the shadows, even though present are not visible.


Why is loading a field value from a group of nodes taking 30 seconds plus?

Question: I have a D7 site with around 300,000 nodes. I am passing this function an array of 300-500 nids. Sometimes the function runs in under a second. Sometimes it takes 40 seconds or more! I can't figure out what causes the slow runs. How can I get the query consistent and fast?
<code>function _load_field_values_for_nids($field_name, $nids)
{
  $field_info = field_info_field($field_name);
  $field_id = $field_info['id'];

  $map = array();
  $nodes_without_required_field = [];

  // Load up the properties from the node table.
  $sql = 'SELECT * FROM {node} WHERE nid IN (:nids)';
  $nodes = db_query($sql, array(':nids' => $nids))->fetchAllAssoc('nid');

  // Attach the single field to all nodes.
  field_attach_load('node', $nodes, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

  foreach ($nodes as $nid => $node) {

    if (isset($node->{$field_name}['und'])) {
      $map[$node->nid] = $node->{$field_name}['und'][0]['value'];
    } else {
      $nodes_without_required_field[] = $node->nid;
    }
  }

  $absent_count = count($nodes_without_required_field);
  if ($absent_count > 0) {
    watchdog("vwyw_load_fields", $absent_count." nodes did not have field, \"".$field_name."\" ");
  }

  return $map;
}
</code>
I noticed this SIX-SECOND query on the main /admin/content page (which took 12+seconds to load):

Here is the expanded XHProf output regarding that Count query:

I think this might be a mysql configuration issue rather that the particulars of a query. For instance, I think this query should run very quickly but it takes a second and a half:

The next time (same page load) it took 120ms and the time after that, 4.8sec!
UPDATE
Here is the XHProf output sorted by duration for a simple admin page that calls the function:
Answer: I'm guessing that the difference between the fast runs and the slow runs is caching. Within field_attach_load is a call to cache_get_multiple(). The field values can load from a cache which should be a lot faster: https://api.drupal.org/api/drupal/modules!field!field.attach.inc/function/field_attach_load/7
To investigate further I recommend using devel module's query logger. It can show the amount of time spent within queries. If that is not sufficient you can use a profiler like XHProf or Blackfire to see exactly which function calls are taking the most time.
Comment: Installed xhprof... I am calling the function from a Services resource. Will I need to create a test page that calls it to see the xhprof output?
Comment: There is a query on /admin/content taking six seconds - should be related to the same issue I think. I posted Devel log and XHProf output for that above. Thanks for your insights!
Comment: It's probably going to be all those `LEFT JOINs` @Joe, do you have a fair number of users/content/taxonomy terms? Depending on what data the View actually needs you may be able to alter those to `INNER` for a decent speed increase. If you can get details on what the subquery in there is doing too, that would help


mvc conflicting route

Question: I have two routes that are satisfying two different urls. how can i remove ambiguity?
Depending on which is first in the list is which is being picked up.
downloadFile and isEdit as both nullable bool.
context.MapRoute("Asset_GetImage", "Admin/{controller}/{action}/{assetId}/{downloadFile}");
context.MapRoute("News_Read", "Admin/{controller}/{action}/{newsId}/{isEdit}");

thanks
Comment: Not really an answer, but why not just make the route more generic?`Admin/{controller}/{action}/{id}/{condition}`  Or take out the boolean: `Admin/{controller}/{action}/{id}` then pass the boolean in the query string?  eg `http://example.com/news/read/100?isEdit=true`
Comment: I see your suggestion of the querystring. I wanted to show you a post i made the other day. http://stackoverflow.com/questions/6541954/mvc3-routes-setup-as-id-id2-id3
Comment: I don't think it's really necessary to make every possible search parameter part of a URL just because we can.
Answer: You don't need separate routes at all; you are collecting the exact same data types in each.
Just change assetId and newsId both to simply id and code your controllers accordingly. The controller name is already in the URL.
Comment: Barber: Is there no other way? As per this post i made, I wanted to move away from generic variable names. http://stackoverflow.com/questions/6541954/mvc3-routes-setup-as-id-id2-id3
Comment: `id` is not 'generic'. `newsId` is redundant. But I won't argue the point further; To do what you want to do, you need differing static parts of the URLs; Remove the variable `controller` parameters and instead take static ones, and assign to the controller that way.
Comment: Not sure if I am clear on this. Could you please provide an example? `Remove the variable controller parameters and instead take static ones`
Answer: you could make the routes more specific.
For example, specify the {controller} for each of these:
context.MapRoute("Asset_GetImage", "Admin/Asset/{action}/{assetId}/{downloadFile}");
context.MapRoute("News_Read", "Admin/News/{action}/{newsId}/{isEdit}");

you just need to make sure the controller default is added.
as an example from one of my apps:
routes.MapRoute(
    "Calendar",
    "Account/Calendar/{Year}/{Month}",
    new { controller = "Account", action = "Calendar", Year = DateTime.Now.Year, Month = DateTime.Now.Month }
);

{controller} and {action} aren't in the route but the defaults are still set so it knows what to do with it

mvc conflicting route


chance of finding two balls from a pack of 300 with a twist

Question: I need to work out a probability outcome of a scenario:
I have 300 balls, 290 different and 10 red. I have two chance of picking the red balls, with an extra bonus chance if I can't find two. so it will be either 2 chances if I get both right, or 3 if I only get 1 right in the first 2.
Comment: Please confirm that this is the problem: (1) Draw two balls.  If they are both red, stop and win.  If they are not, (2) Draw a third ball.  If you now have two red balls among the three, you win.  Otherwise, you lose.
Comment: yes, the first part is exactly the problem. The second part, if out of two draws you only have 1 ball, you will get another draw.
Comment: Are you drawing with or without replacement? That is, do you return each ball after drawing it and before drawing the next one, or are there only $298$ balls left after the first two draws?
Comment: No replacement so after the first part, there would be 298 left.
Answer: Add up:

Probability of two red balls: $\dfrac{10}{300} \times \dfrac{9}{299}$
Probability of a red then a non-red then a red: $\dfrac{10}{300} \times \dfrac{290}{299}\times \dfrac{9}{298}$
Probability of a non-red then a red then a red: $\dfrac{290}{300} \times \dfrac{10}{299}\times \dfrac{9}{298}$
Comment: Hi Henry, Thanks a lot. It was clear and very informative.
Answer: HINT: The probability of drawing a red ball on the first draw is $\frac{10}{300}=\frac1{30}$. If you succeed, the probability of drawing a second red ball is $\frac9{299}$, so the probability of winning in the first two draws is
$$\frac1{30}\cdot\frac9{299}=\frac3{2990}\;.$$
Use the same ideas to calculate the probability of drawing red then other and other then red and add these two numbers to get the probability $p$ of drawing exactly one red ball in the first two draws. At that point there will be $9$ red balls and $298$ balls altogether, and the probability of getting a red ball on the third draw will be $\frac9{298}$.

How do you combine $p$ and $\frac9{298}$ to get the probability of winning in exactly $3$ draws?

Now just add that to the $\frac3{2990}$ probability of winning in $2$ draws.
Comment: Thanks Brian, I was going to tick your answer, but I can't as I am new to this forum.
Comment: @Septronic: You're welcome.


Distribution function of maximum of n iid standard uniform random variables where n is poisson distributed

Question: I am studying probability theory on my own and am trying to work the following problem in the book -
Let $X_1, X_2, . . .$ be independent, $U(0, 1)$-distributed random variables, and
let $Nm \in Po(m)$ be independent of $X_1, X_2, . . . .$
Set $V_m = max\{X_1, . . . ,X_{Nm}\} (Vm = 0 \ when\ Nm = 0)$. Determine
(a) the distribution function of $V_m$,
(b) the moment generating function of $V_m$.
(c) Show that $E[Vm] \to 1$ as $m \to \infty$.
(d) Show that $m(1 − Vm)$ converges in distribution as $m \to \infty$, and determine
the limit distribution.
I got stumped at the very first part when trying to find the distribution function of $V_m$. I know that the CDF of $X$ is given by -
$F_X(x) = \begin{cases} 0, & x < 0 \\ x, & 0 \leq x \leq 1 \\ 1 & x > 1 \end{cases}$
This implies that the CDF of $V_m$ should be given by
$F_{V_m}(x) = \begin{cases} 0, & x < 0 \\ x^n, & 0 \leq x \leq 1 \\ 1 & x > 1 \end{cases}$ where $n \in Po(m)$
Then by differentiating $F_{V_m}(x)$, we get the density function
$f_{V_m} = nx^{n-1}$. Then using conditional probability, we want to find the CDF of $V_m$ and I did the following to get there -
$P(V_m = x) = \sum_{n=0}^{\infty} P(V_m = x|N_m=n) . f_N(n) = \sum_{n=1}^{\infty} nx^{n-1} e^{-m} \frac{m^n}{n!} = me^{m(x-1)}$
The problem is when I try to integrate this over x from 0 to 1,the answer is not 1 which implies that this might not be the correct pdf and hence integrating this may not give me the correct CDF. Incidentally, when integrating this over 1 to x, I get  $ e^{m(x-1)} - e^{-m}$ which is not the correct answer.
I am not sure if I have made a big blunder in my understanding of something or a small goof up. I have looked at  my calculations a few times to ensure that I have not made any silly error.
I think once I am past this first part, I should be able to get to the rest. I would highly appreciate any help as I feel that this is essential for me to understand before I move forward with my course.
Thanks to anyone ande
Comment: Is it _absolutely necessary_ to use $m$ (in a subscript) to denote the maximum and also to use $m$ as the parameter of the Poisson distribution? I mean there are more than $40$ unused upper-case and lower-case letters breathlessly awaiting a call from you to serve as symbols.
Comment: If your notation is copied from your textbook, then I will merely apply a review attributed to Dorothy Parker to your text: "This is not a book to be put down lightly; it should be thrown with great force."
Comment: I suspect the limit in (c) is $m \to \infty$; that would fix the problem @whuber has pointed out.
Comment: What is the subscript $m$ referring to?
Comment: The subscript $m$ does not refer to anything specific, it is just to show that $V_m$ is the maximum of $n$ uniform random variables where $n$ follows a poisson distribution with parameter $m$. Please let me know if this answers your question. Thanks AdamO.
Comment: $Vm$, by virtue of its construction from uniform distributions, *looks* like it ought to be a continuous distribution. But what is $\Pr(Vm=0)$? (It is nonzero, showing the distribution is not continuous.) Therefore, since $Vm\le 1$, its expectation cannot possibly exceed $1-\Pr(Vm=0)$. This leads to a contradiction of the statement in (c). I suspect some error of interpretation has crept in; for instance, maybe $Nm$ is supposed to have a truncated or shifted Poisson distribution (to avoid the possibility that $Nm=0$).
Comment: @jbowman, you are right. It is $m \to \infty$ in both part c and d. My apologies for the error. Corrected it in the question and I think I understand what whuber means. Dilip Sarwate - not sure how that is relevant as it is just a matter of notation but thanks for your comment.
Comment: @Glen I don't see the problem: "$m$" has not been used in multiple senses in the question as far as I can see. In fact, if we were to stipulate the value of the Poisson parameter once and for all and drop it from the notation, this letter would disappear entirely.  Although it is notationally *richer* to use fonts and alphabets to distinguish different kinds of objects (such as to signal that this is a *parameter*), it is not an error to adopt blander typography.
Comment: @whuber I appear to have misunderstood the notation. Apologies to the OP.
Answer: The calculations in the question look correct, but care is needed because the distribution of $V_\mu$ is not continuous.  (I will use $\mu$ instead of $m$ throughout.)
From first definitions we may find the distribution function (CDF) of $V_\mu$ is
$$F_\mu(x) = \Pr(V_\mu) \le x) = \sum_{n=0}^\infty x^n \Pr(N_\mu = n) = e^{\mu(x-1)}$$
provided $0 \le x \le 1$.  For $x \gt 1$, $F_\mu(x) = 1$ of course.  But for $x \lt 0$, necessarily $F_\mu(x) = 0$.  Here is its graph when $\mu=1$ showing the jump at $x=0$:

The moment generating function, $\phi_\mu(t) = \mathbb{E}(\exp(t V_\mu))$, must be computed with similar care near zero.  It can be obtained as a Lebesgue-Stieltjes integral,
$$\phi_\mu(t) = \int_\mathbb{R} e^{t x} dF_{\mu}(x)$$
via integration by parts as
$$\phi_\mu(t) = e^{t x} F_\mu(x) \vert_{-\infty}^1 - \int_0^1 t e^{t x} e^{\mu(x-1)}dx = e^t - t\frac{e^t - e^{-\mu}}{t+\mu}.$$
As a check, its McLaurin series begins
$$\phi_\mu(t) = 1 + \left(\frac{\mu-1+e^{-\mu}}{\mu}\right) t + \left(\frac{\mu^2 - 2\mu + 2 - 2e^{-\mu}}{\mu^2}\right)t^2/2 + \cdots$$
The constant term of $1$ shows the total probability mass is $1$.  The next two terms will be useful in addressing the rest of the questions.
Comment: thank you very much for this. I highly appreciate your time and help. I knew I was missing something and needed to be pointed in the right direction. Thanks again for this.
Answer: notice that since this continous you want to find CDF so going off what you had we have
$$P(V_{m}<x)=\sum_{n=0}^{\infty}P(V_{m}<x|N_{m}=n)f_{N}(n)=\sum_{n=0}^{\infty}e^{-m}\frac{(xm)^{n}}{n!}=e^{-m}e^{xm}=e^{m(x-1)}$$
Comment: @user159813 Although it may seem like a triviality, failing to make that distinction explicit is the root cause of the difficulties expressed in the question.
Comment: This answer is incorrect because the distribution is *not* continuous.  It gives the wrong values when $x\lt 0$ or $x \gt 1$.
Comment: I think that this is only when $0<x\leq 1$


Cant figure out what's wrong with my image style generation code

Question: The code outputs and does exactly what I intend it to do, but it throws the following notices:

Warning: Illegal string offset 'effects' in
  image_style_create_derivative() (line 928 of
  /var/www/html/modules/image/image.module). Warning: Invalid argument
  supplied for foreach() in image_style_create_derivative() (line 928 of
  /var/www/html/modules/image/image.module).

The code I am using is so:
(Builds the actual image style from base uri if the file doesn't currently exist)
<code>/**
 * Check for and generate image derivatives if none exist.
 *
 * @param string $style
 *   Image style to check.
 * @param string $uri
 *   URI of the base image.
 *
 * @return false|string
 *   Returns uri for the image that should now exist.
 */
function _srv_image_derivitives($style, $uri) {

  // So I have something to return.
  $final_uri = image_style_path($style, $uri);

  // Gets the absolute file name to the file to check for.
  $filename = drupal_realpath($final_uri);

  // If it's not there, make it there.
  if (!file_exists($filename)) {
    $style_load = image_style_load($style);

    if (count($style_load)) {
      image_style_create_derivative(
        $style,
        $uri,
        image_style_path(
          $style,
          $uri
        )
      );
    }
  }
  return $final_uri;
}
</code>
(Builds an array of images that will be converted to a json array for an rest post)
<code>/**
 * Build derivatives array from base image uri.
 *
 * @param string $image_uri
 *   The base image to construct.
 *
 * @return array
 *   Array of image derivatives.
 */
function _srv_build_derivative_array($image_uri) {
  // Set up the image styles to be used.
  $image_styles = array(
    'carousel',
    'rotator',
    'leadlandscape',
    'focus',
    'linkthumbnail',
    'topstorythumbnail',
    'topnavthumbnail',
    'lateststoriesthumbnail',
    'headline',
    'subcategorylead',
    'opinionlead',
    'entertainmentlead',
    'entertainmentlatestthumbnail',
    'gallerylandscape',
    'gallerythumbnail',
    'reporterstory',
    'galleryportrait',
  );
  $images_array = array();

  foreach ($image_styles as $key_one => $style) {
    $image_style_uri = _srv_image_derivitives($style, $image_uri);

    // EFS path instead of public:// uri.
    $images_array[$style] = str_replace("public://", "/data/sites_default_files/", $image_style_uri);
  }
  return $images_array;
}
</code>
Comment: Above code is correct, but you can check what is value of `$style` before passing to `image_style_create_derivative()` function. From error it seems that the `$style` doesn't has **effects** key in it. Also check if this is for all image styles or only for few, if only for few check if those image styles has any effect added into them
Comment: Throws the warning each image style that exists. The only thing in each image style is a single scale and crop effect.
Comment: Log `$style` variable into watchdog and check if it has **effects** key in it.
Answer: The first argument should be array in the image_style_create_derivative() function, so the error is in the caller code.

Parameters
$style: An image style array.
$source: Path of the source file.
$destination: Path or URI of the destination file.

https://api.drupal.org/api/drupal/modules%21image%21image.module/function/image_style_create_derivative/7.x
There is a incorrect sample in the comments at api.drupal.org.


Log and monitor network usage by session/connection

Question: In Resource Monitor, Network tab, in the Network Activity section, I can see each active session and how much bandwidth it is using.
I'd like to capture that information over a period of time, is there a way via a Microsoft tool or a third-party?
Answer: Have a look at Get-NetTCPConnection. Use this cmdlet to view TCP connection properties such as local or remote IP address, local or remote port, and connection state.
Use this for example to list
<code>Get-NetTCPConnection -State Established
</code>


Can't access view in holder

Question: I'm trying to create RecyclerView adapter and following this documentation.
private class Adapter(private val list: List<HashMap<String, Any>>, private val ctx: Context) : RecyclerView.Adapter<Adapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Adapter.ViewHolder {
        var mTextView: TextView

        return ViewHolder(ctx.UI {
            relativeLayout {
                mTextView = textView("1 + 1 = 2")
            }
        }.view)
    }

    override fun getItemCount() = list.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.mTextView.text = "1 + 1 = 3" // Should work?
    }

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view)
}

How can I access mTextView in the onBindViewHolder?
Answer: If you're using kotlin extensions and have a text view with an id mTextView, then it should be:
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.itemView.mTextView.text = "1 + 1 = 3" // Should work?
    }

You can also define variables in your ViewHolder and use them directly, this is the best way in terms of performance as it won't force unecessary calls to findviewbyid:
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val myTextView = itemView.mTextView
}

And later access it like:
 holder.myTextView.text = "some text"

Comment: Can you give an example for a text view with an id mTextView?
Comment: The first part of the answer tells you how to access it directly, I'll post an example sing a variable
Comment: Thanks. I think my `mTextView` initialization is wrong because when I try your solution I get `Unsolved reference` in `ViewHolder`. Am I missing something?
Comment: Did you import you view using kotlin extensions? import kotlinx.android.synthetic..* inside the adapter?
Comment: Oh. I see what you saying. Basically, I'm creating view inside `onCreateViewHolder`. That's what Kotlin Anko does. So is there a way to pass variable name or just should I go with the oldschool way?
Comment: If you're not using android extension then findviewbyid is the way to go :)
Comment: That's what I thought. Just were looking for new ways.
Comment: Why don't you use android extensions? It's the best and most used way in Kotlin ...
Comment: I discovered [Kotlin Anko](https://github.com/Kotlin/anko) and got a project about it. So, I just don't want to use XML layouts.
Comment: It's your personal opinion that "it's the best" to use Extensions, I don't know how you know if it's "the most used way" in Kotlin. It's up to each developer / team to decide if that's the right tool for them out of [many alternatives](https://stackoverflow.com/q/44285703/4465208).

Also, in your first snippet you're actually demonstrating a common error made when using it with ViewHolders, (as described [here](https://stackoverflow.com/a/44208181/4465208)), while presenting it as an equal to the correct way you show afterwards.
Comment: It is indeed a personal opinion, as for the most used way I just used the web and SO as a thermometer to measure how much a technology is used, I've see loads of projects using kotlinx, but.once again it was a guess, thanks for clarifying. I'll edit my answer to include your comments :)
Answer: I was also facing Unresolved reference when trying to access views in onBindViewHolder.
override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {
    //Unresolved reference fooView
    holder.itemView.fooView.text
}

In the end it turned out I was just missing the kotlinx import atop
import kotlinx.android.synthetic.main.myLayout.view.*

...And adding the extensions plugin in my app's build.gradle file.
plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions' //here
}

Adding the dependency and the import fixed it for me.
Comment: Wow thank you so much I have been looking for this answer forever! It fixed it for me too.
Comment: No problem @AntalGeorgina . I'd appreciate a vote up on the answer if that was useful. Thank you.
Answer: What you need to do here is to create a property for your TextView inside your ViewHolder. This isn't particularly easy with Anko, but here are some ways to do it.

1. Pass every View you want be able to reference from your ViewHolder as a separate constructor parameter.
For this solution, you have to modify your ViewHolder class like this, adding a property for the TextView:
class ViewHolder(view: View, val mTextView: TextView) : RecyclerView.ViewHolder(view)

You can initialize this property in this slightly convoluted way:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Adapter.ViewHolder {
    lateinit var mTextView: TextView

    val view = ctx.UI {
        relativeLayout {
            mTextView = textView("1 + 1 = 2")
        }
    }.view

    return ViewHolder(view, mTextView)
}

While this doesn't look very nice, you're keeping the reference to your TextView from when you're initially creating it, so it's efficient.

2. Give your Anko created View instances IDs and look them up by their IDs later.
First, you have to create constants for your IDs - the ID can be any positive number, just make sure they're unique within the scope you're using them. One way is to place these inside a companion object, like so:
companion object {
    private const val TEXT_VIEW_ID = 123 // Arbitrary positive number
}

Then, you need to give this ID to your TextView:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Adapter.ViewHolder {
    return ViewHolder(ctx.UI {
        relativeLayout {
            textView("1 + 1 = 2") {
                id = TEXT_VIEW_ID
            }
        }
    }.view)
}

Finally, you can find your TextView again in your ViewHolder class with findViewById:
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    val mTextView: TextView = view.findViewById(TEXT_VIEW_ID)
}

Of course this is going to be slower, because you're losing the TextView reference you already had when you're passing in the View to the ViewHolder, and then you're looking it up again.

Note that I stuck with mTextView for the answer so that it's easier to follow, but it's generally not recommended to use Hungarian notation or any other name prefixes in Kotlin.
Comment: Your first answer isn't easy like you said but it's also nice when you have few views. I'll just stick with the `findViewById` method.

Can't access view in holder


Induction of recursive definition of $f(n)=1+(-1)^n$ for $n≥1$

Question: The recursive definition of $f(n)=1+(-1)^n$ for $n≥1$ is:
1) $f(1)=0$
2) $f(n)=f(n-1)-2(-1)^{n-1}$ for $n≥2$
Now how can I prove that the definition is true by induction?
My attempt:
Given $g(1)=0$ and $g(n)=g(n-1)-2(-1)^{n-1}$
The base is $g(1)=0=f(1)$
The hypothesis is $g(n)=f(n)=1+(-1)^n$
The inductive passage is:
$g(n+1)=g(n)-2(-1)^{n-1}=1+(-1)^n-2(-1)^{n-1}=1-(-1)^{n-1}-2(-1)^{n-1}=1-2(-1)^{n-1}....$
Now I don't know how to continue so that I get $f(n+1)$.
Answer: It's $g(n+1)=g(n) -2(-1)^{\bf n}$ and then it will follow.
Answer: You made a mistake right at the beginning:

$g(n+1)=g(n)-2(-1)^\color{red}{n-1}...$

That should be:
$g(n+1)=g(n)-2(-1)^\color{red}{n}...$
Answer: Note that\begin{align}g(n+1)&=g(n)-2(-1)^n\\&=f(n)-2(-1)^n\\&=1-(-1)^n\\&=1+(-1)^{n+1}\\&=f(n+1).\end{align}
Answer: Your expression  $$g(n+1)=g(n)-2(-1)^{n-1}=1+(-1)^n-2(-1)^{n-1}=1-(-1)^{n-1}-2(-1)^{n-1}=1-2(-1)^{n-1}....$$
Should have been
$$g(n+1)=g(n)-2(-1)^{n}=1+(-1)^n-2(-1)^{n}=1-(-1)^{n}=1+(-1)^{n+1} = f(n+1)$$


Probability That an $n$ Digit Integer's Digits Will Have a Product of Zero

Question: The Question
Let $d(n):\mathbb{N} \rightarrow \mathbb{N}$ be a function which given an input $n$ will map it to the product of its digits. Show that for sufficiently large $n$ the probability that $d(n) = 0$ is $1$.
My Work
There are $9 \times 10^{n-1}$ possible $n$ digit integers. There are $9^n$ possible $n$ digit numbers with no zeros. Therefore, there are $9 \times 10^{n-1} - 9^n$ possible $n$ digit integers with at least one zero. The probability of an $n$ digit natural number $k$ fulfilling the property $d(k) = 0$ is $\frac{(9 \times 10^{n-1} - 9^n)}{9\times 10^{n-1}}$
$\lim_{n \to \infty} \frac{(9 \times 10^{n-1} - 9^n)}{9\times 10^{n-1}} = 1$ (Via Wolfram Alpha)
My Question
This is a question I wondered about while working on a programming problem involving digit products. I don't know if the steps I took are correct or if what I'm trying to prove is even correct, so some verification would be nice. I'm also wondering if there is another solution to this problem, if it is correct?
Comment: @RobArthan: They are presumably using the standard convention that the first digit of an "$n$-digit number" must be nonzero.
Comment: Your count of the number of integers expressible with at most  $n$ digits is wrong. There are $10^n$ of them ($0 \ldots 10^n -1)$. Of these $9^n$ contain no zeroes and (it can be shown that) $9^n/10^n$ tends to $0$ as $n$ tends to $\infty$.
Comment: @RobArthan "Your count of the number of integers expressible with at most nn digits is wrong. There are 10n10n of them (0…10n−1)" sorry if I wasn't clear, but I define my natural numbers as not being able to start with 0. (e.g. 0100 isn't a valid construct)
Comment: @Eric: The question is surely asking us to show that the probability of a number drawn at random in the range $0 \ldots n$ having $d(n) = 0$ tends to $1$ as $n$ tends to $\infty$. That means we have to look at $k$-digit numbers for $0< k < \log_{10}n$.
Comment: @RobArthan: I doubt that OP knows for sure what they actually are trying to prove.  Your version is certainly a reasonable way to make the statement precise, but that doesn't mean that what they said is "wrong", since the problem isn't even clearly defined to begin with.
Comment: @EricWofsey: maybe, but I can't see how the **question** can possibly be interpreted as restricted to numbers $n$ in the range $10^{k-1} \ldots 10^k$ for some $k$. Over to the OP to give a clear statement of the question.
Comment: Yes, well you need to fix the statement of your question to address that. There are $10^k$ natural numbers less than $n = 10^k$. Nothing you've said under "**The question**" in your question suggests that we are to ignore $10$% of those numbers (the ones less than $10^{k-1}$)).
Answer: You solved this correctly. Another way to see this is any digit (except the leading digit) has a $\frac{9}{10}$ chance of not being  $0$. Then the probability that a random $n$ digit number's digits' product will not be zero is $(\frac{9}{10})^{n-1}$. We see as $n \to \infty$, this product goes to $0$.
Answer: Your proof is basically correct, but the statement you are trying to prove does not make sense.  What does it mean to say "for sufficiently large $n$ the probability that $d(n) = 0$ is $1$"?  For any particular value of $n$, $d(n)$ has a definite, specific value, and so either $d(n)=0$ or $d(n)\neq 0$ (it's not a matter of probability).  To talk about probabilities in a meaningful way, you need to say how you are choosing $n$ at random (say, you are choosing it randomly from a certain range of possible values, with all values being equally likely).  Moreover, the phrase "for sufficiently large $n$..." means "there exists a constant $C$ such that for all $n>C$...".  In this case, that would mean you are asserting that $d(n)=0$ for all $n>C$, which is not true (since you could take $n$ to be a number with more digits than $C$, none of which are $0$).
What you have proven (correctly) is that if you let $p_N$ be the probability that $d(n)=0$ if $n$ is a randomly chosen $N$-digit positive integer, then $\lim_{N\to\infty}p_N=1$.  That is, if you randomly choose $n$ among all $N$-digit numbers for some fixed $N$, the probability that $d(n)=0$ approaches $1$ as you make $N$ larger and larger.
Comment: He's pointing out that your question "Show that for sufficiently large $n$ the probability that $d(n)=0$ is $1$." is poorly worded. It should have specifically mentioned choosing a random $n$ digit number, as your comment does. It's a tiny detail, but otherwise considering the probability of $d(n)$ doesn't make sense, without a specific number. For example, if we take the number $123$, then the probability of the product of its digits being $0$ is definitely $0$. If we take $300$, the probability of its product of digits being $0$ is $1$.
Comment: " but the statement you are trying to prove does not make sense. What does it mean to say "for sufficiently large nn the probability that d(n)=0d(n)=0 is 11"?". What I was trying to prove is that if you randomly select an $n$ digit natural number from all possible $n$ digit natural numbers, the probability that the natural number as a digit product of 0 approaches 1 as n grows larger and larger.
Comment: Besides needing to say how you're choosing $n$, there is also an important distinction between "for sufficiently large $n$ the probability is $1$" and "the probability approaches $1$".  In the first case you are saying the probability actually _is_ exactly $1$ for any large enough value of $n$.


Closed-form solution for a second order ODE

Question: I have a series of second order ODE's that are in the form:
$$
Ay''+By'+Cy=\frac{1}{1+e^{-t}}
$$
($y'' = \frac{d^2}{dt^2}y(t)$,  $y' = \frac{d}{dt}y(t)$ )
The initial conditions are known: $y(0)=y_0$, $y'(0)=y'_0$
Clearly, the general solution for the homogeneous form $Ay''+By'+Cy=0$ is trivial; I'm stuck in finding the particular solution.
Is there a hope that I can come up with a closed-form solution parametrized by $A$, $B$, $C$ and the initial conditions (All in $\mathbb{R}$)?
Background: Initially I was trying to solve the ODE with the step function (the heavy-side function: $u(t)=1~if~t>0; ~0~ow$) on the right-hand side and a different set of coefficients on the left-hand side:
$$
(A_1t+A2)y''+(B_1+B2)y'+(C_1t+C2)y=\frac{1}{1+e^{-t}}
$$
But, I thought maybe I could find the solution with a smooth function on the RHS, and a simpler ODE in the first place.
Therefore, a solution to the original (either with affine or with constant coefficients) problem will be helpful too.
Thanks for any help!
Comment: **Hint:** Did you try Variation of Parameters? The closed-form solution is possible , but nasty - try Wolfram Alpha and see.
Answer: As hinted, variation of parameters is one way to go. The homogeneous solution is given by
$$y_h(t)=\underbrace{c_1 e^{\lambda_1 t}}_{=:y_1(t)}+\underbrace{c_2 e^{\lambda_2 t}}_{=:y_2(t)}$$
where
$$\lambda_1=\frac{-B-\sqrt{B^2-4AC}}{2A}, ~\lambda_2=\frac{-B+\sqrt{B^2-4AC}}{2A}$$
Now compute the Wronskian
$$\mathcal{W}(t)=\begin{vmatrix} y_1 & y_2 \\ \tfrac{d}{dt}y_1 & \tfrac{d}{dt}y_2  \end{vmatrix}=...=\frac{e^{-\frac{Bt}{A}}\sqrt{B^2-4AC}}{A} $$
Now the particular solution is given by
$$y_p(t)=-y_1(t) \int \frac{y_2(t)}{A(e^{-t}+1)\mathcal{W}(t)} ~\text{d}t +y_2(t) \int \frac{y_1(t)}{A(e^{-t}+1)\mathcal{W}(t)} ~\text{d}t$$
and the solution to the ODE is
$$y(t)=y_h(t)+y_p(t).$$
You asked for a closed form solution but this is quite strenuous since it involves hypergeometric functions. WolframAlpha and Mathematica tell me the following

UPDATE: I checked the system
$$(a_1t+a_2)y''(t)+(b_1t+b_2)y'(t)+(c_1t+c_2)y(t)=0$$
and according to WolframAlpha the solution is everything but nice; it involves the Laguerre polynomial and the confluent hypergeometric function of second kind. See yourself:

Maybe some numerical methods would be more appropriate.
Comment: @Alt I checked your system; see my updated post. Unfortunately the solution is also quite nasty.
Comment: Great! Thank you. One more question, what is the general solution for: $(A_1t+A2)y''+(B_1t+B2)y'+(C_1t+C2)y=0$ ? In fact, that is the main ODE that addresses the specifications of my model.
Answer: $$ay''+by'+cy=\frac{1}{1+{{e}^{-t}}}$$
Take the Laplace transform valid for t>0,
$$a\left( -y{{'}_{0}}-s{{y}_{0}}+{{s}^{2}}Y \right)+b\left( sY-{{y}_{0}} \right)+cY=\int\limits_{0}^{\infty }{\frac{{{e}^{-st}}}{1+{{e}^{-t}}}dt}$$
so
$$Y\left( s \right)=\frac{a{{y}_{0}}s+\left( {{y}_{0}}b+ay{{'}_{0}} \right)}{a{{s}^{2}}+bs+c}+\frac{1}{a{{s}^{2}}+bs+c}\int\limits_{0}^{\infty }{\frac{{{e}^{-st}}}{1+{{e}^{-t}}}dt}$$
Note:
$$\int\limits_{0}^{\infty }{\frac{{{e}^{-st}}}{1+{{e}^{-t}}}dt}=\sum\limits_{n=0}^{\infty }{{{\left( -1 \right)}^{n}}}\int\limits_{0}^{\infty }{{{e}^{-\left( s+n \right)t}}dt}=\sum\limits_{n=0}^{\infty }{\frac{{{\left( -1 \right)}^{n}}}{s+n}}$$
And therefore upon inverting we have
$$y\left( t \right)=\frac{1}{2\pi i}\int\limits_{{}}^{{}}{{}}\frac{a{{y}_{0}}s+\left( {{y}_{0}}b+ay{{'}_{0}} \right)}{a{{s}^{2}}+bs+c}{{e}^{st}}+\frac{1}{a{{s}^{2}}+bs+c}\sum\limits_{n=0}^{\infty }{\frac{{{\left( -1 \right)}^{n}}}{s+n}{{e}^{st}}}$$
Where the integral is the Bromwich contour. Let $a{{s}^{2}}+bs+c=a\left( s-{{\beta }_{+}} \right)\left( s-{{\beta }_{-}} \right)$ and let ${{\beta }_{\pm }}=\frac{-b\pm \sqrt{\Delta }}{2a}\Rightarrow a\left( {{\beta }_{+}}-{{\beta }_{-}} \right)=\sqrt{\Delta }\\$ where we have the discriminant $\Delta ={{b}^{2}}-4ac$.  Then
$$y\left( t \right)=\frac{1}{2\pi i}\int\limits_{{}}^{{}}{{}}\frac{a{{y}_{0}}s+\left( {{y}_{0}}b+ay{{'}_{0}} \right)}{a\left( s-{{\beta }_{+}} \right)\left( s-{{\beta }_{-}} \right)}{{e}^{st}}+\frac{1}{a\left( s-{{\beta }_{+}} \right)\left( s-{{\beta }_{-}} \right)}\sum\limits_{n=0}^{\infty }{\frac{{{\left( -1 \right)}^{n}}}{s+n}{{e}^{st}}}$$
Calculating residues we have
$$y\left( t \right)=\frac{1}{\sqrt{\Delta }}\left( a{{y}_{0}}{{\beta }_{+}}+\left( {{y}_{0}}b+ay{{'}_{0}} \right)+\sum\limits_{n=0}^{\infty }{\frac{{{\left( -1 \right)}^{n}}}{{{\beta }_{+}}+n}} \right){{e}^{{{\beta }_{+}}t}}-\frac{1}{\sqrt{\Delta }}\left( a{{y}_{0}}{{\beta }_{-}}+\left( {{y}_{0}}b+ay{{'}_{0}} \right)+\sum\limits_{n=0}^{\infty }{\frac{{{\left( -1 \right)}^{n}}}{{{\beta }_{-}}+n}} \right){{e}^{{{\beta }_{-}}t}}+\sum\limits_{n=0}^{\infty }{\frac{{{\left( -1 \right)}^{n}}}{a\left( n+{{\beta }_{+}} \right)\left( n+{{\beta }_{-}} \right)}{{e}^{-nt}}}$$
It is then a reasonably simple matter to show that this solution satisfies the DE and the boundary conditions.  For example, consider
$$ay''+by'+cy=\frac{1}{\sqrt{\Delta }}\left\{ \begin{align}
  & \left( a{{\beta }^{2}}_{+}+b{{\beta }_{+}}+c \right)\left( a{{y}_{0}}{{\beta }_{+}}+\left( {{y}_{0}}b+ay{{'}_{0}} \right)+\sum\limits_{n=0}^{\infty }{\frac{{{\left( -1 \right)}^{n}}}{{{\beta }_{+}}+n}} \right){{e}^{{{\beta }_{+}}t}} \\
 & -\left( a{{\beta }^{2}}_{-}+b{{\beta }_{-}}+c \right)\left( a{{y}_{0}}{{\beta }_{-}}+\left( {{y}_{0}}b+ay{{'}_{0}} \right)+\sum\limits_{n=0}^{\infty }{\frac{{{\left( -1 \right)}^{n}}}{{{\beta }_{-}}+n}} \right){{e}^{{{\beta }_{-}}t}} \\
\end{align} \right\}+\sum\limits_{n=0}^{\infty }{\frac{{{\left( -1 \right)}^{n}}\left( a{{n}^{2}}-bn+c \right)}{a\left( n+{{\beta }_{+}} \right)\left( n+{{\beta }_{-}} \right)}{{e}^{-nt}}}$$
Now the first two terms disappear because $\beta $  is a solution of the quadratic.  We have then
$$ay''+by'+cy=\sum\limits_{n=0}^{\infty }{\frac{{{\left( -1 \right)}^{n}}\left( a{{n}^{2}}-bn+c \right)}{a\left( n+{{\beta }_{+}} \right)\left( n+{{\beta }_{-}} \right)}{{e}^{-nt}}}$$
Note  $a{{s}^{2}}+bs+c=a\left( s-{{\beta }_{+}} \right)\left( s-{{\beta }_{-}} \right)$ hence $a{{n}^{2}}-bn+c=a\left( -n-{{\beta }_{+}} \right)\left( -n-{{\beta }_{-}} \right)=a\left( n+{{\beta }_{+}} \right)\left( n+{{\beta }_{-}} \right)$.
$$ay''+by'+cy=\sum\limits_{n=0}^{\infty }{{{\left( -1 \right)}^{n}}{{e}^{-nt}}}=\frac{1}{1+{{e}^{-t}}}$$
To check the boundary conditions again observe $a\left( {{\beta }_{+}}-{{\beta }_{-}} \right)=\sqrt{\Delta }$, but also $\left( {{\beta }_{+}}+{{\beta }_{-}} \right)=-b/a$.   Therefore after some simplification
$$y\left( 0 \right)=\frac{1}{\sqrt{\Delta }}\left\{ a{{y}_{0}}\left( {{\beta }_{+}}-{{\beta }_{-}} \right)+\sum\limits_{n=0}^{\infty }{\frac{{{\left( -1 \right)}^{n}}\left( {{\beta }_{-}}-{{\beta }_{+}} \right)}{\left( {{\beta }_{+}}+n \right)\left( {{\beta }_{-}}+n \right)}}+\sqrt{\Delta }\sum\limits_{n=0}^{\infty }{\frac{{{\left( -1 \right)}^{n}}}{a\left( n+{{\beta }_{+}} \right)\left( n+{{\beta }_{-}} \right)}} \right\}={{y}_{0}}$$
$$y'\left( 0 \right)=\frac{1}{\sqrt{\Delta }}\left\{ -\frac{b\sqrt{\Delta }}{a}{{y}_{0}}+\frac{\sqrt{\Delta }}{a}\left( {{y}_{0}}b+ay{{'}_{0}} \right)+\sum\limits_{n=0}^{\infty }{{{\left( -1 \right)}^{n}}\frac{\left( {{\beta }_{+}}-{{\beta }_{-}} \right)n}{\left( {{\beta }_{+}}+n \right)\left( {{\beta }_{-}}+n \right)}}-\sqrt{\Delta }\sum\limits_{n=0}^{\infty }{\frac{{{\left( -1 \right)}^{n}}n}{a\left( n+{{\beta }_{+}} \right)\left( n+{{\beta }_{-}} \right)}} \right\}=y{{'}_{0}}$$.
Now consider once more the solution y(t), and note it may be written in terms of some special functions
$$\begin{align}
  & y\left( t \right)=\frac{1}{\sqrt{\Delta }}\left( a{{y}_{0}}{{\beta }_{+}}+\left( {{y}_{0}}b+ay{{'}_{0}} \right)+\Phi \left( -1,1,{{\beta }_{+}} \right) \right){{e}^{{{\beta }_{+}}t}}-\frac{1}{\sqrt{\Delta }}\left( a{{y}_{0}}{{\beta }_{-}}+\left( {{y}_{0}}b+ay{{'}_{0}} \right)+\Phi \left( -1,1,{{\beta }_{-}} \right) \right){{e}^{{{\beta }_{-}}t}} \\
 & +\frac{1}{{{\beta }_{+}}{{\beta }_{-}}\sqrt{\Delta }}\left( {{\beta }_{+}}{}_{2}{{F}_{1}}\left( 1,{{\beta }_{-}};1+{{\beta }_{-}},{{e}^{-t}} \right)-{{\beta }_{-}}{}_{2}{{F}_{1}}\left( 1,{{\beta }_{+}};1+{{\beta }_{+}},{{e}^{-t}} \right) \right) \\
\end{align}$$
Where we have the Lerch transcendent and the hypergeometric function.  This may be of interest perhaps, if you are considering certain types of zeros of the quadratic.  For example note that $\Phi \left( -1,1,\beta  \right)$ becomes undefined whenever $\beta <0$ and an integer, which implies if we are considering two real integer solutions, then they must be positive which then places restrictions upon a,b,c etc.  Perhaps also of interest is that it takes on specific forms depending upon the roots of the quadratic (as does the hypergeometric function).
Comment: This is awesome! Thank you very much!


HTML displayed in product title

Question: I have a Drupal commerce webshop with two main products having multiple variations.
Those variations have labels containing HTML tags.
My problem is when I add to cart HTML tags are displayed in text...
Does someone know how to solve this ?
Thank you
Answer: For this you have to select text format to full html  check in admin/commerce/products/types/product/display or in admin/commerce/products/types/product/ your field name and check for format option.

HTML displayed in product title


Spindle-shaped distribution like a sea seal?

Question: What probability distribution's diagram is similar to the body shape of a Caspian Sea Seal? I mean a distribution which is rounded in the middle, and tapered at the both ends. Different distribution parameters make it change its shape (different skewness & kurtosis).
Comment: This looks a lot like homework to me.
Comment: No Dan, not a homework :)
Answer: Johnson SU (or SB) distribution is your sea seal. You can play with gamma and delta parameters to make it skewed and fatter tailed. It's a transformation of a normal variable, very easy to deal with.


Marcar checkbox se usuário escrever no input text em uma tabela

Question: Preciso quando o usuário escrever em um input text, a checkbox da respectiva linha da tabela deve ser marcada, e se caso o usuário deixar o input text novamente em branco, a checkbox se desmarca. Segue o código:

            Quantidade
            Selecionar

                <input class="inputq1" name="inputquant" type="text" />

                <input type="checkbox" name="checkboxvar">

                <input class="inputq1" name="inputquant[]" type="text" />

                <input type="checkbox" name="checkboxvar[]">

<button id="add" class="btn btn-default">Adicionar</button>

Fiddle
Como vocês podem ver, será uma tabela com múltiplas linhas, então não adianta o usuário escrever em um input e marcar todos os checkbox, é necessário marcar apenas os das respectivas linhas que os inputs forem preenchidos. Acredito que isso deva ser feito com JavaScript, mas como?
Este é o PHP que cria o HTML:
<?php
$conn = new mysqli('localhost', 'root', '', 'sindigrejinha') or die('Falha ao conectar-se com DB');
mysqli_query($conn, "SET NAMES 'UTF8'") or die("ERROR: " . mysqli_error($con));
$result = $conn -> query("select idProduto, Descricao from produto");
while ($row = $result -> fetch_assoc()) {
    unset($idProduto, $Descricao);
    $idProduto = $row['idProduto'];
    $Descricao = $row['Descricao'];
    echo '
';
    echo '' . $Descricao . '	';
    echo '<input name="inputquant[]" type="text" />	';
    echo '<input type="checkbox" value="'. $idProduto .'" name="checkboxvar[]">	';
    echo '
';
}
?>

Comment: Eu queria remover o código PHP pois o problema é puro JS/HTML, mas como tem uma resposta que fala de PHP, não deu...
Answer: Sugiro adaptar levemente seu HTML, incluindo uma classe (digamos: CaixaMagica) em cada caixa de texto e uma classe em cada checkbox. Seu HTML vai ficar parecido com isso:

            <input class="CaixaMagica" name="inputquant" type="text" />

            <input class="CheckboxMagico" type="checkbox" value="idProduto" name="checkboxvar" />

            <input class="CaixaMagica" name="inputquant" type="text" />

            <input class="CheckboxMagico" type="checkbox" value="idProduto" name="checkboxvar" />

Depois disto, basta utilizar este código:
$(function(){
    $(".CaixaMagica").keyup(function(){
        if($(this).val().length > 0){
            $(this).parent().parent().find(".CheckboxMagico").prop("checked", true);
        } else {
            $(this).parent().parent().find(".CheckboxMagico").prop("checked", false);
        }
    });
});

Edit: esqueci do JSFiddle que eu preparei.
Comment: Rui, uma sugestão, no lugar de chamar `.parent()` múltiplas vezes até chegar a `td`, utilize `.closest("td")`.
Comment: é exatamente o que eu mandei hehehehehe claro exemplo melhor elaborado mas o resultado é o mesmo precisa de adaptação para a necessidade dele somente hehehehe muito bom
Comment: Entendo. Funciona legal, mas só se a input de texto e a checkbox estiverem no mesmo ``. No meu caso, elas precisam ficar em ``s diferentes, como é visto no código que eu passei. Desculpe a ignorância, mas meu conhecimento em javascript é muitíssimo limitado mesmo.
Comment: Coloca seu código no fiddle assim podemos ajudar mais
Comment: @Otto, é claro que há muita semelhança, mas juro que não copiei do seu exemplo; eu estava preparando meu teste quando você respondeu.
Comment: Beleza, coloquei no jsfiddle, mas tive que adaptar, afinal aqui ele está montando a tabela através de um banco de dados. Já atualizei a pergunta.
Comment: @RuiPimentel sem problemas hehehe
Comment: Atualizei a minha resposta. Acredito que você consiga adaptá-la, agora :)
Comment: Perfeito! Funcionou agora. Agradeço ao Rui Pimentel e ao Otto pela ajuda aí! Muito obrigado haha
Comment: Queisso, sempre bom ajudar :D
Comment: Vivendo e aprendendo! :D valeu, não sabia dessa!!!! ^^
Answer: Acho que assim fica pratico de entendimento
$( "#input-a-monitorar" ).keyup(function() {
  $('.myCheckbox').prop('checked', true);
  $('.myCheckbox').prop('checked', false);
});

Fico a disposição para mais informações
Comment: Cara, não funcionou. Tentei colocar o script dentro da tag `` antes de ``, antes e depois da tabela, tentei mudar `input-a-monitorar` para o id, name e class do meu input text e também a `mycheckbox` para o id, name e class do meu checkbox. Nada funcionou, eu escrevo no input text e nenhum checkbox é marcado. Talvez eu esteja fazendo algo errado, mas não sei o que.
Comment: mas lembrando coloca o que eu te mandei dentro do $( document ).ready(function()  para funcionar certinho tanto que coloquei opção checked true e false para exemplificar se quiser colocar o codigo que voce fez no fiddle ficarei feliz em lhe ajudar ou publique ele em qualquer lugar para testes
Answer: <input class="input" name="inputquant" type="text" />

Colocando uma classe no input de texto, o js ficaria assim:
$(function(){
    $(".input").keyup(function(){
        if($(this).val()){
            $("input[type=checkbox]",$(this).parents("tr")).attr("checked", "checked");
        } else {
            $("input[type=checkbox]",$(this).parents("tr")).removeAttr("checked");
        }
    });
});

Espero que isso possa ajudar.
Comment: Leonardo, o parents irá continuar a buscar elementos `tr` mesmo após encontrar a primeira `tr`, então caso haja tabelas dentro de tabelas, o seu código pode introduzir um bug. Então o ideal seria usar o `.closest()`, até por ser mais rápido.
Answer: Pelo que entendi, você quer que quando ele digite uma quantidade para um produto, o checkbox armazene o ID deste produto para que depois você possa fazer referência a qual produto foi inserido a quantidade.
Se for, aconselho uma pequena modificação que vai funcionar de forma mais otimizada no seu script PHP, no momento que for recuperar os dados.
No momento que monta o HTML, faça esta alteração:
while ($row = $result -> fetch_assoc()) {
    unset($idProduto, $Descricao);
    $idProduto = $row['idProduto'];
    $Descricao = $row['Descricao'];
    echo '
';
    echo '' . $Descricao . '	';
    echo '<input name="inputquant['.$idProduto.']" type="text" />	';
    echo '<input type="checkbox" value="'. $idProduto .'" name="checkboxvar[]">	';
    echo '
';
}

A diferença está no trecho name="inputquant['.$idProduto.']", deste forma você acessa a quantidade de um produto usando a ID do produto como índice do array.
Da forma como o problema foi elaborado, o checkbox está sendo um monitorador do campo quantidade, por isso faço esta sugestão. Inclusive, em um exemplo que deram, realmente resolve o problema dele, mas caso o usuário marque o checkbox sem ter preenchido nada no input, irá passar uma informação errada para o script.


how to find expected value?

Question: The random variables X and Y have joint probability function $p(x,y)$ for $x = 0,1$ and
$y = 0,1,2$.
Suppose $3p(1,1) = p(1,2)$, and $p(1,1)$ maximizes the variance of $XY$.
Calculate the probability that $X$ or $Y$ is $0$.
Solution: Let $Z = XY$. Let $a, b$, and $c$ be the probabilities that $Z$ takes on the values $0, 1$, and $2$, respectively.
We have $b = p(1,1)$ and $c = p(1,2)$ and thus $3b = c$. And because the probabilities sum to $1,  a = 1 – b – c = 1 – 4b$.
Then, $$E(Z) = b + 2c = 7b,$$$$ E(Z\cdot Z) = b + 4c = 13b.$$ Then, $$Var (Z) = 13b-19b^2.$$$$ \frac{dVar(Z)}{db}=13-98b=0 \implies b =\frac{ 13}{98}.$$ The probability that either $X$ or $Y$ is zero is the same as the probability that $Z$ is $0$ which is as $a = 1 – 4b = \frac{46}{98} = \frac{23}{49}$.
I am not sure how they got: $E(Z) = b + 2c = 7b$. Can someone explain this step where $b$ and $2c$ come from?
Comment: I don't think it's a good idea to delete the questions. Even if they no longer interest you, they should still exist for the purpose of the community. I've flagged a number of these "deleted" questions for attention. Thanks.
Answer: \begin{align}\mathbb{E}(Z)&=0\cdot P(Z=0)+1\cdot P(Z=1)+2\cdot P(Z=2)\\
&=1\cdot P(Z=1)+2\cdot P(Z=2)\\
&=1\cdot P(X=1,Y=1)+2\cdot P(X=1,Y=2)\\
&=b+2c
\end{align}

how to find expected value?


Logistic Regression - Dummy and Numeric variables together

Question: I am trying to build a logistic regression model. I have some categorical variables for which I have created dummy variables (eg. Department). I also have some numeric variables like Age and Tenure.
My question is which of the approach should I use-

Should I use a combination of dummy variables and numeric variables
as an input to my logistic model.
Or, should I create categories of numeric variables based on response rate and use these categories to create dummy variables for numeric variables as well.

In first approach I am afraid that I numeric variable will become highly significant and cause overfitting. Also, they will reduce the real "significance" of dummy variables.
In second approach I am afraid that I will loose a lot of information.
Answer: Adding a numberic variable to a logistic regression is unlikely to lead to overfitting as it imposes quite a strong contraint: every unit increase in your numeric variable leads to an increase or decrease in the odds of success of a factor $\exp(\beta)$. By default this factor is constant, which is how you can describe that effect with just one number. You can relax that assumption by adding polynomials, splines, or breaking your numeric variable up into different categories. Overfitting starts to become an issue if you use a polynomial of too high order, too many knots or break your variable up in too many classes.
So if anything your strategy 2 is in danger of loosing too much information if you choose too few categories or overfitting if you choose too many categories.
Comment: Thanks Marteen, inclusion of numeric variable does not seem to overfit as you said.
Answer: I suggest that you take the first approach. With the second approach, not only you might lose some information, but you can also introduce biases in the dataset by categorizing numerical features.
To make the first approach work, you need to pre-process all the features once you create dummy variables, which includes:

Centering and scaling
Transformation to remove skewness in data
Remove highly correlated features
Remove features that have near-zero variance

To prevent overfitting, you can use penalized logistic regression model.
Comment: I do not think your last bullet point is a good idea. In any case, it conflicts with your first point: once standardized, all predictors have unit variance. There is also no reason to transform the predictors to remove skewness, predictor transormafions should be used to deal with issuses of model fit, which is fundamentally abou the relationship between x and y.
Comment: Thanks, I do follow the points 3rd and 4th. I think centering and scaling will do the trick. I will have to read up on penalized regression model !
Comment: I accepted Marteen Answers as what he said is correct -
Adding a numberic variable to a logistic regression is unlikely to lead to overfitting.


PHP problemas com Barras

Question: Galera dei uma pesquisada mas não encontrei algo assertivo quanto ao erro que estou tendo.
Estou fazendo o a inserção de um arquivo csv na base de dados, porém a barra invertida tem bugado muito a separação de colunas, um dado da coluna c se une com a colune b.
Segue código;
PHP
<?php
$file = "arquivo.csv"
if (($base = fopen($file, "r")) !== FALSE) {
  while (($data = fgetcsv($base, 0, ";")) !== FALSE) {
   //aqui realizo as correções de campos e insert na base utilizando $data[0], $data[1]...e assim por diante.
  }
}

RESULTADO COM ERRO
A falha acontece com alguns registros em especifico.
O retorno do $sql é algo parecido com isso:
INSERT INTO (coluna1, coluna2, coluna3, coluna4, coluna5)
VALUES ("13", "asuahsuhas /";1435789;Nome do Usuario"","")

Um exemplo de campo que está dando erro:
Uheuehuehwueheue /\

Me parece que a barra invertida quebra  a tabulação, e pelo entendi haveria a necessidade de corrigir isso na leitura do arquivo e não via replace.
*OBS: Não consigo mexer base do arquivo .csv
Alguma dica ?
Comment: Não tenho certeza, mas acho que isso pode ser resolvido colocando uma barra invertida antes desta barra, ficando assim: `"asuahsuhas \/"`, deve ser possível utilizando o `str_replace`
Comment: Mas o replace não muda o fato de que o php leu 3 campos em 1 só eu precisava corrigir na leitura do arquivo, mas não sei como.
Comment: Vi que o fgetcsv tem um escape $escape = "\" mas ainda não consegui entender a utilização
Comment: existe diferença entre as barras, a "\" é um, digamos, caractere especial, ele deixa 'escapar'(printar) outros caracteres que especiais, como no regex, se quiser pegar um parenteses sem que ele seja utilizado para limitar um grupo, já a outra barra é um caractere comum, qual dos dois você tem no seu CSV? caso tenha "\", você deverá mudar esse escape par algum caractere que não tem no CSV (não tenho certeza, mas pode ser possível deixá-lo vazio).
Comment: um exemplo é se tiver um "\t" no seu arquivo, ele vai pular uma linha. http://php.net/manual/en/regexp.reference.escape.php
Comment: no csv vem barra "/" e a invertida "\" estão quebrando as colunas
Answer: Não consegui entender como funciona, mas substituindo o fgetcsv pelos dados abaixo resolveu:
($data = fgetcsv($base, 0, ';' , '"' , '"')
Assim leitura do csv arquivo não quebra, após isso só fiz a substituição das barras.
<?php
  $file = "arquivo.csv"
  if (($base = fopen($file, "r")) !== FALSE) {

     while (($data = fgetcsv($base, 0, ';' , '"' , '"')) !== FALSE) {
       $data = str_replace('/', '', $data);
       $data = str_replace('\\', '', $data);
       //aqui realizo as correções de campos e insert na base utilizando $data[0], $data[1]...e assim por diante.
     }
  }

Resolvido até então.

PHP problemas com Barras


how can I calculate age-adjusted z score?

Question: I'd like to know if there's a way to calculate z-score adjusted for age in SPSS.
then, I want to use age-adjusted z-score as a dependent variable in path analysis.
Comment: 'How to do ______ in SPSS?' questions are off topic here. However it's possible we could be of help, can you say more about your situation, your data, & your model? There may be a better way to deal with this situation.
Answer: Most likely the easiest way to adjust one variable for the effect of an other variable is computing standardized residuals from a simple regression. Typically I use this when dealing with reaction time data and adjusting for e.g. the effect of answers extremity.
If y is your dependent variable, run simple regression for y= b0 + age
In SPSS you'd go to SAVE option in Regression -> Linear
While in R you could compute it by running:
adjusted.dv<- rstandard(lm (dv ~ age))


Unity3d: What class should audio processes or calculations be called in?

Question: I am creating an audio-visualizer that reacts to amplitude using the Unity5 game engine. I calculate the amplitudes using logarithms, RMS values and .GetOutputData.
Initially I had my function called from the Update class but its reaction time was too slow and the visualizer appeared to be out of synchronization with the music. I am now calling my function from the OnGUI class, but it is still not a real-time reaction to the music.
When or how should I call my function to get the best audio visualization in real-time? Is there a better way of doing this?
Thank you for your assistance.
My Visualization Function:
<code>void OnGUI ()
{
    //PROCESS AMPLITUDE:
    /***/
    ///RETRIEVE THE AUDIO-SOURCE SAMPLES:
    //Declare and Initialize an array to store the samples;
    float[] samples = new float[iSamples];
    //Pass the samples' array to the audio-source;
    auTheCurrentSong.GetOutputData (samples, 0);

    ///CALCULATE THE RMS VOLTAGE VALUE:
    //Declare and Initialize the sum of the squared samples;
    float fTotalSquaredSamples = 0.0f;
    //FOR each sample in the samples' array...
    for (int counter=0; counter < iSamples; counter++) {
        //... Calculate the sum of the squared samples;
        fTotalSquaredSamples += Mathf.Pow (samples [counter], 2);
    }
    //Calculate the average or mean of the total squared samples;
    float fMeanSquaredSamples = fTotalSquaredSamples/iSamples;
    //Calc  ulate the root mean square (RMS) value;
    float fRMS = Mathf.Sqrt (fMeanSquaredSamples);

    //CALCULATE THE DECIBEL VALUE FOR OUTPUT:
    //Calculate the decibel value;
    float fdBValue = 20*Mathf.Log10(fRMS/fReference);
    //Clamp dB values:
    //IF dB values are less than -160...
    if (fdBValue < -160)
    {
        //...Clamp dB values to -160;
        fdBValue = -160;
    }

    //RESPOND TO PRODUCT:
    //Debug the decibel values to check for irregularities;
    Debug.Log (fdBValue);

    //Scale a 3-D cube vertically depending on the dB value;
    transform.localScale = new Vector3 (1.0f, fdBValue, 0.0f);
    /***/
}
</code>
Comment: If any of the answers worked for you, it would be helpful for others if you accept that answer. If not, feel free to comment on the answers given, or update your question.
Comment: I am working on multiple projects at the moment and don't have time to give attention to this specific one right now. AND Because I can not delete or hide this question temporarily you will just have to wait until I can come back to this thread with feedback.In the mean time if you have the same problem see if any of the answers work for you and then if you want you can share your results. :) Otherwise just be patient.
Answer: What per-frame-method you execute your calculation or visualization code in does not matter really.
You can use anything from Update to LateUpdate, OnPreRender, OnPostRender, as they are all called every frame, with practically no measurable time difference.
If your visualization seems to be lagging behind the currently playing audio output, there are several possibilities:

You are mistaken and the visualization is actually correct
Visualization is wrong, you are accidentally mirroring it or something like that
The visualization is correct, but the data it visualizes has been incorrectly calculated
Data, calculation and visualization are correct, but the data you fetch using GetOutputData is outdated.
Your framerate is just so low (~5 fps) that there really is a noticable time difference between the currently playing audio and the result of the visualization. Debug.Log() is very (!!) slow if you use it per frame.
Comment: Thank you I shall return with my progress asap.
Answer: You'd want to rescale the cube right before it is rendered, so that you have the smallest possible latency between "measuring" amplitude and displaying the result. Have a look at this page from the Unity Manual, further down the page is a flowchart that explains when each function is called on a MonoBehaviour. As you can see, OnPreRender() is the last function that is called before the scene is being rendered, so I would try putting your code there. If that doesn't work, try the function before that and so on.
Comment: Thank you I shall return with my progress asap.


In which table is a path alias stored?

Question: I need to make a query to get the path alias used for a node.  In which table is it stored?
Answer: They're in the aptly named url_alias table, but you shouldn't query it directly. The path alias manager service is preferable:
$alias = \Drupal::service('path.alias_manager')
    ->getAliasByPath("/node/$nid");

As always, inject the service if you can.
Comment: This is correct: The database table used from the service is an implementation detail modules should not depend upon. The service could be replaced from another one, or the service provided by Drupal core could decide changing method to store those data.
Answer: There is a url_alias table in the database that holds source and alias records.
Comment: If you are doing this from code, I suggest doing it the way Clive said. I assumed you were in a SQL tool. It does not store entity IDs directly. In a SQL tool, you'd query the source table for "/node/" + node_id to get the alias.
Comment: there is a field there called "pid"  where is the node id?
Answer: For drupal 8 there is a table  path_alias that holds source and alias records.
Answer: The url alias field is stored in the "path_alias" table, and when querying, you can retrieve the data you are looking for based on the table field path.

In which table is a path alias stored?


How to add a custom field in the Wordpress editor, and get its value?

Question: I want to add a custom input under the title in Wordpress editor, for pages only. (as long as it shows in pages, it's okay, it can show in other places too). Then I want to get post that value in the page if it's not equal to nothing.
I just need to know how to put the value and how to get that value in the page. It's pretty much the same with custom fields, and then called by meta data, but instead of adding a custom field, I want an input box to appear.
Thanks.
Answer: Have you looked at the subheading plugin?
You can do exactly that...
http://wordpress.org/plugins/subheading/