Distribution of the RSA numbers

Question: Let's take a random prime $p$. For the sake of the argument let's say $\log(p)\approx 1000$.
Let's suppose all numbers between $p$ and $p+1000^2$ are composites.
What is the approximate probability that one of these numbers is product of two primes of exactly $217$ digits? ($217=\lfloor(\log_{10} p)/2\rfloor$
To simplify the answer, the probability can be given in terms of the prime counting function and its inverse, or any other number theoretic function which has a reasonably good approximation in terms of computing asymptotic probabilities.
Please note that my question is not about the behavior as $p$ tends to infinity. I already know the answer to that.
Edit: The assumption that all numbers between $p$ and $p+1000^2$ are composite seems to be false if $\log p \approx 1000$; this was stipulated in one the answers and dismissed as irreverent. The answers and the question should be taken in that light.
Comment: Honestly,@user2943324 you don't seem to "get" how MSE works.You don't "own" your questions here. When a question is out there and get an answer it is suppose to be beneficial to the whole community. Your question is not only about yourself.This is a community. Please read up on how things work here.
Answer: First of all, for all practical purposes your stipulation about a lack of primes above $p$ Just Doesn't Matter here — but note that it's actually very unlikely that none of them are; one would expect the 'next' prime to be on the order of $p+1000$, Cramer's conjecture says that the largest gap less than $p$ is of size proportional to $(\ln p)^2$, and a provisional gap of size roughly $1000^2$ is known between two provisional primes, but those numbers are of more than 40k digits.
The odds that a number $q$ of size $\approx\sqrt{p}\approx e^{500}$ is prime are roughly $\frac1{500}=.002$; this means that the odds a number of twice that size is a product of two primes of that size is roughly $\frac12(.002)^2 = 2\times 10^{-6}$ (with the factor of one-half because order of the two primes doesn't matter) and the odds that such a number isn't a product of two suitably-sized primes are roughly $1-(2\times 10^{-6})$.  Now, these probabilities aren't all independent (since e.g. small factors on one number preclude the same small factors on 'nearby' numbers), but it's a very common number-theoretic assumption to presume that they're effectively so.  Since we're looking at $10^6$ numbers, this means that the odds of not hitting such a number are roughly $\left(1-\frac{2}{N}\right)^N$, where $N=10^6$.  But this should be a familiar-looking form from the exponential limit; this probability is very close to $e^{-2}\approx .135$.  In other words, the odds of hitting a product of two appropriately-sized primes in the interval are roughly $86.5\%$.
Note that this is a relatively loose estimate; in particular, effects from the size of the intervals (you're ostensibly asking for primes of exactly 217 digits, not primes 'near $e^{500}$')should come into play.  But for back-of-the-envelope purposes, this kind of calculation (done perhaps a bit more carefully than I have here!) — and in particular the 'local probability' and exponential estimate aspects of it — is the simplest way to approach a problem of this sort.
Comment: @user2943324: Steven's answer contains two errors that I can see: the powers of ten are out by 1, and the odds of a number etc. are half what he says. So I think the correct answer is closer to $80\%$. See my answer for details.
Comment: Don't do it Steven! I get the same answer (98%) by a completely different method, so I'm sure it's right.
Answer: Here is another approach to the original question, which asked (roughly): Given an interval of length $10^6$ in the range $[10^{432},10^{434})$, what is the probability that it contains a number of the form $pq$, where $p$ and $q$ are $217$-digit primes?
There are about $N=\frac{10^{217}}{217\ln 10}-\frac{10^{216}}{216\ln 10}\approx 1.792\times 10^{214}$ $217$-digit primes. So the number of  products $pq$ of $217$-digit primes in the interval $[10^{432},10^{434})$ is $\frac12 N(N-1) \approx 1.606 \times 10^{428}$.
Thus the probability that a random number in the range $[10^{432},10^{434})$ is of the form $pq$ is about
$$P = 1.606 \times 10^{428} / (10^{434} - 10^{432}) \approx 1.622 \times 10^{-6}$$
Now we can refer to Steven Stadnicki's answer, to get that the probability of finding such a number in a million trials is about
$$1-(1-P)^{10^6}\approx1 - e^{-P \times 10^6} \approx 1 - e^{-1.622} \approx 0.8025$$
Comment: @user2943324: I don't understand why you asked the question in the first place if you didn't want it answered. Anyway I enjoyed working it out, so I wanted to share my answer with people (not you, obviously).
Comment: I'll revise my answer; the key differences that lead to the difference in probabilities are (a) the factor of two due to order-of-factors that I Just Plain Missed, and (b) the difference between 'probability that a random number near $x$ is prime' and 'probability that a random number in $[x, x+y]$ is prime' - basically, the difference between a derivative and a modestly-sized finite difference.
Comment: (and this is an excellent answer, of course, covering the interval-size effects that I skipped over.)
Comment: And now the difference between our two answers can be put down to the fact that you are answering the (original) question, where $p \approx e^{1000}$, and I am answering my own version of it, where $p \in [10^{432},10^{434})$.

Distribution of the RSA numbers


htaccess file does not take me to 404 error page

Question: I have created a .htaccess file and placed it in my root directory for 404 error page, but when I type a random subdirectory after my URL, it takes me to the index.php file instead of my 404.php file. I have the following code in my .htaccess file.
ErrorDocument 404 /error/404.php
What am I doing wrong?
Comment: If you don't post your full `.htaccess` file nobody can help you.
Comment: This is the only line I have in the .htaccess file
Comment: shouldn't your `404.php` file be in the error directory instead of root directory?
Comment: Sorry that I didn't mention this, but I do have 404.php file in my error directory.
Comment: Could you make an example of a url that shouldn't work, but takes you to index.php?
Comment: Let's say my website is example.com. I have tried something like example.com/dsajfljdsafdsa, and I thought that should take me to 404.php page, but it takes me to index.php
Comment: Are you sure that your web-server can handle the `.htaccess` file? That said try to give a look to [this post](http://stackoverflow.com/a/7426870/4999641), maybe it will convince you to use a `.html` file for your erreor-page.
Answer: /error/404.php indicates your file location is /var/www/html/error/404.php
If the name of your project directory is, lets say myweb, then your .htaccess should be
ErrorDocument 404 /myweb/error/404.php

Comment: You mean, if my website is example.com, the .htaccess file should be

ErrorDocument 404 /example.com/error/404.php

?
Comment: You should specify full path. Specify folder name not domain name. what is the name of your website directory?
Comment: I have placed the .htaccess file at my root directory. Say my web site is example.com. .htaccess file is at example.com/.htaccess, and 404.php file is at example.com/error/404.php
Comment: Which directory does example.com point to? Also can you access 404.php file by hitting http://example.com/error/404.php in the browser?
Comment: I don't understand your first question. It should point to the root directory. Second question, yes, I can access it with example.com/error/404.php
Comment: With root directory I meant the directory of your website code. Let's say code of my website example.com is present in /var/www/html/myweb/. So myweb will be the root directory. Since you can access 404.php through example.com/error/404.php, the absolute path will be /var/www/html/myweb/error/404.php. So, in .htaccess the path should be /myweb/error/404.php.


How can a random event be independent of the next and still converge to an expected value?

Question: Lets take roulette as an example. You can't tell anything about the outcome of the numbers where the ball will stay with just knowing the previous results. That means the random events are independant. (Lets forget the fact that the results may not be distributed equivalently.)
Now all the individual results together still tend to settle on the expected distribution. For otherwise it wouldn't be profitable for casinos to operate the roulette tables. Doesn't this mean the previous results tend to affect the latter?
How is it possible that the events don't affect each other, but also do? In the end the results still converge to the expected value.
Comment: What do you mean by "tend to settle on the expected distribution"? What you would rather consider as a casino owner is the expected gain/loss over a large number of games (see Central Limit Theorem and Law of Large Numbers).
Comment: Jep I mean the Law of Large Numbers. Doesn't this law implicit state how the future events will be?
Comment: The convergence comes because you divide by the number of trials.
Comment: "Doesn't this law implicit state how the future events will be?"
Absolutely not. If we throw a coin 10 times, then:

"It's more probable to have 5 heads and 5 tails than to have 6 heads and 4 tails" : TRUE
"Suppose that we have thrown 9 coins, and got 5 heads and 4 tail; then it's more probable that the next coin is tail" : FALSE
Answer: You asked essentially the same question two years ago. If the roulette wheel or the coin is really fair - so that the numbers on the wheel or the head on the coin appear with equal probability, then mathematicians have proved that under the assumption that the present is not influenced by the past the long run distribution of the numbers or heads will converge to the underlying probabilities. The central limit theorem
even tells you about how far from the underlying probabilities you are likely to be.
There is no need for the wheel or the coin to "catch up". Believing that is the gambler's fallacy. You can lose money counting on it.
Comment: @elFreak  Read the other answer too. It doesn't (necessarily) catch up in the sense of "difference" but it does (with probability $1$) catch up in "proportion," because catching up in proportion does NOT depend on knowing what happened before. Catching up in "difference" WOULD so depend, but that's not what the theorems say.
Comment: I'm trying to ask a bit a different question. Maybe I couldn't formulate it quite right... I understand that you can't say anything about the result based on the previous results of independant events. But I don't get how this doesn't get in conflict with the Law of Large Numbers?
Answer: Let's say I am flipping an honest coin. It's possible (although not very probable) that, in the first $100$ flips, I obtain $75$ heads and $25$ tails. What is the proportion of heads? Well, is $0.75$. Way off the expected result.
Suppose that I continue flipping the coin more $1000000$ times. The coin is fair, and it obviously doesn't try to "correct" the difference between the number of heads and tails. So, let'say in the new flips, I obtain $500000$ heads and $500000$ tails. What is the proportion of heads now? Is
$$\frac{500075}{1000100}=0.5000249975$$
Well, that is pretty close to $1/2$. Note that the absolute difference is still there (there is $25$ more heads than "should"). But this difference is relatively too small facing the number of flips.
As Ian Stewart says, the Law of Large Number does not eliminate the differences: it buries them.
(Sorry by the bad English, not a native speaker).


Carregar arquivo javascript junto com infinite scroll

Question: Preciso recarregar uma função JS assim que rolar a página com infinite scroll, em AJAX.
Quando a página é rolada o arquivo JS precisa acompanhar.
Comment: Sergio,
Desculpa pela complicação.
"Assim que rolar a página" me refiro ao scroll.
Estou trabalhando com infinite scroll e gostaria que minha função fosse aplicada também nos próximos.

Segue um exemplo http://shopluxo.com.br/maquiagem
Comment: Estou utilizando uma função em uma classe e precisaria que ela se repetisse no infinite scroll, não sei se consegui me expressar com clareza.
Comment: Sergio,
Consegui resolver, problema muito simples e estava quebrando a cabeça rs. Agradeço a disposição em ajudar. Abraços
Comment: Lucas, óptimo. Eu vou apagar os comentários aqui. Na próxima vez coloque mais informação. Há muita gente a querer ajudar, mas sem saber tudo ninguém arrisca dar palpites.
Answer: Pela lógica:

Quando rolar a página -> executa funcao();
quando executar funcao() -> faz o que você deseja.

Tenta imaginar que o engatilhador é parecido com um hover ou click, mas seria, dessa vez, no scroll. Mais especificamente: quando o scroll atingir o extremo baixo da viewport, execute algo (e é aqui que entra o AJAX).
Qual a dificuldade nessa lógica?
Para fins técnicos, a sua questão está bem vaga.
Comment: Desculpa pela falta de clareza,
Criei uma função em uma classe e gostaria que se repetisse no infinite scroll também, porque quando o infinite é carregado não trás a função.
Vou reproduzir a sua lógica. Obrigado!
Comment: Disponha! Qualquer coisa estamos à disposição. =)


Tabela bootstrap, no celular

Question: Eu tenho uma tabela um pouco grande
usei esse código do Bootstrap.

...

Mas no mobile só aparece as 3 primeiras colunas e oculta as restante.
tem como alterar para mostrar toda a tabela, ou aparecer um barra de rolagem?
Comment: A barra de rolagem deveria aparecer normalmente. Tente mover a tabela para verificar as outras colunas.
Comment: Realmente a barra não aparece mas se mover a tabela, vai aparecendo as outras colunas :), valeu mesmo.
Answer: A propriedade para a barra de rolagem é overflow.
table{
  overflow: scroll;   /* Sempre aparece a barra de rolagem */
  overflow: auto;     /* Automaticamente verifica se precisa da barra */
}

Mas como você comentou que é mobile eu indicaria esse artigo: https://css-tricks.com/responsive-data-tables/
Em um desenho mobile responsivo o usuário não deveria precisar fazer zoom ou scroll horizontal.

Tabela bootstrap, no celular


How to pass an array from PHP to javascript using JSON to make a Google Chart?

Question: I want to make a Google Chart and I am trying to send a JSON encoded array from a PHP script to a JavaScript. The two files are as follows:

<title>

</title>

<?php
$data[0]=array('State','Values');
$data[1]=array('Correct',6);
$data[2]=array('Incorrect',3);

echo json_encode($data);
?>

This is saved as test.php
The javascript file is:

This is saved as test2.php.
When I run test2.php, nothing happens and the browser shows a blank screen. Where am I going wrong here? Please help.
Thanks.
Answer: You don't need any HTML tags in your test.php. Instead, just use:
<?php
$data[0]=array('State','Values');
$data[1]=array('Correct',6);
$data[2]=array('Incorrect',3);

header("Content-Type: application/json");
echo json_encode($data);
?>

HTML is not a part of JSON.
Comment: If this fixed your problem, please tick the green tick next to my answer - and welcome to Stack Overflow!
Answer: test.php does not need all those html tags, just return the json.  When mixing js and PHP it is sometimes a good idea to just use hardcoded values first, then have PHP create those hardcoded values when you are sure your js is joined up and working.


Linking to a homepage when Drupal is located in a Directory

Question: I have a problem with creating a proper link to the homepage of my website. I would like this code to redirect to my homepage:

Unfortunetaly it doesn't work, because it brings me to the homepage of my whole server and drupal is located in a subdirectory of the server. I tried to do this using php:
<a href="<?php print ('<front>');?>">

but it doesn't work too. When i click on the image it appears:

Page not found The requested page
  "/drupal7/drupal-7.23/en/%3C?php%20print%20(%27%3Cfront%3E%27);?%3E"
  could not be found.
Answer: You should use url() function to generate a page URL. For the frontpage it is:
<a href="<?php print url('<front>'); ?>">YOUR LINK

If the generated links using the url() function are not correct, you can change the $base_url variable in the settings.php
$base_url = 'http://www.yourwebsite.com/drupal7/drupal-7.23';

Comment: Unfortunetaly, this solution doesn't work either.
Comment: That's odd, Drupal should handle the url generation depending the site folder structure. I've added another solution by setting a `$base_url`
Answer: There is global variable $base_path which define base URL path of the Drupal Installation.
This will at least default to '/'.
<?php global $base_path; ?>

<a href="<?php print $base_path; ?>">Home

Or you can use base_path() function which will return the global variable $base_path.
<?php $path = base_path(); ?>

<a href="<?php print $path; ?>">Home

Or, You can also define $base_url in your settings.php file of Drupal installation as below.
$base_url = 'http://www.example.com';
There should not be trailing slash (/) in your base url.
<?php global $base_url; ?>

<a href="<?php print $base_url; ?>">Home

Kindly see that if you modify your $base_url in your settigns.php file, then you need to modify your $base_url when you transfer your file from development server to live server.
Answer: Drupal stores the homepage URL in the $base_url global.
<a href="<?php global $base_url; print $base_url; ?>">YOUR LINK

Details: https://api.drupal.org/api/drupal/developer!globals.php/global/base_url/7


how to write if condition in javascript , if 1 it should show granted if 0 it should show denied

Question: I'm using freeboard. I cloud platform where I'm adding my API and getting results in charts. I have an API which gives the values 1 and 0 but I need to show granted and denied instead of 1 and 0. There is an option to write is in the data sources like below
return datasources["rfid access"] + 3 // output coming 4

like that i need to show granted if rfid access result is 1 and denied for 0
Comment: `return Boolean(datasources["rfid access"]) ? 'granted' : 'denied'` should do.
Comment: im getting values 1 and 0 . it should show granted or denied
Comment: Check the edited comment.
Answer: You can use simple logic like this:
if(APIval === 0){
    return 'denied';
}
else{
    return 'granted';
}

Or you can use a conscise version of it:
return APIval===0 ? 'denied' : 'granted';


How to refresh grid view height to the size of its dynamic content?

Question: I'm using and adapter to render a the following grid view:
<GridView
    android:id="@+id/gridViewOpciones"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:numColumns="2" >
</GridView>

Said adapter is set to the grid view in the following lines of code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    ...
    final GridView gridViewOpciones = (GridView) rootView.findViewById(R.id.gridViewOpciones);
    OpcionesAdapter adapter = new OpcionesAdapter(getActivity().getBaseContext(), R.id.gridViewOpciones, getTransactions());
    gridViewOpciones.setAdapter(adapter);
    ...
}

This is my adapter code:
public class OpcionesAdapter extends ArrayAdapter<Transaccion> {

    private List<Transaccion> transacciones;
    private Context context;

    public OpcionesAdapter(Context context, int textViewResourceId,
            List<Transaccion> objects) {
        super(context, textViewResourceId, objects);
        this.transacciones = objects;
        this.context = context;
    }

    @Override
    public int getCount() {
        return transacciones != null ? transacciones.size() : 0;
    }

    @Override
    public Transaccion getItem(int position) {
        return transacciones != null ? transacciones.get(position) : null;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Button boton = new Button(context);
        Transaccion transaccion = getItem(position);
        boton.setText(transaccion.getNombre());
        boton.setCompoundDrawablesRelativeWithIntrinsicBounds(
                transaccion.getImagen(), null, null, null);
        ...
        return boton;
    }

}

As you can see, I'm setting programatically an image to the transaccion buttons inside the gridview. The problem I'm having is that the grid view is not refreshing its height to the dynamic height of its content, with the set images and everything.
Let me be more especific: the arrayList transacciones has exactly 4 objects right now. The problem is, if I leave the layout height of the grid as wrap_content it only shows part of the first 2 buttons. But if I leave it as, say, 300dp, all 4 are shown correctly. Unfortunately, that's not the way to go as I want the height of the grid to be dynamic and wrap its content.
Researching I saw a lot of post using the following lines of code for this:
adapter.notifyDataSetChanged();
gridViewOpciones.invalidateViews();

I tried but doesn't seem to have any effect. Perhaps I'm not placing them where I should. Could you help me with this issue?
Answer: You would call notifyDataSetChanged() whenever you add or remove something from the gridView.   The dynamic height won't change based on notifyDataSetChanged() though.  It simply will update the views data after you've added/removed something from the grid.
You can change LayoutParams after you've added/removed something from the grid ifyou want to change the actual size of the grid however..
Comment: You're right, I don't add or remove anything to the grid after setting the adapter. Where should I place the line of code you mentioned?
Comment: You could try putting the code in getView.. but you want to resize the  view every time you change the image? why don't you set the boton to have layoutParams wrap_content?
Comment: Actually, the buttons are being displayed correctly. Let me be more especific: the arrayList transacciones has exactly 4 objects right now. The problem is, if I leave the layout height of the grid as wrap_content it only shows part of the first 2 buttons. But if I leave it as, say, 300dp, all 4 are shown correctly. But that's not the desired behavior as I want the height to be dynamic.
Comment: try setting the height as 0dp and make the layout_weight = 1


Does Sabre Air Availability get more than 7 seats?

Question: I'm using OTA_AirAvailLLSRQ API to search flights, but it only shows 7 seats each class. I wonder is there any way or function in Sabre can show total available seats of each class.
I am brand new to Sabre and appreciate any advice on if this kind of data is possible or available.
Answer: Because LLSR service support is very limited, I would recommend looking for a newer service that allows you to retrieve all information, such as Bargain Finder Max, along the Seats Rest service which retrieves the complete seat maps for all cabins.
Best regards.


Search with sort in table

Question: I want to recreate my table (recently with only sort by header) use search input by parameter. How do I can achieve this when I already put queries for sort?
<?php
$id_prov = $_SESSION['id_prov'];
$level = $_SESSION['level'];
$search = $_POST['search'];

if($level == '1')
{

$sql="select idFormKuesionerPengelola, idprov, FormCode, kecamatan, kelurahan, provinsi, kabupaten from form_kuesioner_pengelola left join mst_province on form_kuesioner_pengelola.idprov = mst_province.id_tbl_mst_prov join mst_kab on form_kuesioner_pengelola.idkab = mst_kab.id_tbl_mst_kab WHERE mst_province.id_prov='$id_prov'";//and idkab = $search
//test
if ($_GET['sort'] == 'idform'){
    $sql .= " order by form_kuesioner_pengelola.FormCode";
}
elseif ($_GET['sort'] == 'kabupaten'){
    $sql .= " order by form_kuesioner_pengelola.idkab";
}
elseif ($_GET['sort'] == 'kecamatan'){
    $sql .= " order by form_kuesioner_pengelola.kecamatan";
}
elseif ($_GET['sort'] == 'kelurahan'){
    $sql .= " order by form_kuesioner_pengelola.kelurahan";
}
//test
$rdata=mysqli_query($connect, $sql); //or die(mysqli_error($connect));

$no = '1';
echo "
";

echo "
";

echo "
 No.	 ID Form	 Provinsi	 Kabupaten	 Kecamatan	 Kelurahan	 View	 Export	 Action	";

while($row = mysqli_fetch_array($rdata)) {
    echo "
";
    echo '' . $no . '	';
    echo '' . $row['FormCode'] . '	';
    echo '' . $row['provinsi'] . '	';
    echo '' . $row['kabupaten'] . '	';
    echo '' . $row['kecamatan'] . '	';
    echo '' . $row['kelurahan'] . '	';

    echo 'View	';
    echo 'Export	';
    echo 'Edit	';

    echo "
";
    $no++;
}

echo "
";

}

so how do I make them as one? When I already get my search and can sort table within the result.
thank you
Answer: for search if you want to search the field kecamatan then add the code before sort
if($search != ''){
    $sql .= "WHERE kecamatan LIKE %.$search.% ";
}

Comment: ty for tour feedback. But it show all rows when i hit sort again. I should put sort inside search i guess?
Comment: If you send search and sort then send the search with the sort , you can send search value using form. if i gave you the correct information then mark it as right

Search with sort in table


Another word for shots

Question: I've been googling for the last 2 minutes and I just can't come up with anything that talks about "shots". Maybe this is a local Toronto term. Here's the definition as I understand it. A shot is when all members of the band accent a particular section note or group of notes. This can be done in unison or not. What is the proper term for this? Yes, I understand that you could call it an accent, but that's not how it would be said if you were playing in a band.
Here's an example (although it's not a super strong example):

 (Beyonce - Love On Top @ 1:15)
Comment: I have heart "hits" used in a similar context. In rock its usually a riff.
Comment: "stab" is also related http://en.wikipedia.org/wiki/Orchestra_hit
Comment: Awesome...thanks so much. Perhaps, you should copy your answer in the answer section so I can checkmark your answer.
Comment: Yeah, I've used that too, but I couldn't find anything on that either :(
Answer: Try "hits". I looked up "orchestra hits" for a more specific answer, as searching Google for just hits in a music context will often lead to "greatest hits."
"Stab" is also related: "Orchestra hit" on Wikipedia
Comment: I wonder if it's a Euro/US breakdown. 'Stab' is the term I've heard in the UK.

Another word for shots


How do I learn finger placement for violin sheet music?

Question: New to the violin!
... So, I'm really confused now.
You see, as a hobby, this whole time I have been learning songs by memorizing the finger placement some violinists use for their pieces.
Buuut, it may be more rewarding to learn songs by first reading violin sheet music instead of watching others play.
So first order of business would be to learn to read violin sheet music and know where to put my fingers for each note (because I simply don't know - music has never been my thing).
Searching the web didn't return good results. So I checked my college's library and tried to locate the most basic material possible. I found the popular Suzuki method book.
... it doesn't provide the information I was looking for. It is literally a compilation of violin sheet music.
The only thing that could teach me about reading violin sheet music (and finger placement), as far as I'm concerned, might be a teacher. But I fear I lack the time for one right now.
So essentially, how do I learn to read violin sheet music? Precisely, where to put my fingers for each note.
A particularly interesting search result was a "Fretless Finger Guides" product, which almost seems to address my problem given that you it makes it slightly easier to understand where to put your fingers for each note.
Comment: http://violin.school.nz It's free and teaches the note names and finger numbers.
Answer: The Suzuki method is a strongly guided method that teaches sound before sight, so chances are that's NOT what you want to be looking at right now.
Though, strangely enough, that may be closer to what you were doing initially. Were you playing these songs entirely by a visual reference to other players' fingerings, or are you also using your ears?
Being a fretless instrument, playing violin is highly reliant on the player's ability to identify when he/she is out of tune, and make adjustments to the fingering, often in real-time. If you are already using your ears and just need a simple chart to help with sheet music, the first Google result for 'violin fingering chart' should be exactly what you need.
If, however, you cannot hear if a note sounds right or wrong, chances are you will need to take lessons to get yourself on the right track.
Even if you are using your ears already, I would strongly recommending taking at least a single lesson for someone to give you a "crash course", even if you can't commit to taking lessons regularly (though do give them the courtesy of telling them you're only interested in a single crash course lesson when you contact them, and make it clear what your skill level is).
Comment: Thanks for the link! What's the first position, second position, etc thing? In general, it does help anyway - thanks!
Comment: Yeah, I've been learning songs mainly by watching others play.
Comment: Like I said, it's most important that you're _using your ears_. Can you tell when a note you are playing is off? First position is closest to the nut, and third position is midway up the fingerboard, with your first finger where the third finger used to be in 1st position. In the chart, you should see that the '1' notes in third position are equivalent to the '3' notes in first position.
Comment: As a beginner stick with first position for a while before venturing into third and higher positions.
Answer: I purchased a chord book for mandolin to get better acquainted with the fingerboard on violin. But like you I haven't paid for lessons so am not entirely sure if all the fingerings transfer 100% (for example barré seems easier on mandolin).


How to get dct of an image in python using opencv

Question: I've been trying to figure out a way of getting a DCT of image. After getting the image and doing a bunch of filtering, I want to calculate DCT. Following is the code sniplet:
imgcv1 = cv2.split(imgcv)[0]
cv2.boxFilter(imgcv1, 0, (7,7), imgcv1, (-1,-1), False, cv2.BORDER_DEFAULT)
#resize image to 32x32
cv2.resize( imgcv1, (32, 32 ) ,imgcv1)

I've been trying to play around with the description given here but no success.
When I tried something like:
dst = cv2.dct(imgcv1)

I get an error like:
cv2.error: /build/buildd/opencv-2.3.1/modules/core/src/dxt.cpp:2247: error: (-215) type == CV_32FC1 || type == CV_64FC1 in function dct

From what I can understand from the error is that the input is not 32 bit float but 8 bit. How may I convert it and pass it as 32 bit float? I am not sure of the problem.  I would be grateful for your help. How can I get the DCT? I am pretty new to openCV and python. I searched through other 2/3 threads on same topic but it did not work.
Answer: I found the solution. As I said we need to convert to float that too within range 0 to 1. Then we can convert it back after computing DCT:
imf = np.float32(imgcv1)/255.0  # float conversion/scale
dct = cv2.dct(imf)              # the dct
imgcv1 = np.uint8(dct*255.0)    # convert back to int

Comment: Shouldn't you multiply first by 255 and then convert to uint8?
Answer: Assuming that your image is greyscale, this function works well in computing the DCT.
import cv2 as cv2
import numpy as np

def doDct(inputMatrix):
    fltMatrix = np.float32(inputMatrix)/255.0
    fltDct = cv2.dct(fltMatrix)
    return np.uint8(fltMatrix * 255)


Iron-Router: Can I target a specific nested template to display my loadingTemplate?

Question: I'm using iron-router in a meteor project. What I want to do is show my loadingTemplate only within a particular nested template on the page (i.e. the content area that uses the data my waitOn is waiting for), not in place of the whole page as happens with Router.onBeforeAction('loading');.
Is it possible to do this using iron-router?
My simplified code:
layout.html
<template name="layout">
    {{> yield}}
</template>

<template name="foo">
    //bunch of intro text
        {{> bar}}
    //a big CTA
</template>

<template name="bar">
    {{this.something}}
</template>

What I want to do is replace the bar template with the loadingTemplate until the data is loaded. The rest of the page can render.
Here's the default way that, of course, shows loadingTemplate in place of the whole page (e.g. `foo'):
router.js
Router.configure({
  layoutTemplate: 'layout',
  notFoundTemplate: 'notFound',
  loadingTemplate: 'loading'
});

//Router.onBeforeAction('loading'); //Future SO visitors: use this to show the loading template on all routes, if that's what you desire. I only want to show the loading template on one route.

this.route('home', {
    path: '/',
    action: function () {
      if (this.ready()) // is there a short-hand version btw?
        this.render();
      else
        this.render('loading');
    },
    onBeforeAction: function () {
      //this.render('loading'); //shouldn't this be the short-hand version? Doesn't work.
    },
    waitOn: function() {
      return Meteor.subscribe('baz');
    },
    data: function () {
      return Baz.find();
    }
  });

If what I'm looking for isn't possible with iron-router, any suggested alternatives are most welcome. Thanks!
For future visitors, here are the iron-router docs.
Answer: Yes, it is possible. Read the section in the docs called Using a Layout with Yields. Basically what you need to do is add a few more yields to your layout template, and define other sub-templates to go into them. The 'loading' template will load only in the main yield.
<template name="layout">
  {{> yield region='header'}}
  {{> yield}}
  {{> yield region='footer'}}
</template>

and
Router.map(function () {
  this.route('home', {
    path: '/',
    template: 'foo',
    layoutTemplate: 'layout', // This and the following two can also be defined
    loadingTemplate: 'loading', // in Router.configure like your code does
    notFoundTemplate: 'notFound',
    yieldTemplates: {
      'myHeader': {to: 'header'}, // You need to define the other templates
      'myFooter': {to: 'footer'} // that will be sent into other yields
    },
    waitOn: function () {
      return Meteor.subscribe('baz');
    },
    data: function () {
      return Baz.find();
    }
  });
});

The action and onBeforeAction parameters in your code are unnecessary; that's what waitOn is doing.
Comment: The alternative is to just use a template helper. Inside `foo`: `{{#if isReady}}{{> bar}}{{else}}Loading...{{/if}}` and create a helper `Template.foo.isReady = function () { return Baz.findOne() !== undefined; };` (or find some other way to determine if ready, such as assign the subscription to a global variable and have the helper call it i.e. `BazSubscription.ready()`).
Comment: How would I make sure the loading template yields only in the `bar` template? And thanks for the clarification re: action/onBeforeAction...very helpful.
Comment: A template is rendered in a yield; what do you mean by 'template yields only in the `bar` template?' You can control what goes where via the `yieldTemplates`, `loadingTemplate`, `notFoundTemplate` and `layoutTemplate` parameters (see my example above). The templates listed in `yieldTemplates` will go into the named yields specified; all others (loading, notFound, `home`) will go into the *main* yield, i.e. the one without a name (just `{{> yield}}`).
Comment: Your comment, "The 'loading' template will load only in the main yield" was helpful. In my case, I only want the 'loading' template to load only in the `bar` template, therefore that will be my main yield (`{{> yield}}`). That means I'll have to define everything else as regions. So in my example code, in the `layout` template I'd have to define the header and footer as regions, and then in the `foo` template I'd have to define `//...a bunch of intro text` and `//...a big CTA` as regions. Then I'd have to use `yieldTemplates` to yield the right templates int he right regions. That right?
Comment: I was afraid of that :( Seems the best option might be going outside iron-router for this one. Thanks for the help in understanding regions...much appreciated.
Comment: Updated your answer to show the full working example (and to help future visitors). I couldn't get the template to show unless I included `//Router.onBeforeAction('loading');` though. Sample repo here: https://github.com/chadokruse/iron-router-sandbox.
Comment: Looks like the moderators rejected your edit; try posting it as a new answer?
Comment: Shame...your answer was right, just missing some detail. Mods, would appreciate feedback on why the edit was rejected (it was intended to simply fill in the missing detail).
Comment: I think there is a significant difference in that my version tells you to direct the main template and the loading template into the main yield, `{{> yield}}`, whereas your version doesn't have a main yield at all (you name all three yields, so they're all regions). Variations on a theme, but I think they *are* two different approaches/answers, as similar as they are. You were changing more than just fixing a few typos. Not to say that one is better than the other, either, they're just slightly different.
Comment: Really appreciate that clarification. Indeed, my use case was a deeply nested template, hence the need to focus the yield on a template deep within `
Answer: Full credit to Geoffrey Booth for sending this in the right direction. The full technical answer to the original question follows. The short answer is yes, it IS possible to target specific nested templates using iron-router as Geoffrey mentioned. The more involved answer: there is likely a better alternative depending on your use case...see comments to Geoffrey's answer for a good discussion.
The full working code using the example in the original question:
The html
<template name="layout">
  {{> yield region='header'}}
  {{> yield region='body'}}
  {{> yield region='footer'}}
</template>

<template name="foo">
  //bunch of intro text
   {{> yield}}
  //a big CTA
</template>

<template name="bar">
  {{this.something}}
</template>

and the router
Router.onBeforeAction('loading');

Router.map(function () {
  this.route('home', {
    path: '/',
    template: 'bar',
    layoutTemplate: 'layout',
    loadingTemplate: 'loading',
    notFoundTemplate: 'notFound',
    yieldTemplates: {
      'myHeader': {to: 'header'},
      'myFooter': {to: 'footer'},
      'foo': {to: 'body'}
    },
    waitOn: function () {
      return Meteor.subscribe('baz');
    },
    data: function () {
      return Baz.find();
    }
  });
});


How do I use dask distributed?

Question: I am trying to use Dask by looking at the code examples and documentation, and have trouble understanding how it works. As suggested in the document, I am trying to use the distributed scheduler (I also plan to deploy my code on an HPC).
The first simple thing I tried was this:
from dask.distributed import Client
import dask.bag as db

if __name__ == '__main__':
    client = Client(n_workers=2)

print("hello world")

The hello world got printed thrice, which I think is because of the workers. I was assuming that unless compute is called, the workers are not started.
I can move my print statement to a function:
if __name__ == '__main__':
    client = Client(n_workers=2)

def print_func():
    print("hello world")

But, how do I make sure that only one worker executes this function? (In MPI, I can do this by using rank == 0; I did not find anything similar to MPI_Comm_rank() which can tell me the worker number or id in Dask).
I went further and started using an example provided in Dask:
from dask.distributed import Client
import dask.bag as db

if __name__ == '__main__':
    client = Client()

def is_even(n):
    return n % 2 == 0

b = db.from_sequence([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
c = b.filter(is_even).map(lambda x: x ** 2)
print(c.compute())

But this shows up an error: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. I was assuming that the dask.bag would split up the compute work automatically.
My apologies for a lengthy post, but I am having trouble wrapping my head around Dask (I am used to MPI and OpenMP programming).
Answer:
But, how do I make sure that only one worker executes this function? (In MPI, I can do this by using rank == 0; I did not find anything similar to MPI_Comm_rank() which can tell me the worker number or id in Dask).

This is effectively what the if __name__ == '__main__' block is checking. That condition is true when your script is run directly; it's not true when it's imported as a module by the workers. Any code that you put outside of this block is run by every worker when it starts up; this should be limited to function definitions and necessary global setup. All of the code that actually does work needs to be in the if __name__ == '__main__' block, or inside functions which are only called from inside that block.
Comment: Nicely phrased answer
Comment: Thank you. So, I did move the dask bag computation inside a function, and call the function from main. But, is there a way to print worker_id or some kind of id that can tell me which worker worked on what piece of the data?

How do I use dask distributed?


What SPSS test should I use for blood pressure pre- and post-intervention for comparison?

Question: I have 10 participants who consumed an intervention for 3 weeks.
I would like to look at any significance between pre-intervention and post-intervention readings.
What SPSS test should I use?
I have tried doing a Paired samples t-test because it's the same sample at 2 different times but got confused on which data to place in variable boxes.
This is because I have 4 sets of data: mean systolic before, mean systolic after, mean diastolic before, mean diastolic after for each of the 10 participants.
If Paired T-test is correct, would it make sense to do this:
Pair 1: Variable 1 (systolic before) -- Variable 2 (systolic after)
Pair 2: Varible 1 (diastolic before) -- Variable 2 (diastolic after)
Comment: Yes, if it makes conceptual sense to interpret SBP and DBP separately. You may also consider Mean Arterial Pressure ([MAP](https://en.wikipedia.org/wiki/Mean_arterial_pressure)).
Comment: Judging the usefulness of an intervention based on only 10 participants is problematic. To what population would you refer when discussing results? Is this the same situation posted [here](https://stats.stackexchange.com/questions/403699/spss-paired-samples-t-test-outcome-interpretation/403705#403705)?
Comment: @Penguin_Knight Thank you,  I will look into Mean Arterial Pressure
Comment: @BruceET Thank you for your response. Yes it is an issue but, unfortunately, I am a student and could only recruit a certain number especially due to university budget. I would refer to female university students. Yes it is the same situation; I decided to create a separate thread to not cause confusion :)
Comment: Maybe have a look at  https://stats.stackexchange.com/questions/3466/best-practice-when-analysing-pre-post-treatment-control-designs
Answer: You were correct that the paired sample t-test was what you wanted. However, you can only test a single outcome at a time. You are running into problems because you are attempting to test two different outcomes (systolic and diastolic pressure).
Penguin_Knight suggested one solution in the comments: use a single measure which incorporates both, such as mean arterial pressure. I don't know anything about the health field, but the idea of moving to a single new measure which unifies the previous two makes sense.
Alternatively, you could test either systolic or diastolic pressure independently, or run two different t-tests.
Which should you pick? The one that fits your hypothesis!  A statistical test is based on a hypothesis about what you think should happen. Is your hypothesis about diastolic or systolic pressure? If so, then you should use whichever your hypothesis includes.


How to get Facebook post likes?

Question: I Am trying to retrieve FB Post Likes and Reactions using Graph API. The code that I used to retrieve the 'LIKE','LOVE','HAHA' of a post is shared below.

But the code showing two {} instead of the result.
Comment: Test your request in Graph API Explorer, to see if that is a problem with your request in itself, or with your code.
Comment: And btw., I hope you are not actually exposing an access token in client-side code? And of course you will run into the API Rate Limits pretty quickly, if you try to fire that request every 3 seconds ...
Comment: I generated a token from Facebook Developer page and I tried the token with some other methods such as, Getting page like count from my FB Page.
Answer: Why don't you using javascript SDK?
                var postID = $('#post_id').val();
                FB.api(
                        '/' + postID + '/',
                        'GET',
                        {
                            "fields": "reactions.type(LIKE).limit(0).summary(1).as(like),reactions.type(WOW).limit(0).summary(1).as(wow),reactions.type(SAD).limit(0).summary(1).as(sad),reactions.type(LOVE).limit(0).summary(1).as(love),reactions.type(HAHA).limit(0).summary(1).as(haha),reactions.type(ANGRY).limit(0).summary(1).as(angry)",
                            "access_token": "token"
                        },
                function (response) {
                    console.log(response);
                    var like_count = response.like.summary.total_count;
                    var love_count = response.love.summary.total_count;
                    var wow_count = response.wow.summary.total_count;
                    var haha_count = response.haha.summary.total_count;
                    var sad_count = response.sad.summary.total_count;
                    var angry_count = response.angry.summary.total_count;
                }
      );

This worked for me

How to get Facebook post likes?


Updating Middle Table Laravel Relationship

Question: I have a table that holds the 'Officiant_id' and 'awards_id'
When a user edits their profile it will display in a checkbox all the available ones and auto check the ones that are on that table.
Although, now its time to update, let's say a user unselects one, how can I update the table to delete it, or if they check a new one add that new one to the table.
@if(!empty($officiant - > useraward))
@foreach($officiant - > useraward as $arr)
@php $removeId[] = $arr - > id @endphp {
    {
        Form::checkbox('awards[]', $arr - > id, true, ['class' => ''])
    }
} {
    {
        $arr - > name
    }
} {
    !!'
'!!
}
@endforeach
@endif

@php
$offaward = Info::officiantAwards();
foreach($removeId as $key) {
    unset($offaward[$key]);
}

@endphp

@foreach($offaward as $k => $v) {
    {
        Form::checkbox('awards[]', $k, false)
    }
} {
    {
        $v
    }
} {
    !!'
'!!
}
@endforeach

if (!empty($request - > awards)) {
    foreach($request - > awards as $i => $k) {
        $awards[] = $request - > $k;
    }
}

Answer: Get all awards as an array and call the sync() method on your $officiant.According to documentation/Syncing Associations

You may also use the sync method to construct many-to-many
  associations. The sync method accepts an array of IDs to place on the
  intermediate table. Any IDs that are not in the given array will be
  removed from the intermediate table. So, after this operation is
  complete, only the IDs in the given array will exist in the
  intermediate table:

So in your case after calling the update() or save(),
//get all award ids
$awards = $request->get('awards');

//save or update officient action

//updating relation
$officiant->awards()->sync($awards);


Qmail mail queue behaviour

Question: hello I am on ubuntu linux distribution
I am using qmail. I have some mails blocked in queue. how can I check why those are not forwarding correctly ?
<code>root@server:~# /var/qmail/bin/qmail-qread
18 Sep 2013 11:55:30 GMT  #1550131  54986  <email@example.com>
        remote  email@example.com
</code>
Are the message shown by the command
Thanks
Comment: You can check qmaillogs to see why the emails are in queue?
Answer: check your maillog /var/log/maillog when qmial try send that message.
maybe target server tiscali.it tell somethink like:
 - server isn't available
 - you are temporary in spam list

Qmail mail queue behaviour


UICollectionView reuseIdentifier in sizeForItemAtIndexPath - swift

Question: I have the following code, which puts a collection view into either one or two columns, depending the size of the screen:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let size = collectionView.frame.width
    if (size > 500) {
        return CGSize(width: (size/2) - 8, height: (size/2) - 8)
    }
    return CGSize(width: size, height: size)
}

I would like to amend this, so the height is dependent upon the reuseIdentifier. There are two I use - set something like this:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let diceRoll = Int(arc4random_uniform(2) + 1)
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("profileViewCell", forIndexPath: indexPath)
    if(diceRoll == 1) {
        cell = collectionView.dequeueReusableCellWithReuseIdentifier("profileChartViewCell", forIndexPath: indexPath)
    }
    return cell
}

How can I get the reuseIndentifier of the current cell, so that I can change the height depending on what type of cell it is?
Answer: reuseIdentifier is a property of UICollectionViewReusableView, which is UICollectionViewCell's base class.  Thus you can call cell.reuseIdentifier at any time once you have a cell.
I'm not sure what your notion of "current cell" is.  You can ask the collection view for a given cell at an index path with collectionView.cellForItemAtIndexPath(), and you can track which cell is currently selected by implementing the delegate method collectionView:didSelectItemAtIndexPath: and then saving off the currently selected indexPath.
Alternately (and what I'd recommend) is that you either subclass UICollectionViewCell and have the subclassed cell be responsible for its own height, or implement a custom UICollectionViewLayout class and handle size there.
If you implement your own cell subclasses, be sure to call registerClass:forCellWithReuseIdentifier: on your custom cell so the UICollectionView knows how to create it properly.


Are bound functions always Henstock-kurzweil integrable?

Question: Is there any function $f:[\alpha,\beta]\rightarrow\mathbb{R}$ that is bound but not  Henstock-kurzweil integrable? I assume such a function would have to be horrendously discontinuous but I am unable to construct one.
Edit: Perhaps we can defined a function on $[0,1]$ that equals $1$ on the Cantor set and $0$ otherwise. I might be wrong, but it seems like perhaps something like that would work.
Comment: What does "dense graph" mean?
Answer: Yes. Notice Lebesgue and H-K integrals are equivalent for $f$ bounded with compact support.
Comment: see https://math.stackexchange.com/questions/1340307/bounded-function-on-compact-interval-that-is-not-lebesgue-integrable
Comment: I know virtually nothing about Lebesgue integrals, but I will keep this in mind when I study them. Thanks for the response.


What is the difference between syncopation and poly-rhythm?

Question: My understand is that syncopation works in the same time signature, but  polyrhythm introduces a new time signature.
For example:
Syncopation would be when a piece is in 4/4 and the lead soloist accents the 1 of 4, while the drummer  accents the 2 of 4 and the bass player the 3 of 4.
The result is effectively 3 different 4/4 rhythms interlocked with each other. The music over-all has a staggered but forward  moving, easily discernible 4/4 pulse, making syncopated music very suitable for use as modern popular dance music.
Polyrhythm would be when  the lead soloist is playing in standard 4/4 while the drummer  is playing in  5/4 and the bass player is playing 7/4.
The result is a staggered, often supspended and only vaguely forward motion - much more difficult to follow than syncopation, because of the assymetrical nature of the rythmic structure. Only a very talented dancer could successfully dance to polyrhythmic music.

Is my understanding correct?
Answer: It's a bit simpler than that.
Syncopation is accenting the off beat, especially accenting in between beats. For example, "Superbad" or "Mother Popcorn" by James Brown. A single rhythm can be syncopated. It's just an unusual stress pattern.
Polyrhythm is playing two rhythms at once. For instance, on the piano, playing straight eighth notes (quavers) on the left hand while playing eighth note triplets on the right hand, or "Kashmir" by Led Zeppelin (the drums are playing straight 4/4 but the guitar and bass rhythm is in threes). In this case, at least two rhythms must be present. As you might logically conclude, generally at least one of the rhythms will come across as syncopated, since either the typical stress pattern or one of the other rhythms will seem to be unsyncopated. But both/all rhythms in a polyrhythm could be syncopated.
Comment: Isn't Kashmir an example of polymeter? See e.g. this answer: https://music.stackexchange.com/a/10508/63781
Comment: _As you might logically conclude, generally at least one of the rhythms will come across as syncopated_ - Yes. That's one the reasons I asked the question - there is almost invariably some overlap between the two.
Comment: @Stinkfoot Yes but it's one way. Meaning polyrhythm almost guarantees syncopation, but syncopation exists quite frequently without polyrhythm.
Comment: Understood. But there are certainly also situations where syncopation will also result in polyrhythm - the syncopated accents can create a meter of their own.
Comment: @Stinkfoot But unlike polyrhythms, syncopation tends to be in lockstep with the song's rhythm, i.e. it's just the same thing shifted over. Whereas polyrhythms don't share a time signature.
Answer: Syncopation isn't essentially a multiple-player thing, though in a band some players may be laying down 'four on the floor' while another plays syncopated rhythms over this steady beat.  Easier to illustrate than to explain:

Polyrhythm is basically what you said.  'Micro polyrhythms' are much more common than whole sections though.   Wheras suncopation is ubiquitous in popular music, jazz, ragtime and many other styles of music.  Only traditional hymn tunes are free of it  (and I'm sure someone will find an example in Hymns Ancient and Modern :-)
Comment: I understand syncopation doesn't have to use more than one player, I just took what was for me an easy example. Your notated example explains it better. I see my example is not entirely correct - I have to play it out. I play such things all the time but I never tried to categorize them. A couple of weeks ago i answered a question about syncopation and when i started thinking about it, I realized I wasn't sure how to distinguish polyrhythm from syncopation.
Answer: Syncopation: playing on the offbeat. On the 'and' of "1-and-and-3-and-4-and".
Polyrhythms/cross rhythms: when two lines (either the right and left hands of a piano piece or multiple lines in an orchestral score for example) play with a different "feel" in time signature. One might be playing triplets whilst the other plays straight.
Answer: Syncopation is an accenting behavior that originates from feeling a polyrhythm (polypulse). A polyrhythm occurs when both pulses are actually played. For instance a dotted quarter note pulse originates 2:3 polyrhythm in a 3/4 bar. Feeling the dotted quarter pulse will cause melodies being played or sung to line up with upbeats of the quarter note pulse. The same principle goes for 4:3 polyrhythm to feel a dotted eighth note pulse, causing a behavior of syncopation when playing or singing melodies lining up with the "weak "beats of second and fourth sixteenth notes within a quarter note pulse.
Edit: yes, it requires you to feel 2 constant pulses at the same time. Syncopation is a rhythm feeling, where the lining up of 2 or more pulses causes the accents of one pulse to line up with the subdivisions of another. All syncopation is derived from a rhythm matrix, which is mostly absent in european classical music, but very common in African and Eastern traditions. It's the rhythm matrix lining up of 2 or more pulses that results in a "danceable feel".  Most conservative definitions of syncopation just define syncopation as accenting weak beats, but that's missing the point altogether. It's probably from a western scholar perspective of feeling just the main pulse and mathematically observing seemingly random or odd accents, but that's a cause of syncopation, and not what it is. A common example is the stressing of the AND( upbeat) but that's just a result of a 2:3 polyrhythm being felt. A practical experiment can be done like this: clapping dotted eighths while tapping the foot to the main quarter note pulse, (2:3 polyrhythm) and singing an improvised Melody. It will be naturally syncopated. Once the secondary pulse is felt internally, there's no need to keep clapping, and the singing will always have the syncopated feel.
Comment: Are you saying that syncopation *requires* feeling a polyrhythm to happen?
Comment: This answer seems incomplete, indeed.
Comment: Please let me know if it's clearer now.


Gradient descent algorithm not terminating

Question: Given the minimization problem
$$\underset{x_1, x_2}{\text{minimize}} \quad f (x_1, x_2) := x_1^2 + y x_2^2 - x_1 x_2 - x_1 - x_2$$
My algorithm is working fine for a specific range of $y$ and for some specific range of $y$, for example $y = -1$, my gradient descent algorithm is not terminating irrespective of the initial step size and initial point chosen.
I am not able to decode that why this is happening.
I tried to evaluate the Hessian matrix and for $y = -1$, it comes out to be negative. That means, this function is neither convex nor concave. Can this be the reason why it is not terminating?
I read about this on internet and found that gradient descent algorithm can be applied to functions in general irrespective of them being convex or concave. I also tried to print the values of function at each iteration. It seems that values are not converging rather diverging and overflow happened after millions of iterations. As I said, this is only happening when Hessian is negative. Please help!
Comment: If your function has no minimum then why should gradient descent terminate? As it turns out for $y = -1$ your function does indeed take arbitrarily large negative values.
Comment: If $y=-1$, the function has no minimum.  Take $x_1=0$, for example.  Then $f(0,x_2)=-x^2_2 -x_2$.
Comment: If $y \le 0$, the function has no minimum.  At what values of $y$ does your algorithm/code converge?
Comment: Huh?  The RHS $X_1^2-yX_2^2-X_1X_2-X_1-X_2$ is a constant function of $(x_1,x_2)$.
Comment: In the same way that $f(x)=X$ (for all $x$) or $f(\omega)=\Omega$ (for all $\omega$) is a constant function, $f(x)=x$ (for all $x$) is the identity function.
Comment: No No! The function is taking different values for different X1, X2. How are you saying it to be constant, is not clear to me?
Comment: The Hessian is [[2, -1], [-1, -2y]] with determinant -4y-1. For `y = -1` the determinant is negative, resulting in a positive and a negative eigenvalue, thus a saddle point. I am not able to decode that why my algorithm is not converging the sequence.
Comment: No! No! In $f(x_1,x_2)$ you are only allow to vary $x_1,x_2$ and not $X_1,X_2$.  The derivative is 0 since $f(x_1+h_1,x_2+h_2)=f(x_1,x_2)$ for all $x_1,x_2,h_1,h_2$.
Comment: Please don't confuse with the notation of Capitalization, I mean, they are same: x1 and X1. I just edited though.
Comment: If you decide $x$ and $X$ are the same then so is $n$ and $N$ in the usual definition of convergent sequences (thus $\forall n>N$ is vacuous hence all sequences converge)  or $f$ and $F$ are the same in FTC.  I'll leave you to figure out all the consequences.
Comment: I'm literally sorry for that. I was my perspective to assume that they are same. Please help!
Comment: @ZhenLin Yes, but theory of Gradient Descent Alogrithm suggests that function should converge to global minima in case of strictly convex function and if function is not convex or concave i.e. having a saddle point, it should go to that. That's why I posed a doubt if it is something related to its proof of convergence and I am probably missing that. As you also correctly pointed out that minimum value doesn't exist is this case, but shouldn't it then stop at its saddle point?
Comment: In your post you refer to "my gradient descent algorithm" – if you designed it yourself, then it is up to _you_ to prove that it has the properties you claim. If you are simply implementing someone else's algorithm then perhaps your implementation is faulty, or their proof is wrong. Either way, you will need to supply more details.
Comment: @mjw Yeah, Thanks!
Comment: @mjw taking y > 0.3 (I have tried this far), the function converges perfectly but for lesser values for example, y = 0.23, it doesn't, it goes to `-infinity`.
Comment: Right, your experimentation is on target.  Turns out that $y=0.25$ is a transition point in the analysis.  Please see the posted answer.
Comment: @mjw Thank you so much!
Comment: You are welcome!
Answer: $$\frac{\partial f }{\partial x_1} =2x_1 - x_2 -1 $$
$$\frac{\partial f }{\partial x_2} =-x_1 + 2yx_2  -1 $$
So optima or saddle points could occur when both of these are zero:
$$2x_1 - x_2 =1 $$
$$-x_1 + 2yx_2  =1 $$
Computing the Hessian (the matrix of second derivatives):
$$H= \pmatrix{2 &-1\\-1 &2y},$$
we see that the Hessian is zero when $y=\frac{1}{4}$ and positive for $y>\frac{1}{4}$.
Thus, for $y>\frac{1}{4}$, a minimum will exist.  For $y<\frac{1}{4}$, the function has a saddle point and no minimum.  For $y=\frac{1}{4}$, higher order tests are required, so says https://mathworld.wolfram.com/SecondDerivativeTest.html.


backward to previous page

Question: in my project I have two pages, page1 and page2. In page1 I have few dropdown controls  to filter the records from the db. And in the grid view I have the button as "View details". When I click the "view details button, the page has to redirect to page2 and complete details of that record will be viewed.
Now what I need is I have back button in page2. when I click that button, the page has to go back to page1 and page should display like how I left it, should not load as fresh page....
Since beginner to asp.net I couldn't find the solution for this issue.
Please provide with some example....
Very thanks in advance...
Comment: I have tried Response.redirect() method. But later I came to know through reference that this method create new reference to a form and loads the controls.
Comment: Then referred Server.transfer() method. But I don't know exactly how to use for my case.
Answer: Try this in you viewdetails button click event:
 Server.Transfer("Page2.aspx")

And similarly in your page2 back button click event
Server.Transfer("Page1.aspx")

The Server.Transfer method also has a second parameter—"preserveForm". If you set this to True, using a statement such as Server.Transfer("Page2.aspx", True), the existing query string and any form variables will still be available to the page you are transferring to.
Comment: Hi I have worked on your idea. But it doesn't work. Could you please give me any other solution...
Answer: A simple solution would be to keep any such filters that you have set in session.
This allows you to keep the filters active even when the user navigates away from the page.
You can have a button the Page1 to clear the filters.
Page1 Load:
if(!String.IsNullOrEmpty(Session["Filter1"]))
{
   dropDownList1.Text = Session["Filter1"];
}

Page1 dropDownList1_SelectedIndexChanged
Session["Filter1"] = dropDownList1.Text;

Comment: Thanks for the suggestion, but I have set.   Passing property in grid view, so how can I retain the paging of grid view
Comment: You can always retain the `PageIndex` too.
Comment: Okay fine. But in a case that we have lot of controls to retain its value. Then using session would be fine or any other way is there to do this better than using session .
Comment: @jeevacl session is ok. But remove the session when you have setting on your previous page. `Session.Remove(key)`
Comment: Most controls will rebuild themselves on Load. There are very few that will need you to maintain their state in session.

backward to previous page


Counting a specific word within cell range based on what another cell range says

Question: I am attempting to gather information on common themes for reviews. I have the content of the review in one column and the rating 1-5 in another. I want to be able to count how many times certain words appear in one column based on what the star rating is another. I am using this formula to count but cannot figure out how to add the second column factor. Sometimes I am only counting for one word sometimes more than once hence the word1/2 difference.
<code>=SUM((LEN(G2:G190)-LEN(SUBSTITUTE(G2:G190,"word1","")))/LEN("word1")+(LEN(G2:G190)-LEN(SUBSTITUTE(G2:G190,"word2","")))/LEN("word2"))
</code>
example of the table I am describing for visual

I want to be able to use this or another formula to say word1 and word2 appears 56 times when the star rating in the other column shows less than 4.
I have attempted to make it a sumif formula to add the if condition but I cant seem to get the logic right to not throw an error. I am not sure if that is even the right route to go.
Answer: This formula works in my Excel 2013 sheet. Enter the formula as an arrayformula with ctrl+shift+enter if you don't work with Office 365 or Excel for the web or Excel 2021. In the example the formula counts how many times the words from cells F1 and F2 occur in cells B4 and B5. B3 is excluded because A3 isn't less than 5.
<code>=SUM((LEN(IF(A3:A5<5,B3:B5))-LEN(SUBSTITUTE(IF(A3:A5<5,B3:B5),F1,"")))/LEN(F1),(LEN(IF(A3:A5<5,B3:B5))-LEN(SUBSTITUTE(IF(A3:A5<5,B3:B5),F2,"")))/LEN(F2))
</code>


Disable Panels Preview when adding new Panes in Layout Editor

Question: Some of my pane's are causing the pane's editor to crash (some cause the grears to dissapear, some cause the add new panes element to break). We'd therefore like to disable the preview option in Panels, it looks like Panopoly has the option to do this: https://www.drupal.org/node/2171809. "Enable Previews when adding Panes"
Does anyone know how this could be done on the panels module for Drupal 7?  We're not using Panopoly.
The reason behind it not working is that Panels was written against jquery 1.4 and some of my blocks that are being previewed when adding panes to the page manager are panels 1.9+
Answer: I had same problem in one of my project. Then what I did, I added a custom code to remove all the js files except drupal core js, Panels js, Token Js, Ctools js and Views Js. And it is only for the panel pages so it solve the issue of jquery version.
We also have a drupal module jqmulti for this. But in some cases it also do not work well. That is why I removed all the unwanted js files from panel page.
Here is the sample code for this.
<code>function custom_module_js_alter(&$js){
  if(arg(0) == 'admin' && arg(1) == 'structure' && arg(2) == 'pages'){
    $allow = array('modules/filter/filter.js', 'modules/field/modules/text/text.js', 'modules/file/file.js');
    foreach($js as $key => $value){
      $pos =  strpos($key, 'misc');
      if(strstr($key, 'misc') == '' && $key != 'settings' && strstr($key, 'ctools') == '' && strstr($key, 'panels') == '' && strstr($key, 'views') == '' && strstr($key, 'token') == '' && strstr($key, 'admin_menu') == '' && !in_array($key, $allow)){
        unset($js[$key]);
      }
    }
  }
}
</code>


How to kill or stop other threads in java applet

Question: In java applet I am plotting chart By JCChart. Now after plotting the chart when I watch the task scheduler then it show that cpu utilization is still greater then 50 by Java.exe. Now I use JConsole with plugin to watch which thread in java taking the much CPU utilization. Then it shows that AWT-EventQueue-2 is taking major time And this thread is in Runnable state and never starts.  and what it doing is that some like below..

sun.java2d.loops.FillRect.FillRect(Native Method)
sun.java2d.pipe.LoopPipe.fillRect(Unknown Source)
sun.java2d.pipe.ValidatePipe.fillRect(Unknown Source)
sun.java2d.SunGraphics2D.fillRect(Unknown Source)
com.klg.jclass.chart.JCChart.paintComponent(JCChart.java:670)
javax.swing.JComponent.paint(Unknown Source)
com.klg.jclass.chart.JCChart.paint(JCChart.java:593)
javax.swing.JComponent.paintChildren(Unknown Source)
javax.swing.JComponent.paint(Unknown Source)

So can any body tell me how can I prevent my applet from such type of happening  or how can I stop this.
Answer: The recommended way of stopping a thread in Java is to  implement the logic in such way that the thread will finish the execution on his own. If you have a loop you can consider ending it based on an action (eg. user clicked stop button of finish). From your details it seems that the applet is repainting. Probably you should look on what is triggering the repaint.
Comment: Thanks a lot @dan , Yes this was due to repaint.


Envio de e-mail com vários remetentes e destinatários

Question: Tenho registros no MySql, basicamente com colunas:
usuario, emailusuario, descricao, responsavel, emailresponsavel.
Preciso que, quando é feito um novo registro, envie um e-mail para o próprio usuário (emailusuario) e para o responsável (emailresponsavel).
Uso o PHPMailer, com uma conta Gmail para os envios, mas o problema é, que dessa forma o e-mail chega com e-mail de envio a conta Gmail e não com o e-mail do remetente (que seria o que faz o novo registro), mesmo setando o $mail->SetFrom('email@example.com','usuario');.
O $mail->AddReplyTo() funciona normalmente.
Gostaria de saber se isso ocorre porque é autenticado pelo Gmail, por ser TLS, ou algum outro motivo, e se há outra forma de fazer caso o problema for o PHPMailer. Preciso fazer isso, independente se tiver que trocar o SMTP ou biblioteca.
Script de envio:
require_once '/PHPMailer/PHPMailerAutoload.php';

$srvNome  = 'smtp.gmail.com';
$srvPort  = '587';
$srvEmail = 'firstname.lastname@example.com';
$srvSenha = '****';

$emailAssunto       = 'NOVO REGISTRO';
$emailDestinatario  = $emailDest1;
$titulo             = 'NOVO REGISTRO';

$conteudo = "teste";

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug  = 2;
$mail->SMTPAuth   = true;
$mail->SMTPSecure = 'tls';
$mail->SMTPOptions = array(
    'ssl' => array(
    'verify_peer' => false,
    'verify_peer_name' => false,
    'allow_self_signed' => true
    )
);
$mail->CharSet    = 'UTF-8';
$mail->Host       = $srvNome;
$mail->Port       = $srvPort;
$mail->Username   = $srvEmail;
$mail->Password   = $srvSenha;
$mail->AddReplyTo($emailRemetente,$remetenteNome);
$mail->SetFrom($emailRemetente,$remetenteNome);

$mail->IsHTML(true);
$mail->Subject    = $emailAssunto;
$mail->Body       = $conteudo;

$mail->AddAddress($emailDestinatario);

if(!$mail->Send()) echo 'erro';

Answer: Por questões de segurança do SMTP (Gmail no caso), a tag FROM (De:) sempre será preenchida com o e-mail da conta autenticada no SMTP, ou seja, do usuário do gmail no caso.
Você só conseguirá utilizar da forma pretendida se montar um servidor de SMTP próprio e enviar e-mail sem a autenticação no SMTP, via função mail() do PHP, pela porta 25. Atualmente a maioria dos provedores não aceitam mensagens oriundas da porta 25.


Filtering list of tuples based on the availability of a member in a list

Question: I want to filter a list of tuples like [(1,22,1),(5,1,8),(8,3,4),(7,5,6)] using a list like [1,7] which would eventually give me the result [(1,22,1),(5,1,8),(7,5,6)]; since (8,3,4) does not have either 1 or 7, it is eliminated.
I can write a comprehensive function for this. But I am looking for a short list comprehension if possible.
Thanks.
Answer: >>> tup_list = [(1,22,1),(5,1,8),(8,3,4),(7,5,6)]
>>> filter_list = [1,7]
>>> [tup for tup in tup_list if any(i in tup for i in filter_list)]
[(1, 22, 1), (5, 1, 8), (7, 5, 6)]

Answer: try with this one :
items = [(1,22,1),(5,1,8),(8,3,4),(7,5,6)]
result = [ item for item in items if (set([1,7]) & set(item))]

>>> [(1, 22, 1), (5, 1, 8), (7, 5, 6)]

Comment: This has a certain elegance, but unfortunately I don't think this is a situation where `set`s result in a better performing solution. You can factor out the `set([1, 7])` but you have to do the intersection and `set(item)` every time, and the intersection doesn't short-circuit, unlike `any()`.
Comment: @agf : in term of performance, I agree, I think the any() solution is better, but as the OP was looking for a 'short' list comprehension, i'm not so far ;)


How to use custom HTML code for a front page

Question: I want to use custom HTML code for a front page in drupal 8 but I am a bit lost of how to do it. Is it possible to just insert a piece of HTML code in a basic page content? Or what is the best way to do it? I have full access to the server and I can modify any file if needed.
Thank you.
Comment: Does this answer your question ? https://drupal.stackexchange.com/questions/293828/how-can-i-restrict-access-to-a-static-html-page-served-from-a-subfolder-of-my-si
Answer: You can make any node be the front page. So, if you have a basic page with a body field, you can place your html there. Then, go to admin > configuration > system (basic site settings) and set the path to your node as the front page such as /node/6.


Get acceleration from distance and speed

Question: I want to know how fast an object with the speed s1 (2.77m/s) would have to deccelarate to reach a speed s2 (0m/s) within a certain distance d (2.35m). With a formula for that I could go on to calculate the time needed, the force applied and so on...

Given:

Initial speed (2.77m/s)
resulting speed (0m/s)
distance to deccelarate (2.35m)

Searching:

deccelaration

Thanks in advance,
Bruno
Comment: See [Equation 4](https://en.wikipedia.org/wiki/Equations_of_motion#Constant_translational_acceleration_in_a_straight_line).
Comment: Write down the relevant equations.
Comment: @David G. Stork edited OP
Comment: @Math Lover There are some interesting formulas there, but not the one I am looking for.
Comment: @Bruno Eq. 4 in the said link should solve your problem. You might look at some 'simple' forms of these equations beneath the first set of equations.
Comment: @Bruno:  You have NOT written down the equations.  Instead you wrote the values of *variables*.  An equation states mathematically how they are related.  Here is just one of your needed equations:  $x = v t + x_0$, i.e., the position $x$ is equation to the initial position $x_0$ plus the velocity times time.
Comment: Unfortunately, I feel I had to flag this. This isn't a site that will solve problems **for** you, and some effort or examples of your own thoughts must be shown. That way, we can help you—and others—the best we can. For more information, please read [how to ask a good question](http://goo.gl/PlJyVQ). At any rate, I wish the best of luck to you, and please continue to contribute to our wonderful site!
Comment: You appear to be assuming constant acceleration. That needs to be made explicit.
Answer: We have the following formula, which can be rearranged easily.
$(v_2)^2 - (v_1)^2$ = $2ad$ $\Rightarrow$ $a$ = $\frac{(v_2)^2-(v_1)^2}{2d}$.
Since our deceleration leads to a final velocity of $0 \frac{m}{s}$, we can say $a$ = $\frac{-(v_1)^2}{2d}$.
$a$ = $\frac{-(2.77)^2}{2(2.35)}$ $\approx -1.63253 \frac{m}{s^2}$
Comment: How would I test if that result is correct? Can I just create a function f(x)=-1.63253x^2+2.77 and look at the interval from x=0 to y=0?
Answer: It is an easy kinematics/physics problem. Your object movement is described by movement equations.
$s2=s1-a*t (1)$
$d = s1*t - \frac{a*t^2}{2} (2)$
where s1,s2 -velocity, t - time, a - deceleration, d-distance.
Because $S2=0$, so (1) can be rewritten
$s1=a*t => t=\frac{s1}{a}(1')$
put (1') to (2)
$d = \frac{s1^2}{a} - \frac{s1^2}{2*a} = \frac{s1^2}{2*a}(3)$
or
$a = \frac{s1^2}{2*d} = \frac{2.77^2}{2*2.35} = 1.6325 \frac{m}{s^2}$


MySQLi edit from php and errors

Question: Here is the link for the big file: http://pastebin.com/ZREjJ2NK
The problem is as follows:
I get the same error:

ERROR: Please fill in all required fields!

But all my fields are written. Then from $bTag till $avatar my variables are with Notices like

Notice: Undefined index: blah blah Line begins at: 74 and ends at 78

If you wanna test the code here is the SQL:
CREATE TABLE `users` (
    `uid` INT(11) NOT NULL AUTO_INCREMENT,
    `email` VARCHAR(50) NOT NULL,
    `bTag` TEXT NULL,
    `password` VARCHAR(50) NOT NULL,
    `firstname` VARCHAR(50) NOT NULL,
    `lastname` VARCHAR(50) NOT NULL,
    `rank` INT(11) NULL DEFAULT NULL,
    `avatar` TEXT NOT NULL,
    `signup_date` INT(10) NOT NULL,
    PRIMARY KEY (`uid`),
    UNIQUE INDEX `username` (`email`)
)
COLLATE='utf8_general_ci'
ENGINE=MyISAM
AUTO_INCREMENT=11
;

Comment: In your form, all of the input fields, except for your `email` field, have `name="lastname"`
Comment: No one gonna see that piece of code. Paste relevant part of it here.
Answer: Finally found my problems. It was the Tags, one SQL problem and had to switch the redirect to the header towards the update page.

MySQLi edit from php and errors


Out of date VM tools - issue with MS licencing.

Question: I had an issue recently, where vmware tools on a production server, went out of date and caused the server in question to become unlicensed, I noticed this completely by accident.
The following error appeared when I tried to run the slmgr -dlv command 0xC004F00F which when I searched comes up with the following:
0xC004F00F  The Software Licensing Server reported that the hardware ID binding is beyond level of tolerance.   MAK/KMS client/KMS host
The hardware has changed or the drivers were updated on the system.
MAK: Reactivate the system during the OOT grace period using either online or phone activation. KMS: Restart, or run slmgr.vbs /ato.
I've inherited this environment and don't currently have a schedule for updating the vmtools (200+ servers), it was previously done on an ad-hoc basis either when someone notices it or whatever....  :(
So I fear an impending avalanche of servers popping off license, and worse still, is there a possibility, that some of these servers, if they go unlicensed for a period, could reach the hourly reboot threshold.
Comment: Yeah, this doesn't make any sense. VMware tools can be out-of-date without impact to your VM licensing.
Comment: Simply changing VMWare Tools versions shouldn't trigger this, or at least I have never seen it happen in hundreds of VMs. Did the tools upgrade coincide with any other change, such as a virtual hardware upgrade, migration to a physical host with different CPU families, and/or NIC reconfiguration from e1000 to VMXNET3 or similar? How are these guests licensed? MAK, I assume? If you really don't want to deal with activation, just use KMS.
Comment: Why not just keep them up to date?
Comment: Hi, it was vmtools that went out of date, it worked fine once the tools were updated. There was no physical hardware change on the server in question.
Comment: Hi, (late edit) it was vmtools that went out of date, i couldn't licence this box until I updated the tools, and worked fine once the tools were updated and I presented it to the internet. There were no virtual hardware change on the server in question.
Comment: Also, VMWare tools don't just go "out of date" unless you upgraded the hosts. If you upgraded the hosts and then proceeded to upgrade the guest virtual hardware versions, I *might* understand the MS licensing showing that as a hardware change - but even then, I've never seen this when I've updated hosts/hardware versions.
Answer: How do you license?
If it is MAK it will just reacticate on slmggr /ATO.
If it is KMS - which it should be - it will reactivate with slmgr /ATO from the KMS.
So, what is the question here? That you need to have licenses reactivating? That is a technicality and not complicated to script.
And servers do not hourly reboot. I had a machine at a custoemr that went unlicensed for a long time mostly because customer uses KMS and that machine had no access to it until a recent patch fixed the RRAS routing. Never got a reboot.
Thank heaven with 2012 R2 those times are over as VM's "pull" the license from the host.
Comment: Hi, it is MAK based, what the issue is, is it went unlicened because of vm tools going out of date, and windows 2008 R2 seen this as a hardware change, dropped the mak licence and disjoined from the network. I could still ping the server but couldn't login as a domain admin only local.
Comment: No, that is absolutely not what happens. MAK unlicesed does not disjoin the network / domain. Not at all. And the key should be in the machine for a relicensing, unless somene deleted it after activating.
Comment: Its really alarming, I'm still investigating this.
Answer: Microsoft have come back to me in relation to this issue, and this is what they have to say.
Yes, it is possible that when VMWare tools go out of date on the VMs the activation on the machine might get into Out-of-Tolerance mode and then eventually into notification mode if you do not reactivate the machine.
Windows Activation Technologies in Windows 7
http://technet.microsoft.com/en-us/library/dd979803.aspx
Excerpt from the above articles:
The software licensing architecture governs the licensing condition of computers that are running Windows operating systems. This architecture has a policy engine built from a number of core Windows security technologies. It is designed to protect the code and the associated licensing condition from tampering or other malicious behavior.
The policy engine gets data from a set of cryptographically signed eXtensible rights Markup Language (XrML) license files. XrML is an industry-standard rights expression language that a number of Windows components use. License files define the rights and conditions of the installed edition of Windows. All licensing files and other data that the policy engine uses are digitally signed or encrypted by using keys that are chained to secure roots of trust with Microsoft.
Windows 7 and Windows Server 2008 R2 may be in one of four software licensing conditions: activated, grace, genuine, or notifications. The following sections describe these conditions, which reflect the status of the computer's activation and genuine state, which dictates the user experience. Figure 6 illustrates these conditions.
Figure 6   License states
Activated

When a computer is activated, users can access the full functionality of the operating system. A combination of licensing files and a set of policies (rights) granted as a result of the activation process defines the functionality for a Windows edition. Individual Windows components call software licensing application programming interfaces (APIs) to determine which rights are granted and adjust their functionality according to the response.
Grace
After installing a Windows 7 or Windows Server 2008 R2 operating system but before activating it, users can access the full functionality of the operating system for a limited time (the grace period). The length of a grace period is 30 days for either the client or server operating system. During this initial grace period, the operating system periodically notifies the user that the computer needs to be activated. Additionally, Windows can fall in to out-of-tolerance grace when the hardware changes significantly. The notifications are minimally intrusive and may not start at the beginning of the grace period, but they increase in frequency toward the end of the grace period.
Genuine
The genuine state is not associated with the activation process. Instead, it is a condition determined by the online genuine validation service. When a user attempts to download or use a genuine-only feature, the online validation service checks the operating system of the requesting computer.
An operating system can have one of three genuine states:
1.  Non-genuine. The computer has obtained a ticket from the online validation service indicating that it is not genuine.
2.  Local genuine. The computer has not obtained a validation ticket.
3.  Genuine. The computer has a  ticket that is signed by Microsoft from the online validation service indicating that it is genuine.
The genuine license condition applies only to client versions of the Windows operating system. Initially, during the grace period, a computer running these Windows versions is always in a local genuine condition. A computer is never marked non-genuine until after it fails validation through the online validation service and receives a non-genuine ticket. Likewise, after a computer has a non-genuine status, it must successfully validate itself through the online validation service to receive a genuine ticket.
Although it is necessary for a computer to be activated to be considered genuine, the process of activation does not reset or clear a previous non-genuine status. As a result, to return a computer to a fully functional activated condition, it must be both activated and validated against the online validation service. For more information, see Genuine Microsoft Software http://go.microsoft.com/fwlink/?LinkId=151993 on the Microsoft Web site.
Notifications
The purpose of the notifications-based experience is to differentiate between an activated (genuine) from an unlicensed (non-genuine) copy of Windows in a way that maintains computer functionality, such as logon, access to the familiar desktop, and so on.
Reduced Functionality Mode (RFM) is not in Windows 7 or Windows Server 2008 R2. Instead, both operating systems have a notifications-based experience. This new notifications user experience means that computers that are not activated during their grace periods (initial activations and those that result from hardware changes) or that fail validation may provide the following user experience:
1.  After logging on to the computer, users see a dialog box reminding them that Windows must be activated along with options to activate now or later. If users do not interact with this dialog box within two minutes, the logon process continues normally.
2.  In the notifications state, Windows changes the desktop wallpaper to a solid black background, displays notifications in the notification area indicating the activation state, and displays dialog boxes showing actions that the user must take.
3.  In the notifications state, users have access to the full functionality of the installed version of Windows, with the following features disabled:
1.  A computer configured as a KMS host responds to KMS client requests with an error message that KMS has not been activated.
2.  Windows Update downloads security and critical updates (optional updates are excluded).
3.  Optional downloads requiring the online validation service—also referred to as genuine-gated downloads—are not available.
The computer must be activated for it to leave the notifications state.


MST that differ only on one edge

Question: I have stack to the following problem
Let $\,\mathbf{G=\left(V,E\right)}$ be a graph with a weight function $\mathbf{w:E\rightarrow\mathbb R}$ such that

G is simple,connected and undirected
w is injective
$\mathbf{\exists x\exists y\in V:f=\{x,y\}\notin E}$

Let $\,\mathbf{G'=\left(V',E'\right)}$ be a graph with a weight function $\mathbf{w':E'\rightarrow\mathbb R}$ such that

$\mathbf{V'=V,E'=E\cup\{f\}}$
$\mathbf{w'\left(e\right)=w\left(e\right),\forall\mathbf e\in E}$
$\mathbf{w'\left (f\right)<min \,w\left(T\right)}$ where T is the unique minimum spanning tree (MST) of G and $\mathbf{w\left(T\right)=\{w\left(e\right):e\in E\left( T\right)\}}$

Show that
$\mathbf{\left (i\right )} $$\,\mathbf G' $ has a unique (MST) , T'
$\mathbf{\left (ii\right )}$ T and T' differ at only one edge
I have shown $\mathbf{\left (i\right )}$ and that T' must contain f instead of ε which is the unique edge of maximum weight on the unique cycle of $\mathbf{T\cup\{f\}}$.
But how do i show that T,T' have all other edges in common?I can show that using for instance Prim's algorithm but is there another way,more theoretical without a use of all known MST-finding algorithms?
Thank You
Answer: Let $C$ be the unique circuit in $T\cup \{f\}$ and $e\in E(C)$ be the edge with maximal weight in $C$.
Notice that any MST $T'$ of $G'$ either contains $f$ or does not contain $f$. If it does not contain $f$ then we claim it is not an MST. If it does, we claim $T' = T\cup \{f\} \setminus \{e\}$. This solves (i) and (ii).
Indeed, if $T'$ does not contain $f$ then it is also a spanning tree of $G$.
By the uniqueness of $T$, $T$ has less weight than $T'$.
But $T$ is also an MST of $G'$, contradicting that $T'$ was an MST.
If it does contain $f$, then $T'-f$ has two connected subtrees.
Let $S, \bar{S}\subseteq V(G)$ be the vertices of these subtrees and note that their disjoint union is exactly $V(G)$, ie $(S, \bar{S})$ induces a cut of $G$.
Then $T'[S], T'[\bar{S}]$, the induced trees are MSTs of their respective induced subgraphs $G'[S], G'[S']$.
Remark that $G'[S] = G[S], G'[\bar{S}] = G[\bar{S}]$ since the two graphs only differ by an edge crossing the cut $(S, \bar{S})$.
But then $T'[S], T'[\bar{S}]$ must be the unique MSTs of their respective induced subgraphs since $T$ was unique. In other words, $T'[S] = T[S], T'[\bar{S}] = T[\bar{S}]$.
This shows that any MST of $G'$ must contain $f$. Moreover, when we remove $f$ and look at the two subgraphs of $G'$ induced by the vertices of the two connected components of $T'-f$, any MST of $G'$ does not differ from the unique MST of $G$.
Any MST of $G$ or $G'$ can only have one edge in the cut $(S, \bar{S})$. For $T'$, this edge is $f$.
For $T'$, this is not $f$ since $f$ does not exist in $G$.
Comment: The only thing u showed is that $T'\left[ S\right],T'\left[\bar S\right]$ are the unique MST's of the induced subgraphs $G\left[S\right],G\left[\bar S\right]$.Why this implies that the unique MST of $G$ ,$T$ differ from $T'$ only by one side?
Comment: I added a few sentences to my answer.
Comment: Now u r talking.Thank u.You were so helpful

MST that differ only on one edge


Como gerar SQL em tabela de relacionamento sem repetir valores?

Question: Eu tenho o seguinte cenário:
Tabelas:
Video (id, url)
VideoCategoria (id, id_video, id_categoria)
Categoria (id, descricao)

Eu preciso pegar as ultimas 120 categorias que receberam videos. No mesmo cursor eu queria o seguintes campos:
(Video.Url, Categoria.descricao)

Só que não pode repetir a url do video, por exemplo, se um unico video entra com duas categorias diferentes então a categoria 1 e 2 estão vindo com a mesma Url.
Já foi dada uma solução aqui usando cursor e fazendo loops até achar outro vídeo, tentei fazer tudo no SQL, mas não estou conseguindo fazer, alguém sabe se é possível?
Eu estou usando o id da tabela Video_Categoria para pegar os registros mais novos.
ATUALIZAÇÃO:
Esquema criado no SqlFiddle como solicitado no comentário.
Answer: você pode usar o DISTINCT para garantir que somente um valor será retornado.
Comment: você pode usar o [Rextester](http://rextester/runcode) ou [SQLFiddle](http://sqlfiddle.com/) para criar test case e facilitar a ajuda ;)
Answer: Video (1, 'TestoUrl1'), (2, 'testeUrl2')
VideoCategoria(1, 1, 1), (1, 1, 2)
Categoria(1, 'Terror'), (2, 'Ação')
Se você quer retornar a URL do Video e a Descrição da Categoria, sempre irá retornar URL repedidas para categorias diferentes. Pois o retorno ficaria:
TesteUrl1, Terror
TesteUrl1, Ação

Distinct para esse caso não resolve.
A dica que dou é utilizar a URL como o nome do campo de retorno e os dados são a descrição, ficando desta maneira por exemplo:
TesteUrl1    TesteUrl2
Terror       ação
Ação         Terror

deu pra entender?
Comment: Nesse caso eu teria q ter 120 colunas, certo? Uma para cada categoria q quero.
Comment: Não, a Coluna seriam as URLs, se temos 120 categorias porém todas estão na mesma URL, então teria apenas 1 Coluna.
Comment: Por favor, faça um exemplo destas tabelas com dados ficticios neste site: http://sqlfiddle.com/
Comment: Criei e atualizei a pergunta, só não entendi como roda o sql lá, não tenho certeza se fiz certo. http://sqlfiddle.com/#!3/fc985
Comment: SqlFiddle com o seu select [sqlfiddle.com/#!3/fc985/2](http://sqlfiddle.com/#!3/fc985/2). Utilizando o seu select no site gerou um erro falando que o campo url não existe, você chegou a testar no sql server?
Comment: O finddle deve estar errado, o sql q eu usei já está rodando já.
Answer: Consegui montar com a ajuda do Entity Framework e o resto eu mesmo terminei.
Segue a solução:

select
 v.url,
 c.id,
 c.description

  from (
select top 120 a.id_video, max(id_categoria) as id_categoria from (

SELECT
    [Join2].[ID] AS [ID],
    [Join2].[ID_VIDEO] AS [ID_VIDEO],
    [Join2].[ID_CATEGORIA] AS [ID_CATEGORIA]
    FROM   (SELECT
        [Extent2].[ID_VIDEO] AS [K1],
        MAX([Extent2].[ID_VIDEO]) AS [A1]
        FROM   (SELECT
            [Extent1].[ID_CATEGORIA] AS [K1],
            MAX([Extent1].[ID]) AS [A1]
            FROM [VIDEO_CATEGORIA] AS [Extent1]
            GROUP BY [Extent1].[ID_CATEGORIA] ) AS [GroupBy1]
        INNER JOIN [VIDEO_CATEGORIA] AS [Extent2] ON ([GroupBy1].[K1] = [Extent2].[ID_CATEGORIA]) AND ([Extent2].[ID] = [GroupBy1].[A1])
        GROUP BY [Extent2].[ID_VIDEO] ) AS [GroupBy2]
    INNER JOIN  (SELECT [Extent4].[ID] AS [ID], [Extent4].[ID_VIDEO] AS [ID_VIDEO], [Extent4].[ID_CATEGORIA] AS [ID_CATEGORIA]
        FROM   (SELECT
            [Extent3].[ID_CATEGORIA] AS [K1],
            MAX([Extent3].[ID]) AS [A1]
            FROM [VIDEO_CATEGORIA] AS [Extent3]
            GROUP BY [Extent3].[ID_CATEGORIA] ) AS [GroupBy3]
        INNER JOIN [VIDEO_CATEGORIA] AS [Extent4] ON ([GroupBy3].[K1] = [Extent4].[ID_CATEGORIA]) AND ([Extent4].[ID] = [GroupBy3].[A1]) ) AS [Join2] ON ([GroupBy2].[K1] = [Join2].[ID_VIDEO]) AND ([Join2].[ID_VIDEO] = [GroupBy2].[A1])

  ) as a

group by a.id_video
order by id_video
) as grupo

join
[CATEGORIA] as c
on grupo.id_categoria = c.id
join
[VIDEO] as v
on grupo.id_video = v.id


Is it possible to disable cache on certain fields?

Question: I am working on a site where i'm implementing my own cookie bar module.
For this module i have made it possible to write something in the CKeditor like:

Where everything between the {cookie} tags is only visible when cookies are accepted. This works fine on my dev environment, but when I deployed it to the test server where cache is enabled it won't show any change when you enable/disable cookies because the page is already cached.
Is there a way to disable cache on the text field or better yet, everything between the cookie tag?
Answer: You need to adjust the cache context of the node.
If the cookie is a drupal session, use the predefined cache context for this:
<code>$build['#cache']['contexts'][] = 'session.exists';
</code>
If you target another cookie, that drupal is not aware of, you would need to create your own context, more info:
https://www.drupal.org/developing/api/8/cache/contexts


What is the difference between "retired out" and "retired not out" in cricket?

Question: I have seen the terms on scoreboard like: "retired out" or "retired not out". What does it mean and what is the different between there?
Reference:

Mohammad Hafeez was retired out in ICC Champions Trophy Warm-up
Matches, 2013 vs South Africa
Gordon Greenidge was retired not out in 5th Test vs India.

Also I have seen "retired out" only on practice matches. Is there any case of "retired out" in international matches?
Answer: Retired not out
If a batsman retires during his innings because of injury, illness or any other unavoidable reasons, and doesn't resume his innings, he is considered as retired not out. He can resume his innings after the wicket is fallen or other batsmen is retired. Retired not out is considered as not out.
Retired out
If a batsman retires during his innings for any reason other than injury, illness or any unavoidable reasons, and doesn't resume his innings, he is considered as retired out. He can resume his innings only with the consent of the opposing captain. Retired out is considered as out.
Reference: Law 2.9 (Batsman retiring)
Answer: In the history of Test match cricket there are only two times a batsman was out by this term retired-out. Both of them are Srilankan cricket players and both the instances were held in a same match.
Generally, retired-outs are happened only in warm-up matches where the result is not as much important. So this dismissal term was not included in the standard dismissal terms.
Retired not-outs are very common as you said, it may be due to any reason, since the batsman can re-enter at anytime.


Puppeteer hides cells borders when backgroundColor is applied

Question: Generally Puppeteer makes pdf as it's expected without backgroundColor (table cells can have colspan/rowspan):

But, if { backgroundColor: #c1c1c1; } is applied cell borders disappear randomly:

How apply backgroundColor to table and preserve cell borders?
Answer: Resolved by using colors with opacity, f.e. background-color: rgba(0, 0, 0, 0.2);