SSH Tunnel: channel 3: open failed: administratively prohibited

Question: I have two servers, let's say server A and server B. I wish to use server B as an ssh tunnel so on server A I did this
ssh -D 1080 root@ip

It connects and as soon as I put in the server B as a SOCKS5 proxy on my server A, the server B comes up with this erorr:
channel 3: open failed: administratively prohibited

Some how if I get server B from a host like vultr, I don't get this error but if I get it from digitalocean I get this error. I did some research and saw I should allowtcpforwarding to be yes but I could not find it in /etc/ssh/ssh_config
This is my ssh_config file:
# Host *
#   ForwardAgent no
#   ForwardX11 no
#   RhostsRSAAuthentication no
#   RSAAuthentication yes
#   PasswordAuthentication yes
#   HostbasedAuthentication no
#   GSSAPIAuthentication no
#   GSSAPIDelegateCredentials no
#   GSSAPIKeyExchange no
#   GSSAPITrustDNS no
#   BatchMode no
#   CheckHostIP yes
#   AddressFamily any
#   ConnectTimeout 0
#   StrictHostKeyChecking ask
#   IdentityFile ~/.ssh/identity
#   IdentityFile ~/.ssh/id_rsa
#   IdentityFile ~/.ssh/id_dsa
#   IdentityFile ~/.ssh/id_ecdsa
#   IdentityFile ~/.ssh/id_ed25519
#   Port 22
#   Protocol 2
#   Cipher 3des
#   Ciphers aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc
#   MACs hmac-md5,hmac-sha1,email@example.com,hmac-ripemd160
#   EscapeChar ~
#   Tunnel no
#   TunnelDevice any:any
#   PermitLocalCommand no
#   VisualHostKey no
#   ProxyCommand ssh -q -W %h:%p gateway.example.com
#   RekeyLimit 1G 1h

Would appreciate if someone could tell me what am I doing wrong :3
Answer: The config file you need to edit is called sshd_config you wrote ssh_config. What you have listed looks like the contents of the ssh client default configuration, not the config for the ssh server (/etc/ssh/sshd_config)
Answer: What you list is just the default values, commented out.
So you can add, below a Host * something like:

AllowTcpForwarding local

Note that yes should be the default, so it is strange it does not work. You can add more verbosity with ssh -v or -vv or -vvv and have a look at your server sshd logfile that should provide more information on what is wrong.
Comment: Nope still can't get it to work, I added that line but it reproduces the same error.
Comment: What do you have in logfiles?
Answer: You likely need to set AllowTcpForwarding yes in the sshd_config on the server to allow this to happen.
Answer: First, check for entries in /var/log/secure for something like this;
Feb  1 19:59:58 vps001 sshd[30375]: error: connect_to
www.somenonexistingdomain.com: unknown host (Name or service not known)

second, check whether selinux is blocking; (if you are RedHat based))
$ sudo ausearch -m avc -c httpd
----
time->Sat Jan  6 08:58:11 2018
type=AVC msg=audit(1515229091.030:7212): avc:  denied  { map } for  pid=20581 comm="httpd" path="/var/

you can test and disable selinux like so;
[~] $ sudo getenforce
Enforcing

[~] $ sudo setenforce Permissive

[~] $ sudo getenforce
Permissive

then test and see if it is now working.
[~] $ sudo setenforce Enforcing

I get the open failed: administratively prohibited behaviour if the server cannot connect to the site you are requesting on the other side.
For example, if I send a request for www.somenotexistingdomain.com via a socks 5 proxy ssh -S none  -D1083 -vvv  my.cheap.vps.com, it results in this output;
debug1: Connection to port 1083 forwarding to socks port 0 requested.
debug2: fd 10 setting TCP_NODELAY
debug2: fd 10 setting O_NONBLOCK
debug3: fd 10 is O_NONBLOCK
debug1: channel 4: new [dynamic-tcpip]
....
debug2: channel 4: dynamic request: socks5 host www.somenonexistingdomain.com port 80 command 1
debug3: send packet: type 90
debug3: receive packet: type 92
channel 4: open failed: administratively prohibited: open failed
debug2: channel 4: zombie
debug2: channel 4: garbage collecting
debug1: channel 4: free: direct-tcpip: listening port 1083 for www.somenonexistingdomain.com port 80, connect from 127.0.0.1 port 42598 to 127.0.0.1 port 1083, nchannels 22

and you can see that it cannot connect.
If you are sure that the server you are trying to access exists; For example, first test that you can wget or curl the site from the command line remotely.
$ wget -S -O - www.bbc.co.uk > /dev/null
Resolving www.bbc.co.uk (www.bbc.co.uk)... 188.8.131.52, 188.8.131.52
Connecting to www.bbc.co.uk (www.bbc.co.uk)|220.127.116.11|:80... connected.
HTTP request sent, awaiting response...
HTTP/1.1 301 Moved Permanently
Server: nginx

If that doesn't work, then its possible that if you are forwarding to the proxy DNS, is that the remote server cannot resolve the DNS. So check that;
$ dig www.bbc.co.uk +short
www.bbc.net.uk.
22.214.171.124
220.127.116.11

and also check direct connection to the port using netcat, telnet etc. however pulling the site with wget should have tested both tcp connection and DNS.
$ telnet www.bbc.co.uk 80
Trying 22.214.171.124...
Connected to www.bbc.co.uk.
Escape character is '^]'.

and definitely check the entries in the /var/log/secure file.
Failing that turn logging right up (ssh -vvvvvvv) and watch both sides of the connection.


Linear dependence and independence of vectors

Question: Let $v_1 = (−1,−1,1,0)$ and $v_2 = (3,0,3,1)$ be two vectors in $\Bbb R^4$. (a) Find a vector $v$ such that the set $\{v_1,v_2,v\}$ is linearly independent. (b) Find real numbers $s,t \in\Bbb R$ such that the vector $v = (−2,1,s,t)$ is a linear combination of $v_1$ and $v_2$.
The solution I think (a) $v=(n,n,0,0),n\in\Bbb Z$
(b) $s,t = (-3,-1)$.
Please let me know if I'm wrong
Comment: Welcome to the website! Can you type out your solution briefly so that we can check? Use [Mathjax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to format your math equations.
Comment: Thank you! I'll look into Mathjax after this.  The solution i think a) (n,n,0,0) Where n can be any Integer.         b) s,t = (-3,-1).  Please let me know if I'm wrong
Comment: Yes, that is a possible choice for $v$. Note that you need to mention $n\ne0$. And what about part b?
Comment: I edited my comment. Could you please read again
Comment: Your question earlier was lacking context, details like where you found this question, what you tried and where you were stuck. That is why it got downvoted by the community. Now I have added your proposed solution to the body of your question and upvoted the question to counter-act the downvote. Make sure to add your effort in future.
Answer: Your solution to part $(a)$ is almost correct. In order for $v_1,v_2,(n,n,0,0)$ to be linearly independent, $n\ne0$ otherwise $v=0$. You can check that$$\begin{bmatrix}-1&-1&1&0\\3&0&3&1\\n&n&0&0&\end{bmatrix}$$is a full rank matrix for $n\ne0$ by performing the row operations $R_2\to R_2+3R_1,R_3\to R_3+nR_1$ to get
$$\begin{bmatrix}-1&-1&1&0\\0&-3&6&1\\0&0&n&0&\end{bmatrix}$$

Let $(-2,1,s,t)=av_1+bv_2=a(-1,-1,1,0)+b(3,0,3,1)$.
So we have $-a+3b=-2,-a+0b=1$. We get $a=b=-1$.
So $s=a+3b=-4,t=b=-1$.
Comment: Yup, -4 and -1 I did a typo up there. I'll be more careful. Thanks!
Comment: If this answered your question, consider accepting my answer by clicking the tick mark next to it. You are welcome @LightoK!


IIS7.5: HTTPS->HTTP 302 redirect

Question: I have an asp.net website running on IIS7 configured long ago. There appears to be a 302 redirection in place redirecting all requests over HTTPS to HTTP instead. I would like to remove this redirect so we can serve the site over HTTPS.
Specifically, when testing with curl, requesting any page "https://WebSite.com/SomeThing" redirects to "http://website.com/something" (insecure, case not maintained). The only request that is not redirected to HTTP is the bare domain, which goes to Default.aspx before redirecting to HTTP. Some examples:
https://www.website.com -302-> Default.aspx
https://www.website.com/Default.aspx -302-> http://www.website.com/default.aspx
https://website.com/Default.aspx -302-> http://website.com/default.aspx
https://website.com/ABOUTUS.aspx -302-> http://website.com/aboutus.aspx

I can't figure out where this redirect is configured. In IIS Manager, I've checked the "HTTP Redirect" module (not enabled), the "URL Rewrite" module (not installed), and the SSL Settings ("Require SSL" is NOT set). I've searched the contents of all *.aspx files in the web root for "redirect" or "rewrite", and not found anything. Ditto for web.config.
Where else could this redirect be hiding? Host is Windows Server 2008 R2 running within an Azure VM.
Comment: "I can't figure out where this redirect is configured." Then it is very likely to come from the web app itself (source code). You can enable FRT on 302 to analyze further, https://docs.microsoft.com/en-us/iis/troubleshoot/using-failed-request-tracing/troubleshooting-failed-requests-using-tracing-in-iis
Answer: One more thing to check is ISAPI Filters on server and site level.
You should see the ASP.Net filter.dlls there, but there may be additional entries.
Some people use a mod-rewrite DLL which is a port of the Apache mod-rewrite module. There may be an ini file in the same directory as the DLL.
Otherwise I would look carefully at:

C:\WINDOWS\system32\inetsrv\config\ApplicationHost.config

look for anything that seems suspicious or may relate to your problem.
Answer: The comment from Lex Li got me moving in the right direction.
In addition to the ASP.net code, there was also C# code which was not in the webroot. MasterPage.master.cs had the redirect.

IIS7.5: HTTPS->HTTP 302 redirect


Creating two package inside one package in intellij

Question: I'm working on Intellij IDEA about java project. However, I see a problem when I want to create new packages.So, my problem is:
>Package1
 >Package2 // (there is a problem in here)
  >Package3

When I want to create third package, it shows Package2.Package3, but my expected look like:
>Package1
 >Package2
  >Package3

Is there any way to make that?
Comment: In Project tab (left side) you can find a settings like icon called **Show option menu**.. Inside this menu turn off the **Flatten Packages**!
Comment: click on  button `show option menu` (which is next to hide button  where your code files are shown) and un-select Flatten packages.
Comment: You probably want to un-check "flatten packages". It's located in the project configuration menu (gear symbol)
Answer:
In Project tab (left side) you can find a settings like icon called
Show option menu.. Inside this menu turn off the Flatten Packages

You can also uncheck/turn off the Compact Middle Packages just below it, that did it for me
Answer: If you examine the actual folder structure, you will in fact see that folder Package2 has a subfolder called Package3.  IntelliJ is just displaying things this way as an abbreviation.  If you add something else to Package2, e.g. another folder or a file, you should no longer see the entry Package2.Package3, but rather you should see the folder structure you expect.


Uniform Distribution and Probability

Question:
A student has the opportunity to take a test at most thrice. The
  student knows that each time he takes the test, his score is
  independent random draw from uniform distribution on interval
  $[0,100]$  . After learning his score on a test, the student can
  either stop and accept it as his official score , or he can discard
  the result and retake the test. If the student rejects his score twice
  and takes the test third time, that score will be his official score.
If the student follows an optimal plan, then her final expected
  score before taking any of the tests is?

The answer is $70$, can anyone explain how?
Also The meaning of the question is not clear to me."expected score before taking the test" ?
Comment: Expected score would mean expected value in the statistical sense. The phrase "before taking the test" is just to emphasize that, after the test, there is no longer any uncertainty about the outcome. Anyhow, I find it amusing how the student changed gender between the two paragraphs.
Comment: Was it a gender identity test? than it's too complicated to answer :)
Answer: Let $X_i$ denote the score of the student if he is allowed to retake the exam $i$ times. Let $Y_i$ denote the score of the student on the $i^{th}$ exam.
Suppose the  student is able to take the test only once. Then the expected score before taking the test is simply the expected value of a uniform $[0,100]$ random variable. So $EX_1 = 50$.
If the student is allowed to take the test twice, then its easy to see that the optimal decision is to only retake if his score is $< 50$. Then on average, he will score higher on the second test. We compute the expected score for this case,
\begin{align*}
EX_2 &= P(Y_1 > 50) E[X_2 \mid Y_1 > 50] + P(Y_1 \leq 50)E[X_2 \mid Y_1 \leq 50] \\
&= \frac{1}{2} E[Y_1 \mid Y_1 > 50] + \frac{1}{2} E[X_1] \\
&= \frac{1}{2} 75 + \frac{1}{2} 50 \\
&= \frac{125}{2} \\
&= 62.5
\end{align*}
The second equality follows because if we score above 50, on the first exam, we keep the score. If we score below 50, then we retake the exam, and we can think of this scenario as being reduced to the first case, i.e. where the payoff is $E[X_1]$.
Finally suppose the student is allowed to take the test three times. Following the recursive intuition we gained from the two case, we have
\begin{align*}
EX_3 &= P(Y_2 > 62.5) E[X_3 \mid Y_2 > 62.5] + P(Y_2 \leq 62.5) E[X_3 \mid Y_2 \leq 62.5] \\
&= 0.375 \cdot \frac{100 + 62.5}{2} + 0.625 \cdot EX_2 \\
&= 0.375 \cdot \frac{100 + 62.5}{2} + 0.625 \cdot 62.5 \\
&= 69.53 \approx 70
\end{align*}

Uniform Distribution and Probability


A formula for heads and tail sequences

Question: I am looking for a formula $f(m,n)$ where m and n are positive integers such that $m \leq n$, such that $f(m,n)$ is the number of n-length sequences of heads and tails where there is at least one run of length at least m. An m-run is a sequence of m consecutive heads or tails. For example, there are 16 5-length sequences with runs of length at least 3. So, $f(3,5)=16$. I am trying to find a nice formula for that function. Has any mathematician worked on anything like this before? If so, I would like to read it.
Comment: I get $f(3,5) = 8$, am I missing something?
Comment: @naslundx You are only counting the runs of heads.
Comment: Oh, I see, so at least one run m-run of heads or one m-run of tails, or both?
Comment: Yes, that is correct. Now, I would like a nice formula for this function.
Comment: At least for $m > \frac{n}{2}$, I believe we can use $f(m,n) = 2(2^{m-n} + (m - n)2^{n-m-1})$. When $m \leq \frac{n}{2}$ however we can have both a run of heads and of tails in the same and need to work out how not to count them several times.
Comment: Is there even a closed form expression at all.
Answer: Odlyzko "Enumeration of Strings" (in "Combinatorial Algorithms on Words" (Springer, 1985), pp. 205-228) gets the generating function for the number of  strings on $\{0, 1\}$ that don't contain a stretch of $k$ zeros as:
$$
B_{0^k}(z) = \frac{1 - z^k}{1 - 2 z + z^{k + 1}}
$$
Unless $k = 2$ (when this gives a Fibonacci number), no simple functions are forthcomming.
I don't see a simple way to extend the techniques used to consider simultaneously excluding stretches of zeros and ones.
Comment: I might add that it's easy to obtain this generating function (or any other generating function for sequences that avoid a given collection of words) with the so-called Goulden-Jackson Cluster method. See http://www.math.rutgers.edu/~zeilberg/gj.html .

A formula for heads and tail sequences


Pattern matching in GitHub GraphQL query

Question: I'm trying to query the branch protection rules which has the similar patterns using wildcards. Any suggestion are welcome.
<code>query {
  repository(owner:"user",name: "repo") {
    branchProtectionRules(first: 10) {
      nodes {
          pattern
            }
        }
    }
  }
</code>
O/P:
<code>{
    "data": {
        "repository": {
            "branchProtectionRules": {
                "nodes": [
                    {
                        "pattern": "release"
                    },
                    {
                        "pattern": "release-220"
                    }
                ]
            }
        }
    }
}
</code>
Is there a way to find the pattern fields with release*
Answer: It seems this issue got fixed:


Were the correct enharmonics used here?

Question: I'm still a bit new to properly writing out sheet music, so I was wondering if the last few measures (see image below) were written out correctly. If they aren't, then which ones are wrong and why (and honestly if they're right it'd be nice to know why too, as I'm mostly guessing when I write out enharmonics).
Comment: It looks good to me, but I don't have time at the moment to write up an explanation.  I'm sure someone else will.
Comment: Looks very fine to me!
Answer: This looks quite reasonable to me.  Each of the chords that would use enharmonics is notated in flats, and each of these chords seems to "slide" down to the final chord.
The chord at the beginning of 58 is an F-flat major seventh, followed by a D-flat minor seventh; at 59 we hear a G-flat major with an added ninth.
Beginning in 57, we have a sort of a V  bVI  iv  bVII progression.  Given that the altered chords bVI, iv, and bVII are all created by lowering the chords of the prevailing scale, the use of flats makes sense.
Another way to think about it (if your head is swirling to consider F-flat and C-flat) is to move the progression into C major for discussion.
V  bVI  iv  bVII would be notated as G Ab Fmin Bb. I think most musicians would agree that the use of flats would be simpler than sharps here.  Also, the flat usage "tells" the singers that their pitches are going to have a tendency to resolve down, which they do.  Nice tag!
Comment: Thank you for the detailed reply! I wish I could say I wrote the tag, but it's actually from an arrangement of "Tonight, Tonight" from West Side Story. I can't remember the arranger off the top of my head but I know I originally heard it from a recording by the Ringmasters. Again, thanks for the response!

Were the correct enharmonics used here?


Server closed connection error when checking if key exists in a redis cluster using stunnel

Question: Using redis-cli command line utility with the -c switch to connect to a redis cluster with stunnel configured and running.
When I execute the EXISTS command to verify a key, as expected, it redirects to the node that contains the key however, get the following error:
127.0.0.1:7000> EXISTS foo
-> Redirected to slot [12182] located at 127.0.0.1:7002
Error: Server closed the connection

When I don't use stunnel it works just fine returning the expected output. However, I want to ensure the connection from the client is encrypted.
Is something needed in the config file stunnel.conf such as the nodes' IP addresses and/or ports?  What are recommended steps to configure redis-cli connecting to a cluster with stunnel?
Answer: You will need to configure one stunnel connection for each port that your cluster uses.  Then, when your client is redirected to 127.0.0.1:7002, it will be able to connect via the stunnel connection for that port.


Azure Management API, when grouping daily costs, what timezone is used?

Question: I am trying to use the Azure Management API to determine an Azure Subscription daily costs.
The documentation of the query I am running is here: https://learn.microsoft.com/en-us/rest/api/cost-management/query/usage?tabs=HTTP .
I would like to retrieve the daily costs, unfortunately the results I get are grouped "daily" by an unknown Time Zone, which makes the query not easy to interpreter.
The query I run is the following:

scope: subscriptions/xxxxx-xxxxx-xxxxx
api-version: 2022-10-01
body:

<code>{
    "type": "ActualCost",
    "timeframe": "Custom",
    "timePeriod": {
        "from": "2023-03-16T00:00:00+00:00",
        "to": "2023-03-17T00:00:00+00:00"
    },
    "dataset": {
        "granularity": "Daily",
        "aggregation": {
            "totalCost": {
                "name": "PreTaxCost",
                "function": "Sum"
            }
        },
        "grouping": [
            {
                "type": "Dimension",
                "name": "SubscriptionId"
            }
        ]
    }
}
</code>
and the answer I receive is:
<code>{
  "id": "subscriptions/xxxxxxx/providers/Microsoft.CostManagement/query/zzzzzzzzzz",
  "name": "ttttttttttttt",
  "type": "Microsoft.CostManagement/query",
  "location": null,
  "sku": null,
  "eTag": null,
  "properties": {
    "nextLink": null,
    "columns": [
      {
        "name": "PreTaxCost",
        "type": "Number"
      },
      {
        "name": "UsageDate",
        "type": "Number"
      },
      {
        "name": "SubscriptionId",
        "type": "String"
      },
      {
        "name": "Currency",
        "type": "String"
      }
    ],
    "rows": [
      [
        8.603384519054256,
        20230316,
        "yyyyyyyyyyyyyyyyyyyy",
        "EUR"
      ]
    ]
  }
}
</code>
So I receive as last day yesterday's data, no data for today.
If I run the same query at 6PM I receive also today's costs, considering them starting from lower values, like "midnight just passed".
Please note that when I specify a time interval, I set the dates to UTC-0 in my query (I also tried the Z format with the same result).
Anyone knows how to change the timezone that the Azure Management API use when grouping for Date?
Thanks,
Michele
Comment: Hi, if I understand well your question, I am running this query from Italy, and the endpoint I am using is https://management.azure.com.
Answer: By default Azure Management API uses UTC time zone but you can change the time zone in two ways,
I have taken references from the MS doc
API

<code>POST https://management.azure.com/subscriptions/xxxxxxxxxxxxxxxxx/providers/Microsoft.CostManagement/query?api-version=2022-10-01
</code>

By passing timeZoneOffset parameter in the request URL like if you want to group the costs according to the pacific standard time then set -480(minutes)

In the request body UTC(current time: 2023-03-28T08:48:00-08:00), you will get today's cost for pacific standard timezone. I have changed the from and to timeframe. I have got the cost for today as well.
Comment: Hi @Ikhtesam, thank you for your answer.
I had time to check it in deep, and the timezone in the timePeriod object is used as a filter (to show more or less days in the result), not as an aggregation criteria.


Qual diferença entre Boolean e boolean?

Question: Realizei alguns testes usando Boolean e boolean e aparentemente retornou o mesmo resultado. Vejam abaixo:
Boolean bool  = true;
boolean bool2 = true;

if(bool)
    Log.wtf(TAG, "Funciona!");

if(bool2)
    Log.wtf(TAG, "Funciona também!");

O Boolean (com B maiúsculo) sendo uma classe, neste caso acima NÃO necessitou ser instanciada antes utilizá-la. Existe alguma diferença entre Boolean e boolean? O que pode influenciar na minha aplicação no momento da declaração dos mesmo?
Comment: Pergunta similar e resposta similar : [int e Integer - Java](http://pt.stackoverflow.com/q/62861/14213)
Comment: Sei que `Boolean` pode receber `null` enquanto `boolean` não, e pode usar apenas `Boolean` nos `Generics`, por exemplo `Convert()`...
Comment: Eu costumo dizer que `Boolean` sem o devido preparo mental é um pedido para NPE inesperado e inexplicável
Answer: boolean é um tipo primitivo, ou seja é um número que ocupa 1 byte (ainda que não seja especificado que tenha esse tamanho) e é considerado um tipo por valor, ou seja, seu valor é sua própria identidade, ele existe em si só. A comparação de valores é direta.
O valor padrão dele é false (que seria um 0).
Ele pode ser convertido implicitamente para um texto ("false" ou "true") ou um número (0 ou 1) pode ser usado para representar falso ou verdadeiro no tipo, onde for necessário.
Boolean é uma classe que encapsula um boolean e é um tipo por referência, portanto o seu valor de fato é um ponteiro que aponta para um objeto cujo valor é o booleano. Obviamente a classe deriva Object e tem todas características de um objeto como outro qualquer.
É uma forma de passar o dado por referência em parâmetros de métodos ou usar onde precisa de uma indireção.
O valor padrão dele null. Ele tem 3 estados possíveis e o fato de precisar do estado null é um motivo para usá-lo.
A comparação se dá pelo método equals(), se usar o operador == vai comparar os ponteiros dos objetos, mesmo tendo o mesmo valor. A não ser que use booleanValue() que pega o primitivo dentro do objeto, mas aí a comparação não é com o objeto e sim com primitivos extraídos das classes.
O compilador faz um truque para o boxing parecer transparente, mas ele está criando uma nova instância no heap.
Boolean x = true; //na verdade é traduzido para o abaixo
Boolean x = Boolean.valueOf(true);

Imagine que além do espaço ocupado pelo ponteiro (4 ou 8 bytes) ele ainda armazena um objeto que pode ocupar 20 bytes ou mais dependendo da arquitetura. Tudo isso por causa de um único bit.
A indireção além de ter um custo maior de alocação e cópia gera mais cache miss no acesso que precisa ocorrer em duas etapas: acessa o valor (endereço do ponteiro) e depois o valor do objeto.
A preferência é sempre usar o tipo primitivo, é mais rápido e ocupa menos memória. Dada a ineficiência a opção pela classe só se for realmente necessário ter uma referência (em outras linguagens é possível ter uma referência sem criar esse problema todo, mas não em Java). Um exemplo de necessidade na versão atual é o uso com generics (isso possivelmente mudará em Java 15 ou superior).
ArrayList<Boolean> = lista = new ArrayList<>(); //válido
ArrayList<boolean> = lista = new ArrayList<>(); //inválido

Veja sobre isso em Qual a diferença entre "generics" (Java/C#) e "template" (C++) e Quais as diferenças entre Tipos Genéricos em C# e em Java?.
Com métodos:
void metodo(boolean x) {x = false;} //quando terminar o método, não muda nada no argumento
void metodo(Boolean x) {x = false;} //quando terminar o método, o argumento valerá false

Coloquei no GitHub para referência futura.
Rumores :) É ideal usar tipos primitivos em Java?
Para efeito de comparação C# consegue todos os 3 principais efeitos relatados com o tipo primitivo: uso como tipo genérico, pode ser passado explicitamente por referência sem fazer boxing e tem a opção anulável bool? que ainda é um tipo por valor ocupando apenas 2 bytes no total (poderia ser 1 se houvesse otimização).
Answer:
Boolean com letra maiúscula no começo é uma classe, é o mesmo que java.lang.Boolean
boolean é um tipo primitivo de comparação de dois valores, true ou false.

Você pode usar ambas com mesmo objetivo, a diferença é que a classe tem métodos para converter para string por exemplo, ou converter de string (ou fazer um parse)
Métodos da classe java.lang.Boolean

bool booleanValue() o valor de retorno deste método é um booleano primitivo.
static int compare(boolean x, boolean y) compara dois valores booleanos.
int compareTo(Boolean b) compara o valor da classe atual com outra classe.
boolean equals(Object obj) retorna true se e somente se o argumento não é nulo e é um objeto booleano que representa o mesmo valor booleano como este objeto.
static boolean getBoolean(String name) Retorna true se e somente se a propriedade do sistema nomeado pelo argumento existe e é igual à string "true".
int hashCode() retorna uma hash para o objeto atual.
static boolean parseBoolean(String s) faz um parse da string para booleano.
String toString() retorna a String que representa o objeto.
static String toString(boolean b) retorna a String que representa o valor do argumento.
static Boolean valueOf(boolean b) retorna a instancia java.lang.Boolean que representa o valor booleano específico.
static Boolean valueOf(String s) retorna o java.lang.Boolean representado pela String no argumento

Qual diferença entre Boolean e boolean?


New to django, django server not loading home page

Question: I started a Django project and went through the regular setup process: I used the "startproject" command to create a project named "social_clone_project", and I used "startapp" to create an app named "accounts". Then I created a "views.py" file and set up the "urls.py" file. Here's what it looks like:
from django.contrib import admin
from django.urls import path, include, re_path
from . import views

urlpatterns = [
    re_path(r'^$', views.HomePage.as_view(), name='home'),
    path("admin/", admin.site.urls),
]

Recently, I switched to Ubuntu Debian with the sublime-text editor. I'm new to the Ubuntu OS, and whenever I run the "runserver" command, the default "Congratulations!" page loads instead of my home page. I've created an "index.html" file, which is supposed to load as the home page, but it's not working. Can someone help me solve this issue?
Comment: You haven't configured `urls.py` in main module (probably called `social_clone_project`, near `accounts` app - the same place where default `settings.py` lives). You need to `include("accounts.urls")` there into urlpatterns under some path, like `urlpatterns = [path("", include("accounts.urls"))]`.
Answer: I think the problem is in your url regex so just change your code as follows :
from django.contrib import admin
from django.urls import path, include, re_path
from . import views

urlpatterns = [
    path('', views.HomePage.as_view(), name='home'),
    path("admin/", admin.site.urls),
]

Comment: Nope not working.Please help!!!


Conditional variant type depending on class template arguments

Question: I have a class template and essentially want to create a template alias for a variant type that will be exposed to API users:
template <bool InsertsAllowed, DeletesAllowed>
class Executor {
   ...

 public:
   // Ideally, would be
   // std::variant<ReadRequest, {InsertRequest only if InsertsAllowed}, {DeleteRequest only if DeletesAllowed}>
   // e.g. InsertsAllowed = true, DeletesAllowed = False ==> std::variant<ReadRequest, InsertRequest>
   // InsertsAllowed = true, DeletesAllowed = True ==> std::variant<ReadRequest, InsertRequest, DeleteRequest>
   using RequestType = ...

   makeRequest(const RequestType &r);

   ...
}

So far, the best solution I could come up with is
template <bool InsertsAllowed, DeletesAllowed>
class Executor {
   ...

 public:
   struct BAD_TYPE = {};
   using RequestType = std::variant<
      ReadRequest,
      std::conditional<InsertsAllowed, InsertRequest, BAD_TYPE>,
      std::conditional<DeleletesAllowed, DeleteRequest, BAD_TYPE>>;

   makeRequest(const RequestType &r);

   ...
}

but this doesn't exactly do what I set out to achieve and isn't the cleanest solution anyway.
I need to be able to make a reference to RequestType, so unfortunately I can't replace BAD_TYPE with void. Also, I'd like to avoid stacking a bunch of conditionals to achieve my goal, in the case that I will need to add more template arguments to similar effect.
Comment: @TedLyngmo Hm not quite sure what you're getting at, but I did update the post with the more correct terminology
Comment: Much better. It helps when people know what others are asking about.
Comment: What you need is a typelist (that's the way it is called). Read this : https://www.codingwiththomas.com/blog/getting-started-with-typelists.
Answer: First, you need to create a meta-function to conditionally append another type to the template argument list of std::variant. Let's name it condit_append:
#include <type_traits>
#include <variant>

template<bool cond, typename A, typename B>
struct condit_append;

template<bool cond, typename U, typename ...T>
struct condit_append<cond, std::variant<T...>, U>
{
    using type = std::conditional_t<cond,
        std::variant<T..., U>,
        std::variant<T...>
        >;
};

Next, let's create a convenience alias to it similar to how it is done for standard traits:
template<bool cond, typename ...T>
using condit_append_t = typename condit_append<cond, T...>::type;

Finally, use it for your class:
    class ReadRequest;
    class InsertRequest;
    class DeleteRequest;
    template <bool InsertsAllowed, bool DeletesAllowed>
    class Executor {
        using Type1 = std::variant<ReadRequest>;
        using Type2 = condit_append_t<InsertsAllowed,Type1, InsertRequest>;
    public:
        using RequestType = condit_append_t<DeletesAllowed,Type2, DeleteRequest>;
         //...
    };

Answer: std::tuple already has function std::tuple_cat.
So you might have:
using RequestTypeTuple = decltype(std::tuple_cat(
     std::declval<std::tuple<ReadRequest>>(),
     std::declval<std::conditional_t<InsertsAllowed,
                                     std::tuple<InsertRequest>, std::tuple<>>>(),
     std::declval<std::conditional_t<DeleletesAllowed,
                                     std::tuple<DeleteRequest>, std::tuple<>>>()
     ));

Then a simple "mapping" traits to transform tuple as variant:
template <typename> struct to_variant_impl;

template <typename... Ts> struct to_variant_impl<std::tuple<Ts...>>
{
    using type = std::variant<Ts...>;
};
template <typename T>
using to_variant_t = typename to_variant_impl<T>::type;

So your class would be:
template <bool InsertsAllowed, DeletesAllowed>
class Executor {
    using RequestTypeTuple = decltype(std::tuple_cat(
        std::declval<std::tuple<ReadRequest>>(),
        std::declval<std::conditional_t<InsertsAllowed,
                                       std::tuple<InsertRequest>, std::tuple<>>>(),
        std::declval<std::conditional_t<DeleletesAllowed,
                                        std::tuple<DeleteRequest>, std::tuple<>>>()
     ));
public:
   using RequestType = to_variant_t<RequestTypeTuple>;

// ...
};


How find this real value $x+y+z $ if such this equation

Question:
let $x,y,z>0$ and such
  $$\begin{cases}
\dfrac{x}{xy-z^2}=-\dfrac{1}{7}\\
\dfrac{y}{yz-x^2}=\dfrac{2}{5}\\
\dfrac{z}{zx-y^2}=-3
\end{cases}$$
  show  that: $$x+y+z=6$$
Comment: @Amzoti [Wolfram alpha finds *only* two](http://www.wolframalpha.com/input/?i=x%2F%28xy-z^2%29%3D-1%2F7%2C+y%2F%28yz-x^2%29%3D2%2F5%2C+z%2F%28xz-y^2%29%3D-3) . But yes, there are two different real values of $x+y+z$
Comment: One has negative $y$.
Comment: I wonder if this can be interpreted using something like Cramer's rule. The numerators are all denominators of symmetric matrices.
Answer: Ones first impression is that this is a set of three quadratic equations. So if we would proceed by eliminating two of the three variables, we would get a higher order equation that presumably can not be solved. However, in this case the functions are such that we can side-step these complications. With a nice trick we can work with linear equations!
$xy - z^2 = P  x$
$yz - x^2 = Q  y$
$zx - y^2 = R  z$
Subtract these equations from each other (e.g. the second from the first). This yields:
$(x - z)  S = P  x - Q y$
$(y - x)  S = Q  y - R z$
$(z - y)  S = R  z - P x$
where we have defined $S = x + y + z$. We now proceed as if $S$ an adjustable parameter, and solve the set of $3+1$ linear equations (of which one can be omitted, since it depends on the other two). The final result is:
$x = (S^2 - QS + QR) C$
$y = (S^2 - RS + RP) C$
$z = (S^2 - PS + PQ) C$
where $C = \frac S  {3S^2 - (P+Q+R)S + QR + RP + PQ}$
Inserting $P = -7, Q = 5/2, R = -1/3$, we find all sets of values $(x, y, z)$ in terms of $S$. In principle $S$ can range from $-\infty$ to $+\infty$. But if we are only interested in positive solutions, than we must restrict $S$ to values equal to or larger than $5/4 + (1/12)\sqrt{345}$. This comes down to $S \implies 2.797848$. There is one solution in terms of natural numbers: $x = 1, y = 2, z = 3$.


UIActionSheet multiple selection possible iOS8 – does not remove UIWindow

Question: I came across some weird iOS8 behavior and I don't know how to handle it. Seems like a bug to me. Perhaps you have a good idea for a workaround.
Way to reproduce: Create a UIActionSheet with at least two options. In iOS8 you have the chance to select multiple options at once. Just touch em: Works on device as well as simulator. This might also happen with bad aiming.
The delegate method
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex;

will be called twice. If it would stop here this would be easy: Just ignore the second delegate call. Problem though is that the _UIAlertControllerShimPresenterWindow is never dismissed, which leads to a UI block since our UIApplication's windows doesn't receive any touch events. If you run
po [[[UIApplication sharedApplication] keyWindow] recursiveDescription]

in Debug mode you'll get the following output:
<_UIAlertControllerShimPresenterWindow: 0x7bf5a3d0; frame = (0 0; 320 568); opaque = NO; autoresize = W+H; gestureRecognizers = <NSArray: 0x7bf5af80>; layer = <UIWindowLayer: 0x7bf5a620>>
    | <UIView: 0x7bf5c460; frame = (0 0; 320 568); autoresize = W+H; layer = <CALayer: 0x7bf5c3f0>>

Also the delegate method
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex

is never called.
Reseting the UIApplication's UIWindow with a dirty hack like:
[[(MyApplicationDelegate *) [UIApplication sharedApplication].delegate window] makeKeyAndVisible];

doesn't work as well. Do you have any other ideas on how to fix this?
To reproduce just put the following ViewController into a UINavigationController and you have the issue ... Just in case you don't believe me:
#import "ViewController.h"

@interface ViewController () <UIActionSheetDelegate>

@end

@implementation ViewController

- (void)loadView
{
    self.view = [[UIView alloc] initWithFrame: CGRectZero];
    self.view.backgroundColor = [UIColor whiteColor];

    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithTitle:@"ActionSheet" style:UIBarButtonItemStylePlain target:self action:@selector(buttonTouchUpInside:)];

    self.toolbarItems = @[buttonItem];
    [self.navigationController setToolbarHidden: NO];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark Target Action

- (IBAction)buttonTouchUpInside:(id)sender
{
    UIActionSheet *aSheet = [[UIActionSheet alloc] initWithTitle:@"Choose an option" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"Option 1", @"Option 2", @"Option 3", @"Option 4", nil];

    [aSheet showFromToolbar: self.navigationController.toolbar];
//    [aSheet showInView: self.view]; // doesn't make any difference
}

#pragma mark UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"Clicked at button index %lu", (unsigned long) buttonIndex);
}

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    NSLog(@"Did dismiss with button index %lu", (unsigned long) buttonIndex);
}

- (void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    NSLog(@"Will dismiss with button index %lu", (unsigned long) buttonIndex);
}

@end

Comment: I am seeing the same issue, too. Here is a radar: http://www.openradar.me/radar?id=4786870772826112
Answer: I believe the best way to solve this problem is to use UIAlertController in iOS 8 instead of UIActionSheet.
Here is example of how you can implement it in manner that will work fine with either iOS 8 or iOS 7:
- (IBAction)buttonCallingActionSheetPressed:(UIBarButtonItem *)sender
{
    id alertControllerClass = NSClassFromString(@"UIAlertController");

    if (alertControllerClass)
    {
        UIAlertAction *sheetAction = nil;
        UIAlertController *actionSheetController = [UIAlertController alertControllerWithTitle:nil
                                                                                message:nil
                                                                                preferredStyle:UIAlertControllerStyleActionSheet];

        sheetAction = [UIAlertAction actionWithTitle:@"Do something"
                                          style:UIAlertActionStyleDefault
                                        handler:^(UIAlertAction *action) {
                                            [self actionSheetSelectedIndex:0];
                                        }];
        [actionSheetController addAction:sheetAction];

        sheetAction = [UIAlertAction actionWithTitle:@"Cancel"
                                          style:UIAlertActionStyleCancel
                                        handler:^(UIAlertAction *action) {
                                            [self actionSheetSelectedIndex:1];
                                        }];
        [actionSheetController addAction:sheetAction];

        [self presentViewController:actionSheetController animated:YES completion:nil];
    }
    else
    {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                                 delegate:self
                                                        cancelButtonTitle:@"Cancel"
                                                   destructiveButtonTitle:nil
                                                        otherButtonTitles:@"Do something", nil];
        [actionSheet showFromToolbar:self.navigationController.toolbar];
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self actionSheetSelectedIndex:buttonIndex];
}

- (void)actionSheetSelectedIndex:(NSInteger)selectedAction
{
    // Your logic goes here
}

Comment: I can confirm that the issue does not happen for me using UIAlertController.
Comment: Sebastian, are you running iOS 8.3+? I've found the use of UIAlertController still has the bug where you can multi tap multiple choices.
Answer: The scenario you described is not possible to occur, with this level of release from Apple. There might be some issue with delegate assigning or some thing like that. But, you can use this method to dismiss the ActionSheet in you delegate method (this is only a work around):
- (void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated;

Like this:
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
     [actionSheet dismissWithClickedButtonIndex:actionSheet.cancelButtonIndex animated:YES];
}

Comment: I just tried your solution and it doesn't work. Sorry. Seems to me like you haven't tried it yourself ... "The scenario you described is not possible to occur, with this level of release from Apple." In my defense I was quite shocked about such a bug as well. But it's in there. Try it ... Regards, fat
Comment: As i said earlier, you don't need this code.. its a work around. You should check your delegate assigning and your flow. I can't expect Apple to give this bug. But if you still say its from apple you should report it to Apple. Another suggestion is you should try your code in another project and then see what is happening there.
Comment: Since you don't believe me I added an example ViewController. Try it!
Comment: "A rectangle constant with location (0,0), and width and height of 0. The zero rectangle is equivalent to CGRectMake(0,0,0,0)."

Please edit your code and try to give a proper width/height in loadView function.. This might be causing your invalid touches, i.e., tapping on one/two button simultaneously. Actually i don't have 8.0 sdk installed yet. So, i'm just trying to help you debug your code. Cheers.
Answer: This issue has been fixed as of iOS 8.3+.


Tighter upper bounds with ratios of powers of norms

Question: This question concerns concentration or sparsity measures for finite sequences, related to ratios of norms and their powers. They are meant for approximations to the $\ell_0$ count index.
Their computation and properties have shown renewed interest in the framework of sparse signal restoration or high-dimensional data analysis. A reference is given at the bottom for some more context.
Given a vector $x\in \mathbb{R}^K$ and $1 \le r < s$, I would like  to find a tight upper bound for the quantity: $$\psi_{r,s}(x) = \frac{\sum_1^K |x_k|^r}{1+\sum_1^K |x_k|^s}\,.$$
Using Hölder inequalities (see Inequalities in $l_p$ norm), one gets: $$\sum_1^K |x_k|^r \le K^{1-r/s} \left(\sum_1^K |x_k|^s \right)^{r/s}.$$
Function $u \mapsto \frac{u^r}{1+u^s}$ is upper bounded by the relatively symmetric expression:
$$ \mu_{r,s} = \left(\frac{r^r (s-r)^{s-r}}{s^s} \right)^{1/s}$$
reached at  $u_0 = \left(\frac{r}{s-r}\right)^{1/s}$ (which also works asymptotically when $ r= s$, with the $0^0 = 1$ convention).
Thus, $$\psi_{r,s}(x) \le  K^{1-r/s}\mu_{r,s}\,.$$
For $r=1$ and $s=2$ with $K=2$, the graph of  $\psi_{r,s}(x)$ is displayed below:

Here, the $\mu_{r,s}$ bound is reached. Yet numerically, with random vectors, I suspect that this bound is not tight in general. My questions are thus:

Are there tighter bounds, potentially using supplementary hypotheses :

based on $\max |x_k|$? I would prefer to allow $\min |x_k|=0$, since we are interested in sparse sequences, with a large proportion of zero or close to zero values.
based on decay laws: e.g. $|x_k|\propto k^{-\alpha}$, $\alpha>0$ for $k\le k_s$, and $x_k=0$ for $k> k_s$ for some $k_s< K$

Can one get estimates of spatial locations $x\in \mathbb{R}^K$ close to the maxima, or bounding areas?

For a little more practical context, see Euclid in a Taxicab: Sparse Blind Deconvolution with Smoothed l1/l2 Regularization.
Answer: Consider the closely related function
$$Q_{r,s}(x)=\frac{\left(\sum_{k=1}^K x_k^r\right)^{1/r}}{\left(\sum_{k=1}^K x_k^s\right)^{1/s}}$$
which is the unweighted counterpart of a ratio defined in Mitrinovic's classic Analytic Inequalities, section 2.14.3, published by Springer many decades ago.
Assuming $0<m\leq x_k \leq M$ for all $k,$ and letting $C=M/m,$ Mitrinovic states the bound,
$$
Q_{r,s}(x)\leq \left(\frac{r(C^s-C^r)}{(s-r)(C^r-1)} \right)^{1/s}
\left( \frac{r(C^r-C^s)}{(r-s)(C^s-1)} \right)^{-1/r}
$$
I am not sure if this will improve on your result, unless the plus one term in your denominator can be neglected, so that this function is close to your ratio, so very large $K$ might be a case where this bound is better.
It does, however, use both the maximum and the minimum. Some related results discussed in that section of the book refer to conditions for equality, which is a kind of concentration of the entries to $m$ and $M$, under some special conditions.
One other reference given with no details by Mitrinovic is Beckenbach, E. F., American Mathematical Monthly,71:606-619, 1964, where apparently the upper bound is also discussed.
Comment: The issue is that a sparse vector generally has a $0$ minimum. But I might use it anyway with a small non negative constant.


Wont move past first while statement

Question: I have been asked to change the script once again and when doing so I have ran into an issue with the script.
I have broken down the sections on the script into different sections so you can better see what i am trying to do. I am trying to choose between the TC, MonsterLock, and Cyc and have them do their own functions when i choose one of them.
The problem I am having is that once I choose one of them I can enter the next section and enter in the information for DATABASE1, DATABASE2,DATABASE3, and DATABASE4. But when I do so it loops at that section and constantly asks me
 This script sets up DATABASE Staging
 Sets up location you want to run staging
 Sets up location you want to run staging
 Sets up location you want to run staging
 Sets up location you want to run staging

This happens everytime I choose tc, MonsterLock, or Cyc. I have information in the MonsterLock as you can see but it doesnt moce past the loop and start the commands that are located inside.
    write-host "This script sets up DATABASE Staging"
     $ProductionDistro = Read-Host -Prompt "Which production do you `enter code here`want to run?(TC/MonsterLock/Cyc)"
    While($ProductionDistro -notmatch "(TC|MonsterLock|Cyc)"){
    write-host "You have entered an error" -ForegroundColor Red
    write-host "You must type TC or MonsterLock or Cyc"
    write-host "you typed $ProductionDistro"
    write-host "This script sets up DATABASE Staging"
    $ProductionDistro = Read-Host -Prompt "Which production do you `enter code here`want to ru(TC/MonsterLock/Cyc)"
     }
      while($ProductionDistro -match $TC) {
      write-host "Sets up location you want to run staging"
        $ElementDistro = Read-Host -Prompt "Which Element do you want to run?  (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
        While($ElementDistro -notmatch "(DATABASE1|DATABASE2|DATABASE3|DATABASE4|ALL)") {
            write-host "you have enterd an error" -ForegroundColor Red
            write-host "You must type DATABASE1 or DATABASE2 or DATABASE3 or DATABASE4 or ALL"
            write-host "you typed $ElementDistro"
            write-host "set location you want to run staging"
          $ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
     }

this is the first while statemet
    While($PrductionDistro -match $MonsterLock){
    write-host "Sets up location you want to run staging"
        $ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
        While($ElementDistro -notmatch "(DATABASE1|DATABASE2|DATABASE3|DATABASE4|ALL)") {
            write-host "you have enterd an error" -ForegroundColor Red
            write-host "You must type DATABASE1 or DATABASE2 or DATABASE3 or DATABASE4 or ALL"
            write-host "you typed $ElementDistro"
            write-host "set location you want to run staging"
          $ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
      }
    }
      while( $ElementDistro -match $DATABASE1 ){

     function Execute-MySqlcommand {param( [string]$Server,    #the host of the SQL server
                                            [string]$Database1,   #the name of the database
                                            [System.Data.MySqlclient.MySqlcommand]$Command)  #the command to execute (name of stored command)

         $mysqlConnection = new-object System.Data.MySqlclient.MySqlConnection
         $MySqlConnection.ConnectionString = "DROP_VIEW DATABASE.BTXADDR;DROP_VIEW DATABASE.BTXSUPB;CREATE_VIEW DATABASE.BTXADDR FOR DATABASE1.DATABASE1S2.BTXADDR;CREATE_VIEW DATABASE.BTXSUPB FOR DATABASE1.DATABASE1S3.BTXSUPB"
         $MySqlConnection.ConnectionString = "TRUNCATE TABLE DATABASE1.DATABASE1S2.BTXADDR;TRUNCATE TABLE DATABASE1.DATABASE1S3.BTXSUPB; INSERT INTO DATABASE1.DATABASE1S3.BTXSUPB SELECT * FROM DATABASE1.DATABASE1S2.BTXSUPB; select count(*) from DATABASE1.DATABASE.BTXADDR; select count(*) from DATABASE1S.DATABASE.BTXADDR; select count(*) from DATABASE1.DATABASE.BTXSURB; select count(*) from DATABASE1S.DATABASE.BTXSUPB;"

         $Command.CommandType = 1 # 1 is the 'Text' command type
         $Command.Connection = $mysqlConnection

         $mysqlConnection.Open()
         $Result = $Command.ExecuteNonQuery()
         $mysqlConnection.Close()

         if ($Result -gt 0) {return $True} else {return $False}

     }
         function Execute-MySQLCommand {param(   [string]$Server,                #the host name of the SQL server
                    [string]$DATABASE1,             #the name of the database
                    [System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)

            $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
            $sqlConnection.ConnectionString = "DATABASE_CONNECT_STRING=DSN=DATABASE1;Description=DATABASE1;Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE1;DATASET=DEFAULT"

            $Command.CommandType = 1 # 1 is the 'Text' command type
            $Command.Connection = $sqlConnection

            $sqlConnection.Open()
            $Result = $Command.ExecuteNonQuery()
            $sqlConnection.Close()

            if ($Result -gt 0) {return $TRUE} else {return $FALSE}
        }

                function Copy-File {
                #.Synopsis
                # Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists
                param}($DATABASE0980453.pkg,"d/DATABASE1/code_stg")

                # create destination if it's not there ...
                #mkdir $destination -force -erroraction SilentlyContinue

                foreach($original in ls $source -recurse) {
                  $result = $original.FullName.Replace($source,$destination)
                  while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") }

                  if($original.PSIsContainer) {
                   # mkdir $result -ErrorAction SilentlyContinue
                 # } else {
                    copy $original.FullName -destination $result
                  }
                        cd /d/DATABASE1/code_stg
                        install  ../DATABASE0980453.pkg

       }

    while($ElementDistro -match $DATABASE2 ) {

    function execute-MySqlcommand {param( [string]$Server,    #the host of the SQL server
                                            [string]$DataBase2,   #the name of the database
                                            [System.Data.MySqlclient.MySqlcommand]$Command)  #the command to execute (name of stored command)

         $mysqlConnection = new-object System.Data.MySqlclient.MySqlConnection
         $MySqlConnection.ConnectionString = "DROP_VIEW DATABASE.BTXADDR;DROP_VIEW DATABASE.BTXSUPB;CREATE_VIEW DATABASE.BTXADDR FOR DATABASE2.DATABASE2MS2.BTXADDR;CREATE_VIEW DATABASE.BTXSUPB FOR DATABASE2.DATABASE2S3.BTXSUPB"
         $MySqlConnection.ConnectionString = "TRUNCATE TABLE DATABASE2.DATABASE2S2.BTXADDR;TRUNCATE TABLE DATABASE2.DATABASE2S3.BTXSUPB; INSERT INTO DATABASE2.DATABASE2S3.BTXSUPB SELECT * FROM DATABASE2.DATABASE2S2.BTXSUPB; select count(*) from DATABASE2.DATABASE.BTXADDR; select count(*) from DATABASE2S.DATABASE.BTXADDR; select count(*) from DATABASE2.DATABASE.BTXSURB; select count(*) from DATABASE2S.DATABASE.BTXSUPB;"

         $Command.CommandType = 1 # 1 is the 'Text' command type
         $Command.Connection = $mysqlConnection

         $mysqlConnection.Open()
         $Result = $Command.ExecuteNonQuery()
         $mysqlConnection.Close()

         if ($Result -gt 0) {return $True} else {return $False}

 }

        function Execute-MySQLCommand {param(   [string]$Server,                #the host name of the SQL server
                    [string]$DATABASE2,             #the name of the database
                    [System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)

            $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
            $sqlConnection.ConnectionString = "DATABASE_CONNECT_STRING=DSN=DATABASE2; Description=DATABASE2; Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE2;"

            $Command.CommandType = 1 # 1 is the 'Text' command type
            $Command.Connection = $sqlConnection

            $sqlConnection.Open()
            $Result = $Command.ExecuteNonQuery()
            $sqlConnection.Close()

            if ($Result -gt 0) {return $TRUE} else {return $FALSE}
            }

                function Copy-File {
                #.Synopsis
                # Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists
                param}($DATABASE0980453.pkg,"d/DATABASE2/code_stg")

                # create destination if it's not there ...
                #mkdir $destination -force -erroraction SilentlyContinue

                foreach($original in ls $source -recurse) {
                  $result = $original.FullName.Replace($source,$destination)
                  while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") }

                  if($original.PSIsContainer) {
                   # mkdir $result -ErrorAction SilentlyContinue
                 # } else {
                    copy $original.FullName -destination $result
                  }

                        cd /d/DATABASE2/code_stg
                        install ../DATABASE0980453.pkg
                    }

    While( $ElementDistro -match $DATABASE3 ) {

    function Execute-MySqlcommand {param( [string]$Server,    #the host of the SQL server
                                            [string]$DATABASE3,   #the name of the database
                                            [System.Data.MySqlclient.MySqlcommand]$Command)  #the command to execute (name of stored command)

         $mysqlConnection = new-object System.Data.MySqlclient.MySqlConnection
         $MySqlConnection.ConnectionString = "DROP_VIEW DATABASE.BTXADDR;DROP_VIEW DATABASE.BTXSUPB;CREATE_VIEW DATABASE.BTXADDR FOR DATABASE3.DATABASE3S2.BTXADDR;CREATE_VIEW DATABASE.BTXSUPB FOR DATABASE3.DATABASE3S3.BTXSUPB"
         $MySqlConnection.ConnectionString = "TRUNCATE TABLE DATABASE3.DATABASE3S2.BTXADDR;TRUNCATE TABLE DATABASE3.DATABASE3S3.BTXSUPB; INSERT INTO DATABASE3.DATABASE3S3.BTXSUPB SELECT * FROM DATABASE3.DATABASE3S2.BTXSUPB; select count(*) from DATABASE3.DATABASE.BTXADDR; select count(*) from DATABASE3S.DATABASE.BTXADDR; select count(*) from DATABASE3.DATABASE.BTXSURB; select count(*) from DATABASE3S.DATABASE.BTXSUPB;"

         $Command.CommandType = 1 # 1 is the 'Text' command type
         $Command.Connection = $mysqlConnection

         $mysqlConnection.Open()
         $Result = $Command.ExecuteNonQuery()
         $mysqlConnection.Close()

         if ($Result -gt 0) {return $True} else {return $False}
}
             function Execute-MySQLCommand {param(   [string]$Server,                #the host name of the SQL server
                        [string]$DATABASE3,             #the name of the database
                        [System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)

                    $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
                    $sqlConnection.ConnectionString = "DATABASE_CONNECT_STRING=DSN=DATABASE3;Description=DATABASE3;Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE3;"

                    $Command.CommandType = 1 # 1 is the 'Text' command type
                    $Command.Connection = $sqlConnection

                    $sqlConnection.Open()
                    $Result = $Command.ExecuteNonQuery()
                    $sqlConnection.Close()

                    if ($Result -gt 0) {return $TRUE} else {return $FALSE}
    }
        cd /d/DATABASE3/code_stg
            install ../DATABASE0980453.pkg
        }

                function Copy-File {
                #.Synopsis
                # Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists
                param}($DATABASE0980453.pkg,"d/DATABASE3/code_stg")

                # create destination if it's not there ...
                #mkdir $destination -force -erroraction SilentlyContinue

                foreach($original in ls $source -recurse) {
                  $result = $original.FullName.Replace($source,$destination)
                  while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") }

                  if($original.PSIsContainer) {
                   # mkdir $result -ErrorAction SilentlyContinue
                 # } else {
                    copy $original.FullName -destination $result
                  }
    While($ElementDistro -match $DATABASE4 ) {

       function Execute-MySqlcommand {param( [string]$Server,    #the host of the SQL server
                                            [string]$DATABASE4,   #the name of the database
                                            [System.Data.MySqlclient.MySqlcommand]$Command)  #the command to execute (name of stored command)

         $mysqlConnection = new-object System.Data.MySqlclient.MySqlConnection
         $MySqlConnection.ConnectionString = "DROP_VIEW DATABASE.BTXADDR;DROP_VIEW DATABASE.BTXSUPB;CREATE_VIEW DATABASE.BTXADDR FOR DATABASE4.DATABASE42.BTXADDR;CREATE_VIEW DATABASE.BTXSUPB FOR DATABASE4.DATABASE4S3.BTXSUPB"
         $MySqlConnection.ConnectionString = "TRUNCATE TABLE DATABASE4.DATABASE4S2.BTXADDR;TRUNCATE TABLE DATABASE4.DATABASE4S3.BTXSUPB; INSERT INTO DATABASE4.DATABASE4S3.BTXSUPB SELECT * FROM DATABASE4.DATABASE4S2.BTXSUPB; select count(*) from DATABASE4.DATABASE.BTXADDR; select count(*) from DATABASE4S.DATABASE.BTXADDR; select count(*) from DATABASE4.DATABASE.BTXSURB; select count(*) from DATABASE4S.DATABASE.BTXSUPB;"

         $Command.CommandType = 1 # 1 is the 'Text' command type
         $Command.Connection = $mysqlConnection

         $mysqlConnection.Open()
         $Result = $Command.ExecuteNonQuery()
         $mysqlConnection.Close()

         if ($Result -gt 0) {return $True} else {return $False}
}
        function Execute-MySQLCommand {param(   [string]$Server,                #the host name of the SQL server
                    [string]$DATABASE4,             #the name of the database
                    [System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)

    $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $sqlConnection.ConnectionString = "DATABASE_CONNECT_STRING=DSN=DATABASE4;Description=DATABASE4;Trusted_Connection=Yes;WSID=Server;DATABASE=TF90PVS;"

    $Command.CommandType = 1 # 1 is the 'Text' command type
    $Command.Connection = $sqlConnection

    $sqlConnection.Open()
    $Result = $Command.ExecuteNonQuery()
    $sqlConnection.Close()

    if ($Result -gt 0) {return $TRUE} else {return $FALSE}
}

function Copy-File {
#.Synopsis
# Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists
param}($DATABASE0980453.pkg,,"d/DATABASE4/code_stg")

# create destination if it's not there ...
#mkdir $destination -force -erroraction SilentlyContinue

foreach($original in ls $source -recurse) {
  $result = $original.FullName.Replace($source,$destination)
  while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") }

  if($original.PSIsContainer) {
   # mkdir $result -ErrorAction SilentlyContinue
 # } else {
    copy $original.FullName -destination $result
  }

    cd /d/DATABASE4/code_st
    install ../DATABASE0980453.pkg
}
     While($ElementDistro -match $ALL ){

     function Execute-MySQLCommand {param(  [string]$Server,              #the host name of the SQL server
                    [string]$DATABASE1,$DATABASE2,$DATABASE3,$DATABASE4,                #the name of the database
                    [System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)

    $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $sqlConnection.ConnectionString = "(DATABASE_CONNECT_STRING=DSN=DATABASE1;Description=DATABASE1;Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE1;DATASET=DEFAULT;),(DATABASE_CONNECT_STRING=DSN=DATABASE2; Description=DATABASE2; Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE2;),(DATABASE_CONNECT_STRING=DSN=DATABASE3;Description=DATABASE3;Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE3;),(DATABASE_CONNECT_STRING=DSN=DATABASE4;Description=DATABASE4;Trusted_Connection=Yes;WSID=Server;DATABASE=TF90PVS;)"

    $Command.CommandType = 1 # 1 is the 'Text' command type
    $Command.Connection = $sqlConnection

    $sqlConnection.Open()
    $Result = $Command.ExecuteNonQuery()
    $sqlConnection.Close()

    if ($Result -gt 0) {return $TRUE} else {return $FALSE}
 }

    install ../DATABASE0980453.pkg
     }

Second While statement
 While($ProductionDistro -match $Cyc) {
 write-host "Sets up location you want to run staging"
        $ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
        While($ElementDistro -notmatch "(DATABASE1|DATABASE2|DATABASE3|DATABASE4|ALL)") {
            write-host "you have enterd an error" -ForgroundColor Red
            write-host "You must type DATABASE1 or DATABASE2 or DATABASE3 or DATABASE4 or ALL"
            write-host "you typed $ElementDistro"
            write-host "set location you want to run staging"
          $ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
 }
}
}}}}}

Answer: The loop beginning while($ProductionDistro -match $TC) { does not appear to modify $ProductionDistro so once you get into that loop it will go round forever. The same appears to apply to the other while($ProductionDistro... loops.
For a while loop to terminate you must update some of the values used in the condition to make the condition no longer evaluate to something true.
Comment: Why do you need to use a `while` loop at all? It looks to me as though you just want `if($ProductionDistro`...
Comment: how would I change to modify $ProductionDistro ro how would I terminate the while loop so i could enter into another one. I am just learning how to write scripts for powershell so I am lost when it comes to adding in stuff
Comment: I went and read about it and i made the mistake of doing while loops. I have changed my script to use switch loops and if loops and it passes between the instances.
Comment: thank you for the help. I had a lot of reading to do to understand what you meant when it didn't modify the $PductionDistro and how to terminate a while loop to stop form running a infinite loop

Wont move past first while statement


Caso específico de RewriteRule para uma URL

Question: Tenho um .htaccess reescrevendo as URLs e um submenu sendo criado dinâmicamente e preciso que um destes links seja aberto em outra URL/página diferente do restante.
Está assim:
RewriteRule conheca/(.+)/(.+)/$ conheca.php?id=$1&slug=$2

Preciso que o caso específico conheca/2/equipe-pastoral/ seja direcionado para equipe-pastoral.php e não para o conheca.php, como é o caso das URLs restantes.
Utilizando
RedirectMatch 301 conheca/2/equipe-pastoral/$ page_diferente.php

ela conseguiu se distinguir das demais porém acontece o erro 500 mesmo a page_diferente.php existindo.
Answer: Basta colocar a regra específica para esta página antes da regra geral, e usar a flag [L] na regra específica para indicar que após a mesma, as seguintes devem ser ignoradas.
Veja mais sobre rewriterule e rewritecond nesta questão:
Reescrever URL para acessos à "root" mas não bloquear acesso aos sub-domínios
Comment: Consegui resolver com a ajuda deste post: http://stackoverflow.com/questions/11691916/removing-php-file-extension-from-the-end-of-a-url

Creio que estava errando ao fazer a reescrita para retirar .php dos links. Obrigado!


Trying to find if username has already been used

Question: I'm trying to find if the username a user enters hasn't already been used by others, but it doesn't seem to work. Here's the code. I don't know what else to put.
   require 'database.php';

   $password = $_POST['password'];
   $fname = $_POST['fname'];
   $lname = $_POST['lname'];
   $username = $_POST['username'];
   $email = $_POST['email'];

   $message = '';
   if ($password === ""){
       $message = "
Oops! Must've missed a spot!
";
   }
   else if ($fname === ""){
       $message = "
Oops! Must've missed a spot!
";
   }
   else if ($lname === ""){
       $message = "
Oops! Must've missed a spot!
";
   }
   else if ($email === ""){
       $message = "
Oops! Must've missed a spot!
";
   }
   else if ($username === ""){
       $message = "
Oops! Must've missed a spot!
";
   }
   $query = mysql_query("SELECT username FROM users WHERE username='".$username."'");

   if (mysql_num_rows($query) != 0)
   {
       $message = "
Username already exists!
";
   }

Comment: `mysql_*` functions are deprecated since PHP 5.5 (and **removed entirely** in PHP 7) and you should [stop using them](http://stackoverflow.com/q/12859942) if you can.
You should choose another API that allows you to use [prepared statements](http://stackoverflow.com/q/60174/) (which you *really should* when dealing with variables), like `mysqli_*` or PDO
- see [choosing an API](http://php.net/manual/en/mysqlinfo.api.choosing.php).
Comment: Enable error-reporting and check your logs, it'll tell you what to look for. `error_reporting(E_ALL);` `ini_set('display_errors', 1);`
[`mysql_error`](http://php.net/manual/en/function.mysql-error.php)
Comment: You should first make your username column in your mysql table unique as a backup.
Comment: Then use a function to fetch the count that is human-readable, something like `function userExists($con,$username) {...ect }` This would be used in an `if` statement like `if(!userExists($con,$_POST['username'])) { //do stuff }`. Try breaking your code into specific parts. Make sure you are using the latest database library as mentioned and not mixing raw user input into your statement.
Answer: Try to use this function to check for existing users with that name:
function userExists($input) {
  $count = mysql_query("SELECT COUNT(*) FROM users WHERE username='".$input."'");
  if ($count > 0) $output = "User already exists";
  return $output;
}

You can try it like that then to check:
if (userExists($username)) { ... }

But consider stop using mysql_ in the future since it's deprecated.


Systems properties assistance

Question: I am a little confused about the properties (is it Linear, Causal, Time-Invariant, Stable?) of this T system.
$$T[x(t)]=\sum_{k=t_0}^{t}{x(k)}$$
Some are obvious (it is linear), but can't come up with the rest of them… any tips on this would be appreciated.
Answer: The system can't be time-invariant, because the interval over which the input is accumulated depends on the time $t$.
The formula implies that the system's output is zero if $t<t_0$. If this is the case then the system is causal, because no future values of the input signal are necessary for computing the output signal.
As for stability, the system is definitely BIBO stable because a bounded input will always produce a bounded output.
Comment: Sounds logical. Thank you for the great tip.
Comment: How about if I change it for a transcendental, say "e", for an equation like this...  http://3.bp.blogspot.com/-zYfPS_sAHOI/Vi_yQxyObvI/AAAAAAAAAvM/oTS4FmLjDq0/s1600/Information2%2Bjpg.jpg
Comment: @AngelRmz: That's an entirely different system; you should try to understand the basic system properties and how to test them, otherwise you will need to ask a new question for each new system you come up with.
Comment: I will. Thanks!!

Systems properties assistance


Realizations of random variable

Question: Can some of you help me with following exercise?

Provide a procedure to generate realizations of a random variable with
  CDF (cumulative distribution function) $Fx(x)$ given by:
$Fx(x)=(x+1)/4$ if   $-1<x<0$
$Fx(x)=(x+3)/4$ if $0<=x<1$

What is the meaning of generate realizations of random variable?
Thank all!
Answer: I think what is meant is: produce (pseudo-) random numbers.
Note that for a distribution function $F$ and its inverse $F^{-1}$ and a uniform random variable $U$ it holds that
$ F^{-1}(U) $ has distribution $F$. You an google random number generation and find this procedure.
In you case:

find the inverse of $F$
Generate uniform random variables
Apply $F^{-1}$

Then you are done. Which programming language do you use?
Edit: As remarked by Macro there is an atom at $0$ with probabilty $\frac12$. I think we can still use the inverse in the following way:

find the inverse for $x \in [-1,0)$ and $x \in (0,1]$
Generate a uniform $U$
Call the generated rv $X$
3.a) If $U \in [0,\frac14]$ then apply $F^{-1}$ as definded on the left of $0$ and set $X = F^{-1}(U)$
3.b) If $U \in (\frac14,\frac34)$ then set $X = 0$
3.c) If $U \in [\frac34,1]$  then apply $F^{-1}$ as definded on the right of $0$ and set $X = F^{-1}(U)$.

This should take care for the atom. Note that I did not care about open or closed intervals in the definition above as the probability for the uniform to reach the the point at the interval end is zero.
Comment: No, I am not using a programming language.Is a normal exercise of statistics.
Comment: there you can get unform random variables with a function and then you apply the inverse ... you can make it in Excel! :)
Comment: Oh: I read Excel ... exercise .. anyways, the path should be clear. Best,R
Comment: Macro yes, you are right, I missed the discontinuity. @lui14 please look at Macro's remark!
Comment: @Macro: inverse transform sampling should be possible here when using the generalized inverse, i.e. $F^{-1}(u) = \inf\;\{x \mid F(x)\geq u, 0<u<1\}$
Comment: Ok thank for yours opinion and advice,so @Macro what do you suggest to resolve that?
Comment: I hope the way that I edited the answer is correct now. It is Friday night in Europe and I have to go off-line soon. If there is still something important missing, then please @Macro post the correct answer and lui14 can choose yours.

Realizations of random variable


dropping NA in a dataframe in R

Question: I am working with the lines below:
library(quantmod)
library(tidyr)

start="2022-01-01"
end="2022-11-01"
getSymbols("0386.HK",from=start, to=end)
getSymbols("600028.SS",from=start,to=end)
CPC_H<-`0386.HK`[,6]
CPC_A<-`600028.SS`[,6]
df<-cbind(CPC_A,CPC_H)

There are some NAs in the dataframe from either varaible, so I am trying to remove the entire row if either shows NA.
> head(df)
           X600028.SS.Adjusted X0386.HK.Adjusted
2022-01-03                  NA          3.197658
2022-01-04            3.555848          3.223655
2022-01-05            3.572542          3.327643
2022-01-06            3.564195          3.318978
2022-01-07            3.630971          3.388304
2022-01-10            3.622625          3.344975

I try to drop NA using the following line n return with an error msg:
df%>%
  drop_na(CPC_H)

Error in UseMethod("drop_na") :
  no applicable method for 'drop_na' applied to an object of class "c('xts', 'zoo')"

Can anyone tell me is there a better way to do it? Many thanks n have a good day.
Comment: Take a look at the function  `complete.cases`
Comment: `df`` is not a data.frame.
Comment: Thanks @G5W, just tried using complete.cases and it working perfectly now.
Answer: I believe na.omit should do the same if you apply it to an object with the same name of your dataframe. But it will remove every line with NA.
df<-na.omit(df)
If you have more columns with NA values and you need to remove lines with NA only from these two specific columns, you should do like this:
df<-subset(df,!is.na(column_1) | !is.na(column_2))
This code will filter your database, keeping only rows that do not have NA in any of the columns.

dropping NA in a dataframe in R


Question on fingering for piano

Question: http://www.frederickhodges.com/fundamentalsofpianotechniquepart1.html
I read that in fingering the major and minor arpeggios, only use the first, second, fourth, and fifth fingers, replacing the third with the fourth for a stronger fourth finger. Is this accurate/efficient, or should I stick to the common use of the 3 finger instead of the fourth?
Comment: It's all about what feels comfortable to your hands. I certainly don't think there's a standard fingering everyone has to use for arpeggios. Granted, there are clearly bad fingerings, but for any given group of notes, there is usually more than one good fingering also. It all depends on what feels comfortable to you and allows you to execute the arpeggios the most proficiently and without unnecessary tension.
Answer: The "standard" fingering for the right hand is to use 2 4 when the interval between those two notes is a fourth, and 2 3 when it is a third.
For the left hand, if the interval between 2 1 is a fourth, you can use either 3 or 4 on the other note.
Mr Hodges is entitled to his own opinions, of course - including the first sentence of the biography on his website claiming he is "Hailed by the press as one of the best concert pianists in the world."
Answer: I use the fingering suggested in Schmitt - Preparatory Exercises (a useful book to get with a great appendix containing tons of scales, arpeggios, broken chords, chord passages etc.)
5421 for all LH arpeggios except where you have a white key to black key major third, i.e. D major, E major and A major, in which case 5321, as the physical distance is slightly larger here. In fact, apart from these, Scmhmitt doesn't even suggest 5321 as an alternative, so 5421 must have been the standard back in the 1800s.
Not only does 5421 strengthen the fourth and fifth fingers but if you are arpeggiating over more than one octave you will find you are set up better for the subsequent octave when you bring 4 over 1 (or 1 under 4 in descending).
Also, as my teacher pointed out, if you are generally using 1245 on the RH (which is my preference), then the LH 1245 descending is symmetrical with this, so using the fourth finger on the left hand may require less brain "processing power" over the long run. He also pointed out that LH 5421 puts your wrist in a more neutral position (test it out and see!)

Question on fingering for piano


Associate one item of content with one taxonomy term

Question: I have a view of type 'term' that displays in a grid, all the terms in a vocabulary. I need to display 2 images per term, but this is not possible I believe. (E.g. the taxonomy Image module only allows you to add one image per term).
So I thought maybe a solution to this would be to create another content type with one piece of content per term. And then associated each one with one of the vocabulary terms. And then create relationship in the view to link them. However I cant figure out how to get the view to do this. Is this possible?
Answer: It's possible, but not terribly easy in D6.
In Drupal 6 (unlike 7 and 8) vocabularies were not fieldable, so the approach you took is a reasonable one.  You probably do not need a relationship in the view, just adjust the filter to include content types of the new type, and then use sorting to move the to the start or end of the result set. You could sort by content type or use the usually ignored "sticky" field on the nodes if its not in use (set all your new images to be sticky and then sort the list to place them where you want).
You could also create a block that uses the same filter pattern as the original view, but limit to the new content type and the only 2 results. Then place that block on the page that's displaying the grid.
Note: Drupal 6 is no longer officially supported by the community. While there are some places that are offering long term support for Drupal 6, you should plan to move to Drupal 7 or 8 soon.


Is it possible to return a form element AND an ajax response from the same ajax callback function?

Question: I have an ajax callback function that needs to return a form element and also an ajax response. Is it possible to do both?
In my callback I need to set and return something like:
$form['fid'] = array(
  '#type' => 'textfield',
  '#value' => 1,
);
return $form['fid'];

And also something like:
   $response = parent::uploadAjaxCallback($form, $form_state, $request);
   return $response;

Is there a way that I can achieve return both a form element and an ajax response?
EDIT: Latest attempt is returning the form element for display but when I examine the $form from the form build function the value is still empty.
class MyManagedFile extends ManagedFile {

  /**
   * {@inheritdoc}
   */
  public static function uploadAjaxCallback(&$form, FormStateInterface &$form_state, Request $request) {

    $response = parent::uploadAjaxCallback($form, $form_state, $request);

    $form['fid'] = array(
      '#type' => 'textfield',
      '#prefix' => '
',
      '#suffix' => '
',
      '#value' => '1',
    );

    $response->addCommand(new ReplaceCommand('#fid', $form['fid']));
    return $response;

  }

}

Examining the $form from the form builder (dpm($form)) results in:
[fid] => Array
(
[#type] => textfield
[#prefix] =>
        [#suffix] =>

    )

Answer: If you want to do more than simply return new markup, then your response should be an instance of Drupal\Core\Ajax\AjaxResponse, to which you can append one or more AJAX commands via the addCommand() method.
A simplified version of this would be:
use Drupal\Core\Ajax\AjaxResponse;
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand('#my-wrapper-id', $form['fid']));
return $response;

I recommend checking out a tutorial, such as one of those below, for more information on using AJAX with FAPI:

https://www.sitepoint.com/using-ajax-forms-drupal-8/
https://www.drupal.org/docs/drupal-apis/ajax-api/core-ajax-callback-commands
Comment: Thank you for the reply. I've edited my question with my latest attempt. It is return the form element and populates it for viewing but the #value is not actually set when I examine the $form (dpm($form)) the #value is empty. Any idea how to resolve this?


hook_preprocess_page: "node_load() + node_page_view()" versus "%node + node_page_view()"

Question: A basic node (nid "123") exists and a module registered two paths using hook_menu:

first/%node
second

Both page callbacks use node_page_view($node) to display a fullpage view of the node,  except the second callback additionally uses node_load(123) to get a reference to $node.
Therefore http://localhost/first/123 and http://localhost/second look the same as far as the user is concerned.

However hook_preprocess_page receives the node variable only with the first path, therefore Drupal obviously does something beyond node_load when it sees a %node wildcard, any idea what it is so that hook_preprocess_page receives the reference to $node in both cases ? (because handling everything internally in the second path produces much more friendly urls than redirecting to the first path from the second).
Example:
<?php

/**
 * Implementation of hook_preprocess_page().
 */
function mymodule_preprocess_page(&$vars){
    if (@isset($vars['node'])) echo '
[mymodule.module] Node is defined
';
    else echo '
[mymodule.module] Node is NOT defined
';
}

/**
 * Implementation of hook_menu().
 */
function mymodule_menu(){
    return array(
        'first/%node' => array(
            'title' => 'First callback',
            'page callback' => 'mymodule_page_first',
            'page arguments' => array(1),
            'access callback' => TRUE,
        ),
        'second' => array(
            'title' => 'Second callback',
            'page callback' => 'mymodule_page_second',
            'access callback' => TRUE,
        ),
    );
}

/**
 * Page callback for url "http://localhost/first/123".
 */
function mymodule_page_first($node){
    echo '
[mymodule.module] Function mymodule_page_first

';
    var_dump($node);
    echo '
';

    return node_page_view($node);
}

/**
 * Page callback for url "http://localhost/second".
 */
function mymodule_page_second(){
    $node = node_load(123); //the ID of an existing node

    echo '
[mymodule.module] Function mymodule_page_second

';
    var_dump($node);
    echo '
';

    return node_page_view($node);
}

(Source of file mymodule.module)

My best/only hope so far is to dig in the source of node_page_view and all functions it consequently triggers until I find what happens between the moment node_page_view is called and the moment the module_invoke_all which triggers the hook is called.
Comment: Are you hardcoding the node id in the "second" method but it won't load the node? Or is the question why you aren't getting that node id in the "second" method?
Comment: apparently I misunderstood the question. seems like @kiamlaluno has a good answer on this one.
Comment: You were close, but no I meant that both manage to retrieve a reference to $node (and it's identical in both cases), however hook_page_preprocess receives that reference only in the first case. Therefore Drupal obviously does something more than just "node_load" when it sees a "%node", and that "something more" is what I'm looking for.
Answer: When mymodule_preprocess_page() is invoked for the "first/%node" path, it gets the node object because the path is associated with a node from the module.
Drupal cannot associate a node object with a path like "/admin/content/node" (Drupal 6 path) because the path doesn't contain any reference to a node ID which is marked as node ID. Which node object should Drupal return for such paths, considering a Drupal website can contains hundreds of nodes?
Your question is "how can Drupal associate a node object in one case, but not in the other one?"
The answer is in the template_preprocess_page() code, which the function executed before the template page.tpl.php is rendered.
In that function, you will find the following code:
if ($node = menu_get_object()) {
  $variables['node'] = $node;
}

The default parameters for menu_get_object() are $type = 'node', $position = 1, $path = NULL, which means template_preprocess_page() is asking for the node object that is associated with the placeholder in position #1, which is the value returned, for example, from arg(1).
Looking at the source of menu_get_object(), you will notice that the code being executed is the following:
function menu_get_object($type = 'node', $position = 1, $path = NULL) {
  $router_item = menu_get_item($path);
  if (isset($router_item['load_functions'][$position]) && !empty($router_item['map'][$position]) && $router_item['load_functions'][$position] == $type . '_load') {
    return $router_item['map'][$position];
  }
}

Using the default arguments, the function will verify the loading function associated with the route item #1 is node_load(). If the loading function is that, then it will return the value returned by the loading function to the calling function (in our case, template_preprocess_node()).
To automatically get a node object, your menu callback should use a path like "second/%node" (which would be compatible with the default menu_get_object() arguments). The only problem is that for such paths the node ID needs to be passed; if the URL is http://example.com/second, Drupal will show a 404 error page, as the placeholder require parameter that must be passed.
To resolve this problem, the module should define two menu callbacks: one associated with "second", and one associated with "second/%node". The first menu callback would not get a node object, while the second would get the node object (and mymodule_preprocess_page() would get it too).
As alternative, you should change the code of mymodule_preprocess_page() to something similar to:
/**
 * Implementation of hook_preprocess_page().
 */
function mymodule_preprocess_page(&$vars){
  // Check if the page being served is one of the pages handled by the module.
  if (arg(0) == 'first' || arg(0) == 'second') {
    if (isset($vars['node'])) {
      // The page is a node page.
    }
    else {
      $vars['node'] = mymodule_load_the_default_node();
    }
    // …
  }
}

Comment: The problem with your answer is that "123" is just an example for the snipplet, but it's not meant to be a fixed value: it's the page callback who decides what "nid" to use. The question was about "what does Drupal do internally besides node_load when it receives a %node wildcard" given there is an obvious difference
Comment: I replied to your question when it was titled "hook_preprocess_page: "node" is not defined unless path contains %node". I already replied about why in one case you get a node object, and in one case you don't.
Comment: I updated the answer, and explained why Drupal is able to return a node object in one case, but not in the other case, reporting exactly which code is responsible of Drupal behavior.
Answer: When Drupal sees the '%node' wildcard in the url it knows the argument is referencing a node id, so automatically sets the $node variable for you, making it available in hook_preprocess_page. In your "second" menu callback, you should set the $vars['node'] variable. That way you can use it hook_preprocess_page.
Reference: http://drupal.org/node/224170
Comment: `node_page_view` is the one [meant to] tell Drupal what node to build the page from, not the fact that there is "%node" wildcard in the path. (As proof: imagine you have a path "some/%node/other/%node/path", how would Drupal guess otherwise which one to use ?)
Comment: have you ever seen a path that does that?
Comment: None come to mind, but multiple wildcards of the same type are allowed afaik. Who knows, maybe they did hardcode to assume the first %node is meant to induce "it's a fullpage view of that node", but that would be inconsistent with the way wildcards are meant to work.
Comment: Until I find the proper Drupal way of transmitting the node reference, I can use a hack like a static variable because for the real module, I will have only one reference per page anyway, but that's just not clean, so I'd rather find out the real reason than just "get it working one way or another".
Comment: It is true, multiple placeholders of the same type are allowed, but Drupal will use only the first placeholder to populate $variables['node'].


Windows 10 Keeps asking for authentication for public samba share

Question: I know there are a couple of questions about this, those are different situations though and the provided answers do not relate to my problem.
I have a WD My Cloud EX2 NAS with a configured public share, I can access this share from my windows 10 laptop, windows 10 desktop and android phone without issues or authentication.
However, I did a clean windows 10 install of another desktop and the exact same share keeps asking me for authentication now and wont accept any input I give it.
I tried enabling a certain key in the registry (can't remember the key-name) and rebooting, but that didn't help.
Am I missing something? I'm 100% certain the share is still configured properly since I can still access it from my other machines.
EDIT 1: Something I just realized: the other windows 10 machines are Windows 10 Pro, this system is Windows 10 Home, not sure how that would affect this problem, but that's the only difference I can think of.
EDIT 2: I upgraded to Windows 10 Pro and still can't access the public share.
EDIT 3: When I enter \ as the username and leave the password blank it shows me the share contents, however when I reboot the computer it asks me for credentials again, it won't remember them.
EDIT 4: I have Plex installed on the server, when I get the authentication dialog for the samba share it shows the plex server name in the "domain" field. perhaps this influences the authentication protocol?
Comment: What's your "network location" configured as? Home/Work/Public?
Comment: it's not a network location, it's a mapped network drive. any other global network settings seem to be set to private network
Comment: Not what I asked, http://www.tenforums.com/tutorials/6815-network-location-set-private-public-windows-10-a.html
Comment: as mentioned that's configured to private network
Comment: This sounds really strange it seems like the NAS is requesting authorization in the form of login for this one machine this would normally say it's a miss configuration on the NAS, do you enable access to each Machine on the NAS or is it supposed to allow everyone on your network access it?
Comment: it allows anyone on the network to access the share
Comment: How are you accessing the NAS - by name: \\Servername\Sharename or by ip address: \\192.168.1.2\Sharename ?
Comment: I tried both, with the same results
Answer: I don't know how, but when I inserted as username \ and left the password field blank suddenly it accepted the credentials and showed me the share contents.
Maybe it will help someone else who has the same issue.
EDIT: when I originally posted this answer I couldn't check the checkbox to remember the credentials, causing me to have to do this on every boot.
However, this time it did allow me to check the checkbox, I don't know what changed, but it's working now. might have been a windows update.
Another Edit: Upon every boot I now have to use smbpasswd to re-configure the correct password for the account.
Final Edit: It seems this question is getting a lot of attention, I think I should add that after all this time, I managed to solve the issue.
This is related to 2 possible reasons:

A complete factory-reset
leaving the username as "admin", I can't recall exactly what or why, but changing it to my custom username resulted in issues, whereas leaving it as "admin" worked perfectly fine. Possibly something hardcoded in the NAS firmware.
Comment: I know this is old but I'm wondering if the OP remembers where you found the backslash username trick. I'm curious about why that works. It worked for me. (My setup was working for _years_ for read/write access to three NASes without credentials, then overnight it simply stopped working. Very annoying.)
Comment: Thinking about it more, maybe the wire format for credentials is `username\password` so that looks like the separator character for a pair of blank values? (In my case that still doesn't explain why it suddenly became necessary to enter anything at all...)
Comment: @McGuireV10 unfortunately I have difficulty remembering what I did yesterday, let alone 7 years ago haha. Knowing me, I probably was at a point where I just started trying things at random; or perhaps just came up with it on the spot after reading something somewhere.
Comment: Thanks man, been looking for months on how to connect as a guest user to the samba, that `\` and no pass worked for me too
Answer: Some Items and Resources that may be related

https://techjourney.net/cannot-connect-to-cifs-smb-samba-network-shares-shared-folders-in-windows-10/
EDIT 1 https://community.wd.com/t/anonymous-share/96348/18

Be sure to check out the above article too regarding a change with Windows 10 and registry key entry, etc. that's related to remote shared folders or network locations on a file server or NAS through CIFS, SMB or Samba protocol.
This talks about turning on allowing insecure guest but also talks about the Windows Credentials options as well.

Also, check for a saved credential to remove (or add perhaps) by typing in control
keymgr.dll or maybe rundll32 keymgr.dll,KRShowKeyMgr from the
RUN and then press enter. Remove (or add perhaps) the stored credentails that
shouldn't be there and then see if it works as expected.

Lastly, I'm not sure if when you upgraded if it changed back that registry entry you changed, but it's important to remember what you change and backup before you change in case it doesn't work so you can revert that change back.
I wouldn't get into the habit of trying things and then before you know it you change 10 things so now you're not sure if any of those helped any or made the issue worse so jus think about this moving forward with these types of strategies.
EDIT1: I added a second link URL above that gives some pointers on this leading it to be either a Windows issue or a NAS configuration issue. On my Windows machine, I setup a share and granted ANONYMOUS LOGON both SHARE and NTFS anf then from another Windows machine I mapped a drive to it with \\PCName\ShareName and saved that without specifying a username or a password just fine.
Comment: The key named in that article (AllowInsecureGuestAuth) was indeed the key I meant, I'll re-check the key when I'm back home
Comment: the key was still set to 1, and win+r `\\servername\sharename` (obviously with the correct values) asked me for authentication again and would not accept empty values
Comment: please read my Edit #4 in the question, this might provide a clue as to what is going on
Comment: I tried that, but it promted me with a new authentication window for the actual server
Answer: I had an issue like this a long time ago.  From memory, it was because the client had a set of credentials stored for that particular share that were wrong.  It tried to use these wrong credentials each time it tried to connect, and when they didn't work it would ask the user for the correct ones (which was blank, because it was an open share).
If you type net use you will see a list of all the conections to SMB shares that the client is using, and you can use /delete to remove one.  Full docs here on technet.
More information in this thread
It's a long shot, but I hope it helps.
Comment: I already tried this a long time ago, unfortunately that's not helping
Comment: please read my Edit #4 in the question, this might provide a clue as to what is going on
Comment: When I type in admin command prompt `net use` I get "System error 1222 has occurred. The network is not present or not started."
Answer: I've ran into this too.  Windows 10 1709 and newer seem to not allow access to SMB shares as guest.
I've tried mapping using
Net use * \server\share /user:server\user_name
while this mapped and allowed me to READ the contents, I was unable to execute anything.
I finally tried mapping from an elevated command prompt.  I don't know why but hope this helps someone.


How to embed $F_q^\times $ in $S_n$?

Question: We cannot embed $F_q^\times $ in $S_n$ for small $n$ if $q − 1$ has "large" (I know it is vague) prime factors.
$F_q^\times $ is a field where $q = p^t$, where $p$ is a prime.
It is easy to see that we can always embed $F_q^\times $ in $S_t$ for "large " value of $t$
Question : What is a relation between $q$ and $t$ so that we can always embed $F_q^\times $ in $S_t$?
I tried to search on google but did not find out anything.
Comment: Maybe you can use that  the multiplicative group of a field is always cyclic.
Comment: http://mathworld.wolfram.com/LandausFunction.html
Answer: It's a standard theorem that $F_q^\times$ is cyclic of order $q-1$. Embeddings from cyclic groups are easy to describe: For a cyclic group $C$ of order $n$ and any group $G$, we can embed $C$ into $G$ if and only if $G$ has an element of order $n$.
To determine the possible orders in the symmetric group $S_n$, note that any element in $S_n$ may be decomposed into disjoint cycles whose cycle lengths sum to $n$ and the order of that element is the least common multiple of the cycle lengths.
So with this in mind, we can say that $F_q^\times$ embeds into $S_n$ if and only if there are natural numbers $n_1, \dots n_k$ such that $\sum_{i=1}^k n_i=n$ and $\operatorname{lcm}(n_1, \dots, n_k)=q-1$.
From this, you can see in particular that it is impossible to embed $F_q^\times$ into $S_n$ if $q-1$ has a prime factor larger than $n$.

How to embed $F_q^\times $ in $S_n$?