How to find a hyperlink text and replace with embedded text?

Question: How should I find a hyperlink text and replace with the embedded text for the below examples?
For e.g. 1:
Table of Contents

Introduction. It refers to the corresponding id "ch1"/p>

Research. It refers to the corresponding id "ch2"

Results. It refers to the corresponding id "ch3"

Discussion. It refers to the corresponding id "ch4"

Conclusion. It refers to the corresponding id "ch5"

E.g. 2:
www.google.com
www.stackoverflow.com

E.g. 3:
Citations
*see* Chapter. 1. It refers to the id "ch1"
*see* Fig. 1. It refers to the id "fig1"
*see* Table. 1. It refers to the id "tab1"

The above mentioned examples are converted to html  tag using VBA Macros.
Example 1 should be converted to:
     Introduction
     Research
     Results
     Discussion
     Conclusion

E.g. 2 should be converted to:
   www.google.com
   www.stackoverflow.com

E.g. 2 should be converted to:
   www.google.com
   www.stackoverflow.com

Comment: possible duplicate of [Convert hyperlink and bookmarked words to html  tag in Word using VBA macros](http://stackoverflow.com/questions/29600076/convert-hyperlink-and-bookmarked-words-to-html-a-tag-in-word-using-vba-macros)
Answer: Actually, I would like to extract the hyperlinks from text. So I have solved the  question with below the code.
    Sub HlinkChanger()
Dim oRange As Word.Range
Dim oField As Field
Dim link As Variant
With ActiveDocument
.Range.AutoFormat
For Each oRange In .StoryRanges
For Each oFld In oRange.Fields
If oFld.Type = wdFieldHyperlink Then
For Each link In oFld.Result.Hyperlinks
oFld.Select
Selection.InsertBefore ""
Selection.InsertAfter ""
Next link
End If
Next oFld
Set oRange = oRange.NextStoryRange
Next oRange
End With
End Sub


WDAC Publisher or Hash rule without a reference file

Question: Does anyone know of a way to create a Windows Defender Application Control Rule (WDAC) without a reference file?  We have a situation where remote users, on laptops, sometimes need to run executables that are blocked by WDAC. Once we review the executable, the next step is adding it to a WDAC policy however both the WDAC wizard and powershell commands require a reference file for publisher and hash. We have the publisher and hash (sha256) values from the event log but not the actual file.
We want to avoid WDAC rules based on filename and the path rule only works for exe's, not MSI,dll,msp etc.
Thanks in advance
Comment: https://learn.microsoft.com/en-us/windows/security/threat-protection/windows-defender-application-control/merge-windows-defender-application-control-policies
Answer: Yes, Event viewer logs contain everything you need to create a WDAC policy and then you can either merge it with your base policy or deploy it as a supplemental policy.
There are 4 types of hashes in each log entry in Microsoft-Windows-CodeIntegrity/Operational Event logs category, ID = 3076

SHA256 Hash
SHA256 Flat Hash
SHA1 Hash
SHA1 Flat Hash

They allow you to create WDAC rules and policy for files that no longer exist anymore.
But you need to be aware that the default log size is 1MB and after that new logs will overwrite the old ones, so assuming they still exist or you increased the default log size, you can scan that remote machine's event logs or collect their logs, import them to a new clean VM and then make a WADC policy based on them.
There are PowerShell cmdlets that can be used do it but I've created PowerShell module for automation:

WDACConfig - GitHub

WDACConfig - PowerShell gallery

You can use this parameter to create a new supplemental policy by scanning audit event logs of that specific category.
New-WDACConfig -MakePolicyFromAuditLogs -Deployit -TestMode -RequireEVSigners -Debugmode -Levels <String> -Fallbacks <String[]> -LogSize <Int64>

You're right to avoid FilePath rules as they are not as secure as others such as Hash, SignedVersion, FilePublisher etc.
I also suggest taking a clean VM, Prepare it for Audit log collection, install the executable that you want your remote users/employees to be allowed to install on it, run it and use it a bit to all of its components get executed and event logs created for them, then uninstall it. This way you create event log entries for every file in that program and your remote users can install/run/uninstall the program.
More Windows Defender Application Control (WDAC) resources on my GitHub:
https://github.com/HotCakeX/Harden-Windows-Security/wiki/Introduction


Laplace transform,Fourier transform and Z transform mathematical equations

Question: Fourier transform $x(w)$ of signal x(t) is given by
$$ x(w) = \int\limits_{t=-\infty}^{+\infty} x(t) e^{-j w t} dt   -(1)$$
Laplace transform $x(s)$ of signal x(t) is given by
$$ x(s) = \int\limits_{t=-\infty}^{+\infty} x(t) e^{-pt} e^{-j w t}dt -(2)$$
where $s=p+jw$
and
Z transform $x(z)$ of discrete signal x(n) is given by
$$ x(z) = \sum\limits_{n=-\infty}^{+\infty} x(n) (re^{-j w ) n}   -(3)$$
where $z=re^{jw}$
As you can see that all above transform are slightly different with one another. If we consider Fourier transform as a reference, Laplace transform has addition of only $e^{-p}$
and $r^{-n}$ term in case of Z transform .
So my question is what role such added terms play  in making 3 different transform?
What is there importance?
Answer: They are indeed related, which shows up in many places.
The difference is in the meaning of the result, but most importantly, in the domain. Fourier transform requires a $L^2$ integrable function (physicists abuse this a lot). It gives you a spectrum of the signal, it treats positive and negative times equally (noncausal signals). It's a unitary transformation (it's its own inverse, plus or minus a conjugation and a sign) and as such has a lot of nice mathematical qualities.
Laplace transform deals with causal signals: typical examples are response functions in circuitry, material physics and so on. The lower integration limit is 0 (or finite, but not $-\infty$). It is more related to a fourier transform of a function, multiplied by the Heaviside step function. The difference is also in what values you usually put in. Although you can put complex values in both of them, the traditional domain are real frequencies for FT and real (or at least positive complex) exponents for LT. But their relationship does show up in physics a lot: fluctuation-dissipation theorem, relationship between statistical physics and quantum mechanics, one of the prominent examples is the the dielectric response (refraction index) as a function of frequency. As FT, it's also suitable for solving linear differential equations, but has the advantage, that its causal nature takes the initial conditions into account explicitly and ignores the negative time portion. That's how most phenomena in nature work (future does not affect the past, nothing happens before the cause happens). FT on the other hand deals mostly with uniform steady-state phenomena that have been running since forever following the same rules. Periodic phenomena are one big example of this.
Z-transform is, as you noticed, discrete. It is quite related to the discrete Fourier transform, zhe $z=1$ circle representing the fourier spectrum. It's a sort of polar version of the fourier transform and makes the cyclic nature of frequencies in discrete signals apparent (compare to the FT where the frequency domain is infinite). The interpretation of the $|z|=r$ coordinate gives you the dissipation rate, making it suitable for real time series analysis (stability of linear systems and so on).
In short: all three transforms follow the same concepts, but the difference is both in what kind of signals you put in, and what sort of information you need to get out of it.


If $\{f_n\}$ is Cauchy in measure, then there is a measurable function $f$, such that $\{f_n\}$ converges in measure to $f$

Question: The theorem is from Real Analysis (Carothers).
Let $\{f_n\}$ be a sequence of real valued measurable functions, all defined on a common measurable domain $D$. If $\{f_n\}$ is Cauchy in measure, then there is a measurable function $f:D\rightarrow \mathbb{R}$, such that $\{f_n\}$ converges in measure to $f$. Moreover, there is a subsequence $\{f_{n_{k}}\}$ that converges pointwise a.e. to $f$.
And the proof is shown in the picture

Can someone explain the last line to me? The stuff in the red box. I don't quite understand how they get that inequality.
Answer: The previous inequality shows that
$$|f(x)-f_{n_k}(x)| < 2^{-k+1} \qquad \text{for all $x \in D \backslash \bigcup_{j=k}^{\infty} E_j$,}$$
i.e.
$$x \in D \backslash \bigcup_{j=k}^{\infty} E_j \implies x \in \{|f-f_{n_k}| < 2^{-k+1}\}.$$
This is equivalent to
$$D \backslash \bigcup_{j=k}^{\infty} E_j \subseteq \{|f-f_{n_k}| < 2^{-k+1}\}.$$
Taking complement on both sides yields
$$\{|f-f_{n_k}| \geq 2^{-k+1}\} \subseteq \bigcup_{j=k}^{\infty} E_j,$$
and now the monotonicity of the measures proves the claimed inequality.


Pular a rota devido a parametro mal formatado é um erro de sintaxe?

Question: Por exemplo, eu tenho a rota GET: /user/{id}, sendo que o id passa por uma validação de expressão regular do tipo [0-9]+. Ao realizar requisições com o verbo GET para as seguintes URLs:

/user/17, retorna os dados do usuário de id igual a 17
/user/null, retorna o status 404, como se não existisse a rota

Isso seria um erro de sintaxe? Deveria ser retornado um 400?
E no caso de em vez de um parâmetro na URL inválido, um parâmetro no corpo, por exemplo, uma rota que precisa de dois parâmetros, oldPassword e newPassword, mas a requisição só tem newPassword?
Comment: Se a requisição está errada/incompleta, 400. A "Bad Request" é justamente responder um "olha, o erro foi aí do seu lado, não no servidor. Se vira para corrigir".
Comment: @AndersonCarlosWoss então ambos os casos que citei estariam incorretos retornar 404?
Comment: No meu entendimento, sim. A rota existe e foi encontrada, não faz sentido responder com 404.
Answer: A URL é um valor opaco por definição, o que significa que ela não necessariamente reflete a estrutura da sua aplicação; tanto que acessar /user/1 não é, necessariamente, acessar o arquivo em /user/1/index.html, a URL pode não representar a organização de pastas (ou pode, como é comum para os arquivos estáticos).
Dito isso, a resposta final à sua pergunta é: depende dos requisitos da sua aplicação.
Não podemos dizer o que é certo ou errado, pois em uma aplicação pode fazer sentido e em outras não. Sendo a URL opaca, em diferentes aplicações ela pode representar diferentes recursos e, assim, exigir diferentes respostas.
Vamos começar com o contra-argumento da sua pergunta: temos uma aplicação em que eu posso acessar as informações de um usuário tanto com /user/1 quanto /user/anderson-carlos-woss. Acontece que no primeiro caso eu informei o ID do usuário, enquanto no segundo eu informei o nome. Na minha aplicação eu garanto que ambos serão únicos para cada usuário. Ou seja, acessar o recurso /user/null, por exemplo, faria com que minha aplicação chegasse ao recurso correto (usuários), provavelmente existiria uma condição que verificaria se o valor é um número; se for, busca pelo id, caso contrário busca pelo nome. Neste caso, seria buscado do banco o usuário com nome Null e se não encontrado geraria uma resposta de erro.
Percebe que neste caso o recurso da aplicação foi identificado corretamente, foi feito toda a busca e não encontrou o registro no banco? Para esta situação a resposta indicada seria a 404 Not Found, pois sua aplicação conseguiu processar a requisição com sucesso, somente não encontrou o recurso que o cliente requisitou.
Na sua pergunta você cita:

... sendo que o id passa por uma validação de expressão regular do tipo [0-9]+

E é isso que define qual utilizar. Os requisitos da sua aplicação demandam que o id informado pela URL deve ser um valor inteiro não negativo. Se o cliente solicitar o recurso /user/null, é mais interessante você informá-lo que a requisição está errada e que ele precisa corrigi-la antes de tentar novamente. Veja, é um problema na requisição, não na aplicação. Erros na requisição são informados com a resposta 400 Bad Request, que basicamente diz ao cliente "cara, sua requisição não faz sentido, não sei o que fazer com ela".
Resumindo:

Responda com 404 Not Found quando existir a rota naquele formato, mas o recurso em questão não foi encontrado;
Responda com 400 Bad Request quando não existir a rota naquele formato;

Então é errado eu enviar a resposta 404 neste caso? Não! Depende da sua aplicação. Algumas aplicações optam por enviar a resposta 404 mesmo que a requisição esteja errada para ocultar a estrutura da própria aplicação. Digamos que um usuário com más intenções tente invadir o recurso /user/null e recebe a resposta 400 ele saberá que a requisição está errada e tentará fazer o ataque em um recurso semelhante, até obter outra resposta; enquanto se ele receber a resposta 404 ele poderá achar que o recurso não existe e desistir do ataque. Depende de que recurso estamos tratando, de qual contexto ele será usado e de quais são os requisitos da aplicação.
A minha visão é bem simples: a aplicação deve estar protegida contra ataques em qualquer recurso, não é uma resposta HTTP que mudará isso, então eu busco sempre utilizar aquela que facilita para o cliente (bem intencionado).

E no caso de em vez de um parâmetro na URL inválido, um parâmetro no corpo, por exemplo, uma rota que precisa de dois parâmetros, oldPassword e newPassword, mas a requisição só tem newPassword?

Mesma situação. Sua aplicação saberá o que fazer quando só tiver um dos valores? Se sim, a requisição é válida. Se não, a aplicação não tem o que fazer com a requisição, então responda com 400 Bad Request.
Lembre-se que não é feio dizer pro cliente que ele está errado. Se ele fez uma requisição errada, avise-o para que ele possa corrigir.

Outra forma de analisar o problema é verificando as definições de cada resposta:

400 Bad Request
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

Traduzindo, a requisição pode não ter sida entendida pelo servidor devido à sintaxe mal formatada. O cliente NÃO DEVE repetir a requisição sem modificações.
Isto é, se eu acessar hoje o recurso /user/null e obter a resposta 400, saberei que sempre que eu fizer essa mesma requisição eu terei a mesma resposta. Se existe a possibilidade de amanhã (ou outro momento) o recurso existir, então a resposta deverá ser 404, não 400. Ah, mas e se um dia eu quiser criar esse recurso, então já devo usar a resposta 404? Não. Você responde conforme sua aplicação é hoje. No dia que você for criar o novo recurso você altera a resposta.

404 Not Found
The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.

Traduzindo, o servidor não encontrou resultados para a URI requisitada. Nenhuma indicação é dada sobre se a condição é temporária ou permanente. A resposta 410 (Gone) deve ser utilizada se o servidor sabe, de alguma maneira, que o recurso existiu e foi permanentemente removido sem nenhum endereço alternativo. Esta resposta é comumente utilizada quando o servidor não deseja revelar o motivo real da requisição ser recusada.
Neste caso, responder com 404 quando acessar /user/null não significa que um dia esse recurso existirá. Indica apenas que hoje não existe e que há a possibilidade de existir um dia. Se o recurso existiu e foi excluído, a aplicação pode responder com 410 (isso é comum em aplicações que efetuam o soft-delete).
Também como comentado anteriormente, a resposta 404 é mais genérica e pode ser utilizada em ocasiões diversas, seja para não revelar informações da aplicação, seja porque não havia respostas melhores para a situação.

Outra dúvida que é bastante comum é como diferenciar se a rota não existe ou se o registro não existe ao receber a resposta 404. Se eu acesso /user/1 e recebo a resposta 404 significa que eu deveria tentar outra rota, como /usuario/1, ou minha rota está certa e é id 1 que não existe no banco?
Para fazer essa diferenciação é comum utilizar o corpo da resposta enviando uma mensagem com detalhes sobre o motivo dela ter sido gerada.
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8

{"error": "Rota não encontrada"}

Ou
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8

{"error": "Usuário 1 não encontrado"}

Você pode, inclusive, alterar a descrição da resposta (response reason) livremente, porém não é tão depender dela para indicar o erro, pois é muito mais fácil trabalhar com o corpo da resposta que sua descrição. Se o cliente for algo mais visual ao usuário, como o Postman, talvez seja interessante utilizá-la:
HTTP/1.1 404 User Not Found
Content-Type: application/json; charset=utf-8

{"error": "Usuário 1 não encontrado"}

Isso pode facilitar para o usuário, pois não demanda dele analisar um possível JSON no corpo da resposta.
Comment: Respondeu 250% a pergunta :)
Comment: @woss, no caso de enviar apenas `newPassword` e não `oldPassword`, não seria um 422 Unprocessable Entity?
Answer: Não, esse comportamento está correto, essa rota que você informou não existe, eu fiz um script rápido em JS para exemplificar isso, onde eu testo a expressão regular que você está utilizando para validar a rota:

paths_test = ["/user/17", "/user/null"]

paths_test.forEach(x => {
  console.log(x.match('[0-9]+') || `Rota não encontrada: ${x}`);
})

O path parameter null não da match com a sua rota /user/{id}, ele vai retornar 404 pois não encontrou nenhuma rota que atenda a requisição /user/null já que a única existente valida se o parâmetro é numérico através de uma expressão regular.
Sobre a segunda pergunta é a relacionado a primeira certo? Então acho que a mesma lógica se aplica.
Comment: Sua resposta me parece confusa, não diz se tá ou não certo, parece que está dizendo "tanto faz"
Comment: @GuilhermeCostamilam Veja se ficou mais claro.
Comment: Pelo que pude entender, você só testou pela existência de dígitos na string. Creio que uma validação melhor fosse `x.match('/[0-9]+$')`, onde garanto que os números devem existir após a barra. Mesmo assim, não ficou muito óbvio na minha leiga cabeça a relação entre esse `match` e a questão...
Answer: O erro 404 é um código de resposta HTTP que indica que o cliente pôde comunicar com o servidor, mas o servidor não pôde encontrar o que foi pedido. No seu caso foi possível comunicar com o servidor mas não foi possível encontrar o que você procura que é uma URL específica (página específica) , ou seja, o retorno 404 é correto porque ele não encontra sua rota (página não encontrada).

O comportamento está correto mas a lógica errada. Um identificador não pode ser nulo, logo, você já deveria trazer somente ID'S válidos para montar sua URL, pois o ID é um parâmetro para se montar a sua rota (no máximo validar que o id não seja nulo como também não pode ser diferente de numérico). Ou seja não faz sentido em montar a URL da página de um usuário que não existe. Se você cria um tabela no banco de dados e efetua um insert o campo ID como chave primária assume o valor 1 e não 0 ou NULL.
Há contextos em que queremos buscar valores em que podem vir campos nulos, mas não é o seu. Se é um parâmetro obrigatório para formar uma instrução e ele vem de uma consulta, de um array, ou um campo informado, não pode vir nulo.
Comment: Nesse trecho "você já deveria trazer somente ID'S válidos para montar sua URL". Aqui está dizendo que quem irá montar a URL é o autor. Porém, isso normalmente não é verdade. Veja mais algumas perguntas interessantes do Guilherme, como [métodos HTTP na prática](https://pt.stackoverflow.com/q/300329/64969), [retorno do `OPTIONS`](https://pt.stackoverflow.com/q/339104/64969), [método `DELETE` possuir corpo](https://pt.stackoverflow.com/q/301436/64969) e [obter a comunicação textual de uma chamada HTTp](https://pt.stackoverflow.com/q/340047/64969). [1/3]
Comment: Em todas elas o Guilherme está indo além das requisições típicas de browser (`GET`/`POST`) para uma abordagem mais semântica, onde o método HTTP importa para que ele possa fazer um tratamento especial. Em especial, a [métodos HTTP na prática](https://pt.stackoverflow.com/q/300329/64969) dorme na minha cabeceira todo dia para que eu possa fazer uma boa API no trabalho no dia seguinte. E, como os métodos fora do `GET` e do `POST` não são trivialmente acessíveis pelo browser, o cliente dele é uma aplicação. Logo, não faz nem sentido falar em "página". [2/3]
Comment: Como ele é acessado por uma aplicação, um usuário que pretende obter dados sigilosos pode tentar se passar pela aplicação em questão, fazendo a [requisição HTTP textualmente](https://pt.stackoverflow.com/q/340047/64969), por exemplo. [3/3]
Comment: Sobre rotas, por que ele deveria carregar todas elas? Normalmente isso gasta mais memória. Basta por alguém que identifique que, se for `/user/{id}` para um `{id}` arbitrário, retorne o resultado de uma computação passando esse `{id}` como argumento
Comment: E se a URL fosse montada por um atacante? Não seria ele, então, quem montou a URL, porém ela seria gramaticalmente válida no que tange URLs
Comment: Não entendi seu comentário. O que significa"montada por um atacante"? Estou chamando a atenção para "se não existe o id do usuário não é possível montar a url". Logo ele já tem que trazer todos os id's válidos para que todas as rotas sejam montadas sem falha.
Comment: Todas as respostas 4xx implicam que a comunicação com o servidor foi bem sucedida e que falhou devido ao erro por parte do cliente, tanto que são chamadas de "client errors". Não entendo como isso pode ser argumento para se dizer que o correto é a 404. Também não entendi quando você comenta sobre "montar a URL"; parece que está presumindo que será acessadas somente as URLs presentes na página e não será acessadas nenhuma manualmente ou geradas a partir de um script de invasão buscando falhas na aplicação. Você discordaria de alguma coisa da minha resposta?
Comment: Entendi o que você quis dizer. Ele tem o script que monta a URL tanto que ele valida se o campo ID é númerico. Caso ele não queira carregar todos os ID's válidos é só na parte do código que ele valida se é númerico acrescentar que não pode ser nulo também. Em relação a pessoa inserir um código malicioso é por isso que ele faz a validação de que seja númerico e para não apresentar  o erro 404, deve evitar que o id seja diferente de nulo (pois assim existirá rota). Informei na minha resposta também.
Answer: Eu consideraria um erro de sintaxe: 400 - Bad Request.
Se você está buscando por usuários com determinado número de identificador, o número null não é um número válido. Portanto, isto é considerado uma request "ruim" (bad request), ou seja, o cliente não observou a forma correta do parâmetro passado e ele deve fazer a correção necessária antes de tentar novamente.
O 404 - Not Found não faz sentido aqui, pois o usuário de identificador null é um identificador inválido antes de ser considerado um usuário que não existe (o que de certa forma é também verdade).

E no caso de em vez de um parâmetro na URL inválido, um parâmetro no corpo, por exemplo, uma rota que precisa de dois parâmetros, oldPassword e newPassword, mas a requisição só tem newPassword?

Excelente pergunta. Se as duas informações são obrigatórias, você pode retornar também um 400 - Bad Request. Se eu não me engano, este é o comportamento padrão do framework Spring quando as informações do body da request são anotadas com @NotNull e o cliente não as preencheu.
No mais, também faria a seguinte alteração no seu endpoint: ao invés de usar /user/ usar /users/.
Comment: Um motivo para se retornar 404 seria para tentar alguma forma de segurança por obscurantismo
Comment: @JeffersonQuesado, pode ser um motivo. Algumas soluções podem variar dependendo do contexto, tanto que estas discussões de qual o status HTTP correto em determinadas situações existem aos montes. O que apreendi ao final é que o mais importante em uma API é manter, independente da decisão tomada, o mesmo padrão.


How to script non-default collation and skip explicit scripting for default collation?

Question: In SSMS 2008 R2, I created a table:
aTest(Albnian varchar(10), Dflt varchar(10))

In SSMS table designer, both columns have the collation: "<database default>" (under "Column Properties" → "Table Designer")
I changed the collation of the column "Albnian" to a non-default, for example, Albanian_CI_AS.
If I script the table in SSMS (right click on "aTest" → "Script Tables as" → "CREATE To" → "New Query Editor Window", I get [1] with no explicit collations scripted at all.
Bad.
Obviously, one would expect the table to be scripted with explicit collation for non-default collation (the one that the developer intentionally introduced with a specific purpose) and no collation for default collation.
In SSMS menu → Tools → Options → SQL Server Object Explorer → Scripting, I changed:

Include collation: True
Script defaults: False

but now, I am getting all column collations scripted, both default and non-default ones [2].
How can I configure script generation to script non-default collation and skip the default ones, as in [3]?
[1] Default scripting of table:
CREATE TABLE [dbo].[aTest]
(
    [Albnian] [varchar](10) NOT NULL,
    [Dflt] [varchar](10)  NOT NULL
) ON [PRIMARY]

[2] Table script after "Include collation" changed to True
CREATE TABLE [dbo].[aTest]
(
    [Albnian] [varchar](10) COLLATE Albanian_CI_AS NOT NULL,
    [Dflt] [varchar](10) COLLATE Cyrillic_General_CI_AS NOT NULL
) ON [PRIMARY]

[3]  Needed collation script generation behavior:
CREATE TABLE [dbo].[aTest]
(
    [Albnian] [varchar](10) COLLATE Albanian_CI_AS NOT NULL,
    --non-default should be scripted

    [Dflt] [varchar](10) NOT NULL
    -- default database collation should not be scripted
) ON [PRIMARY]

Related question:

What issues to anticipate having different collations between development and production SQL Servers?
Comment: I see no harm in using version [2]. Why do you object to it?
Comment: This is to be deployed to a server with different default collation, there is no intention to have any cyrillic oriented fixed options on columns with English-only text
Comment: In that case, you may have to just do a post-cleanup search & replace on your generated script file to remove the undesired collation.
Answer: I submitted a suggestion through MS Connect:
Collations are scripted either for all columns or for none
Here's the related response:

Posted by Microsoft on 11/11/2010 at 10:16 AM
  Hi Gennady:
Thanks for writing in to Microsoft. We greatly value your feedback. We understand your problem, and how fixing this could improve productivity.
However, given the work that would be involved in implementing this work, and our set of deliverables, we do not think, we would be able to get to this in the near future.
Having said that, we value your suggestions, and would like to assure you that, we would keep these ideas in mind, when we do revisit this feature in the future.
Thanks again for providing feedback and making SQL Server the greatest Database server.
Regards
Chandramouli


Como fazer com que um arquivo PDF no assets do meu APP seja aberto pelo leitor de PDF nativo do android?

Question: Tenho um APP que precisa abrir alguns arquivos PDF (leis) que deve vir junto com a aplicação.
A ideia é chamar uma Intent para abrir estes arquivos PDF pelo próprio leitor PDF nativo do Android ou um leitor de PDF já instalado no celular. Os arquivos estão no assets (dentro do diretório res). Como faço para a aplicação abrir o leitor de PDF externo e a intenção abrir o PdF com o caminho do arquivo que esta no assets?
Já tentei várias coisas e ainda não consegui.
Por favor, me ajudem!
Comment: Tem algum código que consiga mostrar para dar mais detalhes?
Comment: Seria como o APP Bombeiros IT-instruções Tecnicas (Ele abre a legislação em um visualizador de PDF onde tem campo de buscas do próprio leitor de PDF).
Answer: file://android_asset é visível apenas para o seu app. Você está querendo que outro aplicativo abra um arquivo da pasta assets que ele não possui.
O que você pode fazer é copiar esse arquivo para o diretório interno ou externo e ai tentar ler o mesmo.
Comment: Isso mesmo. Você tem algum código assim?
Comment: Algo assim: https://gist.github.com/alhazmy13/c93c5e083ec0b7fe6d1c
Comment: Não esqueça das permissões de `READ` and `WRITE`
Comment: Acho que é isso ai. Mas como ficaria o meu xml?
Comment: ``
    ``
Comment: No exemplo que você me passou, como faço para chamar o método openPDFFiles (Como informado no item 5)?
Comment: `openPDFFiles("file.pdf")`
Comment: Nossa, ao clicar no botão ele aciona o leitor de PDF e depois volta para o APP com a seguinte mensagem: Não foi possível acessar o arquivo. Verifique a localização ou a rede e tente novamente.
Comment: Fiz uma outra pergunta com o código no seguinte link: https://pt.stackoverflow.com/questions/309949/como-abrir-um-arquivo-pdf-que-esta-no-assets-do-meu-app-em-um-leitor-de-pdf-j%C3%A1
Comment: Desculpa pelo incômodo, mas, por favor, verifica o que fiz de errado.


Generating PDF file with PuppeteerSharp from webpage containing images linking to Azure Blob storage

Question: I have a web page that contains href tags pointing to pictures stored in Azure Blob storage. The Azure container is a private and the link generated to access each images is performed using Azure SAS token.The format of a href link is similar to https://myblob.blob.core.windows.net/mycontainer/myfolder%2Fmyfile.jpeg?sv=2019-12-12&st=2020-10-13T18%3A52%3A48Z&se=2020-10-13T18%3A58%3A48Z&sr=b&sp=r&sig=P5JRdwKa4GkbIFF55sWywOe4vnPnWOCoSf29UHYmNPA%3D
When generating the PDF using Puppeteer sharp using WaitUntilNavigation.Networkidle0, I didn't succeed in retrieving the images:

I also tested each generated secured SAS link and they work without problem. I also replaced each href link with a base 64 data encoded image and it works great.
I tested PDF generation using online Puppeteer service based on Nodejs (https://try-puppeteer.appspot.com/) and it works like a charm. So there seems to be an issue with puppeteersharp version (v2.0.4).
Any idea on what could be the issue?
Comment: I bet you would be getting the same navigating that page using a stock browser.
Comment: Actually if I connect to the page with the built-in browser of Samsung S20 phone, it works, I can see all the pictures.
Answer: After struggling with the issue for several hours, we finally located the issue. It is not related with Puppeteer that works like a charm but rather with the way a private blob storage container handles authentication: as our request contained an Authorization HTTP Header with a bearer token required by our own app, this header was sent by Chromium while retrieving remote images from the blob container.
Unfortunately Azure service tried to handle that token and rejected our request.
How did we identify that? By connecting a chrome debugger to the Chromium instance and by checking the logs. Indeed it is possible to launch Puppeteer with a remote debugging port.


Trying lessening the amount of functions i need to write to set state to the props of this elements size

Question: I am trying to set the state of size chosen with a function but i have 20 sizes and do not want to repeat a function 20 times is there a way to lessen the code? Is there a way to check and see if the state change matches the props clicked on?
1 when they click the button set the state to the props of the element clicked using one function.
If you want to look at the full code https://github.com/CodingOni/Ecommerce-Store
Example of Data
{
    id: 6.97,
    title: "Adidas Yeezy Boost 350 V2 Glow",
    img: "img/product-6.97.png",
    img2: "img/product-6.97-1.png",
    img3: "img/product-6.97-2.png",
    img4: "img/product-6.97-3.png",
    price: 800,
    info: "Adidas Yeezy Boost 350 V2 Glow",
    inCart: false,
    count: 0,
    total: 0,
    size1: "4",
    size2: "4.5",
    size3: "5",
    size4: "5.5",
    size5: "6",
    size6: "6.5",
    size7: "7",
    size8: "7.5",
    size9: "8",
    size10: "8.5",
    size11: "9",
    size12: "9.5",
    size13: "10",
    size14: "10.5",
    size15: "11",
    size16: "11.5",
    size17: "12",
    size18: "12.5",
    size19: "13",
    size20: "13.5",
    size21: "14",
    size22: "14.5",
    size23: "16",
    size24: "17",
    luxury:
      "All Luxuryitems are inspected to verify authenticity (Sizes above 14 may cost more)",
    category: "Mens Shoes"
  },

Drop Down Menu
import React from 'react';
import {
  Dropdown,
  DropdownToggle,
  DropdownMenu,
  DropdownItem
} from 'reactstrap';

export default class DropDown extends React.Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      dropdownOpen: false,
      choice: 'null'
    };
  }

  toggle() {
    this.setState(prevState => ({
      dropdownOpen: !prevState.dropdownOpen
    }));
  }

  render() {
    return (
      <Dropdown isOpen={this.state.dropdownOpen} toggle={this.toggle}>
        <DropdownToggle className="bg-info" caret>
          {this.props.title}
        </DropdownToggle>
        <DropdownMenu className="bg-info">
          <DropdownItem className="bg-info" header>
            {this.props.special}
          </DropdownItem>
          {this.props.size && (
            <DropdownItem
              onClick={() => {
                this.setState({ choice: this.props.size });
              }}
              className="bg-info"
            >
              {this.props.size}
            </DropdownItem>
          )}
          {this.props.size1 && (
            <DropdownItem className="bg-info">{this.props.size1}</DropdownItem>
          )}
          {this.props.size2 && (
            <DropdownItem className="bg-info">{this.props.size2}</DropdownItem>
          )}
          {this.props.size3 && (
            <DropdownItem className="bg-info">{this.props.size3}</DropdownItem>
          )}
          {this.props.size4 && (
            <DropdownItem className="bg-info">{this.props.size4}</DropdownItem>
          )}
          {this.props.size5 && (
            <DropdownItem className="bg-info">{this.props.size5}</DropdownItem>
          )}
          {this.props.size6 && (
            <DropdownItem className="bg-info">{this.props.size6}</DropdownItem>
          )}
          {this.props.size7 && (
            <DropdownItem className="bg-info">{this.props.size7}</DropdownItem>
          )}
          {this.props.size8 && (
            <DropdownItem className="bg-info">{this.props.size8}</DropdownItem>
          )}
          {this.props.size9 && (
            <DropdownItem className="bg-info">{this.props.size9}</DropdownItem>
          )}
          {this.props.size10 && (
            <DropdownItem className="bg-info">{this.props.size10}</DropdownItem>
          )}
          {this.props.size11 && (
            <DropdownItem className="bg-info">{this.props.size11}</DropdownItem>
          )}
          {this.props.size12 && (
            <DropdownItem className="bg-info">{this.props.size12}</DropdownItem>
          )}
          {this.props.size13 && (
            <DropdownItem className="bg-info">{this.props.size13}</DropdownItem>
          )}
          {this.props.size14 && (
            <DropdownItem className="bg-info">{this.props.size14}</DropdownItem>
          )}
          {this.props.size15 && (
            <DropdownItem className="bg-info">{this.props.size15}</DropdownItem>
          )}
          {this.props.size16 && (
            <DropdownItem className="bg-info">{this.props.size16}</DropdownItem>
          )}
          {this.props.size17 && (
            <DropdownItem className="bg-info">{this.props.size17}</DropdownItem>
          )}
          {this.props.size18 && (
            <DropdownItem className="bg-info">{this.props.size18}</DropdownItem>
          )}
          {this.props.size19 && (
            <DropdownItem className="bg-info">{this.props.size19}</DropdownItem>
          )}
          {this.props.size20 && (
            <DropdownItem className="bg-info">{this.props.size20}</DropdownItem>
          )}
          {this.props.size21 && (
            <DropdownItem className="bg-info">{this.props.size21}</DropdownItem>
          )}
          {this.props.size22 && (
            <DropdownItem className="bg-info">{this.props.size22}</DropdownItem>
          )}
          {this.props.size23 && (
            <DropdownItem className="bg-info">{this.props.size23}</DropdownItem>
          )}
          {this.props.size24 && (
            <DropdownItem className="bg-info">{this.props.size25}</DropdownItem>
          )}
          {this.props.size9 && (
            <DropdownItem className="bg-info">{this.props.size25}</DropdownItem>
          )}
        </DropdownMenu>
      </Dropdown>
    );
  }
}

Dropdown Menus Parent

import React, { Component } from "react";
import { ProductConsumer } from "../context";
import { Link } from "react-router-dom";
import { ButtonContainer } from "./Button";
import DropDown from "./Dropdown";
import ItemCategory from "./ItemCategory";
import { Carousel } from "react-responsive-carousel";
import "react-responsive-carousel/lib/styles/carousel.min.css";
import { AwesomeButton } from "react-awesome-button";

export default class Details extends Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      dropdownOpen: false,

    };
  }

  toggle() {
    this.setState(prevState => ({
      dropdownOpen: !prevState.dropdownOpen
    }));
  }
  render() {
    return (
      <ProductConsumer>
        {value => {
          const {
            id,
            img,
            img2,
            img3,
            img4,
            info,
            price,
            title,
            inCart,
            size1,
            size2,
            size3,
            size4,
            size5,
            size6,
            size7,
            size8,
            size9,
            size10,
            size11,
            size12,
            size13,
            size14,
            size15,
            size16,
            size17,
            size18,
            size19,
            size20,
            size21,
            size22,
            luxury,
            special,
            category,
            fabric
          } = value.detailProduct;
          return (

              {/* ProductInfo */}

                  <Carousel autoPlay>

                  </Carousel>

                  {/* Add a Second Image */}

                {/* Product Text */}

{title}

                      price : $
                      {price}

                    <DropDown
                      title="Options"
                      special={special}
                      size={size1}
                      size1={size2}
                      size2={size3}
                      size3={size4}
                      size4={size5}
                      size5={size6}
                      size6={size7}
                      size7={size8}
                      size8={size9}
                      size9={size10}
                      size10={size11}
                      size11={size12}
                      size12={size13}
                      size13={size14}
                      size14={size15}
                      size15={size16}
                      size16={size17}
                      size17={size18}
                      size18={size19}
                      size19={size20}
                      size20={size21}
                      size21={size22}
                    />

{info}

{fabric}

                  {luxury}
                  {/* buttons */}

                    <Link to="/all">
                      <AwesomeButton
                        className="text-capitalize mx-10"
                        ripple
                        size="large"
                        type="primary"
                      >
                        Back To Products
                      </AwesomeButton>
                    </Link>

                      <AwesomeButton
                        className="text-capitalize m-auto"
                        ripple
                        size="medium"
                        type="primary"
                        cart
                        disabled={inCart ? true : false}
                        onPress={() => {
                          value.addToCart(id);
                        }}
                      >
                        {inCart ? "inCart" : "add to cart"}
                      </AwesomeButton>

                    <ItemCategory title={category} />

          );
        }}
      </ProductConsumer>
    );
  }
}

Comment: Can you show us the code you have written? Its hard to reduce something we cannot see.
Comment: Yes i have a glitch where i cant post code until i submit the question
Answer: Why not simply make the sizes an array so you can loop over them?
// In your object instead of having multiple sizes keys separately,
// have a single property called sizes
{
    id: 6.97,
    title: "Adidas Yeezy Boost 350 V2 Glow",
    img: "img/product-6.97.png",
    img2: "img/product-6.97-1.png",
    img3: "img/product-6.97-2.png",
    img4: "img/product-6.97-3.png",
    price: 800,
    info: "Adidas Yeezy Boost 350 V2 Glow",
    inCart: false,
    count: 0,
    total: 0,
    sizes:["4", "4.5", "6", "7", /*and the rest of the values*/],
    luxury:
      "All Luxuryitems are inspected to verify authenticity (Sizes above 14 may cost more)",
    category: "Mens Shoes"
  },

//Then you could simply do something like this
{this.props.yourObjectName.sizes.map((size, index)=> {
   return (
      <DropdownItem className="bg-info" key={index}>{size}</DropdownItem>
    )

})

Comment: Are the objects coming from an API? If so, is the API written by you? Then you can change the shape of the object?
Comment: By changing the shape of the object I mean, instead of putting keys like ```size1, size1``` etc, have a single key call ```sizes``` which should be an array. Then move all the values of the sizes to that array. In your given example, your object would look something like this,

```javascript
 {
 sizes:["4", "4.5", "5",.....]
}
```
I have edited my answer to show what I mean by changing the shape of the data.
Comment: Can you clarify on what do you mean by sizes corresponding with items? Isn't it an ```item``` object which contains all the sizes it comes in? I'm assuming every single object is an item, which has an array of sizes to show what sizes are available?
Comment: Well there is more than one object this is just an example
Comment: Yes it is an api it's just a data file and yes what do you mean by change the shape?
Comment: Okay but how would I know which sizes correspond with correct item?
Comment: Im sorry i was on mobile i am just now seeing the code i wil test it out and let you know thank you.
Comment: Wouldnt it be {sizes} instead of {size}


Error Divisão por 0

Question: Olá
Gostaria de uma ajuda, estou iniciando com a linguagem e estou tento algumas duvidas, O que eu quero no meu código é que o calculo da divisão não seja divido por zero. No momento que eu insiro o valor de Y = 0 retorne uma mensagem "Invalido, não pode ser divido por 0".
Quando eu faço um insert com o divisor 0 retorna essa mensagem:
Calculadora03.rb:32:in `/': divided by 0 (ZeroDivisionError)
        from Calculadora03.rb:32:in `calculo'
        from Calculadora03.rb:57:in `'

Esse é o meu codigo:
def escolha_operador
    puts "Escolha o tipo de operação abaixo:"
    puts "1 Adição"
    puts "2 Subtração"
    puts "3 Multiplicação"
    puts "4 Divisão"
    puts ""

    tipo_operador = gets.chomp().to_i

    if tipo_operador == 1
        return "Adição"
    elsif tipo_operador == 2
        return "Subtração"
    elsif tipo_operador == 3
        return "Multiplicação"
    elsif tipo_operador == 4
        return "Divisão"
    else
        return "erro"
    end
end

def calculo(operacao, x, y)
    if operacao == "Adição"
        return resultado = x + y
    elsif operacao == "Subtração"
        return resultado = x - y
    elsif operacao == "Multiplicação"
        return resultado = x * y
    elsif operacao == "Divisão"
        return resultado = x / y
    end
  # elsif operacao == "Divisão"
    #   rescue ZeroDivisionError
    #   else
    #   return resultado = x / y
  # end
end

continuar = 1

while continuar == 1

  calculo_atual = escolha_operador()

  if calculo_atual == "erro"

    puts "Opção invalido! Escolha a opção correta."

    else
    puts "Entre com o primeiro valor da #{calculo_atual}: "
    p_numero = gets.to_i
    puts "Entre com o segundo valor da #{calculo_atual}: "
    s_numero = gets.to_i

    result = calculo(calculo_atual, p_numero, s_numero)

    puts "O resultado é #{result}"
    puts "Deseja continuar o calculo? Digite 1- Sim ou 2- Não"
    continuar = gets.to_i

        system ('cls')

    if continuar != 1

    end
  end
end

Comment: Você quer subverter a matemática? Qual seria o resultado de um número dividido por 0?
Comment: A sua pergunta não é clara. Dividir por 0 é um erro que foi descoberto muito antes da invenção das linguagens de programação. Agora, se vc deseja tratar a divisão quando o divisor for 0, basta fazer um `if` antes invocar a divisão. Caso o divisor seja 0, não divida
Comment: @Amadeus desculpe eu acabei descrevendo errado mesmo a minha duvida. O que eu quero no meu código é que o calculo da divisão nao seja divido por zero. No momento que eu esteja colocando o valor de Y = 0 retorne uma mensagem "Invalido, não pode ser divido por 0".
Answer: Como o Isaque disse, coloque uma IF para o y, deve ficar assim:
elsif operacao == "Divisão"
    if y != 0
        return resultado = x / y
    else
        return "Invalido, não pode ser divido por 0"
    end
end

Então isto:
result = calculo(calculo_atual, p_numero, s_numero)

puts "O resultado é #{result}"

Vai exibir algo como:

O resultado é Invalido, não pode ser divido por 0
Answer: É uma regra da matemática, nada pode ser dividido por 0.
Em qualquer linguagem de programação irá dar erro se tentar dividir por 0.
Você pode botar um if para verificar se o divisor não é 0.
Comment: Comentei errado hehe, eu nao quero que no meu código, o calculo da divisão seja divido por 0.
Comment: @Cintia e tentou colocar a IF para verificar se o divisor é 0 como o Isaque disse?
Comment: sim @GuilhermeNascimento coloquei. Deu certo
Comment: @Cintia **que erro?** O mesmo? Se foi o mesmo é porque não fez a IF de maneira correta, mostra como você colocou essa if. Veja se assim funciona: https://pt.stackoverflow.com/a/239444/3635
Comment: @GuilhermeNascimento eu só editei a minha duvida... mas fiz conforme vc disse ...usei o IF e deu certo
Comment: @Cintia legal, se deu certo marque a minha resposta ou a do Isaque como correta (a que vc preferir)
Answer: Divisões por zero lançam uma exceção do tipo ZeroDivisionError, que pode capturada com raise e traduzida para um Float::NaN (Not A Number), veja só:
def calculo(operacao, x, y)
    if operacao == "Adição"
        return resultado = x + y
    elsif operacao == "Subtração"
        return resultado = x - y
    elsif operacao == "Multiplicação"
        return resultado = x * y
    elsif operacao == "Divisão"
        return resultado = x / y
    end
rescue ZeroDivisionError
    return Float::NAN
end

p calculo("Divisão", 1, 0 )
p calculo("Divisão", 10, 2 )
p calculo("Divisão", 70, 5 )
p calculo("Divisão", 20, -5 )

Saída:
NaN
5
14
-4

Exemplo no repl.it
Comment: na época tentei usar esse comando rescue, e não estava dando certo.. obrigado pela ajuda...
Answer: Altera o pedaço de código para isto:
def calculo(operacao, x, y)
if operacao == "Adição"
    return resultado = x + y
elsif operacao == "Subtração"
    return resultado = x - y
elsif operacao == "Multiplicação"
    return resultado = x * y
elsif operacao == "Divisão"
    if y != 0
       return resultado = x / y
    end
end

O problema é que não se pode dividir um número por zero. É uma regra matemática.
Answer: Conforme comentários acima, a regra matemática impossibilita a divisão por 0.
Assim caso você queira tentar dividir mesmo assim algum numero por 0, poderia tentar a solução
10.try(:/, 0)

onde obterá a resposta:
ZeroDivisionError: divided by 0.
Contudo lembrando que a boa prática deveria ser verificar o valor antes de tentar tal operação.

Error Divisão por 0


ASP.NET MVC 3 Preview 1 -- safe to use?

Question: MVC 3 Preview 1 just released a few days ago.
My designer isn't too familiar with C#, so ASPX view pages are sort of overwhelming for him. Razor would really help him focus on the HTML.
Considering MVC3 seems to be an incremental compatible update, it feels like it's good to go.
Usually it's considered harmful to use preview products in production, but lately I'm seeing a fair amount of it, with F# being used in banks before V1 and stuff.
Has anyone tried MVC 3 yet? Is it sturdy enough to start a project on it?
Comment: I do not believe that Preview 1 has a go-live licence, so if something goes wrong, you are most definitely on your own.
Comment: These questions baffle me.  Without telling us the level of risk your willing to undertake how can anybody answer this question?
Comment: By answering with what level of risk you think would be the threshold, maybe? I agree that it's not a perfectly technical question, but I don't think the parameters of the question are too difficult.
Answer: I wouldn't use any Preview release in a Production environment, it doesn't go through the same level of testing as even a beta release does.
Is it safe (in production), not probably not, there are unknown bugs, more than would be present in a final/tested product.  Is it safe to start developing a product on that probably won't be out until after MVC 3 final is?  Sure go nuts :) But, expect a few API adjustments along the way.
It's the same reason most larger shops wait until SP1 of a product before deploying, more time for bugs to be found/fixed.  That being said, it's totally up to you and how much risk/reward you're willing to go for.
Personally I'd wait until at least a beta, but if you're entering log-term development on a product, starting with a Preview may be more acceptable to you (I have to admit, more use of the Razor engine is a pretty good reason for that, again if it were me).
Comment: So, so tempting... but I think I'll wait for a beta.

Every company seems to have a different understanding of what "beta" and "alpha" and "preview" and "rc" and "qc" and "release" mean, so I get lost.

Thanks for the input!
Answer: It is a preview, that is, not close to production ready.
If you want to develop on it, hoping it will go into production by the time you launch, go ahead, but remember that things are likely to change, sometimes large changes sometimes subtle ones (the subtle ones are the harder ones to figure out...).
If it was me, I would wait.
Answer: In addition to the obvious risk involved in using any "Preview" software in production, I can tell you that MVC 3 Preview 1 does indeed have a couple of bugs that would be considered regression bugs (they worked in MVC 2, but now are broken).
These bugs include:

DisplayName attribute is broken -- your model's property name will be displayed instead of any value you provided via DisplayName.
While I'm not sure if this is a bug or just weirdness with my particular configuration, but my usage of strongly typed models is even broken -- when I use <%: Model.MyProperty %>, I get the following compiler error (and runtime compilation error):

Compiler Error Message: CS1061:
  'object' does not contain a definition
  for 'MyProperty' and no extension method
  'MyProperty' accepting a first argument
  of type 'object' could be found (are
  you missing a using directive or an
  assembly reference?)
Answer: Still there is a pretty big difference in asp.net mvc 1 preview 1 and asp.net mvc 3 preview 1 as asp.net mvc 3 preview 1 builds on top of asp.net mvc 2 RTM. Using mvc3 spesific features could be risky of course but you could control your use of those. I am going to switch to MVC3 to use Razor views for my new mobile views.
Answer: If you're ok with the possibility of running into a bug that might not be resolved for months (if at all), or the possibility of having to recode certain portions of your application, then yes it's ready.
I have no problem starting projects with ASP.NET MVC 3 PR1, but nothing I'm writing with it is mission critical. And nothing needs immediate deployment.

ASP.NET MVC 3 Preview 1 -- safe to use?


Basic data binding to textbox using MVVM, Entity Framework and mysql

Question: I am just starting out with WPF and MVVM. I know this question was probably asked a lot on SO but I have read everything I could find on MVVM and EF, tried every example and tutorial out there, read "How to survive MVVM for Enterprise" but I still cannot understand how to properly use the pattern and the framework for a simple bind to a textbox. Can someone please help me with an easy to understand example?
I have created a model using EF Designer. Inside my Model folder, the LocationModel.Context looks like this:
MODEL:
namespace Location.Model
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class DailyEntities : DbContext
    {
        public DailyEntities()
            : base("name=DailyEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public DbSet<LocationKPI> LocationKPI { get; set; }

    }
}

LocationKPI.cs
namespace Location.Model
{
    using System;
    using System.Collections.Generic;

    public partial class LocationKPI
    {
        public long sMonth { get; set; }
        public Nullable<decimal> Efficiency { get; set; }
    }
}

I've created a ViewModel folder with a class that implements INotifyPropertyChanged:
VIEWMODEL:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Location.ViewModel
{
    public class LocationViewModel: INotifyPropertyChanged
    {

        public decimal Efficiency
        {
            get { return _Efficienecy; }
            set
            {
                _Efficiency = value;
                OnPropertyChanged("Efficiency");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName = null)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

XAML:
<Window x:Class="Location.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Location"
        xmlns:vm="clr-namespace:Location.ViewModel"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">

    <Grid>
        <DatePicker HorizontalAlignment="Left" Margin="392,17,0,0" VerticalAlignment="Top"/>
        <TextBlock Text="Efficiency"></TextBlock>
        <TextBox Text="{Binding Efficiency}" ></TextBox>

    </Grid>
</Window>

I am really losing my mind here. I am looking for some guidance on how to "glue" the model and the viewmodel to my view and I just need a simple example to understand. I am sorry if the question is too broad.
Is the query supposed to be written in the model or the viewmodel? How do I define the data context and write a simple select Efficiency where sMonth = 9 statement using linq? How do add the month from the datepicker as a parameter to the above query? I would be so grateful for any kind of help. Thank you.
Comment: You don't write any queries on your `model` or `viewmodel`, you would have a `service` layer that will do that, that could be whatever pattern you want to adopt on your application like `Repository` pattern or `CQRS`.
Comment: Thanks for pointing that out CQRS. Can you please show me an example? It's the only way I can make sense of things.
Answer: I am going to address your MVVM issue and leave the data source for another discussion. I am going to try to give you some good habits along with showing you how to wire together you MVVM environment.
Let's start with the INotifyPropertyChanged interface and how to implement it. Generally speaking I try to create an abstract classes that both the Model and ViewModel utilize that contains everything that is common among all my models and viewmodels.  Here are those Abstract Classes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace WpfStackOverflow.Models
{
///
/// Abstract class that provides common functionality accross all View Models.
///
public abstract class modelBase : INotifyPropertyChanged
{

    #region INotifyPropertyChanged
    ///
    /// Provides a simplefied INotifyPropertyChanged interface.
    /// requires System.Runtime.CompilerServices and
    /// System.ComponentModel.
    ///
    /// <param name="property"></param>
    public void SetPropertyChanged([CallerMemberName] string property = null)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(property));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
#endregion
}

namespace WpfStackOverflow.ViewModels
{
    ///
    /// Abstract class that provides common functionality accross all View     Models.
    ///
    public abstract class ViewModelBase : INotifyPropertyChanged
    {

        #region INotifyPropertyChanged
        ///
        /// Provides a simplefied INotifyPropertyChanged interface.
        /// requires System.Runtime.CompilerServices and
        /// System.ComponentModel.
        ///
        /// <param name="property"></param>
        public void SetPropertyChanged([CallerMemberName] string property = null)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(property));
        }

        public event PropertyChangedEventHandler PropertyChanged;
        #endregion
    }
}

each class resides in a Models and ViewModels folder respectfully.
Here is the View Model I created:
namespace WpfStackOverflow.ViewModels
{
    class BasicMVVMViewModel:ViewModelBase
    {

        private ObservableCollectionEx<LocationKPI> _locations;

        public BasicMVVMViewModel()
        {
            CreateTestData();
        }

        private DateTime _selectedDate;
        public DateTime SelectedDate
        {

            get { return _selectedDate; }
            set
            {
                _selectedDate = value;
                SetPropertyChanged();
                SetSelectedLocationKPI( _selectedDate.Month);
            }
        }

        private LocationKPI _selectedLocationKPI;
        public LocationKPI SelectedLocationKPI
        {
            get { return _selectedLocationKPI; }
            set
            {
                _selectedLocationKPI = value;
                SetPropertyChanged();
            }
        }

        private void  SetSelectedLocationKPI(long sMonth)
        {
            SelectedLocationKPI = _locations.Where(p => p.SMonth.Equals(sMonth)).FirstOrDefault();
        }

        private void CreateTestData()
        {

            _locations = new ObservableCollectionEx<LocationKPI>();
            for(int i=0; i < 12;i++)
            {
                _locations.Add(new LocationKPI() { SMonth = i, Efficiency = i*17 });
            }

        }

    }
}

Finally here is the XAML Markup:
<UserControl x:Class="WpfStackOverflow.Controls.BasicMVVM"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:WpfStackOverflow.Controls"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="35"/>
            <RowDefinition Height="35"/>
            <RowDefinition Height="35"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <DatePicker HorizontalAlignment="Left" Margin="30,5,0,0"   Grid.Row="1" VerticalAlignment="Top" Width="150" SelectedDate="{Binding SelectedDate}"/>
        <TextBlock x:Name="textBlock" HorizontalAlignment="Stretch"  Grid.Row="2" TextWrapping="Wrap"
               Text="{Binding SelectedLocationKPI.Efficiency,Mode=TwoWay}" VerticalAlignment="Stretch" Margin="5"/>

    </Grid>
</UserControl>

In the Viewmodel I call a method that creates the test data.  In your case you can get your data from a linq query. (you figure it out :))
You will have to adjust some references and namespaves to fit your environment. What I posted here is tested and works.  I hope it helps you understand MVVM better. Oh yeah, one more thing, the XAML you see here is from a UserControl not a XAML Window.  In the codebehind you have to instantiate the ViewModel and set it as the DataContext:
namespace WpfStackOverflow.Controls
{
    ///
    /// Interaction logic for BasicMVVM.xaml
    ///
    public partial class BasicMVVM : UserControl
    {
        public BasicMVVM()
        {
           InitializeComponent();
           DataContext = new BasicMVVMViewModel();
        }
    }
}

Good Luck with this. StackOverflow is mostly used to solve actual coding issues. This case is actually a coding lesson. Try to avoid using StackOverflow for lessons in the future.
Comment: >>what I have read INotifyPropertyChanged should be implemented on the ViewModel and not the Model. << Depends upon your context. I often do things inside a ViewModel that requires knowing when something has changed within a model. I will create an event handler within the Viewmodel (or perhaps some other business logic class) that monitors the state of a given model. It was overkill for your situation, but I was trying to impress on you the use of an abstract class to handle common properties or methods across a group of related classes.
Comment: At this point I have invested all the free time I can in this issue.  We long ago crossed the line into tutoring instead of diagnosing a programming issue. I wish you luck on your endeavor. If you are stuck on an actual project you might consider acquiring some professional consulting from someone like myself.
Comment: >>and from what I have read INotifyPropertyChanged should be implemented on the ViewModel and not the Model. << if you want the UI to respond to changes in value of items within an observable collection, then you have to implement INotifyPropertyChanged in the model. :)
Comment: Bye the way, change the ObservableCollectionEX to just ObservableCollection.  I didn't provide the code for the subclassed ObservableCollectionEX.
Comment: Ibrahim, thank you so much for taking the time to help me. I totally agree with you regarding the lesson part but I just can find anything else that helps. Your example really compounded my confusion. I have tried using what you have provided and failed miserably. I don't really have a grasp of abstract classes and from what I have read INotifyPropertyChanged should be implemented on the ViewModel and not the Model. Where and how should I write the linq query ( Model or LocationKPI.cs)? And how do I referrence that in the ViewModel. That's all I need to get going so I can bind it to my View.
Comment: Get what I gave you working in your environment. You should only need to change namespaces to fit your project. I gave you a call to a method that creates data then populates the Treeview.  That is where I recommend you write the query that gets the data for the treeview.  What I provided in this post was tested and works. It should also work for you. If you find it to answer your needs; mark it as the answer.
Comment: Thank you for you time and guidance Ibrahim. I can't get what you gave me working in my environment and instead of making thing easier for me, it seems overly complicated for a rookie like me. I would like to mark it as the answer but it does not answer my question. After hours spent to reading books, examples and tutorial I feel like I'm losing my mind. Can you please update your answer to be specific to my example and make it simpler for me? Even the CreateTestData throws me off. Why is the query under the ViewModel and not the model or the model context?Thank you Ibrahim.
Comment: Thank you Ibrahim. You are right. I have figured it out and it works now.


JS: determine amount of occurrences in a string

Question: Is there a way to determine the number of times a letter occurs inside another string?
 if not, can you determine the number of times a string is in an array
 if you can do it with the array, how can you split 2 words, such as: Hello, World! into an array of 2 words, like this:
["Hello", "World"]

Answer: Sure.  A simple one liner that comes to mind is
var numOccurrences = str.split("<char>").length -1

where  can be replaced with whatever character (or string) you want to test for
That will split the string on each occurrence and then take the length of the resulting array -1.  Which will tell you the number of occurrences.
If you want to do it while ignoring upper/lower case, you can use regex
str.match(/<char>/gi).length

Answer: The number of times a letter occurs in a string
This can be found as follows:
"Hello World Hello World!".match(/e/g).length    // Will result in 2

/e/g is a regular expression that matches the letter 'e'. The 'g' stands for "global" and gets all the occurances in a string.
String in an array
This can be found as follows:
var arrayOfStrings = ["Hello", "World", "Hello", "World"],
    wordCount = 0,
    i;

for (i = 0; i < arrayOfStrings.length; i += 1) {    // Remember to optimise length call
    if (arrayOfStrings[i] === "Hello") {
        wordCount += 1;
    }
}

console.log(wordCount) // This will log 2

Comment: Did you actually try this?  I got TypeError: Object Hello World Hello World! has no method 'matched' when I ran it in the console.  I think you want `match`
Comment: A typo—that is what comes of making your code more terse in the editor. Thanks for pointing it out.
Comment: Be careful, if no matches are found, `match` returns `null`. So `'abc'.match('e').length` throws an error. Test the result before using it.


GAE: How to include other classes in my app engine main.py

Question: I want to use my python file, which consists of some classes in my app engine. This file is present in the root directory. When I import that file into main.py, my application is not starting - I'm getting an error:

"Error: Server Error
  The server encountered a temporary error and could not complete your request.
  Please try again in 30 seconds."

Should I set any environment variables?
How I can import and call other functions which I already have written.
app.yaml
runtime: python
env: flex

runtime_config:
        python_version: 3

entrypoint: gunicorn -b:$PORT --workers 2 main:app
manual_scaling:
        instances: 1
resources:
        cpu: 1
        memory_gb: 0.5
        disk_size_gb: 10

main.py
from flask import Flask
import sample
app = Flask(__name__)
@app.route('/')
def hello():
    return 'Hello Everyone!'

@app.route('/sample')
def foo():
    return sample.Sample()

sample.py
def Sample():
    return "hello world"

requirements.txt
Flask==1.1.1
gunicorn==19.3.0

Answer: I tested this files on my local, it worked fine and also deployed on Google Cloud, it is working fine there too.
Since it is flex environment which takes time to boot as compared to GAE standard environment ref doc
Give sometime and try again.
Answer: I see no errors within your code. Moreover, I have tested it and could deploy the app successfully.
The issue you are experiencing will require more project-specific details. Please contact the Google Cloud Platform support for a deeper investigation.
Comment: The app is deployed successfully for me as well, but when I hit the url from gcloud app browse it shows me that error.

Let me try contacting the Google Cloud Support.
Comment: @KishanKumar, I understand - what I wanted to say is that, in my case, the app was not only deployed successfully but also functioning. Both URLs `https://.appspot.com/` and `https://.appspot.com/sample` worked fine for me. I used exactly the same code/structure you provided, thus I believe that the issue lies on the project level.


QML transition changes immediately, not according to 'duration'

Question: I have the following QML file. I wan't the rectangle myRect to slide in from the right when the root item is clicked (simplified setup). What actually happens is that myRect appears immediately when the root item is clicked.
I checked the running property on the transition and that seems to be fine. It logs true when I click the root item, and then false after 2 seconds.
Does anyone know why the x property doesn't gradually change?
import QtQuick 2.7

Item{
    id: root

    MouseArea{
        anchors.fill: parent
        onClicked: {
            myRect.state = "visible"
        }
    }

    Rectangle{
        id: myRect

        width: root.width
        height: root.height

        state: "hidden"

        color: "yellow"

        states: [
            State {
                name: "hidden"
                PropertyChanges{
                    target: myRect
                    x: myRect.width
                }
            },
            State {
                name: "visible"
                PropertyChanges{
                    target: myRect
                    x: 0
                }
            }
        ]
        transitions: [
            Transition {
                NumberAnimation{
                    duration: 2000
                }
                onRunningChanged: {
                    console.log("Running:", running)
                }
            }
        ]
    }
}

Answer: You have to indicate the property, in your case "x"
NumberAnimation{
    duration: 2000
    properties: "x"
}

Comment: Thank you, that works. I actually tried that ealier, but forgot the ""


Erro: Mysql retorna o seguinte "Subquery return more than one row"

Question: Bom dia!
Criei esta query no mysql e ao adicionar a 1º subquery que chamei de "totalEscolas" recebo o seguinte erro: "Subquery return more than one row" sem esta subquery o código funciona blz.
Poderiam me ajudar? Obrigado!
<code>  SELECT qs.slot as Questao, avg(fraction) * 10 as Media, qs.quizid as Quiz, qs.questionid as QuestaoID, q.name as Descritor, SUBSTRING(u.`department`,2,4) as Nivel, SUBSTRING(u.`department`,6,1) as Turma, q.category as cat, quiz.name as Simulado,

        (Select institution
    from fhrw_user listaEscolasU

    INNER JOIN fhrw_quiz_attempts listaEscolasQa ON listaEscolasQa.userid=listaEscolasU.id
    INNER JOIN fhrw_quiz listaEscolasQ ON listaEscolasQ.id=listaEscolasQa.quiz
    where listaEscolasQ.name=$P{simulado}
    and listaEscolasU.lastname=lastname
    and SUBSTRING(listaEscolasU.`department`,1,5) = $P{nivel}
    and SUBSTRING(listaEscolasU.`department`,6,1) = $P{turma}
    and listaEscolasQa.state="finished"
    ) as listaEscolas,

    (Select count(totalAlunosQa.id)
    from fhrw_quiz_attempts totalAlunosQa

    INNER JOIN fhrw_user totalAlunosu ON totalAlunosu.id=totalAlunosQa.userid
    INNER JOIN fhrw_quiz totalAlunosq ON totalAlunosq.id=totalAlunosQa.quiz
    where totalAlunosq.name=$P{simulado}
    and totalAlunosu.lastname=lastname
    and SUBSTRING(totalAlunosu.`department`,1,5) = $P{nivel}
    and SUBSTRING(totalAlunosu.`department`,6,1) = $P{turma}
    and totalAlunosQa.state="finished"
    ) as totalAlunos,

    (select avg(fraction) * 10 as mediaPT FROM fhrw_question_attempt_steps mediaqas
    INNER JOIN fhrw_user mediau ON mediau.id=mediaqas.userid
    INNER JOIN fhrw_question_attempts mediaqa ON mediaqa.id=mediaqas.questionattemptid
    INNEr JOIN fhrw_question mediaq ON mediaq.id=mediaqa.questionid
    INNER JOIN fhrw_quiz_slots mediaqs ON mediaqs.questionid=mediaqa.questionid
    Inner Join fhrw_quiz mediaquiz ON mediaquiz.id=mediaqs.quizid
    inner Join fhrw_school mediaschool ON mediaschool.IdEscola=mediau.lastname
    where
    SUBSTRING(mediau.`department`,1,5) = $P{nivel}
    and SUBSTRING(mediau.`department`,6,1) = $P{turma}
    and mediaq.category = 7
    and mediaquiz.name=$P{simulado}
    and mediau.lastname=lastname
    and mediaqas.state!="todo"
    and mediaqas.state!="complete") as mediaGeralPT,

    (select avg(fraction) * 10 as mediaPT FROM fhrw_question_attempt_steps mediaqas
    INNER JOIN fhrw_user mediau ON mediau.id=mediaqas.userid
    INNER JOIN fhrw_question_attempts mediaqa ON mediaqa.id=mediaqas.questionattemptid
    INNEr JOIN fhrw_question mediaq ON mediaq.id=mediaqa.questionid
    INNER JOIN fhrw_quiz_slots mediaqs ON mediaqs.questionid=mediaqa.questionid
    Inner Join fhrw_quiz mediaquiz ON mediaquiz.id=mediaqs.quizid
    inner Join fhrw_school mediaschool ON mediaschool.IdEscola=mediau.lastname
    where
    SUBSTRING(mediau.`department`,1,5) = $P{nivel}
    and SUBSTRING(mediau.`department`,6,1) = $P{turma}
    and mediaq.category = 8
    and mediaquiz.name=$P{simulado}
    and mediau.lastname=lastname
    and mediaqas.state!="todo"
    and mediaqas.state!="complete") as mediaGeralMT,

    (select avg(fraction) * 10 as mediaPT FROM fhrw_question_attempt_steps mediaqas
    INNER JOIN fhrw_user mediau ON mediau.id=mediaqas.userid
    INNER JOIN fhrw_question_attempts mediaqa ON mediaqa.id=mediaqas.questionattemptid
    INNEr JOIN fhrw_question mediaq ON mediaq.id=mediaqa.questionid
    INNER JOIN fhrw_quiz_slots mediaqs ON mediaqs.questionid=mediaqa.questionid
    Inner Join fhrw_quiz mediaquiz ON mediaquiz.id=mediaqs.quizid
    inner Join fhrw_school mediaschool ON mediaschool.IdEscola=mediau.lastname
    where
    SUBSTRING(mediau.`department`,1,5) = $P{nivel}
    and SUBSTRING(mediau.`department`,6,1) = $P{turma}
    and mediaquiz.name=$P{simulado}
    and mediau.lastname=lastname
    and mediaqas.state!="todo"
    and mediaqas.state!="complete") as mediaGeral

    FROM `fhrw_question_attempt_steps` qas

    INNER JOIN fhrw_question_attempts qa ON qa.id=qas.`questionattemptid`
    INNER JOIN fhrw_quiz_slots qs ON qs.questionid=qa.questionid
    INNER JOIN fhrw_user u ON u.id = qas.userid
    INNER JOIN fhrw_question q ON q.id=qa.questionid
    Inner Join fhrw_quiz quiz ON quiz.id=qs.quizid
    inner Join fhrw_school school ON school.IdEscola=u.lastname

    where
    quiz.name=$P{simulado}
    and u.lastname=lastname
    and SUBSTRING(u.`department`,1,5) = $P{nivel}
    and SUBSTRING(u.`department`,6,1) = $P{turma}
    and state!="todo"
    and state!="complete"

    group by qa.questionid
    ORDER BY `Questao` ASC
</code>
Comment: Seu sub-select está retornando mais de 1 registro, coloque no começo: `SELECT TOP 1 ......(resto da sql)`, ou ajuste seu sub-select para retornar apenas 1 valor.
Comment: @MaxRogério, obrigado por responder!
A questão é que não gostaria de trazer apenas um registro, mas todos os registros da coluna "institution" da tabela "fhrw_user" isso é possível?
Nesta coluna são registradas as escolas que estão cadastradas, gostaria de trazer todas que realizaram determinado quiz
Comment: Então você terá que fazer o join com essa tabela (lembrando que pode-se repetir o join na tabela, é só mudar o alias), e depois fazer o tratamento da visão dos dados na sua aplicação ou o que estiver usando. Agora até onde eu sei(não sei muito), com subquery é necessário retorna somente 1 valor.
Comment: @MaxRogério eu achei que este join já fosse suficiente:
`INER JOIN fhrw_quiz_attempts totalEscolasQa ON totalEscolasQa.userid=totalEscolasU.id`

`INNER JOIN fhrw_quiz totalEscolasQ ON totalEscolasQ.id=totalEscolasQa.quiz`

Tenho que fazer ainda outro?
Comment: Como disse, se você quiser retornar mais de um valor "Instituiton", recomendo fazer JOIN ou repensar sua consulta...
Comment: @MaxRogério obrigado pela ajuda, mas não entendi este JOIN
Answer: Adicione um GROUP_CONTAT para retornar as escolas em apenas uma linha, a sua subquery está retornando mais de 1 linha.
<code>(Select
     GROUP_CONCAT(institution SEPARATOR ',')
from fhrw_user totalEscolasU
INNER JOIN fhrw_quiz_attempts totalEscolasQa ON
totalEscolasQa.userid=totalEscolasU.id
INNER JOIN fhrw_quiz totalEscolasQ ON totalEscolasQ.id=totalEscolasQa.quiz
where totalEscolasQ.name=$P{simulado}
and totalEscolasU.lastname=lastname
and SUBSTRING(totalEscolasU.`department`,1,5) = $P{nivel}
and SUBSTRING(totalEscolasU.`department`,6,1) = $P{turma}
and totalEscolasQa.state="finished"
) as totalEscolas,
</code>
Comment: @arliondias
Acho que minha query acabou confusa, onde tem totalEscolas na verdade seria listaEscolas, pois não quero apenas contar mas listar as escolas. vou editar a pergunta
Comment: Você quer fazer todas as somas por escola, ou as somas em um geral e apenas listar as escolas? @MiguelSilva
Comment: As somas necessárias eu já consigo fazer, a query funciona, só não estou conseguindo listar as escolas, só falta mesmo listar as escolas
Comment: eu indico que retorne na mesma linha então, usando o GROUP_CONCAT, separando por ",". ai ficaria assim: GROUP_CONCAT(institution SEPARATOR ','), vou editar minha resposta. @MiguelSilva
Comment: Vou testar, uma dúvida, no tratamento dos dados usando Ireport é possível substituir as virgulas por uma quebra de linha?
Comment: Aí já não vou saber te responder, porém se você souber o que ele espera para quebrar linha, você pode colocar no separator do group_concat e testar por exemplo GROUP_CONCAT(institution SEPARATOR '\r\n'), algo assim. Abs


Create content types containing other content-types

Question: I've created a custom content-type called "Books."
I need to create another content type named "Catalogs" which may contain one/many "Books" as its fields.
How would I achieve that? I'd prefer some GUI tool to construct my custom content type, from admin panel, or doing some coding, if necessary.
PS: I found this question asked here but the solution did not help. Can someone provide a detailed answer, please?
EDIT:
MohammadAliAkbari's answer works perfectly :) One problem - When adding "Books" a user can add Books not created by him - he can add any Book to his "Catalog" - How can I add constraints such that a user can add Books only created by him to his Catalog?
Solution:
Using Tenken's answer, I figured out that I can write this code in my module to solve the scenario just mentioned above:
function myModule_form_alter(&$form, &$form_state, $form_id) {
//    dsm($form_id); // Use this line to find YOUR-DESIRED-FORM-ID
    switch ($form_id) {
        case 'YOUR-DESIRED-FORM-ID':
            $form['#validate'][] = 'stylesku_add_sku_form_validate';
//            dsm($form); // Use this to find out form's elements
            global $user;
            $currentUser = $user->uid;
            $fieldSku = $form['FIELD-ID-OF-BOOK'];
            $lang = $fieldSku['#language'];
            $fieldOptions = $fieldSku[$lang]['#options'];
            foreach($fieldOptions as $nid=>$nodeTitle){
                if(!is_int($nid))
                    continue; // Needed as the first option in select box is not really any book
                $nid = (int) $nid;
                $n = node_load($nid);
                if($n->uid != $currentUser){
                    // Remove this BOOK, this book was not created by current user
                    unset($form['FIELD-ID-OF-BOOK'][$lang]['#options'][$nid]);
                }
            }
            break;
    }
}

Answer: Ok, you should be familiar with

entity
view mode
entityreference

after install entityreference create a reference to books in your catelogs content-type, then go to catelogs > manage display and for books reference select Rendered entity formatter and in its options set something like teaser
after this go to books > manage display and configure teaser as you need.
also you can add more view modes by Display Suite or via simple module:
function mymodule_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['render_in_catelogs'] = array(
      'label' => t('render in catelogs'),
      'custom settings' => FALSE,
  );
}

Comment: Thanks @MohammadAliAkbari that works perfectly :)

One problem - When adding `Books` a user can add Books not created by him - he can add any Book to his `Catelog`

- How can I add constraints such that a user can add `Books` only created by him to his `Catelog`?

Thanks in advance for helping...
Comment: some hacks near `protected function buildEntityFieldQuery(...` is needed in `entityreference/handler/base.inc`
Comment: Hacking will ruin it, being unable to update the module later. Is there any other elegant solution? Thanks
Comment: entityreference not allow other solution (I think), so you can add this feature and commit it in drupal.org, you should add some setting in widget form and some conditions in buildEntityFieldQuery based on field instance setting
Comment: I've created an issue at EntityReference's page... I'm waiting for their response, then I'll try!
Answer: I can see 2 options to build upon @Akbari's advice ...

the easy way hook_form_alter to change the select options to be limited to entityreference node values owned by the end-user. Alter the node submit validate function to assure its one the user owns. So this attempt would just edit the $form item using FAPI tweaks ... you can use FAPI '#element_validate' option to set a validate function for the selected $book.
the really hard way ... which might work as @Akbari suggested ... you need to alter EntityReference_SelectionHandler_Generic::buildEntityFieldQuery() somehow. I recommend using hook_field_info_alter() to supply your own $info['entityreference']['handler'] key in the field info that extends the base class with your own and overrides the buildentityinfo logic with "ownership" logic. You will probably need to make the entityreference ctools plugins aware of your custom handler (somehow) ... an example using hook_field_info_alter can be found in this blog post (not mine) ...
Comment: Thanks Tenken! I'd really like to go with option 1 - I'll try and ask again here if I'm in trouble!
Comment: Thanks @Tenken, option 1 works perfectly, I added my code in my question. I tried to manipulate the form using malicious data - and it seems that Drupal can figure out if any user is trying to change form's select box's information. So do I really need to add a validate handler?
Answer: You can use the Multifield or Field Collection module.
Answer: You can use node reference cck field.
Node reference is a CCK field by which you can create some relationship between the two content types. At the time of creation a catalog you can assign book nodes to the catalog and make it multivalued so you can assign one or more book nodes to the catalog content type.
Comment: I can't find any such field, do I need to install some module for that?

Attaching a screen-shot.

http://dl.dropbox.com/u/9053005/hosted/screen-casts/Drupal/content-type-fields.png
Comment: See this http://www.youtube.com/watch?v=CpUoVNt8O4s
Comment: CCK is not a Drupal 7 concept.
Comment: In Drupal 7, the core part of CCK has been implemented as field API. CCK still have a Drupal 7 release, but it is only for updating from Drupal 6 to Drupal 7, and for implementing the extra fields that have not moved to Drupal core.


How to formulate a formula using logistic regression

Question: So I used SPSS for the possible RGB of fire and I got this as a result.
How do I make a formula to predict the possibility of fire using another set of data (RGB)
I tried using the formula P = -14.039 + (0.101*red) + (0.034*green) + (-0.119*blue)  but I keep getting answer above 1 or below 0. I thought the answer should be in between 0 and 1?
Answer: See the Wikipedia page, or a statistics textbook. The equation obtained in logistic regression is for a function of the probability, the log-odds (logit), not the probability itself. Other so-called "link" functions are possible in related generalized linear models, however, so check the manual for your statistics program to be sure you are doing standard logistic regression based on the logit.


Linux routing by requested name

Question: I've asked this on another SE site, but I don't think I was clear enough. So, I will try it here. As an example - I have 2 domains (acme.com, ajax.com). Both resolve to my single static IP. Meanwhile, my router routes all port 22 traffic (SSH) to a Linux server (192.168.1.21). What I would like to do (if this is possible) is to make acme.com THE url for SSH. I realize all of the traffic is routed to .21 (the router doesn't know about names), but is there some way to instruct Linux to reject port 22 requests when the name requested is ajax.com? In other words, is there any way to ask Linux to see the entire request?
Or perhaps the SSHd can do this? (shot in the dark)
Thanks in advance for any advice.
Comment: Typically you are not supposed to re-post identical questions on SE, it violates the FAQ for SF and many of the other SE sites as well.  Do you mind providing a link to the old question please?
Comment: Please do not cross-post. If a question should be on a different site we can migrate it. I've requested your other question be closed as this one has a better answer.
Answer: No.
When you ssh to acme.com, clients PC resolves it to an IP address, and ssh just connects to that IP. It never sends the domain name to the sshd on the server.
Comment: @aserwin: In the HTTP case, it's handled by the HTTP protocol. DNS and the router have nothing to do with it. The SSH protocol has nothing comparable, so there's no way to do it with SSH. The information is just never sent.
Comment: Your browser also sends the "Host" (the domain) in the request (starting from http 1.1 i think). SSH doesnt. Very old browsers dont. Ftp doesnt. VPN's dont. bittorrent doesnt. ping doesnt. ....
Comment: When traffic comes into the server on port 80, the daemon parses the request by name. You can have several domain names coming to the same IP address... Why can't SSH read this information?
Comment: Yes, but webservers are not ssh. With webservers it's practical (economical) to have more then one page on one server, and to separate them with vhosts. With ssh you usually dont need separation.. there is no practical need for it (except security-through-obscurity).
Comment: BTW, virtualhosts are not that old, and AFAIK virtualhosts with ssl are/were still unsupported with IE on WinXP.
Comment: Security is what I crave... but that is my point. The information is there, in the request... I just have a hard time believing there is no way I can get at it.
Comment: @aserwin To parse on name info the name info needs to be send in the first place. That just is not standard. HTTP is the weird one out.
Comment: I guess I don't understand that... Does the router know to pass the name? Or does that happen at the DNS level? (I didn't think DNS knew about port)
Comment: @DavidSchwartz that makes a lot more sense. The protocol itself. I had noticed that I can telnet to a web site on port 80 and get the same information as I can when I browse to it with a web browser... Thanks for that.
Comment: Turns out it might be possible after all! http://serverfault.com/questions/329529/virtual-hosts-for-ssh
Comment: @aserwin That's a horrid question, running two different services on different ports isn't even close to the same things as virtual hosts. If you ran two copies of Apache with different websites, one on port 80 and the other on 81 nobody would know to put the "81" in the address and for practical purposes it wouldn't be usable. The "Answer" to that question talks about setting up a SSH gateway, which still isn't the same, it's just creating a second connection based on username (which caries plenty of problems and unexpected behavior).
Comment: @Chris S - I am not talking about running more than one service... I am talking about limiting the ways one can get to a service.
Comment: And I am not sure I am buying the argument that the name isn't sent. You can clearly see that logging into a linux system via SSH, when prompted for you password, you are identified as 'username@ip' OR 'username@name'... so CLEARLY SSH has some idea of how it was accessed.
Comment: "I am not sure I am buying the argument that the name isn't sent" - Ok, [here's the source code repository](http://www.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/), read the code for yourself if you don't believe us. That prompt is client side too, the server has no idea what the client program is doing at that time.
Comment: That prompt is a program on the server called login, which is launched by a program called getty. It is not client side.

Linux routing by requested name


K value vs Accuracy in KNN

Question: am trying to learn KNN by working on Breast cancer dataset provided by UCI repository. The Total size of dataset is 699 with 9 continuous variables and 1 class variable.
I tested my accuracy on cross-validation set. For K =21 & K =19. Accuracy is 95.7%.
<code>from sklearn.neighbors import KNeighborsClassifier
neigh = KNeighborsClassifier(n_neighbors=21)
neigh.fit(X_train, y_train)
y_pred_val = neigh.predict(X_val)
print accuracy_score(y_val, y_pred_val)
</code>
But for K= 1, I am getting Accuracy = 97.85% K = 3, Accuracy = 97.14
I read

Choice of k is very critical – A small value of k means that noise will have a higher influence on the result. A large value make it computationally expensive and kinda defeats the basic philosophy behind KNN (that points that are near might have similar densities or classes ) .A simple approach to select k is set k = n^(1/2). (Here.)

Which value of K should I consider for my model. Can you guys elaborate the logic behind it?
Thanks in advance!
Comment: You would consider k as a hyperparameter of your algorithm and chose the best possible hyperparameter by crossvalidation. There is no valid rule of thumb for chosing k, since the ideal k varies depending on domain and data.
Answer: Nikolas is right. The way to go about it is to do something like cross validation with different Ks, and chose the k that minimizes the cross validation error.
Comment: Hi @filipe
I tested accuracy on cross-validation data and these results are tested on that data only.
Comment: Hi Rahul. In that case, I guess it stands to reason, that K=1 is the value that leads to the best generalization accuracy.
However, maybe another concern is the issue of class imbalance. If you have a class imbalance (one of the classes is far more frequent than others), then "Accuracy" may not be the best error metric.
Answer: Given that its cancer data (which inherently has class imbalance), F1 score (not accuracy) will be the correct metric to use. Here's wiki for more on F1 score. It basically lets you chose how you want to relatively weigh Precision and Recall.
Small changes to K in training set can lead to large changes in decision boundary so you'll need to cross validate and see if the results generalize well.

K value vs Accuracy in KNN