Locations geocoding to province, not country

Question: I previously asked a question but since have done much research and am getting more focused on my problem.
I have a locations cck field in a profiles 2 profile. Here, I get users to select just countries (no cities or provinces) and they are geocoded to points and displayed on a user specific map. Many of the countries are not accurate. I have discovered the locations are being geocoded by their province code. Example: the country code is being ignored and it is selecting a province code.

I had a problem that Barbados was being displayed in Germany. Barbados has a country code of "BB", but I found that the point was being displayed in Brandenburg Germany, the province code "BB". Every wrong point can be explained this was but 3.
I have the geocoding setup to be at a country level accuracy. I dont think its a config problem and I have yet to find any other people with this problem.
Any ideas on what to do?
Thanks
Comment: If you feel the geocoding is wrong, or you need more options than the module provides you with, it would be more appropriate to ask in the module issue queue. We can't take bug reports/feature requests for contrib modules here I'm afraid
Comment: @Mołot I still think a discussion about re-writing/fixing a contrib module should be had in the module's issue queue. Having it here isn't really very useful to other users of the module. Don't get me wrong - good question, well researched, usually the sort of thing we love here. But because it's specifically about fixing a contrib module, I would always recommend the conversation happens on Drupal.org
Comment: @Clive as far as I remember in previous question OP started to take the module apart and he already, messed about it's code a bit, and wrote he is willing to fix it on his own, so I'm not sure if it should count as a mere bugreport. It may use some improvements all right, but maybe it might be a valid question.
Comment: @Clive Would you agree that best way is to have a bugreport there and small in-development questions here? Greg, consider finding me on Skype. And link bugreport if there is one. I'm interested n getting this done too.
Comment: @Mołot Ideally yeah, but breaking this up into context-less code pieces might be difficult (the issue is part of the worfklow of the module, as I can tell, and extracting meaningful out-of-context functions would probably be confusing). I've got no intention of closing this or anything, just wanted to point out it might be better suited to Drupal.org
Comment: @Clive you may be right. And as you can see I'm not upvoting it as it is now ;)
Comment: Here is the bug report: https://drupal.org/node/2072869
Comment: If there is anything more you'd like me to do I am more than determined to get this working (Although I have not mastered php, I am still more than willing to do my best)
Comment: @Mołot The bug report doesn't seem to be getting any attention. Using cities within the country may be a way to solve my problem. Would there be anyway to use a hook alter and create your own module (Using something similar to 'function location_province_list_xx' in the location.xx.inc file) to make a dropdown list for use when a country is selected in the location module (Using ajax).
Answer: The problem is not actually with that snippet of code in _google_geocode_flatten(), but is just a result of google's geocoding algorithms.
For example, your search for BB finds 2 results, Brandenburg Germany & Barbados, however google puts the former as the first result, possibly due to popularity of searches or something.
See http://maps.googleapis.com/maps/api/geocode/json?address=bb&region=bb&sensor=false
The solution I can see is to also pass in the component param when requesting from google geocoder, which allows you to specify specific parts of the address in addition to the full address string.
See https://developers.google.com/maps/documentation/geocoding/#ComponentFiltering
I have posted a patch back to your issue on drupal.org
Answer: Looks like each geocoding service is responsible for 'flattening' the address to a string, so that's where you need to look. The default one included with Location is the Google Geocoder. In its <code>_google_geocode_flatten()</code> function you'll find this interesting piece of code (the comment being especially interesting):
<code>// @@@ Fix this!
if (substr($location['province'], 0, 3) == $location['country'] . '-') {
  $address .= substr($location['province'], 3);
  watchdog('Location', 'BUG: Country found in province attribute.');
}
else {
  $address .= $location['province'];
}
</code>
So I'm going to take a guess that's where the problem is.
As for fixing it, I'd strongly recommend liaising with the module maintainers on Drupal.org, as it looks like this is a known bug.
Comment: I have found this snip-it of code in the google.inc function as you stated, as well as the location.inc function location_address2singleline($location = array()) I have also posted a bug report


What determines the combination of ciphers available on an SSL server?

Question: I have a site that has been bound to a new SSL certificate with SAN (4 additional names).
The certificate has a 2048-bit key.
The problem is that it works on some browser/OS combinations but not on others.

IE7 / Win XP - fail
IE6 / Win 2003 - fail
IE8 / Win XP / Corporate proxy - OK
IE8 / Win 7 / OTHER Corporate proxy - fail
IE9/10 / Win 7 - OK
Chrome / Win 7 - OK
Firefox / Win 7 - OK
Chrome / Android - OK

Note: The two corporate proxies are very different organisations, in two separate countries.
I have installed Fiddler on the IE6 / Win 2003 (2nd on the list) and have captured this from the Inspectors\Raw tab:
IE6:
CONNECT sorry.site.not.disclosed:443 HTTP/1.0
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; FDM; .NET4.0C; .NET4.0E)
Host: sorry.site.not.disclosed
Content-Length: 0
Connection: Keep-Alive
Pragma: no-cache

A SSLv2-compatible ClientHello handshake was found. Fiddler extracted the parameters below.

Major Version: 2
Minor Version: 0
Random: EA AE EB C5 20 0C 46 90 7F C1 E0 EE 47 BE 05 63
SessionID: empty
Ciphers:
    [10080] SSL2_RC4_128_WITH_MD5
    [700C0] SSL2_DES_192_EDE3_WITH_MD5
    [30080] SSL2_RC2_128_WITH_MD5
    [60040] SSL2_DES_64_WITH_MD5
    [20080] SSL2_RC4_128_EXPORT40_WITH_MD5
    [40080] SSL2_RC2_128_EXPORT40_WITH_MD5
    [00FF]  TLS_EMPTY_RENEGOTIATION_INFO_SCSV

Compression:
(not specified)
Extensions:
    none

Chrome:
CONNECT sorry.site.not.disclosed:443 HTTP/1.1
Host: sorry.site.not.disclosed
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 5.2) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22

A SSLv3-compatible ClientHello handshake was found. Fiddler extracted the parameters below.

Major Version: 3
Minor Version: 2
Random: 51 4A 0D 68 FE C4 50 A9 26 43 9E 1A C2 E9 05 5C FE 5F CF 37 4D 20 96 FF 0E 2F 5E EB 16 C1 F2 20
SessionID: empty
Ciphers:
    [C014]  TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA
    [0088]  TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
    [0087]  TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA
    [0039]  TLS_DHE_RSA_WITH_AES_256_SHA
    [0038]  TLS_DHE_DSS_WITH_AES_256_SHA
    [C00F]  TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
    [0084]  TLS_RSA_WITH_CAMELLIA_256_CBC_SHA
    [0035]  TLS_RSA_AES_256_SHA
    [C011]  TLS_ECDHE_RSA_WITH_RC4_128_SHA
    [C013]  TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA
    [0045]  TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
    [0044]  TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA
    [0066]  TLS_DHE_DSS_WITH_RC4_128_SHA
    [0033]  TLS_DHE_RSA_WITH_AES_128_SHA
    [0032]  TLS_DHE_DSS_WITH_AES_128_SHA
    [C00C]  TLS_ECDH_RSA_WITH_RC4_128_SHA
    [C00E]  TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
    [0096]  TLS_RSA_WITH_SEED_CBC_SHA
    [0041]  TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
    [0005]  SSL_RSA_WITH_RC4_128_SHA
    [0004]  SSL_RSA_WITH_RC4_128_MD5
    [002F]  TLS_RSA_AES_128_SHA
    [C012]  TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
    [0016]  SSL_DHE_RSA_WITH_3DES_EDE_SHA
    [0013]  SSL_DHE_DSS_WITH_3DES_EDE_SHA
    [C00D]  TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
    [FEFF]  SSL_RSA_FIPS_WITH_3DES_EDE_SHA
    [000A]  SSL_RSA_WITH_3DES_EDE_SHA

Compression:
    [00]    NO_COMPRESSION

Extensions:
    server_name sorry.site.not.disclosed
    renegotiation_info  00
    elliptic_curves 00 06 00 17 00 18 00 19
    ec_point_formats    01 00
    SessionTicket TLS   empty
    NextProtocolNegotiation empty
    channel_id(GoogleDraft) empty
    status_request  01 00 00 00 00

When testing using SSLLabs, e.g. https://www.ssllabs.com/ssltest/analyze.html?d=mail.google.com
The site shows ONLY two options under cipher suites, and supports only TLS 1.0:
Protocols
TLS 1.2 No
TLS 1.1 No
TLS 1.0 Yes
SSL 3.0 No
SSL 2.0 No

Cipher Suites (SSLv3+ suites in server-preferred order, then SSLv2 suites where used)
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (0xc013)   ECDH 256 bits (eq. 3072 bits RSA)                                128
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (0xc014)   ECDH 256 bits (eq. 3072 bits RSA)

I have contacted Verisign (Australia) and the chap claims that all Verisign certificates support SSLv1, v2, v3, TLS.
So why does the IIS server not present it?  Using a SELF-SIGNED wildcard certificate, I was able to get the same IIS server to report on SSLLabs:
Protocols
TLS 1.2  No
TLS 1.1  No
TLS 1.0  Yes
SSL 3.0  Yes
SSL 2.0   INSECURE           Yes

Cipher Suites (SSLv3+ suites in server-preferred order, then SSLv2 suites where used)
TLS_RSA_WITH_AES_128_CBC_SHA (0x2f)          128
TLS_RSA_WITH_AES_256_CBC_SHA (0x35)          256
TLS_RSA_WITH_RC4_128_SHA (0x5)      128
TLS_RSA_WITH_3DES_EDE_CBC_SHA (0xa)         168
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (0xc013)   ECDH 256 bits (eq. 3072 bits RSA)                128
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (0xc014)   ECDH 256 bits (eq. 3072 bits RSA)                256
TLS_RSA_WITH_RC4_128_MD5 (0x4)     128
SSL_DES_192_EDE3_CBC_WITH_MD5 (0x700c0)                168
SSL_RC4_128_WITH_MD5 (0x10080)       128

Where to look next?
Comment: typically you'd set the ciphers on/off under [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers]
"Enabled"=dword:ffffffff (on) or "Enabled"=dword:00000000 (off)

I've never seen different certs change the protocols and ciphers offered...
Comment: when you say it "doesn't work" - what exactly do you mean? it throws an invalid certificate error or?
Comment: Please see edit to question
Comment: that's odd that the protocols and ciphers would change - did you bounce the machine between cert changes? possibly you made some changes to the protocol and cipher settings and they only took affect on reboot?
Comment: I can switch between the two at will, and the ciphers/protocols reported by ssllabs changes. Maybe that site's not trustworthy? It does match up with my own tests using Firefox enabling/disabling TLS.
Comment: Qualys is about as reputable as they come and i have previously used them to troubleshoot issues that the verisign scanner and OpenSSL scripts I had couldn't find... Still- something very odd is happening. Can you put up your cert properties minus identifying info ?
Comment: First, check if your Verisign certificate and your self-signed certificate are signed under the same SHA algorithm (SHA1 or SHA256 or SHAxxx above 256). If not, then create a self-signed certificate with the same algorithm as Verisign's and check again. It is possible that your Verisign cert's cryptography is plain incompatible with older protocols. (And while you are still at that, drop SSLv2 off your IIS FTGJ)
Answer: On all Windows 2008 R2 servers that I've seen ssl v2 has been enabled by default and I've had to go and disable it myself. Doing so (disabling it) hasn't seemed to break IE6... obviously the machine has been hardened by someone
Qualys has a very decent online SSL scanner that will tell you exactly what protocols and even cipher suites you have enabled, and if there are any other cert errors and what renegotiation is allowed - https://www.ssllabs.com/ssltest/ -  perhaps an overly limited combination of ciphers and protocols has been chosen.
When you say it fails - what do you mean? That there is a certificate error? Is the root CA trusted on the older client machines?
It is possible in IE to disable SSL v3 and other protocols, on those machines throwing errors, check in Tools / Internet Options / Advanced tab and see if SSL 3 and TLS 1 is checked.
Check the values of the following reg keys
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\DisableRenegoOnClient
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\DisableRenegoOnServer

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\AllowInsecureRenegoClients
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\AllowInsecureRenegoServers

see http://support.microsoft.com/kb/977377 and http://support.microsoft.com/kb/980436


Chamar a variável em SQL para o programa C#

Question: Tenho de criar uma função em c# que vá chamar a variável que criei em sql-server mas não consigo entender como o fazer!
C# code:
var ss = new SqlConnection("Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=tupaidb;Integrated Security=True");
ss.Open();
if (ss.State == ConnectionState.Open)
{

var ee = new SqlDataAdapter("[dbo].[dbo.Bi_DispositivoInset]", ss);

ee.SelectCommand.CommandType = CommandType.StoredProcedure;
ee.SelectCommand.Parameters.Add("@disp_mac", SqlDbType.NVarChar, (17)).Value = macAddr;
ee.SelectCommand.Parameters.Add("@disp_nom", SqlDbType.VarChar,(50)).Value = nomeCompleto;
ee.SelectCommand.Parameters.Add("@ID_interno_cc", SqlDbType.Int).Value = "1";
ee.SelectCommand.ExecuteNonQuery();
ss.Close();

}
foreach (var s in SerialPort.GetPortNames())
{
var comPort = DetectArduino();

var myPort = new SerialPort {BaudRate = 9600, PortName = s};
myPort.PortName = comPort;
myPort.BaudRate = 9600;

myPort.Open();
/*    IntPtr hWnd = GetConsoleWindow();
if (hWnd != IntPtr.Zero)
{
ShowWindow(hWnd, 0); //Esconde
}*/

while (true)
{
var dataRx = myPort.ReadLine();

var underscore = dataRx.Split('_');
humidade = underscore[0];
temperatura = underscore[1];
heatIndex = underscore[2];
lpgGas = underscore[3];
monoCarbo = underscore[4];
smoke = underscore[5];

Console.WriteLine(humidade);
Console.WriteLine(temperatura);
Console.WriteLine(heatIndex);
Console.WriteLine(lpgGas);
Console.WriteLine(monoCarbo);
Console.WriteLine(smoke);
Console.WriteLine(DateTime.Now);
Console.WriteLine("___________________");

SqlConnection connString = new SqlConnection("Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=tupaidb;Integrated Security=True");
connString.Open();

SqlCommand command = new SqlCommand();
command.Connection = connString;
command.CommandText = "[dbo].[dbo.Bi_medicaoInset]";
command.CommandType = CommandType.StoredProcedure;

command.Parameters.Add("@ID_interno_disp", SqlDbType.Int).Value = ;
command.Parameters.Add("@med_hum", SqlDbType.VarChar, (50)).Value = humidade;
command.Parameters.Add("@med_temp", SqlDbType.VarChar, (50)).Value = temperatura;
command.Parameters.Add("@med_lpg", SqlDbType.VarChar, (50)).Value = lpgGas;
command.Parameters.Add("@med_co", SqlDbType.VarChar, (50)).Value = monoCarbo;
command.Parameters.Add("@med_fumo", SqlDbType.VarChar, (50)).Value = smoke;
command.ExecuteNonQuery();
connString.Close();
                }
            }

Sql code:
DECLARE @macadr nvarchar(17)
    set @macadr= (select disp_mac FROM Bi_Dispositivo Where disp_mac=@disp_mac)

    if @macadr = null
    begin
    insert into Bi_Dispositivo (disp_mac,disp_nom,ID_interno_cc) values (@disp_mac,@disp_nom,@ID_interno_cc)
    set @macadr=@disp_mac
    end

    select ID_interno_disp
    from Bi_dispositivo
    Where disp_mac = @macadr

Answer: Tem uns jeitos mais fáceis, vou por exemplo abaixo:
Aqui estou usando .net core 3.1 (recomendo) e instalei o pacote:
System.Data.SqlClient
CREATE PROCEDURE BUSCARMOTORISTA @Nome nvarchar(30)
AS

SELECT [Id] ,[Nome] ,[Cpf]
    FROM [dbo].[Motorista]
    WHERE NOME = @NOME
GO

E pra chaamr a proc via código
  using var conn = new SqlConnection("Server=.\\SQLEXPRESS;Database=tupaidb;Trusted_Connection=yes;");
            using var command = new SqlCommand("BUSCARMOTORISTA", conn)
            {
                CommandType = CommandType.StoredProcedure
            };

            // AQUI É O PARAMETRO DA PROCEDURE
            command.Parameters.Add(new SqlParameter("@Nome", "Fabio"));

            conn.Open();
            using SqlDataReader rdr = command.ExecuteReader();
            while (rdr.Read())
            {
                // AQUI VOCE LE A RESPOSTA, CUIDADO PRA NAO TA NULL
                int id = Convert.ToInt32(rdr["Id"]);
                string nome = rdr["Nome"].ToString();
                string cpf = rdr["Cpf"].ToString();
            }


Computing the Standard Error of the Estimate from the ANOVA table

Question: My question is quite straightforward, but I did not find a clear answer anywhere.
I'm computing the Standard Error of the Estimate (SEE) by doing the square root of the Residuals Mean Square output of the anova table:
anovatable<-anova(lm(carb~hp,data=mtcars))

anovatable

Analysis of Variance Table

Response: carb

          Df Sum Sq Mean Sq F value    Pr(>F)
hp         1 45.469  45.469  38.527 7.828e-07 ***
Residuals 30 35.406   1.180

Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

SEE<-sqrt(anovatable$`Mean Sq`[2])
SEE
[1] 1.086363

Is it the correct way of doing it?
Is there any already implemented way in R to obtain the SEE? If so, It will be better than accessing the Mean Sq term for Residuals, since its position depends upon the number of predictors.
Answer: The standard error of the estimate (SEE) is the following where $SSE$ is the sum of squares of the ordinary residuals (this sum of squares is also called the deviance) and $n$ is the number of observations and $k$ is the number of coefficients in the model.  (The intercept counts as a coefficient so $k=2$ in the case of the example shown in the question.)
$ \sqrt{SSE / (n - k)} $
In R, it can also be calculated from a model object using the sigma function so any of these work (assuming no NA's):
fm <- lm(carb ~ hp, data = mtcars)

sigma(fm)
## [1] 1.086363

sqrt(sum(resid(fm)^2) / (nrow(mtcars) - 2))
## [1] 1.086363

sqrt(deviance(fm) / (nobs(fm) - length(coef(fm))))
## [1] 1.086363

summary(fm)$sigma
## [1] 1.086363

sqrt(anova(fm)["Residuals", "Mean Sq"])
## [1] 1.086363

If what you meant was the standard errors of the coefficient estimates then there would be one for each coefficient and those standard errors would be any of the following where the last one makes use of an estimate of $var(\hat{\beta})$ being $\hat{\sigma}^2 (X'X)^{-1}$
sqrt(diag(vcov(fm)))
## (Intercept)          hp
## 0.459500176 0.002845806

coef(summary(fm))[, "Std. Error"]
## (Intercept)          hp
## 0.459500176 0.002845806

sigma(fm) * sqrt(diag(solve(crossprod(model.matrix(fm)))))
## (Intercept)          hp
## 0.459500176 0.002845806

Comment: Really nice and detailed answer :-) I didn't know about the sigma-function either.
Answer: The residual error ist something very different that the standard error of the estimate of a predictor.
The residual standard deviation tells you how precisely you can estimate y if you know all the predictors.
On the other hand, the standard error of the estimate for an predictor tells you how precisely your estimate for the coefficient is.
An important distinction is that given enough data you can make the standard errors of estimates arbitarily small, but you will never be able to decrease the residual standard error below a specific amount.
For example, if you have enough data for your country you will be able to estimate the influence of Gender on Body Height (standard error of gender coefficient almost zero) very exactly, but you will always a residual error of about 7-8 cm.
In R you get the standard error of the estimator coefficients by using summary(model).
Answer: What you've computed is the standard deviation of the residuals, which is not what you want. Also note that in your model, hp is a continuous covariate, so this is not really ideal for an ANOVA model but more of a regression model (what you've computed is the F test for the regression).  To calculate the standard error of the estimate, compute as follows
$$ se = \sqrt{
        \frac{MS_{error}}{N-2}
         } $$
However, I think it would be more meaningful to run this model as a regression model. As such, you would get a standard error for both the intercept and the slope.


Why aren't the coskewness and cokurtosis matrices square like the covariance matrix?

Question: The variance-covariance matrix is shaped $p\times p$, whereas the co-skewness matrix is shaped $p\times p^2$ and the co-kurtosis matrix is $p\times p^3$. Why is this, given that skewness and kurtosis are merely the 3rd and 4th moments after variance, the 2nd moment? Is there something fundamentally much different in the formula of skewness and kurtosis than variance that makes their matrices much larger and non-square?
Answer: The statistics aren't really $p\times p^2$ and $p\times p^3$ matrices.  They are really $p\times p \times p$ and $p\times p \times p\times p$ arrays (covariant tensors of rank 3 and 4), but because we like representing things in two dimensions they get folded into non-square matrices.
The coskewness is $p\times p \times p$ because it has $(i,j,k)$ value $E[X_iX_jX_k]$; similarly, the co-kurtosis represents expectations of products of four variables and so is a 4-way array.


Programa em C onde tem que remover um aluno de um vetor

Question: Tenho que fazer um programa que faculdade que remover uma aluno de uma vetor, que quando executo o código abaixo, ele exclui o aluno mais deixa um carácter especial no código, podem me ajudar?
//Remover o Aluno
void removerAluno(DADOSPES p[], int n)
 {
     char codigo[10];
     int i;
     printf("Digite o Codigo que deseja excluir: ");
     fflush(stdin);
     gets(codigo);
     int encontrou =0;
     for(i=0; i<n; i++)
     {
         if((strcmp(codigo,p[i].codigo))== 0)
         {
            encontrou =1;
         }
     }
     for(i=0; i<n; i++)
     {
        if(encontrou == 1)
          {
            system("cls");
            p[i] = p[i+1];
            p[i].DiaN = p[i+1].DiaN;
            p[n-1].DiaN = 0;
            p[i].MesN = p[i+1].MesN;
            p[n-1].MesN = 0;
            p[i].AnoN = p[i+1].AnoN;
            p[n-1].AnoN = 0;
            p[i].idade = p[i+1].idade;
            p[n-1].idade = 0;
          }
     }
     printf("Codigo Excluido: %s \n",&codigo );
     system("pause");
     getch();
 }

Comment: Além disso, o `p[i+1]` está acessando um elemento depois do fim do vetor. Em C isso dá merda / resultados imprevisíveis (talvez o caracter esquisito seja devido a isso)
Comment: @hugomg "dá merda" é o melhor termo técnico ever! :)
Comment: Bom, o seu código parece estar removendo TODOS os alunos, quando o código digitado é encontrado no meio dos alunos existentes. Você faz dois laços, no primeiro procura pelo código e marca se encontrou. No segundo laço (que é desnecessário, já que poderia ter removido ao encontrar, no primeiro laço) você simplesmente verifica se encontrou e remove EM CADA INTERAÇÃO DO LAÇO. Só isso já não parece muito correto...
Comment: Mas, de todas as formas, o que significa "deixa um caractere especial no código"? Em que código? Como assim?
Answer: Como dito por @Luiz Vieira nos comentários da pergunta, os dois laços poderiam ser mesclados. Por exemplos a onde lê-se encontrou == 1 no segundo laço, poderia ser trocado por (strcmp(codigo,p[i].codigo))== 0, evitando de levar a escola a falência e remover todos alunos.
Outro problema é que aparentemente você quer preencher o espaço deixado pelo aluno a ser removido. Como dito pelo companheiro @hugomg nos comentários, ao usar p[i+1] você acaba usando um ponteiro para fora da tua tabela quando i==9, o que pode causar erros aleatórios em execução.
O que lhe aconselho a fazer é reutilizar o loop, tomando cuidado quando chegar no limite de tua lista. Repare também que eu não removi a parte onde tem p[i] = p[i+1], pois não conheço a estrutura.
for(i=0;i<n; i++)
{
    if(strcmp(codigo, p[i].codigo) == 0)
    {
        encontrou = 1;
    }
    if(encontrou == 1 && i < n-1)
    {
        p[i].DiaN = p[i+1].DiaN;
        p[i].MesN = p[i+1].MesN;
        p[i].AnoN = p[i+1].AnoN;
        p[i].idade = p[i+1].idade;
        p[i].codigo = p[i+1].codigo; //???
   }
}
if(encontrou == 1)
{
    p[n-1].MesN = 0;
    p[n-1].DiaN = 0;
    p[n-1].AnoN = 0;
    p[n-1].idade = 0;
}

Porem, para responder tua pergunta sobre o caractere especial no fim, pode ser porque você esta passando um pointeiro de codigo (que já é em si um ponteiro de char. Como printf aceita apenas um ponteiro, voce poderia passar só: printf("Codigo Excluido: %s \n", codigo);


Optimal messages's probability problem

Question: https://i.stack.imgur.com/gb9SD.png
Translation:
Set of two messages m1, m2 is given. Those messages are coded as follows:
C(m1) = 01, C(m2) = 101
Find a probabilities those messages in such a way, that the coding is optimal.
Only a probabilities such that numerator is a whole number and denominator is equal to 2, 4 or 8 are allowed.
I've solved this for sum of probabilities not equal to 1, but I assume that this is not correct. I have not idea hot to solve it for a sum of those probabilities equal to 1 without calculating R for every possibility. Any ideas how to solve it?
Answer: This code can't be optimal, no matter the probabilities. If you have only two messages, the optimal code encodes one as $0$ and the other as $1$.

Optimal messages's probability problem


Limit of non-negative non increasing function is Lebesgue integrable

Question: So the problem is: Suppose $g_n \in C[a,b]$ is a sequence of non-negative functions such that $g_n(x)$ is a non-increasing sequence for each $x \in R$. Show that the limiting function $\displaystyle g(x) = \lim_{n\rightarrow\infty} g_n(x)$ is Lebesgue integrable.
I think I should somehow use monotone convergence theorem but I am not sure how to apply the theorem here.
Comment: Dominated convergence theorem.
Comment: Alternatively, apply the monotone convergence theorem to the sequence of functions $\left(g_1-g_n\right)_n$.
Comment: I guess it should be "for each $x\in[a,b]$", not "for each $x\in\mathbb{R}$".
Answer: Well, the limit $g$ is measurable, as a limit of continuous functions, it is also non-negative, as a limit of non-negative functions, and as
$$
g_1\ge g\ge 0,
$$
then
$$
\int_a^b |g|\,dx= \int_a^b g\,dx\le \int_a^b g_1\,dx<\infty,
$$
as hence $g$ is Lebesgue integrable.
By the way, $g$ is also continuous!


Highcharts - Line chart with date

Question: Olá, não consigo criar um chart line usando o plugin Highcharts, onde o eixo X é separado por meses (Jan, Fev, etc...) e o eixo Y é o número de novos clientes baseado nesses meses.
Abaixo está como o meu json está formado.
[{
 "newCustomers": "1",
 "creationDate": "2017-08-07 09:33:18"
 }, {
 "newCustomers": "1",
 "creationDate": "2017-08-07 17:35:28"
 }, {
 "newCustomers": "1",
 "creationDate": "2017-08-07 17:52:45"
 }, {
 "newCustomers": "1",
 "creationDate": "2017-08-08 18:08:16"
 }, {
 "newCustomers": "1",
 "creationDate": "2017-08-09 15:41:03"
 }, {
 "newCustomers": "1",
 "creationDate": "2017-08-09 16:13:48"
 }, {
 "newCustomers": "1",
 "creationDate": "2017-08-09 16:17:18"
 }, {
 "newCustomers": "1",
 "creationDate": "2017-08-10 09:47:40"
}]

Eu gostaria de pegar esses dados acima e colocar no formato abaixo. Onde no parâmetro "data" de "series" seria a quantidade de novos clientes e no eixo X, seria o "creationDate" formatado e separado por mês "Jan, Fev, etc.."
Highcharts.chart('container', {
chart: {
    type: 'line'
},
title: {
    text: 'New Customers Per Month'
},

xAxis: {
    categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
yAxis: {
    title: {
        text: 'New customers'
    }
},
plotOptions: {
    line: {
        dataLabels: {
            enabled: true
        },
        enableMouseTracking: false
    }
},
series: [{
            name: 'BEARLabs',
            data: [7, 6, 9, 14, 18, 21, 25, 26, 23, 18, 13, 9]
        }]
});

Comment: Poderia colocar o código fonte que tentou? o problema é agrupar?
Comment: Coloquei ali @rray.
Comment: Esse gráfico vai exibir os valore somente de um ano?
Comment: Sim, somente de um ano. Digamos que desde Jan/2017 até Dez/2017
Answer: O problema parece ser a forma da totalização no json ela está como o timestamp quando deveria ser pelo mês. Escrevi uma função que faz isso. Basicamente o que ele faz é criar um array de 12 posições que represetam os meses (0 para janeiro e 11 para dezembro). Depois pego a string em creationDate e crio uma data e obtenho o mês para saber qual é a posição do array a ser incrementada.
Modifiquei os valores do json para melhorar a exibição do gráfico.
var  lin = [{
     "newCustomers": "1",
     "creationDate": "2017-03-07 09:33:18"
     }, {
     "newCustomers": "1",
     "creationDate": "2017-07-07 17:35:28"
     }, {
     "newCustomers": "1",
     "creationDate": "2017-03-07 17:52:45"
     }, {
     "newCustomers": "1",
     "creationDate": "2017-08-08 18:08:16"
     }, {
     "newCustomers": "1",
     "creationDate": "2017-02-09 15:41:03"
     }, {
     "newCustomers": "1",
     "creationDate": "2017-09-09 16:13:48"
     }, {
     "newCustomers": "1",
     "creationDate": "2017-08-09 16:17:18"
     }, {
     "newCustomers": "1",
     "creationDate": "2017-02-10 09:47:40"
    }];

function totalizaClientes(clientes){
    var total = [0,0,0,0,0,0,0,0,0,0,0,0];
    for(var i=0; i<clientes.length;i++){
        let mes = new Date(clientes[i].creationDate).getMonth();
        total[mes]++;
    }
    return total;
}

Na hora de criar o gráfico pode fazer dessa forma:
series: [{
   name: 'BEARLabs',
   data: totalizaClientes(lin)
}]

Comment: Obrigado @rray. Fiz algumas modificações e ficou exatamente como eu estava tentando fazer.

Highcharts - Line chart with date


does multiplication of singular matrix with some matrix result in singular matrix?

Question: Suppose that there is singular (non-invertible) matrix $A$. If it gets multiplied by any square matrix $B$, would $AB$ be singular?
Answer: $A$ is singular iff there is some $x\neq 0$ such that $Ax = 0$.
Now consider $AB$. If $B$ is singular, there is some $x'\neq 0$ such that $Bx' = 0$, hence $AB x'=0$ and so $AB$ is singular. If $B$ is invertible, then let $x' = B^{-1} x$ (where $Ax = 0$), then $ABx' = Ax = 0$. Hence $AB$ is singular.
Answer: Hint: Compute the determinant of $AB$.


How to print Hindi words in NLTK's Indian corpus?

Question: Code:
from nltk.corpus import indian

nltk.corpus.indian.words('hindi.pos')

Output:
[u'\u092a\u0942\u0930\u094d\u0923', u'\u092a\u094d\u0930\u0924\u093f\u092c\u0902\u0927', ...]

But, I need output to be: ['पूर्ण', 'प्रतिबंध', 'हटाओ', ':', 'इराक', 'संयुक्त', ...]
Like shown in: http://www.nltk.org/book/ch02.html
Could you please tell how can I print the actual words instead of unicode.
Any help is appreciated.
Comment: Seems like this is Py2K, no unicode literals by default (try printing those strings)
Comment: What if you print just one?
Comment: When I use print nltk.corpus.indian.words('hindi.pos'), the output is the same.
Comment: Thank you so much. I am able to print now.
Comment: Try `print nltk.corpus.indian.words('hindi.pos')`
Comment: print u'\u092a\u0942\u0930\u094d\u0923' prints the word.
Answer: Python 2 doesn't have VM-wide Unicode support. The prettyprinter isn't the same as printing one of the strings in the array -- but printing just one will work as expected.


What is the recommended way to write a stored procedure?

Question: I usually use following way to write my stored procedure:
ALTER PROCEDURE MasterInsertUpdateDelete
    (@id INTEGER,
     @first_name VARCHAR(10),
     @last_name VARCHAR(10),
     @salary DECIMAL(10,2),
     @city VARCHAR(20),
     @StatementType NVARCHAR(20) = '')
AS
BEGIN
    IF @StatementType = 'Insert'
    BEGIN
        INSERT INTO employee (id, first_name, last_name, salary, city)
        VALUES (@id, @first_name, @last_name, @salary, @city)
    END

    IF @StatementType = 'Select'
    BEGIN
        SELECT * FROM employee
    END

    IF @StatementType = 'Update'
    BEGIN
        UPDATE employee
        SET First_name = @first_name,
            Last_name = @last_name,
            salary = @salary,
            city = @city
        WHERE id = @id
    END
    ELSE IF @StatementType = 'Delete'
    BEGIN
        DELETE FROM employee
        WHERE id = @id
    END
END

The second way is to split the one stored procedure into 4 separate stored procedures for insert, delete, select and update the table.
Which one is recommended with respect to performance ?
Comment: 4 is far more maintainable than 1 with multiple processes. Also, it means you don't have to have wasted parameters. As it stands you **must** pass a value for `@first_name`, `@last_name`, `@salary` and `@city`, even though you don't use them for your `DELETE`. You also must pass all of those parameters, and an `ID` for the `SELECT` even though you use none of them. Your `UPDATE`, as well effectively requires them all (including the existing value), even if you only want to update 1 column.
Comment: IMHO (the answer is opinion-based), a stored procedure should have a well-defined interface. The interface includes not only the parameters but the result sets, messages, etc. returned. The Swiss army knife interface violates this because result sets are returned, or not, depending in the parameter values passed. Think of all the unit test cases needed to thoroughly test the proc.
Comment: Based on the generally accepted **Single Responsibility Principle**, I would always opt for an **one stored procedure does *ONE* job only** approach. Do not try to does these "everything-but-the-kitchen-sink" approaches - they might *sound clever* at first - but long term, they're a lot more trouble than benefits....
Comment: All these depends on the complexity of the statement / operations. If your query is too long/complex for either select, insert, update or delete and also performing options based on that then you should write separate procedure otherwise it is ok for one procedures for all the operations. Remember use case and future update is also remembered.
Comment: Why did you use the word `else` only 1 time ?
Answer: You are asking whether it is better to write a single stored procedure that does four things or a separate procedure for one thing.
At first I thought this was opinion-based and was going to close the question.  It might be opinion-based, but the evidence for four stored procedures seems pretty overwhelming.

A stored procedure should encapsulate logic that "goes together".  Your single procedure has multiple personality disorder (well, that name is no longer used but you get the idea).
You have declared a bunch of parameters.  Some personalities do not use them.  Others might have different meanings.
If you start writing tests for the stored procedure, you are quite likely to miss important chunks of functionality.
SQL Server stashes compile plans for stored procedures, generally on the first run.  You may not get the optimal execution plan for some of the branches.

I cannot think of a good defense of combining such different functionality into one procedure.
I would also add that I don't see much benefit to wrapping basic SQL functions in a stored procedure, unless you are auditing, validating the data, or using the stored procedures to control access.  I doubly don't see the benefit for SELECT statements.
Comment: *"or using the stored procedures to control access"* I find this is the most common reason. Seems silly for a `SELECT *` with no `WHERE`, but often user/service account are limited to only be able to `EXEC` SPs, so that they cannot interact directly with the underlying data. With things like GDPR now, this style of compartmentalising is really useful for limiting exposure. But, I completely agree with everything said here.
Answer: I think if every operation is done in a separate stored procedure, it is better because it makes managing and updating the stored procedures easier.
MasterInsert
CREATE PROCEDURE MasterInsert
    (@first_name VARCHAR(10),
     @last_name  VARCHAR(10),
     @salary     DECIMAL(10, 2),
     @city       VARCHAR(20))
AS
BEGIN
    INSERT INTO employee (id, first_name, last_name, salary, city)
    VALUES (@id, @first_name, @last_name, @salary, @city)
END

MasterSelect
CREATE PROCEDURE MasterSelect
AS
BEGIN
    SELECT *
    FROM employee
END

MasterUpdate
CREATE PROCEDURE MasterUpdate
    (@id         INTEGER,
     @first_name VARCHAR(10) = NULL,
     @last_name  VARCHAR(10) = NULL,
     @salary     DECIMAL(10, 2) = NULL,
     @city       VARCHAR(20) = NULL, )
AS
BEGIN
    UPDATE employee
    SET    First_name = @first_name,
           last_name  = @last_name,
           salary     = @salary,
           city       = @city
    WHERE  id         = @id
END

MasterDelete
CREATE PROCEDURE MasterDelete
     (@id INTEGER)
AS
BEGIN
    DELETE
    FROM employee
    WHERE id = @id
END

MasterInsertUpdateDelete
CREATE PROCEDURE MasterInsertUpdateDelete
     (@id            INTEGER = NULL,
      @first_name    VARCHAR(10) = NULL,
      @last_name     VARCHAR(10) = NULL,
      @salary        DECIMAL(10, 2) = NULL,
      @city          VARCHAR(20) = NULL,
      @StatementType NVARCHAR(20) = '')
AS
BEGIN
    IF @StatementType = 'Insert'
    BEGIN
        EXEC MasterInsert @first_name,
             @last_name,
             @salary,
             @city
    END
    ELSE IF @StatementType = 'Select'
    BEGIN
        EXEC MasterSelect
    END
    ELSE IF @StatementType = 'Update'
    BEGIN
        EXEC MasterUpdate @id,
             @first_name,
             @last_name,
             @salary,
             @city
    END
    ELSE IF @StatementType = 'Delete'
    BEGIN
        EXEC MasterDelete @id
    END
END

Answer: As per my view write stored procedure as below.
Write comment on every section you don't need to separate the part.
Also mentioned the detail like who created and who modified the stored procedure and reason for changes. This may help you in future to track the information. And always use tab in place of space while you are writing Begin and End.
-- =============================================
-- Created By:      Author Name
-- Create Date: Create Date
-- Modify By with Reason: Name of Person who modified the Store Procedure, Description
-- =============================================

-- Drop Proc MasterInsertUpdateDelete
-- Execute MasterInsertUpdateDelete 1,'First Name','Last Name',22500.15,'Banglore','Type'
Create PROCEDURE MasterInsertUpdateDelete
(
   @id INTEGER,
   @first_name VARCHAR(10),
   @last_name VARCHAR(10),
   @salary DECIMAL(10,2),
   @city VARCHAR(20),
   @StatementType nvarchar(20) = ''
)

AS
BEGIN
    -- Insert Employee
    IF @StatementType = 'Insert'
        BEGIN
           insert into employee (id,first_name,last_name,salary,city) values( @id, @first_name, @last_name,
           @salary, @city)
        END

    -- Select Employee
    IF @StatementType = 'Select'
        BEGIN
           select * from employee
        END

    -- Update Employee
    IF @StatementType = 'Update'
        BEGIN
           UPDATE employee SET
              First_name = @first_name, last_name = @last_name, salary = @salary,
              city = @city
           WHERE id = @id
        END

    -- Delete Employee
    ELSE IF @StatementType = 'Delete'
        BEGIN
           DELETE FROM employee WHERE id = @id
        END
END

Comment: What is your reason for wanting a `MasterInsertUpdateDelete` to begin with? Do you not agree it is more conventional to have different stored procedures for each of the CRUD operations? What value are you gaining by doing it this way?
Comment: I suggest leveraging source control to capture the commit history. That will track the author, reason for changes, revision history without embedding the info as comments in the source code.


$ABC$ is a triangle right angled at $B$. $D$ is a point on $AC$ such that $\angle ABD = \pi/4$. If $AC = 6$ and $AD = 2$, then $AB$ is

Question: I've solved this question but I'm not getting the right answer.
I assumed the radius of the in-circle of the triangle to be $r$.
As tangents drawn from the same point to a circle are equal, I get the equation :
$$(r+2)^2 + (r+4)^2 = 36$$
On solving this I get an answer that my math teacher claims is wrong. Can anyone tell me what I'm doing wrong ?
Answer: $BD$ is angle bisector of angle $B$
Using bisector theorem we have:
$$\frac{BC}{4}=\frac{AB}{2} \Rightarrow BC=2AB$$
Pythagoras Theorem:
$$6^2=AB^2+BC^2 \Rightarrow 36=5AB^2 \Rightarrow AB=6\sqrt{5}/5$$


How to parse a string in a calculator in R?

Question: I wrote a calculator program in which the User enters two numbers and an arithmetic operation between the numbers, then presses Enter and gets the result, or rather did a string parsing, but it doesn't work. What can this be related to? I also wrote the code so that I could exit the function
  add<- function(x,y){
      return(x+y)
    }
      subtract <- function(x,y){
      return(x-y)
    }
      multiply <- function(x, y) {
         return(x * y)
    }
      div <- function(x,y){
        if(y==0){
          return("Error")
          break
    }
      else if(y!=0){
        return(x%/%y)
      }

    }

      res<-NA
       repeat{
    print("9", quote=FALSE)
    user_string <-
      readline(prompt = ("Enter: "))

    if(user_string== 9){
      break # to stop the programme
    }

    components_of_user_string <-
      unlist(strsplit(user_string, split = '')) #splitting the line

      num1<-as.numeric(components_of_user_string[1]) #first number
      num2<-as.numeric(components_of_user_string[3]) # second number

    us_chosen_operation <-
      components_of_user_string[2]
    operations_vector <-
      c('+', '-', '*', '/')
    choice <- match(us_chosen_operation, operations_vector)
    operator <- switch(choice, ' + ', ' - ', ' * ', ' / ')

    result <-
      switch(
        choice,
        add(num1, num2),
        subtract(num1, num2),
        multiply(num1, num2),
        divide(num1, num2)
      )
    print(paste(num1, operator, num2, "=", result))
}

Comment: variable `result` is not defined before the line `is.numeric(result)`. Also,  there is a stray `{` before the line `res<-NA`
Answer: String parsing with eval(parse(...)) could be an option :
repeat {
  input <- readline(prompt = ("Enter: "))
  print(eval(parse(text = input)))
}

# Enter: (-4)+2
# [1] -2
# Enter: raise_to_degree(2,3)
# [1] 8

Comment: But if I want, for example, to add up the numbers (-4)+2, then he can't count, right? I also wanted the user to set the numbers and the operation themselves
Comment: Not sure to get your first point : `eval(parse(text = "(-4)+2"))` also works.
Comment: Yes, it works, thank you. But I asked about how to make it so that when I run my code, a line comes out( I did this) and there the user can enter: 4+(-2) and get just the answer (-2)
Comment: see my edit : is it what you're looking for?
Comment: It's really good method, but i don't understand how correctly use it in my cod. This method ignoring all my functions
Comment: How do you mean 'ignoring all my functions': your own function `raise_to_degree` is working in example above.
Comment: In my code, above were functions for addition,subtraction, multiplication and division, so I want, your method operate with this functions. I'm trying to do it, but I can't achieve the desired result
Comment: where do you define `num1`, `num2` and  `c_of_user_string` in your code? Please provide a working [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example).
Comment: You can see, I added changes to the code above
Comment: The code above works with all the functions you defined : I gave `raise_to_degree` as an example, but all others (`multiply`, ...) work. Not sure to understand where the problem is..
Comment: Yeah, I understood. Thank you!


Non-Naturality of the Splitting in the Universal Coefficient Formula

Question: I want to show the non-naturality of the splitting in the universal coefficient formula for homology. The s.e.s. is
$$0\to H_q(X,X';R)\otimes_R N\to H_q(X,X';N)\to Tor^R_1(H_{q-1}(X,X';R),N)\to 0$$
where $R$ is a PID and $N$ an $R-$module.
I found a counter example with the map $\mathbb{RP}^2\to S^2$ that collapses the 1-cell of $\mathbb{RP}^2$ to a point, but I don't get why this map works.
Answer: Look at $R=\mathbb Z, N = \mathbb Z/2$.
Then you have the two short exact sequences $0\to H_2(\mathbb RP^2; \mathbb Z)\otimes \mathbb Z/2\to H_2(\mathbb RP^2;\mathbb Z/2)\to \mathrm{Tor}_1^\mathbb Z(H_1(\mathbb RP^2;\mathbb Z), \mathbb Z/2)\to 0$
and
$0\to H_2(S^2; \mathbb Z)\otimes \mathbb Z/2\to H_2(S^2;\mathbb Z/2)\to \mathrm{Tor}_1^\mathbb Z(H_1(S^2;\mathbb Z), \mathbb Z/2)\to 0$
In the first exact sequence, the leftmost term is $0$, and in the second one it's the rightmost term which is $0$.
If the splitting were natural, since $H_2(\mathbb RP^2; \mathbb Z)\otimes \mathbb Z/2\to H_2(S^2; \mathbb Z)\otimes \mathbb Z/2$ and $\mathrm{Tor}_1^\mathbb Z(H_1(\mathbb RP^2;\mathbb Z), \mathbb Z/2)\to \mathrm{Tor}_1^\mathbb Z(H_1(S^2;\mathbb Z), \mathbb Z/2)$ are both $0$ (because in each one, one of the terms is $0$), then $H_2(\mathbb RP^2;\mathbb Z/2)\to H_2(S^2;\mathbb Z/2)$ would be $0$ (can you see how this relates to naturality of the splitting ?)
But it's not $0$ (I don't know what's the easiest way to see this, here are at least two possibilities :
a) Use Poincaré duality and try to convince yourself that your map sends the fundamental class (mod $2$) $[\mathbb RP^2]$ to $[S^2]$
b) Use the following cofiber sequence : $S^1\overset 2\to S^1\to \mathbb RP^2$ and note that it continues as $S^1\to S^1\to \mathbb RP^2\to S^2\to S^2$ and that the map $\mathbb RP^2\to S^2$ is the one you're looking for. This implies that the map $S^2\to S^2$ is $\Sigma 2 = 2 : S^2\to S^2$ so it induces $0$ in mod $2$ homology, and so the long exact sequence in homology of the cofiber sequence $\mathbb RP^2\to S^2\to S^2$ shows that the first map is an iso on $H_2(-;\mathbb Z/2)$   )
Comment: In part a) do you really want to say "characteristic class" or do you mean "fundamental class"?
Comment: @William : I meant fundamental class, you are right !


Non-measurable set $A$ such that every measurable subset of $A$ or $A^c$ has measure zero

Question: I want to show the following:

There is $A \subset \mathbb{R}$ such that both are satisfied:

if $E \subset A$ is a Lebesgue measurable set then $\lambda(E) = 0$
if $E \subset A^c$ is a Lebesgue measurable set then $\lambda(E) = 0$

where $\lambda$ is the Lebesgue measure on the real line.

Do you know how to show that such a set exists? Also a reference would be appreciated. Thank you :)
ps: if you find a better title feel free to modify it!
Answer: Yes. A standard construction goes by building the set by transfinite recursion to ensure that neither $A$ nor its complement contains a perfect set. Note that if this is the case, then any measurable subset of $A$ has measure $0$, because (by regularity of Lebesgue measure) if $E$ is measurable, $\lambda(E)$ is the supremum of $\lambda(K)$ for $K$ compact contained in $E$. But any compact set that has no perfect subset is in fact countable, so it has measure $0$. The same happens with $A^c$, but then neither $A$ nor $A^c$ can be measurable: If $A$ is measurable, then it has measure $0$, so $A^c$ has full measure and therefore contains a perfect set.
The transfinite recursion goes as follows: There are $\mathfrak c=|\mathbb R|$ many perfect subsets of $\mathbb R$. Identifying cardinals with ordinals, list them in a well-ordering of type $\mathfrak c$. We build $A$ and its complement by recursion. At stage $\alpha$ we have a set $A_{<\alpha}$ and a disjoint set $B_{<\alpha}$. (When $\alpha=0$, both are empty.) Consider the $\alpha$-th perfect set. Pick two elements of the perfect set not in $A_{<\alpha}\cup B_{<\alpha}$. Let $A_{\alpha}=A_{<\alpha+1}$ be the union of $A_{<\alpha}$ and one of these points, and let $B_{\alpha}$ be the union of $B_{<\alpha}$ and the other point. That the points exist follows from the fact that there are $\mathfrak c$ reals in any perfect set, but at stage $\alpha$ at most $2|\alpha|<\mathfrak c$ of them have been used. (When $\lambda$ is limit, $A_{<\lambda}$ is just the union of the previous $A_\alpha$, same for $B_{<\lambda}$.) At the end, one of the sets so built is $A$. This works, because by construction, given any perfect set $P$, at least one of its points is in $A$ (so $P$ is not contained in $A^c$), and at least one of its points is not (so $P$ is not contained in $A$).
The details of the construction can be varied a bit, but any argument must use choice in a nontrivial way, since it is consistent with the usual axioms of set theory (without the axiom of choice) that all sets of reals are measurable. That said, I haven't seen a presentation of the result I'm describing that avoids the use of a well-ordering of $\mathbb R$. The sets so obtained are called Bernstein sets, and were first exhibited by Felix Berenstein (of Bernstein-Schroeder fame) in $1908$.
Comment: Note that such a set is called a Bernstein set, and there have been [a](http://math.stackexchange.com/questions/169714/whats-application-of-bernstein-set) [bunch](http://math.stackexchange.com/questions/257328/constructing-a-bernstein-set-in-a-polish-space) [of](http://math.stackexchange.com/questions/393002/is-it-possible-that-the-union-of-a-bernstein-set-and-a-singleton-isnt-a-bernste) [questions](http://math.stackexchange.com/questions/543499/bernstein-set-in-0-2) asked here about it already.
Comment: Yes, I should add a note mentioning the name.


How would you add a hyperlink to a BG img using CSS?

Question: CSS
header.site-header .wrap {
    background: url(http://jadeluxurycondos.com/jadeluxurycondos-new/wp-content/uploads/2014/04/header-banner.jpg) right top no-repeat;
}

This is what I am working with.
Any insight would be grateful.
Here is the home.php code.
Answer: You could do something simpler:

This creates a link that is an image.
EDIT after more info came to light.
From what I've gathered so far... you're using the "Open Floor Plan" Theme for Wordpress. (Maybe ask them for support? After all you paid for a theme.)
The simple method and recommended:
That theme appears to have a widget position at the top right. Why not use that to add your banner-link?
The hard-way hacking not-recommended method:
In wordpress you can edit the theme files (not recommended) by going to Appearance then Editor. This will open up the theme editor view and on the right side you'll see all the files of the currently active theme. You then could search those files for the HTML tag  and add the above modifications.
The file that could have what you're looking for could be the header.php or index.php, but if it isn't there just sift through the other files until you find it.
The html markup would look something like this:

        It will contain more stuff in here...

It will probably contain a lot more classes and PHP code...

The Widget Method
Add your banner code in a Text widget. You can add the CSS styling in-line, so that you won't have to upload anything else.
Add the CSS property for the parent container:

Now add your HTML code:

Please note that with the z-index, the other widget will cover the banner and the ability to click it. You could simply use another position for that widget and just have the banner there.
Comment: Would I add this into the css?
Comment: No, this goes in to the  of the page. You should also post on your question the HTML you are targeting with that CSS you have already posted.
Comment: The site is a wordpress site.  I am adding to the custom css.  I don't know where to add this if it must be the way u wrote your answer.
Comment: @MSiegle Next time, use correct tags. If you use any framework, tag it, please.
Comment: @Benio thank you for the correction.  1 for the memory bank.  cheers!
Comment: @Petsoukos I have asked for support and they suck....  I have tried to add to the top right widget, there are the social icons there and it doesn't look right.  Maybe if I give it a class in html?  Is this possible?  would u be willing to walk me thru this process?
Comment: The is from the home.php
Comment: You could add another widget, that will have a position:absolute; but the parent of that container should have position:relative; otherwise it will float off the parent container.
Answer: You cannot do this using CSS.
What you've done here is just passed the URL for the background.
If you want to add a link to the image, you can do this either by using a pair of anchor tags.
EG:
Add this in your HTML :

OR by adding a click event on to the div.
EG:
$(document).ready(function(){
   $('header.site-header .wrap').click(function(){
       window.location.href = "Link";
   });
});

Comment: You need to share your code so that i can tell you where to keep it. I cannot assume which files are you using here.
Comment: This is a wordpress site and i was adding to the custom css.  I am unfamiliar as to where to add the 2 codes u posted.
Comment: Ok.  Please pardon any of my ignorance, but I am not sure how to add the code you posted.  Which php file am I supposed to add the Html to, as well as the JS?
Comment: Ok I understand what you mean. But for my sake, this was a pre-made theme.  I am just trying yo customize a banner in the header area and hyperlink it to another page on the site.
Comment: I understand what you mean, but I have no idea where to add either code you posted.  There is no HTML file.  It's all PHP.  this is a wordpress theme.
Comment: That is what I have been saying.  I do not know where to add your code.
Comment: Is this a live site? Could you provide us with a URL to the page you're trying to add this ?
Comment: In the top right is the banner - http://jadeluxurycondos.com/jadeluxurycondos-new
Comment: Well, since I don't know the structure of the Theme I cannot help... Did you try to contact the developer you bought it from? I've edit my answer to include some general tips for what you need...
Comment: I have contacted the developer, but hasn't help at all.  Is there a way I can get u the files so you can look at it?
Comment: i just want to add a hyperlinked banner in the header sitting behind the social media icons in wordpress.  I have beat my brains about it and cannot figure it out.
Answer: Hi all and thank you for the help.
I have found a solution.  I left the image on the BG, then added a widget to the top right of the page where the image (banner sits), then added a text box to the widget area and added this

The image appears to be clickable.  Check here to see it in action.


how to put an array character into the equation?

Question: i try to put 8 byte character into the equation causing a lot of error,what i'm supposed to do to make sure the equation can take the static value and produce output  in the 8 bytes.
#include <math.h>
#include <hidef.h> /* for EnableInterrupts macro */

#include "derivative.h" /* include peripheral declarations */

void voltage_measure(void);

void main(void) {

  voltage_measure();

}

void voltage_measure(void) {
   char Van1[8],VA;
   char Vbn[8],VB;
   char Vcn[8],VC;
   char AC[4],ac;
   char BC[4],bc;
   char AB[4],ab;
   double Vab1,Vab2,Vbc1,Vbc2,Vac1,Vac2;
   double Vab[8],Vbc[8],Vac[8];

   Van1[0]=0xF0;
   Van1[1]=0x00;
   Van1[2]=0x00;
   Van1[3]=0x00;

   VA=0x000000F0;

   Vbn[0]=0x78;
   Vbn[1]=0x00;
   Vbn[2]=0x00;
   Vbn[3]=0x00;

   VB=0x78;

   Vcn[0]=0x3C;
   Vcn[1]=0x00;
   Vcn[2]=0x00;
   Vcn[3]=0x00;

   VC=0x3C;

   AB[0]=0xB4;
   AB[1]=0x00;

   ab=0xB4;

   AC[0]=0x2D;
   AC[1]=0x00;

   ac=0x2D;

   BC[0]=0x5A;
   BC[1]=0x00;

   bc=0x5A;
   Vab1=(VB*sin(ab))*(VB*sin(ab))  ;
   Vab2=(VA+(VB*cos(ab)))*(VA+(VB*cos(ab)));
   Vab[4]=sqrt(Vab1+Vab2);

   Vbc1=(VC*sin(bc))*(VC*sin(bc));
   Vbc2=(VB+(VC*cos(bc)))*(VB+(VC*cos(bc))) ;
   Vbc[4]=sqrt(Vbc1+Vbc2);

   Vac1=(VC*sin(ac))*(VC*sin(ac));
   Vac2=(VA+(VC*cos(ac)))*(VA+(VC*cos(ac)));
   Vac[4]=sqrt(Vac1+Vac2);
}

Comment: You might want to expand on your question a little...
Comment: -1 until more information provided
Comment: First off, `main()` should not return `void`. It should return `int`. Any compiler that lets your `main()` return `void` is wrong.
Comment: @Chris: it may be wrong, but it's not uncommon in embedded software. Some compilers don't even require there to be a main function at all!
Answer: This is what I have understood as yet,

you want to do arithmetic with double precision that has several parameters

you would like to store the parameters in char variables (maybe to save on space?)
I don't know why you try to write VA=0x000000F0; when its a char (1 byte) variable
the static value you refer are probably the constants VA etc
It might be useful to have all these working in the arithmetic at double precision
when you use the sin and sqrt kind of functions, they will work at double anyways
you do not have a main function listed here;
it would be there in your actual file (that compiles this code)
so, i am also assuming you have things like math.h included
and the math library on the compile command
that is, you do get the binary compiled without errors

maybe you can elaborate the problem you are facing a little more?

Update from comment 1.
When you say, "character with 8 byte array" -- are you trying to create a double with an 8 char array?

Update from comment 2.
If your answer is in double, you can catch it in a double variable.
A double is already 8-bytes (on most platforms).
Is there a special reason to get it into a char array or a byte array?
Update from comment 3.
The link error implies you did include a math library for the linking.
The header just gives function prototypes for compilation.
With gcc, it would be -lm on the command line.
Update from comment 4.
To convert a double to an integer value check this page,
How can I convert a floating-point value to an integer in C?
Comment: actually in this programming i try to created character with 8 byte array,and than the value Va is only the combination of the array,so what can i do so that the char value can be put into the equation.
Comment: from the calculation the answer must be in double.so i need to created a double with an 8 char array.is that possible..
Comment: @kiki: double VA = Van[0] + (Van[1] * pow(2, 8)) + (Van[2] * pow(2,16)) + (Van[3] * pow(2,24)) ...;
Comment: i also do not know what the special reason..i just been asked to do it so.i was facing the link error when i try to compile..it say that "sin"is undefined but i already include the math.h
Comment: do you know ow to assign values to a UINT8 variable?
Answer: Is the trouble that plain char on your machine is signed, so numbers such as 0xF0 are treated as -16 instead of +240?  Did you know that on some machines, this is what will happen?
Answer: Concerning your link error you mentioned in the comments: including math.h is not enough, you have to tell the linker to add the library as well. Try adding "-lm" in your command line.


Drupal 7 to D7 Migration

Question: I wan to migrate taxonomy terms from a D7 install to another.
The taxonomy terms have fields added to them and also translations.
Drupal Migration module would be the only option?
Answer: Use Taxonomy CSV import/export module. I used it once, works great...
Answer: I would look into using the Feeds module for this. Maybe this article can help.
Answer: Any of these following modules would help you to migrate your taxonomies:

Features
Taxonomy CSV import/export
Data export import
Feeds

Here is an article that explain how to do it without a module (manually).

Drupal 7 to D7 Migration


How to return custom exit code status in puppet apply using biemond orawls module

Question: I am using puppet module "Biemond orawls" orawls to install and orchestrate weblogic server, in orawls for successful configuration change puppet returns
 exit code and i restart the weblogic server for every successful "Change" to update the changed configuration which is not good every time, because during changing anything in weblogic from weblogic admin console we get the indication that server restart required which is only applicable for particular selected attribute or resource changes, and orawls do not give any option to get status of restart required like WLST, so i want to use WLST command isRestartRequired([attributeName]) during every edit session inside orawls code which will tell me if restart is required or not instead of restarting server for every successful change in weblogic server and i want this status to be returned from orawls to puppet apply command.
i am using puppet apply command to change any weblogic server resources like -
apply -e 'include amd_wls_cluster' ${PUPPET_COMMON_OPTS} ${IS_NOOP}

which returns few specific code like - Puppet apply exit code
--detailed-exitcodes: Provide extra information about the run via exit codes. If enabled, 'puppet apply' will use the following exit codes:
0: The run succeeded with no changes or failures; the system was already in the desired state.
1: The run failed.
2: The run succeeded, and some resources were changed.
4: The run succeeded, and some resources failed.
6: The run succeeded, and included both changes and failures.

Here i want to add my own custom status code may be 7 if WLST isRestartRequired([attributeName]) return true
i tried searching a lot but could not find anything, is this possible to return custom exit code from biemond orawls to puppet.
or is there any such option which i can use to identify if server restart is required using puppet's biemond orawls module.
Thank you in advance.
Comment: A more typical approach would be to have *Puppet* manage the service on each managed node.  This way you can easily limit restarts to circumstances that require them.  I'm uncertain whether this would present a problem for your particular configuration.
Answer:
i tried searching a lot but could not find anything, is this possible
  to return custom exit code from biemond orawls to puppet.

No, Puppet does not provide a mechanism for customizing its exit codes.  There is no hook exposed to modules that could provide for this.

or is there any such option which i can use to identify if server
  restart is required using puppet's biemond orawls module.

As I wrote in comments, the usual pattern is to let Puppet manage the service restart (or even a server restart, though I don't see why that would be necessary).  It's unclear exactly how that would look with orawls, which appears to have a ridiculously large public interface, but it looks like the docs contain several example configurations, and I would hope to see such a thing in at least one of those.
Alternatively, the Puppet agent can be configured (and in some versions is configured by default) to send reports describing each run to (typically) the master.  The master can then be configured to process these via a user-provided processing module.  These reports contain information about exactly which resources were changed, so you could surely use them to decide remotely whether to restart services / servers.


Show that $PQ$ bisects the line joining the Incenters

Question: Given a cyclic quadrilateral $ABCD$ such that $I_1, I_2$ denote the incenters of $\Delta ADC, \Delta ABC$ respectively and $P, Q$ are the midpoints of the arcs $AB,CD$, then show that $PQ$ bisects $I_1I_2$.
I have tried doing it. All I could find out is that if $K\equiv PQ\cap CD$, then, $MI_2KI_1$ forms a parallelogram and that completes the proof.
But I can't show how it forms a parallelogram.
Answer: Let $R$, $S$ the midpoints of the arcs $BC$, $AD$, respectively, and $I_3$, $I_4$ the incenters of $\triangle BDC$, $\triangle ABD$. It's not difficult to show that $I_1I_3I_2I_4$ is a rectangle: Note that $PQ \perp RS$ by chasing angles and see that are respectively parallel to $I_4I_2$, $I_1I_3$ and $I_4I_1$, $I_2I_3$). In fact, in this angles chasing you'll realize  that $\triangle PI_2I_4$, $\triangle RI_2I_3$, $\triangle QI_3I_1$ and $\triangle SI_4I_1$ are isosceles. Then $PQ$ is the perpendicular bissector of $I_4I_2$, then this line pass through the midpoint of $I_1I_2$.
Comment: I have taken the liberty to replace in your excellent answer : "mediatrix" (unused) by "perpendicular bissector"
Comment: The property that $I_1I_2I_3I_4$ is a rectangle is called the "Japanese theorem for cyclic quadrilaterals" (https://en.wikipedia.org/wiki/Japanese_theorem_for_cyclic_quadrilaterals)
Answer: Tricky. I slightly changed the notation for the midpoints of arcs:

We have that $AI_2, CI_2, AI_1, CI_1$ go through the midpoint of some arc, hence $M_{AB}M_{CD}, M_{AD} M_{BC}$ and $I_1 I_2$ are concurrent by Pascal's theorem. We also have $M_{AB}M_{CD}\perp M_{AD} M_{BC}$, so by setting $X=M_{AB}M_{CD}\cap M_{AD} M_{BC}$ it is not difficult to prove $I_1 X = I_2 X$ through some trigonometry. On the other hand, if you already know that $I_1,I_2,I_3,I_4$ are the vertices of a rectangle the other proof is far superior.
Comment: Excellent. Thinking to Pascal's theorem looks rather natural when one looks at you solution, but I wouldn't have had the idea by myself ...


Downloading a CSV from tmp folder of PHP project

Question: I currently am working on a PHP project that uses the Zend Framework.  I am making a CSV without any issues in the controller, but then want the user to be able to download the file by clicking a button in the view.
In my .phtml I have:
<a class="btn" href="<?php echo $this->download;?>" download>Export to CSV

$this->download is being set in the controller:
$view["download"] = $this->_createCSV($bqc_jobs, $startDate, $endDate, $processor_id, $defaultTime);

The _createCSV function creates the CSV and stores it in the temporary directory that the site uses.  It then returns the filepath.
private function _createCSV($jobs, $start, $end, $user=null, $minutes){
    $format = "Ymd_His";
    if(!$start && !$user){
        $start = date($format, strtoTime("-" . $minutes . " minutes"));
    }

    if(!$end){
        $end = \DateTime::createFromFormat($format, date($format))->format($format);
    }
    $directory = Config::$tempDir;
    $fileName = $directory . "/" . ($user ? $user . "_" : "") . ($start ? $start . "_" : "") . $end . "_report.csv";

    $file = fopen($fileName, 'w');
    foreach ($jobs as $job){
        fputcsv($file, $job);
    }

    fclose($file);

    return $fileName;
}

When the button is clicked, the browser tries to download the file, but errors because it cannot find the file.  This makes sense, since the browser should not have access to the temporary folder, but I'm not entirely sure how to get around this.
Comment: In Laravel I've recently achieved exactly the same thing by Streaming a file – I did a quick google and came across this which may help (not familiar with zend) http://www.sasaprolic.com/2013/02/sending-stream-responses-with-zend.html
Comment: @Djave that looks promising, thanks
Answer: If you are unable to see the folder due to the UNIX file permissions, then your only options will be to:

Change the file permissions on the tmp folder so that your web server can read/write there using chmod/chown (I assume it is a linux system?)
Use a different folder with sufficient permissions
Don't store the file on disk - store it in a database instead (not optimal).

Once you are sure your file permissions are in order and that the file can be read by apache, it appears that you should be able to use php's readfile function to actually transmit the file back to the browser:
<?php
$file = '/tmp/monkey.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
?>

Comment: I don't think it's an issue of file permissions, rather that the `tmp` directory is not being hosted on the site anywhere.
Comment: So what you are looking for is a way to open the temp file and serve it without it actually being part of the web site scope in the web server configuration file? What web server are you using?
Comment: Yes, pretty much.  I have access to the file on the server side, but I want it to be downloadable on the client side, so I need to figure out how to pass it to the client side.  I'm using Apache


Como alterar valores de posição para determinado recurso?

Question: Mais um desafio Hardcore, não sei se vou saber explicar bem, mas ai vai.
Na tabela abaixo, eu tenho o recurso "X", onde ele já efetuou 8 contatos( 5 concluídos e 3 não concluídos) e eu gostaria de contar automaticamente qual é o próximo contato que ele irá realizar retirando os 8 casos em que ele já realizou o contato. Na tabela também há a posição para contato que seria a sequencia de contato que deveria seguir mas essa coluna sempre vem com erro.

Muito obrigado por qualquer ajuda ou troca de conhecimento.
Answer: Com estes dados de teste:

Você pode realizar isto com o seguinte código, em que a explicação está no comentário:
<code>Sub teste()
    Dim ws As Worksheet
    Dim UltimaLinha As Long, i As Long
    Dim rng As Range
    Dim matriz() As Variant
    Set ws = ThisWorkbook.Sheets("Planilha1")
    i = 1
    With ws
        'Mostra dados se estiverem filtrados
        If .FilterMode Then
            .ShowAllData
        End If
        'Última linha da coluna A
        UltimaLinha = .Cells(.Rows.Count, "A").End(xlUp).Row
        'Filtra o campo 3 do intervalo [A1:D & ultimalinha], ou seja, filtra a coluna C para valores diferentes de Concluída e Não Concluída
        .Range(.Cells(1, "A"), .Cells(UltimaLinha, "D")).AutoFilter Field:=3, Criteria1:="<>Concluída", Operator:=xlAnd, Criteria2:="<>Não Concluída"
        'Ordena os valores filtrados
        .Range("D1").CurrentRegion.Sort Key1:=.Range("D1"), Order1:=xlAscending, _
                                        Header:=xlYes, OrderCustom:=1, DataOption1:=xlSortNormal
        'Se houver após o filto, msgbox do primeiro valor
        If .Range("A2:A" & UltimaLinha).SpecialCells(xlCellTypeVisible).Count > 0 Then
            For Each c In .Range("A2:A" & UltimaLinha).SpecialCells(xlCellTypeVisible)
                If i = 1 Then
                    MsgBox c
                End If
                i = i + 1
            Next c
        End If
    'Mostra dados se estiverem filtrados
    If .FilterMode Then
        .ShowAllData
    End If
    End With
End Sub
</code>
Resultado:
Comment: Cara, resolveu como se fosse nada haha, muito obrigado pela ajuda compartilhada.


Calculating the volume of a solid of revolution about a line.

Question: A figure is formed by revolving the region bounded by $f(x) = \cos{(x)}$ and $g(x) = \sin{(x)}$ from $0$ to $\dfrac{\pi}{4}$ about the line $y=-1$. This figure is formed by integration of two concentric circles with radii $f$ and $g$ where $f > g$. Since the axis of revolution is shifted down $1$, the functions are now $1$ greater than the axis $\implies V=\int_{0}^{\pi/4}((\cos{(x)}+1)^2-(\sin{(x)}+1)^2)dx$.
Is this true?
Comment: Almost. Left out the $\pi$.
Answer: Yep,
You're almost right, just forgot the $\pi$.
$V=\pi  \int\limits_0^{\frac{\pi }{4}} (\cos (\theta )+1)^2-(\sin (\theta )+1)^2 \, d\theta =\left(2 \sqrt{2}-\frac{3}{2}\right) \pi$


Could you give me an example (if it exists) of an $A$-module $M$ that is finite and has a base?

Question: *Definition:
Let $A$ be a unit ring. A left $A-$module is a triple $(M, +, ·)$ such that $M$ is a set, $ + : M \times M \rightarrow M$ is an internal operation on $M$ and $·$ is what is called an external operation on $M$ with domain of operators on $A$, which simply means that $· : A \times M \rightarrow M$. Furthermore the following properties must be met:

$(r + s) + t = r + (s + t)$ for all $r, s, t \in M$.
$r + s = s + r$ for all $r, s \in M$.
There exists an element $0\in M$ such that $r + 0 = r$ for all $r \in M$.
For every $r\in M$ there exists an element $−r\in M$ such that $r + (−r) = 0$.
$a(r + s) = ar + as$ for all $a \in A$ and all $r, s \in M$.
$(a + b)r = ar + br$ for all $a, b \in A$ and all $r\in M$.
$a(br) = (ab)r$ for all $a, b \in A$ and all $r\in M$.
$1r = r$ for all $r \in M$.

*Context:
I've read that not every module has a basis. As example $\mathbb Z/n\mathbb Z$ is a $\mathbb Z-$ module but if it has a basis then the $\mathbb Z-$module $\mathbb Z/n\mathbb Z$ has to be isomorphic to the $\mathbb Z-$module $\mathbb Z^m$ (for some $m\in \mathbb N$). But it is not possible because $\mathbb Z/n\mathbb Z$ is finite and $\mathbb Z^m$ not . So the $\mathbb Z-$ module $\mathbb Z/n\mathbb Z$ has not basis (by the way $\mathbb Z/n\mathbb Z$ is also represented by $\mathbb Z_n$).
*Question:
Is it possible for an $A$-module $M$ to be finite and also have a basis?
If it exist. Could you give me an example please?
Answer: There clearly is a finite module, and also has a basis.
You will know that we call $F$-module as $F$-vector space if $F$ is a field. And a vector space has a basis(which can be proven by Zorn's Lemma).
If $F$ is a finite field with $q$ elements(often written as $\Bbb F_q$), then $\Bbb F_q^n$ has $q^n$ elements, so it is finite. And it is $\Bbb F_q$-vector space, so it has a basis, like $\{e_i\mid1\le i\le n\}$.
Comment: In general, a finite free modules are (up to isomorphism) those of the form $R^n$, where $R$ is the base ring, which is finite, and $n$ is a non-negative integer, or the trivial module $\{0\}$. In particular, it is easy to check that there are no nonzero finite free modules over infinite rings.


Analysis Open and Closed Sets

Question: I have the following question and i'm not sure how to go about proving whether sets are open closed, or both.
Which of the following sets are open and which are closed?
$1)\ [1,2] \cup [3,4] \ in \ ( \mathbb{R},|\cdot|)$
$2)[1.2] \ in (\mathbb{R},d)$ where d is a discrete metric.
$3)\ B=[x=(x_n)_(n\in\mathbb{N}) :|x_n|< \epsilon\ for  \ all \ n \in \mathbb{N}] $ where $\epsilon>0$ is given in $(\ell^\infty, ||\cdot||_\infty)$
$4)\ c_0 $the set of sequences converging to 0 in $(\ell^\infty,||\cdot||~_\infty)$
Any help would be greatly appreciated
Answer: Hints:
1) Solve this intuitively first. There are basically two types of points in the set (inside an interval or boundary). Is it true that for such points you can always find a little interval that will be contained in the set? Once you convince yourself the answer is no, give a rigorous proof that the set is not open. Now, do the same with the complement and prove the set is closed.
2) Do you know that the union of open sets is open ? (if not, prove it). Do you know that in a discrete space, every singleton set is open (if not, prove it). Now conclude that any set is a discrete space is open (and thus also closed).
3 + 4) Figure out what open balls look like under the supremum metric, then proceed as above.
Remark: 1 and 2 above are very elementary, while 3 and 4 require some more getting used to the abstractness of metric spaces and open sets. Make sure you fully understand 1 and 2 before tackling 3 and 4 (this is the reason why I gave you detailed hints for 1 and 2, and left 3 and 4 more vague).
Good luck!
Answer: For 1) use that union of a finite number of closed sets is closed,
For 2) use that in the discrete metric every set is open and closed.
For 3) use that preimages of open sets are open when the function is continuous
For 4) This one is closed
Comment: The union of closed sets need not be closed (though the union of a finite number does). This can be shown by proving that the intersection of an infinite number of open sets can be closed, for example $$ \bigcap{\infty} (-\frac{1}{n},\frac{1}{n}) = {0} $$. Therefore by taking the complement we get that the union of an infinite number of closed sets need not be closed.
Comment: Sorry, that should be $$\bigcap_{\infty} (-\frac{1}{n},\frac{1}{n}) = \left\{ {0} \right\} $$ I made a typo and it won't let me fix it.

Analysis Open and Closed Sets


Paragraph's fields value loaded in a custom controller are in the default language instead of the current language

Question: I made a custom controller that load a paragraph field from a node and then render some part in a template. The paragraph field field_title and field_description are translatable.
The translation works fine on the admin side. I followed https://www.drupal.org/docs/8/modules/paragraphs/multilingual-paragraphs-configuration and I can see the content is translated from the admin. But my controller only loads the default language value instead of the current language.
<?php

/**
 * @file
 * Contains \Drupal\MyModule\Controller\MyModuleController.
 */

namespace Drupal\MyModule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class MyModuleController extends ControllerBase {

    /**
     * Controller load the game
     *
     * @return \Drupal\MyModule\Controller\RedirectResponse
     */
    public function gameView() {

        $nid = 1;

        // Load the game
        $game = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

        $stages = [];

        // Get all the stages of the game
        $paragraph_field_items = $game->get('field_stages')->getValue();
        if (!$paragraph_field_items) {
            throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException('This game has no level');
        }

        // Get storage for paragraph
        $paragraph_storage = \Drupal::entityTypeManager()->getStorage('paragraph');
        // Collect paragraph field's ids.
        $ids = array_column($paragraph_field_items, 'target_id');
        // Load all paragraph objects.
        $paragraphs_objects = $paragraph_storage->loadMultiple($ids);

        /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
        foreach ($paragraphs_objects as $paragraph) {
          // Get field from the paragraph.

          $description = [
              '#type' => 'processed_text',
              '#text' => $paragraph->get('field_description')->value,
              '#format' => 'basic_html',
          ];

          $stages [] = [
              'title' => $paragraph->get('field_title')->value,
              'image' => $paragraph->get('field_image'),
              'description' => $description,
              'east_lv95' => $paragraph->get('field_east_lv95')->value,
              'north_lv95' => $paragraph->get('field_north_lv95')->value,
          ];
        }

        return [
            '#theme' => 'game_map',
            '#party' => $party,
            '#stages' => $stages,
            '#game' => $game,
        ];
    }

Comment: This might be helpful https://drupal.stackexchange.com/questions/269468/what-is-the-difference-between-getvalue-and-referencedentities-to-fetch-para
Comment: After you loaded the `$game` with the entity type manager, load the translation with the entity repository: `$game = \Drupal::service('entity.repository')->getTranslationFromContext($game);`. So you just have to add this one line to the code you already have. And maybe consider injecting the services instead, since `\Drupal` calls should be avoided.
Answer: Based on the comments I changed $game->get('field_stages')->getValue(); for $game->get('field_stages')->referencedEntities();. This allow me to greatly simply a part of the code.
To load the correct language I added $paragraph = \Drupal::service('entity.repository')->getTranslationFromContext($paragraph); inside the loop. Using getTranslationFromContext on the $game didn't works for the paragraph.
I'm not 100% satisfied as I feel translation should be loaded directly when all the fields are loaded with referencedEntities(). But it works and perhaps caching do some magic behind the scene.
This answer helped a lot https://drupal.stackexchange.com/a/269493/1761
// Load the game
$game = \Drupal::entityTypeManager()->getStorage('node')->load($gameID);

$stages = [];

// Get all the stage of the game
$paragraph_field_items = $game->get('field_stages')->referencedEntities();

if (!$paragraph_field_items) {
    throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException('This game has no level');
}

/** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
foreach ($paragraph_field_items as $paragraph) {

  // Get the translation
  $paragraph = \Drupal::service('entity.repository')->getTranslationFromContext($paragraph);

  $description = [
      '#type' => 'processed_text',
      '#text' => $paragraph->get('field_description')->value,
      '#format' => 'basic_html',
  ];

  $stages [] = [
      'title' => $paragraph->get('field_title')->value,
      'image' => $paragraph->get('field_image'),
      'description' => $description,
      'east_lv95' => $paragraph->get('field_east_lv95')->value,
      'north_lv95' => $paragraph->get('field_north_lv95')->value,
  ];
}


Can I use if statements to prevent SQL injection?

Question: I have been trying to get my application to pass Checkmarx but I keep running into a Second Order SQL Injection vulnerability.
Presently my code looks like this:
    public static final String SELECT_NEXTVAL_FOR = "SELECT NEXTVAL FOR ";

    @Value("#{ systemProperties['sequence.schema']}")
    String sequenceSchema;

    public Integer getNextContactId() {
        if (sequenceSchema.matches("[A-Z]{3}@[A-Z]{3}|[A-Z]\\d[A-Z]{5}")) {
            Query getNextContactIdQuery = entityManager.createNativeQuery(
                    SELECT_NEXTVAL_FOR + sequenceSchema + ".CNTCT_ID FROM SYSIBM.SYSDUMMY1");

            return (Integer) getNextContactIdQuery.getSingleResult();
        } else {
            return null;
        }

Checkmarx is flagging the sequenceSchema as the problem here. My thoughts were that the if statement would ensure whatever is present in sequenceSchema would only match the specific regex for our schemas. Apparently that is not good enough. I have tried to use positional/named parameters but those don't work outside of WHERE or HAVING clauses. I have tried Criteria Queries as seen here without any luck.
I had another thought along similar lines to what I have here, but instead of using regex I could create a set of the valid schemas and comparing that to the sequenceSchema as such:
    public static final String SELECT_NEXTVAL_FOR = "SELECT NEXTVAL FOR ";

    @Value("#{ systemProperties['sequence.schema']}")
    String sequenceSchema;

    Set<String> validSchemas = ... //create set of valid schemas

    public Integer getNextContactId() {
        if (validSchemas.contains(sequenceSchema)) {
            Query getNextContactIdQuery = entityManager.createNativeQuery(
                    SELECT_NEXTVAL_FOR + sequenceSchema + ".CNTCT_ID FROM SYSIBM.SYSDUMMY1");

            return (Integer) getNextContactIdQuery.getSingleResult();
        } else {
            return null;
        }

Would that prevent against SQL injection? If not, why? I am really struggling to find a working solution here.
Comment: the code was "safe" even without those regexp puzzles: in order to exploit the "vulnerability"  the attacker is supposed to modify java startup parameters, if he can, potential "sql injection" is already not a security issue :).
Comment: There's a difference between "protection against SQL injection" and "can a tool **understand** it's protected against SQL injection". In other words: let's say I had a fool-proof way of quoting user input such that SQL injection simply can't happen. There's no *(reasonable)* way a tool will **know** it's safe if I'm just concatenating strings.
Comment: Use security practices from experts, don't try to create your own: https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html
Answer: Folks who recommend using query parameters to defend against SQL injection are half-right. That is the recommended solution in most cases of dynamic SQL queries.
But query parameters can be used only in place of constant values. Not identifiers (in your case a schema identifier), or expressions, or SQL keywords, etc.
You are on the right track with using validation of some kind, so the schema identifier is limited to a known safe value. Then you can interpolate that string into your SQL query. If you have done adequate validation, then it's safe from SQL injection.
You should also delimit your identifier, just in case it contains a space, or a punctuation symbol, or conflicts with an SQL reserved keyword. In DB2, use double-quotes as identifier delimiters.
However, even though the kind of validation you are doing may be sufficient, it may not be a method of defense that can be recognized by an automated SQL injection detection tool like Checkmarx. It might see that you're putting variables together into an SQL string, and conclude that it's an SQL injection risk. It can't tell that your validation is sufficient to prevent problems.
Automated solutions for SQL injection detection are always limited. You do have to use human analysis sometimes.
I know this is unfashionable to say these days, given the trend to say that AI will put programmers out of work. But AI is not yet able to handle edge cases as reliably as expert humans. I am not convinced it ever will be.
Comment: I ended up going with a whitelist of sorts for the schema since there are only ten possible schemas that it could be. I found this would be a little bit safer than comparing against regex. The validation to compare the schema identifier against what is allowed should protect against any injection. Like you mentioned the AI in Checkmarx cannot recognize this as a solution so I had to mark it as a false positive.
Answer: I am not going to do your work for you... But your question can be summed up as "Why am I getting SQL injection?"
The answer is "Because I am dynamically creating SQL queries", the solution is: Stop making dynamically created SQL queries. Once you stop doing that, all your problems go away.. How do you stop? Use PreparedStatement() with variable binding (parameterized queries).
Using PreparedStatement() your sql access will look something like:
string what_schema= //! Some value;
String query = SELECT_NEXTVAL_FOR + "?.CNTCT_ID FROM SYSIBM.SYSDUMMY1";
PreparedStatement pstmt = connection.prepareStatement(query);
pstmt.setString(1, what_schema);
ResultSet results = pstmt.executeQuery();

Comment: I'm not a DB2 user, but as far as I know, one cannot use query parameters for schema names in any implementation of SQL. Query parameters can only be used in place of constant values in expressions. (I did not downvote your answer)


How to make an EditText wrap correctly in a Constraintlayout

Question: Hello everyone I have a problem that I have been bashing my head against for 2 days now. It seems like such a simple issue but I just cant seem to solve it. Basically I am making a morse code translating app
When the user types into the EditText field it immediately translate the typed text into morse below.
Problem:
What I want is the EditTexts to expand to take up as much space as is needed but to wrap an become scrollable once they reache a certain height. The issue is virtually everything ive tried has resulted in one of the EditTexts pushing the other off screen or notwrapping its text at all.
What Iv Got so far:
I have a layout that does exactly what I want, And works the way I want. It just doesn't look the way I want. I am using Navigation components so the below view is inflated in the FragmentContainerView in the MainActivty. I am also setting the window behaviour  android:windowSoftInputMode="adjustResize"
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/decoder_text_to_morse_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/blue"
    tools:context=".Fragments.DecoderFragment"
   >

    <androidx.appcompat.widget.AppCompatEditText
        android:padding="@dimen/four_dp"
        android:gravity="top"
        android:id="@+id/include1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="@dimen/sixteen_dp"
        android:background="@drawable/card_background"
        app:layout_constraintBottom_toTopOf="@+id/decode_changer_fab"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="packed" />

    <TextView
        android:id="@+id/header_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/sixteen_dp"
        android:layout_marginEnd="@dimen/sixteen_dp"
        android:text="Text"
        app:layout_constraintBottom_toBottomOf="@id/decode_changer_fab"
        app:layout_constraintEnd_toStartOf="@+id/decode_changer_fab"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintHorizontal_chainStyle="spread_inside"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@id/decode_changer_fab" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/decode_changer_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/eight_dp"
        android:src="@drawable/ic_arrow"
        app:layout_constraintBottom_toTopOf="@+id/include2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/include1" />

    <TextView
        android:id="@+id/header_morse"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/sixteen_dp"
        android:layout_marginEnd="@dimen/sixteen_dp"
        android:text="Morse"
        app:layout_constraintBottom_toBottomOf="@id/decode_changer_fab"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toEndOf="@+id/decode_changer_fab"
        app:layout_constraintTop_toTopOf="@id/decode_changer_fab" />

    <androidx.appcompat.widget.AppCompatEditText
        android:padding="@dimen/four_dp"
        android:gravity="top"
        android:id="@+id/include2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="@dimen/sixteen_dp"
        android:background="@drawable/card_background"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/decode_changer_fab" />
</androidx.constraintlayout.widget.ConstraintLayout>

All I want is for the EditTexts to begin in a collapsed state, Expand to house their content and resize if the Keyboard is open. Using app:layout_constraintHeight_default="wrap" doesnt work and causes the bottom EditText to push the top one off the screen. I realize app:layout_constraintHeight_default="wrap" is deprecated and the recommended way is  app:layout_constrainedHeight="true" with android:layout_height="wrap_content" but the behaviour is the same with the bottom EditText pushing the top one off screen. Any help will be greatly appreciated. Really struggling to do a mundane thing -_-
Comment: I think what fixed it is using `android:inputType="textMultiLine"` as well as limiting the height of 1 of the EditTexts using `android:maxHeight="128dp"`. Now it seems like `android:layout_height="wrap_content"` with `app:layout_constrainedHeight="true"` is working. That said i'm sure sure I tried it this way and it still wasn't working. So Confused XD
Comment: Neither of these answers solved the problem. turned out it was an xml formatting issues. New question is [here](https://stackoverflow.com/questions/66256281/a-question-for-anyone-experienced-with-android-and-xml-to-explain-a-mystery)
Answer: have you tried put:
android:inputType="textMultiLine"
inside your EditText tag ?
like :
<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="textMultiLine" />

Answer: For me when I needed this, using max and min heights worked, after the max height, the edit text will become scrollable
<androidx.appcompat.widget.AppCompatEditText
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:maxHeight= //desired dimensions
      android:minHeight = //desired dimensions
       />


Show an absolute minimum and positive/negative derivative of function

Question: Let $f : \mathbb R \to \mathbb R$ be defined by $f(x) := 2x^4+x^4\sin(1/x)$ for $x \neq 0$ and $f(0) = 0$. Show that f has an absolute minimum at x = 0, but that its derivative has both positive and negative values in every neighborhood of 0.
I'm already confused intuitively about this problem
To prove absolute minimum, I need to show that for all $c$ in $\mathbb R$, $f(c) > f(x)$ when $x = 0$ right? or in other words $f'(x) = 0$, but it says that the derivative has positive and negative values in the neighborhood of $0$? What?
Comment: function is not defined at $x=0$.
Answer: Since $f(x)=x^4\left(2+\sin(1/x)\right)$ when $x\ne 0$ we have
$$x^4\le f(x)\le 3x^4,\quad x\in\mathbb{R}\backslash\{0\}$$
Then $f(x)\ge0=f(0)$ for all $x\in\mathbb{R}$, so $f$ has an absolute minimum at $x=0$.
On the other hand,
\begin{align*}
f'(0)&=\lim_{h\to 0}\frac{h^4\left[2+\sin\left(\frac{1}{h}\right)\right]-0}{h}\\
&=\lim_{h\to 0}\left[h^3\left(2+\sin\frac{1}{h}\right)\right]
\end{align*}
last limit exists, and is $0$, since $1\le2+\sin(1/h)\le 3$ for every $h\ne 0$ and $h^3\to 0$. So $$\color{blue}{f'(0)=0}$$
Thus $$\color{blue}{f'(x)=\begin{cases}0&x=0\\4x^3\left[2+\sin\frac{1}{x}\right]-x^2\cos\frac{1}{x}&x\ne 0\end{cases}}$$
If $U\ni0$ is a neighborhood of $0$ there exist $r>0$ such that $(-r,r)\subset U$, now, by Archimedean property there exist $N\in\mathbb{N}$ such that $N>\frac{1}{r}$, so
$$x_N=-\frac{1}{2N\pi}\in U\implies f'(x_N)=8x_N^3-x_N^2<0,\quad\text{and}$$
$$y_N=\frac{1}{(2N+1)\pi}\in U,\quad f'(y_N)=8y_N^3+y_N^2>0$$
Answer: $f'(x)$ is indeed $0$. But this does not contradict the fact that $f'(x)$ achieves positive and negative values alternately. It is clearly shown in the pictures:

$f(x)=2x^4+x^4 \sin (1/x)$
It's derivative


Why does inverse fourier transformation have a $\frac{1}{N}$ term?

Question: I've been trying to learn the Discrete Fourier Transformation (DFT) and the Inverse DFT (IDFT).
From Wikipedia, I gather we can define the matrix transformations for the DFT as follows. Let $\omega= e^{-2\pi i/N}$ and let $$\mathbf{W}= \left[\frac{\omega^{jk}}{\sqrt{N}}\right]_{j,k=0,\cdots,N-1}$$
Then we can take a vector $\mathbf{x}$ and transform it via
$$\mathbf{X} = \mathbf{W}\mathbf{x}$$
Source: https://en.wikipedia.org/wiki/DFT_matrix
Question 1: Does the DFT always involve a $\frac{1}{\sqrt{N}}$ term? I noticed that in many cases it seems defined without that, e.g.

Source: https://en.wikipedia.org/wiki/Discrete_Fourier_transform
Now, $\mathbf{W}$ is a unitary matrix and therefore $\mathbf{W}^{*}\mathbf{W}=\mathbf{I}_{N}$. I have read that the IDFT is then defined as
$$\mathbf{x} = \frac{1}{N}\mathbf{W}^{*}\mathbf{X}$$
Source: https://www.kth.se/social/upload/50919490f2765474b1890dde/lec2.pdf
Ok, so if we put these together
$$\mathbf{x} = \frac{1}{N}\mathbf{W}^{*}\mathbf{X} =  \frac{1}{N}\mathbf{W}^{*}\left(\mathbf{W}\mathbf{x}\right)=\frac{1}{N}\mathbf{I}_{N}\mathbf{x}=\frac{1}{N}\mathbf{x}$$
which obviously doesn't make any sense.
Question 2:
What is wrong with my definitions of the DFT and IDFT such that it isn't inverting properly?
Comment: Did you read the entire wiki entry? As with the continuous FT, there are different conventions for normalizing. If you make $\mathbf W$ unitary, there is no $1/N$. If there's no $\sqrt N$ in the original, then you use the $1/N$.
Comment: @TedShifrin ok, that's helpful. Thanks Ted!
Answer: Since
$$
\left[\omega^{jk}\right]\left[\omega^{jk}\right]^\dagger = NI_N
$$
your forward and inverse matrices need to be multiplied by a net factor of $1/N$ for normalization. This can be accomplished by giving each a $1/\sqrt{N}$ factor, as in your first link, or by putting the full $1/N$ on the inverse matrix, as in your second two links. The matrix will only be unitary using the first convention.
You could also, hypothetically, split it up in other ways as long as the product is $1/N$, but the above two are most common.
Different normalization conventions are used by different sources, so always check which one they're using.
Comment: super helpful! this was great. thank you!