Equicontinuity with decaying oscillators

Question: Suppose $D \subset \mathbb{R}$, $f : D \to \mathbb{R}$ is a bounded continuous function, $a_n$ is a sequence of positive numbers tending to $+\infty$, and $b_n$ is a sequence of positive numbers tending to zero. Define $f_n(x)=b_n f(a_n x)$. Is the family $f_n$ equicontinuous?
I think the answer is yes, but I am not sure my construction is legitimate. Here is my idea. Define $M=\sup f - \inf f$; assume $M>0$, since the case $M=0$ is trivial. Let $\epsilon > 0$. Choose $N$ large enough that if $n > N$ then $b_n<\epsilon/M$. Let $n > N,x \in D,y \in D$. Then
$$|f_n(x)-f_n(y)|=b_n|f(a_n x)-f(a_n y)| \leq \epsilon M/M = \epsilon.$$
Now the family $f_1,f_2,\dots,f_N$ is automatically equicontinuous, because it is finite and each function is separately continuous. So by defining the equi-modulus of continuity for the whole family at $\epsilon$ to be the equi-modulus of continuity of these first $N$ functions, we conclude that the entire family is equicontinuous. Is this last step legitimate? If not, is it legitimate if $D$ is assumed compact?
The title comes because this result is justified by considering problems like "is $f_n(x)=\frac{1}{n} \sin(n^n x)$ equicontinuous?"
Comment: This seems correct. Every finite set of continuous functions being equicontinuous.
Comment: @mathcounterexamples.net My concern is that in the interesting cases, $N$ will blow up with $\epsilon$. But I *think* this is OK, since $N$  depends only on $\epsilon$ and never on $x$.
Answer: You need to assume $f$ is uniformly continuous, otherwise it's a nonstarter. Then the answer is yes: Each $f_n$ is then uniformly continuous and $f_n\to 0$ uniformly. So given $\epsilon>0,$ choose $N$ such that $n>N$ implies $|f_n| <\epsilon/2$ on $D.$ It's clear there exists $\delta > 0$ that works for $f_1,\dots , f_N.$ It also works for the rest of the $f_n$'s because for these $n,$
$$|f_n(y) - f_n(x)| \le |f_n(y)| + |f_n(x)| <\epsilon.$$
Comment: Why do we not get pointwise equicontinuity if $f$ is not uniformly continuous? (I'm aware of the terminology issue here; some authors don't bother talking about pointwise equicontinuity.)
Comment: In particular, $f_n$ converges to zero uniformly regardless of whether we have uniform continuity of $f$, since $f$ is assumed bounded. For a concrete example, is $\frac{1}{n} \sin(n^n x^2)$ pointwise equicontinuous on the whole line?
Comment: I dealt with global equicontinuity on $D,$ but the proof I gave will give pointwise equicontinuity. (Incidentally, your domain $D$ needs to include $b_nD$ for all $n.$) So yes, $\frac{1}{n} \sin(n^n x^2)$ is pointwise equicontinuous everywhere.


Expose View of Visitors information via JSON:API

Question: I've enabled the JSON:API Views module to expose View data via the JSON:API. I've created a page view of Visitors data. Preview data suggests that there is data available. The view is set to be exposed via JSON:API. However, navigating to the jsonapi path (/jsonapi/views/visitors/page_1) consistently results in a 404 "Page Not Found" error.
Other views of different data types are exposed via the JSON:API just fine.
Why would Visitors info not be accessible via the JSON:API?
Comment: First check the access permissions.  Does the user accessing JSON:API have permission to view the data?
Comment: For testing purposes, I'm setting the View to be unauthenticated, and am still not seeing any data come through.
Comment: The permissions on the view are relevant, but also the permissions on the visitor entities are relevant. The anonymous user must have read access to visitors entities (not just the view) or nothing will be shown.  JSON:API will always check the permissions of the entity before returning it.
Answer: Follow these steps to expose visitor data by json API:
Create view of "vistior" entity type of rest export
Then add required path/url like: jsonapi/views/visitors in path setting
Select "json" format by click on setting link > that next to serializer format
you can select field or entity as per requirement
In the access you can select any option as per requirement or can keep unrestricted as well (testing purpose)
Save the view & try to hit the view page, result 'll start appear
Note:There is no need to configure any  additional permission.
if you try to check in this file here is routes() function Try to get entity_type value it is empty due to which code return & getting 404 page not found error. so JSON:API Views" module not support/extend to "visitor" module functionality
There are some approaches that you can follow:

either extend "json api view" module functionality so that it supports vistor entity it requires custom workaround

create custom json api which is also custom workaround

Create REST export view as mentioned in answer
Comment: Thanks @mini, this method of exposing the data via REST export allows me to expose the data in a consumable JSON format. So for that, it meets my needs. The data still will not show via the JSON:API route though, and I am interested if anyone has a solution in that regard. But I will accept this answer if nothing else comes through!
Comment: I have checked with JSON:API Views as well same error replicate : Page not found

 But for this reason of this issue:
  "JSON:API Views" module not support/extend to "visitor" module functionality & if you check at code level "visitor" is separate custom entity not drupal standard entity


Date module is missing but it's exisit

Question: I have installed Date module since i made drupal installation, i built many date fields but Suddenly this message show up when i go to my content type's manage field page "Inactive fields are not shown unless their providing modules are enabled.
The following fields are not enabled:(here my date field and tell me date module is not enabled)"
When open modules page can't find date module but other sub modules exist like (date tools, date views ....)
I tried to recopy the date module and nothing change, date module still lost.
All my date fields disabled please help, thanks.
Comment: You can check for missing modules here and maybe its just a disconnect try this [Missing Modules](https://drupal.org/project/missing_module) or these responses here can help you list your modules http://timonweb.com/advice-may-help-you-if-your-drupal-7-has-started-run-slowly
Answer: Check the permissions and owners of the date module folder inside your sites/all/modules it should be same as others...
Check drupal watchdog logs for more information on errors....
Comment: permissions is 755 for all folders and files in module folder already
Comment: Did you check logs.. ? Can you see info file inside date module ? can you check permissions of date.info file ?
Comment: yes all there, date.info and date.module  and all the test files. the permissions of the files is 755
Comment: Open and read the module's info file, in case it has been damage during the upload.

Check the permissions of that module's folder (is it at least 755?) and of the .info file (is it at least 644?).

Look for differences in permissions and owner between a module that works and one that doesn't work.

Check uninstall tab and see your module is listed there... Try Uninstalling & installing...
Comment: thanks for your help, i did what you say and the permission what it should, i tried to uninstall all the sub date module and remove the date module files and recopy new files but it's the same

Date module is missing but it's exisit


How to override flask_admin ModelView.get_list to get custom amount of entries

Question: Now i get all entries in admin when i open page of MyView(ModelView). I want to manage this behaviour and get only, for example, 10 entries. I tried to override ModelView.get_query method in MyView like
def get_query(self):
     return current_app.db.session.query(MyModel).limit(10)

but this does not work.
Answer: When you override get_query, you must also override get_count_query, for displaying the correct item count in the list view, and get_one, which is used when retrieving records for the edit view (references here). It could be that get_query and get_count_query differs for just one parameter so you can define the method _query and then use it like so:
from sqlalchemy.sql import func

...

def _query(self, param):
    return db.session.query(param).limit(10)

def get_query(self):
    return self._query(MyModel)

def get_count_query(self):
    return self._query(func.count('*'))

def get_one(self, id_):
    return self.get_query().filter(self.model.id == id_).one()


Gerar struct em matlab dinamicamente, com campos de tamanhos diferentes

Question: Estou com uma demanda que é o seguinte, eu quero criar um conjunto de imagens e vou relacioná-las, para isso eu crio um vetor de struct similar a resultsInfo = struct('indice',0,'correlatas',cell(1,5),'fatorCorrelacao',zeros(1,5),'somaImagens',zeros(640,480));, onde:
indice é um inteiro representando o índice da imagem;
correlatas recebe célula com 5 nomes diferentes de imagens que são similares
fatorCorrelacao é um vetor que recebe um número que representa o quão similar são essas imagens;
e somaImagens recebe a soma das 5 imagens similares.
Quando faço isso, ele preenche as matrizes do campo somaImagem, apenas dos 5 primeiros elementos do vetor, os demais ele aloca uma matriz vazia.
A minha intenção é preencher o vetor dinamicamente, pois o número de imagens pode variar de acordo com cada projeto.
Comment: Que bom que você conseguiu resolver. Para ficar mais coesa a pergunta e sua resolução, sugiro que copie a solução e poste como resposta logo abaixo e marque no "v" como resolvida.
Comment: Obrigado pela orientação, Diego
Answer: Resposta no SOen
Defina o seguinte método:
function resultStruct = CreateEmptySruct ()
    resultStruct.img_index = 0  ;
    resultStruct.correlated  = cell(1,5);
    resultStruct.correlationFactor = zeros(1,5);
    resultStruct.ImgSum = zeros(640,480) ;
end

Then call this method in For loop like this:

for i = 1 :5
    structArray(i) = CreateEmptySruct () ;
end

No entanto você pode definir também qualquer valor separadamente para cada struct, passando argumentos da função.
Comment: Boa tarde Daniel, quando disseram que era pra trazer a resposta do SOen, voce deveria ter traduzido ela, somos uma comunidade em Português, a sua duvida pode ser de outras pessoas, mas nem todo mundo sabe inglês.
Comment: Ok Guilherme, obrigado pela edição e pela orientação


Como criar um "glass pane" em JavaScript?

Question: Estou tentando criar um "glass pane" em JavaScript, parecido com o suportado por Java. O objetivo é oferecer uma espécie de ajuda interativa ao usuário, onde informações sobre cada elemento são sobrepostas na tela, e todos os elementos exceto aquele que está sendo explicado fica desabilitado.
Criar o glass pane é fácil - basta um elemento fixo ocupando a tela inteira. Desabilitar todos os elementos exceto um pode ser feito através das propriedades disabled e readonly, ou interceptando eventos na fase de captura. O problema está em fazer o glass pane não bloquear os elementos que estão "atrás" dele.
Para uma demonstração do problema, veja esse exemplo no jsFiddle - todos os elementos funcionam normalmente, até que o link "Ajuda" é clicado; a partir daí, tudo o que está "atrás do glass pane" pára de funcionar, uma vez que os eventos de mouse e teclado vão todos parar no glass pane. Eu gostaria que o glass pane "deixasse passar" os eventos para o que está atrás dele, assim como a versão em Java permite.
Nota: De preferência isso deve ocorrer independentemente do seu grau de trasnparência, ou mesmo de ter ou não coisas desenhadas nele (gostaria de colocar setas e coisas assim).
Workaround
Não usar um glass pane, e sim elementos individuais que não bloqueiem o elemento em foco. Exemplo. Embora não seja a solução ideal, isso e mais alguma estilização condicional do conteúdo poderia resultar em mais ou menos o que eu quero - só que de forma muito mais trabalhosa...
Answer: Isso pode ser feito via CSS:
#glasspane{
    pointer-events:none;
}

Esta propriedade desabilita qualquer evento de mouse no elemento em questão, o que faz com que o elemento logo abaixo de onde você clicou receba os eventos.
Exemplo: FIDDLE
O problema é a compatibilidade com o IE, já que apenas a versão 11+ aceita esta propriedade.
Já o suporte em outros browsers é unânime:
Chrome | FF | Safari 7+ | iOS 3.2+ | Android 2.1+ via CanIUse
Comment: Perfeito! Só tive que adicionar `pointer-events:all` em alguns componentes individuais do glass pane (para que eu pudesse clicar no link "Próximo"), deixando o resto com `none`. [Código final](http://jsfiddle.net/mgibsonbr/8s2eh/1/). Obrigado pela ajuda!


Should I use node.js + express or Rails + Juggernaut to build a chat room?

Question: I'm trying to build a chatroom in the conventional sense to operate in the browser but with a decent API layer allowing for decent abstraction between the server and the client.
I want to keep it SIMPLE, but still have room to develop extra functionality going forwards, such as saving transcripts in the database.
Comment: did you add a look at the examples of the server side of socket.io http://socket.io/#how-to-use
Answer: You can use faye.
https://github.com/jcoglan/faye
There is also a Railscast for this
http://railscasts.com/episodes/260-messaging-with-faye
Answer: You could consider leveraging Faye which is built on top of Node.js and I believe has WebSockets support too.  Possibly route all transcripts with Redis storage.


How can I submit scores with one decimal to Game Center?

Question: I want to send my score with one decimal to Game Center. Ho can I do this??
Answer: You can only submit 64 bit integers as scores to a leaderboard. From the documentation:

To Game Center, a score is just a
  64-bit integer value reported by your
  application. You are free to decide
  what a score means, and how your
  application calculates it. When you
  are ready to add the leaderboard to
  your application, you configure
  leaderboards on iTunes Connect to tell
  Game Center how a score should be
  formatted and displayed to the player.
  Further, you provide localized strings
  so that the scores can be displayed
  correctly in different languages. A
  key advantage of configuring
  leaderboards in iTunes Connect is that
  the Game Center application can show
  your game's scores without you having
  to write any code.

That doc page should tell you about formatting your score. It sounds like in order to display float-like scores you will have to tinker with the format settings in iTunes Connect.
Try this :
<code>- (IBAction)setScore
{
     float score = (float)self.currentScore / 100.0f;
     currentScoreLabel.text = [NSString stringWithFormat: @"%f", score];
     NSLog(@"%lld", self.currentScore);
}
</code>


Como resgatar a string de conexão do App.config de outro projeto?

Question: Tenho essas strings de conexão no App.config de outro projeto:
<connectionStrings>
   <add name="ConexaoTeste1"
    connectionString="RGF0YSBTb3VyY2U9JCQkXFNRTEVYUFJFU1M7SW5pdGlhbCBDYXRhbG9nPXRlc3RlOw=="
    providerName="System.Data.SqlClient"/>

   <add name="ConexaoTeste2"
    connectionString="RGF0YSBTb3VyY2U9dGVzdGU7UGVyc2lzdCBTZWN1cml0eSBJbmZvPVRydWU7"
    providerName="System.Data.OracleClient"/>
</connectionStrings>

Esse outro projeto não está no meu computador. Está na rede.
Como resgato o valor de ConexaoTeste2 no meu projeto?
Answer: Adicione referência System.Configuration no seu projeto e faça:
string conexao =
    System.Configuration.ConfigurationManager.
    ConnectionStrings["ConexaoTeste2"].ConnectionString;

Sobre o fato de o App.config ser remoto: Aqui tem um bom motivo para não fazer dessa forma, e tem também algumas alternativas.
Comment: Jovem, ele disse há alguns minutos atrás que não é isso que precisa.
Comment: @IgorVenturelli Eu tinha apagado a minha, eu só restaurei pra que você pudesse ver os comentários.
Comment: Conforme coloquei na pergunta, o config é remoto, tem toda uma questão de permissão de acesso, o problema é um pouco mais cabeludo.
Comment: Que doideira. Quando fui responder não tinha aparecido nenhuma resposta, @jbueno . Não foi por querer.
Comment: @ROBERTOALBINOJUNIOR Não tinha visto. Editei a resposta.
Comment: @jbueno editei a pergunta. Tá em análise. Deixei mais direta e explícita sobre o fato de ser remoto.
Answer: Consegui resolver o problema com o código abaixo, ignorando o arquivo como config e tratando ele como um xml normal, percorri o documento, encontrei o nó que precisava alterar e funcionou:
XmlDocument xml = new XmlDocument();
xml.Load("\\server\\configs\\teste.exe.config");
xml.SelectNodes("configuration/connectionStrings/add").Item(1).Attributes["connectionString"].Value = "foi";
xml.Save("\\server\\configs\\teste.exe.config");


Atualizar ProgressBar em segundo plano java android

Question: Como que faço para o serviço em background atualizar o ProgressBar no Android?
Meu código:
public void onClick(View v) {
    // inicial o progressbar
            progressBar = new ProgressDialog(v.getContext());
            progressBar.setCancelable(true);
            progressBar.setMessage("Exportando os dados...");
            progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressBar.setProgress(0);
            progressBar.setMax(100);
            progressBar.show();

// Inicia o serviço a partir de INICIAR_SERVICO definido no

    startService(new Intent("INICIAR_SERVICO"));

Não estou sabendo usar o progressBar.setProgress(); na class do serviço chamado.
Answer: O serviço não pode chamar progressBar.setProgress() diretamente. Ele precisa dar um jeito de solicitar à Activity visível nesse momento que esse método seja chamado.
Vejo duas possibilidades: a primeira, que não é minha preferida por ser um pouco mais complicada, é se acoplar (bind) ao serviço e assim permitir que o serviço se comunique com a Activity em questão. Para isso deve-se passar ao serviço a referência a um listener que o serviço vai chamando cada vez que o progress deva ser aumentado. Na Activity, o listener executa progressBar.setProgress(). A documentação explica como fazer para se acoplar a um serviço.
A segunda, que eu prefiro, é transmitir atualizações de progress via broadcast. Você registra um BroadcastReceiver associado ao ciclo de vida de sua Activity (por exemplo, é feito o registerReceiver() em onResume() e o unregisterReceiver() em onPause() - uma dúvida minha aqui, não tenho certeza se os melhores métodos para isso são o par onResume()/onPause() ou onStart()/onStop()). E quando a Activity recebe um broadcast intent contendo o novo valor de progress, chama progressBar.setProgress().
Código no qual você pode se basear:
MinhaActivity.java:
public class MinhaActivity extends Activity {

    private BroadcastReceiver mReceiver;
    private IntentFilter mFilter;

protected void onCreate(Bundle savedInstanceState) {
    mFilter = new IntentFilter();
    mFilter.addAction("ATUALIZA_PROGRESSO");
    mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("ATUALIZA_PROGRESSO".equals(intent.getAction())) {
                mProgressBar.setProgress(intent.getIntExtra("progress"));
                if (intent.getIntExtra("progress") >= 100) {
                    mProgressBar.dismiss();
                }
            }
        }
    }

    mProgressBar = new ProgressDialog(v.getContext());
    mProgressBar.setCancelable(true);
    mProgressBar.setMessage("Exportando os dados...");
    mProgressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressBar.setProgress(0);
    mProgressBar.setMax(100);
}

public void onClick(View v) {
    // inicia o progressbar
    mProgressBar.show();

    // Inicia o serviço
    startService(new Intent(this, MeuServico.class));
}

protected void onResume() {
    registerReceiver(mReceiver, mFilter);
}

protected void onPause() {
    unregisterReceiver(mReceiver);
}

MeuService.java
public class MeuService extends IntentService {
    protected void onHandleIntent(Intent intent) {
        while (tarefaNaoTerminada) {
            (...)
            Intent intentAEnviar = new Intent("ATUALIZA_PROGRESSO");
            intentAEnviar.putExtra("progress", progresso);
            sendBroadcast(intentAEnviar);
        }
    }
}

Comment: @EmersonBarcellos Que bom que ajudou. Se a resposta for o que você precisava, pode aceitá-la.
Comment: Ótimo! é isso que eu preciso Piovezan, muito obrigado.


PHP code displaying as plain text and isset($_POST) not working

Question: I've been trying to use PHP to connect to MySQL and display some data. I'm completely new to this. I read up on the subject mainly from w3schools, and a few other site found on Google.
However I'm having 2 problems 1st, the PHP code starting after
$result = mysql_query("SELECT * FROM Passengers_On_Flight");

is being displayed as plain text.
The other problem is that the it always happens even when a form has not been submitted which leads me to believe that form some reason the if(isset($_POST['submit'])) is not being evaluated correctly. I've found other questions where people have the problem that its never evaluating true but not that it always evaluates true.
I did a PHP -v on my server to ensure php5 is installed, I also did this: http://www.gilesorr.com/papers/PHP/x37.html
both showed that PHP was in fact installed and working. I've searched but can't seem to figure out the problem.
Here is my HTML with PHP:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

    <link rel="stylesheet" type="text/css" href="cobraStyle.css">

    <TITLE>Cobra</TITLE>

            Cobra Airlines

Home

Check Flights

Administration

Contact us

        Flights heading

        <?php
        if($_POST['submit'])
        {
            $con = mysql_connect("localhost","root","qwerty");
        if (!$con)
        {
            die('Could not connect: ' . mysql_error());
        }
        mysql_select_db("Cobra_Airlines", $con);

        $result = mysql_query("SELECT * FROM Passengers_On_Flight");

        echo "

            Fligh Number
            Departure Date
            First Name
            Last Name
            Passenger Number

";

        while($row = mysql_fetch_array($result)){
            echo "
";
            echo "" . $row['FlightNum'] . "	";
            echo "" . $row['Departure_Date'] . "	";
            echo "" . $row['First_Name'] . "	";
            echo "" . $row['Last_Name'] . "	";
            echo "" . $row['PassengerNum'] . "	";
            echo "
";
        }
        echo "
";

        mysql_close($con);
    }
?>

<form name="input" action="viewFlights.html" method="post">
    Flight Number: <input type="text" name="flight">
    <input type="submit" value="submit" name="submit">
</form>

    Copyright © Cobra Air, 2012

Here is the updated PHP:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<link rel="stylesheet" type="text/css" href="cobraStyle.css">

      <TITLE>Cobra</TITLE>

                    Cobra Airlines

Home

Check Flights

Administration

Contact us

                Flights heading

            <?php

                    $con = mysql_connect("localhost","root","qwerty");
                    if (!$con)
                    {
                        die('Could not connect: ' . mysql_error());
                    }
                    mysql_select_db("Cobra_Airlines", $con);

                    $result = mysql_query("SELECT * FROM Passengers_On_Flight");

                    echo
                    "

                        Fligh Number
                        Departure Date
                        First Name
                        Last Name
                        Passenger Number

";

                    while($row = mysql_fetch_array($result))

                        echo "
";
                        echo "" . $row['FlightNum'] . "	";
                        echo "" . $row['Departure_Date'] . "	";
                        echo "" . $row['First_Name'] . "	";
                        echo "" . $row['Last_Name'] . "	";
                        echo "" . $row['PassengerNum'] . "	";
                        echo "
";

                    endwhile;
                    echo "
";

                    mysql_close($con);

            ?>

                <form name="input" action="viewFlights.php" method="post">
                    Flight Number: <input type="text" name="flight">
                    <input type="submit" value="submit" name="submit">
                </form>

            Copyright © Cobra Air, 2012

Comment: in addition mysql_ is now being phased out, you should instead use mysqli.
Comment: Don't read w3schools: http://w3fools.com/
Comment: action="viewFlights.html" are you parsing html as PHP?
Comment: action="viewFlights.html" is outside the php tags, I believe
Comment: No it's nothing to do with the php tags. Your pages are .html, they are not parsed as php unless you explicitly tell your server to do that.
Answer: The problem is they are html files not php viewFlights.html and x37.html won't parse as PHP unless your server is told .html is supposed to.
Change their file names to .php, i.e. viewFlights.php and x37.php (and update your form action to viewFlights.php).
You should change if ($_POST['submit']) to if (isset($_POST['submit'])) to avoid and Undefined index error.
Aside...
When you've dealt with that, I can never fathom why people do this where white-space isn't important.
echo "
";
echo "" . $row['FlightNum'] . "	";
echo "" . $row['Departure_Date'] . "	";
echo "" . $row['First_Name'] . "	";
echo "" . $row['Last_Name'] . "	";
echo "" . $row['PassengerNum'] . "	";
echo "
";

just
echo "

    " . $row['FlightNum'] . "
    " . $row['Departure_Date'] . "
    " . $row['First_Name'] . "
    " . $row['Last_Name'] . "
    " . $row['PassengerNum'] . "

";

EDIT
Answer to second problem, while(){} has been changed to while():endwhile but the colon is missing. Needs to be
while($row = mysql_fetch_array($result)):

Comment: Ok thanks i tried it. However now I get:

HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.

is this because there is something wrong with my php code?
Comment: You will have an undefined index "submit" because you're not checking for it but that shouldn't cause a 500. Does the test page work?
Comment: but has the 500 gone? If not, edit your question and post the new code underneath the old.
Comment: other than cahnging the xtension to .php and edit action="viewFlights.html" to action="viewFlights.php" nothing has changed. Do you still want me to post the code? Also I removed my php code so it only contain am echo, it worked then I added if($_POST['submit']) as a condition to echo. and it agve a 500 error again so i guess the problem is with that line.
Comment: ok, you've changed your while(){} to while():endwhile, put it back to braces or add a colon after the condition, e.g. while(condition):
Comment: WOW! Man that was it. Everything is working now. I can't thank you enough.
Answer: what do you mean by plain text? if you are trying to pull records unless its a password etc... shouldnt it be fine?
by you $_POSTing the submit value, you are just pushing it no where.
you should be $_POSTing the Flight number like:  if($_POST['flight'])
you are missing a chunk of programming to pull the records too.
i suggest you plan the process, before you code.
also, the structure of your mysql connection is poor, keep ONE persistent connection in an external directory, until you are ready to close it, it uses less resources.
(../Connections/config.php)
$pcon = mysql_pconnect('','','')
mysql_select_db('', $pcon)
dont forget to change the page to a .php extension not .html!!
Comment: by plain text I mean rather than the records on the data base I get

while($row = mysql_fetch_array($result)){
            echo "";
            echo "" . $row['FlightNum'] . "";
            echo "" . $row['Departure_Date'] . "";
            echo "" . $row['First_Name'] . "";
            echo "" . $row['Last_Name'] . "";
            echo "" . $row['PassengerNum'] . "";
            echo "";
        }
        echo "";

        mysql_close($con);


Função jQuery com fancybox - Estou com problema de refresh

Question: Ao abrir ou fechar a fancybox (sou programador php mas iniciante em Javascript com jquery), a minha página dá um refresh e volta para o topo do conteúdo perdendo o foco do lugar que o conteúdo se encontrava ao acionar a fancybox. A ação pode ser vista aqui (http://santins.com.br/_z/holcim) clicando em qualquer link que abre a fancybox e o código que estou usando é este:
$(document).ready(function ($) {
    $('.fancybox').fancybox({
        closeClick: true,
        padding: 0,
        width: 800,
        height: 'auto',
        arrows: true,
        autoSize: false,
        nextClick: true,
            'ajax': {
            dataFilter: function (data) {
                return $(data).find('#primary')[0];
            }
        }
    });
});

Answer: Olhando o seu site, como não há uma referencia de posição utilizando a barra de endereço mais especificamente a área de hash do window.location o que acontece é que quando você entra no seu fancybox ele acaba por eliminar o scrollbar, levando o valor para 0.
Uma solução é na hora em que a pessoa clicar, antes de exibir seu fancybox, você armazenar em uma variável de contexto a posição do scroll e ao fechar, você aplicar a navegação pro scroll que salvou, levando a pessoa de volta a posição original.
Primeiro vamos pegar os botões que tem fancybox e dar uma função para armazenar o valor do scrollTop quando clicado:
window.lastScrollTop = $(window).scrollTop(); // Vai iniciar em zero;
// Quando clicar no fancybox vamos salvar um novo valor
$('a.fancybox').on('click', function () {
    window.lastScrollTop = $(window).scrollTop();
});

Agora quando você sair do fancybox tem que retornar ao valor armazenado, então nas sua configurações, tem que adicionar onClosed handler.
$(document).ready(function ($) {
    $('.fancybox').fancybox({
        // ...
        onClosed: function () {
            // Ao fechar leva de volta a posição armazenada anterior do scrollTop
            $(window).scrollTop(window.lastScrollTop);
        },
        // ...
    });
});

Utilizei uma variável global lastScrollTop pois não sei como seu código foi escrito e não sei como isolar o contexto pra este caso. Mas não recomendo o uso de variáveis globais.
Outra maneira mais genérica também é possível, no lugar de adicionar o evento de click nas ancoras, é utilizar o onStart handler do fancybox, teoricamente é chamado antes de aplicar seu efeito que vai eliminar o scrollTop, ficaria assim:
$(document).ready(function ($) {
    var lastScrollTop;
    $('.fancybox').fancybox({
        // ...
        onStart: function () {
            // Armazenando o scrollTop antes de iniciar o processo scrollTop
            lastScrollTop = $(window).scrollTop();
        },
        onClosed: function () {
            // Ao fechar leva de volta a posição armazenada anterior do scrollTop
            $(window).scrollTop(lastScrollTop);
        },
        // ...
    });
});

Desta maneira é possível utilizar variável de contexto não expondo nenhuma variável global.
Comment: Poderia me ajudar a fazer isso Gabriel?
Comment: Está ai uma solução que deve ajudar-lhe @marcosvinicius
Comment: Desculpe minha ignorância em não saber se devo colocar alguma coisa nesses 3 pontinhos (...) ...
Comment: os três pontinhos é só pra exemplificar que esse trecho de código fica entre o seu código, pode ficar antes ou depois. Tenta colocar depois do `autoSize` e antes do `nextClick` sem incluir os `...` claro, pois são propriedades de um objeto literal que você está passando como parâmetro do método `fancybox`.
Answer: Eu resolvi o problema com o seguinte código:
$('.fancybox').fancybox({
  padding: 0,
  helpers: {
    overlay: {
      locked: false
    }
  }
});

Comment: também funciona


Contact Form with drop-down subject (bonus: auto-selected based on GET/POST)

Question: I have a number of services on my site and I want them to all direct to the contact form. Now, this is where it gets tricky- I want the subject to be a dropdown selection of all services provided and, if possible [bonus], based on the link clicked (GET/POST).
Alternatively:
I would also be open to a contact-form jquery popup modal box that I could tailor for specific services.
Any help is greatly appreciated and I thank you in advance.
Answer: You can try hook_node_view() to pre-select default value of webform component on the base of referer.
function yourmodule_node_view($node, $view_mode){
    if($node->nid == [nid of webform]){
            global $base_path;
            $referer = $_SERVER["HTTP_REFERER"];
            $start = strpos($referer, $base_path) + strlen($base_path);
            $ref_local_path = substr($referer, $start);
            switch($ref_local_path){
                    case 'service_1_path':
                            $node->content['webform']['#form']['submitted']['<component_name>']['#default_value'] = 'option_1';
                    break;
                    case 'service_2_path':
                            $node->content['webform']['#form']['submitted']['<component_name>']['#default_value'] = 'option_2';
                    break;
            }
    }
...

If you are looking to do it via JS/JQuery that is another solution.


How to capture still image from webcam on linux

Question: I am trying to write a C++/Qt program for linux, where I take a still image photo from a webcam, make some transformations to a photo (cropping, resizing, etc.), and save it to a jpeg file.
But I have encountered some problems. The main problem is that standart UVC (usb video device class) linux driver currently does not support direct still image capture: http://www.ideasonboard.org/uvc/ .
So, there are two possible ways to capture still image. You can take one frame from the video stream from the camera, or you can take a separate photo, like a digital portable camera. The second way is not supported in linux uvc driver, so the first method is the only way. But the problem is, that if you want to take a frame from the video stream, the size of the photo can't be bigger than the size of video in the video preview window. So, if I want to take 2 megapixel photo, I must start videostream with the size 1600x1200, which is not so comfortable (At least, in Qt the size of the videostream depends on the videopreview window size).
I know that there is video for linux 2 API, which may be helpful in this task, but I don't know how to use it. I am currently learning gstreamer, but I can't now figure out how to do what I need using these tools.
So, I will appreciate any help. I think it is not a hard problem for people who know Linux, GStreamer, v4l2 API, and other linux-specific things.
By the way, the program will be used only with web-camera Logitech C270 HD.
Please, help me. I don't know what API or framework can help me do this. May be you know.
Comment: I don't know if this might help, which is why I am putting it as a comment. There is an oss program called "cheese" that takes pictures and video recordings. Take a look here: https://apps.ubuntu.com/cat/applications/precise/cheese/   ... Perhaps taking a look at the code might help you.
Comment: Possible duplicate of [Webcam library for C on Linux?](http://stackoverflow.com/questions/278112/webcam-library-for-c-on-linux)
Answer: Unfortunately the C4V2 calls in opencv did not work for still image capture with any camera I have tried out of the box using the UVC driver.
To debug the issue I have been  playing with trying to accomplish this with c code calling c4v2 directly.
I have been playing with the example code found here. It uses the method of pulling frames from the video stream.
You can compile it with:
gcc -O2 -Wall `pkg-config --cflags --libs libv4l2` filename.c -o filename

I have experimented with 3 logitech cameras. The best of the lot seems to be the Logitech C910. But even it has significant issues.
Here are the problems I have encountered trying to accomplish your same task with this code.
It works pretty much every time with width and height set to 1920x1080.
When I query other possibilities directly from the command line using for example:
v4l2-ctl --list-formats-ext

and I try some of the other "available" smaller sizes it hangs in the select waiting for the camera to release the buffer.
Also when I try to set other sizes directly from the command line using for example:
v4l2-ctl -v height=320 -v width=240 -v pixelformat=YUYV

Then check with
v4l2-ctl -V

I find that it returns the correct pixel format but quite often not the correct size.
Apparently this camera which is listed on the  UVC site as being UVC and therefore v4l2 compatible is not up to snuff. I suspect it is just as bad for other cameras. The other two I tried were also listed as compatible on the site but had worse problems.
I did some more testing on the LogitechC910 after I posted this. I thought I would post the results in case it helps someone else out.
I wrote a script to test v4l2 grabber code mentioned above on all the formats the camera claims it supports when it is queried with v4l2 here are the results:
640x480 => Hangs on clearing buffer
160x120 => Works
176x144 => Works
320x176 => Works
320x240 => Works
432x240 => Works
352x288 => Works
544x288 => Works
640x360 =>  Works
752x416 => Hangs on clearing buffer
800x448 => Hangs on clearing buffer
864x480 => Works
960x544 => Works
1024x576 => Works
800x600 => Works
1184x656 => Works
960x720 => Works
1280x720 => Works
1392x768 => Works
1504x832 => Works
1600x896 => Works
1280x960 => Works
1712x960 => Works
1792x1008 => Works
1920x1080 => Works
1600x1200 => Works
2048x1536 => Works
2592x1944 => Hangs on clearing buffer.

It turns out that the default setting of 640x480 doesnt work and that is what trapped me and most others who have posted on message boards.
Since it is grabbing a video frame the first frame it grabs when starting up may have incorrect exposure (often black or close to it). I believe this is because since it is being used as a video camera it adjusts exposure as it goes and doesnt care about the first frames. I believe this also trapped me and other who saw the first frame as black or nearly black and thought it was some kind of error. Later frames have the correct exposure
It turns out that opencv with python wrappers works fine with this camera if you avoid the land mines listed above and ignore all the error messages. The error messages are due to the fact while the camera accepts v4l2 commands it doesnt respond correctly. So if you set the width it actually gets set correctly but it responds with an incorrect width.
To run under opencv with python wrappers you can do the following:
import cv2
import numpy

cap = cv2.VideoCapture(0)  #ignore the errors
cap.set(3, 960)        #Set the width important because the default will timeout
                       #ignore the error or false response
cap.set(4, 544)        #Set the height ignore the errors
r, frame = cap.read()
cv2.imwrite("test.jpg", frame)

Answer: **Download And Install 'mplayer'**
mplayer -vo png -frames 1 tv://

Comment: >mplayer -vo png -frames 1 tv://
does not work. Plain green picture appears in the home directory.
Comment: As I know, mplayer uses gstreamer to play media...may be you know some gstreamer code to do the same thing?
Comment: No, mplayer doesn't use gstreamer to play media, rather they both use the same underlying libraries like x264 and ffmpeg.
Answer: mplayer -vo png -frames 1 tv://

might give a green screen output as the camera is not yet ready.
mplayer -vo png -frames 2 tv://

You can try increasing the number of frames and choose a number from which the camera gives correct images.
Comment: if your camera needs some time to auto-adjust the brightness etc., try `mplayer -vo png -frames 2  -vf "framestep=30" tv://` to just skip the first 30 frames (or whatever your camera needs) after the first shot, so the second is the correct one.
Answer: What about this program?
#include<opencv2/opencv.hpp>
using namespace cv;
int main()
{
    VideoCapture webcam;
    webcam.open(0);
    Mat frame;
    char key;

    while(true)
    {
        webcam >> frame;
        imshow("My Webcam",frame);
        key = waitKey(10);

        if(key=='s')
        break;
    }
    imwrite("webcam_capture.jpg", frame);
    webcam.release();
    return 0;
}

This will capture a picture of maximum size allowed by your webcam. Now you can add effects or resize the captured image with Qt. And OpenCV is very very easy to integrate with Qt, :)
Comment: does not work. I removed part of your code, and now it simply takes a picture and saves it to file without showing to a window. and output is       HIGHGUI ERROR: V4L/V4L2: VIDIOC_S_CROP
Comment: well, then you need to set some options to open function, such as capture size, frame etc. Alternatively you can use GLWidget to show webcam video inside a Qt window.


How to display cgi-bin errors instead of 500 in Apache?

Question: I'm interested in getting errors from cgi-bin scripts inside the browser like the PHP errors.
The cgi script can be Perl, Python, Ruby, binary or something else. I'm not interested about a specific solution - I'm looking for something that should work with any script.
I want to use is on a development/test server not in production. I am aware that in production you should not display the error_log to the user.
I'm looking for a script to be used to replace ErrorDocument inside Apache. I had one in the past but I lost it.
Answer: Basically as radius says, catch & display the error rather than let it pass through. In perl, see the Carp module: http://search.cpan.org/~nwclark/perl-5.8.9/lib/Carp.pm
Answer: I think that using a wrapper can do that.
Write a script that always return 0 so that apache will never do error 500 for it.
In this script launch the true script to execute and catch STDOUT and STDERR to be able to send them back to the client.
Answer: Not quite what you asked but how about just exposing the logs through an alias?
<code>Alias /var/log/httpd /apache-logs
<Directory /var/log/httpd>
  # access control options, fancy indexing options, etc
</Directoy>
</code>
Answer: In the past I've placed a small script on my development server that tailed the log file to the browser.  It didn't replace the 500 error but I suppose you could have Apache redirect to such a script when a 500 error is detected.


Android GridLayout single CardView takes all screen

Question: I'm want to implement a 2x2 GridLayout so I can show 4 Card Views. My problem is a single Card View is taking all the space. When I add the second one (row 0, column 1) it is positioned out of the screen (on the right).
This is my layout code
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<androidx.gridlayout.widget.GridLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:columnCount="2"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:rowCount="2">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_row="0"
        app:layout_column="0" />

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_row="0"
        app:layout_column="1" />
</androidx.gridlayout.widget.GridLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Answer: Use layout_width of both cardview as wrap_content instead
Answer: both CardViews match the width of the parent, that's why, you only see one
you can change it like this
android:layout_width="wrap_content"
app:layout_columnWeight="1"

using app:layout_columnWeight will ensure both cards have the same width regardless of their content


Does "full count" in MLB mean to "three balls and two strikes"

Question: At about 7'11″ into the video linked below, the announcer says "full count now three balls and two"
Boston Red Sox vs New York Yankees - August 2, 2020 - Regular Season 2020 - MLB - Full Game
Does "full count" in MLB mean to "three balls and two strikes"? Is it in the statistical?
Answer: Yes. Quoting from Wikipedia:

A full count [...] is the common name for a count where the batter has three balls and two strikes.


Radius of convergence of $\sum_{n = 1}^{\infty} \frac{1}{n^{n}} \cdot x^{2^{n}}$

Question: By Cauchy Hadamard Theorem,
$$R = \frac{1}{\limsup_{n\to\infty} |a_{n}|^{1/2^{n}}} $$
But
$$\limsup_{n\to\infty}|a_{n}|^{1/2^{n}} = \lim_{n\to\infty} |\frac{1}{n^{n}}|^{1/2^{n}} = \lim_{n\to\infty} |1/n|^{n/2^{n}} = L$$
Then
$$\text{log}(L) = \lim_{n\to\infty} \frac{n}{2^{n}} |1/n|.$$
Since $1/n > 0$
 always,
$$\log(L) = \lim_{n\to\infty} \frac{n}{2^{n}} \frac{1}{n} = \frac{1}{2^{n}} = 0. $$
Therefore $L = e^{0} = 1$.
Therefore $R = 1$. Am I right? Pretty sure it's wrong I think it should be $R = \infty$. I don't know what's wrong.
Comment: What is your exponent of $x$ exactly? $2n$ or $2^n$?
Comment: It is $2^{n}$, not $2n$. Just edited the title. It was a typo.
Comment: That $\log L$ seems not to be right.
Comment: ok. it is a new technique I saw online. I don't know how else to evaluate the limit. I tried to use power rule of logarithm
Comment: what's wrong with log $L$?
Answer: You are correct, the radius of convergence is 1.
Another way to see this is that for any positive $a$, the quantity $(1+a)^{2^n}$ will grow extremely quickly with $n$, even much faster than $n^n$ will. In fact, even the log of $(1+a)^{2^n}$ is growing exponentially with $n$, whereas the log of $n^n$ is growing far more slowly--only growing on the order of $n \log n$.
Comment: There are some conflicting answers.
Comment: The OP is correct on the answer, but the computation is not all correct.
Answer: The "new technique" should be like this.
$$
L = \lim_n \exp \left(\frac n {2^n} \log \left(\frac 1n \right)\right) = \lim_n \exp \left( \frac {-n \log n}{2^n}\right).
$$
Since
$$
0 \leqslant \frac {n \log n}{2^n} \leqslant \frac {n^2}{\binom n 3} \to 0,
$$
the limit $L =\exp 0= 1$. And the answer is not correct.
UPDATE
For the ratio test,
$$
\ell = \lim_n \left. \frac {x^{2^{n+1}}}{(n+1)^{n+1}}\middle/ \frac {x^{2^n}} {n^n} \right. = \lim_n \frac {x^{2^n}}{ \left( \dfrac {n+1}n \right)^n \cdot (n+1)} = \lim_n \frac 1 {\mathrm e} \cdot \frac {x^{2^n}} {n+1}
$$
The limit would be different when $x$ varies. If $|x|>1$, then $\ell = +\infty$, since $x^{2^n} = |x|^{2^n} = (1+a)^{2^n}[a > 0] > 2^n a$, and $$\frac {x^{2^n}}{n+1} > \frac {2^n a}{n+1} > \frac {\binom n 2 a}{n+1} \xrightarrow{n \to \infty} +\infty.$$
If $|x|\leqslant 1$, then
$$
0 \leqslant \frac {x^{2^n }}{n+1} \leqslant \frac 1{n+1} \xrightarrow{n \to \infty} 0,
$$
hence $\ell = 0$.
Conclusion: the series converges iff $x \in [-1, 1]$.
Comment: There are conflicting answers below now..
Comment: what's wrong with my computation though?
Comment: @DillainSmith $$\log \left(\left|\frac 1 {n^n}\right|^{1/2^n}\right) = \frac n {2^n}\color{red}{\log |1/n|}, \neq \frac n{2^n} |1/n|. $$
Answer: Hint::
for any real number r we will check this series is convergent or not. This is a series of positive real numbers. $\sum_{n = 1}^{\infty} \frac{1}{n^{n}} \cdot r^{2^{n}}$.
Now you can use D'Alembert's ratio test. I think lim $\frac{t_{n+1}}{t_n}=0$ for $[-1 , 1]$.For $|r| >1$ we can use the other Positive real number series tests.
Comment: I cannot successfully show that the ratio equals $0$. Also, this answer is not the same as Mike's


How to prove the open interval $(1,5)$ is a convex set?

Question: I want to prove the interval $(1,5)$ is a convex set.
A convex set is a set having all the convex linear combinations of its point in it, where a convex linear combination is a linear combination of the form $X=(1-\alpha)X_1+ \alpha X_2$ where $\alpha$ lies between $0$ and $1$ and the sum of coefficients of above linear combination is equal to 1.
How can we prove the interval $(1,5)$ a convex set?
Comment: Take any two $x_1, x_2$ from the interval and any $\alpha\in[0,1]$. Prove that $\alpha x_1 + (1-\alpha) x_2$ is in the interval.
Comment: Welcome to Math.SE! Please consider updating your question with some information about what you have tried or where you are getting stuck. You will find people are much more willing to help if you do!
Answer: You just have to prove that for every $\alpha \in (0,1)$ and every pair $x_1$, $x_2$ $\in (1,5)$, $\alpha x_1 + (1-\alpha)x_2$ also lies in $(1,5)$.
Suppose without loss of generality that $x_1 \leq x_2$. Then for every $\alpha \in (0,1)$ (which implies that both $\alpha$ and $1-\alpha$ are positive)
$\alpha x_1 + (1-\alpha)x_2 \leq \alpha x_2 + (1-\alpha)x_2 = x_2$
and
$\alpha x_1 + (1-\alpha)x_2 \geq \alpha x_1 + (1-\alpha)x_1 = x_1$.
Hence we find that for every $\alpha \in (0,1)$, $\alpha x_1 + (1-\alpha)x_2 \in [x_1,x_2]$.
Hence for every pair $x_1$, $x_2$, any convex-combination of $x_1$, $x_2$ lies in $[x_1,x_2]$. And since $x_1$, $x_2$ $\in (1,5)$, every convex-combination of any two points in $(1,5)$ also lies in $(1,5)$.
Comment: an exrcise is given in a book that prove X=(-1/2,1/2,7/4) is the convex linear combination of X1,X2 and X3??? we did'nt provided with that X1,X2 and X3...either this question  is wrong or there  any way to prove it??
Answer: If $x_1\leq x_2$ then $$x=(1-\alpha)x_1+\alpha x_2=x_1+\alpha(x_2-x_1)$$ If $\alpha \in [0,1]$ then $$0\leq \alpha(x_2-x_1)\leq x_2-x_1$$ so: $$x_1\leq x\leq x_1+(x_2-x_1)=x_2$$
Then $x_1,x_2\in (1,5)$ gives: $$1< x_1\leq x\leq x_2<5$$
Comment: why we are taking x1x1 then alpha will be less then zero...which is against covexity condition that is alpha should lie between 0 and 1....is this rzn for taking x1<x2???
Comment: we do not take $x_1<x_2$ but $x_1\leq x_2$. If both are elements of $\mathbb R$ then you will have $x_1\leq x_2$ *or* $x_2\leq x_1$. You could say that the answer deals with case $x_1\leq x_2$ and it is quite obvious that the same way of proving can be handled in the other case. Just switch the roles of $x_1$ and $x_2$.
Comment: an exrcise is given in a book that prove X=(-1/2,1/2,7/4) is the convex linear combination of X1,X2 and X3??? we did'nt provided with that X1,X2 and X3...either this question is wrong or there any way to prove it??
Comment: It is not be the right way to go deeper into this in a comment on this answer. I advice you to post your problem as a new question.
Answer: Hint :

$1<X_1<5\Rightarrow 1-\alpha<(1-\alpha)X_1<5(1-\alpha)$
$1<X_1<5\Rightarrow \alpha<\alpha X_2<5\alpha$

Can you now bound $(1-\alpha)X_1+ \alpha X_2$ just by adding above two inequalities?


Use the definition of partial derivative to show that ∂f/ ∂x (0, 0) does not exist

Question: [I just need help with part b of this problem][1]
Let $f:\mathbb{R}^2\to\mathbb{R}^2$ be defined by $f(0,0)=0$ and $f(x,y)=\frac{2x^2-y^2}{x^2+y^2}$ if $(x,y)\neq (0,0)$.
a) Show that $f$ is not continuous at $(0,0)$.
b) Use the definition of partial derivative to show that $\frac{\partial f}{\partial x}(0,0)$ does not exist.
Comment: $f(x,0)-f(0,0)=2$. Now what?
Answer: Hint: You just have to setup the proposed limit $$\lim_{h \to 0} \frac{f(0+h,0)-f(0,0)}{h} = \lim_{h \to 0}\frac{2-0}{h} = \lim_{h \to 0}\frac{2}{h}.$$What about lateral limits?
Comment: Okay, so you get 2/h. Take the limit as h approaches zero from above (0+) and you get positive infinity. Take the limit as h approaches zero from below (0-) and you get negative infinity. Since you get different values for the limit, the partial at (0,0) DNE.
Is this correct?
Comment: I don't understand how you got 2....
and what are lateral limits?
Comment: I just plugged in $x = h$ and $y = 0$ in the expression for $f(x,y)$. And [lateral limits](https://en.wikipedia.org/wiki/One-sided_limit) you should have learned in single variable calculus (it's a terrible idea to tackle multivariable calculus before that).
Comment: Okay, yes I am familiar with one-sided limits. I've just never heard them be referred to as "lateral limits"
Comment: Yes, precisely!


Default configuration for ngStorage

Question: I would like to use $localStorage for ngStorage through out my application. Is there any way to configure it in app.config so that I don't need to repeat $scope.$storage = $localStorage; code in every controller/service where I needed.
Thanks in advance.
Answer: You can use .run on your module and set $localstorage.$default there so it will be initialized when your app runs.

Default configuration for ngStorage


How to have a penetrating voice?

Question: My voice is always buried in background sound, no matter if it is singing or speaking. What can I do to have a more penetrating voice?
What kind of voice is more penetrating, high or low pitch?
Comment: Definitely higher.
Answer: Well, you have to use the fact that the sound you produce is caused by air, which is pushed up from your lungs, and this in turn is controlled by the tension in the muscles around them. Singing teachers or voice trainers often refer to anchoring, support and other ideas to describe this. The aim is to have the muscles in your torso (diaphragm and others on the waist level and up) provide a steady and forceful air flow to your larynx. Note that these muscles are involuntary and cannot be controlled directly (see edit at end).
There are various ideas about how to exactly achieve this and how it translates into "penetration" and "power" in a voice so that it "carries" well over the orchestra like in classic opera and dramatic singing. There are specific excercises teachers often use to build up this ability, usually based on breathing. If you are interested in studying this, you might be interested in Estill voice training or similar programs.
Having that air flow, you need to think about how the resulting sound is created and amplified throughout your body. Obviously, there are many, many aspects to this also directly related to the "power" of the sound. For example, luser droog pointed out in another answer that overtones are an important factor shaping the intensity of a voice, and surely influence its character as percieved by others. But I think the breathing part is where it all starts.
In practice, I think it boils down on a personal level to discovering what you need to do in order to trigger a solid air flow in your body, and how best to resonate the resulting sound. The voice is inside your body, so you can remember the sensation by how it feels. For example: it can feel like the muscles beneath your stomach move outwards (yes!) while exhaling, and you can imagine the sound flowing out in front of you through your forhead.
Edit: there were comments that correctly pointed out that it is not possible to control just your diaphragm, it is an involuntary muscle. However, you can control the way you exhale, and excercises such as "breathing with your diaphragm" are meant to fortify breathing technique. You can find many texts on the topic, for example this page at choirly and this. The first one has this instructive picture comparing chest and diaphragmatic breathing, the second being more appropriate for controlling a (singing) voice and providing strong "support":

For more information on the anatomy of breathing, in particular exhaling, there is an informative NIH page that describes what happens when breathing. So, it states that under normal conditions exhaling requires no effort from your body.
Edit 2: the more I read about muscles and the way they are controlled, it is becoming clear to me that the diaphragm is both involuntary and voluntary. That means that the brain has mechanism for both the conscious and unconscious control of the that muscle system (it is apparently not just one muscle). I don't think all the scientific details are entirely understood, yet.
Comment: I'm cleaning up the comments here and am going to summarize myself to avoid putting words in anyone's mouth: You cannot directly control your diaphragm, since it is an involuntary muscle.  The goal should be proper breathing involving your abdominal muscles, which might involve your diaphragm behaving differently (but indirectly).
Comment: @karol Hi Karol, when you mention the use of muscle tension, could you expand on how they are involved in singing at http://music.stackexchange.com/questions/12380/what-muscles-are-involved-in-singing-and-does-toning-them-improve-singing ?  I'm intregued as to how they fit into the picture, but it may be outwith the scope of this question.
Comment: @MatthewRead You are correct. I've added a bit about this, and marked the asnwer as a community wiki, so feel free to add stuff right there if you'd like to make it more comprehensive. Thanks for pointing this out, I was not aware.
Answer: To complement Karol's excellent answer covering the mechanics of vocal sound production, there is another side, that of human audio perception. The human ear tends to perceive higher frequencies as having greater intensity even at the same volume as a lower frequencies. This is why Bass Amplifiers have to be so enormous to compete with a smaller guitar amplifier.
For male voices, this puts the tenor at a more favorable position than a baritone or bass. For the lower voices, achieving a piercing tone has to take into account the overtones of the fundamental. Counter-intuitively, it is the breathy sound (soft vocal fry) that produces a sort of white noise which contains loads and loads of partials and overtones. So the breath-support Karol advises also provides the tool to reinforce higher overtones when the note being sung is quite low. That is, adding more "breath" sound actually helps add more presence. (This point is disputed. In fact, I may be totally wrong about all of my "explanation".)
Edit: Of course pure white noise wouldn't work here, as it (by definition) has a flat frequency spectrum. Fortunately, the sound of breath is not pure white noise, just a rather unfocused collection of tones and overtones.
And my use of the terms high and low with regard to pitches refers to the context of human vocal ranges, not human hearing ranges where, as leftaroundabout comments, the increased-perceived-intensity effect happens over the middle-range.
Comment: "adding more "breath" sound actually helps add more presence."  That's very definitely wrong. "breath sound" has a wide spectrum and does not stand out.  If it did, steam whistles (or actually any whistle) would be pointless as you would be better off just letting the steam hiss.  Good vocal closure stops the "breathy" sound quality and lets the vocal folds generate a "pulse train" which (idealized) is rich in harmonics that can be shaped into vowels.  Falsetto has weak overtones, making vowel distinction harder than even whispering.  But carrying power and vowel distinction are not the same.
Comment: @luserdroog - just want to point out here that bass amplifiers are large because lower pitches resonate at lower frequencies (i.e. more slowly) and therefore need a larger vibrating material to resonate.  This is why tubas are large and trumpets are annoying.
Comment: Also would like to add that luser droog makes a good point about amplitude of overtone frequencies.  Really, overtones are more important than merely speaking loudly - you can amplify a fundamental, but there will be nothing to separate that frequency from the rest of the spectrum. Audio engineers use this all the time in their work - "carving" out sound in mixes for different instruments. You can study vowel modification to change which overtones in your voice are highlighted, and therefore make your voice more recognizable in a crowded room or otherwise.
Comment: The human ear tends to perceive _midrange frequencies_ as louder than bass frequencies, but also louder than treble frequencies ([above 3 kHz, the response drops again](http://en.wikipedia.org/wiki/Equal-loudness_contours)). Which is why something white-noise-ish wouldn't really be efficient, that's rather what you get on many pop records (for a present, "close", literally breathing, yet soft sound). A "piercing" sound OTOH needs most of all strong [formants](http://en.wikipedia.org/wiki/Formant), which are in the midrange. Sure you need good breathing technique, but only as an indirect tool.
Answer: In addition to the excellent answers posted by several other people here, I would like to mention another important aspect of singing.
As a classically-trained singer, I learned about placement of the voice. This is a concept that is difficult to explain, and can only really be learned by working with a good professional voice teacher.
Just like running an electric guitar through an EQ (equalization) pedal, it is possible for a trained singer to control the tonal characteristics of the voice according to its placement. Apart from the volume or loudness of the voice, the placement of the voice has an even greater impact on whether the voice is penetrating or can "cut through" a band or orchestra. By adjusting the placement of the voice, the singer can learn to emphasize certain "EQ" frequencies (the technical term for these, in physics, is formants) that tend to allow the voice to project more clearly over a band or orchestra.
Untrained singers (like the famous rock singers Bob Dylan or Tom Petty) sing with the resonant "center" of their voice in their throat. This produces a weak sound that does not penetrate or "cut through" the sound of a band or orchestra. These singers have voices that tend to be difficult to record or amplify properly, as a result (and I mean no disrespect to their chosen techinque).
Similarly, some singers sing in their "chest voice", which is a warm resonant sound (like Frank Sinatra), and some learn to sing in their "head voice", which is less warm and more clear (this is what most operatic singers use), meaning that they can control their bodies to adjust the part of the body where the sound resonates the most. Furthermore, operatically-trained singers learn to focus the sound of the head voice more toward the back of the naso-pharyngeal passages (sinuses) or more toward the front of the sinuses, into what some teachers call the "mask", to achieve different effects. Bluegrass and American folk singers tend to use the "high lonesome" sound, which doesn't really refer to the pitches sung, per se. It has more to do with the "forward" placement of the voice up in the head and into the front of the sinuses, with little or no vibrato.
All of this has a dramatic effect on how clear and penetrating the voice sounds. If you get training, you can learn to manipulate these elements to achieve different kinds of vocal effects that are suitable for different songs and different styles of music.
Answer: I think it's worth adding to the other excellent answers, that it depends on what the background sound is.
Against a background of silence, of course any voice will be audible.
Against similar frequencies, a voice will be lost. The most obvious example, is if you're part of a choir singing in unison. Your individual voice won't be audible - it will be part of the whole. But the same goes for other sounds. If a guitar is playing in your vocal range, your voice will be lost against it.
But, against dissimilar frequencies of a similar loudness, voices can be heard quite clearly. For example, if a bass singer and a tenor duet, each voice can be clearly heard.
For this reason, musical arrangements need to make space for each sound that the composer wants to be heard clearly. If the guitar and the singer share the same frequency range, then they will either fight for the listener's attention, or mesh into one "voice".
So, work out where your voice sits in the frequency range, and try to make a "hole" in the arrangement in which your voice will fit.

How to have a penetrating voice?


$k$ divides $\binom{kn}{n}$

Question: For positive integers $k,n$ , is it true that $k$ divides $\binom{kn}{n}$?
I can write $$\binom{kn}{n}=\frac{(kn)(kn-1)\cdots(kn-n+1)}{n(n-1)\cdots 1}$$ but must the $k$ at the top remain after cancelling stuff out?
Answer: Note that $$\binom{nk}n=\frac{nk}n\binom{nk-1}{n-1}=k\binom{nk-1}{n-1}\;,$$
and $\binom{nk-1}{n-1}$ is an integer.

$k$ divides $\binom{kn}{n}$


Orthonormality of the columns of a matrix

Question: I am studying orthogonal columns and matrices right now and I have encountered the following theorem:

Theorem An $m \times n$ matrix $U$ has orthonormal columns if and only if $U^T U = 1$.

Is it even possible to have a matrix $U$ of the size $m\neq n$ here?
I ask because  $U^TU=I\iff U^T=U^{-1}$, which means $U$ must be $n\times n$.
Also, I tried using it on some examples.
For instance, let $\displaystyle y=(4,8,1), u_1=\left(\frac{2}{3},\frac{1}{3},\frac{2}{3}\right), u_2=\left(-\frac{2}{3},\frac{2}{3},\frac{1}{3}\right), W=\text{span}(u_1,u_2)$ and $U$ be the matrix formed by $u_1$ and $u_2$ as columns.
So $\{u_1,u_2\}$ is an orthonormal set (I checked it is an orthogonal set and $u_1\cdot u_1=u_2\cdot u_2 = 1$).
But I am not able to use this theorem computing $U^TU$ and $UU^T$ (i.e. $UU^T\neq I$!). I am definitely misunderstanding something here.
If $u_1\cdot u_1=1$, would $u_1$ be an orthonormal column?
Comment: $U^TU = I$ doesn't imply $U$ is invertible. Actually, $U$ can be not a square matrix. An invertible matrix must be squared.
Answer: Your mistake is that if $U$ is $m\times n$ you are always allowed to take the transpose, but $U$ is not necessarily invertible.  $U^T$ in this case is an $n\times m$ matrix, and the product $U^TU$ makes sense because you end up with an $n\times n$ matrix (an $n\times m$ matrix multiplies on the left of an $m\times n$ matrix yields an $n\times n$ matrix).  Similarly $UU^T$ also makes sense but in this case you get an $m\times m$ matrix by the same logic.
Above you wrote $U^TU = I \Leftrightarrow U^T = U^{-1}$, but this is not correct.  Just because $U^TU = I$ doesn't mean $U$ is invertible.  For invertibility you would require that $m = n$.  If the dimensions are different you are automatically guaranteed that $U$ is not invertible because it doesn't achieve full rank: at least one of its rows or columns is linearly dependent on the other rows/columns, respectively.  Even if a matrix is square ($m=n$) you only get invertibility when all of the columns (interchangeably, all of the rows) are linearly independent.
To illustrate why $U^TU = I$ implies the columns of $U$ are orthogonal, suppose that $U = \left [ \begin{array}{ccc}
u_1 & \ldots & u_n \\
\end{array} \right ]$ where $u_i$ is the $i$th column of $U$.  Then the multiplication $U^TU = I$ is equivalent to
$$
\left [ \begin{array}{c}
u_1^T \\
\vdots \\
u_n^T \\
\end{array} \right ] \left [ \begin{array}{ccc}
u_1 & \ldots  & u_n \\
\end{array} \right ] \;\; =\;\; \left [ \begin{array}{cccc}
\langle u_1, u_1\rangle & \langle u_1, u_2 \rangle & \ldots & \langle u_1, u_n\rangle \\
\langle u_2, u_1 \rangle & \langle u_2, u_2\rangle & \ldots & \langle u_2, u_n \rangle \\
\vdots & \vdots & \ddots & \vdots \\
\langle u_n, u_1\rangle & \langle u_n, u_2\rangle & \ldots & \langle u_n, u_n\rangle\\
\end{array} \right ].
$$
This above matrix being equal to the identity, is equivalent to saying that $\langle u_i, u_j\rangle = \delta_{ij}$, hence the columns are orthonormal.
Answer: Orthonormality is not a property of a vector, but rather of a set of vectors (in an inner product space):

A set $S = \{v_{\alpha}\}$ of vectors in an inner product space $(\Bbb V, \,\cdot\,)$ is orthonormal iff
  $$v_{\alpha} \cdot v_{\beta}
= \delta_{\alpha \beta} := \left\{
\begin{array}{cl}
1, & \alpha = \beta \\
0, & \alpha \neq \beta
\end{array}
\right.$$
  (for all $\alpha, \beta$ in the index set).

It is certainly possible to have a nonsquare matrix with orthonormal columns: Given any unit length vector $v \in \Bbb R^n$, $n > 1$, the columns of the $n \times 1$ matrix $\pmatrix{v}$ trivially comprise an orthonormal set. (The flaw in the reasoning in the question is that it assumes the existence of an inverse of the matrix, and this really does require the given matrix to be square.)
On the other hand, one can show easily that an orthonormal set (or even just an orthogonal one) is linearly independent, so an orthonormal set cannot contain more elements than the dimension of the given inner product space; in particular, if the columns of a $m \times n$ matrix are orthonormal, we must have $m \geq n$.


Using the Facebook PHP SDK inside a Cake PHP Application

Question: I am looking for advice and guidance on how to use the Facebook PHP SDK inside my Cake PHP application.
I have read articles (one or 2 on SO) around adding the Facebook PHP SDK as a Vendor Package, but after consulting the Cake Cook Book:
http://book.cakephp.org/2.0/en/development/vendor-packages.html
It appears that support for vendor packages has been removed and that the preferred method is to repackage the functionality as a plugin.
Can you please advise me on how to do this. Best case would be a working example of how to return data to my Cake PHP application after providing the plugin with some parameters:

Method: eg. FQL
Query: Eg. SELECT  eid, name, description,
start_time, end_time, location, venue, pic_cover FROM event WHERE eid
= xyz
access token: 'App ID | Secret Key'

Just worth mentioning, I have in the past developed client side jquery plugins that uses the Facebook Javascript SDK. Essentially I am looking to build a server side equivalent of this and implement it inside my CakePHP application
Answer: I can see that you are using CakePHP 2. Recently i worked on a facebook application using SDK version 5 which uses Namespace . What i did to load the SDK in my controller is , modified the Bootstrap file to include libraries using Namespace .
in /app/Config/bootstrap.php added following code :
spl_autoload_register(function ($class) {

    foreach (App::path('Vendor') as $base) {

        $path = $base . str_replace('\\', DS, $class) . '.php';

        if (file_exists($path)) {

            include $path;

            return;

        }

    }

});

Then i placed the Facebook Sdk in /app/Vendor/ directory .
I could successfully load the Facebook library in my controller as follows:
function login(){
    session_start();
    App::import('Vendor','Facebook',array('file'=>'Facebook'.DS.'Facebook.php'));
    $this->fb = new Facebook\Facebook([
      'app_id' => 'YOUR APP ID',
      'app_secret' => 'APP SECRET',
      'default_graph_version' => 'v2.5',
    ]);
    $helper = $this->fb->getRedirectLoginHelper();
    $permissions = ['email', 'user_likes','publish_actions','manage_pages','publish_pages','read_page_mailboxes','pages_show_list','pages_manage_cta']; // optional
    $loginUrl = $helper->getLoginUrl('Your Callback URL', $permissions);

    echo 'Log in with Facebook!';
    exit;
}

You can see the same steps in my blog too . Loading Facebook SDK in CakePHP2
Answer: Importing vendor libraries is still supported, the (not very detailed) documentation is about vendor assets (CSS, JS, images, etc).
Assuming the Facebook PHP SDK folder is placed in /app/Vendor/, import the library as described in the Cook Book:
App::import('Vendor', 'Facebook', array
(
    'file' => 'facebook-php-sdk' . DS . 'src' . DS . 'facebook.php'
));

and then use it as shown in the SDK examples and tests:
$facebook = new Facebook(array(
    'appId'  => 'YOUR_APP_ID',
    'secret' => 'YOUR_APP_SECRET',
));
$response = $facebook->api(array(
    'method' => 'fql.query',
    'query' => 'SELECT eid, name, description, start_time, end_time, location, venue, pic_cover FROM event WHERE eid = xyz',
));


SnapKit snp can't assign to UIHostingController

Question: On many of projects I use SnapKit. And on new project too. On project I have ViewController which connected with SwiftUI view:
class OfficeListViewController: UIViewController {
 override func viewDidLoad() {
   super.viewDidLoad()
   let vc = UIHostingController(rootView: OfficeListView())
   addChild(vc)
   view.addSubview(vc.view)
   vc.didMove(toParent: self)
   vc.view.translatesAutoresizingMaskIntoConstraints = false

   // Here I want to set constraints to vc
   vc.snp // throws error: Value of type 'UIHostingController<OfficeView>' has no member 'snp'
 }
}

struct OfficeListView: View {
  var body: some View {
    Text("View")
  }
}

But it throws error:

Value of type 'UIHostingController' has no member 'snp'

How to correctly use SnapKit with it?
Comment: `UIHostingController` is just subclass of `UIViewController`. I don't know what do you mean by `vc.snp`, but if you want to set up constrains then use `vc.view` as usually we do.
Answer: The UIHostingController is just subclass of UIViewController and it renders SwiftUI view inside regular UIView. If you want to set up constrains, then you should use vc.view as we usually do with views.


Nginx not parsing PHP

Question: So I can't remember what I did, but for some reason I cannot get PHP to be parsed anymore. What would be the basic troubleshooting steps to check on this? I have php5 installed and nginx running but when I, for example, create a phpinfo page, the raw php is displayed on the website. I'd like to know how to really 'activate' php and make sure it can make a successful connection with nginx to serve up pages with php content. I am referring to a linux CLI environment, in case that was unclear.
Answer: nginx doesn't bundle itself with PHP support.  To "enable" PHP, you have to let your webserver know how to handle the packages.  This is where PHP-FPM comes in.
Using whatever package manager is appropriate for your OS, install FPM (e.g. apt-get install php5-fpm), give it a configuration file, then reload nginx.
Here's my /etc/nginx/nginx.conf to get you started:
user  nginx;
worker_processes  1;
pid        /var/run/nginx.pid;

events {
    worker_connections  768;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;
    access_log  /var/log/nginx/error.log  main;

    sendfile                on;
    tcp_nopush              on;
    tcp_nodelay             on;

    keepalive_timeout  10;
    types_hash_max_size 2048;
    server_tokens off;

    ssl_session_cache       shared:SSL:10m;
    ssl_session_timeout     10m;
    ssl_ciphers     HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

        open_file_cache          max=5000  inactive=20s;
        open_file_cache_valid    30s;
        open_file_cache_min_uses 2;
        open_file_cache_errors   on;

    #php cache
    #mkdir /var/cache/nginx; chown nginx:nginx /var/cache/nginx;
    #consider doing a tmpfs if memory allows - VPS disk speed is hardly robust
    fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=microcache:10m max_size=1000m inactive=60m;

    #consider turning off if CPU thrashing
    gzip  on;
    gzip_static on;
    gzip_disable "msie6";
    gzip_http_version 1.1;
    gzip_vary on;
    gzip_comp_level 6;
    gzip_proxied any;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript text/x-js;
    gzip_buffers 16 8k;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

Answer: nginx doesn't have built in support for PHP, as Apache does via mod_php.
To get PHP scripts running you should research the use of FPM.
Answer: You need to check you have all the relevant packages installed. It might be that you accidentally deleted something, or missed something.
Try cleaning up, and starting again.
Check out this link, it has the basic packages and set up required to get you started again

Nginx not parsing PHP


Custom submit handler for theme settings form

Question: I am creating a new D8 theme and having slideshow functionality in it. For slideshow, we have title, description and image field in the theme settings form. I am able to alter the theme setting form using THEME_NAME_form_system_theme_settings_alter, but when I add a custom submit handler the form seems to break and get internal server error.
My objective for adding custom submit is to make the uploaded files status as permanent.
Here is my code,
function THEME_NAME_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  // $form['#submit'][] = 'custom_settings_form_submit'; //tried this as well
  $form['actions']['submit']['#submit'][] = '_custom_settings_form_submit';
}

function _custom_settings_form_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $account = \Drupal::currentUser();
  $values = $form_state->getValues();
  for ($i = 0; $i <= SLIDESHOW_COUNT; $i++) {
    if (isset($values['slide_image_path' . $i]) && !empty($values['slide_image_path' . $i])) {
      // Load the file via file.fid.
      $file = file_load($values['slide_image_path' . $i][0]);
      // Change status to permanent.
      $file->setPermanent();
      $file->save();
      // $file_usage = \Drupal::service('file.usage');
      // $file_usage->add($file, 'user', 'user', $account->id());
    }
  }
}

NOTE:
This is the error present in apache error log:
PHP Fatal error:  Invalid placeholder (!message) in string: %type: !message in %function (line %line of %file). in /core/lib/Drupal/Component/Render/FormattableMarkup.php on line 240
Does anyone have any idea where I'm doing it wrong? or is there any workaround for making the file status permanent?
Comment: Check watchdog, you'll see what the replacements mean.
Comment: That was the first thing I checked, but there was nothing regarding this, then only I looked at apache log.
Comment: Check the DB directly.
Comment: Possible duplicate of [How do I save a file with managed\_file in a theme?](http://drupal.stackexchange.com/questions/186982/how-do-i-save-a-file-with-managed-file-in-a-theme)
Answer: From Drupal 8: Use Custom Submit Handler for Theme Settings Form:
Use this method to add custom submit handler for theme settings form in drupal 8.
/**
 * Implements hook_form_system_theme_settings_alter().
 */
function MY_THEME_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $theme_file = drupal_get_path('theme', 'MY_THEME') . '/MY_THEME.theme';
  $build_info = $form_state->getBuildInfo();
  if (!in_array($theme_file, $build_info['files'])) {
    $build_info['files'][] = $theme_file;
  }
  $form_state->setBuildInfo($build_info);

  $form['#submit'][] = 'MY_THEME_form_system_theme_settings_submit';
}

function MY_THEME_form_system_theme_settings_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  // TODO: Extra submssio logic.
  // This submit handler will be called before default submit handler for this form.
}


VS Webpack Task Runner - how to bind run tasks to Debug and Release

Question: In the Visual Studio Task Runner Explorer, I can bind 'Run - Development' to 'After Build' and this works very well. I can also bind 'Run - Production' to 'After Build' and this will also work.
What I want to be able to do, is have 'Run - Development' execute when I'm in Debug mode, and have 'Run - Production' execute when I'm in Release mode.
How do I make this happen?
Comment: Although the response from @VinTem below is marked as the answer I would prefer to have an integrated solution in the Task Runner itself. There really needs to be some way to setup bindings that pertain to Debug, Release, or any other configuration.
Answer: There's a nuget package that you can install that allows you to run npm commands.
Then you can add two different commands to your package.json file, like so:
"scripts": {
  "webpack": "webpack",
  "webpack-prd": "webpack -p"
},

After having the nuget package installed you edit your .csproj file to run the npm commands configured. Here's how I did:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
  <NpmCommand>run webpack</NpmCommand>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
  <NpmCommand>run webpack-prd</NpmCommand>
</PropertyGroup>


Facing Auto Merge failure after teammate amends his changes

Question: I'm facing an issue while working with git.
Scenario:
Me and my teammate is working on a code. Say it has 2 files.
File-1
File-2

Suppose on Day 1 we both have code at same level, say Commit-0.
On day 2, my team mate pushed some changes in File-1. This is commit-1.
On day 3, I want to make some changes in File-2, but before that I take a pull to get latest changes. So my code is now at commit-1.
I'm in process of making some changes in File-2 and have not pushed them yet.
On day 3 only, my team mate makes some more changes in File-1, but instead of pushing them as new commit, he uses amend & edits his original commit-1, say the new commit is now commit-1.1
On day 4, now I want to push my changes in File-2. But just to be sure that there are no conflicts, I stash my changes and then run git pull.
As soon I do this, I'm getting Auto merge fail in File-1.
For me it is difficult to do manual merge as I don't have idea what is being done in File-1.
For now I'm exporting my stash in a .patch. Then take a fresh checkout of latest code and then apply patch changes, which is a very bad solution.
Please suggest what should I do in this case?
Answer: Reset your local branch to the remote state to start again from your coworker's last amended commit, and apply your stash on that. (Might as well backup your local branch first.)
git branch backup_local
git reset --hard @{upstream}
git stash apply

Then resolve conflicts if any.


Docker build does not see existing bash script and can't run it

Question: I'm trying to build a docker container for a tool named DECoN (versin 2.0.0). To do so, I'm doing these steps:

start FROM the latest bash image
RUN the download of the tool's source code and extract it
set the WORKDIR to the tool's ./Linux subdirectory
RUN the existing setup.sh script that is found within the Linux subdirectory.

# syntax=docker/dockerfile:1

# start from a bash image
FROM bash:latest

# download files
RUN wget https://github.com/RahmanTeam/DECoN/archive/refs/tags/v2.0.0.tar.gz && \
    tar -xf v2.0.0.tar.gz

# go to directory
WORKDIR DECoN-2.0.0/Linux

# run setup script
RUN setup.sh

# check directory content
RUN ls

You can see the existence of the script with the last RUN ls. However, the script is not found and the docker build returns the following error:
docker build -t decon:2.0.0 .

...

/bin/sh: setup.sh: not found
The command '/bin/sh -c setup.sh' returned a non-zero code: 127

Do you have any idea what I'm doing wrong? I don't understand why the script is not found. I have tried setup.sh, ./setup.sh, /DECoN-2.0.0/Linux/setup.sh, but nothing works.
EDIT #1: This is the content of the bash script:
#!/bin/bash

Rscript sessionInfo.R > setup.log 2>&1

Answer:
RUN ./setup.sh is the correct way to run a shell script in the current WORKDIR. You can only use RUN setup.sh if the script is on the path.

ls -al will confirm if the file has r-x permissions for the appropriate users. otherwise you will need to RUN chmod +x setup.sh to ensure it can be executed.

As you are using bash:latest is it unlikely that the script references a shell that is not present, but if the first line of the .sh file references a shell that's not present, it will return an error. i.e. If its #!/bin/ash then ensure that ash is actually present.

Again, as you are downloading and unzipping in the container, this is unlikely, but if the zip file has been processed on a windows computer, there may be CRLF line endings in the .sh file. As Linux only recognises LF this means it processes #!/bin/bash<CR><LF> as an instruction to execute the shell /bin/bash<CR> which does not exist. Download the file and check it in an editor (VSCode) that can tell you the ending style.
Comment: I've edited the main post with the content of the bash script. It seems ok, without special characters.
Comment: Running `file` returns `setup.sh: Bourne-Again shell script, ASCII text executable`
Answer: To debug this kind of problems, run the base image and execute the commands of the Dockerfile by hand on the prompt:
docker run -it --rm bash:latest
wget https://github.com/RahmanTeam/DECoN/archive/refs/tags/v2.0.0.tar.gz
tar -xf v2.0.0.tar.gz
cd DECoN-2.0.0/Linux
./setup.sh

The last line fails because, as you have noted, it runs Rscript which is not present in your (very minimal) base image.  Rscript belongs to the R language so I have tried again with the official R base image:
docker run -it --rm r-base:latest bash
wget https://github.com/RahmanTeam/DECoN/archive/refs/tags/v2.0.0.tar.gz
tar -xf v2.0.0.tar.gz
cd DECoN-2.0.0/Linux
./setup.sh

This time the script runs and creates the following setup.log:
# Bootstrapping renv 0.15.4 --------------------------------------------------
* Downloading renv 0.15.4 ... OK
* Installing renv 0.15.4 ... Done!
* Successfully installed and loaded renv 0.15.4.
Error: package 'BiocManager' is not available
In addition: Warning messages:
1: This project is configured to use R version '4.2.0', but '4.3.1' is currently being used.
2: could not retrieve available packages for url 'https://cran.ma.imperial.ac.uk/src/contrib'
Traceback (most recent calls last):
20: source("renv/activate.R")
19: withVisible(eval(ei, envir))
18: eval(ei, envir)
17: eval(ei, envir)
16: local(...)
15: eval.parent(substitute(eval(quote(expr), envir)))
14: eval(expr, p)
13: eval(expr, p)
12: eval(quote(...), new.env())
11: eval(quote(...), new.env())
10: renv::load()
 9: renv_load_bioconductor(project, lockfile$Bioconductor)
 8: renv_bioconductor_init()
 7: renv_bioconductor_init_biocmanager()
 6: install("BiocManager")
 5: retrieve(names(remotes))
 4: handler(package, renv_retrieve_impl(package))
 3: renv_retrieve_impl(package)
 2: stopf("package '%s' is not available", package)
 1: stop(sprintf(fmt, ...), call. = call.)
Execution halted

The warning about the wrong version of R can be avoided by using r-base:4.2.0 instead of r-base:latest (recommended to be safe) but the error message package 'BiocManager' is not available persists.
The URL referenced in the log is still valid and BiocManager is a package that must be installed within R.  Since I'm not an expert of R, I stop my analysis here hoping it helps.
UPDATE: Searching in Docker Hub I found some ready-made images that reference RahmanTeam/DECoN in the Dockerfile:

https://hub.docker.com/r/stefpiatek/decon
https://hub.docker.com/r/nderoo324/decon/tags

This one explictly installs BiocManager:

https://hub.docker.com/r/euformatics/decon/tags

Other images could exist.
Comment: I'm very glad it helped. If you complete your work you could publish the resulting image on Docker Hub and add a link to it in a comment here for future reference.
Comment: Thank you, this was extremely helpful. It definitely made me reach a further point in the debugging, and I think I can take it from here. The docker hub images were my first attempt, but they reference an older version of the tool as far as I know. Thanks anyway for looking there too, really!


Can we show that the supremum of the following functional over the unit sphere in $C^0[0,1]$ is $1$?

Question: Consider the following functional (Luenberger ''Optimization by Vector Space Methods", p40) defined on $C^0[0,1]$:
$$f(x)=\int_0^{1/2}x(t)dt-\int_{1/2}^1x(t)dt$$
We are interested in its supremum over the unit sphere $S(0,1)\doteq \big\{x\in C^0[0,1]: ||x||=1\big\}$. Here the norm is the usual one for $C^0[0,1]$, i.e. $||x||\doteq \sup_{0\leq t \leq 1}|x(t)|$.
I can show that $|f(x)| \leq ||x||$. Hence, an upper bound of $f(x)$ over the unit sphere is $1$. Luenberger claims that the supremum is also $1$. I just wonder how to prove it? Thank you!
Answer: Hint: If $x=1$ on $[0,1/2),$ $x=-1$ on $(1/2,1],$ then $f(x)=1.$ That's not possible of course, but you can get close to it.
Comment: Thank you @zhw for your prompt reply. Did you mean that we can construct continuous approximations that approach to the function you described?
Comment: Compute $f$ of the function whose graph is the line joining $(0,-1), ({1 \over 2}-{1 \over n}, -1), ({1 \over 2}+{1 \over n}, 1), (1,1)$. Let $n \to \infty$.
Comment: @camio Yes, that was what I meant.


Why I can't use the same code from Drupal 7 in Drupal 8 to generate a button with FAPI?

Question: Following the question Generating <button type="submit"> with the form API for Drupal 7 I tried to implement the same thing in Drupal 8.
I need the following output:
<button type="submit" class="clearfix">Login</button>

So I tried to use this code:
$form['submit'] = array(
  '#prefix' => "<button type ='submit'>",
  '#suffix' => "</button>",
  '#type' => 'markup',
  '#markup' => "" . t('Login') . "",
);

But I obtain this:
Login

But if I use this code:
$form['submit'] = array(
  '#prefix' => "",
  '#suffix' => "",
  '#type' => 'markup',
  '#markup' => "" . t('Login') . "",
);

I obtain this:
Login

So the <button> tag is eliminated but the  tag not. Very strange for me, the Button is not rendered.
Thanks to @Kevin I used the leymannx answer an with this code I solve the problem:
$form['submit'] = [
  '#type' => 'inline_template',
  '#template' => '<button type="submit" class="glyphicon glyphicon-search"></button>',
];

But, why I can't use the same code in Drupal 7 and Drupal 8 to generate a button with FAPI?
Comment: @Kevin thanks, yes the leymannx answer (http://drupal.stackexchange.com/a/230031/28275) solve my problem, I will edit my question to see if we can find why this has changed.
Comment: @AdrianCidAlmaguer don't forget to up vote laymannx ;-)
Comment: Have you tried adding the span to your prefix and suffix? `""` ...  What's the point of the span anyways? are you trying to inline stuff?
Comment: Check that link for two potential solutions
Comment: @NoSssweat The front-end developper want this "Login" in the page, but if you use the code that works in Drupal 7 it doesn't works in Drupal 8.
Comment: @Kevin I changed the question.
Comment: @NoSssweat I changed the question
Comment: After that duplicate flag was raised, I edit the question and the new question is not a duplicate.
Answer: The reason why it is not working in Drupal 8 as in Drupal 7 is, that prefix and suffix are passed to xssFilterAdminIfUnsafe() function in doRender() function. Thus preventing all tags except the tags specified in $adminTags.
Excerpt from doRender:
  // We store the resulting output in $elements['#markup'], to be consistent
  // with how render cached output gets stored. This ensures that placeholder
  // replacement logic gets the same data to work with, no matter if #cache is
  // disabled, #cache is enabled, there is a cache hit or miss.
  $prefix = isset($elements['#prefix']) ? $this->xssFilterAdminIfUnsafe($elements['#prefix']) : '';
  $suffix = isset($elements['#suffix']) ? $this->xssFilterAdminIfUnsafe($elements['#suffix']) : '';

  $elements['#markup'] = Markup::create($prefix . $elements['#children'] . $suffix);

You can use '#allowed_tags' property to enable specific tags. So this should work:
  $form['submit'] = array(
  '#type' => 'markup',
  '#markup' => "<button type ='submit'>" . t('Login') . "</button>",
  '#allowed_tags' => ['button', 'span'],
  );

But '#allowed_tags' property will not work for '#prefix' and '#suffix'.


Create Git branch feature/x/y?

Question: I currently have a Git branch feature/i18n which I am using to create different localizations of my app. I want to create a sub-branch for each language so I can integrate them separately. Is it possible to create sub-directories, e.g. feature/i18n/French or feature/i18n/Spanish, so they are more easily organized? I am getting the following error message from Git: error: unable to resolve reference refs/heads/feature/i18n/spanish: Not a directory.
Comment: @DaveNewton: The heads of the branches are organized in folders inside `.git/refs/heads`
Comment: I thought branch names were just that, names.
Comment: Yes, you can. I have no idea why you are getting that error.
Comment: @DanielHilgarth Oh, I see. I use names like this all the time; I guess I just never noticed an issue. Thanks for the info.
Comment: Just a comment - I don't quite understand why would you want to create branches for every language instead of just committing them to master.
Answer: Yes, you can create those branches. The problem preventing you from sub-dividing your i18n namespace, so to speak, is that you already have the feature/i18n branch.
Every branch is created as a file under .git/refs/heads, so when you created your branch, Git created the file .git/refs/heads/feature/i18n.
Now you're trying to created .git/refs/heads/feature/i18n/spanish, for which git tries to create an i18n folder -- which it can't, because there is a file of the same name.
To create those "sub-branches", you'll have to delete or rename your feature/i18n branch.
Answer: you have created a branch feature/i18n
That means you have created a file by name
feature/i18n.
Now
to create a file feature/i18n/spanish, i18 must be a Directory.
To fix this delete  feature/i18n branch and create  feature/i18n/spanish

Create Git branch feature/x/y?


General Relativity and the Wave Equation

Question:
Suppose that u is a function on space-time. We can define a vector field with components $\triangledown^a u = g^{ab}\partial_b u$.

Why have they chosen $g^{ab}$ and not $g_{ab}$ here?

The wave operator sends $u$ to

$$\square u = \triangledown_a(\triangledown^a u)$$
Why here does you use superscript $a$ first and then subscript $a$?
Answer: In special and general relativity, whether an index is a subscript or superscript matters. We replace the invariant infinitesimal squared length in Euclidean spacetime expressible in terms of Cartesian coordinates viz. $\sum_a dx_a^2$ with a more general quadratic function, which requires us to introduce a square matrix viz. $ds^2=g_{ab}dx^adx^b$. From this we get something that satisfies all inner product axioms, except for positive definiteness; in fact the positive and negative eigenvalues of $g_{ab}$ (this matrix is called the meric tensor) represent space and time (which way round depends on which of two conventions you use). You always sum over two matching indices at different heights; this is called contraction. You can use the metric or its inverse to change the index height, as in your first equation. Note in particular that $\partial_b u=g_{bc}\nabla^c u$.
Comment: ok I will do that tomorrow
Comment: Sorry but how does this answer the question?
Comment: @Permian First you asked why we used $g^{ab}$ instead of $g_{ab}$; because $g_{ab}\partial_b u$ doesn't make sense. Then you asked why we write $\nabla_a\nabla^a u$, rather than both indices being downstairs; because that would also not make sense.
Comment: i think my key question is why dont they make sense?
Comment: @Permian What do you imagine $g_{ab}\partial_b u$ would mean? How do you expect it transforms under coordinate transformations?
Comment: What is the underlying structure of $g^{ab}$ and $\partial_b u$?
Comment: @Permian What do you mean by underlying structure? Bear in mind $g^{ab}g_{bc}=\delta^a_c,\,\partial_b=\frac{\partial}{\partial x^b}$.
Comment: Well why wouldnt $g_{ab}\partial_b u$ make sense then? Just because $g^{ab}g_{bc}=\delta^a_c,\,\partial_b=\frac{\partial}{\partial x^b}$ doesnt necessarily mean that the $g_{ab}\partial_b u$ invalid.
Comment: @Permian I want you to have a series think about what it would mean, though. Effectively it means $g_{ab}g_{bc}\partial^c$, but how do you expect that to behave? How could a universal physical law even contain it?


Solve the i.v.p DE

Question: Solve the i.v.p $y^{(4)}-y'''=0 , y(0)=0, y'(0)=0, y"(0)=0, y"'(0)=0$
Would I use the formula $a^{(1/n)}=R^{(1/n)}e^{(e^{i(alpha+2k(\pi))/n})}$
Answer: I don't think so! In fact you should set an axillary equation regarding to the OE as $$m^4-m^3=0$$ and so solve it: $$m=0,~~~\text{3 times}~~~m=1$$ and then write the proper solution as $$y=C_1+C_2x+C_3x^2+C_4\text{e}^x$$ Now put the initial conditions. I don't think you get another one but the Andrea's one.
Comment: @Amzoti: Thanks >8-).
Comment: Nice work, Babak!
Comment: @BabakS.:Excellent❁You are the best teacher ✓
Comment: @flashdesign2550: Manunam.:)
Comment: @BabakS.:(◕‿◕)khahesh mikonam.man mamnunam.
Answer: There is no calculation needed. The family of solutions consists of linear combinations of $4$ functions. The initial conditions make all the constants $0$, so the solution is the identically $0$ function.
Another way of thinking about it is that the solution of the initial value problem is unique. But identically $0$ works, so it is the only solution.
Comment: Ok But how would I work that out to prove that...?
Comment: You can quote the uniqueness result, which has probably already been covered. If you want to do it the long long way, the characteristic equation has the triple root $0$, and a root of $1$. So the solutions are $A+Bx+Cx^2+De^x$. Now use the initial conditions to show that $A=B=C=D=0$. But that's too much work!
Comment: You are welcome. The question you were asked is a *conceptual* one. It can be solved by a calculation, but it follows immediately from knowledge of the nature of solutions of homogeneous linear DE with constant coefficients.
Comment: We went over the Characteristic Eqn. briefly earlier this semester. And I don't think I remembered because I was not so much of a fan of that particular concept.
Comment: It will be useful to become a fan. You are likely to be asked a question on the exam about it. And there are quite a number of applied settings where one needs it, specially in the second-order case.
Comment: Yes! Which is why I am trying to figure out a lot of this stuff now. I'm picking different homework problems that I have been working on.

Solve the i.v.p DE