Generate file to open Outlook new message with Bcc field

Question: I need to programatically open outlook 2016 on users computer, with new message, which contains the predefined fields (To, Bcc, UTF-8 body, attachment). For that, I need to generate either a file which outlook opens as a new message, or a script which makes outlook open the new message.
It may look like an easy task, but it is actually tricky. I would, for example, do it in a way that I generate an .eml file, with content like this:
From: firstname.lastname@example.com
To: firstname.lastname@example.com
Cc: firstname.lastname@example.com
Bcc: email@example.com
X-Unsent: 1
Subject: Something

This is a test message.
Multipart can be used to add attachment.

The problem is that this won't work, because if such file is opened by outlook (as .eml file), outlook is able to open it, but it ignores Bcc line entirely.
So in another iteration, I would try to make a VBS script instead:
Set objoutlookApp = CreateObject("Outlook.Application")
Set objmessage = objoutlookApp.CreateItem(olMailItem)
objmessage.TO = "email@example.com;firstname.lastname@example.com"
objmessage.CC = "email@example.com;firstname.lastname@example.com"
objmessage.BCC = "firstname.lastname@example.com"
objmessage.Subject = "E-Mail Subject"
objmessage.Body = "Here comes some text"
objmessage.display
set objmessage = Nothing
set objoutlookApp = Nothing
wscript.quit

This seems a bit better, but is still insufficient. First of all, the VBS file cannot be in UTF-8 format, thus it's not possible to send an email in chinese, for example, I need to be able to write UTF-8 encoded string directly to the body since it needs to be a single-file solution. And second, I have no idea how to add atachments (multipart) this way.
Is there any way to open new message window in outlook with predefined fields (including Bcc), by a file which I can generate server side and then send to the user to open?
Comment: How about loading the UTF-8 body using ADODB: http://wiki.mcneel.com/developer/scriptsamples/readutf8
Answer: The Outlook object model provides three main ways for working with item bodies:

Body - a plain text without any mnarkup.
HTMLBody - a HTML markup which represents the message body.
The Word editor. The WordEditor property of the Inspector class returns an instance of the Word Document which represents the message body. So, you can use the Word object model do whatever you need with the message body.

It is up to you which way is to choose. See Chapter 17: Working with Item Bodies for more information.
You can use the Add method of the Attachments class which reates a new attachment in the Attachments collection. For example:
 Sub AddAttachment()
  Dim myItem As Outlook.MailItem
  Dim myAttachments As Outlook.Attachments

  Set myItem = Application.CreateItem(olMailItem)
  Set myAttachments = myItem.Attachments
  myAttachments.Add "D:\Documents\Q496.xlsx", _
    olByValue, 1, "4th Quarter 1996 Results Chart"
  myItem.Display
 End Sub

Finally, you may find the How to automate Outlook from another program article helpful.
Answer: Your VBS file cannot be UTF-8 encoded, but VB script works just fine with UTF-16 encoded files. I had no problem with the following file saved in UTF-16 encoding from Notepad:
Set objoutlookApp = CreateObject("Outlook.Application")
Set objmessage = objoutlookApp.CreateItem(olMailItem)
objmessage.TO = "firstname.lastname@example.com;email@example.com"
objmessage.CC = "firstname.lastname@example.com;firstname.lastname@example.com"
objmessage.BCC = "有些BCC名 <firstname.lastname@example.com>"
objmessage.Subject = "E-Mail Subject"
objmessage.Body = "Here comes some text"
objmessage.display
set objmessage = Nothing
set objoutlookApp = Nothing


C# - Tuple arrays are mutable, but tuple lists are not. How do I get around this?

Question: I have an array of value pairs I want to modify. I need to add and remove values from this array as well, so I used a list. When I tried to use a list, I encountered an error.
Error CS1612 - Cannot modify the return value of 'List<(int, float)>.this[int]' because it is not a variable
So I decided I would investigate. I tried using an array instead, and it... worked fine? The following code only throws an error on arr1[0].Item1 += 1;.
static void Main()
    {
        List<(int, float)> arr1 = new List<(int, float)>() { (0, 0) };
        (int, float)[] arr2 = new (int, float)[1];

        arr1[0].Item1 += 1; // This line
        arr2[0].Item1 += 1;
    }

Why are tuple arrays mutable, but lists are not? Is this because arrays are simple blocks of data you can modify easily, but lists have a lot of backend behind them that complicates things? Is there a simple way to get around this, or am I going to have to make my own custom class?
Comment: C# arrays are special in that accessing elements in them gives you a *reference*  to that element, while the indexer of a `List` returns a copy
Comment: @UnholySheep: I would avoid using the term "reference" here - it's already an overloaded term, and "reference" to a value type ends up sounding a bit weird. I think it's clearer to think of an array as a collection of variables.
Answer:
Why are tuple arrays mutable, but lists are not?

The list itself is mutable, but not in the way you're doing it. Note that this isn't anything specific to tuples - it's just the case for any mutable struct.
The list indexer getter returns a value (i.e. a copy of the tuple in your case) - so modifying that value wouldn't modify the copy in the list. The compiler is trying to avoid you making a change to a value that's about to be thrown away. Array access doesn't do that - arr2[0] refers to the variable within the array. (An array is effectively a collection of variables.)
If you want to mutate the list, you can have to fetch the tuple, mutate it, then put it back:
var tuple = arr1[0];
tuple.Item1++;
arr1[0] = tuple;

Note that this also explains why you can't use list access expressions as arguments for ref parameters, but you can do the equivalent for arrays:
public void Method(ref int x) => x++;

public void CallMethod()
{
    var list = new List<int> { 0 };
    var array = new int[] { 0 };
    Method(ref list[0]); // Error
    Method(ref array[0]); // Valid
}

Comment: Most probably only because `ref returns` didn't exist in C# at the time `IList` and `List` were introduced. If they were, then there wouldn't be such difference, which now has to be kept forever for backward compatibility.
Comment: @IvanStoev: Hmm... maybe. `IReadOnlyList` would *not* be able to use ref returns, which would introduce an odd inconsistency between those. (I suspect there are some more subtleties as well - when an array is copied due to list expansion, if you still had a `ref` to the "old" array, that could produce some really unexpected behavior. Basically I don't think it's a slam-dunk...)


Possível SHA256 retornar 128bytes após fazer assinatura?

Question: Estou usando o seguinte código para pegar meu certificado e assinar meus CNPJs,
porém estou usando o algorítimo SHA256, mas ele está retornando 128bytes.
Alguém sabe dizer o que está errado?
Segue o Código:
<code>  Dim data = Encoding.UTF8.GetBytes(Me.txtCNPJSoftwareHouse.Text + Me.txtCNPJEmpresa.Text)
  Dim csp As RSACryptoServiceProvider = DirectCast(cert.PrivateKey, RSACryptoServiceProvider)

            ' cert = certificado X509
            Dim sha As New SHA256Managed()
            Dim hash As Byte() = sha.ComputeHash(data)
            Dim encrypted As Byte() = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA256"))

            Me.txtBox.Text = Convert.ToBase64String(encrypted)
</code>
A variavel data fica com 28 bytes
A variavel hash fica com 32 bytes
A variavel encrypted fica com 128 bytes < - PROBLEMA
No final meu txtBox.text recebe apenas 172Bytes e deveria receber 344bytes se a variavel "encrypted" estivesse recebendo os 256bytes
Comment: E por que você acha que SHA256 vai ter 256 bytes? Ele tem 256 bits. pra falar a verdade estou tentando entender como ficou tão brande. Até existe a necessidade de 64 bytes para representar de forma hexadecimal, mas não 128. Será que está gastando 2 bytes por ser UTF-16? São *bytes* ou caracteres? Vou pesquisar. http://www.xorbin.com/tools/sha256-hash-calculator
Comment: encrypted não é um SHA256... E sim um RSA usando o SHA... SHA é um mecanismo de Hashing... RSA de criptografia.
Comment: O certificado é um arquivo .pfx correto ou uma chave? irei fazer um exemplo em c#
Comment: Entendi.
Vc teria alguma solução para esse caso o que posso estar fazendo para que eu chegue a esse resultado final de 344 caracteres?
obrigado.
Comment: Depende do que você quer fazer. Por que precisa chegar neste tamanho?
Comment: Pq isso seria uma chave de vinculo entre meu sistema e o S@T-Fiscal da Receita Federal, eles explicam que a chave assinada com meu ICP-Brasil(Certificado Digital) + a concatenação dos CNPJs (AC + Contribuinte) deve ser no total de 344Chars com Base64
Comment: Será que não está faltando alguma coisa? Não parece ser problema do SHA. Ou você tem alguma informação que demonstre que é?
Comment: Aqui nesse PDF disponibilizado pela Receita:http://www.fazenda.sp.gov.br/sat/downloads/Especificacao_SAT_v_ER_2_11_4.pdf
No paragrafo 2.1.3 Pag. 15 ele explica.
Comment: Daniloloko, entendi e qual seria a solução para isso?
Obrigado
Comment: Então Danilo, é um cartão A3, com 1 Chave privada e outra publica, e sim quando exportado ele pode ser um arquivo .pfx
Porém estou com a função de localizar o Certificado Conectado em meu micro, no caso a função busca a CHAVE PRIVADA!
Pode fazer, depois eu passo para o Vb,rs
OBRIGADO!
Comment: @FelipeWalleg Dê uma olhada no [tour]. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: O SHA-256 tem 256 bits e não 256 bytes. Estou tentando entender como ficou tão grande.
256 bits são 32 bytes. Até existe a necessidade de 64 bytes, ou mais precisamente 64 caracteres, afinal cada byte precisará de dois dígitos para representar em hexadecimal.
Não faço ideia de onde está saindo os 128 bytes. Só se for um problema de encoding e está usando UTF-16 que é o padrão de string para o .NET e que ocupa 2 bytes por caractere.
Comment: mas será que no `Me.txtBox.Text` não está convertendo para UTF-16? Só uma suposição, sem ver não dá para dar muita certeza.
Comment: Entendi, mas convenhamos que assim que ele passasse por aqui " Dim hash As Byte() = sha.ComputeHash(data)" Ele deveria gerar os 256 e não 128.
Aqui ele só disponibiliza UTF-7 / UTF-8 e UTF-32
Comment: Olha eu não tinha pensado nisso, e realmente faz sentindo.
Vou verificar...
Quer que eu poste algo para te ajudar?
É que já estou a tempos quebrando a cabeça com esse código e finalmente estou perto de terminar,rs
Answer: Irei apenas iniciar uma discussão doque pode estar acontecendo...
<code> Dim data = Encoding.UTF8.GetBytes(Me.txtCNPJSoftwareHouse.Text + Me.txtCNPJEmpresa.Text)
 Dim csp As RSACryptoServiceProvider = DirectCast(cert.PrivateKey, RSACryptoServiceProvider)

 //vou continuar o exemplo em c#(não entendo muito vb.net)

 byte[] signature = csp.SignData(data, "SHA256");
 bool isValid = csp.VerifyData(data, "SHA256", signature);//verifica se e valido

//Conversao para UTF8 caso for necessario ser lido...
string final = Encoding.UTF8.GetString(signature);
</code>
Um link que pode te ajudar
Voce pode utilizar o CryptoConfig.MapNameToOID("SHA256") ao inves de "SHA256", porem nao sei qual diferença irá causar.
Comment: isValid retorno true... tente debugar e ver se os dados estao certos realmente... string final = Encoding.UTF8.GetString(signature);
Comment: Opááá!
Vou passar para o VB aqui!!
Então eu uso o CryptoConfig.MapNameToOID("SHA256")
Porem ele está trazendo os 32 Chars, mas no caso se pegarmos esses 32(byte) * 8(bit), chego no resultado final.
Mas vou converter aqui para VB.net!
Obrigado mesmo!
Comment: Apenas utilizei a convenção que esta no link na resposta... nao sei se ira funcionar pois a conversao da receita pode ter alguma particularidade... Porem nada que tentando iremos descobrir :D
Comment: rsrs
Então, Danilo.
Seria engraçado se não fosse trágico,rs
Fiz a conversão do código consegui chegar na mesma chave criptografada que eu conseguia antes.
E deu a mesma coisa!
byte[] signature = csp.SignData(data, "SHA256"); = 128Chars =[
Comment: Então, está retornando TRUE, estou começando a achar que o problema é meu certificado A3, pq vi alguns usuários falando sobre essa chave feita no A1 e conseguiram o resultado final de 344chars
Comment: A assinatura signAC nao precisa ser exatamente 344 caracteres, é de 1 a 344... o assinaturaQRCOD sim! (pag 55)
Esse tamanho é refencial a key que foi passada para o RSA... o tamanho final sempre é baseado na KEY (http://stackoverflow.com/questions/6658728/rsa-signature-size). Ou seja... testa que ta certo!
Comment: Então, 172chars que está sendo a gerado está correto ?
Mas mesmo assim acho estrango os 256 gerar apenas os 128chars.
Mas blz, Obrigado mesmo por enquanto, Danilo!!


TypeError: list indices must be integers, not str. Know the issue, not the answer

Question: Unique situation, I know the problem, just dont know a solution.
import string

timefile = open('lasttimemultiple.txt','r+')#opens the file that contains the        last time run
lasttime = timefile.read()#reads the last time file
items= int(2)

splitlines = string.split(lasttime,'\n')
print splitlines[items][0:2]
timefile.close() #closes last time
PullType = '00'
datapt = '01'
for items in splitlines:
if splitlines[items][0:2] == PullType:
    datapt = splitlines[items]
else:
    print ''

print datapt

I know my issue is I am using 'items' as the index I am calling versus an integer, but I don't know how to use a reference to work through the data without using an non-int variable name.
Any ideas how to achieve this?
Thanks
Comment: Change `if splitlines[items][0:2] == PullType:` with `if items[0:2] == PullType:` and `datapt = splitlines[items]` with `datapt = items` ? Since we don't know the content of the file and what are you trying to extract from it - we can only guess...
Answer: You should show the actual traceback. If you had, you would have seen that the error is in this line:
if splitlines[items][0:2] == PullType:

That's because items here has been redefined by the for loop in the line before. In a for loop in Python, the variable is not a counter, it is the actual item from that iteration. So, in the first iteration, items is the first element of splitlines, etc. So it is a string, not an integer. The fix is to use it directly:
if items[0:2] == PullType:

(Also, you should think about better variable names: that should be item, not items).
Comment: This worked, Thanks! Also changed the varible names!


How to freeze first column while horizontal scrolling in Semantic UI

Question: I have a semantic ui stackable two column grid. i want to freeze the left column when scrolling .
I've created a plunker with my grid . i wanted to use sticky from Semantic but it didn't work. Do you have any idea  how to fix that?

    left

s
    right

Answer: It looks like the class definitions for column and sticky are clashing. Take .ui .sticky out of the column and add it as a child.

$('.ui.sticky').sticky();
.f-content {
  height: 1000px;
  background: beige;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.9/semantic.min.css" rel="stylesheet"/>

      Sticky

    Scrolling

    Scrolling

    Scrolling

    Scrolling

    Scrolling

    Scrolling

    Scrolling

    Scrolling

    Scrolling

    Scrolling


History of self-duets

Question: The lockdowns associated with current coronavirus pandemic have sparked production of self-duets. The Austrian-German concert violinist Augustin Hadelich has released a lot of piano-violin self-duets on his YouTube channel.
Back in 2016, fiddler Katy Adelson produced this interesting cello-violin self-duet -

Also back in 2016, Fran Guidry produced a guide to producing video self-duets using Reaper on YouTube and in his blog.
Self-duets predate the YouTube era. Back in 2006 on the album "You Raise Me Up: The Best of Aled Jones" there was a track featuring the adult, baritone Aled Jones accompanying his younger treble self on his 1985 hit "Walking in the Air".
Is this the earliest recorded self-duet? Have many musical artists been producing self-duets before lockdown?
Comment: @Dom According to the help center (https://music.stackexchange.com/help/on-topic) "What topics can I ask about here?" - "music theory, notation, **history**, or composition". This is asking about music history
Comment: FYI, when I was studying for my Bar Mitzvah in 1973, my temple's cantor had released an album containing a song where he sang all 5 parts of a vocal quintet.
Comment: This sounds like it would be more fit on the Music Fans SE.
Comment: History _is_ on topic, but this seems more in vein of the history questions that are better cared for on the Music Fan SE (there are several questions on the music fan's SE about recording firsts). The question to me seems to be more about finding the earliest out of appreciation rather than the typical topics of the site. There's not necessarily a hard line, but it feels more towards the fan site. There have also been other discussions about what qualifies as a history question in the past: https://music.meta.stackexchange.com/questions/2867/what-music-history-questions-are-on-and-off-topic
Answer: Self-duets of the sort you have in mind are an example of "overdubbing", a technique allowing a musician to record one part and then record a second part while playing back the first. The technique goes back to the very early days of recording technology. Wikipedia has a brief history.

Perhaps the earliest commercial issue of recordings with overdubs was by RCA Victor in the late 1920s, not long after the introduction of electric microphones into the recording studio. Recordings by the late Enrico Caruso still sold well, so RCA took some of his early records made with only piano accompaniment, added a studio orchestra, and reissued the recordings.

This is corroborated on the Victor Records website:

Some highlights of [Nathaniel Shilkret's] career include ... conducting some of the first overdubbed recordings onto Enrico Caruso's voice. (SOURCE)

The earliest example of a "self-duet" mentioned in the Wikipedia article is Sidney Bechet's 1941 recording of "The Sheik of Araby", on which he plays all of the instruments.
However, depending on how expansive you want the definition of "self-duet" to be, keyboardists have been playing self-duets since, at least, the invention of counterpoint for those instruments. One obvious example is the fugue, which requires the keyboardist to play several "voices" simultaneously. For example, here is Bach's Fugue in C Major from The Well-Tempered Clavier Book 1 (BWV 846).
If you require one musician to play to separate instruments, then whoever invented the "one-man band" would be the originator of the self-duet. This web article places one-man bands as early as the 13th century.

Certainly one of the oldest combinations of two instruments played simultaneously is the pipe and tabor, to which the earliest references appear in the 13th century.

Wikipedia corroborates this.
Comment: I would speculate that the "self-duet" is even older than the 13th century, and likely dates to the first time humans began creating music. Singing and clapping hands, for example, would be a "self-duet." There's also throat singing, which could be consider a form of self-duet.
Answer: By no means the earliest, but I'm just dropping this in as about the only appropriate place we've ever had for this example.
This guy is Yattie Westfield, apparently out of Birmingham, Alabama. The only footage of him you ever find is shot on phones, so sound & picture isn't great, but once you got beyond the initial, "WTF? OMG! Really? No!!" this is quite a display of limb independence.

History of self-duets


Google PlacePicker Closes Immediately After Launch with resultCode 2

Question: In my project PlacePicker was working fine but today suddenly its closing immediately after launch with resultCode 2.
here is the logcat output
07-06 16:06:36.596   1023-20519/? W/Places﹕ e.a:638: gLocReplyElement
unsuccessful status: 1

07-06 16:06:36.596   1023-20519/? W/Places﹕ e.a:665: gPlaceQueryResult
unsuccessful responseCode: 26

07-06 16:06:36.596  21086-21708/? E/PlacePicker﹕
PLACES_API_QUOTA_FAILED

Any idea? what is the meaning of PLACES_API_QUOTA_FAILED error code?
Answer: Assuming you have the Place API for Android enabled and your API key is correctly configured in your manifest, this could also happen if you are missing your SHA-1 certificate fingerprint(s) in your developer console. So, make sure you have the following covered:

In the developers console make sure you have the API key generated for your android app and make sure the API key is entered in your manifest file. It should be a meta tag nested inside the application tag.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.my.awesome.app">
    <application>
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIza..."/>
        ... other stuff
    </application>
</manifest>

On the same page as your API key, at the bottom, you need to enter the package name from your manifest and the certificates. While in development/debug mode you can use the certificate from the debug keystore supplied by the studio, however, for the release version you'd have to generate your own keystore.

To generate the keyhash for the debug mode:
keytool -exportcert -alias androiddebugkey -keystore C:\Users\{username}\.android\debug.keystore -list -v

Same command is used for the release version, but this time you'd need to point to your own keystore.
More info here
Answer: See here for info on the error code... It might throw a better error by now, but that used to mean something is wrong with your certificate fingerprints in the API Console.
We were having a similar problem (PlacePicker closing immediately with result code 2, except we did not have any relevant console output). We ended up fixing our issue by removing all fingerprints to get it working and then slowly adding security back:

Remove all entries under "Restrict usage to your Android apps" on the page for your api key in the credentials section of the Google API console
On the same key page, click "regenerate key" at the top (yes -- this was actually required for us @_@... you could try the old key again before doing this)
Test your app with the new key

If PlacePicker is now working, try adding security back in:
https://developers.google.com/maps/documentation/android-api/signup
Other info

Our devices were running Android API level 23 (Android 6.0)
Our app / module level build.gradle is using:
compile 'com.google.android.gms:play-services-maps:9.0.0'
compile 'com.google.android.gms:play-services-gcm:9.0.0'
compile 'com.google.android.gms:play-services-location:9.0.0'

Our project level build.gradle is using:
classpath 'com.google.gms:google-services:3.0.0'

```
Answer: The Google Places API for Android enforces a default limit of 1 000 requests per 24 hour period. If your app exceeds the limit, the app will start failing.
You can find complete explanation here
  https://developers.google.com/places/android/usage
Comment: yeah i know that i have checked developer console and its showing Remaining
1,000 requests/day
100% of total
and for that i think error code is different USAGE_LIMIT_EXCEEDED.


What food are the players served in a break?

Question: What food are the players served with, during a test match? I am asking this since they have to play game for 3-4 hours from the lunch time as well.
Answer: It completely depends on the venue. A "traditional" cricket tea in the UK & Ireland would consist of sandwiches, cakes and scones, with hot tea, but traditions vary across the world.
In general, though, the venue provides the catering, and what's served depends on cost, budget, dietary requirements of players & officials and tradition.
Comment: Given the question specifically refers to Test Matches I suspect budget isnt much of a consideration.
Comment: True, but I reckon the catering budget varies wildly from country to country, so it would come in to it somewhere along the line
Comment: Shane Warne was known for having a Meat Pie. Most players now days have healthier preferences.
Answer: When the match has lunch and tea, Lunch is usually a warm meal, with Tea being sandwiches, cakes etc.
Lunch would typically be something like pasta or perhaps chicken and rice.  The last all day game I umpired in we had a chicken currey with Rice.
Comment: What experience do you have umpiring at the Test Match level, which is what the question is asking about?


Is there any theory for the following series expansion method of solving PDEs?

Question: I am trying to solve a nonlinear PDE defined over the intervals $0 \leq t \leq 1$ and $0
\leq x \leq x_{max}$, which has the following form:
$4t(1-t)U_t(x,t)=U_{xx}(x,t)+2xU_x(x,t)-4t[U(x,t)^2-U(x,t)]$.
I am looking for the solution in the form:
$U(x,t)=u_0(x) + u_1(x)t + u_2(x)t^2 + ...$
The PDE is accompanied by simple two-point Dirichlet boundary conditions:
$U(0,t)=0,  U(x_{max},t)=1$.
and a known initial condition. I get a system of two-point BVPs for the functions $u_i(x)$. I solve these BVPs numerically and the results appear reasonable, but the series is very slowly convergent when $t$ approaches 1.
Is there any theory telling when such a solution exists and what might be alternative expansions if the above one is not suitable? I would appreciate any pointers to the relevant literature.
I especially need some information concerning how to obtain an accurate and quickly convergent expansion valid in the limit of $t$ approaching 1, if the (above) expansion around $t=0$ is not convergent or very slowly convergent in this limit. I tried an expansion around $t=1$:
$U(x,t)=v_0(x) + v_1(x)(1-t) + v_2(x)(1-t)^2 + ...$
but I find that only the first two terms of this expansion agree with the solution, I don't understand why.
Leszek
Answer: A bit strange, but
<code>du/ds == t (1 - t) du/dt /.
  {t -> E^s/(1 + E^s), dt -> D[E^s/(1 + E^s), s] ds} //  FullSimplify

 True
</code>
So its the standard diffusion operator $$\partial_s u - \partial_{x,x} u+\dots =0$$ with a drift term and a nonlinear production term.
Comment: Just for clarification, please: what software?
Comment: Yes, this PDE results from a certain reaction-diffusion problem, but the advantage of the present formulation is that an infinite (true)  time interval is reduced to the [0, 1] interval of t. Also, a growing-in-time spatial interval affected by diffusional changes is reduced to a fixed interval of x. Hence, by considering the present formulation one can consider a complete solution within a bounded t-x domain.
Comment: @paulgarrett The expression (minus the True) evaluates to True in Mathematica.


How can I find the name of the field store in the DB?

Question: I have a content type for which I have created my own img using cck like this:

How can I find the name of the table that stores the img field?
Comment: mention the Drupal version you are using
Comment: you would see a table with the name of the field. something like field_revision_field_image_field
Answer: Drupal 7
If the name of the image field is "Dark Image", then the table name in database will be field_data_field_dark_image
Drupal 6
As mentioned in this page, table name should be content_type_YOUR_CONTENT_TYPE_NAME. If the name of the image field is "Dark Image", inside the table you will find a column called field_dark_image that stores field data.
Comment: If a CCK field in D6 is used in multiple content types, it gets its own table.
Comment: The poster mentions using CCK, which is not available for Drupal 7.  I assume the question refers to Drupal 6.
Comment: @PatrickKenny The CCK module has a version for Drupal 7. From the screenshot, I take the OP is using Drupal 7. (The used theme seems the Seven theme.)
Answer: If indeed this is about D6, you have the following possibilities:

This image is only found in one content type:
a.  Look for a content_type_TYPE, eg, content_type_story, table.
b.  In there, you will have fields/columns like:
  i. field_dark_image_fid -- the file id of the image file
 ii. field_dark_image_list -- a boolean used basically to show if the file is there and is listable (eg if it isn't a required field, these columns are still here)
iii. field_dark_image_data -- a serialized blob of other info about the file, alt, title, height, width etc

The image is found in multiple content types:
a.  Look for a content_field_FIELDNAME table, eg, content_field_dark_image
b.  In there, look for similar fields/columns as in 1. above that are linked back to your content type via the nid and vid fields/columns.

In both scenarios, more/major information about your image field is contained in the files table, which is indexed off of the ..._fid field/column above, and there you can find information such as uid, filename, path, mime type, size, creation date etc.


Declaring highwater property in Migrate

Question: I would like to know how to correctly define the highwater property when using Migrate for Drupal 8. I am doing an import from a legacy non drupal database and I should be able to update only the relevant nodes whenever a column highwater changed. According to the official documentation, the solution is to use a highwater property. How to declare it? Is it a property to be set in the Plugin mapping class or is it an entry in the migrate.migration.*.yml file?
Thanks!
Answer: highWaterProperty renamed to high_water_property, and moved from the top-level migration plugin configuration into the source plugin configuration.
id: my_migration
source:
  high_water_property:
    name: changed

For more information, see: https://www.drupal.org/node/2795403
Answer: You can add "high_water_property" in your migration config entity:
id: my_migration
source:
  high_water_property:
    name: changed
    alias: n

From the documentation:
- high_water_property: (optional) It is an array of name & alias values
  (optional table alias). This high_water_property is typically a timestamp
  or serial id showing what was the last imported record. Only content with a higher value will be imported.
Note: The high_water_property and track_changes are mutually exclusive.
Note: If you're not using SqlBase in your source, you might also want to implement something similar as shown there.
Comment: Thanks Berdir for the answer. I will try the patch and give feedback
Comment: The patch has in #2485385 has been fixed. The answer below is more up to date.

Declaring highwater property in Migrate


Object Browser inside the Android Studio

Question: I need to navigate through the whole android api objects inside the Android Studio to find out classes that extend an individual class and also list of class and interfaces that is extended by an individual class in a hierarchy form.
In a simple word I need something like visual studio's Object Browser inside the android studio.
any solution?
Answer: Navigate menu > Type Hierarchy.
Comment: thanks for your suggestion, also regard to your answer I found that simply putting the cursor on desired class and pressing the **Ctrl + H** the same window will be opened, where you can select _Class_ Hierarchy, _Supertypes_ Hierarchy, _Subtypes_ Hierarchy from the top menu.
Comment: Not sure if I don't know how to use this Type Hierarchy but this is not like ***Object Browser*** in Visual Studio at all, you can navigate all classes and components of some assembly using ***Object Browser*** but this `Type Hierarchy` is not something like that.
Comment: My god this is insanely helpful
Answer: This is what comes with the IDE: into Project Tab, select Project View, and browse the External Libraries.
Answer: Updating info since the question is from '13
Sadly I couldn't find anything after about an hour of digging beyond the 2 awkward and not comparable answers above.
My solution was to create a chrome window app of the page located at:
https://developer.android.com/reference/packages.html
It's only after you leave Visual Studio that you understand why people say VS users are spoiled. I guess Balmer really meant it when he said it - DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS =)


What's a good metric for determining the performance of my ethernet link across my optical comm. channel?

Question: I have a system that I've built for using optical signals to communicate underwater. I'm using a GNURadio + USRP system to test this and I have a program that creates an ethernet connection across my system. I need to measure the link quality as a function of communication distance, water quality, etc.
My question is what method should I use to measure ethernet link quality, and how? Say I have a FTP connection, how would I go about measuring and plotting the retransmits? Or, is there an easy way to directly measure TCP packet CRC failures? What other useful metrics could I gather? I want something more high-level than bit-error rate vs. signal/noise.
Answer: Wireshark is a very useful tool for examining ethernet links.
Ethernet has its own check that it performs before TCP's check. It is the Ethernet layer that catches line errors and is probably the best place to be investigating.
Comment: @Kellenjb As you probably know, if Ethernet recognizes a corrupt frame it does not retransmit, it leaves that to a higher level protocol (typically TCP).
Comment: @blankabout correct. Thanks for clarifying my post.
Comment: @gallamine By checking for link layer errors you are able to determine the performance of the link you created. If you go any higher level then that then there can be errors and dropped packets that have nothing to do with your link, but rather just the nature of Ethernet networks. It is best to not deal with these in your situation.
Comment: @Kellenjb, I have wireshark installed. You're suggesting I track the LL errors there? Is the layer exposed to Wireshark, or should I track TCP retransmits as a proxy metric?
Answer: Netperf seems to be a popular tool for analyzing ethernet links. I think it is installed by default in Ubuntu.
Answer: I tried to find such a tool to verify my long range WiFi link but the best thing I came up with was ping.
sudo ping -i 0.01 -c 10000 -s 1024 192.168.17.2

You can change both the interval -i (in seconds) and packet size -s (in bytes) to change the bandwidth utilization. Large packet sizes are also more sensitive to link errors (1 bit error will cause the whole packet to be discarded) so expect higher lost packet counts with bigger -s.
Comment: These are OS X (really BSD I guess) ping arguments but this will work on both Linux and Windows if you adjust the option letters.
Comment: This worked on my Linux system (Fedora 14) with no complaints, as is. No adjusting needed.


ORM Doctrine ManyToOne on update CASCADE (Symfony)

Question: I have two entities
class Promotor
{

/**
 * @ORM\ManyToOne(targetEntity="Ciudad", inversedBy="promotor")
 * @ORM\JoinColumn(name="ciudad_id", referencedColumnName="id", nullable=false)
 */
protected $ciudad;

and
class Ciudad
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="nombre", type="string", length=50)
 */
private $nombre;

A "Promotor" can live in one "Ciudad" (City). And in a "Ciudad" (City) can live many "Promotores".
If i add onDelete="CASCADE" in JoinColumn
/**
 * @ORM\ManyToOne(targetEntity="Ciudad", inversedBy="promotor")
 * @ORM\JoinColumn(name="ciudad_id", referencedColumnName="id", nullable=false, onDelete="CASCADE")
 */
protected $ciudad;

it generate the next code
ALTER TABLE promotor DROP FOREIGN KEY FK_BF20A37FE8608214;
ALTER TABLE promotor ADD CONSTRAINT FK_BF20A37FE8608214 FOREIGN KEY (ciudad_id)
REFERENCES Ciudad (id) ON DELETE CASCADE

but also i like do CASCADE on update. I try with onUpdate="CASCADE" but it doesn' work
[Doctrine\Common\Annotations\AnnotationException]
[Creation Error] The annotation @ORM\JoinColumn declared on property     Web\PromotorBundle\Entity\Promotor::$ciudad does not have a property named
"onUpdate". Available properties: name, referencedColumnName, unique, nulla
ble, onDelete, columnDefinition, fieldName

By the error I understand that the property onUpdate does not exist, but.. Is there any way to do cascade on update?
Comment: I found this note in the documentation of doctrine, but I do not understand. It is no longer necessary to control the cascade on update. In theory it will never change the ids

http://www.doctrine-project.org/jira/browse/DDC-725?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
Answer: The onDelete="CASCADE" is used on the database level. As you already said there is no onUpdate. Another downside is that ON DELETE CASCADE only works on InnoDB. It doesn't work on MyISAM.
But you can use Doctrine in-memory cascade operations:
class Promotor
{

/**
* @ORM\ManyToOne(targetEntity="Ciudad", inversedBy="promotor", cascade={"persist", "remove"})
* @ORM\JoinColumn(name="ciudad_id", referencedColumnName="id", nullable=false)
*/
protected $ciudad;

It's all described in the documentation: https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html#transitive-persistence-cascade-operations
Plus you can skip the JoinColumn annotation, because the way you have it written, is the default configuration and it's generated implicitly.
So you can just write:
class Promotor
{

/**
* @ORM\ManyToOne(targetEntity="Ciudad", inversedBy="promotor", cascade={"persist", "remove"})
*/
protected $ciudad;

Comment: I think I figured it out: As per documentation `The inversedBy attribute designates the field in the entity that is the inverse side of the relationship.` The key word is `field in the entity` - it is a field in other entity (but in the other entity representation in the database there will be NO extra fields added for that relationship). And it is still MTO to OTM relationship.
Comment: BTW, how come there is `inversedBy="promotor"` on the `$ciudad` property, if the `Ciudad` entity does NOT have field `$promotor` ? (And even from the nature of MTO relationships, it CAN NOT have 'inverse' reference to `Promotor` at all)?
Comment: You are right, there is no `promotor` property on the `Ciudad` entity. So there can't be `inversedBy="promotor"`.
But you're wrong about the ManyToOne relationship and the `inverse` reference. ManyToOne has `inverse` and OneToMany has `mappedBy`.
Comment: Sorry, my wording was not precise enough. When I said 'inverse' I actually meant same `inversedBy`.
Also though it seems logical what you have said (that there can't be `inversedBy="promotor"`) I looked up the docs for `@ManyToOne` http://doctrine-orm.readthedocs.org/en/latest/reference/annotations-reference.html#annref-manytoone and it mentiones this `inversedBy` parameter (though not as obligatory). But I am still confused as of - how come an MTO relationship may have `inversedBy`? Isn't it true that, may there have been `inversedBy` that would be ManyToMany relationship?


Can a boost::lockfree::queue be checked for full?

Question: I am using a boost::lockfree::queue Foo(128).
Before Popping the queue I can check the queue for empty status by Foo.empty() function.
I was wondering if I can check similarly for its status at full capacity before Pushing! Couldn't find any resource online explaining how to do it.
Any suggestions?
Answer: It appears Boost's LF multi-producer multi-consumer queue implementation doesn't support this.  Other MPMC queues might.
boost::lockfree::spsc_queue (single-producer single-consumer ring-buffer queue) does, with spsc.write_available() > 0.

boost::lockfree::queue is not fixed-size by default, only if you pass a capacity as a template arg, or fixed_sized<true>.  If the data structure is configured as fixed-sized, the internal nodes are stored inside an array and they are addressed by array indexing.  (But it's not a ring-buffer like some other MPMC queues.)  Otherwise they're dynamically allocated and kept on a free-list.
For performance you probably should make it fixed-size.  Or if you want to limit dynamic allocation, you can use bounded_push instead of push, so it will return false instead of going to the OS for more memory (which might not be lock-free).

If you are using a queue<fixed_size<true>>, then it is possible for the queue to become full.
But It wouldn't be very meaningful to check separately because another producer could have made the queue full between the check and the push.  Are you looking for a performance optimization like avoiding constructing the object if the queue would probably still be full by the time you're ready to call push?
(Also, a consumer could make the queue non-full right after you check, so it really only makes sense to check as part of an attempted push.  And perhaps there isn't even an efficient lock-free way to check.  Otherwise they could have had the function always return true for non-fixed-size queues, and return a meaningful result for fixed-size.)
This is why push() returns bool: false means the queue was full (or a new node couldn't be allocated for non-fixed-size queues).

Before Popping the queue I can check the queue for empty status by Foo.empty() function.

I hope you're not actually doing this; it has all the same problems of racing with other threads as push, and with fewer opportunities to optimize.  There's no object to construct before the attempt, you just call pop and see if you get one or not.
Another thread could have made the queue empty, or made it non-empty, between your check and your actual pop.  Unless you're the only consumer, in which case seeing non-empty does mean you can definitely pop.  A multi-producer single-consumer use-case would not be compatible with spsc_queue.
Anyway, this is why it's bool pop(T &); not T pop().
Comment: That was a nicely drafted answer. Thanks :)


TeamCity, nginx, and Websockets - 501 Error

Question: I'm currently setting up TeamCity behind an nginx reverse proxy, but I am getting an error in my browser. The error is as follows:
WebSocket connection to 'ws://ci.example.net/app/subscriptions?X-Atmosphere-tracking-id=0&X-Atmosphere-Framework=2.2.7-javascript&X-Atmosphere-Transport=websocket&X-Atmosphere-TrackMessageSize=true&X-atmo-protocol=true&browserLocationHost=http%3A%2F%2Fci.example.net' failed: Error during WebSocket handshake: Unexpected response code: 501

I've looked in both the nginx error logs and the TeamCity error logs, both of which turn up empty.
My nginx config is as follows:
server {
  listen 80;
  server_name ci.example.net;

  error_log /var/log/nginx/error.log;
  proxy_intercept_errors on;

  error_page 401 403 404 /404.html;

  location / {
    proxy_set_header        Host $host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header        X-Forwarded-Proto $scheme;

    proxy_pass          http://127.0.0.1:8111;
    proxy_read_timeout  90;

    proxy_redirect      http://127.0.0.1:8111 http://ci.fluxmc.net;
  }
}

#Websocket configuration
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''   '';
}

server {
    listen 400;
    server_name ci.example.net;

    error_log /var/log/nginx/error.log;
    proxy_intercept_errors on;

    location /tc {
        proxy_pass http://localhost:8111/tc;
        proxy_http_version 1.1;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $server_name:$server_port;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }
}

I am really not sure where to go from here, I've followed the documentation for TeamCity almost exactly. If you could provide any help, I would appreciate it!
Comment: Did you ever find out the problem? I'm running into the same issue right now. I've added the `` setting to `server.xml` as well.
Answer: The documentation for TeamCity makes a couple of assumptions that don't hold up for you:

TeamCity server is installed at URL: http://teamcity.local:8111/tc
It is visible to the outside world as URL: http://teamcity.public:400/tc

In your case TeamCity is visible to the outside world as URL: http://ci.example.net.
This changes your NGINX configuration as follows:
server {
  listen 80;
  server_name ci.example.net;

  error_log /var/log/nginx/error.log;
  proxy_intercept_errors on;

  error_page 401 403 404 /404.html;

  location / {
    proxy_set_header        Host $host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header        X-Forwarded-Proto $scheme;

    proxy_pass          http://127.0.0.1:8111;
    proxy_read_timeout  90;

    proxy_redirect      http://127.0.0.1:8111 http://ci.fluxmc.net;
    proxy_http_version  1.1;
    proxy_set_header    Upgrade $http_upgrade;
    proxy_set_header    Connection $connection_upgrade;
  }
}

#Websocket configuration
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''   '';
}

For me, that was enough to get the websocket connection with TeamCity working.


Precedents for Excluding Athletes from Sport Based on Nationality

Question: There has been a lot of talk recently about excluding Russians and Belarusians from sport. The general idea seems to be that the sporting bodies don't want to give the players a platform to speak. Lots of places are banning teams, but fewer are banning players. Excluding someone on the basis of what their country is doing is a pretty big step—one that I haven't seen in a long time.
There are well-documented human rights abuses in a variety of countries, but these tend to be internal; it has been a while since one country has been so openly hostile to another.
These exclusions are, of course, fraught with difficulties over fairness, productivity and the like. This post isn't intending to discuss those—they are perhaps better suited to another SE, such as politics, anyway. Rather, it asks,

What examples are there in recent history where individuals and/or teams have been banned from competing on the basis of disapproval of their country's actions?

Certainly, a lot of exclusion of Russians and Belarusians is going on at the moment. I am interested in this historical context of these decisions, whether they have solid precedent or not.

It seems like there are a number of cases related to the exclusion of national teams—see the answers given below. I would be particularly interested if anyone has examples for individuals.
My main sport is tennis, so I had a look at Davis Cup—the team–tennis tournament. It seems that Yugoslavia was part of it in 1999 and Yugoslavians were playing tennis, pretty much as normal, throughout that year. This is the year in which Belgrade was bombed for ~7wks consistently by NATO. It's hard to get information on tennis over 20yrs ago, but it doesn't seem like players were excluded—but, as I say, it is hard to find information.
Wimbledon is (currently) banning Russian and Belarusian players—they can play on the world tour under a neutral flag and at French Open, but Wimbledon is forbidding their participation at all. Precedent for this decision was actually my main motivation for this question.
Comment: @ImClarky That's a difficult one! I would probably say, "No, it isn't included." My understanding is that it's the Olympic team which is excluded, due to actions that the team has taken—namely, doping. Sure, it was state-sponsored. But it's because of what the team did and the lack of trust in the legitimacy of its actions. The members still play as ROC/similar, so they aren't excluded.
Comment: @user24601 I'm going to revert your most recent change here. I appreciate this is your preferred style, but Stack Exchange style is for the question to read as one body of work without "updates" or the like. On a more minor note, the title should be a question, not a statement and we use typical American English capitalisation (i.e. only proper nouns are capitalised).
Comment: @PhilipKendall I have made it all a single flow, no update. I prefer title cases for titles and sentence cases for sentences. There is no rule on this as far as I can see and there are many examples of both. I have thus chosen to leave it in my preferred format. Hope you understand :)
Comment: Do state-run doping programs count? On the one hand, it's a country's actions to perform such actions into which they were subsequently banned, but on the other hand, it's a "internal" sporting matter rather than an "external" matter as is the case currently. The specific example I'm thinking off is the "official" exclusion of Russia from the Olympics, with some Russian athletes competing as members of the ROC.
Answer: The major precedent for this would be apartheid-era South Africa. From 1964 until the end of apartheid, South Africa was excluded from the Olympic Games due to its refusal to field an integrated team. In 1976, 25 other African nations demanded that New Zealand be kicked out of the IOC for conducting a rugby tour of South Africa, and when the IOC refused, those nations boycotted that year's Montreal Olympics in protest.
In the years following the Olympic exclusion, South African teams and athletes were systematically frozen out of pretty much every single international sporting competition. They were banned from the FIFA World Cup staring with England '66 (and expelled from FIFA entirely in 1976), the first two Rugby World Cups in 1987 and 1991, and the Davis Cup from 1979 after an initial ban between 1970-1972. Formula One, however, continued to hold races in South Africa until 1985, when it was boycotted by multiple teams and drivers.
Comment: @user24601 I've updated the answer to add a few more specific examples, including the Rugby World Cup.
Comment: Ah, I have enough rep to give +1 now! Thanks again for the references :)
Comment: Don't forget that worked both ways.  South Africa refused entry to the England cricket team because of the selection of Basil D'Oliviera.
Comment: Good example! I tried to +1, but not enough rep. I always feel that Olympics are very country-centred—I guess particularly because of all the sports together, with the different sportspeople all considered part of the same team even cross-discipline. A more pertinent example would be, eg, SA being banned from Rugby World Cup due to apartheid. Still, a good example all the same, thanks!
Comment: I see, eg, that SA played cricket in England in 1965, whilst banned from Olympic Games. Australia played in SA in 1966–1967. However, England and Australia clashes with SA were cancelled in 1970, but only after protests, it appears. @Chenmunka is this the tour you were referencing?
Answer: Actually looking at Yugoslavia was a good  idea, but the year was wrong. Yugoslavia qualified for the football European Championship in 1992, but was disqualified only a few weeks before the tournament, Denmark had to play instead. The Danish players had to be literally called from the beaches (they were already on holiday), but eventually won the whole thing.
Comment: Thanks for the references! Interesting to see when countries are/aren't banned. Funny anecdote, too, about Denmark—I'll have to remember that one!
Comment: I was just reading a little on that UN sanction. It's interesting that they were disqualified—if I'm reading it correctly—in essence by the UN. It wasn't the the Euros made a decision to disqualify them on their own, in the style that Wimbledon is. Moreover, Yugoslavia were not invited to the Olympics that year, but *individual* Yugoslavians *could* enter as independents—somewhat akin to the current Russian Olympic ban
Comment: Ah, I have enough rep to give +1 now! Thanks again for the references :)


Change Hyperlink Color in Views

Question: I am looking for a way to change the hyperlink for Node title on a view. So far have tried rewriting the Node title field and also tried a global text field but links still show as blue.
Tried this but did not work:
{{ Node Title }}
What is the best way to change link color in views?
Comment: What output are you getting from that code? It must be something in your syntax or Views concepts. Inline styles should work, even though that isn' the proper way (to mix content and presentation).
Answer: The correct way to style websites is with CSS.
You can use a selector from the existing Views output, or you can assign a special class to your Content: Title Field under Style settings. You can Create a CSS class for the field wrapper or the HTML element.
Then use the class selector in your CSS inside the theme:
.my-class a {
  color: #cc0000;
}

If you're not creating your own (sub)theme and only want to make minor adjustments you can use the CSS Editor or CSS Injector modules.

Change Hyperlink Color in Views


How to see that $\mathbb Q (z_1,\ldots,z_n, \bar z_1,\ldots, \bar z_n)$ is closed under conjugation?

Question: How to see that if $z_i \in \mathbb C$ then $\mathbb Q (z_1,\ldots,z_n, \bar z_1,\ldots, \bar z_n)$ is closed under conjugation? The claim is made in a proof that a number is constructible from $z_i$ iff it's in some square root tower over the above field.
Answer: Notice that $\mathbb{Q}$ and $\{z_1,\ldots,z_n,\overline{z_1},\ldots,\overline{z}_n\}$ are closed under conjugation and recall that $\mathbb{Q}(z_1,\ldots,z_n,\overline{z_1},\ldots,\overline{z}_n)$ is the smallest field containing $\mathbb{Q}$ and  $\{z_1,\ldots,z_n,\overline{z_1},\ldots,\overline{z}_n\}$.
Comment: I still can't see it. Could you please elaborate?
Comment: Let $K:=\{\overline{z};z\in\mathbb{Q}(z_1,\ldots,z_n,\overline{z_1},\ldots,\overline{z_n})\}$, it is a field containing $\mathbb{Q}$ and $\{z_1,\ldots,z_n,\overline{z_1},\ldots,\overline{z_n}\}$ and hence $\mathbb{Q}(z_1,\ldots,z_n,\overline{z_1},\ldots,\overline{z_n})$.
Comment: Aha. Nice. Thanks
Answer: Concretely, the field $\Bbb Q(z_1,...,z_n,\bar z_1,...,\bar z_n)$ consists of all rational functions (i.e. quotients of polynomials) in $z_1,...,z_n,\bar z_1,...,\bar z_n$ with rational coefficients.
Since complex conjugation fixes the coefficients and interchanges $z_i$ with $\bar z_i$, it transforms a rational function in $z_1,...,z_n,\bar z_1,...,\bar z_n$ into another.


Drupal 8 page manager and panels contextual filters for views_block

Question: I'm working with Drupal 8(first project with 8) and trying to build page (via page manager) with taxonomy tid argument.
As a display variant I use panels and inside of panel I put block, generated by views and this views_block have contextual filter.
I haven't found the way for how to attach my contextual filter to views_block plugin from panel or associate context to anywhere.
From debug session I know what panels have my argument as a context.
But how to pass it to views_block plugin inside of panel?
Thank you for any help and information. I'm ready to digg inside of code(and contribute also, if needed) to solve this.
Comment: I don't know the answer to this, since I haven't used Panels for D8 yet. I know in D7 you can pass the argument to the view. But another option you have is to have the view pickup the argument instead. So what exactly do you want to pass to the view? the Node ID?
Comment: I want to pass taxonomy id. In d7 ctools provide modules Views content panes, what extend views pane settings and give option Argument input for source selection.
Comment: `I want to pass taxonomy id` so your node is a taxonomy term?
Comment: My node have attached taxonomy and i want to use filter by them
Comment: Taxonomy reference, right?
Answer: Alternative, you can use Views to pick up the tax term id's

If your node has multiple tax terms, you need to allow multiple values for your contextual filter
Comment: It's works for me only like this http://prntscr.com/bqcgho
Comment: I found ctools_views module without appropriate code about Argument input as it was in Drupal 7. May it's no longer useful, perhaps it is in development. In any case at this moment, i'm follow the solution referred above and pick up arguments directly from url.
Thank You.
Comment: @KirilLazur I guess that works too, if my solution doesn't work try unchecking the `load default filter from node page`.
Comment: @No Sssweat your answer works BUT it's not related to the question which is how to pass the view argument to the panel pane!


Generate all binary combinations possible

Question: I would like to specify a number of bits, and then get an array containing every possible combination of these bits, in PHP.
Example:
<code>number: 3
000
001
010
011
etc...
</code>
I have tried recursive algorithms which were originally designed for strings, so the algorithm is too slow.
What is the most efficient way to do this?
Answer: The nice part about bits is that you can do really simple stuff with them. If you want 3 bits, you'll have 7 numbers, which happens to be 8-1. If you want 4 bits, you'll have 15 numbers, which happens to be 16-1. Use this nice fact to make your code simple.
<code>$bits = 4;
$max = (1 << $bits);

for ($i = 0; i < $max; $i++) {
    // Use $i
    // echo str_pad(decbin($i), $bits, '0', STR_PAD_LEFT);
}
</code>
Comment: So, who downvoted me? And why? You're not going to tell me that there's an easier way to do this, right? :-)
Comment: I thought that the nice part was that enumerating numbers and counting are the same thing.
Comment: @Sosumi PHP has nice [`decbin`](http://php.net/manual/en/function.decbin.php)and [`str_pad`](http://php.net/manual/en/function.str-pad.php)functions.
Comment: So using decbin and str_pad on $i will give me every 3-bit combination possible...? Because it doesn't seem to be working for me. I'd like it to go from 000 to 111 and include every combination in between, however it seems to skip some combinations.
Comment: My code will bring you from 0 (0b000) to 7 (0b111) if `$bits` is set to 3, yes. You may like to `str_pad(decbin($i), $bits, '0', STR_PAD_LEFT)` to get a string version. (added that to my answer)


jquery mobile clips text when there is not enough space

Question: jquery mobile clips text when there is not enough space, but is there a native way to make it scroll? Is there a plugin or something that could handle this? I can write some custom code, but I'm new to jmobile so why waste time if there is built in functionality :)
Comment: Did you try `overflow: auto` ?
Comment: @Tim Bad wording on my part, I want it to scroll as reveal what is hidden with animation. I could have used white-space: normal; to show hidden text. But that is not my intended question.
Comment: @Tim I'm looking for something like this: http://remysharp.com/demo/marquee.html
Comment: Ah, I misunderstood sorry. Did you get it to work with jQuery Marquee?
Answer: you could have something like this for window width (450px):

Home

<marquee scrollamount="6" behavior="alternate" direction="right" width="250">
START Lorem epsom
</marquee>

Menu

with the style:
div.demo {
          padding-left: 100px;
         }

This can help if you have fixed width device support, else need to programatically update the padding-left value and the marquee width.


Amanda, Bacula, BackupPC Which has a reliable windows client?

Question: I wish to setup an automated backup system for three Windows XP machines in the same building to a Linux server out on the WAN.  I visit each machine every few months and make a disk image for a bare metal recovery.  I need a way to automatically backup user documents (including Outlook's mailbox file).  This is for a small daycare/preschool and therefore needs to be a low budget project.
There will be no qualified sysadmin on site daily to deal with problems.  The backup needs to run without user intervention and without fail.
The file recovery needs to either be accomplished remotely (i.e., they call me; I push the recovered file back to their system), or simple enough for a non-techie to operate.
As I see it the candidate systems are Amanda, Bacula and BackupPC.  Reading the docs I see that BackupPC is probably out of the running because it does not do Volume Snapshot Services (VSS).  What is your practical experience with these systems?  Is there some other system that I should be considering?
Comment: +1 for asking the about the clients for each option. I've used both Amanda and Bacula as server backups but never client. It would be interesting to hear from others for possible solutions.
Answer: Bacula has a Windows client (that can be either desktop or server clients) that handles backups quite well. It utilizes VSS to create hot images of whatever you're looking to backup (works fine with Outlook AFAIK). You can set the desktop clients to use different ports than the default (9101 I think?) and port forward requests from their WAN router to each individual computer. Something with a VPN would be preferable, but not always possible.
Amanda and BackupPC use samba shares to backup - not exactly ideal, especially over WAN.
Additionally, Bacula has a bartpe plugin to do bare-metal recoveries, something that I haven't found for Amanda or BackupPC. The problem is that bare-metal recoveries are going to be tough (read: not impossible) to do remotely. I'm thinking your best bet with that is to have the clients boot to PXE where you recover the files to the client PC, or something similar. Either way, it'll be tough to set up.
Currently I use Bacula to backup 2 servers, 8 Windows clients, and 3 Linux clients, and it works very well. It has a number of front ends, with a python based graphical tool coming soon.
Recoveries are done to a server's local directory, then you can copy/push files to the clients that need them.
For what you're looking for, I think this fits the bill.
Comment: For the record, BackupPC can also use rsync for backing up, which is how I use it.
Comment: You can restore files to the remote file system using bacula too. I'm not an expert at it, but we certainly use it to do so, having set the storage device (?) to that of the client.
Comment: Thanks for pointing that out - I (obviously) haven't experimented with that yet.
Comment: One correction. Bacula can and does restore to remote systems as well. Bacula also can do TLS encrytpion between the File Deamon (client) and the servers. Also it can even encrypt the data on the client if the information is sensative. I use bacula to backup about 59+ servers with my full backups storing over 12TB of data.
Answer: Amanda has a Windows Client from zmanda which support VSS:
http://wiki.zmanda.com/index.php/Zmanda_Windows_Client
Comment: I see that it supports VSS, but does it also support NTFS ACLs, and does it run with Backup Operator privileges so it can bypass ACLs and backup everything?
Answer: backuppc can also use VSS, via the rsyncd+vss method, check the url:
http://www.goodjobsucking.com/?p=62
It uses the windows RPC to remotely start scripts that setup the VSS and startup a rsync daemon.
i already build the needed "client" scripts and tools in here, so its easy to install:
http://caravela.motaleite.net/~higuita/backuppc/
i use this on +500 workstations and +50 servers with windows xp, windows 2003, vista, 7 and 2008 32bit and 64bits.
other package with the same scripts (version 1.1 doesn't seem to support 64bit, but do have wake-on-lan support):
http://www.michaelstowe.com/backuppc/
As it uses a windows service and no encryption, i recommend this for LAN usage, if you need security (as for WAN usage) you will want to setup a vpn to protect the traffic and the clients. check the openvpn, its easy to setup and secure.
If you need WAN and cant use a vpn, you can also check the cygwin ssh+rsync method:
http://sourceforge.net/apps/mediawiki/backuppc/index.php?title=CygwinSSHWindows
http://sourceforge.net/apps/mediawiki/backuppc/index.php?title=User_Scripts_-Client-_Windows_VSS


Are confidence intervals always symmetrical around the point estimate?

Question:
Possible Duplicate:
Binomial confidence interval estimation - why is it not symmetric?

Are confidence intervals always symmetrical around the point estimate?
Comment: This question is readily answered by a quick internet search on "confidence interval."  For instance, Wikipedia links to http://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval where non-symmetrical intervals are exhibited.  A [quick search](http://stats.stackexchange.com/questions/4713/binomial-confidence-interval-estimation-why-is-it-not-symmetric) on this site immediately answers the question.
Answer: Short Answer: No
Long Answer: It depends.
A confidence interval obtained from an analytical technique (a formula) will be symmetrical around the point estimate on a particular scale. For example, Hazard Ratios, Risk Ratios and Odds Ratios are symmetrical around the point estimate on the natural log scale. They aren't necessarily on other scales, which is often while you see them graphed on the log scale.
Confidence intervals obtained by other techniques, like bootstrapping, simulation, or credible intervals in Bayesian analysis, often are, but need not be.


activemq url starts with scp://

Question: I have inherited a system where the activemq address looks like this scp://localhost:61616
ActiveMQ itself only seems to be configured for tcp.  I can't find any reference to that protocol here: http://activemq.apache.org/activemq-connection-uris
Has anybody seen this before?
Comment: Is the `scp://localhost:61616` used as a connection string?
Comment: yeah - and works
Comment: Which version of ActiveMQ you're using?
Answer: SCP is not supported by default in ActiveMQ for the connection string (checked in 5.16.x, 5.15.x e 5.14.x), but there may be a few explanations for why that works:

The code is manipulating the URI to ignore the protocol definition. You can confirm this behaviour by replacing scp to anything else and checking if it still works.
There's a custom implementation of the protocol, as the ActiveMQ loads it's implementations using reflection. If that'd be the case I'd glad to see what are your use cases for implementing communication over scp.
Comment: thanks - something else was ignoring the protocol.  but thanks for confirming that it doesn't exist

activemq url starts with scp://


Operator norm $4$ different definitions how to prove that $\sup$ is $\max$ and $\inf$ is $\min$ for the last two?

Question: From what I have understood, all the $\sup$'s and $\inf$'s in the $4$ different definitions of the operator norm can be taken as $\max$'s and $\min$'s.
For a linear map $A\in \mathscr L (V,W)$ between two vector spaces $V$ and $W$ (of the form $\mathbb R^k$):
$$\begin{align*}
I &= \inf\{ c\;\colon\; \lVert Av\rVert\leq c\lVert v\rVert \text{ for all }v\in V\}\\
S_1&=\sup\{ \lVert Av\rVert\;\colon\; v\in V\text{ with }\lVert v\rVert\leq 1\}\\
S_2&=\sup\{\lVert Av\rVert\;\colon\; v\in V\text{ with }\lVert v\rVert = 1 \}\\
S_3&=\sup\left\{ \frac{\lVert Av\rVert}{\lVert v\rVert}\;\colon\; v\in V\text{ with }v\neq 0\right\}.
\end{align*}$$
As $\{ x\in V \mid ||x|| \leq 1\}$ and $\{ x\in V \mid ||x|| = 1\}$ are compact, as the composition of the absolute value with $A$ is continuous and as this composition is a real-valued function, we can conclude that the $\sup$ is attained, and hence is the same as the $\max$ for $S_1$ and $S_2$.
For $S_3$ , I don't see why the $\sup$ would be equal to the $\max$. The function considered is $|\frac{A}{Id}|$ and the domain is $V\backslash \{0\}$. As far as I know, $V\backslash \{0\}$ is not compact (since it is unbounded).
I have the same problem for $I$ (proving that the $\inf$ is the $\min$).
Thanks in advance.
PS: I also am wondering if the vector spaces $V$ and $W$ can be of an other form than $\mathbb R^k$. But I doubt so, because then we could not argue that $\{ x\in V \mid ||x|| \leq 1\}$ and $\{ x\in V \mid ||x|| = 1\}$ are compact.
Comment: Referring to your PS: Indeed, all of this holds without the vector spaces being finite dimensional. However, the reasoning about the supremum being attained due compactness of the unit ball and the unit sphere will fail.
Comment: Hint: Use linearity of $A$ and homogeneity of the norm to show that a maximal element in $S_2$ is also a maximal element in $S_3$. Similar reasoning can be applied to show that there is a minimum for $I$. The statement remains valid in any finite dimensional vector space (use an isomorphism).
Comment: For $I$ it'll always be a minimum no matter the dimensions and no matter the operator, but for the $\sup$s there are operators for which there is no maximiser $v$.
Comment: @niobium yes, that is what i mean.
Comment: @niobium i am not saying that this is some general relation between infima/suprema and minima/maxima. It follows here from the specific conditions. For example to go from $S_2$ to $I$ let $u$ be the maximum. Then $ \| A v \|  \leq \| Au \| \|v \| $ for all $v \in V$. Therefore $\|Au\|$ is one of the $c$'s in the infimum and $\|Au\| \geq I$. But we also have $\|Au \| \leq c \|u \| = c$ for all the $c$'s in the infimum and therefore $\|Au\|$ is the infimum.
Comment: @jd27 so your point is using the equivalence of these definitions, to say that (for example between $I$ and $S_2$) the $\min$ is attained because the $\max$ of the equivalent definition is attained ?
Comment: @jd27 What if we took $I= \inf (\mathbb R ^{+*}) = 0 \neq \min (\mathbb R ^{+*})$ and $J= \sup(\mathbb R^{-} ) = 0 = \max (\mathbb R^{-} )$. My point is that an $\inf$ definition can be equal to a $\sup$ definition but at the same time $\sup = \max$ doesn't imply $\inf = \min$
Answer: To address your first question: the $\sup$ can be turned into a $\max$ because the set $$\left\{\frac{\|Ax\|}{\|x\|} : x\neq 0\right\} = \{\|Ax\| : \|x\| = 1\}$$ is compact.
To address your second question, indeed we can consider other spaces than $\mathbb R^n$. One such type of space is called a Banach space. Formally, a Banach space is a vector space $V$ equipped with a norm $\|\cdot\|$ such that the metric $d(x,y) := \|x-y\|$ generates a complete metric space. Frequently encountered Banach spaces are the $L^p$ spaces on $\mathbb R^n$, i.e.,
$$L^p(\mathbb R^n) := \left\{f : \mathbb R^n \to \mathbb R : \int_{\mathbb R^n} |f|^p\,d\mu < \infty\right\},$$
with the associated norm $\|\cdot\|_p$ defined by
$$\|f\|_p := \left(\int_{\mathbb R^n} |f|^p\,d\mu\right)^{1/p}.$$
Here $\mu$ denotes the Lebesgue measure. In the special case of $L^2$ it turns out that $\|\cdot\|_2$ is generated by the inner product
$$(f,g) = \int_{\mathbb R^n} fg\,d\mu, \quad \|f\|_2 = \sqrt{(f,f)}.$$
This leads us to a second popular way to study spaces other than $\mathbb R^n$: Hilbert space. A Hilbert space $V$ is a Banach space where the norm $\|\cdot\|$ is generated by an inner product; i.e., there is an inner product $(\cdot,\cdot)$ such that $\|x\| = \sqrt{(x,x)}$ for all $x\in V$.
It is still possible (and in fact, useful) to define operator norms on a Banach space $V$. In fact, they are defined exactly the same. In particular, if $T : V \to V$ is a linear operator, then $\|T\|_{op} < \infty$ if and only if $T$ is continuous, where $\|\cdot\|_{op}$ is the operator norm.
Indeed, your observation that $\{x \in V : \|x\| = 1\}$ is not compact holds whenever $V$ is infinite dimensional, by Riesz's lemma.
Answer: I've finally found a way (my way) of proving that for $I$, the $\inf$ is equal to the $\min$:
$\{ c\;\colon\; \lVert Av\rVert\leq c\lVert v\rVert \text{ for all }v\in V\}$ $=$ $\{ c\;\colon\; \lVert Av\rVert\leq c  \text{ for all }v\in V,\text{ such that } \lVert v \lVert = 1\}$ (to see this, just divide the inequality by $\lVert v \lVert$).
The last set is nothing more than $F^{-1} ([0,c])$ with $F = \lVert A \lVert$ (the composition of absolute value with $A$), intersected with the compact set $\{v\in V \text{ such that } \lVert v \lVert = 1\}$.
Hence $\{ c\;\colon\; \lVert Av\rVert\leq c\lVert v\rVert \text{ for all }v\in V\}$ is a part of $\mathbb R$, bounded from below (by $0$) and closed ; we conclude that $\inf\{ c\;\colon\; \lVert Av\rVert\leq c\lVert v\rVert \text{ for all }v\in V\}$ belongs to the set and hence is a $\min$.


Quantitatively, how powerful is Shapiro-Wilk or other distribution-fit tests for small sample sizes?

Question: I'm looking for an analysis (I assume a book or website, but feel free to put it all in comments here) that provides an in-depth discussion of the power/accuracy of normality assessments such as Shapiro-Wilk.
In short, I understand that Shapiro-Wilk "is good for small data sets" and with large data sets it is overly sensitive to small deviations from normality - but what does this mean quantitatively?
Overall I'd like to get a feel for something like this:
If I have n data points, I'm mm% confident that the Shapiro-Wilk (and/or other tests) test is providing me a reasonable conclusion.
How does mm% change when n is 15 ... 10 ... 7?  How about as it goes from 100 to 500 ... 1000?
Please note that I do believe in the power of graphical assessments as well, but I'm keeping those out of scope for this question and I'm looking for numeric, quantitative assessments in this case.
Comment: Frame challenge: what I would like to see (maybe I will post this as a separate question) is *how well the Shapiro-Wilk statistic {or other tests/statistics} reflects the magnitude of **non-robustness to non-Normality**. Obviously one would have to specify (1) type of deviation, (2) analysis type (e.g. ANOVA, t-test, regression), (3) sample size/experimental design, and (4) problem of concern (bias, type 1 error/poor coverage, etc.)
Comment: @Ben Bolker Sometimes, in a slightly perverse spirit, I show people the effects of running Shapiro-Wilk on all variables in a dataset. Often the strongest rejections are for indicator variables with values 0 and 1. Naturally, this is not wrong: Shapiro-Wilk is doing what it is designed to do and discerning that such distributions are not normal. Equally naturally, it is irrelevant to good practice, as it is impossible for an indicator variable to be normally distributed and that shouldn't matter any way. In practice people care more about outliers, long tails and/or skewness.
Answer: What can be simulated is the power of the Shapiro-Wilk test for detecting specific non-normal distributions. This depends strongly on the exact distribution you want to detect. For this reason a plethora of results can be considered, and you can find examples for the test working well and not so well. (This means that data from a certain non-normal distribution with a certain sample size is simulated, and by this you can determine, at least approximately, the probability for the S-W test to reject normality; the higher the better.)
Here is some work that simulates the power of the Shapiro-Wilk test:
Hadi Alizadeh, N. R. Arghami (2011) Monte Carlo comparison of seven normality tests. Journal of Statistical Computation and Simulation 81(8):965-972
https://www.researchgate.net/publication/232942214_Monte_Carlo_comparison_of_seven_normality_tests
Hadi Alizadeh Noughabi (2018) A Comprehensive Study on Power of Tests for Normality. Journal of Statistical Theory and Applications 17. 647 - 660
https://www.atlantis-press.com/journals/jsta/125905578/view
Razali, N. M. & Wah, Y. B. (2011), 'Power comparisons of Shapiro-Wilk, Kolmogorov-Smirnov, Lilliefors and Anderson-Darling tests', Journal of Statistical Modeling and Analytics 2, 21–33.
https://www.nrc.gov/docs/ML1714/ML17143A100.pdf
Danush K. Wijekularathna, Ananda B. W. Manage & Stephen M. Scariano (2019) Power analysis of several normality tests: A Monte Carlo simulation study, Communications in Statistics - Simulation and Computation, DOI: 10.1080/03610918.2019.1658780
Some older work is cited in Thode, H. C. (2002) Testing for Normality. Marcel Dekker Inc.
Answer: You are asking for the probability of a "reasonable conclusion". You can get this if and only if you give a precise enough definition of a reasonable conclusion. I too would love a procedure that reliably tells me when deviation from normality is important enough to matter, but there is a gradation from sample sizes of 1 and 2   -- for which any sample whatsoever is totally consistent with a normal distribution -- to arbitrarily large sample sizes -- for which trivial deviations will return significance levels below conventional thresholds.
What is important enough to matter depends on your purposes and on your view of the data, as statistics is a craft drawing on personal expertise and experience just as much as it is codified technique. For example:

Marginal normal distributions are only rarely required or even ideal.

In practice if I found very close approximations to conditional normal distributions -- e.g. in residuals from models known to be sound scientifically for high quality data -- I would suspect fraud more frequently than I would believe the result implicitly.

It's quite hard to teach beginners how to sit loose to significance testing, not least in disciplines that persist in over-rating it, and because you have to look at many datasets before you start getting your own independent sense of what helps. But the existence proof that beginners can grow into experts is the fact that there are experts.
EDIT A general purpose "test" is to post a normal quantile plot of the data together with several normal quantile plots for random samples of the same size from a normal. Convenient numbers of simulated samples might be 24, 35, 48, ... permitting, when combined with the original, a 5 x 5, 6 x 6, 7 x 7, ... display. This is the line-up test, similar to the idea that a suspect should be shown to witnesses together with various arbitrary people. If the suspect isn't identifiable from the others, the case for being different isn't supported. Although quite often re-invented fairly recently, the idea is in Walter Shewhart's main book (and may yet be older). One attraction of the test is the Anna Karenina principle that each non-normal distribution may be non-normal in its own different way.
Comment: I completely agree, I'm looking at this from the standpoint of providing guidance to non-statisticians, but technical people.  I would love to provide a large training course, but in this case the guidance must be brief, with an attempt at a standardized approach (I know, I know...).  In such a case, thresholds must be determined, or at least discussed from the standpoint of ideal conditions with brief discussion of repercussion of smaller sample sizes.  I'd love to say something like "Sample sizes should be 15 units or greater, but groups of 10 may be acceptable with additional scrutiny..."
Comment: I suppose part of your advice could be that people need more data. However, in my experience the usual deal is to make sense of the data that are in hand. (I am a non-statistician, a geographer by training.)
Answer: As you allude to when you bring up the use of graphical examination for this task of assessing normality, the answer is $0\%$ $\forall$ $n$.
Comment: @Porter It is not a random number generator. For given input data, it will generate the same p-value every time.
Comment: A special case of that comment is to say that for given seed, a pseudo random number generator will generate the same value every time. @Porter's is not refuted, is it?
Comment: I'm afraid you're simply wrong on this one.  You're suggesting that Shapiro-Wilk is a random number generator, which is absolutely incorrect.  Graphical analysis is important, but numerical analysis is always preferable.
Comment: I don't think Dave is claiming that Shapiro-Wilk is _meaningless_, which the "random number" comments imply. He is just saying that as is true with any such test there is no certainty that such a test points out in the direction you prefer: there is always scope for it to fail to detect an "important" departure or for it to indicate a "trivial" one. The answer of @Lewian seems closest to understanding what the OP really wants, formal investigations of power; this answer and mine reacted to  the broad wording of the question.


can anybody help me solve this?

Question: Compute the distance between the point $M=(1,0,0,0)$ and the line $q$ ,where
$$ q: x=3-2t ,\quad y=3 ,\quad z=-1+2t ,\quad w=1+t. $$
Comment: I would like to know if you have made any effort to solve the problem..
Comment: Welcome to Math.SE: In order to get the best possible answers, it is helpful to state what your thoughts and attempts on the problem are; this will prevent people from telling you things you already know, and help them give their answers at the right level.
Comment: well the distance between [1,0,0,0] and [x,y,z,w] = $\sqrt{(x - 1)^2 + y^9 + z^2 + w^2} = \sqrt{(2-2t)^2 + 9 + (-1+2t)^2 + (1+ t)^2}$ so find the $t$ where that value is smallest (use max/min calculus).  Or you know the shortest distance is a perpendicular.  Or there should be a formula to remember.
Answer: HINT
There is an explicit geometric approach you can use, projecting the point on the line, which is straight-forward.
Alternatively, here is an outline of an algebraic approach from first principles. You need to minimize (the square of) the distance between the point and the line, which is
$$
f(t) = (3-2t-1)^2 + 3^2 + (2t-1)^2 + (1+t)^2
$$
which is clearly a parabola opening up, so its vertex is the minimum as you need. Can you simplify $f$ and find its minimum?
(For simplicity, recall that the $x$-coordinate of the vertex of the parabols $ax^2+bx+c=0$ is at $x = -b/(2a)$)
Comment: Nice hints without giving the answer.  +1
Comment: @fleablood i try... it sometimes feels like people come here to get others to do their homework for them :(
Answer: The line is $p(t) = at+b$ where $a =[-2,0,2,1]$ and $b=[3,3-1,1]$.
We need a point $p(t)$ such that $M-p(t)$ is perpendicular to $a$, which is the direction of the line. So, multiply $M-p(t)$ and $a$ and that should be zero. $$a\cdot(M-p(t))=0$$
We get $a\cdot M = a\cdot a t + a\cdot b$.
Therefore $t = \frac{a\cdot M - a\cdot b}{a\cdot a}$. Since $M=[1,0,0,0]$ those products are very easy to compute.
$t =\frac{(-2\times 1 + 0\times0 + 2\times0+1\times 0) -(3\times1+3\times0+(-1)\times0+1\times0)}{(-2)^2+0^2+2^2+1^2} = -5/9$.
Answer: Here are some hints:
Let the point be $p(t) \in \mathbb{R}^4$.
Then the distance for a given $t$ is $\|p(t)-M\|$, but it makes it
easier to minimise the square of the distance since that is a quadratic
in $t$.
So, compute $s(t) = \|p(t)-M\|^2$ and find the value of $t^*$ such that
$s'(t^*) = 0$. Then the minimum distance will be $\|p(t^*)-M\|$.
Comment: Please explain the downvote?
Comment: i don't understand it either -- up-voted for compensation :)
Comment: @gt6989b: Thanks :-)!

can anybody help me solve this?


Can you play metal on single coil pickups?

Question: People keep telling me you need humbuckers to play metal but I want to play some heavy stuff on my strat. How does high gain work on single coils and what are some of the pitfalls?
People keep telling me that it is a blues/country guitar but I'm interested in playing an unconventional style on a strat.
This question was partially inspired by this video.
Comment: People who tell you that you have to use some specific tool to accomplish some artistic goal should be acknowledged politely and then their advice should be disregarded. Also be aware that heavy metal occasionally doesn't mean high gain. Some of the most brutal guitar sounds I've heard have been made with very moderate amounts of gain.
Comment: Simplest way may be to go through an effects pedal.
Comment: @ToddWilcox What about that electric-bow thing in that question about how to get a violin sound from a guitar? http://music.stackexchange.com/a/24943/27335
Comment: I ask, because, from my uneducated perspective, it seems like almost all electric guitar sounds have to do with specific technology that does not occur naturally. Distortion is just that; a distortion of "normal," "natural" sound.
Comment: @GeneralNuisance There are many other ways to get a violin like sound from a guitar.
Comment: Who can tell the difference?  Metal sound is mud, after all.
Answer: The obvious answer is yes, you can! The question is if you really want it, because it will be easier to achieve an appropriate metal sound with humbucking pick-ups. Today's amps or (modeling) effects provide you with insane amounts of gain, so gain is no problem, even with (lower output) single coil pickups. As explained in topo morto's answer, hum can be a problem, but using a noise gate, not standing too close to the amp or to other sources of interference should be sufficient in most cases. Remember that many rock guitar players use(d) single coil strats at high volumes and relatively high gain settings (Jimi Hendrix, Ritchie Blackmore, Yngwie Malmsteen, etc.).
One useful option is to change the wiring of your single coil strat to allow a series connection of two pickups. Note that this is different from the parallel connection achieved by two positions of the 5-way pickup selector switch. A real hum-bucker uses a series connection of two coils. I've added that option to my strat and it achieves a hum-bucking (i.e., noise canceling) effect, and a sound that is darker and fuller than the original single coil sound. It does sound different from a "real" humbucker though, and honestly, I don't use it that much because even for high gain sounds I found I like the original strat sounds best (I don't play metal though).
Note that this answer only refers to the single coil pickups in your original stat, not the strat as a guitar model itself, because it's probably obvious to you that you can replace the pickups if you like, even without replacing the pickguard.
In sum, you can play metal with a single coil strat, you can even play metal with a ukulele (

), but the question is if it's worth the additional effort to achieve the sound that you like.
Answer: The only real problem you may have with playing high-gain stuff on single coils is if the pickups are picking up hum, a high-gain signal chain that introduces a lot of clipping (distortion) is going to amplify that hum relative to the level of the actual notes played, potentially to the point where it could sound intrusive. Humbuckers, on the other hand, will 'buck the hum', rejecting some interference to some extent.
If you're not getting problems with hum, then really, there's no problem. You may find that you don't like the sound of single coils through high-gain, but that's where you have to make your own mind up!
bear in mind that two of the 5 pickup selector positions on a modern strat do allow two pickups to sound together and you may find those position somewhat hum-canceling.
Also : you can have true humbuckers in a strat:

my strat has a couple of types of dimarzio humbuckers in, both switchable for series, parallel, AND single coil operation.
Comment: @KirkA basically I have a humbucker  in each of neck and bridge positions, none in the centre position. Each pickup has a 3-way switch to switch between series, parallel, and single coil operation; there's then just one switch to go between the neck and bridge pickups. No blend, and no volume control either!  I'm afraid I can't remember exactly which ones I have - I think one's a 'billy corgan' and the other is a tone zone.
Comment: Worth saying that the 2-pickup settings in modern Strats are _designed_ to cancel hum: the magnets and wiring in the middle PU have reverse polarity, so if you connected bridge+middle in series you'd _have_ a humbucker (with very wide coil spacing). These settings actually put the PUs in _parallel_, which still gives the hum-cancelling but doesn't increase the inductance. Hence this setting doesn't give as much level and fat resonance as a "true" humbucker, but that can be adjusted with effects.
Comment: It may be worth noting that some of the sound of a humbucker comes from the interaction of the two sets of magnets; it's also possible to get pickups that have two coils but only one set of magnets which might be useful to someone who decides they prefer what they can do with the sound of a single-coil pickup except for the noise (while the harmonically-simple sound of a single-coil sound itself might be boring, a simpler sound may be easier to shape using effects pedals).
Comment: would you summarize your pickups and switches? I'm always looking for new ideas, and haven't yet built a frankenstrat to accompany my partscaster which features a combination of hb & sc operation.
Answer: It is certainly broadly true that humbuckers tend to provide an fundamentally 'heavier' basic tone, especially when you aren't using much in the way of effects, indeed many modern guitars designs specifically for heavy styles have active pickups for even higher output from the instrument.
Having said that metal covers a diverse range of styles and sounds and it is as much about performance and playing styles as the sound and not all metal is just about a wall, of distortion.
For example consider Iron Maiden, undoubtedly a quintessentially metal band but the guitar sound isn't really all that heavy with a lot of the power of the overall band sound coming from the bass lines and harmonising guitar parts. Indeed often the guitar parts are played by two guitars in unison ever so slightly out of tune with each other.
Equally as mentioned in another answer Jimi Hendrix managed to get a pretty meaty sound out of a single coil Strat.
Also with a Strat type guitar you do have the advantage that it is relatively easy to swap pickups around so you aren't stuck with single coils forever if you find they don't work for you. Indeed a humbucker at the bridge with single coils in the mid and neck positions is common enough in heavy rock and metal.
It is also failry simple to wire up a humbucker to be 'coil tapped' so that you can switch between humbucking and single coil modes at the flick of a switch.
Ultimately what matters is that you can get a sound which you like and works with your musical vision and playing style, how you achieve this is largely irrelevant and many players never really stop experimenting with equipment and setup to either get the sound they want or to try to find something new.
Comment: Good points about how the band mix sounds - though a big thick sound is fun when practicing on your own, a bassy distorted guitar isn't necessarily needed if your rhythm section is doing its job; cutting through in your own space can be a better place to be.
Comment: Indeed metal is often very much about the whole band sound and as you say solo practice often needs a different frequency spread than when you are performing with a band. Indeed in some cases you can almost have a swapping of the conventional roles of different instruments eg Korn tend to use very sludgy and bassy guitars with quite a bright bass sounds.
Answer: That is what I love about us guitar players, always so quick with a well formed opinion when it comes to gear, what you can and can't use for a particular sound.
Truth is you can play metal with any electric, heaven forbid even a Telecaster should you wish :)
You can do anything with a Strat, they are the most versatile of them all in the right hands. It may not surprise you to learn I have 2 Player Strats, an MIJ Squier and a Partscaster I put together. In saying that I've an SG, ES335, LP Traditional and a Jackson JS32 so I've plenty of experience using different styles of guitars with varying PUs and custom wiring.
If you are using a traditional style Strat  SSS set up then at high volume, high gain or with a cranked up overdrive/distortion pedal you are going to run into feedback and unwanted noise that can be hard to control particularly on the bridge PU. The trouble is the bridge/middle and middle/neck can get muddy with a lot of dirt and/or high gain. The middle or neck aren't ideal for metal either and suffer from hum nearly as bad as the bridge.
Player Strats, infact I believe most modern variations tend to come with AlnicoV PUs which mitigate the problem compared to say older Squiers or some older Strats but I think the best thing about them nowadays is the way they have been wiring the bridge PU through the tone control which they never used to do. Just being able to roll off some of that shrillness you can get with cranked up bridge SC makes so much difference.
Copper foil shielding your Strat as well as just making sure it's wired well, good solid solder joints, decent pots, caps, wires, particularly that it's properly  earthed at the trem claw and bridge. Taken all together can do a lot to cut out the less desirable noise a single coil strat can produce.
Cranked up a Strat will be more noisy than the average guitar with two HBs but in many ways if you can harness that extra noise, the kind of high output, barely controlled, contained feedback that is intrinsic to single coils and strats then it makes for a glorious, exciting, thrilling tone that's hard to beat.
It also depends on what you mean by metal, if you want a very specific tone then it. may be easier to go the HB route but if you want a raw, energetic, less refined sound which can suite certain forms of metal to a tee then the Strat is the way.
Answer: You can play metal even on classical guitar or harp and sound great but of course your question is not about genre. Metal tone is the sound of humbuckers with a lot of gain. Humbuckers are naturally little compressed so for single you need even more gain (or compressor). Distorted sound will be little buzzy so you will need to use tone knob (or eq pedal, or seymour duncan pickups booster that has humbucker mode). The hum can be terrible in some environments so you will need noiseless pickups or at least second position of selector switch (or gate). A lot of work and compromises without any benefit over real humbuckers.
IMHO the best high gain sound I've ever heard were humbucker and single coil played together.
Anyway you may hear single coil on many metal recordings. Leads are sometimes played single coil to give more treble.
I posted link to a video that shows benefits from double tracking in high gain mode. This effect can be emulated by dedicated pedal or chorus set exteeeeeeemly subtly.