Por que declarar static para todos os métodos de uma classe static?

Question: Eu estava estudando aqui C# até que cheguei na parte que fala sobre o static. O professor mostra que é possível utilizar essa declaração em métodos e até na própria classe.
O problema é que quando se utiliza o static na classe, todos os métodos devem ser declarados como static obrigatoriamente. A minha dúvida é: porque devo declarar static em todos os métodos se eu já declaro que a classe é estática?
Por que o compilador não pode simplesmente definir os métodos como estáticos implicitamente ao declarar a classe como estática, para que não precise adicionar essa declaração a dezenas de métodos e atributos como no exemplo abaixo?
static class Class1 {
    static public void Method1(){...}
    static public void Method2(){...}
    static public void Method3(){...}
}

// Bem melhor a forma abaixo não é ?

static class Class2 {
    public void Method1(){...}
    public void Method2(){...}
    public void Method3(){...}
}

Answer: E por que você deveria deixar de dizer que o método estático é estático?
É uma questão de gosto. Você acha que digitar menos é mais importante, os criadores da linguagem acharam que era mais importante ser mais legível e consistente. Se o método é estático diga que ele é estático, em outras classes e interface tem que dizer, diga nessa também.
O compilador poderia aceitar isso, não há motivos técnicos que impeçam, mas linguagem tem estética e preferiram assim.
Mas há dúvidas qual é a melhor forma. Um dos escritores do compilador do C# diz como é difícil decidir o que é melhor fazer, traduzo aqui a resposta do Eric Lippert no SOen:

Eu recebo perguntas como essa o tempo todo. Basicamente, a pergunta se resume a "quando de fato um membro declarado pode ser deduzido pelo compilador, a declaração explícita desse fato deve ser (1) obrigatória, (2) opcional ou (3) proibida?"
Não há uma resposta fácil. Cada uma deve ser tomada caso a caso. É
necessário colocar static em um membro de uma classe estática.
Colocar new em um método oculto e não substituinte de uma classe
derivada é opcional. É proibido colocar static em uma const.
Considerando brevemente seu cenário, parece bizarro torná-lo proibido.
Você tem uma classe inteira cheia de métodos marcados como static.
Você decide tornar a classe estática e isso significa que você deve
remover todos os modificadores estáticos? Isso seria estranho.
Parece bizarro torná-lo opcional; suponha que você tenha uma classe
estática e dois métodos, um marcado como estático e outro não. Como a
estática normalmente não é o padrão, parece natural pensar que existe
uma diferença entre eles. Torná-lo opcional parece ser potencialmente
confuso.
Isso faz com que ser obrigatório, como a menos ruim das três opções.

Coloquei no GitHub para referência futura.


Loop for em lista com vários elementos - Python

Question: Tenho uma lista com várias tuplas dentro, e dentro das tuplas vários elementos.
Preciso varrer todas as tuplas da lista para capturar um elemento que está dentro de cada uma dessa tuplas. Como posso fazer isso?
A estrutura está abaixo:
Variável criada / Tipo:list / Tamanho: 10
Ao abrir a lista:
Índice: 0 / Tipo: Tuple / Tamanho: 5 -> sendo: 2 Str e 3 Int
Quero capturar um dos dados do tipo Int.
Answer: Normalmente usa-se o for para iterar em cima de uma lista.
lista = [1, 2, 3]

for numero in lista:
    print(numero)

A saída será:
1
2
3

Uma tupla (assim como uma lista) pode ser acessado pelo índice de seu elemento
tupla = ("John", "Doe", 40)

nome = tupla[0]
sobrenome = tupla[1]
idade = tupla[2]

Sendo assim temos:
>>> print(nome)
John
>>> print(sobrenome)
Doe
>>> print(idade)
40

Juntanto dos dois
lista_com_tuplas = [("John", "Doe", 40), ("Joao", "Silva", 30)]

for tupla in lista_com_tuplas:
    nome = tupla[0]
    sobrenome = tupla[1]
    idade = tupla[2]
    print(f"{nome} {sobrenome} tem {idade} anos.")

Saída
John Doe tem 40 anos.
Joao Silva tem 30 anos.

Espero ter ajudado.
Comment: Ajudou sim, mas o que eu preciso é pegar somente um dos elementos de cada tupla e somar tds.... São várias Tuplas no qual eu preciso capturar 1 elemento de cada uma...
Comment: Consegue seguir a partir do que eu mostrei ou precisa de ajuda ainda?
Comment: Não consegui, Paulo. Fiz um for dentro de outro for, mas ele está iterando o primeiro item dentro da Tupla (que é uma Str), mas eu preciso que retorne o quinto elemento da Tupla, que é um Int.
Comment: Paulo, consegui agora!!! Fiz uma junção do que vc me respondeu e deu certo!!! Agradeço muito! Sou novo na programação e essa foi minha primeira postagem aqui e foi resolvido graças à sua contribuição!!! Agradeço imensamente sua ajuda!!! Abs e sucesso!
Comment: Boa @DarthGaino um passo por vez


Numbering rows in a view

Question: I am connecting to an SQL database using a PLC, and need to return a list of values. Unfortunately, the PLC has limited memory, and can only retrieve approximately 5,000 values at any one time, however the database may contain up to 10,000 values.
As such I need a way of retrieving these values in 2 operations. Unfortunately the PLC is limited in the query it can perform, and is limited to only SELECT and WHERE commands, so I cannot use LIMIT or TOP or anything like that.
Is there a way in which I can create a view, and auto number every field in that view? I could then query all records < 5,000, followed by a second query of < 10,000 etc?
Unfortunately it seems that views do not support the identity column, so this would need to be done manually.
Anyone any suggestions? My only realistic option at the moment seems to be to create 2 views, one with the first 5,000 and 1 with the next 5,000...
I am using SQL Server 2000 if that makes a difference...
Answer: While the code provided by Derek does what I asked - i.e numbers each row in the view, the performance for this is really poor - approximately 20 seconds to number 100 rows. As such it is not a workable solution. An alternative is to number the first 5,000 records with a 1, and the next 5,000 with a 2. This can be done with 3 simple queries, and is far quicker to execute.
The code to do so is as follows:
SELECT TOP(5000) BCode, SAPCode, 1 as GroupNo FROM dbo.DB
UNION
SELECT TOP (10000) BCode, SAPCode, 2 as GroupNo FROM dbo.DB p
WHERE ID NOT IN (SELECT TOP(5000) ID FROM dbo.DB)

Although, as pointed out by Andriy M, you should also specify an explicit sort, to ensure the you dont miss any records.
Answer: One possibility might be to use a function with a temporary table such as
CREATE FUNCTION dbo.OrderedBCodeData()
RETURNS @Data TABLE (RowNumber int IDENTITY(1,1),BCode int,SAPCode int)
AS
BEGIN
    INSERT INTO @Data (BCode,SAPCode)
    SELECT BCode,SAPCode FROM dbo.DB ORDER BY BCode

    RETURN
END

And select from this function such as
SELECT FROM dbo.OrderedBCodeData() WHERE RowNumber BETWEEN 5000 AND 10000

I haven't used this in production ever, in fact was just a quick idea this morning but worth exploring as a neater alternative?
Comment: Thanks Justin - that sounds like it might work, however we have decided to go with the option I mentioned in my post. We are communicating to the database from a PLC, which has very limited support for SQL.. I am not sure if it will support calls to DB functions.
Answer: There are 2 solutions. The easiest is to modify your SQL table and add an IDENTITY column. If that is not a possibility, the you'll have to do something like the below query. For 10000 rows, it shouldn't be too slow. But as the table grows, it will become worse and worse-performing.
SELECT        Col1, Col2, (SELECT COUNT(i.Col1)
               FROM yourtable i
               WHERE i.Col1 <= o.Col1) AS RowID
FROM          yourtable o

Comment: Thanks, Derek, while that works and numbers them, it takes 20 seconds to number 100 records on my test database, so that isn't going to work too well with 10,000 rows! I have instead found a way to number the first 5,000 with a 1, and the second 5,000 with a 2, we can then query on that instead.
Comment: The code mentioned above is as follows:

`SELECT TOP(5000) BCode, SAPCode, 1 as GroupNo FROM dbo.DB
union
SELECT TOP (10000) BCode, SAPCode, 2 as GroupNo
FROM         dbo.DB p
WHERE ID NOT IN (SELECT TOP(5000) ID FROM dbo.DB)`
Comment: I'm glad you found a solution - you can post it as a separate "Answer" and accept your own answer so anyone that runs into this problem will see your end-solution.
Comment: @Gavin Coates: Without an explicit ORDER BY you are not guaranteed to always obtain the same 5000 rows in both cases. The problem may never arise, yet that is unreliable.

Numbering rows in a view


Reboot a Ubuntu server based on AWS Cloudwatch Metric

Question: I'm in the process of debugging a random spike on a server and in the mean time I would love to be able to just reboot the machine when a certain CPU threshold is met.
The AWS Cloudwatch rule is set up and works beautifully to notify me by email.  What I would prefer is to have it take action and just cycle the machine.
Answer: AWS Cloudwatch can send alarms not only through email but through HTTP(S) or Amazon SQS. You could create a script to receive these notification on your EC2 instance or on an external monitoring server and execute server reboot through ssh shudown -r or through EC2 API.


Pigeonhole principle.

Question:
Let $p(x)$ be a polynomial with integer coefficients. Suppose there exist $3$ different integers $a$, $b$, and $c$, such that $$p(a) = p(b) = p(c) = 3.$$ Now using the fact that $x−y$ divides $p(x)−p(y)$ for any two $x,y\in\mathbb Z$ and the pigeonhole
  principle to show that there is no integer $d$ with $p(d) = 4$.

How do you apply the pigeonhole principle here? Thank you in advance.
Answer: Suppose otherwise. Then, using $u-v\mid p(u)-p(v)$, $$d-a,d-b,d-c$$ are divisors of $4-3=1$. This is only possible if these numbers are $1$ or $-1$. Then, by Pigeonhole, two of these numbers are equal, contradicting the fact that $a$, $b$, $c$ are distinct. $\blacksquare$

Pigeonhole principle.


Which decimal can be multiplied by the result of $(x \times 1.15)$ to return $15$% of $x$?

Question:
Which decimal can be multiplied by the result of $(x \times 1.15)$ to return $15$% of $x$?

For example, when I want to add $15$% sales tax to an item before tax, I would multiply by $1.15$.
$100 \times 1.15 = 115$
I was trying to figure out which decimal I can multiply against the result $(115)$ that would essentially give me the same result of $[(x \times 1.15) - x]$.
Through trial and error I've come up with the decimal $0.13044$ which approximately gave me what I want. Example:
$(100 \times 1.15) - 100 = 15$
vs
$4(100\times1.15) \times 0.13044 = 15.0006$
Is there a way to calculate the exact or close to exact decimal that I am looking for, that when multiplied by a number plus $15$% would return the value of the $15$%.
This is purely out of curiosity rather than for any practical purpose.
Answer: Let $y = 0.15 x$, and let $z = 1.15x$.
Then, you want to uncover the relationship between $z$ and $y$.
$$\frac{z}{y} = \frac{1.15 x}{0.15 x} = \frac{1.15}{0.15} = \frac{23}{3}.$$
So, $y = \frac{3}{23}z$, so we see that
$$\frac{3}{23} 1.15 x = 0.15x.$$
Answer: You want to have your decimal $q$ such that $$q \times (1.15 \times x ) = 1.15 \times x - x = 0.15 \times x$$
so $$q \times 1.15 \times x = 0.15 \times x$$ for all $x$
Finally, you have $$q = \frac{0.15}{1.15} \simeq 0.1304347826$$
In general, if you increase by $p$ (i.e. $100p$ %), $$q = \frac{p}{p+1}$$
Comment: Yes thank you this makes a lot of sense. Arkamis answer was good too, but it was for the opposite of what i wanted. His answer was giving me a factor to divide by and yours which is the inverse is the factor to multiply by. Thanks guys.


NPM | Error while installing modules

Question: When I try to install some modules I get this error:

npm ERR! Unexpected end of JSON input while parsing near
  '..."hjs":"~0.0.6","marke'
npm ERR! A complete log of this run can be found in: npm ERR!
  C:\Users\omare\AppData\Roaming\npm-cache_logs\2018-07-30T09_21_21_147Z-debug.log

And in the log file I get this:
0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'i',
1 verbose cli   'express' ]
2 info using firstname.lastname@example.com
3 info using email@example.com
4 verbose npm-session 1b65207ea7164d4e
5 silly install loadCurrentTree
6 silly install readLocalPackageData
7 http fetch GET 304 https://registry.npmjs.org/express 1289ms (from cache)
8 silly fetchPackageMetaData error for express@^4.15.3 Unexpected end of JSON input while parsing near '..."hjs":"~0.0.6","marke'
9 verbose stack SyntaxError: Unexpected end of JSON input while parsing near '..."hjs":"~0.0.6","marke'
9 verbose stack     at JSON.parse (<anonymous>)
9 verbose stack     at parseJson (C:\Program Files\nodejs\node_modules\npm\node_modules\pacote\node_modules\make-fetch-happen\node_modules\node-fetch-npm\node_modules\json-parse-better-errors\index.js:7:17)
9 verbose stack     at consumeBody.call.then.buffer (C:\Program Files\nodejs\node_modules\npm\node_modules\pacote\node_modules\make-fetch-happen\node_modules\node-fetch-npm\src\body.js:96:50)
9 verbose stack     at <anonymous>
9 verbose stack     at process._tickCallback (internal/process/next_tick.js:188:7)
10 verbose cwd H:\Projects\WEB Development\My Stuff\Nuxt
11 verbose Windows_NT 10.0.17134
12 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "i" "express"
13 verbose node v8.11.3
14 verbose npm  v5.6.0
15 error Unexpected end of JSON input while parsing near '..."hjs":"~0.0.6","marke'
16 verbose exit [ 1, true ]

My package.json file:
{
  "name": "mevn",
  "version": "1.0.0",
  "description": "MongoDb, Express, Vue.js, and Node.js stack workflow",
  "main": "app.js",
  "scripts": {
    "start-server": "node server/bin/www",
    "dev": "webpack-dev-server --inline --progress --config Client/build/webpack.dev.conf.js",
    "start-client": "npm run dev",
    "build-client": "node Client/build/build.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/Omar-Hussein/MEVN.git"
  },
  "keywords": [
    "workflow",
    "mevn",
    "mongodb",
    "express",
    "node",
    "vue"
  ],
  "author": "Omar Hussein",
  "license": "WTFPL",
  "bugs": {
    "url": "https://github.com/Omar-Hussein/MEVN/issues"
  },
  "homepage": "https://github.com/Omar-Hussein/MEVN#readme",
  "engines": {
    "node": ">= 6.0.0",
    "npm": ">= 3.0.0"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 8"
  ],
  "dependencies": {
    "axios": "^0.18.0",
    "connect-mongo": "^2.0.1",
    "cors": "~2.8.4",
    "debug": "^3.1.0",
    "express-session": "^1.15.6",
    "express-validator": "^5.3.0",
    "http-errors": "^1.6.3",
    "lodash": "^4.17.10",
    "mongoose": "^5.2.5",
    "morgan": "^1.9.0",
    "vue": "^2.5.16",
    "vue-router": "^3.0.1",
    "vuetify": "^1.1.8",
    "vuex": "^3.0.1",
    "vuex-persistedstate": "^2.5.4",
    "vuex-router-sync": "^5.0.0"
  },
  "devDependencies": {
    "autoprefixer": "^9.0.1",
    "babel": "^6.23.0",
    "babel-helper-vue-jsx-merge-props": "^2.0.3",
    "babel-loader": "^7.1.5",
    "babel-plugin-syntax-jsx": "^6.18.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-plugin-transform-vue-jsx": "^3.7.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-stage-2": "^6.24.1",
    "chalk": "^2.4.1",
    "copy-webpack-plugin": "^4.5.2",
    "css-loader": "^1.0.0",
    "extract-text-webpack-plugin": "^3.0.2",
    "file-loader": "^1.1.11",
    "friendly-errors-webpack-plugin": "^1.7.0",
    "html-webpack-plugin": "^3.2.0",
    "material-design-icons-iconfont": "^3.0.3",
    "node-notifier": "^5.2.1",
    "optimize-css-assets-webpack-plugin": "^5.0.0",
    "ora": "^3.0.0",
    "portfinder": "^1.0.13",
    "postcss-import": "^11.1.0",
    "postcss-loader": "^2.1.6",
    "postcss-url": "^7.3.2",
    "rimraf": "^2.6.2",
    "semver": "^5.5.0",
    "shelljs": "^0.8.2",
    "uglifyjs-webpack-plugin": "^1.2.7",
    "url-loader": "^1.0.1",
    "vue-loader": "^15.2.6",
    "vue-style-loader": "^4.1.1",
    "vue-template-compiler": "^2.5.16",
    "webpack": "^4.16.3",
    "webpack-merge": "^4.1.3"
  }
}

info:

OS: Windows 10
Node: v 8.11.3
NPM: v 5.6.0

Some of the modules I get this error from:

express
connect-flash
webpack-bundle-analyzer
webpack-dev-server
Comment: Check your `package.json`, seems it's not well-formatted JSON.
Comment: Can you please update your post with your `package.json` file contents?
Comment: your `package.json` contains a single quote, its not placed properly, You need to format that
Comment: I don't think the problem is from my `package.json` file. I've tried this in multiple folders without `package.json` file. anyway, I've added it...
Answer: Try executing,
npm cache clean

And then do a,
npm install

Hope this helps!
Comment: I had to use the force flag but this worked for me too
Answer: After struggling to resolve this issue, the thing that finally worked for me was:
npm cache clean --force
npm install

NPM | Error while installing modules


Differences in proportion of variance explained by MuMin and r2glmm packages using the nsj method

Question: I estimated the proportion of variance explained by the fixed predictors of a linear mixed model using both packages MuMIn and r2glmm however when I use the nsj method I get R2c and R2m with the MuMIn of 0.217 and with the r2glmm an r2  of 0.42.  The difference is even larger if I use the sgv method.  Why is this?
I was hoping both estimates were similar.
My model:
modeltemp4<-lme((S1_93_11) ~(MSperDA)+MEANELEVSMO+DivDASqKM,
corGaus(form=~jlat+jlon), method = "ML",
weights=varIdent(form=~1|Contrast),random= ~ 1|Contrast,data=Priest, control =
lmeControl(opt = 'optim') )

r2=r2beta(modeltemp4,partial=TRUE,method='nsj', data=NULL)
> r2
       Effect   Rsq upper.CL lower.CL
1       Model 0.418    0.563    0.284
4   DivDASqKM 0.210    0.366    0.082
2     MSperDA 0.130    0.278    0.028
3 MEANELEVSMO 0.092    0.232    0.011

r.squaredGLMM(modeltemp4) =0.2168

Answer: I was looking for an explanation for this same mistake that I've also found. In my case, the differences are even greater. I copy down the values of the marginal R2 in case it is useful to find an explanation or identify a problem with one of the functions. In my case, the different functions estimated the values:
MuMIn::r.squaredGLMM = 0.48
r2glmm::r2beta (method='nsj') = 0.04

These two above are supposed to give the same
r2glmm::r2beta (method='sgv') = 0.16
rsq::rsq(adj=F) = 0.08
rsq::rsq(adj=T) = 0.07

My impression is that the function r.squaredGLMM of the MuMin package might have some error.
The authors of the r2glmm package say in the "README" document that the method "sgv" is more stable. (https://cran.r-project.org/web/packages/r2glmm/README.html).
P.S. I'm sorry for not including the code in the example, but I don't know how I could leave the data used accessible for another user to check the veracity of the differences.
Comment: `r2beta` is equivalent to marginal R^2 (`"r2m"` in `r.squaredGLMM` result). Also, `r.squaredGLMM` follows closely the code in Nakagawa et al. 2017 paper while, as much as I can see, `r2beta` does not.


Update , Delete and Edit Table on MS SQL Server with different errors

Question: I have a table called "News-News" that can save my website's news in it.
I add new four columns to this table with "int" and "nvarchar(3999)" data types.
The problem is here: I can change data type's to "nvarchar(50)" and I can save it successfully but when I want to change it to "nvarchar(3999)" again, It returns this error:
'News-News' table- Unable to modify table.  Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

The problem isn't finished yet! I can insert data to this table but I cant delete and Update it.
This is error:
string or binary data would be truncated
The data in row 1 was not committed
.Net SqlClient Data Provider

This is the table full code :
/****** Object:  Table [dbo].[News-News]  ******/

    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Title] [nvarchar](399) NOT NULL,
    [Abstract] [ntext] NULL,
    [Value] [ntext] NULL,
    [UserID] [int] NOT NULL,
    [GroupID] [int] NOT NULL,
    [Date] [nvarchar](3999) NOT NULL,
    [Views] [int] NULL,
    [Hates] [int] NULL,
    [Likes] [int] NULL,
    [Source] [nvarchar](3999) NULL,
 CONSTRAINT [PK_News-News] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Columns of Hates , Likes , Views , and Source are new.
I have this problem on MS SQL Management Studio and my ASP.NET website. Both have same timeout problem.

UPDATE
I have a SqlDataSource called "NewsSqlDataSource" that has three queries for "Insert" , "Update" , and "Delete".
I use NewsSqlDataSource.Insert(); for inserting,  NewsSqlDataSource.Update(); for editing, and NewsSqlDataSource.Delete(); for deleting.
Here I have query codes:

For inserting

INSERT INTO [News-News] (Title, Abstract, Value, UserID, GroupID, Date, Source) VALUES (@title, @Abstract, @Value, @UserID, @GroupID, @Date, @Source)

For Updating

UPDATE [News-News] SET Title = @Title, Abstract = @Abstract, Value = @Value, Date = @Date, GroupID = @GroupID, Source = @Source WHERE (ID = @ID)

For Deleting

DELETE FROM [News-News] WHERE (ID = @ID)
Comment: This question seems a better fit for [DBA StackExchange](http://dba.stackexchange.com/). Consider deleting this question and posting it on that site instead.
Comment: You have a table so you can not create it again! Your code shows you are going to create `News-News` table again.
Comment: That code want's to show you the database columns and data types. I know that it uses in CREATE command of SQL Server. My questions are about errors. * First error of changing table columns in design mode and Second is about Updating and Deleting data in row.
Comment: You didn't show the script you used to alter that table. Please post that.
Answer: You can't insert the data because the data that you're trying to insert is too wide for the column and ANSI_WARNINGS is ON. Given the content of your application, you probably don't want to turn it OFF and let the server silently truncate the data.
The other error that you're getting is probably due to the fact that your table is getting large and the SQL Server is consuming too many resources because it's essentially storing the data in work table and then updating the original table all with temp objects and RAM.
Here's what I'd do.
SELECT
    [ID],
    [Title],
    [Abstract],
    [Value],
    [UserID],
    [GroupID],
    [Date],
    [Views],
    [Hates],
    [Likes],
    [Source]
INTO dbo.[News-News_Newest]
FROM [dbo].[News-News];

DROP TABLE [dbo].[News-News_Newest];
GO

EXEC sp_rename '[News-News_Newest]' , '[News-News]';
GO

ALTER TABLE [News-News]
  ADD CONSTRAINT PK_News_ID PRIMARY KEY CLUSTERED (ID ASC);

Please note that you will need to figure out how to handle any foreign keys if they exist. You'll also need to make sure no writes will occur on this table while you're doing this.
Comment: @MohammadRezaTayyebi I thought I addressed that. You've inserted existing data that met the original requirements. Now you need wider data or ANSI_WARNINGS was originally set to OFF. I'm assuming you're trying to update the existing table with data that is wider than you've defined so you're getting an error. Is this on a new server?
Comment: I can insert data into database but I can't Update and Delete it. I Told it in my question to.
Comment: Let me see. First you send data to new table called "News-News_Newest" and after that you renamed it to "News-News". If I right , this is not fast solution for my problem. Here's another question: Why I cant update data of a specific row in my Table?
Comment: @MohammadRezaTayyebi the speed of the process will depend on your data, your server specs, and other activity on the server. Also, it'll be faster than what you're currently doing: `Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.`
Comment: I think it's better to know that this problem is same between "ASP.NET" and "SQL Server Management Studio (Design time)" and also similar between my server and "(LocalDb)\v11.0"
Comment: So you ***are*** doing this between two database instances.
Comment: No, But I tried this on server and local. [This](http://www.snowcity.ir/News) is the website that uses the database. You can translate it on translate.Google.com
Comment: What do the famous websites (Like yahoo! and twitter) do? I want to change my website to real News Application.
Comment: Considering your answer and comments, I tried many ways to delete data with following code:`DELETE FROM [News-News] WHERE (ID=1)`. This code can execute successfully on MS SQL Server Management Studio but when I use it in asp.net, I have timeout error again.
Answer: I just saw that you used the design mode of SSMS to change the table. This is a mistake and tables should never be altered this way if they have significant amounts of data in them. Personally I feel you shouldn't ever use the designer because the code should be in a script in source control so you can move it to production from dev easily. Alter table is typically much faster than using the designer which loads all the data to a temp table and then makes the change and then loads the database. If you have a lot of data, then you will have a problem with timeouts using the designer.
Comment: Do you want to call this a bug? bug for SQL Server management studio designer?
Comment: No it is not a bug, it is intentional design to prevent you from accidentally losing data. The assumption is that anyone using the designer doesn't know what they are doing and so should be prevented from an accidendtal data loss or is creating a table for a prototype. It is not intended for use by a developer to work with populated tables.  If you are using it for actual development you are doing things incorrectly. All tables should be designed using sql scripts stored in source control like other code.
Comment: Considering your answer and comments, I tried many ways to delete data with following code:`DELETE FROM [News-News] WHERE (ID=1)`. This code can execute successfully on MS SQL Server Management Studio but when I use it in asp.net, I have timeout error again.


How can I fix this error in MATLAB: "Index exceeds matrix dimensions."

Question: I'm tryin to solve two non-linear equations with two unknowns with the Newton-Raphson method in MATLAB.
Here is my matlab code:
f = @(x)[ x(1)^2+x(2)^2;
          2*x(1)-x(2)];
J = @(x)[ 2*x(1), 2*x(2);
          2, -1];
tol = 1e-4; % Or some other tolerance
err = 1000; % Any value larger than tol
x = 0.01; % However this is defined.
iter = 1; max_iter = 30; % Or whatever.
while (err > tol)
    delta_x = J(x)\(-f(x)); % Compute x_{n+1}-x_n
    err = norm(delta_x);
    x = x + delta_x;
    iter = iter + 1;
    [iter x']; % This line simply outputs the current iteration and the solution. You can dress this up by using sprintf if you like.
    if (iter > max_iter)
        disp 'Failed to converge';
        break;
    end
end

Why does MATLAB show "Index exceeds matrix dimensions."?
Comment: Your functions `J` and `f` use `x(2)`, while you call them with a scalar `x`. There *is no* `x(2)`.
Comment: Thanks in advance :)
Answer: You define f and J to receive a vector x with two elements but initialize x as a scalar: x = 0.01;.  Define it as a vector:
x = [0.01;0.01];

Also, for the portion of the code displaying stuff ([iter x'];), I'd suggest a simple working version as
disp(['iter: ',num2str(iter)]);
disp(x.');

How can I fix this error in MATLAB: “Index exceeds matrix dimensions.”


Transaction boundary is not properly set in JpaTransactionManager

Question: Im using JPA with Hibernate implementation and using JpaTransactionManager to mange transactions.
Below is my application context file
<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
    <property name="persistenceXmlLocations">
        <list>
            <value>classpath*:META-INF/persistence.xml</value>
        </list>
    </property>
    <property name="defaultDataSource" ref="dataSource" />
</bean>

<bean id="entityManagerFactory" primary="true"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitManager" ref="persistenceUnitManager" />
    <property name="persistenceUnitName" value="infra_services" />
</bean>

<bean
    class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

<tx:annotation-driven transaction-manager="transactionManager"
    proxy-target-class="true" />

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
    </property>
</bean>

I have defined my service class as below
@Service
@Transactional
public class ComponentService {

I execute queries in dao layer as below
Query q = entityManager.createQuery(
            "SELECT cc.component FROM "
                    + this.typeParameterClass.getSimpleName()
                    + " cc WHERE cc.caseload.id = ? ").setParameter(1,
            caseloadId);

    Collection<Component> ddd =q.getResultList();
    for (Component c : ddd) {
        System.out.println(c.getComponentId());
        System.out.println(c.getComponentRelationships2());
    }
    return ddd;

I  started with select queries.  While executing the line System.out.println(c.getComponentRelationships2()); getting could not initialize proxy - no Session] with root cause exception
Not sure why the session is not available here. Please help me on this.
Comment: Are you sure that you have `` in your xml config file ?
Comment: Are your service in the same context as the one where you define  ?
Comment: Service is not in same context. But I get this exception even in dao layer as soon as I execute the query
Comment: Yes, I have it in my application context file
Answer: If your service is not in the same context as the one where <tx:annotation-driven /> then it's not working. Because it only look for bean in the same context. Extract from spring doc:

@EnableTransactionManagement and  only looks for @Transactional on beans in the same application context they are defined in. This means that, if you put annotation driven configuration in a WebApplicationContext for a DispatcherServlet, it only checks for @Transactional beans in your controllers, and not your services. See Section 21.2, "The DispatcherServlet" for more information.
Comment: Thanks !!!, Also I added  in my applciation context to resolve the issue


Issues while Updating drupa/slack to 8.x-1.2

Question: The site I am working on is using drupal/slack ^1.2 in composer.json file but the module present in the instance and that in composer.lock is the dev version.
I ran a
<code>lando composer require drupal/slack:^1.2
</code>
However, the module is not changing and neither is the composer.lock file.
FYI, The site is running inside lando.
How do I debug this problem?
Additional info
<code>"prefer-stable": true,
</code>
Also the problem only seems to effect the slack module.  The others seem to work fine.
Comment: Your question seems to be "How do I debug composer?" or "Why is composer not working inside of lando?" I think either are off-topic because the former is specific to PHP and the latter is a bug/support request for the lando team. Either way, I would probably include your composer.json and try to replicate without lando.
Comment: Have you tried `lando composer remove drupal/slack` and then `lando composer require drupal/slack` again? Does your composer.json have [`"prefer-stable": true`](https://getcomposer.org/doc/04-schema.md#prefer-stable) configured yes or no?
Comment: Let me try that suggestion
Comment: Nope not working
Comment: Come on, what does >>Nope not working<< mean? What you typed exactly? Any error messages? Any messages at all? What happened? Please update question. Also maybe try `rm -rf composer.lock && rm -rf vendor/` and then `composer install` again. In a local copy of your site of course.
Comment: Oops missed the second part of your question. Let me check that. Also no error messages. This happens only with this module. The others usually update fine.
Comment: prefer-stable is set to true.
Comment: Usually composer print some solutions in order to fix your dependency versions problems. So you just need to read the output of your console and execute it :).
Comment: The problem is affecting the slack module only. The others are working fine. So I think the problem could be related to the drupal slack module.
Answer: I figured out the problem. There was a custom module that had it's own composer.json listing the dev version of slack as a dependency.
This seems to have been overriding the root package version.  I got to know this after removing the drupal slack as suggested here but the module remained on the web directory. So figured that some other package was listing it as a dependency.
Doing a grep led me to the file and updating the version in that composer.json and running lando composer update drupal/slack solved the problem.
Thanks for everyone's help.


Get nth highest salary

Question: I want to write a SQL query to get the nth highest salary from the Employee table.
+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

What have I tried?
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  RETURN (
      # Write your MySQL query statement below.
      SELECT Salary
        FROM Employee
        ORDER BY Salary desc
        Limit N,1
  );
END

Problem:
I want to return row N-1 not N as rows start from 0. I tried to set a variable but it didn't work,
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
SET M=N-1;
  RETURN (
      # Write your MySQL query statement below.
      SELECT Salary
        FROM Employee
        ORDER BY Salary desc
        Limit M,1
  );
END

Comment: If you want to write a query, why are you writing a function?
Comment: @Strawberry: I am practicing on leetcode. Their problem had a function.
Answer: You could just decrement the variable:
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  set n = n - 1;
  RETURN (
      # Write your MySQL query statement below.
      SELECT Salary
        FROM Employee
        ORDER BY Salary desc
        Limit n, 1
  );
END;

if you must use separate var, declare it first:
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  declare m int;
  set m = n - 1;
  RETURN (
      # Write your MySQL query statement below.
      SELECT Salary
        FROM Employee
        ORDER BY Salary desc
        Limit m, 1
  );
END;

Demo
Answer: select DISTINCT salary from employee e1 where 2 = (select count(DISTINCT salary) from employee e2 where e1.salary <= e2.salary);
where 2 = number. You can find any highest salary from employee table. like 3rd then replace 2 with 3.
Answer: This will also take into consideration the scenario where there is a null value or 2 same highest salaries
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
declare m int;
set m = n-1;
  RETURN (SELECT DISTINCT Salary AS getNthHighestSalary
      FROM Employee
      ORDER BY Salary DESC
      LIMIT m, 1

  );
END

Get nth highest salary


PARTITION BY with DISTINCT

Question: I have the following data. I want to partition on ID and only return unique OrgIDs based on Date desc.
For ID 14, Encompass and Premier were chosen in the output based on the Date. For ID 57, Encompass, Example and Premier were chosen because Example would fall under the unique OrgID category.
ID  Num  Dx   Code   Describe   OrgID   Nm1     Name        Type         Date
14  242  438  26994  Fractures  4534    2332    ENCOMPASS   AGENCY       2020-01-01
14  242  438  26994  Fractures  4533    2332    Premier     Hospital     2020-02-01
14  242  438  26994  Fractures  4533    2332    Premier     Hospital     2019-08-08
14  242  438  26994  Fractures  4534    2332    ENCOMPASS   AGENCY       2019-07-09
14  242  438  26994  Fractures  4534    2332    ENCOMPASS   AGENCY       2019-08-07
57  242  438  22699  Nervous    4533    2332    Premier     Hospital     2018-01-12
57  242  438  22699  Nervous    4534    2332    ENCOMPASS   AGENCY       2020-01-09
57  242  438  22699  Nervous    4533    2332    Premier     Hospital     2020-01-01
57  242  438  22699  Nervous    4535    2332    Example     Nurse        2019-11-11
57  242  438  22699  Nervous    4534    2332    ENCOMPASS   AGENCY       2019-06-30

Expected output -
ID  Num  Dx   Code   Describe   OrgID   Nm1     Name        Type         Date
14  242  438  26994  Fractures  4534    2332    ENCOMPASS   AGENCY       2020-01-01
14  242  438  26994  Fractures  4533    2332    Premier     Hospital     2020-02-01
57  242  438  22699  Nervous    4533    2332    Premier     Hospital     2020-01-01
57  242  438  22699  Nervous    4534    2332    ENCOMPASS   AGENCY       2020-01-09
57  242  438  22699  Nervous    4535    2332    Example     Nurse        2019-11-11

Comment: You have two columns named `Num`?
Comment: @JoshuaSchlichting Nope. Fixed that. Sorry.
Answer: It seems like you could use row_number() to get the latest for each id and orgid pair.
SELECT x.id,
       x.num,
       ...
       x.date
       FROM (SELECT t.id,
                    t.num,
                    ...
                    t.date,
                    row_number() OVER (PARTITION BY t.id,
                                                    t.orgid
                                       ORDER BY t.date DESC) rn
                    FROM elbat t) x
       WHERE x.rn = 1;

Answer: In Postgres, I would recommend DISTINCT ON:
select distinct on (id, orgid) t.*
from t
order by id, orgid, date desc;

This is typically faster than the corresponding query using window functions or subqueries.  And is quite speedy with an index on (id, orgid, date desc).

PARTITION BY with DISTINCT


Serving public IP-adresses through two ethernet ports with public subnets, while protecting some interfaces for remote access

Question: Done a lot of research and it's all kind of confusing. Some switches are also firewalls, most firewalls seems to be routers, with or without their own switches, but they're all different depending on the manufacturer. Hence I now ask for advice here!
My problem:
I have two ports that give access to two subnets of public IPs.
What I want is to be able to connect servers to them and run ipfilter as a firewall, but some I would want to block traffic to depending on IP, before delivering packets to the machine that is.
Now, cisco layer 3 switches seems to have this functionality (ACL:s is what they call the firewall functionality right?). I have administered cisco ACL:s before through CLI on cisco pix (long time ago) so I guess it's about the same.
Would I be able to connect such a switch to my two subnet ports so that machines connected to the switch can all steal ip-adresses from any of the subnets?
The network units I don't want exposed directly to the WAN are all remote access controllers, known to be full of security holes. Perhaps it would be better to have a "dumb" switch and then a cheap router in front of these interfaces instead of an advanced switch with firewall functionality?
This is to be a small business network with 2-4 servers, possibly growing just a bit. Any other ideas than what I describe above are welcome!
Comment: can you make a small diagram of the network you plan? I am a bit confused.
Comment: Ethernet port 1&2, subnet x.x.x.x/8 y.y.y.y/8 -> switch and firewall(possibly) -> servers that have access to all the public IPs from the two ports (with remote access devices protected behind a non-software firewall like I have on the servers through ipfilter.)
Comment: I am sorry, I just can not visualize it. I do not understand what you try to do.
Comment: In short, I have two subnets with public ip-adresses from my provider, two ethernet ports and one subnet for each port. I want to split those public IPs to more than two machines. Does that make sense to you?
Comment: ah. ok, I get it now. so your two subnets from the provider comes 1 subnet per port. thanks, I will think about it now.
Answer: so you have two /8 networks from your ISP (one for each of the two ports).
a /8 is a huge network, I wonder why you get such a large address space, but anyway.
if you have two separate ip addresses on two separate ports if you want to setup a firewall and then have some of the same ip seriesd behind the network, then you should split your two subnets in two, so that part of it is outside the firewall, and part of it is inside your firewall. (that is what I would have done at least).
I am a juniper guy, so I would have used something like a SRX100 (provided not much traffic is needed), then setup at least 3 different zones in the network
<code>1. RED1 = x.x.x.x/9
2. RED2 = y.y.y.y/9
3. GREEN = x.x.x.B/9 and also y.y.y.C/9
</code>
Where B and C are the network number after you split from 8 to 9 (use subnet calculator to find what network that is).
that way any server on your GREEN (protected) network could take a network address from either of the two ip series.
Comment: sorry for quick answer, have to run, but can look at this more later if still in need.
Comment: Thanks, I will check the SRX100 out. Haha, I meant /28! But wouldn't a regular switch enable the machines behind it to steal IPs from any of the subnets? Then I would use ipfilter on the machines I need a firewall for.
Comment: /28 does make more sense. there are many ways to trick. but I like to do things this way. that way I have clean networks, and it is easy to make different firewall rules for the different clearly defined networks (and all these rules are made on the srx).


How cond works in Scheme?

Question: (define (list-ref items n)
  (cond ((null? items) "Out of range exception")
        ((= n 0) (car items))
        (list-ref (cdr items) (- n 1))))

(list-ref (list 1 2 3) 6)
5

Why it always return value of (- n 1)? Why it doesn't execute (list-ref (cdr items) (- n 1)) ?
Answer: You forgot an else in the final clause.
Instead, it used list-ref as the condition (which is always truthy, since all procedures are truthy), and evaluated your other two subforms and returned the last one.
Comment: No, `cond` clauses have an implicit `begin`, so more like `(if list-ref (begin (cdr items) (- n 1)))`.
Comment: I understand. But why compiler didn't evaluate `(list-ref (cdr items) (- n 1))`?
Comment: It did. It evaluated `list-ref` as the truthiness condition (which is always true), and the `(cdr items)` and `(- n 1)` as the "then" expressions. The value of the last is returned.
Comment: In Scheme, only `#f` is considered false. Every other value is considered true.
Comment: Ok, if value of `list-ref` is true, why it didn't return value of `(cdr items)`?

As I understand it transforms to `(if(list-ref) then
                                                       (cdr items)
                                                       otherwise (- n 1))`
Comment: Thanks you very much!

How cond works in Scheme?


How do I "scanf()" and "printf()" a user's message in discord.js when creating a BOT for Discord server?

Question: I am new at coding and I only have the basic knowledge of C but I do know how other codes work if I know the functions its equivalent in C. I am using discord.js (12.0.2) to make my Discord bot. How do I scan and print a user's sent message?
Answer: To 'scan' a user's message, use the content property of their message. I barely know C but I'm pretty sure the equivalent of printf is console.log:
const {Client} = require('discord.js')

const client = new Client()

client.on('message', message => {
  console.log(message.content)
}

client.login(yourToken)

I recommend reading the Discord.js guide.


What is a easiest way to implement Mail Server in ubuntu and hook in webmail through XAMPP?

Question: I currently have xampp running on my ubuntu server. I tried a variety of things including installing, postfix+dovecot+roundcube+postfixadmin (postfix+dovecot work I think, postfix admin also works, roundcube works and connects to dovecot but i cant create user accounts, or figure out how that works), citadel (it installed, but I have no idea how to make it work with xampp for webmail) and i tried messing with exim and vexim a bit also. In short I feel like this should be a lot easier, and I can't figure it out haha.
XAMPP works fine. I got my server running with everything. I was thinking about mercury mail, but I need a webmail solution also. I was thinking about google apps, but 50 bucks a year per user is a steep change from free.
Thanks for the help!
Answer: I didn't even know there was a XAMPP release for Linux. You see, an ubuntu LAMP server nowadays can get installed out of the box without touching a .conf file.
For the mail server stack, by far the best resource i am aware of on the internet is
http://johnny.chadda.se/2007/04/15/mail-server-howto-postfix-and-dovecot-with-mysql-and-tlsssl-postgrey-and-dspam/
I have followed the aforementioned howto and then installed horde3 for webmail 3 times already in two different data-centers
Answer: Old topic, but lately, I realized (at least for sending mail) using sendmail is a pretty good solution. I also use gmail for actually email accounts. This seems to work nicely.


Is n! mod p doable in sub $O(n)$ time?

Question: I ask because I can use Lucas Theorem to find ${n \choose k} \mod p$ but don't know of an equivalent for permutations ($n$ permute $k \mod p$).
Comment: For fixed $p$?  $n! \equiv 0 \mod p$ if $n \ge p$.
Comment: Sounds like what you want is actually $n(n-1)(n-2)\dotsm(n-k+1) \pmod{p}$. Is that right?
Comment: well i know how to get combinations quickly and i know the only difference between combinations and permutations is a denominator factor of k!
Comment: But working mod $p$ you should be careful, because this denominator might be zero (mod $p$). The expression I wrote it what you want then. Still, if $k\geq p$ it will be zero.
Comment: Yeah, but you can't divide by $k!$ in general, $\pmod p$, if $k\geq p$.  For example, in general, $\binom {2p}p\equiv 2 \pmod p$. If you instead compute $(2p)!\equiv 0\pmod p$ and $p!\equiv 0\pmod p$ how are you going to compute $$\frac{(2p)!}{p!p!}$$ mod $p$?
Comment: I mean this may be an XY question or whatever. I just want n choose k mod p in fast execution. I just thought the factorial difference was what i needed. http://mywiki.wooledge.org/XyProblem
Comment: How big is $n$? How big in $p$? How big in $k$? (approximately)
Comment: arbitrary. i am writing a function
Comment: i also know about the zero condition but i am mainly concerned about nontrivial case k < p
Comment: I that case, I think you should measure your time complexity as a function of $p$. This will help people here understand what you need. I'll think about it.
Comment: technically time complexity of min(n,p) i think, right?
Comment: It also looks like there is an assumption that multiplication is constant.  Are you guaranteed that the numbers are machine words (ie. processor bus/register sized?).  If not, you need to count digits as well, and multiplication is O(n^2) naive or better if fast fourier multiplication and related are used.  Naively, you're actually looking at O(n^2 k) - in other words, your O(n) is wrong as there are O(k) multiplies here, but n is a factor if you aren't looking at machine words.
Comment: Well i can solve it iteratively by multiplying by n-k+1 all the way up modulo p every step. rationale: (n!/((n-k)!)) /(n!/((n-(k-1))!)) = n-k+1
Answer: If $k\geq p$ then the answer is zero and we're done. Otherwise:
Let $M=\lfloor \sqrt{k}\rfloor$.

Define a polynomial: $f(x)=x(x+1)\dotsm (x+M-1)$.
There is a divide and conquer algorithm to evaluate $f(x)$ simultaneously at $M$ points (see Modern Computer Algebra / Joachim von zur Gathen, Jürgen Gerhard).
We will evaluate it at $n-k+1, n-k+1+M,n-k+1+2M,\dotsc,n-k+1+(M-1)M$.
We will get the values of $f(n-k+1), f(n-k+1+M),f(n-k+1+2M),\dotsc,f(n-k+1+(M-1)M)$.
Now just multiply all of those values to get
$f(n-k+1)\cdot f(n-k+1+M) \cdot f(n-k+1+2M)\dotsm f(n-k+1+(M-1)M)$.
If $\sqrt{k}$ is an integer then we're done. Otherwise, we need up to $M$ more multiplications.

The complexity is about $O(\sqrt{p})$ times some logarithmic factors, so it beats the $O(p)$ naive solution.
(the botteleck with the logarithmic factors is in Step 3).
Comment: All numbers should be taken $\pmod{p}$.
Comment: forgive my ignorance but explain p(x) please?
Comment: You want to multiply $k$ numbers. So I divide them to $\sqrt{k}$ groups of $\sqrt{k}$ numbers. The polynomial $p(x)$ is used to evaluate the proudct of $k$ consecutive integers. That's one such block. Step 4 then calculates the product of each such block and step 5 multiplies the products of the blocks to get to product of all $k$ numbers.
Comment: First, I think there is an error in your definition of $p(x) -$ an extra factor of $x$ seems to have snuck in there. Second, in your comment, I think "$k$ consecutive integers" should be "$M$ consecutive integers". Is that right?
Comment: @TonyK: You are right. Edited the post. I can't edited the comment, but it really should be "$M$ consecutive integers". Thanks.
Comment: You might want to choose some other symbol than $p$ for the polynomial, since it's already used to denote the modulus. Yes, it's evident from context which is meant, but still...
Comment: @IlmariKaronen: Agreed. Edited and changed.

Is n! mod p doable in sub $O(n)$ time?


How to Hide Sender IP Address in Email Headers?

Question: I'm using PHPMailer and Postfix in my web server and hosting an application that will often send emails out, like: password recovery, user registration, new orders, orders update, etc..
With PHPMailer Is possible to set a value to Message ID, but not for SPF, since SPF values must be set with the DNS, my DNS settings refer to the proxy server and not to the web server, also I do not want to setup the MailServer with the proxy server, since it is not a good practice.
Then, my last resort is Postfix, should be an option/set in there to help me hide or spoof the real IP address of my web server. any ideas?
I have so far edited the file /etc/postfix/main.cf but without any success, also I read part of the documentation --> http://www.postfix.org/postconf.5.html#smtpd_recipient_restrictions but nothing seems to help me hide the real IP address.
If it is not possible, I will deploy a new mailserver to do the job.
I'm having problem with ddos, that's why I do not want to expose my web server IP anymore, since it is behind a proxy server the whole idea is not to expose it in anyway, but the attacker can easily discover my web server IP address just receiving an email from the server (take a look at the prt sc attached - the parts with blur contains the IP and Domain Name).
Answer: Hiding those headers won't do anything to protect your system from DDOS attacks. After all, it's  a web server and to do this job, it needs to be accessible from the outside and it's IP address known, and thus is susceptible to these kind of attacks. It appears from your post that you have no real idea what you are talking about anyway.
Nevertheless, you can do this easily with Postfix anyway:
In /etc/postfix/main.cf put something like this:
smtp_header_checks = regexp:/etc/postfix/header_checks

with /etc/postfix/header_checks having the following content:
/^Received:.*with ESMTPSA/      IGNORE
/^X-Originating-IP:/            IGNORE

and don't forget to reload postfix.
This will remove all Received: lines from your own mail systems, but the first external mail server will put in the address of your mail server and there is nothing you can do about that.
Comment: If your volume is low you can use sparkpost for free
Comment: Sorry, but if you try to hide headers in order to get your SPF check passing, this is just complete nonsense. Really, stop what you are doing and use a hosted mail service. Those are cheap and usually reliable.
Comment: I know there is other points to take into consideration when the subject is ddos, but right now i'm only interested in solve the mail's problem, one step at a time. Well, I'm only interested in hide/spoof the real ip of the web server, but it seems not possible. I just tried the `smtp_header_checks` in my postfix config and it returns the same result. `spf=fail (google.com: domain of firstname.lastname@example.com does not designate IP XX.XX.XXX.XXX as permitted sender)`. And yes, I have no clue about mail servers, that's why I'm asking a question here. Thanks for your input.
Comment: Thanks anyway. I was considering Mailgun or Sendgrid, but my volume is ridiculously low, no point to use a mail service. BTW it was good to know it is not possible, I did learn a new thing today here, thank you for your time.


Theorem 3.43 from baby Rudin

Question: Theorem. Suppose
(a) $|c_1|\geqslant |c_2|\geqslant |c_3|\geqslant \dots;$
(b) $c_{2m-1}\geqslant 0, c_{2m}\leqslant 0,$
(c) $\lim c_n=0$
Then $\sum c_n$ converges.
Is it crucial that sequence $|c_n|$ is decreasing? What will happen if $|c_n|$ is increasing?
Comment: This is called Leibniz's rule. Is the series $1 - 2 + 3 - 4 + \cdots$ converging?
Comment: Not. I wrote my opinion about this below. You can check my post.
Comment: If $|c_n|$ is encreasing, then $c_n$ does not converge to $0$ as $n\to \infty$. Therefore, $\sum_{n=1}^k c_n$ does not converge to any real number as $k\to\infty$.
Answer: Well it's Rudin, so my inclination is to say that there's not a single unnecessary punctuation mark in the book.
Here's what we'll do.  I remember like one divergent sequence ever, namely $\{ \frac{1}{n} \}$.  So let's try to build that.
I sort of want to let the odd factors just be that.  So let's take $c_{2n - 1} = \frac{1}{n} $, since they're supposed to be positive.  But that's not quite good enough, because I need to subtract something too.  So let's add a little something at the end and make it
$c_{2n -1} = \frac{1}{n} + \frac{1}{2n} $.
Now let's take $c_{2n} = -\frac{1}{2n}$, all of this for $n = 1, 2, \dots$.
Now the sequence $c_n \to 0$ and we have the alternating condition, but the sequence $\{|c_n|\}$ is not decreasing.
However, it's clear that $\sum c_n $ does not converge.
Comment: What is your example shows? Why this series does not converge?
Comment: Because the sum of the first 2n - 1 terms is just $\sum_{k=1}^n \frac{1}{k}$, which diverges as $n \to \infty$
Comment: Thanks! Your example is great!

Theorem 3.43 from baby Rudin


How to catch AJAX abort in jQuery?

Question: I have the following code which detect any error regarding ajax, I need specifically to get "abort" error for ajax.
How to do it?
$(document).bind("ajaxError", function (e, jqXHR, ajaxSettings, thrownError) {

});

I'm not sure if if (thrownError == "abort") is the correct approach.
Answer: Yes you are atmost there see this one
$(function() {
    $.ajaxSetup({
        error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                alert('Not connect.n Verify Network.');
            } else if (jqXHR.status == 404) {
                alert('Requested page not found. [404]');
            } else if (jqXHR.status == 500) {
                alert('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
                alert('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
                alert('Time out error.');
            } else if (exception === 'abort') {
                alert('Ajax request aborted.');
            } else {
                alert('Uncaught Error.n' + jqXHR.responseText);
            }
        }
    });
});

For your Reference http://www.sitepoint.com/jquery-ajax-error-handling-function/
Hope it may helps :)

How to catch AJAX abort in jQuery?


limit problems, rules! and squeeze theorem question

Question: in exercise i-iii evalute the limit or explain why it does not exist
i) $\displaystyle \lim_{y\to 1}\frac{4-4\sqrt{y}+3}{y^2-1}$
ii) $\displaystyle lim_{x\to 0}\frac{\sqrt{2+x^2}-\sqrt{2-x^2}}{x^2}$
iii) $\displaystyle lim_{x\to 2}\frac{x^4-16}{x^3-8}$
iv) if $\lim_{x\to 2} \frac{f(x)-5}{x-2} = 3,$ find $\lim_{x\to 2}f(x)$
v) suppose $|f(x)| \le g(x)$ for all $x.$ What can you conclude about $\lim_{x\to a} f(x)$ if $\lim_{x\to a} g(x)=0?$ What if $\lim_{x\to a} g(x)= 3?$
any tips/advice/solutions? :d I guess its kinda much to ask but I would rather ask it as one question instead of making a lot, since I dont have any idea how to solve any of these problems:( and for the evaluation of the limit part, question, i, ii, iii I have big trouble with the algebra, and for iii) im pretty much 100% clueless, basically no idea on iv) and v) other than that I know the basics like limit rules and obviously the squeeze theorem aswell, but im not sure how to apply this to these "more complicated" problems. Will be more than grateful with just help on the limit problems!
Comment: Is it $1$ correctly written?
Comment: I mean.. all of them are correctly written and the answer to the first one should be -1/2
Comment: If it well written it doesn't exist. When $y\to 1$ the numerator goes to $3$ and the denominator goes to $0.$
Comment: yupp.. that was exactly what I tought, hence why I ask the question here:P the solution however says its -1/2 so idk, I have never ever encountered any wrong solution in this book.. so I think I need to simplify it, idk how tho
Answer: Hints
For the second limit multiply and divide by $\sqrt{2+x^2}+\sqrt{2-x^2}.$ Next, use the identity $(a+b)(a-b)=a^2-b^2.$ That is:
$$\displaystyle lim_{x\to 0}\frac{\sqrt{2+x^2}-\sqrt{2-x^2}}{x^2}=\displaystyle lim_{x\to 0}\frac{(\sqrt{2+x^2}-\sqrt{2-x^2})(\sqrt{2+x^2}+\sqrt{2-x^2})}{x^2(\sqrt{2+x^2}+\sqrt{2-x^2})}$$ $$=\lim_{x\to 0}{2x^2}{x^2(\sqrt{2+x^2}+\sqrt{2-x^2})}=\lim_{x\to 0}\frac{2}{\sqrt{2+x^2}+\sqrt{2-x^2}}$$ $$=\frac{2}{\sqrt{2+0}+\sqrt{2-0}}=\frac{2}{2\sqrt{2}}=\frac{1}{\sqrt{2}}.$$
For the third limit factor $x^4-16=(x-2)(x+2)(x^2+4)$ and $x^3-8=(x-2)(x^2+2x+4)$ and simplify.
For the fourth limit, since it exists and the denominator goes to $0$ the same must happen to the numerator.
In the last case use that if $f(x)\le g(x)$ then $\lim_{x\to a}f(x)\le \lim_{x\to a}g(x).$
Comment: well for the second problem the thing that is confusing me is how to multiply that thing with the numerator using (a+b)(a-b)=a^2 -b^2, do I consider the whole thing root(2+x^2) as a? like what do I get in the numerator, I guess is the question
Comment: I have edited the answer to write the complete solution of this case.
Comment: ahh yeah, I see, thanks a lot! but how did you factor x^4 -16 and x^3 - 8? in the third question?
Comment: Use Ruffini's rule http://en.wikipedia.org/wiki/Ruffini%27s_rule to divide by $x-2.$ Note that these are the problematic factors to be simplified since they vanish at $x=2.$
Comment: ahh ok so its just polynominal division or whatever its called by x-2 since its one of the roots?
Comment: iv) lim x->2 of f(x)=5 then? so the numerator also become 0?
Comment: Yes. In other case the limit doesn't exists or it is $\pm\infty.$
Comment: If both numerator and denominator are $0$ then the limit can exists. Think of $\lim_{x\to 0}\frac{x}{x}=1$ or cases $2$ and $3.$


how to display a media description in a twig template?

Question: i want to display the media description available in the file field of a media ( media of type video, audio, image, etc...), it is an option to activate:

Enable Description field
The description field allows users to enter a description about the uploaded file.

i already print other fields that i want in the media twig template, but i can not find the value of that "description" field attribute, because it's not a field, but some sort of attribute of the file field.
Answer: I got the media description in the preprocess
<code>function template_preprocess_media(array &$variables) {

  $bundle = $media->Bundle();

  if($bundle == 'file') {
    $field_media_file = $variables['content']["field_media_file"];

    if($field_media_file[0]["#description"]){
      $desc = $field_media_file[0]["#description"];
    } else{
      $desc = $variables['name'];
    }
    $variables['description'] = $desc;
  }
}
</code>


Cannot get my while statement to work properly

Question: The error in this program is the while statement in the main method. It was working before in the sense that when I invalid input value it would stop and exit program and when I input proper value it would loop through the while statement once but suddenly after more work too my code it loops infinity for any input below 1025. Ignore the sloppiness of the output of the program as I am still editing that, the main problem is why it does not stop looping in the while statement.
import java.util.Scanner;

public class DNS
{
    public static void main(String[] args)
    {
        int y;
        Scanner input = new Scanner( System.in);

        System.out.println("java DisplayNumberSystems");
        System.out.println("Enter a decimal value to display to: ");
        y = input.nextInt();

        while(y !=1025)
        {

            for(int x=0; x <=y; x++)
            {
                System.out.println("Decimal");
                System.out.println(x);
            }

            for(int i=0; i <=y; i++)
            {
                System.out.println("");
                System.out.println("Binary");
                convertToBinary(i);
            }

            System.out.println("");

            for(int z=0; z <=y; z++)
            {
                System.out.println("Hex");
                convertToHex(z);
            }

            System.out.println("");

            for(int d=0; d <=y; d++)
            {
                System.out.println("Octal");
                convertToOctal(d);
                System.out.println("");
            }

        }
    }

    public static void convertToBinary(int x)
    {

        if(x >0)
        {

            convertToBinary(x/2);
            System.out.printf(x%2 + "");

        }

    }

    public static void convertToOctal(int x)
    {
        int rem;

        while(x >0)
        {
            rem = x%8;
            System.out.printf("%d", rem);
            x=x/8;
        }
    }

    public static void convertToHex(int x)
    {
        int rem;

        while(x >0)
        {

        rem = x%16;
            switch(rem)
            {
                case 1:
                    System.out.printf("1");
                    break;

                case 2:
                    System.out.printf("2");
                    break;

                case 3:
                    System.out.printf("3");
                    break;

                case 4:
                    System.out.printf("4");
                    break;

                case 5:
                    System.out.printf("5");
                    break;

                case 6:
                    System.out.printf("6");
                    break;

                case 7:
                    System.out.printf("7");
                    break;

                case 8:
                    System.out.printf("8");
                    break;

                case 9:
                    System.out.printf("9");
                    break;

                case 10:
                    System.out.printf("A");
                    break;
                case 11:
                    System.out.printf("B");
                    break;

                case 12:
                    System.out.printf("C");
                    break;

                case 13:
                    System.out.printf("D");
                    break;

                case 14:
                    System.out.printf("E");
                    break;

                case 15:
                    System.out.printf("F");
                    break;
            }
            x=x/16;
        }
        System.out.println("");

    }

}

Comment: Holy cow code repetition
Answer: Why do you need a while loop if you are going to execute it only once ? Consider if instead.
Never mind, how about breaking the while loop ?
You can use break; wherever applicable, to stop execution of a loop.
For example :
while (y != 1025) {

    for (int x = 0; x <= y; x++) {
        System.out.println("Decimal");
        System.out.println(x);
    }

    for (int i = 0; i <= y; i++) {
        System.out.println("");
        System.out.println("Binary");
        convertToBinary(i);
    }

    System.out.println("");

    for (int z = 0; z <= y; z++) {
        System.out.println("Hex");
        convertToHex(z);
    }

    System.out.println("");

    for (int d = 0; d <= y; d++) {
        System.out.println("Octal");
        convertToOctal(d);
        System.out.println("");
    }
    break;
}

Answer: You did not increment y's value anywhere inside the while.
So, for a value of y below 1025, say 100.y is always 100 and every time while checks the condition y!= 1025 is true.So, please put a increment y = y + 1 or anything and it will do.
Comment: i cant increment y because it is what my for functions within it count to. i also changed it to <= instead of != and it still loops.
Answer: while(y !=1025)

In this line Your loop work while y is lower than 1025 and higher than 1025.
Also You didn't change y value.
Comment: i changed it now from != to <=. my y is suppost to stay the same and my for function would stop after reaching y. the problem is that they just restart after reaching the y value.
Answer: It will always loop, just as the people above have said. Unless y changes, it will always, always be not equal to 1025 unless it's original value is 1025.
What exactly are you trying to achieve? Should you be including  y = input.nextInt(); inside the loop so that the loop will break if the condition becomes true?
Answer: If you add a break at the end of the while loop, it effectively makes the while loop redundant. It will loop once then exit. If you only want to run the loop for a value other than 1025, you should use an if then statement...
Answer: The reason that your while loop is running infinity times is because you're not updating (perhaps increment) the value of y. You may want to add something like the following statement inside your loop:
y++;

That will increment the value of y by 1 at every loop iteration


Getting sales values by day in CakePHP and MySQL

Question: I have a sales model, with a salesitems related model, the sales model has some modifiers, ie discount.
To get sales totals, I have done this:
var $virtualFields = array(
  'total' => '@vad:=(SELECT COALESCE(SUM(price*quantity), 0) FROM saleitems WHERE saleitems.sale_id = Sale.id)',
  'paid' => '@pad:=(SELECT COALESCE(SUM(amount), 0) FROM payments WHERE payments.sale_id = Sale.id)',
  'discountamount' => '@dis:=(SELECT COALESCE(SUM(price*quantity), 0) FROM saleitems WHERE saleitems.sale_id = Sale.id)*(0.01 * Sale.discount)',
  'saleamount' => '@vad - @dis',
);

Which all seems to be working well. However, when I come to do some reporting, and try to get total sales amount per day, I have run up against the limit of brain power. Should I just tot them up in PHP, or run a query? Or is there a way to do this with Cake's ORM?
I tried the query method:
SELECT
created,
(@vad:=(SELECT COALESCE(SUM(price*quantity), 0) FROM saleitems WHERE `saleitems`.`sale_id` = `Sale`.`id`)) AS `Sale__total`,
(@pad:=(SELECT COALESCE(SUM(amount), 0) FROM payments WHERE `payments`.`sale_id` = `Sale`.`id`)) AS `Sale__paid`,
(@dis:=(SELECT COALESCE(SUM(price*quantity), 0) FROM saleitems WHERE `saleitems`.`sale_id` = `Sale`.`id`)*(0.01 * `Sale`.`discount`)) AS `Sale__discountamount`,
sum(@vad - @dis) AS `Sale__saleamount`
FROM `sales` AS `Sale` WHERE `Sale`.`account_id` = 37 GROUP BY DAY(`Sale`.`created`) order by created

But this is giving me completely incorrect answers.
Answer: you can run this query:
SELECT SUM((si.price * si.quantity) * (1 - (0.01 * s.discount))) AS SalesByDay
FROM sales s JOIN saleitems si ON s.id = si.sale_id
WHERE s.account_id = 37
GROUP BY DATE(s.created)

Notes:

The DAY function, returnes the day of the month, not the date
I did not join the payments table since i do not see where you use the @pad variable


Is there already pre-existing code for supporting Dojo AMD, NodeJS require and Browser window.[something] for a Javascript micro library

Question: I have some code which supports writing a micro-library and having it loaded in Dojo AMD, NodeJS require() and the browsers normal window.[something]... But I was wondering if there are already established means of doing this and I just re-invented the wheel or if the code is worth while. I did do a good search around the internet.
The code I created is at https://gist.github.com/forbesmyester/5293746, if people have comments, great, but I am much more interested in finding out if there is a proper method of doing this.
Comment: You might also consider asking JSMentors https://groups.google.com/forum/?fromgroups#!forum/jsmentors
Comment: Hi psema4, I Followed your link and posted and posted. The URL for the post is https://groups.google.com/forum/?fromgroups#!topic/jsmentors/VRX30sCrgsM
Answer: I followed the link psema4 added and with some reading around found this github project which attempts to collate all the different approaches people have used to solve this problem into a set of boilerplate files.
I'm sure that Forbesmyester has already found this solution, but I thought it ought to be put up on SO for anyone who finds this question in future.


angular-ui-router share states

Question: So I have a few states set up like this:
<code>$stateProvider.state('accounts', {
    url: "/accounts",
    templateUrl: 'tpl/accounts/index.html',
}).state('accounts.view', {
    url: "/{accountNumber:[A-Z]{3}[0-9]{3,7}}",
    views: {
        '@': {
            templateUrl: 'tpl/accounts/view.html',
            controller: 'AccountController',
            controllerAs: 'controller'
        }
    },
    resolve: {
        account: ['$stateParams', 'AccountService', function ($stateParams, accountService) {
            return accountService.get($stateParams.accountNumber);
        }]
    }
}).state('accounts.create', {
    url: '/create',
    views: {
        '@': {
            templateUrl: 'tpl/accounts/save.html',
            controller: 'AccountSaveController',
            controllerAs: 'controller'
        }
    },
    params: {
        account: null
    },
    resolve: {
        account: ['$stateParams', 'AccountProvider', function ($stateParams, provider) {
            return $stateParams.account || provider.newAccount();
        }]
    }
}).state('accounts.view.edit', {
    url: '/edit',
    views: {
        '@': {
            templateUrl: 'tpl/accounts/save.html',
            controller: 'AccountSaveController',
            controllerAs: 'controller'
        }
    }
})
</code>
and it all works fine.
Now I have the need to create some child states for both create and edit. They will use the same view and controllers, but I was wondering if I can use the same state.
For example, I will be setting up an address state which will look something like this:
<code>.state('accounts.view.edit.address', {
    url: '/address',
    views: {
        '@': {
            templateUrl: 'tpl/accounts/save/address.html',
            controller: 'AccountAddressSaveController',
            controllerAs: 'controller'
        }
    }
})
</code>
and I will set another up for the create state like this:
<code>.state('accounts.create.address', {
    url: '/address',
    views: {
        '@': {
            templateUrl: 'tpl/accounts/save/address.html',
            controller: 'AccountAddressSaveController',
            controllerAs: 'controller'
        }
    }
})
</code>
It isn't an issue to do this for one child state, but there are 4 others and I just thought i would ask if there is a way to share the states, like perhaps:
<code>.state(['accounts.create.address','accounts.view.edit.address'], {
    url: '/address',
    views: {
        '@': {
            templateUrl: 'tpl/accounts/save/address.html',
            controller: 'AccountAddressSaveController',
            controllerAs: 'controller'
        }
    }
})
</code>
Answer: You may put your state config in a variable
<code>var sharedState = {
    url: '/address',
    views: {
        '@': {
            templateUrl: 'tpl/accounts/save/address.html',
            controller: 'AccountAddressSaveController',
            controllerAs: 'controller'
        }
    }
}
</code>
and then simply do,
<code>.state('accounts.create.address', sharedState)
.state('accounts.view.edit.address', sharedState)
</code>
Comment: I would make a shallow copy for each one using `angular.extend({}, sharedState)` or `Object.assign({}, sharedState)`

angular-ui-router share states


$\text{rk}(AB)=\text{rk}(BA)$ generally

Question: I would like to generalize the group of matrices of order $n\times n$, $A,B$ such that
$\text{rk}(AB)=\text{rk}(BA)$.
I'm pretty sure that if $AB$ and $BA$ are nonzero, the condition will hold.
(clearly if $AB=0$ or $BA=0$ we can find counter-examples).
I was thinking for some time and couldn't find any proof at all.
I would like to get your help! Thanks!
Note: This wasn't asked here before! others have asked for counter-example
for general $\text{rk}(AB)=\text{rk}(BA)$, but I added a condition.
Comment: Counterexample: $A(x, y, z) = (y, 0, z)$ and $B(x, y, z) = (0, y, z)$. Then $AB(x, y, z) = (y, 0, z)$ but $BA(x, y, z) = (0, 0, z)$.
Answer: Let's try and find two $3\times3$ matrices $A$ and $B$ such that the rank of $AB$ is $1$ and the rank of $BA$ is $2$:
$$
A=\begin{bmatrix}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & 0
\end{bmatrix}
\qquad
B=\begin{bmatrix}
1 & 0 & 0 \\
0 & 0 & 0 \\
0 & 1 & 0
\end{bmatrix}
$$
Then
$$
AB=\begin{bmatrix} 1 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{bmatrix}
\qquad
BA=\begin{bmatrix} 1 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 1 & 0 \end{bmatrix}
$$
Answer: Your additional condition does not any anything substantial to the issue. Suppose you have an example that $AB=0\ne BA$. Then
$$
\pmatrix{A\\ &1}\pmatrix{B\\ &1}=\pmatrix{0\\ &1}
$$
is a nonzero matrix of rank 1 but
$$
\pmatrix{B\\ &1}\pmatrix{A\\ &1}=\pmatrix{BA\\ &1}
$$
is a nonzero matrix of rank $\ge2$.

$\text{rk}(AB)=\text{rk}(BA)$ generally


How can we tell if a matrix is diagonalizabel based on its characteristic polynomial?

Question: True or false and explain why?: a matrix with characteristic polynomial $\lambda^3 -3\lambda^2+2\lambda$ must be diagonalizable.
First I found the lambda's that make this zero (eigenvalues) and got $0, 1, 2$ but I don't know if having $0$ as an eigenvalue means that the matrix is not diagonalizable? I know that a matrix has $0$ as an eigenvalue if it is not invertible, but I don't know if a matrix needs to be invertible to be diagonalizable? Also if a matrix has complex eigenvalues does that also mean it cannot be diagonalizable?
Comment: Is the matrix with all entries equal to $0$ diagonalisable?
Comment: The question in your title ("If zero is an eigenvalue...") and in the question body (the characteristic polynomial is $\lambda(\lambda - 1)(\lambda - 2)$") do not match (in the strong sense that the answers differ). Could you please fix this?
Comment: You might try recalculating those eigenvalues since one of them is incorrect.
Comment: @NigelOvermars The definition for a diagonal matrix is "all non diagnoal entries are zero" so I guess the zero matrix is considered diagonal.
Comment: I understand now, a matrix is diagonalizable iff the algebraic multiplicity = the geometric multiplicity for each eigenvalue.
Comment: If all eigenvalues are distinct, then it is diagonalizable.
If not all eigenvalues are distinct, then the characteristic polynomial is not sufficient to tell whether or not it is diagonalizable.
Answer: The characteristic polynomial splits as follows $P_M(\lambda)=\lambda(\lambda-1)(\lambda-2)$. The matrix is $3\times 3$ (the degree of the characteristic polynomial) and has three distinct eigenvalues therefore it is diagonalisable.
Comment: @marwalix I am not sure that the author of the question is aware of that, since (it seems to me that) he knows that there are three different eigenvalues (although he claims these are $0$, $2$, $3$), but he is not able to draw your conclusion. Also, I would say that there are things that are much easier to prove.
Comment: That is based on the assumption that eigenvectors that belong to different eigenvalues are linearly independent?
Comment: @Antoine That's not an assumption, it is an easy proof.
Comment: You have a double implication if you use the minimal polynomial instead of characteristic polynomial: a square matrix is diagonalizable if and only if its minimal polynomial factors into DISTINCT LINEAR factors.
Comment: @Antoine I understand marwalix's answer
Answer: Edit (better wording)
$0$ as an eigenvalue doesn't hinder the diagonalization, actually there is no eigenvalue that would hinder it.
That doesn't mean that every matrix is diagonalizable, but that the eigenvalues have no influence, at least in $\mathbb{C}$.
Let A be a complex $n\times n$ matrix with $A=diag(\lambda_1,...,\lambda_n)$, it is always diagonalizable, no matter what eigenvalues.

If a pure imaginary eigenvalue $\lambda \in \mathbb{C}\setminus\mathbb R$ belongs to a real matrix $A \in \mathbb{R}^{n\times n}$ you have a problem, since you can't diagonalize nor triangularize it in $\mathbb R$.
Comment: @idknuttin No, the algebraic and geometric multiplicity has to be equal for all eigenvalues.
Comment: So does that mean every matrix is diagonaliable?


Can there be a situation where one regression model gives lower RMSE than the other but also lower R-squared?

Question: Consider the following scenario where you use the same data X (the same number of predictors p, same number of observations n) to predict a continuous outcome y, in 2 different regression models (e.g. Linear Regression and Random Forests).
For both models you calculate RMSE and R-squared (assume simple correlation between y and y-hat, squared).
You get:
RMSE1 < RMSE2

R-squared1 < R-squared2

Could someone explain if this scenario is possible and how it occurs?
A simple simulation in R could also do.
Answer: This may arise if the regression model is nonlinear. Consider the following true data
0.6
0.55
0.3
0.24
0.22

With model 1 predicting
0.82
0.72
0.55
0.29
0.1

and model 2
0.7
0.58
0.51
0.2
0.09

$R^2$ for Model 1 is 0.8448 while for Model 2 is 0.7866.
However, Model 1 has higher RMS error, at 0.1770 but Model 2 only has RMSE of 0.1212
This happens because $R^2$ is only really valid for linear regression models (and data).


How to set datatime column?

Question: I have some datatime columns on my dataframe. One of them appear with the object type and the other appear as datatype. How to pass tho object type one as datatype also ?
enter image description here
enter image description here
Thank you in advance !
Comment: `DL_2.DATE_ENTREE_ = pd.to_datetime(DL_2.DATE_ENTREE_)`?
Comment: It gives me this error message:
OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1013-08-20 00:00:00
Comment: And `DL_2.DATE_ENTREE_ = DL_2.DATE_ENTREE_.astype('datetime64')`?
Comment: It gives me the same error message than before.
Comment: Last chance :) `DL_2.DATE_ENTREE_ = pd.DatetimeIndex(DL_2.DATE_ENTREE.to_numpy())`
Comment: What does it mean `"1013-08-20 00:00:00"`??? Typo?
Comment: Same error. It's ```datetime.datetime(2014, 5, 14, 0, 0)```
Comment: Please provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example)
Answer: According your comments, it seems you have some bad dates.
Use pd.to_datetime with errors='coerce'
DL_2.DATE_ENTREE_ = pd.to_datetime(DL_2.DATE_ENTREE_, errors='coerce')

To find bad dates:
DL_2.loc[pd.to_datetime(DL_2.DATE_ENTREE_, errors='coerce').isna(), 'DATE_ENTREE_']

How to set datatime column?


Ler uma pagina da internet em uma variavel em VB

Question: Gente eu estou tentando ler uma  página da internet e não estou conseguindo, quero que salve todo o conteúdo em uma variavel, o problema é que ela não tem nada de html nem xml, é somente texto, alguem saberia como fazer isso e tambem como procurar um texto nela?
Comment: Essa pagina seria um [JSON](http://www.json.org/json-pt.html)   certo ? Você teria que procurar como serializar um Json com `vb.net`
Comment: como eu poderia fazer isso?
Comment: Alguma das respostas lhe foi útil?
Answer: Para serializar um Json em Vb.Net  DataContractAttribute.
Primeiro você teria que criar um objeto para receber esse JSON, percebe que o seu exemplo pussui objetos dentro do proprios Json, exemplo:
"atividades_secundarias": [
    {
      "text": "Reprodução de vídeo em qualquer suporte",
      "code": "18.30-0-02"
    },

Neste caso é um objeto chamado atividades_secundarias com dois atributos text e code. Que alias e uma Array
Para Serializar você pode fazer :

1.Você irá criar um método que receberá esse JSON e fara a deserialização

' VB.NET
Private Function DeserializarDataContractJsonSerializer() As List(Of SeuObjeto)
    Using Stream = New System.IO.FileStream(JsonQueVocêPassa, System.IO.FileMode.Open)
        Dim Serializer = New System.Runtime.Serialization.Json.DataContractJsonSerializer(GetType(List(Of Pedido)))
        Return DirectCast(Serializer.ReadObject(Stream), List(Of SeuObjeto))
    End Using
End Function

JsonQueVocêPassa = https://www.receitaws.com.br/v1/cnpj/27865757000102
SeuObjeto = Objeto que você cria coma  estrutura do Json que você esta tentando serializar.
Neste exemplo esta lendo um Json de um arquivo usando o e montando o objeto.
Caso queria alguns exemplos tem no site da Microsoft e também esse
Tutorial
Comment: espera, eu copiaria a função no meu código e como eu chamaria ela? E ele retorna como?
Comment: Então, esse é um exemplo, você pode usar esse exemplo de base e tentar implementar para o seu caso, no seu a diferença seria que não esta deserializando apartir de uma arquivo, e sim apartir desse link, que pode ser uma `API REST`, tenta entrar nesses links que te mandei e veja o que você não entende.
Comment: E porque mutias vezes falta algum conhecimento sobre  `JSON `ou  como funciona esse retorna que você esta recebendo, ai fica dificil para você entender e fazer certo.
Answer:
Pegar o Json

Na variável json você tera o objeto json obtido a partir da URL.
   Dim json As String = New System.Net.WebClient().DownloadString("https://www.receitaws.com.br/v1/cnpj/27865757000102")

Converter Json para Xml

-Baixe a dll NewtonSoft:
http://www.newtonsoft.com/json
-Utilize a dll NewtonSoft
Dim doc As XmlDocument = JsonConvert.DeserializeXmlNode(json, "root")


Preg_match() from string issue

Question: Situation
I am trying to capture an element of a string with a regex. I am trying to retrieve the offset from these strings:
America/Iqaluit (-4:00)
America/Anchorage (-8:00)

These string are passed in a function that is used by the usort() function as so usort($timezones, "sortByTime");. Here is the code I am using to sort my elements:
function sortByTime($a, $b) {
    if(preg_match("/^[A-z]*\/[A-z]* \((-[0-9]:[0-9]{2})\)/", $a, $matches)){
        $tz[0] = $matches[1];
    }

    if(preg_match("/^[A-z]*\/[A-z]* \((-[0-9]:[0-9]{2})\)/", $b, $matches)){
        $tz[1] = $matches[1];
    }

    return $tz[1] - $tz[0];
}

Problem
The preg_match function is not working with the variables $a and $b. I tried changing the variable with an inline string and it worked. Here is an example:
preg_match("/^[A-z]*\/[A-z]* \((-[0-9]:[0-9]{2})\)/", $b, $matches); //Doesn't work
preg_match("/^[A-z]*\/[A-z]* \((-[0-9]:[0-9]{2})\)/", "America/Yellowknife (-6:00)", $matches); //Works

Why and how can I fix this issue?
Thank you.
Edit
Please note that the $timezones array has a structure like this:
array(2) {
  ["America/Adak"]=>
  string(21) "America/Adak  (-9:00)"
  ["America/Anchorage"]=>
  string(26) "America/Anchorage  (-8:00)"
}

Comment: Can you verify that `$timezones` is an array of timezones? Similarly, are `$a` and `$b` timezone strings?
Comment: Yes they are. I will update the post
Comment: Maybe there are timezones that don't match `[A-z]*\/[A-z]*`? Or timezones with double digit offsets, such as: `Foo/Bar (-20:00)`
Answer: It looks like you have 2 spaces in your timezones, so:
/^[A-z]*\/[A-z]*  \((-[0-9]:[0-9]{2})\)/
// or
/^[A-z]*\/[A-z]*\s*\((-[0-9]:[0-9]{2})\)/

If you're just interested in the time a partial match might be better:
/\(([-+][0-9]{1,2}:[0-9]{2})\)$/

Comment: That was not exactly it, but you leaded me to a working solution! Here is the regex I came up with: /[-+][0-9][0-9]?:[-+]?[0-9]{2}/
Comment: So `+4:-15` is also valid?
Comment: I saw that the generated array was adding some strange values like +4:-15... It is a bit weird but I will keep it that way!
Answer: Try it: /^\w+\/\w+ \((-?\d:[\d]{2})\)/
Comment: Could you explain this solution a bit more?
Comment: The answer that Doge provided is working. Thank you for the help!

Preg_match() from string issue


jQuery use variable as event?

Question: Is there a way in jQuery or javascript to trigger a variable string as an event?
ex.
if (a == b) {
    x = "$('div').hide()";
} else {
    x = "$('div').show()";
}

*trigger x event here*

Ignore the fact that this isn't the correct way to do it.. It is only an example to make the question easier to understand.
Thanks
Answer: You could use the eval function:
var x = '';
if (a == b) {
    x = "$('div').hide()";
} else {
    x = "$('div').show()";
}

eval(x);

Also you could simplify your code like this using the .toggle() method which obviously is a far better solution:
$('div').toggle(a == b);

Comment: aha. damn i totally forgot about that. Thanks!
Answer: if (a == b) {
    action = "hide";
} else {
    action = "show";
}

$('div')[action]();

Or you can use jQuery.toggle

jQuery use variable as event?


Display selected users image from phonebook

Question: I am creating a multi-users chat application. The Inbox activity load the list of users from XML which i used for storage.I have a problem i want that when inbox activity loads the users list it also check that whether any of these user present in phone-book or not. if any user is in phone-book then it loads the Image of that user in listview.
I solved my problem up to some extent but i am unable to display the selected user image. Please give me some hint how to do this.Thank you in advance.
Here is a snapshot of Inbox

Inbox Activity java:
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.users_index);
        listView=(ListView)findViewById(R.id.listview);
        actionBar = getActionBar();
        actionBar.setTitle("Inbox Messages");
        //getNumber(this.getContentResolver());
        getdata();
        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                TextView uname=(TextView)view.findViewById(R.id.sendername);
                username = uname.getText().toString();
                Intent i = new Intent(getApplicationContext(), MainActivity.class);
                i.putExtra("username", username);
                startActivity(i);
            }
        });
    }
    private void getdata() {
        try {
            File fXmlFile = new File("/data/data/net.multiplesystem.nosms/Messeges/UserList.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();
            NodeList nList = doc.getElementsByTagName("details");
            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    String a=eElement.getElementsByTagName("name").item(0).getTextContent().toString();
                    userIndex.add(a);
                }
                }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        setListAdapter();
    }

    private void setListAdapter(){
        adapter = new ArrayAdapter<String>(this,R.layout.user_index_layout,R.id.sendername,userIndex);
        listView.setAdapter(adapter);
        registerForContextMenu(listView);
    }

    /*
    public void getNumber(ContentResolver cr)
    {
        Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
        while (phones.moveToNext())
        {
            name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
            contactId = Long.parseLong(id);
            System.out.println(".................."+phoneNumber);
            System.out.println(".................."+name);
            Number.add(phoneNumber);

        }
        phones.close();// close cursor
           ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.user_index_layout,R.id.sendername,Number);
         listView.setAdapter(adapter);
        setListAdapter();
    }
    */
}

Comment: There's a lot of answers that explain how to use a ListView as you request. Please browse the site and you'll find surely what you need.
Comment: i have search a lot but could not find the desired one. :(
Comment: Maybe you could post some code that narrow the issue then if the response that's been posted doesn't answer your question =)
Comment: sorry for the late reply,i have posted the code please check.
Answer: try this it may help, pass the phone number to get photo
    public Bitmap getPhoto(String phoneNumber) {
    Uri phoneUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
    Uri photoUri = null;
    ContentResolver cr = this.getContentResolver();
    Cursor contact = cr.query(phoneUri,
            new String[] { ContactsContract.Contacts._ID }, null, null, null);

    if (contact.moveToFirst()) {
        long userId = contact.getLong(contact.getColumnIndex(ContactsContract.Contacts._ID));
        photoUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, userId);

    }
    else {
        Bitmap defaultPhoto = BitmapFactory.decodeResource(getResources(), android.R.drawable.ic_menu_report_image);
        return defaultPhoto;
    }
    if (photoUri != null) {
        InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(
                cr, photoUri);
        if (input != null) {
            return BitmapFactory.decodeStream(input);
        }
    } else {
        Bitmap defaultPhoto = BitmapFactory.decodeResource(getResources(), android.R.drawable.ic_menu_report_image);
        return defaultPhoto;
    }
    Bitmap defaultPhoto = BitmapFactory.decodeResource(getResources(), android.R.drawable.ic_menu_report_image);
    return defaultPhoto;
}

Comment: rather than using ArrayAdapter, use custom adapter & create a model object which can store both name & object, pass this object to adapter.. At the time of setting data, u can set all the parameters & set imageview also
Comment: how to pass bitmap object to adapter ?
Comment: hey call that method in adapter it self... at the time of setting bitmap to imageview do this.. imageView.setImageBitmap(getPhoto(999999999));
Comment: i have posted my code please check and give some suggestions.
Answer: What i understand from your code is that you need to inflate custom layouts for displaying contacts.
I believe your R.layout.user_index_layout is something like that :
<LinearLayout
    android:orientation="horizontal"
    ... >
    <ImageView
        android:id="@+id/userIndexLayout_img"
        ... />
    <TextView
        ... />
</LinearLayout>

So imagine some callback that gets notified when a user becomes connected like this (more pseudo-code) :
public void onUserConnected(int id) {
    int indexInsideListView = getUserIndex(id);
    View userView = listView.getChildAt(indexInsideListView);
    ImageView imgView = (ImageView) userView.findViewById(R.id.userIndexLayout_img);
    // User ImageView.setImageResource/Drawable/Bitmap
}


Rails e MySQL - Tipos de Dados

Question: Comecei a utilizar Ruby on Rails recentemente para um projeto, e tenho dúvidas quanto ao scaffold e outras funcionalidades de DB presentes no Rails.
Aqui há um tópico explicando sobre tipos de dados no Active Record Migration
https://stackoverflow.com/questions/17918117/rails-4-list-of-available-datatypes
Como posso utilizar outros tipos de dados presentes no MySQL, como Set, Enum e tantos outros? Posso alterar tabelas diretamente pelo MySQL ou tenho que seguir exatamente o que as migrações do Active Record oferecem?
Answer: O Rails utiliza ActiveRecord (ORM) para fazer o mapeamento de todas as tabelas e atributos das mesmas. Então para você utilizar o Rails sem utilização de bibliotecas externas, sim você só poderá utilizar os dados oferecidos pelas migrações do Rails.
No entanto você pode extender essas funcionalidades utilizando uma Gem. Para seu caso, se precisa utilizar SET ou ENUM do MySQL pode utilizar a gem native_enum que, segundo a documentação, adiciona esses dois tipos à migração do Rails. Ex:
create_table :balloons, :force => true do |t|
  t.enum "color", :limit => ['red', 'gold'], :default => 'gold', :null => false
  # or...
  t.column "size", :enum, :limit => ['small', 'medium', 'large']
end

Answer: A ideia do migration é ter registrado como scripts a evolução do seu banco de dados, dessa forma voce teria a a gestão de mudança de banco de dados documentada, alem de facilitar a atualização do banco junto com código da aplicação, facilidade na aplicação de muitos scripts e equalização de banco entre ambientes, por exemplo. Com migrations voce poderá evoluir ou regredir o banco baseado na evolução histórica junto com seu código. Aconselho a não mexer diretamente no banco de dados a não ser que sejam tarefas especificas de tunning ou gestão, ou que voce não consiga fazer com migrations (Raríssimas exceções).
No rails 4 voce pode fazer Enum da seguinte maneira DOC.
Ou voce pode executar queries no migration, exemplo.

Rails e MySQL - Tipos de Dados


Como fazer o HEADER acompanhar a altura dos elementos internos?

Question: Estou com o seguinte problema. Meu header não acompanha a altura automaticamente dos elementos internos. Com isso quando defino o css border-bottom:#DE5207 3px solid; para o header ele não exibe, pois fica sempre com altura menor que os elementos internos. Já tentei colocar height: auto mas não funciona.

*{
  margin: 0px;
  padding: 0px;
  font-family: Arial, Helvetica, sans-serif;
}
div.principal{
  background-color: #ccc;
  margin: auto;
  box-sizing: border-box;
}

/* CABEÇALHO */

.cabecalho_topo{
  border-bottom:#DE5207 3px solid;
  height: auto;
}

/* Logomarca */

figure.logo{
  float: left;
  width: 21.42857142857143%; /* 300px */
  height: 80px;
  background-color: #FF8922;
}

/* Formulário de busca no Guia Comercial */

section.frmbuscaguia{
  float:left;
  width: 39.28571428571429%;
  height: 80px;
  background-color: #FF8922;
  text-align: center;
}
section.frmbuscaguia h1{
  font-size: 16px;
  color:#222;
  text-align: center;
  padding: 2% 2%;
 }
section.frmbuscaguia button{
  background-color:#F4F4F4;
  border: 0px;
  padding: 5px;
  box-sizing: border-box;
}
section.frmbuscaguia input{
  background-color:#F4F4F4;
  border: 0px;
  padding: 5px;
  box-sizing: border-box;
}

/* Menu do topo */

.menutopo{
  float: left;
  background-color: #FF8922;
  width: 39.28571428571429%;
  height: auto;
}
.menutopo a{
  color:#ffffff;
  text-decoration: none;
  font-size: 15px;
}
.menutopo ul{
  margin: 0px;
  padding: 0px;
}
.menutopo ul li{
  float:right;
  display: inline;
  padding: 0 20px 0 20px;
  line-height: 79px;
}
.menutopo ul li:hover{
background-color: #DD6900;
}

Buscar no Guia Comercial

            <form>
                <input type="text" name="buscar">
                <button type="submit">Pesquisar</button>
            </form>

QUEM SOMOS

ANUNCIE

CONTATO

Answer: É por causa do float: left, então o elemento fica com height:0 por que os elementos interno estão com float.
Você tem que adicionar um elemento com clear: both após, pode criar um pseudo-elemento, assim:
.cabecalho_topo::after {
    content: "";
    height: 0;
    display: block;
    clear: both;
}

Resultado:

*{
  margin: 0px;
  padding: 0px;
  font-family: Arial, Helvetica, sans-serif;
}
div.principal{
  background-color: #ccc;
  margin: auto;
  box-sizing: border-box;
}

/* CABEÇALHO */

.cabecalho_topo{
  border-bottom:#DE5207 3px solid;
  height: auto;
}

.cabecalho_topo::after {
    content: "";
    height: 0;
    display: block;
    clear: both;
}

/* Logomarca */

figure.logo{
  float: left;
  width: 21.42857142857143%; /* 300px */
  height: 80px;
  background-color: #FF8922;
}

/* Formulário de busca no Guia Comercial */

section.frmbuscaguia{
  float:left;
  width: 39.28571428571429%;
  height: 80px;
  background-color: #FF8922;
  text-align: center;
}
section.frmbuscaguia h1{
  font-size: 16px;
  color:#222;
  text-align: center;
  padding: 2% 2%;
 }
section.frmbuscaguia button{
  background-color:#F4F4F4;
  border: 0px;
  padding: 5px;
  box-sizing: border-box;
}
section.frmbuscaguia input{
  background-color:#F4F4F4;
  border: 0px;
  padding: 5px;
  box-sizing: border-box;
}

/* Menu do topo */

.menutopo{
  float: left;
  background-color: #FF8922;
  width: 39.28571428571429%;
  height: auto;
}
.menutopo a{
  color:#ffffff;
  text-decoration: none;
  font-size: 15px;
}
.menutopo ul{
  margin: 0px;
  padding: 0px;
}
.menutopo ul li{
  float:right;
  display: inline;
  padding: 0 20px 0 20px;
  line-height: 79px;
}
.menutopo ul li:hover{
background-color: #DD6900;
}

Buscar no Guia Comercial

            <form>
                <input type="text" name="buscar">
                <button type="submit">Pesquisar</button>
            </form>

QUEM SOMOS

ANUNCIE

CONTATO