Do frameset work in quirks mode (IE9 - IE10)?

Question: I am working a very old application which is used in quirks mode - IE7. It is working with frames (frameset).
Do those frames will work (no effects) with IE9 - IE10 by staying in the quirks mode (no doctype)? Is it possible to be still running under IE9 - IE10 ?
==> EDIT
Frameset are obsolete in html5, does it mean the same in quirks mode (no DTD) for IE9 - IE10 ?
Comment: did you test this yourself? What tests have you ran?
Comment: sounds it works, but do frameset are obsolete in html5, does it mean the same in quirks mode (no DTD) ?
Comment: Nobody said all that modern browsers could display was HTML5.
Answer: I guess adding in IE10 or IE9
<code>  <meta http-equiv="X-UA-Compatible" content="IE=5">
</code>
make frameset work as in IE7-
Natively, IE9 can support frameset but IE10 no more
Comment: I'm not sure what you are doing. My IE10 loads a frameset without complaining. And why wouldn't it? It's not that everybody magically stopped using frames. - Can you provide an example that does not work?
Comment: Yea I tried, but as expected the CSS file didnt work anymore. I wanted to add      ... but same result
Comment: When I say frameset dont work in IE10, I mean JS interactions, for instance : parent.frames(target) returns undefined if you dont add the quirks IE5 tag in the DoM Head
Comment: As I said - can you provide an example that does not work for you? BTW, next time such information should be part of the question, not part of the 4th comment under some answer.


Prove that their is one empty set?

Question: (I am aware this question has been asked before but mine is little different). Applying the axiom of extensibility , I am able to prove this, but still I am not able to understand the significance of this result, it appears to me that this is true for every set. Say $A=(a_1,a_2,a_3)$ then $A=B$ iff $B=(a_1,a_2,a_3)$ hence their is unique set $A$ (that is $A$ itself).
Comment: As a translation note, the English words *there*, *their*, and *they're* have different meanings though the same pronunciation.  [This page might help](http://www.wikihow.com/Use-There,-Their-and-They%27re) with keeping them straight.  The word you intend to use in this context is *there*.
Comment: I don't understand the problem. You are simply quoting the content of the axiom of extension.
Comment: @PatrickStevens Given any set $A$, their is only of its kind i.e $A$, so this is a general result, so what is special about this theorem applied to empty set
Comment: Nothing, as far as I know. It's just an easy and accessible result, and it clarifies that "there is only one kind of empty".
Answer: The axiom of extensionality states that two sets are equal if and only if they have the same elements. In particular, if we have two sets $x,y$ without any elements, then $x = y$ and thus, there is a unique empty set.
If we drop the axiom of extensionality, it is possible to have sets $U,V$ such that $U \neq V$ and neither $U$ nor $V$ contain any element. These sets can be regarded as "urelements" (that are also called "atoms") - a concept that has been of significant interest in the earlier days of set theory. In fact, Fraenkel and Mostowski used urelements in independence arguments long before Cohen invented forcing. One important result is that ZF + "urelements" doesn't imply the axiom of choice and so ZF - extensionality doesn't imply the axiom of choice. The fact that extensionality has to fail in order to apply the methods of Fraenkel and Mostowski is a considerable weakness of their theory and for several decades, no one saw how to adapt their methods in order to construct new models of ZF. In fact, no one was able to prove the consistency of $\neg V = L$, relative to ZF.
In 1963, with Cohen's introduction of forcing, all of this changed and soon he realized that his theory could be used to imitate Fraenkel's and Mostowski's methods without violating extensionality. A development that lead to the theory of "permutation models".
TL;DR Having a unique empty set is - in a sense - the requirement that our models don't have urelements and this complicates the early independence results of Fraenkel and Mostowksi.

Prove that their is one empty set?


Print JavaScript in Custom Block Module

Question: I have a google chart timeline that is dynamically updated from a google sheet. I created a custom module 'jsblock' to manage the script, styling and layout of the chart.
To begin with, first I need to get the chart to actually print in the block, which it does not.
jsblock/js/custom.js:
(function ($) {
Drupal.behaviors.jsblock = {

    attach: function (context, settings) {

    google.charts.load('current', {'packages':['corechart', 'controls', 'timeline']});
google.charts.setOnLoadCallback(drawStuff);

function drawStuff() {
  // query against spreadsheet
  var queryString = encodeURIComponent('SELECT A, B, D, E');
  // Test that the variables are added to the queryString as the strings contained within the variables - which they do.
  //alert(queryString);
  // below grabs just data, not header rows
  var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/[chartstrid/gviz/tq?gid=0&headers=1&tq=' + queryString);
  query.send(handleQueryResponse);
}

// handler for query response from spreadsheet
function handleQueryResponse(response) {
  if (response.isError()) {
  alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
    return;
  }
  var data = response.getDataTable();
  // control for date filter
  var datepicker = new google.visualization.ControlWrapper({
    'controlType': 'DateRangeFilter',
    'containerId': 'control4',
    'options': {
      'filterColumnLabel': 'Start',
      'labelStacking': 'horizontal',
      'ui': {
        'cssClass': 'slider'
       }
    }
  });

  var changeTimeline = new google.visualization.ChartWrapper({
     'chartType': 'Timeline',
     'containerId': 'timeline',
     'chartArea': {'left': 55, 'top': 15, 'right': 0, 'bottom': 0},
  });
}

function drawChart(dataTable) {
  var container = document.getElementById('timeline');
  var chart = new google.visualization.Timeline(container);
  var dataTable = new google.visualization.DataTable();
  var options = {
    timeline: { showRowLabels: false, singleColor: '#8d8' }
  };
  chart.draw(dataTable, options);
      // data and options to be used in drawing the regular table
  var programmaticChart1 = new google.visualization.ChartWrapper({
    'chartType': 'Timeline',
    'containerId': 'programmatic_chart1_div',
    'chartArea': {'left': 55, 'top': 15, 'right': 0, 'bottom': 0}
           //'view': {'columns':[0,2,]}
  });
  // start up the dashboard
  var dashboard = new google.visualization.Dashboard(document.getElementById('programmatic_dashboard_div'));
  //bind the control and the chart to the dashboard
  dashboard.bind(datepicker, programmaticChart1, changeTimeline);
  // Draw the dashboard.
  dashboard.draw(data);
}

function createCustomHTMLContent(flagURL) {
  console.log('inside custom');
       //
    }
  }
);

jsblock.module:
// Render the chart in the block inside the divs specified by the getElementById calls in the chart code above
<?php

function jsblock_block_info() {
    $blocks = array();
    $blocks['jsblock']['info'] = t('My JS Block');
    return $blocks;
}

function jsblock_block_view($delta = '') {
    $block = array();
    $block['subject'] = t("The title");
    $block['content']['#markup'] = "My content goes here";
    $block['content']['#attached']['css'][] = drupal_get_path("module", "jsblock")."/css/styles.css";
    $block['content']['#attached']['js'][] = drupal_get_path("module", "jsblock")."/js/custom.js";
    $block['content']['#attached']['js'] = array(
  'https://www.gstatic.com/charts/loader.js' => array(
    'type' => 'external',
    ),
    );
    $block['content']['#markup'] = "

 Technology Product Life Cycle

";

  return $block;
}

Here's how it's currently rendering:

Here is how it should look:

No console errors in chrome or firefox.
Any help is greatly appreciated!
Comment: If you use single quotes for your HTML strings you don't have to escape all the double quotes.
Comment: From the looks of it your block is printing correctly but something in the chart JS you wrote isn't correct, which means I don't think that this is a drupal specific question, it's just a google charts question. I can't test it thoroughly because your spreadsheet link is missing, but one thing that stands out is that you never call the draw chart function. You also refer to the containerID 'timeline', which doesn't exist in your block markup. It might just be an omission from your question but you also don't attach the google charts JS and there are some missing closing brackets in your JS.
Comment: @rooby Thanks for these suggestions. I've updated my code with the timeline div as well as the attached external script. I also checked over the js and I can't find any missing closing brackets. As for calling the draw chart function, you can see the functions chart.draw(dataTable, options); and dashboard.draw(data); near the bottom. I'll mock up a sheet and update the code so there is a better working example.
Comment: Re the closing brackets. I made a custom module with the code you have here and it had a javascript error unexpected ) on the last line. Instead of ); at the end it should be }; }(jQuery)); - If the code in this question is exactly what you are using and you really aren't getting any javascript errors then your javascript would seem to be not running at all.
Comment: @rooby I scoured the document and found I had a bracket in the wrong place! Thank you for encouraging me to take a closer look!
Answer: At first sight I see 2 problems in your code.

The javascript order, the external file has to load first in order to use the code in your custom javascript.
The custom javascript will never be loaded because you rebuild the complete $block['content']['#attached']['js'] array in the next line.

Change
$block['content']['#attached']['js'][] = drupal_get_path("module", "jsblock")."/js/custom.js";
$block['content']['#attached']['js'] = array(
  'https://www.gstatic.com/charts/loader.js' => array(
    'type' => 'external',
  ),
);

to
$block['content']['#attached']['js'] = array(
  'https://www.gstatic.com/charts/loader.js' => array(
    'type' => 'external',
  ),
  drupal_get_path("module", "jsblock") . "/js/custom.js"
);

Add
Also, if is good practice to use hook_theme to load a template instead of inserting html directly as content markup.
Comment: the order of loading was the final thing keeping my chart from loading. This did it. Thanks for taking the time to provide an answer and for showing me how to add multiple js files into an #attached array!

Print JavaScript in Custom Block Module


When was the last 'clean' race?

Question: When was the last 'clean' Formula 1 race?
A 'clean' race is one in which all cars that made a time in qualifications ended the full race (they did not retire or receive a DNF or DNS).
Answer: As of June 2018: the 2016 Japanese Grand Prix
Prior to the 2016 Chinese Grand Prix, only five races had finished with a full house. That list includes the 2015 Japan Grand Prix, where Felipe Nasr did not physically finish the race, but was classified after having run more than 90% of the total distance.
The 2016 Chinese and subsequent 2016 Japanese Grands Prix both had a true full house finish, 22 of 22 cars that qualified also finished.
Since then, the closest to a full house finish has been a single retirement from a qualified field of 20 and of 22.
Answer: Just as an update to the previously accepted answer, which is from 2018, the last "clean" race as OP describes was the 2019 Austrian GP.
According to Wikipedia:

Verstappen's victory marked the first win for a Honda-powered F1 car since Jenson Button in the 2006 Hungarian Grand Prix. The race was also the first race in the season not to be won by a Mercedes driver, as Valtteri Bottas finished in third and Lewis Hamilton fifth. Antonio Giovinazzi scored his first ever career points in Formula One by finishing tenth place.[13] This also marked the first race in which every driver saw the chequered flag since the 2016 Japanese Grand Prix. (emphasis mine)

When was the last 'clean' race?


Server down at 23:26 every night

Question: We are having a big problem with our sites stability the last couple of weeks and after endless hours of troubleshooting I don't get anywhere. So I turn to you dear community.
Setup:
2 x VPS servers
- Front end, 8 core, 8G RAM.
- Database, 5 core, 3G RAM.
Both running Ubuntu. Ruby on Rails EE with Passenger 3 and Rails 2.3.11. MySQL 5.1.67.
The problem is that each night, at the exact same time (23:26) the SQL server suddenly shows a processlist full of COMMIT with an increasing Time. After 30-40 seconds (can go longer) a wave seems processed and the site responds for a few seconds before it repeats. During this hick up the database server load spikes while the front end is relaxing.
I have looked at slow queries, but is not finding any locks or other unusual queries ran at this time. I have looked at iotop at the time of the halt and there is no activity from mysql. I also tried turning off query_cache and messed around with the mysql configuration file without much change.
Any ideas?
Comment: Could this be the time that the VPS provider suspends the VMs to snapshot them?
Comment: Have you enabled the full query log, and captured all the queries happening during that time-frame?  Yes logging all the queries will slow things down, but it might be worth doing at least once to see if you can isolate the cause.
Comment: Yes, but I just see a bunch of the regular queries that we run. I'm not sure where to look for the exact cause of the lockup though since the log doesn't specify the time the query took etc.
Comment: what does the sar output say. any clue from there.
Comment: Good one, I'll check this. Thanks for thinking outside the box.
Comment: sar output shows the database as 100% (nearly) idle on all cores when the hickup happens.
Comment: We have now created a new server (VPS provider made sure the server was created on a different cluster) using Debian 5 and the same version of the MySQL server. We did this in the middle of down time last night. The results are promising but we'll wait until tonight to celebrate.
Answer: check for:

cron jobs
access/error log
mysql slow query log

* UPDATE *
I'd log-in to system around that time and would use (h)top and monitor system to see what exactly is causing it and then work from there to enable more logging on that daemon to figure it out.
Comment: There is no cron job at that time. Nothing in the error log. Like I said, nothing unusual in the slow query log. The most logged ones are the COMMITS, but it doesn't show exactly what query was ran.
Answer: We switched the DB server to a new cluster on our VPS provider's network and installed it fresh. We didn't notice any problems at all yesterday. Guess it's just one of those things that fall outside of our own configuration. Moral story is that you might need to check with your VPN provider if you're having these kind of troubles.

Server down at 23:26 every night


Counting polynomials which are constant on a specific hyperplane

Question: Say a function $f:\mathbb{R}^m\to\mathbb{R}$ is having the 1-property if it equals $1$ on the hyperplane $\sum_{i=1}^m x_i=1$.
How many polynomials of degree $n$ have the 1-property?
Answer: Infinitely many. In particular, given any polynomial $f(x)$ we have that
$$f(x)\left(1-\sum_{i=1}^m x_i\right)+1$$
is such a polynomial, and this describes all such polynomials.
Answer: Infinitely many.  Anything of the form $g(x_1,\ldots,x_m) (\sum_{i=1}^m x_i - 1) + 1$ where $g$
has degree $n-1$ will do.


when i press row in my datagrid, how to show picture that in database?

Question: i working on asp.net & C#
i have datagrid that contain my database.
i have table Workers that contain ID,Fname,W_PIC (W_PIC contain the picture)
when i press row in my datagrid how to show the picture in image control
that i has in my web-form ?
(the picture in the database is not a link to picture - its binary array)
Comment: What is the database data type of W_PIC?
Answer: Retrieve Images from a SQL database for display in an Asp.Net Datagrid


CSV import from JAVA using postgres script

Question: So I have this script that i need to execute from  a Java web application.
The file containing this lines is located under WEB-INF
    truncate table amm.mm_dosage_unit;
    alter table amm.mm_dosage_unit add column code_new_version character varying(1);
    copy amm.mm_dosage_unit FROM 'code_list.csv' DELIMITER ',' CSV;

I use reader to execute each of the lines.
Problem is that I dont know how to scpecifie the correct path for my .csv file and i get No such file or directory error.
Any ideas
Comment: In PostgreSQL, when you use the `COPY` command (not the `\copy` command from psql), it is looking for files on the server that runs PostgreSQL, not on the client side. Is your web application running on the same machine as PostgreSQL?
Comment: yes. it is the same machine always.
Comment: Then you need to specify the full path of the csv file, and also make sure that the hierarchy of folders and the file itself are readable by the user account that runs PostgreSQL.
Comment: Understood. Thanks.
Answer: To my understanding, the SQL query is running on the server, which is a separate filesystem to the client running the web application.
The sql server would be looking for a file on the server, while the CSV file is actually located on the client's machine.


Aplicação Web e token A3 sem instalações locais

Question: Meu objetivo é um sistema web que sirva como ponte entre um serviço do governo e o usuário, abstraindo o acesso e a troca de dados.
O usuário acessaria meu sistema web e poderia realizar ações, como enviar documentos assinados digitalmente, para um serviço do governo (como um xml).
Porém pra realizar esse envio, o WebService do governo, disponibiliza classes com métodos de acesso e nessas classes existem algumas propriedades que precisam ser preenchidas, como a propriedade ClientCertificate.Certificate nela eu tenho que atribuir um objeto tipo X509Certificate2 com o objeto do certificado do cliente.
Consegui fazer usando A1, o usuário faz upload do A1 e insere a senha, com o arquivo do A1 eu consigo instanciar o objeto X509Certificate2 e atribuí-lo a respectiva propriedade na classe responsável pelos dados da conexão com WebService do governo.
Não sei como faria com A3, já que não daria pra fazer upload da chave publica/privada. Já vi que o browser consegue acessar a lista de certificados na máquina, mas não sei como faria pra instanciar um objeto X509Certificate2 no servidor usando esse método, nem se isso é viável pra uma aplicação web.
Resumindo, minha dúvida é:
É possível (ou viável) uma aplicação web acessar as chaves e os dados locais de um token A3 pra se comunicar com um WebService do governo?
Dúvidas extras:
O acesso do browser aos certificados na store do usuário é feito de que forma? Como eu preencheria um objeto X509Certificate2?
Answer: Diego, eu passo basicamente pelo mesmo problema. Depois de pesquisar muito, optei por usar somente certificados A1 nos casos de sistema na nuvem.
Minha conclusão foi a seguinte: Se o minha API ou serviço está rodando no servidor e o certificado A3 está no cliente, para cada chamada o cliente sempre terá que me enviar o certificado. Com isso eu me limito a trabalhar somente com requisições de entrada. Não poderia, por exemplo, adicionar um serviço que faça uma determinada operação que dependa do certificado em um timer (ou alguma rotina - nesse caso foi para aplicação no serviço de notas fiscais do destinatário da NF-e).
Dependendo da necessidade, você pode fazer um sistema desktop tryon ou um serviço do windows no cliente que faça essas chamadas, com isso você conseguiria sim utilizar o certificado A3 (inclusive setando a senha automaticamente quando for o caso). Porém, o problema de um timer como citei acima ficaria nesse app no cliente.
Já utilizei uma forma de se criar um "servidor" de certificado para a rede local do cliente. Ele possuía um certificado A3 e vários usuários faziam a transmissão de NF-e, com isso toda regra de transmissão eu coloquei nesse comunicador de NF-e
Trabalhando com A1 eu o deixo salvo no servidor web, no meu caso salvei em formato string na base64. E tenho autonomia total sobre ele.
Bom eu não solucionei nada pra você(haha), mas como estamos no mesmo barco vale a troca de experiência.
Comment: _"não solucionei nada pra você"_ Meu irmão, esse relato ajudou demais e me deixou muito mais próximo da solução mais prática pro meu problema, agradeço muito por dividir sua experiência. Pro A1 eu fiz a mesma coisa que você, fica super tranquilo. Acho que pro A3 vou acabar tendo que fazer uma aplicaçãozinha windows forms mesmo, ou algo do tipo, que o cliente instala local e eu crio uma logica de comunicação entre o servidor e a aplicação.
Comment: @DiegoPenha valeu parceiro! Se puder ajudar estou a disposição. Abraço.


Forçar o GPS do Android a atualizar a leitura

Question: Recentemente adicionei a minha aplicação a funcionalidade de coletar
os pontos de latitute e longitude do GPS em que o dispositivo se encontra.
Para tal adicionei ao AndroidManifest.xml as linhas:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Criei uma Activity que implementa LocationListener
public class MinhaClasse extends FragmentActivity implements LocationListener {

e no Evento OnCreate instanciei as classes que serão utilizadas.
   locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
   Criteria criteria = new Criteria();
   String provider = locationManager.getBestProvider(criteria, false);

   location = locationManager.getLastKnownLocation(provider);
   locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, this );

   if (location != null) {
       onLocationChanged(location);
   } else {
       .... "Localização não disponível"
   }

@Override
    public void onLocationChanged(Location location) {
        float lat = (float) (location.getLatitude());
        float lng = (float) (location.getLongitude());
    }

Desta maneira esta funcionando, acontece que o ponto devolvido nem sempre é o melhor. Na maioria das vezes esse ponto está a 50 metros
de distancia do dispositivo e eu não vejo como atualiza-lo. Quando essa aplicação rodava em um dispositivo com Windows Mobile eu lia
uns 100 pontos e em seguida tirava uma média desses pontos e a posição resultante era precisa na casa dos centimetros.
Como posso 'força-lo' a atualizar a leitura quantas vezes eu quiser?
Answer: Pode "forçar" uma leitura através de uma das variantes do método requestSingleUpdate().
Com requestLocationUpdates() não é possível "forçar" updates, apenas definir em que condições um novo update é feito.
A frequência em que o método onLocationChanged() do listener é chamado é determinada pelos valores passados ao segundo e terceiro parâmetros de requestLocationUpdates()
void requestLocationUpdates (String provider,
                long minTime,
                float minDistance,
                LocationListener listener)

minTime indica o número de milissegundos mínimo entre chamadas.
minDistance indica a distância em metros que o dispositivo tem de se deslocar para haver uma nova chamada ao método.

Notas:

A precisão da localização não é determinada pelo número de vezes que a leitura é feita mas sim pela qualidade do GPS e condições de recepção(número de satélites).
Se for passado o valor 0 a minTime o método é chamado quando é obtida uma leitura e não voltará a ser chamado enquanto não houver uma alteração da posição em minDistance.
minTime tem precedência sobre minDistance. Quando minDistance for diferente de 0 haverá um update se houver uma alteração de posição superior a minDistance e se tiver passado pelo menos minTime milissegundos.

Observação:
Considere usar a Api Fused Location Provider que a Google afirma ter várias vantagens sobre o LocationManager. Veja a documentação em Making Your App Location-Aware.
Esta resposta tem um exemplo de uso.
Comment: Agora sim. Usando a LocationServices API do GoogleApiClient as chamadas a atualizações podem ser feitas bem facilmente e as respostas são muito mais precisas. Apesar de eu estar em uma área coberta o ponto 'cai' exatamente onde estou. Valeu. Obrigado mesmo.
Comment: Veja que eu passei 0,0 para que a atualização fosse máxima, mas isso não ocorre. Ocorre atualizações, mas não compreendi como. Já permaneci nos mesmo local e elas ocorreram e me desloquei e elas não ocorreram.
Comment: Sim, eu compreendo a questão da recepção e do número de satelites. Acontece que mesmo em condições favoráveis o ponto é impreciso. A técnica de ler várias vezes e tirar uma média surtia um bom efeito nos dispositivos Windows Mobile.
Comment: Veja que estranho. Alterei os parametros e coloquei um minTime igual a 100. Na volta do almoço, executo minha aplicação e a coordenada que ele me dá é a do restaurante, 200 metros de distancia de onde estou agora.
Comment: Vendo aquela chamada a `onLocationChanged(location);` no `onCreate()` é possível que essa seja a `LastKnownLocation`. O facto de colocar `minTime igual a 100` não quer dizer que o método seja chamado de 100 em 100 milissegundos. O GPS pode não ter conseguido obter uma nova localização entre o trajecto do restaurante até ao local onde está agora.


What is the meaning of the affixed paragraph on Sharps?

Question: I am having a doubt with regard to the below portion of a textbook I am studying. I am new to music theory and therefore, the doubt that I have might sound trivial. But, Kindly help.
It says that when one sharp is employed all F's must be raised. When two are employed F and C must be raised and so on. I did not understand what the author is trying to say. I also did not understand why the author gave the order of the notes as F#, C#, G#, D#, A#, E# and B# instead of E#, F#, G#, A#, B#, C#, D#, E# etc which seems logical to me in the order of the lines of the staff notation. Am I missing something? Kindly help.
Thank you.
Comment: I'd be useful to have around a fifth and forth circle (as chemist do with the periodic table) as you start your learning process. @Lazy's answer is correct
Comment: You might have an easier time with a more modern source! This language is quite old-fashioned and stilted, and wouldn't even have been very clear in 1908 (or earlier?) when it appears to have been written, from a Google books search. You might start with [Musictheory.net](https://www.musictheory.net/lessons), or get a copy of a textbook from at least the past 50 years from a library or used book store.
Answer: This is about sharps in key signatures. The sharps in key signatures follow the circle of fifths (this is because sharpening the 4th degree of a major scale leads to the major scale on the fifth degree).
So the first note that is sharpened is F→F♯, then (the fifth of F) C→C♯, G→G♯ and so on.
Answer:
when one sharp is employed all F's must be raised. When two are employed F and C must be raised and so on. I did not understand what the author is trying to say.

This is normally expressed in terms of the major and natural minor scales, and therefore major and minor keys (it can be applied to other modes as well, but this answer will ignore that).
Whenever you see a key signature with one sharp, it is F♯, meaning that the piece is e'in G major or E minor.  If there are two sharps, they are F♯ and C♯ and the key will be either D major or B minor.  Every time you increase the number of sharps, you add the next sharp in the circle of fifths, and this gives you the key signature for the major key a half step above that sharp and the minor key a whole step below it.

I also did not understand why the author gave the order of the notes as F#, C#, G#, D#, A#, E# and B# instead of E#, F#, G#, A#, B#, C#, D#, E# etc which seems logical to me in the order of the lines of the staff notation.

Because you will never see a key signature with E♯ and F♯ only.  There are essentially only seven key signatures containing sharps:

F♯: G major or E minor
F♯ C♯: D major or B minor
F♯ C♯ G♯: A major or F♯ minor
F♯ C♯ G♯ D♯: E major or C♯ minor
F♯ C♯ G♯ D♯ A♯: B major or G♯ minor
F♯ C♯ G♯ D♯ A♯ E♯: F♯ major or D♯ minor
F♯ C♯ G♯ D♯ A♯ E♯ B♯: C♯ major or A♯ minor

Given this set of seven key signatures, it should be more obvious why the author lists the sharps according to the circle of fifths.
(You might encounter experimental music that violates this principle, but it is exceedingly rare.  Theoretically, this sequence can be extended into key signatures with double sharp signs, but it is highly impractical.  Similarly, the key signature of seven sharps is very rare because it is more convenient to use the enharmonically equivalent key signature of five flats.)
Comment: For those as baffled as I was by the preceding comment: [The origin of "Battle Ends And Down Goes Charles' Father"](https://music.stackexchange.com/q/9858/2257)
Comment: Father Charles goes down and ends battle. :-)
Answer: This is about the diatonic gamut of diatonic pitches A B C D E F G, key signatures, and organizing those by perfect fifths.
It can be a bit tricky to explain... and understand for a beginner. Personally, I think it is easiest to understand visually.
You can take the gamut of diatonic pitches...
A B C D E F G
...and re-arrange them by ascending perfect fifths...
F C G D A E B
...despite that series starting on F it is the group of pitches for the key of C major and a key signature of zero sharps or flats.
In order to continue that series of ascending perfect fifths you need to repeat the letter series and use a sharp...
F C G D A E B F#
...if we take just the last seven pitches, we get...
C G D A E B F#
...which are the pitches for a key signature of one sharp and those for G major.
You can keep going up by perfect fifths moving through all the key signatures with sharps. It's easier to then show it as a kind of grid...

F C G D A E B          - zero sharps/flats, C major
  C G D A E B F#       - one sharp, G major
    G D A E B F# C#    - two sharps, D major
      D A E B F# C# G# - three sharps, A major
      ...etc, etc.

Notice that when the sharps are introduced you repeat the original letter series starting with F. If you continue to seven sharps, C sharp major, you have the original series, but with sharps on all the letters!
F# C# G# D# A# E# B#
You can also go in the descending direction to introduce flats...

      F C G D A E B
   Bb F C G D A E
Eb Bb F C G D A
...etc, etc.

You may need to take some time to review all of this. Studying it at a keyboard may help. But eventually you should see the connections. The principle ideas are...

each diatonic key signature can be arranged as a series of pitches by ascending or descending perfect fifths
sharps or flats are added to the repeated series of seven letters to maintain ascending or descending perfect fifths
sharps or flats are introduced at the point of the tritone between B F ascending or F B descending
the number of sharps/flats and their corresponding letters added to the series by fifths give the letters and numbers for sharps/flats in a key signature
Comment: I admit my answer is long, because I show it as a step by step procedure, but the concept isn't really that complicated, it just shows pitch letters by perfect fifth, and how sharp/flats are needed to continue the series by perfect fifths.
Comment: The sharps/flats are needed to retain the TTSTTTS arrangements of notes belonging to keys, rather than following the circle of fifths, which makes things the opposite way round, in my opinion.
Comment: It isn't the "opposite" way. It's just another way.
Comment: This seems to me an over-complicated way to solve the question, especially for whom appears to be a beginner.
Comment: What I meant was the pattern of notes came way before the circle of 5ths was adopted, for a better word. Therefore the TTSTTTS pattern was the former, not the other way round.
Comment: I said nothing about the circle of fifths. I'm describing a linear series of perfect fifths. It only becomes a circle (or spiral) when you bring in enharmonic equivalents.
Comment: In terms of which came first, I think an argument could be made that P5 could be the primary generator of the diatonic gamut. If you consider the first _five_ pitch in a P5 series make a pentatonic scale, and many feel the pentatonic scale is primitive, pre-dating diatonic scales, the continuation of the series by two steps to get a diatonic scale, kind of mirrors history. That's speculation, but I think it's interesting. P5 is interesting as a primitive and fundamental interval.
Comment: In my procedure only one interval is needed, P5, to generate the diatonic gamut. As a scale, two intervals are needed, M2 and m2. I think the P5 perspective is an elegant way to look at it.
Answer: Sharps (and flats) are additive- as in, they are represented in a specific order, and that order cannot be changed. As in, they have a particular order they're applied to keys in music.
In key C, there are no sharps or flats. Going to the key with just one sharp, key G, the sharpened note is F, which is the leading note. That maintains the spacing between all the notes in the scale used, TTSTTTS.
Moving on to a key with two sharps, it's key D. Retaining the 1st sharp, it gains the 2nd in its leading note, C♯. Then on to the key with 3 sharps - A. Its leading note is G♯, and it retains the other two. And so on.
All this is reflected in the circle of fifths - well worth looking up and digesting. The same applies to flats, with key F having B♭ as its altered note, again to retain the TTSTTTS pattern of the major scale. Then comes the key B♭, with the aforementioned B♭ itself (obviously!) and E changed to E♭. And so on.
The one sign at the beginning of a piece will refer to all octaves of that changed note - otherwise the key signature would get too busy and blocked up - it's simply a convention that makes sense, and musos all understand and adhere to it. I hope! And, of course, the piece would sound out of tune with some altered and some not.
Comment: "Sharps (and flats) are additive." – please rephrase that, I've seen many people confused by that.
Comment: @user1079505 - I thought it was explained in the very next sentence. A dv could have been awarded after a couple of days inaction. However...
Answer: The row of sharps has to do with the development of the circle of fifths. Why  do we have different keys for the doremi scale? Because you can build a major scale starting from any of the 12 black or white keys. Traditionally the major scale of C needs no sharps has it is built exactly w-w-h-w-w-w-h (whole steps/ half steps).
C D EF
G A BC
1 2 34
5 6 78.
We've got an octave built by 2 equal tetrachords. As we can see the half tone steps are between EF and BC.
To build the major G scale (a 5th from C) we take the 2nd tetrachord of the C major scale (g a bc) and say this the first tetrachord of G. the second tetrachord would be d ef g.
As you see the halftone step is between 6 and 7 ...
Now to get the leading tone (halftone 7-8) we have to sharpen F a halfton up: F# G.
If you continue this operation (upper tetrachord of a scale becomes the lower tetrachord, sharpen the 7th, you can develop yourself the circle of 5ths.
Always keep the sharps you have developed before.
Answer: Short Answer
The short answer is that, as many other people have answered, the first sharp in a key signature is always F#, the second one is always C#, and so on in the order listed in the paragraph. That's just the way music works - or rather, it's a natural consequence of the way the Western music tradition has decided what our notes are and what a key signature is for.
Reason
The reason for this, for someone newer to music theory, can be explained in a couple different ways. I'll use the major scale as an example. There are a bunch of different scales - as you study music theory further you may read about the Aeolian or Ionian or Mixolydian modes, and then there are more modern scales like the Harmonic Minor scale - but the major scale is the common one everyone starts out with.
What is a scale?
A scale is a pattern of intervals. For the major scale, that pattern is whole step, whole step, half step, whole step, whole step, whole step, half step - 2 wholes, 1 half, 3 wholes, 1 half, and it's done (but of course you can start again from the beginning if you want to play multiple octaves of the scale). For the other scales, the pattern is different, but each scale has a defined pattern.
Also, it will be helpful to know that there is a half step between B and C, and a half step between E and F, and all the other notes have a whole step between them. I can't explain why; I pretend someone woke up one morning and decided to put the half steps there just to mess with future music theory students. And, a sharp note is a half step up from the named note, so F and F# are a half step away from each other, and E and F# are a whole step away from each other (half step from E to F, then another half step from F to F#).
A scale can start on any note. For example, the C major scale starts on C, then goes up by a whole step to D, a whole step to E, a half step to F, and so on according to the major scale pattern. As it turns out, the C major scale has no accidentals in it; the notes are C-D-E-F-G-A-B-C.
What if you tried starting the major scale on a different note?
Now, say you wanted to start a major scale on D instead of C. You'd start with D, then go up a whole step to E, then you'd have to put in an F# to get the next whole step, then up a half step to G, then a whole step to A, a whole step to B, another whole step to C#, and the final half step to D (D-E-F#-G-A-B-C#-D). So, by starting on D, you had to put in two accidentals to make the major scale pattern work, and those accidentals were on F# and C#. Or, if you wanted to start a major scale on B, for example, you'd have to play the scale B-C#-D#-E-F#-G#-A#-B, which is a horrible number of accidentals but it's what you need to make the pattern work.
What if you only wanted to have one sharp?
Or, to look at it another way, let's say you instead wanted to play a major scale with only one sharp in it, and you didn't care which note you started the scale on. Where would you put the sharp? As it turns out, you will have to put the sharp on F#, and you will have to start the scale on G.
Say you instead tried to put the sharp on A#, for example. Then, your scale would have to have G-A# in it somewhere, which is one and a half steps all on its own, and there are no intervals in the major scale pattern that are one and a half steps! So A# is out, and in fact if you put the sharp on B, D, E, or G, you'd have the same problem. The interval ending in those notes is already a whole step, and you'd be making it even larger.
Only C# and F# are possible, because only B-C and E-F are half steps and the sharp on the upper note would widen those intervals to a whole step. But, if you tried to put in a C# as your only sharp, then you'd have the pattern C#-D-E-F in your scale, which is a half step, then a whole step, then another half step. The major scale pattern doesn't have a single whole step with a half step on either side, so C#-D-E-F isn't part of any major scale and you can't put the only sharp on C# either.
If you put the only sharp on F#, it does work out, as long as you carefully pick which note you start on. You can't still start on C, because now your pattern would be 3 whole steps, 1 half, 2 wholes, 1 half, and that's close to the major scale pattern but it's still wrong. However, if you start on G, you do get the major scale pattern, G-A-B-C-D-E-F#-G!
You can do a similar exercise with more sharps, or with flats instead of sharps, or even with both flats and sharps! You'll still find that however many flats and/or sharps you have, you'll only end up with one arrangement of those flats/sharps that lets you play a major scale at all, and you'll have to start that major scale on exactly the right note each time. (If you do try with flats and sharps both, you'll have to cancel them out because they will end up on the same notes - C#b is the same as C, so you can cancel them, and I promise you won't find a working scale that has sharps on some notes and flats on other notes.)
Purpose of a key signature
I'm including this because I remember when I was starting music lessons, I once wondered "if the composer wants you to play only C# in a song but no other sharps, then why don't they just put a C# in the key signature?" But, by convention, nobody does that. There is probably a music theory justification - maybe the theoreticians think a song won't sound good like that? But I think one big part of the reason is that it's just easier to play music if you don't always have to look back at the key signature and pick out exactly which notes are marked. If I glance to the beginning of the line and I see 3 sharps, in their distinctive triangle shape, then I just know that I should play F#, C#, and G# but not any other sharps. This might not be a satisfying answer, but it's just the way everyone's used to by now.
Answer: Frankly this is an overcomplicated way of saying:

look, the first key with a sharp will have an F#, the second will have F# and C#, the third F#, C# and G# etc etc, based on the circle of fifths

In other words, the 4th key signature will include all the sharps from the 3rd, plus one extra; it will not contain an arbitrary selection of 4 sharps.
Of course, this is just for the keys that are typically used, there's nothing preventing you from creating a key with C# and D# (but it will probably not sound very "traditional").


Can't test Windows.Services.Store namespace

Question: I've followed the instructions but can't get this guide to work https://learn.microsoft.com/en-us/windows/uwp/monetize/in-app-purchases-and-trials#testing.
When I try StoreContext::GetAssociatedStoreProductsAsync and StoreContext::GetStoreProductForCurrentAppAsync I get the error code 0x803F6107 just like this question I'm unable to get a proper StoreContext.

If you do not associate your project with an app in the Store, the StoreContext methods set the ExtendedError property of their return values to the error code value 0x803F6107. This value indicates that the Store doesn't have any knowledge about the app.

When I try to debug my project (as per step 5 of the guide) I get this error message:
DEP0700: Registration of the app failed. [0x80073CF3] Windows cannot install package 66MyApp.MyApp_220.127.116.11_x86__2zbdsnss4mwk0 because a different package 66MyApp.MyApp_126.96.36.199_neutral_~yqhzh56ke71nw with the same name is already installed. Remove package 66MyApp.MyApp_188.8.131.52_neutral~_yqhzh56ke71nw before installing.
Must the package deployed from visual studio be the same as that downloaded from the store for this to work?
Answer: I uploaded a different app and it worked, with the same error message as before. So I'll just have to keep trying things.
I tried to associate my original app with the store identity of the second, and still got 0x803F6107. Then I associated the second app with the store identity of original and succeeded (a third app also successfully associates with both). So it must be a problem with the configuration of the original (maybe it's because I originally created it under a visual studio different account).
Okay so I think I have identified a marker of the problem. The package names of the original always end in __2zbdsnss4mwk0, but all the packages of my new account end in __yqhzh56ke71nw.
Finally, I got I working by creating a new visual studio project and copying my files accross. If the association works then the package ends in __yqhzh56ke71nw (same as that generated from the msixupload file I uploaded to the store), but without associating my packages end in __2zbdsnss4mwk0.


Summation of L1-function values finite

Question: For $f \in L^1(\mathbb{R})$, we can proof, that $\sum_{n\in \mathbb{Z}} |f(t+na)|<\infty$ ALMOST EVERYWHERE for $t\in [0,a]$
($\star$ proof below)
My Question: If we assume $f\in L^1(\mathbb{R})\cap C(\mathbb{R})$, can we conclude
$$\sum_{n\in \mathbb{Z}} |f(t+na)|<\infty \text{ for all }t\in [0,a]\ \ \ ?$$
I would especially need to show: $\sum_{n\in \mathbb{Z}} |f(na)|<\infty$

$\star$ proof:
Define $f_n=\chi_{(na,(n+1)a]}\cdot f \Rightarrow\ \sum_{n\in \mathbb{Z}}|f_n|=|f|\ \ \forall x\in \mathbb{R}$
If we use monotone convergence and shifting invariance of the Lebesgue integral we get:
$$\infty>\int_\mathbb{R} |f(t)|dt=\int_\mathbb{R}\sum_{n\in \mathbb{Z}}|f_n(t)|dt = \sum_{n\in \mathbb{Z}}\int_\mathbb{R}|f_n(t)|dt=\sum_{n\in \mathbb{Z}}\int_{(na,(n+1)a]}|f(t)|dt=$$
$$=\sum_{n\in \mathbb{Z}}\int_0^a|f(t+na)|dt=\int_0^a\sum_{n\in \mathbb{Z}}|f(t+na)|dt$$
So we can conclude: $\sum_{n\in \mathbb{Z}}|f(t+na)|<\infty$ a.e. for $t\in[0,a]$
Comment: I'm curious for the assertion in the first line. Could you show me a proof?
Comment: I just added the proof
Answer: No this is not true, it would still be for allmost all $a$. As a counter example consider $a=1$ and $f$ given such that $f(n)=1$ but $\int_{n-1/2}^{n+1/2}f(x)dx = \frac{1}{n^2}$.
If you need me to elaborate a bit more leave a comment.
Comment: I see, thank you very much. So even for $f\in L^1 \cap C^\infty$ we could construct such a counterexample...
Comment: Exactly and even easily
Comment: Maybe I have to say something more to my problem. Actually I am looking at bandlimited $f\in L^1$, i.e. $supp(\hat{f})\in [-\lambda,\lambda]$. Therefore Parley-Wiener tells us, that $f\in C^\infty$ and also of exponential type: $f(\xi)<Ce^{2\pi \lambda|\xi|}$ .

But nevertheless I think  your counterexample will apply.

Summation of L1-function values finite


Pattern for updating Objects/Documents with Spring-Data MongoDB and Spring MVC

Question: I'm trying to come up with a reusable pattern for updating MongoDB Documents when using Spring Data in conjunction with Spring MVC.
The use case can generally be summarized by:

A document is created in Mongo using repository.save()
Parts of that document are then presented in a Spring MVC editable form.
A user submits updated parts of that document which are then saved.

If I use the repository.save() method in step 3, I will lose any data in the document that was not bound to the form.  Making the form responsible for the entire document is fragile so this is where it seems the findAndModify() method of the MongoTemplate comes in handy.
To use the findAndModify() method, I've created Form objects that support a toMap() method which takes the Form object's properties as a Map and removes some of the fields (e.g. class and id).  This gets me a Map that contains only the fields that I care about from the Form object.  Passing the object ID and this map to an update() method on my customized repository, I build Query and Update objects that I can pass to the findAndModify() method.
Using this approach, I'm able to add fields to my objects easily and only worry about instances when there are fields I don't want to update from a form posting.  Document fields not manipulated by the Form should be retained.  It still seems slightly convoluted to be using both the Repository and MongoTemplate so I'm wondering if there are better examples for how to handle this.  It seems like this should be a consistent pattern when working with Mongo and Spring MVC (at the least).
I've created a sample project showing how I achieve this model on GitHub.  The Spock Tests show how "updating" a Document using save() will blow away fields as expected and my update() method.
https://github.com/watchwithmike/diner-data
What are other people doing when dealing with partial updates to Documents using Spring MVC and Spring Data?
Answer: If you are taking whatever the user supplies and just shoving that in the database you are running the risk of doing something dangerous like updating or creating data that they shouldn't be able to. Instead, you should first query Mongo to get the most recent version of the document, change any fields (it looks like you are using Groovy so you could loop through all the properties and set them on the new document), and then save the new, complete document.
If you are making small, consistent updates (like increasing the number of votes, or something like that), you could create a custom MongoDB query using the MongoTemplate to do an update to a few fields. Check out the spring-data-mongodb docs for more. You can also add custom methods to the MongoRepository that use the MongoTemplate.
Comment: The idea is to not take everything the user supplies and shove it into the database.  The only thing the user may supply are the data fields in the form.  For my simple example I had my Form extend my model object but that's not necessary.  I can also exclude "user supplied" fields in my toMap() method. The update() method I created in my custom repository does use the MongoTemplate to query and update but coming from JPA/Hibernate this seems like a bit more code than I expected and I'm wondering if there's a better way or if this is just a side effect of having greater flexibility with Mongo.
Comment: @VishwasShashidhar I ended up using the patterns you can find in the [JHipster](https://jhipster.github.io/) application which you can configure to use MongoDB. The [Creating an entity page)[https://jhipster.github.io/creating_an_entity.html] provides an overview of what the project does on the entity side, you'll just want to make sure you configure it to use MongoDB instead of JPA.  I just used JHipster as a reference rather than start my whole project from it. Hope that helps.
Comment: @watchwithmike were you able to solve this problem by any chance?


What kinds of optimization are used in PyTorch methods?

Question: I'm using PyTorch to implement an intense sequence of matrix operations, using methods such as torch.mm or torch.dot. I was wondering if PyTorch uses multithreading or other optimization mechanisms to speed up the process. I am not utilizing a GPU. I appreciate if you could inform me of how fast these methods are and whether I need to take any actions to help the process.
Answer: PyTorch uses an efficient BLAS implementation and multithreading (openMP, if I'm not wrong) to parallelize such operations with multiple cores. Some performance loss comes from the Python itself - since this is an interpreted language, no significant compiler-like optimization can be done. You can use the jit module to speed up the "wrapper" code around the matrix multiplies, but for anything more than very small matrices this cost is probably negligible.
One big improvement you may be able to get manually, but which PyTorch doesn't apply automatically, is to properly order the matrix multiplies. As you probably know, depending on matrix shapes, a multiplication ABCD may have different performance computed as A(B(CD)) than if computed as (AB)(CD), etc.


If Cell contains specific text in col A copy cell from Col C into Col F stacked

Question: I am working on code where if in Column "A"="test" then to copy cell from Col C into Col F but without spaces .
Can someone please help?
Sub FindValuePaste()

    Dim FndRng As Range
    Dim cll As Range

    Set FndRng = Range("A3:A9")

    For Each cll In FndRng
        If cll.Value = "test" Then
           ' cll.Offset(0, 5) = cll.Offset(0, 2).Value
            Range("F1").Offset(1) = cll.Offset(0, 2).Value
        End If
    Next cll

End sub

Appreciate your help and thank you in advance!
Answer: Copy Matching Row From Another Column

A Quick Fix
Sub FindValuePaste()

    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    Dim srg As Range: Set srg = ws.Range("A3:A9")
    Dim dcell As Range: Set dcell = ws.Range("F3")

    Dim scell As Range

    For Each scell In srg.Cells
        If StrComp(CStr(scell.Value), "test", vbTextCompare) = 0 Then
            dcell.Value = scell.Offset(, 2).Value
            Set dcell = dcell.Offset(1)
        End If
    Next scell

End Sub

Answer:
Use .End(xlUp).Row to locate the last row

Sub FindValuePaste()
    Dim FndRng As Range
    Dim cll As Range
    Dim lastRow as Long, oSht as Worksheet
    Set oSht = ActiveSheet ' modify as needed
    lastRow = oSht.Cells(oSht.Rows.Count, "F").End(xlUp).Row
    If len(oSht.Range("F" & lastRow)) > 0 Then  lastRow = lastRow + 1
    Set FndRng = oSht.Range("A3:A9")

    For Each cll In FndRng
        If cll.Value = "test" Then
           ' cll.Offset(0, 5) = cll.Offset(0, 2).Value
            oSht.Range("F" & lastRow).Value = cll.Offset(0, 2).Value
            lastRow = lastRow + 1
        End If
    Next cll
End sub

Use CountA to get the count of non-blank cells (The data should be start from F1 on Col F)

Sub FindValuePaste2()

    Dim FndRng As Range
    Dim cll As Range
    Dim lastRow As Long, oSht As Worksheet
    Set oSht = ActiveSheet ' modify as needed
    lastRow = Application.CountA(oSht.Columns("F")) + 1
    Set FndRng = oSht.Range("A3:A9")
    For Each cll In FndRng
        If cll.Value = "test" Then
           ' cll.Offset(0, 5) = cll.Offset(0, 2).Value
            oSht.Range("F" & lastRow) = cll.Offset(0, 2).Value
            lastRow = lastRow + 1
        End If
    Next cll

End Sub

Answer: What about a formula in cell F3:
=SUBSTITUTE(INDEX(FILTER(A3:C9,A3:A9="test"),0,3)," ","")

Where the FILTER function filters the table A3:C9 to only rows with 'test'
Where the INDEX function picks column number 3 from that filtered range
Where SUBSTITUTE replaces the spaces (although I did not see the necessity in the example sheet)


How can a user select a different language to the site default language?

Question: My Drupal 6 site should always display in French for all users except me. I need to administer the site in English.
Using the Locale module I have both languages installed and default set to French. In the language negotiation settings ('Configure'), I have selected 'none'. The help text says that "users may (optionally) select a preferred language on the My Account page".
Even though I have selected English in my account settings (under "Language settings"), everything remains in French when I login?
Answer: Have you tried using the Administration Language module?

This module lets the administrator see all administration pages in her preferred language.
You can use this to display the frontend of the site in one language and still keep most of the backend in English (or another language of your choice).
Answer: It doesn't seem to work like that; see Drupal: changing language settings in user edit not working.

If you had the Language negotiation set to None, because -- like me -- you thought that would allow users to change their language preferences, you were wrong. The problem is this help text on the Languages page is completely misleading:

None. The default language is used for site presentation, though users may (optionally) select a preferred language on the My Account page. (User language preferences will be used for site e-mails, if available.)

It should read:

None. The default language is used for site presentation, though users may (optionally) select a preferred language — for site e-mails, if available — on the My Account page.


How to make Redirect Extension

Question: I am creating website which will redirect to the user/login before to see the content since I am using Anonymous Redirect module.
Also, I'm using the Commerce module, so with that, I have one problem. When I want to checkout anonymously, it redirects me to the login page. How can I extend this checkout process to add product before login?
Example: When I add "example.com/product/someproduct" it's redirecting me to the login page without checkout button, cant see the products.
Thank you for your time.
Answer: Note that since you are requiring that anonymous traffic not see content, then product pages would be protected as well, making anonymous checkout impossible without some monkeying. You would likely need to bypass the anonymous redirect on product pages OR create a url that passes a product id to the anonymous user's cart (it would create one if it doesn't exist) and then redirects to the checkout. This would be possible with a rule running on bootstrap, but does have performance implications.
https://www.youtube.com/watch?v=6Rn7FLFytTU is the video where I walk you through this using rules.
Answer: Use Checkout login step module to provide option for without login.
Comment: the problem is, then i add "example.com/product/someproduct" it redirecting me to the login page without checkout button, cant see the products
Comment: you mean when you go to `example.com/product/someproduct` it redirects you to the login, so you can't see the product page until you login?
Answer: I have changed the module to Required Login and repair my problems, thank you.

How to make Redirect Extension


How to disable payment cart pane when discount brings total to $0

Question: I am using the uc_discounts_alt module on a Drupal 6 / Ubercart 2 site to provide specific dollar amount discounts for specific products. The discounts bring the product price down to zero, and conditional actions check for that discount code and, if found, make the shipping cost $0 as well.
I enabled the Ubercart Free Payments Module to allow these free orders to check out, but the cart states that the credit card info is missing when I to proceed to the order confirmation page. Apparently the Free Payments Module is not working as expected.
Is there any way I can hide or otherwise disable the payment panel when a certain discount is being applied... or any other options that may give me the functionality I need? Unfortunately, I am in a bit of a time crunch as we have a big promotion starting tomorrow, and this issue was masked by another payment method.
Thanks!
Answer: I was able to fix the problem by modifying the "Free Order" payment method's Conditional Action. Free Order is the payment method associated with the Ubercart Free Payments Module and comes pre-loaded with a CA that checks the cart total to see if it is more than $0.01... if it is more than that, it negates that condition and does not allow the Free Order payment method in the cart.
I changed that CA to instead check whether the cart had the discount(s) in question. If the discount(s) was used, the cart pulls in the Free Order payment method, and it all works as expected.


how to do autocomplete search in  element

Question: i need jquery or javascript to do autocomplete drop-down list with the results of my search typing.. i need the result as link "" so i can open it in new tab or open it directly by click on it.
here is my code:
<input type="text" id="searchinput" class="search-input" placeholder="ابحث هنـــا.." />

 الملاك و الوحدات

 إدارة بيانات الوحدات

 محتويات وحدة

نظام الفندقة والإيجارات

الوحدات المؤجرة

تأجير وحدة

 المستأجرين

 التعاقدات

Answer: i found the solution with some help here below..

$(function () {
                            var menuPages = $('#main-menu li a:has(.childtitle)').map(function () {
                                return {
                                    label: $(this).text(),
                                    value: $(this).attr('href')
                                };
                            }).toArray();
                            $("#txt_MenuSearch").autocomplete({
                                source: menuPages,
                                select: function (event, target) {
                                    /* On select, show item's label in text input */
                                    event.preventDefault();
                                    $("#txt_MenuSearch").val(target.item.label);
                                    var link = target.item.value;
                                    window.open(link);
                                },
                            });
                            /* Highlight text */
                            $("#txt_MenuSearch").data("ui-autocomplete")._renderItem = function (ul, item) {
                                var newText = String(item.label).replace(
                                    new RegExp(this.term, "gi"),
                                    "$&");

                                /* Wrapping the matching option within  tags */
                                newText = '' + newText + '';

                                return $("
")
                                .attr("data-value", item.value)
                                .append(newText)
                                .appendTo(ul);
                            };
                        });
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

<input type="text" id="txt_MenuSearch" class="search-input" placeholder="ابحث هنـــا.." />

 الملاك و الوحدات

 إدارة بيانات الوحدات

 محتويات وحدة

نظام الفندقة والإيجارات

الوحدات المؤجرة

تأجير وحدة

 المستأجرين

 التعاقدات


Averaging rankings of small geographical areas to find an average ranking for a larger area

Question: I have a friend who is very intelligent with a professional background in accountancy but no formal mathematical or scientific training. He is studying for a PhD (as a mature student) looking at how the philosophy of accounting affects big science projects
We have been talking about statistics. As a personal piece of work, he has been using a database of national indices of mass deprivation to show how different areas are getting more or less deprived over time. He has been grouping smaller areas together to create bigger areas. All fine so far. However, he has been averaging the rankings of the smaller areas to get an average ranking for the larger area and then comparing how the larger area's ranking varies over time
This just seems wrong to me - the ranking has no direct link to a measurable value, and averaging ranks "works arithmetically", but to me doesn't seem to provide a meaningful stat. It seems obvious (dread word!) that you need to work out the values of deprivation for the larger areas and then rank them all again (as long as all larger areas are approximately equivalent)
As I said, he is very intelligent and an excellent debater. His view is that statistics is only a representation of the truth, and as such he is able to select how to represent this truth
Who is right? If I'm right, what arguments could I use to help him understand?
Comment: Your prior title was very broad and didn't say much about the specific issue at hand. I've tried to improve it, but feel free to change it further to more closely reflect what you want to express.
Comment: I'm inclined to agree. I'm not a statistician either, and you will always lose information when using summary statistics measures such as the mean, but I would be much more inclined to value the measure of the larger areas if it were the mean of an actual measure.
Comment: I agree your actual quetion is how to do the averaging instead of simple mean. If you can show up a useful alternative it will be easier to explain why it's better.
Answer: This is one of those areas with few, clearcut right or wrong answers, but some ways are clearly better than others.
All rankings are fraught with many, many pitfalls as this article by Malcolm Gladwell about them makes clear. Your friend's problems begin with his assumption that the different indices of "mass deprivation" can be summarized into a single number. Among the problems Gladwell enumerates are:
1) Omitted variables bias, it can be really hard to identify the right set of measures for ranking. If there are key constructs that define a construct that are left out of an analysis, then any resulting ranking will be compromised
2) The subjective nature of the weightings employed
3) The quality of the input information is often suspect
4) The nearly infinite ways to develop the rankings
5) The loss of complex information in generating an ordinal ranking
http://www.newyorker.com/magazine/2011/02/14/the-order-of-things
Simplistic and easily derived methods like your friend's will pass muster among the technically illiterate and naive but are guaranteed to flame out if anyone with any statistical insight takes a look under the hood -- like a PhD dissertation committee. In other words, there is a serious element of risk in what he's proposing.
At the end of the day, there is no substitute for analytic rigor and stubbornness is no answer for ignorance.
Answer: The best illustration for why something problematic might be going on when averaging rankings is probably an example of the following ranking of areas (as an example I will use average income and assume that income per head is a relevant number):

Large area 1, small geographical sub-area A: population 100, average income 100,000 USD
Large area 2, small geographical sub-area C: population 10000, average income 10,001 USD
Large area 2, small geographical sub-area D: population 10000, average income 10,000 USD
Large area 1, small geographical sub-area B: population 9900, average income 1,000 USD

The average rank for both large areas is 2.5, but the average income per head is much higher in large area 2.
You can probably also construct all sorts of examples with small differences such as {10,001,10,002,10,003 USD} vs. {9,997, 9,998, 9,999 USD} causing major changes in raking and obscuring massive differences in some sub-areas (e.g. if you add another sub-area with average income 100,000 USD to the second group, it still has the lower average rank). A classic example of ranking can be abused is gerrymandering.
Better approaches might include: calculating the metric of interest on a larger area level (if possible based on the available data), using hierarchical models etc.
Answer: Disclaimer: I'm not a statistician, but I'm going to provide a completely contrived example of why what he is doing might have issues:
Consider the following measures of deprivation for six small areas (lower is more deprived, so worse).
1, 2, 100, 3, 4, 5

It's clear the ranking is:
6, 5,   1, 4, 3, 2

(1 is best).
We are going to group the first three areas in one "super area" and the latter three in another area.
The average ranking for the first "super area" is (6+5+1)/3 = 4. The average ranking for the second area is (4+3+2)/3 = 3. So by his metric, the second area has a better "score" than the first. However, it's clear that this isn't the case: it's not hard to see that the average measure for the first area is (100+2+1)/3 = 34.333... and the average measure for the second area is (3+4+5)/3 = 4, and higher is better. So in fact, his "ranking" is misleading.
This is because rankings abstract the original measure away, so there is no way of knowing just how different the underlying measures are.
Of course, this example is completely contrived, but like Ansombe's Quartet I hope it highlights the issues that could arise when using such an statistic.
Does your friend have access to the underlying statistics?
Finally, aggregating areas is hard, as gerrymandering shows how easily it can be abused. How is he deciding to do it?
Edit: I suppose that is an example of point 5. of DJohnson's answer.


Eclipse RCP 4: Adding a Popup Menu to an MPart

Question: I am trying to add a Popup menu for an MPart when it is right clicked, but I am having difficulty doing so. It should function the same way it did in Eclipse 3.x (Right click near the title of the view and the popup menu to detach the view/move it appears). I have added a Popup Menu with a Handled Menu Item. I assumed this would be all that is required to allow the popup menu to appear on right click, but nothing happens when I do.
I did follow Lars Vogel's tutorials, but his tutorial only shows how to add a JFace viewer to a part, and then adding the popup menu to that viewer. What is the proper way to add a popup menu when you right click on an MPart?

Thanks for any help you may be able to provide! :)
EDIT: Example of what I want
Answer: As well as declaring the Popup Menu in the Application.e4xmi (or fragment) you must also use the EMenuService in the code to register the menu with the control that you are going to right click on.
@Inject
EMenuService menuService;

menuService.registerContextMenu(control, "menu id");

Changing the menu shown when right clicking on the tab for a part is much more complex. To do this you must define a custom renderer for the MPartStack using a custom renderer factory (see here for basic details).
Your renderer can extend the standard StackRenderer class and override the populateTabMenu method.
This is an example method I use which reduces the menu to just show 'Close':
@Override
protected void populateTabMenu(final Menu menu, final MPart part)
{
  if (!isClosable(part))
    return;

  // Just add Close menu item and handle enabling it correctly

  final MenuItem menuItemClose = new MenuItem(menu, SWT.NONE);

  menuItemClose.setText(SWTRenderersMessages.menuClose);

  menuItemClose.addListener(SWT.Selection, this::closeSelected);

  menu.removeListener(SWT.Show, _menuListener);
  menu.addListener(SWT.Show, _menuListener);
}

Comment: Hi Greg, I did this in Lars Vogel's tutorial but I got the control of a JFace viewer that I created inside the MPart and used that. I am trying to set the popup menu for when you right click on the MPart itself. Is there a way to get the control for the MPart, or another way to add the popup menu to the MPart itself?
Comment: What do you mean by 'click on the MPart'? The body of the MPart is just your controls, or are you asking about something like the toolbar or the tab?
Comment: Yes, I mean when you right click near the actual title of the MPart, the tab for the MPart. For example, in the Eclipse IDE, when you right click on the Call Hierarchy tab it displays several options. I want to be able to right click on my MPart in the same way and display the Popup Menu. (Added an example image in my question)
Comment: Perfect! Is this the only way to add custom Menu Items in the renderer (through creation of Menu objects and listeners), or is there also a way to access the Popup Menu in my Application Model and set that as the menu in the renderer?
Comment: You might be able to find things using the EModelService. I just copied the way the existing code in StackRenderer worked.
Comment: Thanks Greg, I appreciate your help :)


Idiosyncratic volatility forecast using EGARCH (Fu, 2009)

Question: I have a time series of historical volatility observations. I want to use an EGARCH model because I believe it is a good representation of the behaviour of these volatilities.

Can I estimate an EGARCH model using the observed volatilities without using the underlying returns? I'm using R and I think in the input the program expects returns instead of volatilities.

To be more specific, I'm trying to follow the methodology described in a paper about idiosyncratic volatility. To estimate it, the author runs the following regression:
$$
\begin{aligned}
r_t − r^f_t &= \alpha_t + b_{1,t}(r^m_t−r^f_t) + b_{2,t}SMB_t + b_{3,t}HML_t + \varepsilon_t \ \ \ \ \ \ \ \text{(1)} \\
\varepsilon_t &∼ N(0,\sigma^2_t) \\
\ln(\sigma^2_t) &= \omega + \Sigma_{i=1}^p\beta_i \ln(\sigma^2_{t−i}) + \Sigma_{i=1}^qc_i \left[\theta(\varepsilon_{t−i}\sigma_{t−i}) + \gamma\left( ∣\varepsilon_{t−i}\sigma_{t−i}∣−\sqrt{2\pi}\right)\right]
\end{aligned}
$$
Idiosyncratic volatility is defined as the standard error of the residuals of the regression in equation (1).
I want to build an EGARCH to have a conditional idiosyncratic volatility. To do this,

I run the regression (1) and took the standard error of the residuals; this is the historical idiosyncratic volatility.
Then I supply these historical idiosyncratic volatilities as input to my program (I use R and the package "rugarch").

Does this procedure make sense, or should I do something else?
The problem is that in all the application that I view of EGARCH, the inputs are the returns; but in my case, if I give returns as input, then I would have an EGARCH for the normal volatility and not the idiosyncratic, which is the one in which I am interested.
Comment: I tried to make the formulas appear OK using $\LaTeX$ typesetting, but you would have to check very carefully whether they are correct.
Comment: Thanks you Richard, I was wondering if you offer private consulting service. I'm struggling with my code.
Comment: Sorry, I don't provide private consulting.
Comment: I was going through my old answers and noticed this one was not accepted. Do you perhaps need further clarification?
Answer: Let me give you an answer that is a bit more explicit and general than you directly need, but that could nevertheless be useful.

The true conditional variance $\sigma_t^2$ of a time series is unobservable, just as any other theoretical moment of the data generating process (DGP). $\sigma_t^2$ is a property of the DGP that we try to estimate.
GARCH models (including EGARCH) assume $\sigma_t^2$ follows a deterministic process where $\sigma_t^2$ is completely determined by the past values of itself ($\sigma_{t-1}^2,\dotsc$) and the past values of shocks ($\varepsilon_{t-1}^2,\dotsc$).
Shocks may or may not coincide with returns depending on the conditional mean specification for the model for returns.
An outcome of an estimated GARCH model will be a series of fitted conditional variances $\hat\sigma_t^2$.
If you have a series of realized volatilities $\tilde\sigma_t^2$, you should probably not treat them as perfect estimates of $\sigma_t^2$. Realized volatility is probably conditional variance measured with error, so $\tilde\sigma_t^2 \neq \sigma_t^2$.

Now getting to your questions:

Can I estimate an EGARCH model using the observed volatilities without using the underlying returns? I'm using R and I think in the input the program expects returns instead of volatilities.

and

Does this procedure make sense, or should I do something else?

You are right that the expected input is returns (if the conditional mean model is empty). Therefore, you would not substitute $\varepsilon_t$ or $\varepsilon_t^2$ with $\tilde\sigma_t^2$ directly. Instead, you would have to code the model estimation (an optimization problem) yourself.
If you assume the true DGP is EGARCH and treat realized cond. variances $\tilde\sigma_t^2$ as estimates of the true cond. variances $\sigma_t^2$, then you could specify the optimization problem corresponding to an EGARCH model that uses $\tilde\sigma_t^2$ in place of $\varepsilon_{t-1}$ as inputs. That would be something like errors-in-variables models where the regressand and the regressors (lagged realized cond. variances) would be measured with error.


Problema com posição e tamanho de componentes

Question: Estou fazendo um programa usando o assistente, o famoso "clica e arrasta". Boa parte do projeto estou fazendo no meu computador, e uso o comando pra maximizar a tela no frame, e ajeito certinho os painels pra que tudo encaixe, mas quando continuo o projeto no computador do meu serviço por exemplo, o tamanho muda completamente e fica cortando como se não coubesse na tela.

Queria saber se tem alguma forma de padronizar isso, independente do computador, faça com que a tela abra em tela cheia e se encaixe conforme o desktop.
Comment: qual a IDE está usando pra montar as telas?
Comment: NetBeans IDE v8.2
Comment: Sim tem como padronizar,  forneça um **[mcve]**  para que seja possivel te ajudar.
Answer: Se quer definir os tamanhos de forma relativa, de forma que as posições sejam respeitadas independente da tela, você precisa utilizar os gerenciadores de layouts. Eles servem como organizadores de componentes na tela ou dentro de outros componentes na propria tela. Com isso, você sempre terá a mesma organização independente da resolução da tela do usuário que está executando a aplicação.
Quanto a manter o tamanho do JFrame relativo ao tamanho da tela do usuário, nesta resposta há uma solução que pode funcionar.
Como você não apresentou um exemplo Mínimo, Completo e Verificável, não dá para sugerir nada de específico para a tela apresentada, mas a solução com certeza é o uso de um ou mais gerenciadores.
Apenas para demonstrar o poder dos gerenciadores de layout, juntamente com a dica da resposta linkada, veja o exemplo abaixo onde fiz uma tela com proporçoes relativas a metade da minha tela, e mesmo redimensionando, os componentes náo se desorganizam, apenas a tabela se adapta graças ao JScrollPane.:

O assistente do netbeans pode parecer tentador, mas usá-lo sem conhecer a API swing e seu funcionamento vai te engessar nesta IDE e te prender a problemas como o que você enfrenta nesta pergunta. Sugiro que, antes de brincar de arrastar e soltar, aprenda o basico sobre swing e seus componentes, pois é essencial ter noção, de como criar telas e organizar componentes sem depender de IDEs, por mais que o construtor de telas do netbeans ou windowbuilder no eclipse facilitem bastante esse processo.
Answer: Faça uma janela com menos pixels que quando aumentar o próprio windows corrige. mas se a janela for muito grande ele não pode fazer isso pra não perder informação.
Você usou o clica e arrasta pras opções do seu computador, mas você precisa fazer um padrão menor para que caiba em todas as telas possíveis. tente setar seu monitor na hora de clicar e arrastar pra 1024x768 por exemplo. é uma resolução ruim mas caberá em qualquer  computador. Depois que você voltar ao tamanho normal  a tela vai ficar melhor.
Mas o certo é não utilizar o clica e arrasta mesmo haha
Comment: Não existem definições percentuais no modo drag and drop?


Find Mean of a geometric distribution using R

Question: I am currently struggling to find a way to calculate the mean of the geometric function (or any other function for that matter using R. So basically I want R to calculate for me
$\frac{1-p}{p}$
for the geometric distribution. I feel like it is extremely obvious and I just don't get it. I would very much appreciate if someone could point it out in this case.
Sample question: How often do you have to draw a card from a standard deck of cards until you win (by drawing the ace of spades). Where the mean would be
$\frac{1-\frac{1}{52}}{\frac{1}{52}}$ = 51
How do I get this result in R?
Comment: In your sample question the answer is $1/\frac1{52}=52$ because it concerns the number of all draws that are needed. Not only the draws resulting in no ace of spades.
Answer: If you know a formula for the expected value in terms of the parameters, R will happily accept the formula you type in. :)
If not, R provides the density functions and cdfs for most distributions you might want to use, and also has facilities (e.g., the package cubature) for numerical integration.  Using those together will solve your problem.  (For discrete distributions, rather than using cubature you probably just need good judgment as to how many terms of an otherwise infinite sum are enough.)
It also turns out that the package actuar provides moment-generating functions for a number of distributions.  That may be what you are looking for, if it handles the distributions you care about.  See https://cran.r-project.org/web/views/Distributions.html for a complete discussion of what is available in various packages.
Also, if the mgf is not available, easier than using cubature (though perhaps slower and less accurate) would be to generate several thousand random variates of whatever distribution you care about and taking their mean.  Most facilities in R that deal with distributions provide a function that generates random variates.  And even if random variates are not available, you just need the quantile function to use this method, since you can always generate uniform random numbers and apply the quantile function to each and then average.
Comment: Oh okay, I just assumed it could be solved in R (not by typing the formula myself) because most exercises are solvable like that.
Thanks I will look into cubature!
Comment: OK....also you may want to take a look at *actuar*.  Some things are easier than others.  The standard in R is to provide cdf, density, quantile (so median would have been easy),and random variates, but most packages won't give you mgfs,
Answer: If $\mu$ denotes the number of failures that preceed the first success then we have the equality:$$\mu=p\cdot0+(1-p)\cdot(1+\mu)=(1-p)(1+\mu)$$which lead easily to: $$\mu=\frac{1-p}{p}$$
If the first trial is a success already (probability on that is $p$) then we have $0$ failures. If the first trial is not a success (probability on that is $1-p$) then the process starts again, but we have $1$ failure in our pocket (explaining the factor $1+\mu$).
If $\nu$ denotes the number of trials needed to arrive at the first success then: $$\nu=1+\mu=1+\frac{1-p}{p}=\frac1p$$
Also $\nu$ can be found directly on base of equality:$$\nu=p\cdot1+(1-p)\cdot(1+\nu)$$


If $A^m=I$ then A is Diagonalizable

Question: Let $A$ be an $n\times n$ complex matrix. If $A^m=I_n$ for some positive integer $n$. How to show that $A$ is diagonalizable?
Answer: Hint
What we can say for the polynomial $x^m-1$?
Comment: @Danial A little more! You're in $\Bbb C$, not (algebraically) boring $\Bbb R$!
Comment: @Danial $A$ is diagonalizable iff the minimal polynomial splits into linear factors so with the given hypothesis of your question can we say that we have this condition?
Comment: @Peter Tamaroff:  Not to be contentious, but I think $\Bbb R$ is at least as interesting as $\Bbb C$.  That is to say, $\Bbb C$ is no more boring than $\Bbb R$.
Comment: @Danial so as not to tease you - what you should notice is that the polynomial has no multiple roots
Comment: @Danial notice, as $x^m - 1$ has no duplicate roots, it is irreducible, and $0 = A^m - I = (x^m - 1)[A]$ by requirement.
From this we have: 1. $\mu(x) = x^m - 1$ is irreducible, 2. $\mu(A) = 0$.
$$$$
Conclusion?
Comment: It's interesting to note that using this technique you can actually prove the somewhat stronger result: if $A$ is a complex matrix (or a matrix over any alg closed field with characteristic prime to the integer $m$ about to appear) such that $A^m$ is diagonalizable for some $m$, then $A$ is diagonalizable. This follows because $m_A(x)\mid m_{A^m}(x^m)$ and by assumption $m_{A^m}(x^m)$ is separable and splits in the field.
Comment: $x=\pm 1$.. I think i got it
Comment: @Danial What if $m$ is odd?
Comment: I am trying the following: $A=P^{-1}JP\Rightarrow A^m=P^{-1}J^mP=I_n\Rightarrow J^m=I_n$ but i don't see what can i do further.. I don't know how to use the hint above .. i feel i stupid
Comment: @Peter Tamaroff:  algebraically and/or otherwise! ;)
Comment: Yes thank you all .. I solved it :)
Comment: @RobertLewis Sure. The above was merely a joke to hint on what the OP was missing.
Comment: @Peter Tamaroff:  As was my remark, albeit directed toward the general readership, since I admit it didn't really address the question at hand.  Humor and math, great together or separately!

If $A^m=I$ then A is Diagonalizable


Prove $\lfloor \log_2(n) \rfloor + 1 = \lceil \log_2(n+1) \rceil $

Question: This is a question a lecturer gave me. I'm more than willing to come up with the answer. But I feel I'm missing something in logs.
I know the rules, $\log(ab) = \log(a) + \log(b)$ but that's all I have.
What should I read, look up to come up with the answer?
Comment: Didn't the lecturer mean $\lfloor lb(n) \rfloor + 1 = \lceil lb(n+1) \rceil$ ?
Comment: What is $lb(n)$?  Did you mean $\ln(n)$?
Comment: lb(n) is log to the base 2 of n
Comment: @DávidKaya, yes, he did.  How does that change things?
Comment: @Irwin $\lfloor$ $\rfloor$ - these round a real number down to the next integer and $\lceil$ $\rceil$ - round a real number up to the next integer. With these symbols your equation can be proved.
Answer: EDIT: This answer is for the original question, before it was changed by the OP by adding ceil and floor.
I suppose $\operatorname{lb}()$ is the binary logarithm. Then this equation is not a general identity, so you cannot "prove" it. However you can solve for $n$ so that it is true.
$\operatorname{lb}(n)+1 = \operatorname{lb}(n+1) \Rightarrow 2^{(\operatorname{lb}(n)+1)} = 2^{\operatorname{lb}(n+1)} \Rightarrow 2^{\operatorname{lb}(n)} \cdot 2^1 = 2^{\operatorname{lb}(n+1)}$
$\Rightarrow n \cdot 2 = n + 1$
So $n = 1$ is a possible answer. Plugging it into the initial equation shows it really solves it. It's also the only solution.
Comment: Answers, and questions, written without LaTeX look pretty ugly and sometimes are even almost impossible to understand. You can try the FAQ section where you'll get directions how to properly write mathematics in this site.
Comment: @Ricbit, The question was changed after I replied. I answered the question for lb(n)+1 = lb(n+1), no floor or ceil.
Comment: This is not true, take $n=5$ for example. $\lfloor\log_2 5\rfloor + 1 = 3$, and $\lceil\log_2 6\rceil=3$ also.
Answer: Well, even after your edit, this is not an identity in general. It is valid only for integral $n$. For a counter-example of why this is not valid for a positive $n$, take $n = 1.5$. Then,
$$\lfloor \log_2(n) \rfloor + 1 = \lfloor \log_2(1.5) \rfloor + 1 = 1$$
and
$$\lceil \log_2(n + 1) \rceil = \lceil \log_2(2.5) \rceil = 2$$
However, for $n \in \mathbb N$ and $n > 0$, this identity holds, and can be proven as follows:
Let $2^k \le n < 2^{k+1}$ for some $k \ge 0$ and $k$ is an integer.
Therefore, let $n = 2^k + m$, where $k \ge 0$ and $0 \le m < 2^{k}$, and $k, m$ are positive integers.
Then,
$$\lfloor \log_2(n) \rfloor + 1 = \lfloor \log_2(2^k + m) \rfloor + 1 = k + 1$$
Notice that $\log_2(2^k + m) = k$ when $m = 0$. Otherwise, $k < \log_2(2^k + m) < k+1$, and hence the above result.
Also,
$$\lceil \log_2(n + 1) \rceil = \lceil \log_2(2^k + m + 1) \rceil = k + 1$$
This last equation is clear for $m < 2^k -1$, where $2^k + m + 1 < 2^{k+1}$. When $m=2^k-1$, notice that $\log_2(2^k+2^k-1+1) = \log_2(2^{k+1})$ is an integer, and therefore $\lceil k+1\rceil=k+1$.
Hence, this identity is valid only for positive integers ($n \in \mathbb N$).


Is running my Unreal Tournament server like this slower than it has to be?

Question: Unreal Tournament 2004 is an old game, and it does not run on a new server. I was said to run the server like this.
<code>LD_LIBRARY_PATH=$HOME/archive/gcc3 ./ucc-bin server BR-Serenity?game=XGame.xBombingRun?Mutator=UT2Vote51.UT2VoteXMulti,UAdminModV095b.UAdminMod,DualAssaultRifles2k4.DualAssaultRifles ini=ut2004-server.ini
</code>
Although this works perfectly, I wonder if running it with the old gcc3-compiler(?) makes it run slower? Is this not recommended?
The game does not run without adding this to the command-line.
Answer: you dont run it with gcc compiler, it uses your gcc3 libs.
even if you would recompile it with recent versions of gcc, i dont thnik it will have an effect. tuning other parts, e.g. disabling unneeded mods is a much better way to improve performance.


Handler.handleMessage is not called in test, but is called in the app

Question: I have a service that runs in a separate process. The service spawns a new thread in onCreate() method. This thread sends messages back to the service.
If I start the app manually everything works fine - messages are received by the Handler in my service. But in my test handleMessage() method is never get called.
How can I fix my test to make handleMessage() method work?
Thanks!
Service:
public class MyService extends Service {

    private ServiceHandler mHandler;
    private final int MSG_HELLO_WORLD = 1;

    private final String TAG = getClass().getSimpleName();

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return null;
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "MyService.onCreate");
        super.onCreate();

        mHandler = new ServiceHandler();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "Thread: run()");

                while (true) {

                    try {
                        Log.d(TAG, "sleeping...");
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        Log.d(TAG, "Thread was interrupted.");
                        break;
                    }

                    Log.d(TAG, "sending message...");
                    Message msg = Message.obtain(mHandler, MSG_HELLO_WORLD);
                    msg.sendToTarget();
                }
            }
        }).start();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "MyService.onStartCommand");
        return START_REDELIVER_INTENT;
    }

    private class ServiceHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            Log.d(TAG, "ServiceHandler.handleMessage");

            if (msg.what == MSG_HELLO_WORLD) {
                Log.d(TAG, "Hello World message received!");
            }
        }
    }

}

Test:
public class MyServiceTest extends ServiceTestCase<MyService> {

    private static final String TAG = MyService.class.getSimpleName();

    public MyServiceTest() {
        super(MyService.class);
    }

    public void setUp() throws Exception {
        super.setUp();
    }

    public void testStartService() throws Exception {

        Intent startServiceIntent = new Intent(getContext(), MyService.class);

        startService(startServiceIntent);

        MyService myService = getService();

        assertNotNull(myService);

        // give the service some time to send messages
        Thread.sleep(10000);
    }
}

App's logcat output (handleMessage() is called):
MyService.onCreate
MyService.onStartCommand
Thread: run()
sleeping...
sending message...
sleeping...
ServiceHandler.handleMessage
Hello World message received!
sending message...
sleeping...

Test's logcat output (handleMessage() is not called):
MyService.onCreate
MyService.onStartCommand
Thread: run()
sleeping...
sending message...
sleeping...
sending message...
sleeping...
sending message...
sleeping...

Answer: Your question seemed interesting to me, so I started digging.

If I start the app manually everything works fine - messages are received by the Handler in my service.

When you initialize mHandler in the MyService's onCreate() method with mHandler = new ServiceHandler(), the Handler is associated with the message queue of the currently executed thread. mHandler process Messages from the queue that, in its turn, is handled by Looper which is looping. As the result you can see "Hello World message received!" in logs.

But in my test handleMessage() method is never get called.

When you test the service its methods are called on InstrumentationThread (see the threads in Debugger) whose Looper is prepared but not looping, so the messages can't be handled and aren't shown in logs.

How can I fix my test to make handleMessage() method work?

I'd suggest the following options:

Tie MyServiceTest to the thread on which MyService's methods are called. Write one more unit test for the component and then combine the test with MyServiceTest in one common .java test file. This will show the desired logcat output.
Loop the prepared Looper of InstrumentationThread in MyServiceTest. You can do it by adding Looper.loop() in the testStartService() method of MyServiceTest:
public void testStartService() throws Exception {

    Intent startServiceIntent = new Intent(getContext(), MyService.class);
    startService(startServiceIntent);
    MyService myService = getService();
    assertNotNull(myService);

    // Run the Looper (this call is to be added)
    Looper.loop();

    Thread.sleep(10000);
}

Note: running the Looper will show the desired logcat output, but the test won't stop because of Looper.loop() running indefinitely until you call Looper.quit().


xampp problem trying to dowload a file outside documentRoot

Question: I have this in vhost :
<VirtualHost url.com:80>
    DocumentRoot "e:\xampp\htdocs\project"
    ServerName url.com
    <Directory "e:\xampp\htdocs">
        Options Indexes FollowSymLinks
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

and I'm trying to download a file from  htdocs\downloads...
in php code when I do this:
    file_exists('../../downloads/fcm/'.$fcmb.'.pdf')

the result is 1  but when i do this
<a href="../../downloads/fcm/<? echo $fcmb;?>.pdf" target="_blank"><? echo $fcmb;?>

the result is ERROR 404
thing is I don't know how to download a file outside the project directory I tried different ways but not working
Comment: You can NOT redirect users to folders outside DocumentRoot!
You can Serve files from other folders, but user MUST access this files via DocumentRoot folder or its subfolders. So Direct a href link will not work. Use PHP to serve this file instead.
Comment: so if I force the download with php it should work?
Comment: PHP can access folders outside DocumentRoot. A web browser can not, as URLs are limited to the DocumentRoot folder.
Answer: Your download page should be something like:
$file = '../../downloads/fcm/'.$fcmb.'.pdf';

if (is_file($file)) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    header('Content-Type: ' . finfo_file($finfo, $file));
    finfo_close($finfo);
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}


Comunicação entre software de relatórios em JAVA e software principal em PHP

Question: Pensei muito se abriria a pergunta ou não (pode ser fora de escopo ou ampla ou baseada em opiniões), mas como estou com muitas dúvidas em relação a utilização de uma estrutura correta e que atenda a minha necessidade decidi abrir.
Vamos a minha necessidade.
Sistema de relatórios:
Temos um software para geração de relatórios (JAVA), ele não possuí API para renderização do relatório no PHP.
Todos os clientes terão acesso a ele. (cada cliente será diferenciado por uma chave única)
Precisamos acessar esses relatórios através de uma URL passando parâmetros, o que poderia trazer transtornos por tentativas de acessar informação indevida...
Segurança:
Quando o usuário fizer login no sistema em PHP ele ganhará uma chave única que seria armazenada em uma tabela MEMORY e ao sair essa chave seria eliminada.
Toda vez que ele acessar um relatório essa chave seria passada para validação no outro sistema antes de abrir o relatório. Afinal o usuário não gostaria de fazer login novamente quando entrasse nesse sistema... e também passamos a chave única para cada cliente.
Ou seja até agora temos três parâmetros: exemplo.com/relatorios?relatorio=teste&cliente=teste&chave_acesso=teste
A principal questão:

Não teria alguma forma melhor de implementar a segurança entre esses dois softwares sem precisar usar parâmetros pela URL?
Caso usasse a url, na questão de armazenar a chave em uma tabela MEMORY, quais seriam suas vantagens/desvantagens?
Comment: Recomendo fortemente essa lib:

https://github.com/geekcom/phpjasper
Answer: Sim, existem formas melhores, afinal qualquer pessoa poderia ver o parâmetro na URL no navegador ou em um log de acessos e saberia o "segredo" daquele usuário, que acaba funcionando como uma senha.
Uma maneira simples, mas ainda não 100% segura é gerar uma nova chave aleatória por relatório, pois mesmo que alguém consiga ver aquele relatório copiando a URL, a brecha de segurança será muito menor do que permitir o acesso a todos os relatórios.
Outra alternativa seria que o sistema em Java expusesse um web service para o sistema em PHP. Então o usuário solicitaria o relatório para o sistema em PHP, o qual invocaria o web service correspondente e retornaria o relatório para o usuário.
Há duas formas básicas de repassar o conteúdo do relatório:

Instruir o sistema em Java a armazenar o relatório em disco, então você lê do PHP e joga o stream de bytes como retorno para o usuário. Isto é relativamente simples, pois o PHP implementa uma função pronta: fpassthru.
O webservice Java retorna diretamente o stream de bytes e o PHP apenas repassa para o usuário.

A principal vantagem dessa abordagem é que o segundo sistema é transparente para o usuário, ele não terá ciência de sua existência, portanto ele não precisa estar aberto para acesso externo e seria um nó a menos para se preocupar com a questão de segurança. Em suma: menos exposição.
As desvantagens incluem um pouco mais de trabalho para implementar e uma carga maior para o sistema em PHP, pois este precisará chamar o web service, recuperar o retorno e repassar para o usuário. Se o servidor já estiver sobrecarregado esta pode não ser uma opção.
Comment: Muito obrigado, abriu meu leque de possibilidades, além de apresentar opções que eu não havia pensado antes. Vou pesquisar a respeito e ver se consigo implementar a solução aqui.


Want to generate csv of a view programmatically in drupal 7

Question: I have a view in drupal 7 and I want to generate a csv of this view programmatically after click any button.
Comment: The comments you've written below the (good) answer provided by @darol100 indicate that there are a lot of things about your configuration you have not told us.  It is very unlikely that you receive an answer you can use unless you expand the question with more detailed information about what you try to do, and what you have tried so far without getting it working.  Your question says you want to to this "programmatically".  If you want help with your code, you need to show us the code.
Answer: Views data export

This module is designed to provide a way to export large amounts of
  data from views. It provides a display plugin that can rendered
  progressively in a batch. Style plugins are included that support
  exporting in the following types:

CSV
Microsoft XLS
Microsoft DOC
Basic TXT
XML

You should created a Views with CSV display. And then created a bottom that point to that page.
Comment: Thanks for answer. But I am also using one csv exprot button using this module . I need two button . One is working with expose filter that providing me csv after filtering.. I need second button that will provide all csv.
Comment: You can created two views and point them out to different displays. Base on the buttons.
Comment: I need this functionality in same view.