Algorithm for finding prime numbers of specific form

Question: Given the natural number $n$,who is in the form $p^2 \cdot q^2$,with $p$,$q$ prime numbers.Also $φ(n)$ is given.Describe a fast algorithm(polynomial time) that calculates the $p$ and $q$.Apply your algorithm to calculate the $p$,$q$ when $n=34969$ and $φ(n)=29920$
I found this problem on a mathematical competition on cryptography.I  tried to find a solution alone and in the internet and i didn't conclude anywhere, can we find a solution?
Answer: Hint:
$$\phi(n) = n^2 - n(p+q) - pq$$
Answer: Since $n$ is a perfect square, $pq = \sqrt{n}$. Now, as for the $\phi$ function:
$$ \phi(p^2 q^2) = \phi(p^2)\phi(q^2) = (p - 1)(q - 1)pq$$
Thus, $$\dfrac{\phi(n)}{\sqrt{n}} = (p - 1)(q - 1) = pq - p - q + 1$$
And thus, you get:
$$\sqrt{n} - \dfrac{\phi(n)}{\sqrt{n}} + 1= p + q = p + \dfrac{\sqrt{n}}{p}$$
Multiply both sides by $-p$:
$$p^2 - p\left(\sqrt{n} - \dfrac{\phi(n)}{\sqrt{n}} + 1\right) + \sqrt{n} = 0$$
Let's try your example. Since $n = 34969$ and $\phi(n) = 29920$, then $\sqrt{n} = 187$ and the equation we have to solve for $p$ is:
$$p^2 - p\left(187 - \dfrac{29920}{187} + 1\right) + 187 = 0$$
If we simplify:
$$p^2 - 28p + 187 = 0$$
The solutions are $p = 11$ and $p = 17$. Actually, due to the symmetric relation between $p$ and $q$ in our previous equation, these two solutions for $p$ happen to be the solution for the pair $(p, q)$. You'd notice that $pq = 187$ if we assign $p = 11$ and $q = 17$.
So, an efficient algorithm is to solve the quadratic equation. The solution for the pair $(p, q)$ is then just both roots of the equation. This is $\mathcal{O}(1)$.
Comment: why it is not $φ(n)=n^2-n(p+q)-pq$?
Comment: @paris My solution makes that sort of implicit.


Does anybody know how to add the remove button in a custom module (field type) with unlimited number of values?

Question: I am trying to add my custom field/module to a content type. I select Unlimited for the Allowed number of values option in Field Settings and I am able to Add another Item, however there is no remove button. Furthermore, each time I edit the content; an extra (blank) field is added.
Comment: Both issues seem to be connected, your field is not able to detect a blank line and so doesn't know when to remove or not save a line.
Comment: @4k4 how can I resolve this?
Comment: The custom field type needs to return a correct answer in the class method  `isEmtpy()`.
Comment: and does that need to be in the FieldType FieldFormatter or FieldWidget?
 I'm not exactly sure how this error came about. All the other fields such as imagefield work fine. can you please give me an example/outline of how to go about this.
Answer: The custom field type has to implement a method which tells whether the field is empty (if the inherited default method is not able to do this).
For example for a numeric field:
NumericItemBase::isEmpty()
  public function isEmpty() {
    if (empty($this->value) && (string) $this->value !== '0') {
      return TRUE;
    }
    return FALSE;
  }

Comment: That didn't do it :(
Comment: Then you have to debug how blank lines are submitted. What happens with the value and why it isn't detected as empty when it reaches `isEmpty()`).
Comment: That actually did it. I forgot to change the value to my variable. Thanks a lot :)


Url problem due to htaccess

Question: I uploaded my website here . But when I check the url it doesn't change when I click another page. I used the Rewritebase in my .htaccess to have clean urls. The url should be like kantoorleenknegt.be/contact ....
Comment: You don't need RewriteBase to generate clean URLs. That's purely used if the site is running in a virtual document root. It's worth noting that your site isn't redirecting. Also, can you post the relevant directives? You should be able to do this with the default Drupal .htaccess file unless you're making significant changes to it.
Answer: This is not really a drupal question. You are seen the website through a frame
The real url is http://184.108.40.206/~leenkneg/ where the urls work as expected.
To answer your question after the info you gave.
One solution is to add an A record to the DNS of the domain. So every http traffic will land to your site but without the users notice and the can have the emails where they want.
So you will have the hosting and the can keep the emails.
Comment: So the problem lays with my domainname?
Comment: You have a domain name (kantoorleenknegt.be) that have an index page with just a frame that show the real location of your site(/~leenkneg/). If you move your site from the /~leenkneg/ to the targeted domain it should work just fine!
Comment: the domain name kantoorleenknegt.be is redirected to http://18.104.22.168/~leenkneg/
Comment: How you have done the migration?
Comment: I don't have the ownership of the domain name. I juste designed the page and gave the url http://18.104.22.168/~leenkneg/ so the domain is linked to the ftp where the site is.
Comment: I think the professional think to do is to tell them to give you access to the ftp.domain.de so you can upload the site and after that you have to create the database.Import from the one you have now and change the settings.php to reflect the new db.
Comment: that is not possible because i'm in charge of the hosting. they only have the domain because of the mailboxes.
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient [reputation](http://drupal.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](http://drupal.stackexchange.com/help/privileges/comment).
Comment: I contacted my provider, the problem wasn't on my server but on the domain name, they used an iframe to redirect the page. They had to change te dns and normally it should work.
Comment: i'm glad it finally worked!

Url problem due to htaccess


Is anyone familiar with the instrument called the mellertion?

Question: Does anybody know about the mellertion? As far as I know, it's a synthesis instrument. But that is all I have found. I need information for a college assignment.
Comment: Do you mean "mellotron"?
Comment: I seem to recall that mellertion is the feeling you get when you can't identify a melody.  Possibly  I dreamt that. It's hard to know.
Comment: Seems it did exist, made in 1933. Nothing else appears...
Comment: Disappointing:  igtfy and there's even a wikipedia entry.  A number of books mention this chimera as well.
Comment: No. It is "Mellertion". There is a quote in wikipedia. https://en.wikipedia.org/wiki/Electronic_musical_instrument but i couldn't find more information
Comment: Google 'Mellotron', and many sites turn up. Made in B'ham England 1963,
Answer: An electrical instrument built in 1933, divided into a ten-division octave, instead of twelve. Billed as 'Altogether new types of melodies, far beyond the range of our present musical experience, emanate from this instrument'.
The decimal version of music? Sometimes known as Mellerton. Obviously didn't catch on... , but good for 'playing in the cracks'.
Comment: https://books.google.com/books?id=8Bk5AAAAIAAJ&q=mellertion&dq=mellertion&hl=en&sa=X&ved=0ahUKEwiXnMugw5PWAhWp34MKHUgeAzcQ6AEIJjAA
Comment: I found it in one of my 'bibles' - The Oxford Companion to Music.
Answer: I read too quickly and assumed you meant the Mellotron. But it appears that you are asking about a different early electronic instrument, the Mellertion, and @Tim has given the correct answer. Since before realizing my mistake I wrote up an answer for Mellotron than might be of interest, I'll leave it here meanwhile...
If you are actually asking about the Mellotron, it was early sort of synthesizer, apparently developed in the early 1960s in Great Britain. See Mellotron.
The Mellotron's chief claim to fame is that the Beatles used it on Strawberry Fields Forever. Hear it here: Strawberry Fields Forever - Restored HD Video - one of the greatest and most innovative Beatles/John Lennon songs in their catalogue. It was recorded in late 1966 and released in early 1967 see: Strawberry Fields Forever. The Mellotron was used to create a very "far out - psychedelic" sort of sound, kind of a cross between a flute, an organ and a hurdy-gurdy, if you will...

It was reportedly the idea of Paul McCartney to use it, and he plays it on that recording. The opening bars are played with a Mellotron and you can hear it throughout the whole song. That Mellotron was part of the very distinctive sound signature of that song, helping considerably to make it the huge hit that it became.
Although McCartny-George Martin (their producer, known as "the 5th Beatle") brought the Mellotron into the Strawberry Fields Forever recording, the song is among Lennon's signature works, synonymous today with the name John Lennon among Beatles aficionados, to the point that in Central Park NYC - close to Lennon's home, where was shot in 1980 - there is a garden/meadow supposedly frequented by Lennon when he lived there, and is today named Strawberry Fields in his memory.

The Beatles also used the Mellotron on other later songs, and typically, various other rock groups followed in their footsteps during those years.
Here are some interesting links and info:
The Mellotron (1965)
Paul McCartney demonstrates the Mellotron
The Beatles - Strawberry Fields Forever (Mellotron Tutorial)


Windows certificate import not accepting private key password

Question: I'm trying to follow the instructions provided here: https://codekabinett.com/rdumps.php?Lang=2&targetDoc=create-install-ssl-tls-certificate-sql-server for setting up a self-signed certificate for use in testing. I was able to successfully create the certificate and key and convert them into a .pfx file. Now I'm trying to actually import that pfx to the local machine using the certificate import wizard. After selecting the file, it asks for the password for the private key. I assume that this is either the password chosen when creating the cert or when converting to pfx. Either way, it will not accept the password. I double checked to make sure I wasn't typing it wrong. I deleted all the files and recreated them using the same password for both. Still rejected. At this point I'm not sure what else to try. What am I missing here?
FYI, here are the commands I used to generate the files:
openssl req -x509 -newkey rsa:4096 -keyout C:\Users\pbuchheit\sqlkey.pem -out c:\Users\pbuchheit\sqlcert.pem -days 3650 -extensions server_ssl

openssl pkcs12 -export -out C:\Users\pbuchheit\sqlcert.pfx -inkey C:\Users\pbuchheit\sqlkey.pem -in C:\Users\pbuchheit\sqlcert.pem

Update:
The problem seems to have something to do with the pfx file. If I try no install a normal certificate (.crt) file it works fine. Could the password be getting deleted or changed when converting the crt and key into a pfx?
Comment: It should be the 'Export' password given to `openssl pkcs12 -export`; if the password for the PEM file was different that has no effect on the pkcs12. Does it contain any non-ASCII character(s)? If so openssl uses 'console' I/O with old-style codepage, while the wizard is a GUI with native Unicode, which likely produces different bytes for the same keystrokes and thus doesn't work; try commandline `certutil` or powershell `import-pfxcertificate` (with `convertto-securestring`)
Comment: @ dave_thompson_085 The password is letters only. I just went through the process again and tried using 'password' as the export password. It still rejects it when I try to do the import.
Answer: I finally found the answer here: https://stackoverflow.com/a/70369871/1860222. Apparently, the import wizard was giving garbage feedback and the problem had nothing to do with the password. As it turns out, openssl defaults to an encryption that is not compatible with Windows 10. Once I explicitly set the encryption for the pfx to something windows could handle, the import worked fine.
The final command ended up looking like this:
openssl pkcs12 -export -certpbe PBE-SHA1-3DES -keypbe PBE-SHA1-3DES -nomac -out C:\Users\pbuchheit\turadev.pfx -inkey C:\Users\pbuchheit\turadev.key -in C:\Users\pbuchheit\turadev.crt


Consulta usando Entityframework porquê a performance variação?

Question: Eu tenho as seguintes querys usando Linq to Object:
_Context.GerenciaTransacao.Where(x => x.Placa == "LUN1320").ToList();

nesta query, os resultados retornam em 100ms.
e
string placa = "LUN1320";

_Context.GerenciaTransacao.Where(x => x.Placa == placa).ToList();

já nesta, os resultados levam cerca de 3min para chegarem. Porquê essa variação tão grande?
eu preciso passar o valor em forma de parâmetro, mas não consegui resolver.
   SELECT
"Extent1"."ID_GERENCIA_TRANSACAO" AS "ID_GERENCIA_TRANSACAO",
"Extent1"."COD_TRANSACAO" AS "COD_TRANSACAO",
"Extent1"."DSC_TRANSACAO" AS "DSC_TRANSACAO",
"Extent1"."PARTE_FIXA" AS "PARTE_FIXA",
"Extent1"."PARTE_VARIAVEL" AS "PARTE_VARIAVEL",
"Extent1"."RETORNO" AS "RETORNO",
"Extent1"."NM_USUARIO" AS "NM_USUARIO",
"Extent1"."HOST_ACESSO" AS "HOST_ACESSO",
"Extent1"."DT_ALTERACAO" AS "DT_ALTERACAO",
"Extent1"."PLACA" AS "PLACA",
"Extent1"."CHASSI" AS "CHASSI"
FROM "DETROWEB"."TPL_GERENCIA_TRANSACAO" "Extent1"
WHERE ('LUN1320' = "Extent1"."PLACA")

Sql gerado no primeiro caso.
SELECT
"Extent1"."ID_GERENCIA_TRANSACAO" AS "ID_GERENCIA_TRANSACAO",
"Extent1"."COD_TRANSACAO" AS "COD_TRANSACAO",
"Extent1"."DSC_TRANSACAO" AS "DSC_TRANSACAO",
"Extent1"."PARTE_FIXA" AS "PARTE_FIXA",
"Extent1"."PARTE_VARIAVEL" AS "PARTE_VARIAVEL",
"Extent1"."RETORNO" AS "RETORNO",
"Extent1"."NM_USUARIO" AS "NM_USUARIO",
"Extent1"."HOST_ACESSO" AS "HOST_ACESSO",
"Extent1"."DT_ALTERACAO" AS "DT_ALTERACAO",
"Extent1"."PLACA" AS "PLACA",
"Extent1"."CHASSI" AS "CHASSI"
FROM "DETROWEB"."TPL_GERENCIA_TRANSACAO" "Extent1"
WHERE (("Extent1"."PLACA" = :p__linq__0) OR (("Extent1"."PLACA" IS NULL) AND (:p__linq__0 IS NULL)))

Sql gerado no segundo caso.
Answer: O problema foi resolvido adicionando em cima da propriedade o atributo:
[Column("PLACA", TypeName = "varchar2")]

obrigado a todos que colaboraram.


Devo pedir a senha do usuário duas vezes no momento do cadastro?

Question: Nos formulários de cadastro, é comum ver o campo "Digite sua senha novamente", como uma confirmação para ter certeza de que o usuário não errou a senha digitada.
Pensando na experiência do usuário, esse campo é realmente necessário? Pensando nas heurísticas de Nielsen, pra esse caso, não existe uma convergência entre "prevenção de erros" (heurística 5) e "estética e design minimalista" (heurística 8)?
Como aplicar a heurística de prevenção de erro nesse caso? Não seria um botão de "esqueci minha senha" no caso do usuário ter digitado errado? Ou seria mesmo o campo de "digite sua senha novamente"? E por que?
Essa etapa de confirmação adiciona algum fator de segurança para o fluxo? Novamente em segurança, se meu formulário tiver esse campo, eu deveria estar fazendo essa confirmação no lado do cliente, no lado do servidor, ou em ambos?
Note que não procuro opiniões sobre o assunto, mas respostas concretas, com fontes confiáveis, e bem embasadas em termos de UX.
Comment: A maioria das pessoas digita com os indicadores e lentamente :D, ainda mais com a decadência do uso de computadores em detrimento de celulares. Mas eu concordo com você, é algo bem complexo de ser resolvido. Eu pessoalmente _prefiro_ colocar o segundo campo de confirmação, mas não tenho nenhum embasamento na perspectiva de UX para isso.
Comment: Particularmente, creio que um campo com o "olho" para revelar a senha já serviria como uma confirmação. Mas e se o usuário estiver com alguém do lado e não puder clicar ali? Não é um assunto tão simples quanto parece, envolve muitas variáveis.
Comment: @RafaelTavares, o que impede o "usuário do lado" olhar o cara digitando a senha? Acaba dando na mesma... :-]
Comment: @LuizFelipe se for no celular, pode dar na mesma, se for no computador / notebook, não. Vai depender da velocidade que a pessoa digita, quantos dedos ela usa ao digitar, a mão estar na frente das teclas etc. Fora que se alguém estiver sentado atrás de mim por um motivo X aceitável, ela pode não conseguir me ver digitando mas conseguir ver a tela. Enfim, muitas variáveis, não é algo tão simples. Já participei de uma palestra onde o apresentador digitou uma senha com o tablet conectado no projetor e todos puderam ver o que ele digitava mesmo com o campo *****, são diferentes situações.
Comment: O propósito é evitar definir uma senha que foi digitada errado por engano, me parece uma boa prática de segurança, pense em quantos problema de "perdi minha senha", ou mesmo "digitei meu email errado" (sim, para aqueles casos que tens de confirmar tbm o email), é um protocolo de confirmação perfeitamente aceitável
Answer: Toda resposta sobre UX tem que começar com aquele blablablá de que você tem que conduzir estudos, analisar seu público, etc.
Feito isso e para dar um parâmetro eu vou recorrer ao UX.SE que é um dos lugares onde mais tem pessoas especializadas no assunto e lá vi algumas respostas.
A conclusão majoritária é que não deve pedir. Mas tenho medo de ser uma percepção apenas porque foi a resposta aceita e por causa disso ela recebeu muitos votos.
Um dos motivos apresentados é que as pessoas burlam isso e acabam copiando automaticamente, então o mecanismo pode não funcionar porque a pessoa "digita" errado nas duas e ainda cria uma dificuldade para a pessoa que é desnecessária.
O que recomenda-se é ter outras formas de resolver o problema caso a pessoa não lembre a senha ou tenha digitado ela errado e não está funcionando. De um jeito ou de outro você precisa ter esse mecanismo, então deixe só ele.
A ideia é que é mais usável quando você só crie um fardo para a pessoa se ele cometeu mesmo um erro e está tendo problemas por isso. O sistema de recuperação de senha (que não devolve a senha mas deixa você trocar) é mais efetivo. Você paga só se precisar. Quando você pede para a pessoa digitar duas vezes você paga mesmo fazendo tudo certo, e pode ter que pagar de novo depois.
Note que não é unânime, algumas pessoas apresentam problemas dessa abordagem, então tem que ser bem pensado.
Um dos problemas que disseram é que a pessoa pode estar com o CAPS LOCK ligado, mas você deveria detectar isso e avisar a pessoa antes de digitar. UX é pensar em resolver cada problema com a ação certa, somos engenheiros até fazendo UX. Engenheiro acha a melhor solução para cada problema, não segue receita de bolo.
Também reclamaram que teria que deixar a senha visível para a pessoa conferir, mas isso não deve ser feito, deve ter a opção de tornar visível em dado momento e aí a pessoa escolhe fazê-lo se ela se certificou que ninguém está vendo ou ela não liga para isso.
Não adianta forçar as pessoas fazerem algo que elas não querem, elas darão um jeito de fazer errado se o errado for melhor para ela.

Algo que é recomendado até para confirmar o e-mail é a pessoa precisar clicar no link enviado para confirmar que o e-mail está certo e que não é um uso indevido de um endereço. Tem várias formas de lidar com isso. É uma boa ideia.
Um problema que existe mesmo é que a pessoa pode não perceber que errou e não saber depois o que fazer, e o seu site não ter nenhum indicativo disso, você poderia perder o usuário. É algo para se pensar. Realmente acontece em alguns cenários. Por isso não tem solução mágica universal que funciona sempre e está livre de problemas.
Um  argumento interessante para usar esse mecanismo é que ele é tão amplamente usado que as pessoas já não se importam mais. O que acha? Eu sei que as pessoas odeiam esses processos de sign up.
Uma solução pode ser usar um autenticador externo e evitar isso. Tem seus problemas, não deve ser a única forma, mas mata sua dúvida para a maioria dos casos.
Segurança
Outra solução que obviamente tem seus defeitos é não pedir senha para a pessoa digitar. Resolve outros problemas de segurança. Gere uma para ele, é essa que ele deve usar. Ele que use um gerenciador, anote no caderninho ou peça a "recuperação" toda vez que for entrar, o que é quase um two factor authentication, exceto que ele esqueceu um dos fatores :D, mas esse é um mecanismo mais forte do que só saber a senha.
Não ache que é mais seguro pedir a senha duas vezes, pode ser mais confiável que a pessoa digitou certo, mas não 100% confiável, muito menos seguro.
O que pode acontecer quando você pede uma digitação apenas e deixa a pessoa ver é que talvez ela digite mais facilmente senhas mais longas e difíceis. Quando você cria dificuldade para ela digitar algo ela tenderá digitar coisas menores e mais simples, e isso pode afetar a segurança em algum grau. Novamente, a pessoa burlará sua "proteção".
Acessibilidade
Não vi ninguém em lugar algum que eu pesquisei discutindo esse aspecto. Curioso né?
Talvez pedir duas vezes ajude quem precisa de acessibilidade porque é, provavelmente, a única forma dela conferir se digitou certo de forma a não expor a senha (a outra seria a senha digitada ser falada, mas aí todo mundo perto pode escutar). Mas há casos e casos.
Então talvez deveria ser opcional digitar ou não.
Concluindo
É fácil achar falácias em todas essas opiniões, até porque ela viu um problema, mas talvez ele não seja tão relevante assim.
Todos os casos apresentados lá têm seus problemas, escolha seu veneno. De fato essas regrinhas apresentadas na resposta tem algum grau de dicotomia, e talvez seja até proposital, você tem que escolher qual regra é mais importante. Só não descarte soluções criativas, até mesmo de adotar ambos de alguma forma opcional. Não estou dizendo que é bom, mas não siga uma receita única, experimente, crie!
Algumas coisas eu tenho meio claro o que costuma compensar mais, mas essa não. Talvez mude muito pouco, sem pensar em um público específico.
Alguns links para acompanhar mais discussões e artigos de gente que trabalha com isso:

UX Movement
Nielsen Norman Group (sua referência) - é mais amplo do que esse ponto, mas deve ajudar
UX Stack Exchange - gerou boas discussões nessa pergunta também
CLX - muita gente high profile falou lá

Coloquei no GitHub para referência futura.


Closed surface integral

Question: I've been practicing questions on past exams to prepare for my upcoming one, but they didn't come with solutions and one question has really got me stuck:
"Consider $\iint\limits _S \vec F . d \vec S$, where $\vec F =xcos^2(\pi z)\hat i +2ycos(\pi x)\hat j +xy^2\hat k$ and S is the surface of the box $0\ge x, y, z \ge 2$. Calculate the integral. You may use one of the integral theorems if you wish."
(That's supposed to be the surface integral of a closed surface at the beginning, but I couldn't work out how to format that)
If anyone could help with the solution it'd be greatly appreciated!
Comment: Argh, that should be "0 ≤ x,y,z ≤ 2"
Answer: Since: (1) $S$ is piecewise smooth closed surface, (2) the cube is connected, and (3) $F$ has continuous partials, you can apply the Divergence theorem.
$$\iint_S F \cdot dS = \iiint_E \text{div}(F) \, \mathrm{d}V.$$
The divergence is straightforward to calculate:
$$\text{div}(F) = \cos^2(\pi z) + 2\cos(\pi x).$$
Now it is just a matter of computing a messy triple integral. Note that $E$ in my integral in the first line is the unit cube, so we use the nice bounds on $x$,$y$, and $z$.
$$\iint_S F \cdot dS = \iiint_E \text{div}(F) \, \mathrm{d}V = \int_0^2 \int_0^2 \int_0^2 \cos^2(\pi z) + 2\cos(\pi x) \, \mathrm{d}x \, \mathrm{d}y \,\mathrm{d}z = 4.$$
A good take-away from this problem is that you should try to apply the 3 classical vector analysis theorems as much as possible to simplify calculations. Computing the surface integral along each of the 6 surfaces of the cube would be quite inefficient. Be sure to check if the hypotheses are satisfied, however.

Closed surface integral


S.O.S my Upright Piano keys aren'r working

Question: please someone help me! I have an ED.SEILER upright wood piano with ivory keys, that's from 1911 (so it's 106 years old) and some of the black keys stopped working! It was working perfectly like a week ago! I'm in major panic! What do I do???
Comment: Call a technician.
Comment: @Tetsujin said the main the thing. But if you manage to open the piano lid, check to see if some of the hammers are out of place. If they are, gently tap them to help them get back into place. Some times in old pianos the return mechanism gets stuck and the hammers rest out of place, it may or may not be your case. If the hammers don't respond to a gentle tap, DON'T FORCE them (yeah, call the technician) .
Answer: Did you do anything between the black keys working and them not working?  Like moving the piano, or taking the front off to 'have a look' and maybe also have a fiddle?  Or might someone else have?  This can happen when the action has been taken out and not replaced properly.
Anyway, you won't do any great harm by removing the front panel and having a look.  Is everything in place?  Has anything fallen into the piano?  Are some notes 'stuck'?   But if there isn't an obvious simple solution, call a piano tuner/technician.  Don't risk further damage by poking around beyond your capabilities.


Qual a diferença entre os métodos de string find() e index() em Python?

Question: Eu sempre uso o método index() para buscar o índice de um caractere em uma string em Python. Recentemente, descobri o método find() e notei que ele faz exatamente a mesma coisa. Exemplo:
name="Alan Turing"

print(name.index(n))
print(name.find(n))

Ambos retornam 3.
Existe alguma diferença nesses métodos que não estou conseguindo enxergar?
Answer: Eles servem para o mesmo propósito, a diferença está na semântica quando ocorre um erro por não achar o que estava procurando.
O find() retorna a posição -1, portanto depois de fazer a busca você deve testar se o resultado foi esse antes de fazer qualquer operação com ele, porque se não for um valor positivo, provavelmente não é o que desejava. Ele é melhor usado quando se espera que não ache o alvo em algumas situações, ou seja, a operação é um valor inválido, porém que há chance de acontecer, você sabe disso.
O index() gera uma exceção se não achar, e só não quebrará a aplicação se ela for tratada. Aí a maioria das pessoas pensarão: "então é só tratar". Pode ser em alguns casos, mas provavelmente de uma forma genérica, porque isso é um erro de programação ou algo muito fora do esperado. Esse método só deve ser usado quando você sabe que o que procura sempre será achado, portando se não achar é um problema sério na aplicação. Então use e confie que achou, se não achar, deixe a aplicação quebrar, ou trate antes pra ficar bonitinho, mas não tome decisões de regras de negócios com essa exceção.
Quando eu vejo coisas desse tipo eu percebo que em alguns momento Python tentou tomar a decisão certa sobre o uso de exceção. Pena que nem sempre é assim.


Solving Chinese Remainder Theorem Help

Question: I need some help finishing up this CRT calculation. So far I have
$$x\equiv 0 \pmod {49}$$
$$x\equiv -1 \pmod {121}$$
$$x\equiv -2 \pmod {169}$$
$$x\equiv -3 \pmod {289}$$
$$x\equiv 53424 \pmod {190969}$$
so first I choose to solve
$$x\equiv -3 \pmod {289}$$
$$x\equiv 53424 \pmod {190969}$$
So I used the extended euclidean alg to find the solution to
1 = 190969*s + 289*t
and got 1 = 190969(-53) + 289(35022)
so then $$1\equiv 289*(35022) \pmod{190969}$$
and then
x = 289k - 3
$$289k\equiv 53427 \pmod{190969}$$ ?
But I get stuck at this point and can't properly find x?
Comment: This appears to be a duplicate of your prior two questions.
Answer: We write $x=53424+m\times 190969$ and we want to find $m$ so that $x\equiv -3 \pmod {289}$.  Thus we want $$248+229m\equiv -3\pmod {289}\implies 251 \equiv 60m\pmod {289}$$  This is easily solved to get $m\equiv 9\pmod {289}$
Finally we get $$x= 53424+9\times 190969 = \boxed {1772145}$$
Comment: im sorry how did you get 248 + 229m = -3 mod 289?
Comment: $x=53424 + 190969m$ and $53424 \equiv 248$, $190969\equiv 229$.
Comment: also I dont understand how you got 251 = 60m I swear everyhwere I look people do the CRT differently im so confused
Comment: As a suggestion:  you seem to be struggling with the basic operations of modular arithmetic.  Given that, why work such a messy problem?  Start with smaller numbers and build up from there.
Comment: Im not sure how I am supposed to solve this then the numbers get so big and almost impossible to work with
Comment: That's why I propose working with smaller numbers until you gain confidence.  To be clear:  $289$ is fairly small!  A bit outside comfort zone with pen and paper, but only a bit.  You ought to be able to solve $ax+b\equiv c \pmod {289}$.  Focus on that first.
Answer: Here is a method for k residues $(a_i)$ and k modulus $(m_i)$. Let $m=m_1 m_2 \cdot \cdot \cdot m_k$ and consider $m/m_1$. This is relatively prime to $m_1$, so there exists an integer $t_1$ such that $t_1\cdot m/m_1 \equiv 1 $ (mod $m_1$). Accordingly, let $s_1=t_1\cdot m/m_1$. Then $s_1 \equiv 1$ (mod $m_1$) and $s_1 \equiv 0$ (mod $m_j$), $j\not =1$. Similarly, for all i, there exists an $s_i$ such that $s_i \equiv 1$ (mod $m_i$) and $s_i \equiv 0$ (mod $m_j$), $j\not =i$. Then $x=a_1s_1+a_2s_2+...+a_ks_k$ is a solution for the system.
You already had $m_1=289$, $a_1=-3$, $t_1=-53$ and $m_2=190969$, $a_2=53424$, $t_2=35022$. Therefore, $x=35022\cdot 53424+ (-3)\cdot(-53)=1871015487$
But $190969(-3)+289(35022)=9548451$ so the numbers you gave must be wrong.

Solving Chinese Remainder Theorem Help


I had a webform Application with .net 4 Framework and downgrade to .net 2.0 Framework System.Web.Script.Services.ScriptServices not define

Question: I wrote a WebForm Application with .net 4 framework everything work fine. At the time of publishing they told me that the server only supports 2.0. When I change the target framework to 2.0 I had the error:
Type 'System.Web.Script.Services.ScriptService' is not defined. I have seen some other examples like here but nothing very concrete on how to fix it. Any help would be really appreciated.
Answer: You are likely to run into other issues as well because the web.config differs between 4.0 and 2.0 as well.
When I am forced to downgrade from 4.0 to 2.0 I usually create a new web project as 2.0 and pull in the .aspx and .aspx.cs I need from my other project's file system.
Then if I referenced anything in a .cs or .vb I can manually edit.
This assumes you weren't actually using any 4.0 features.
(create a new 2.0 project with web.config and pull everything in manually to that project from the other project)
Comment: I did made some changes like I had to change my listview for a repeater. So there is no way to change something on the configuration of the project to make it work ?
Comment: No sorry. Not that I know of. But all of that markup for your listview is retained when you copy the page etc.. Give it a shot. I just did it to verify.


Cardinalities and injective function between two infinite sets

Question: Let $A$ and $B$ two infinite sets and let $|A| = m$ and $|B| = n$ and also suppose that $m > n$. Also suppose that $g$ is an injective function from $B$ into $A$. For each of the following sets, find its cardinality $(m, n, 2^m \mbox{ or } 2^n)$ and prove your answer.
1) $S_{1} = \{f\in B^A : |f(A)| = 1 \}$.
2) $S_{2} = \{ f\in B^A : |f(A)| = 2 \}$.
3) $S_{3} = A - g(B) $
I am trying to solve this exercise but i seem to struggle a lot on proving the cardinality of the above sets.
Comment: For each of *which* following sets?
Comment: I just added the sets.
Answer: Hint:  The first one asks how many functions from $A$ to $B$ there are where every element of $A$ is mapped to the same element of $B$.  That is what $|f(A)|=1$ means.  How many functions like that are there?  The second asks how many functions from $A$ to $B$ there are where every element of $A$ is mapped to one of two elements of $B$.  How is this different from $S_1?$  What do you think $S_3$ means?
Comment: Thank you for your response. We know that in general, each element in $A$ has $n$ choices to be mapped to $B$, where each choice is a function. So the total number of functions from $A$ to $B$ is $n^m$. So for the first one there exist $n$ functions. Is that right? Now, for the second one, are there $2^m$? but how can I prove that?
Comment: You are right for the first.  For the second, you first have to choose the two elements of $B$  that are the image, then you choose which one each element of $A$ goes to.  Yes, you should wind up with $2^m,$ but you need to show that by a chain of reasoning to show the choices of elements in $B$ don't matter.  If $B$ were  larger than $2^m$ the argument would fail.
Comment: I don not seem to understand your argument on how to prove this. My thought is that there are $2^m$ functions from $A$ to $B$ mapping 2 or less $b_{0} \in B$. But these functions include the ones that map only one element of $B$.So the there are $2^m - m$ functions with this property. Which part of this is wrong?
Comment: @Angela your arguments seem to more or less ignore the fact that we are dealing with infinite sets. What does it mean for a set to have $2^m-m$ elements if $m$ is an infinite cardinal?
Comment: Yes!You are right!So, in order to prove the second one, we need to map a 2 element set $B$ to a $m$ element set $A$. We can do that by $2^m$ different ways, all beginning with two elements, 1 and 2. This is just a different combination of mappings over $B$. Is that right? Also, in the last set, are we looking for the non surjective functions?
Comment: Be more careful with your wording.  We are mapping the $m$ element set $A$ to a two element  subset of $B$, which we can do in $2^m$ ways.  If the sets were finite, you would have more choices because of selecting the two elements of $B$, but with $n \lt m$ that doesn't increase the number.  That is a big part of the argument you are supposed to make.  For the last part, there is just one function $g$.  You are supposed to count the elements of $A$ that are left after we delete the range of $g$
Comment: Ok, since the set $A$ is infinite, then by deleting some elements, it would still be infinite and so the cardinality of $S_3$ is $m$. Is that true?
Comment: That is true because you are given that $m \gt n$.  If $|A|$ were $n$ we couldn't tell.  It could be $0$, it  could be $n$, it could be anywhere in between.
Comment: Thank you so much for your help!


Creating a calendar in PHP

Question: Are there any APIs or libraries that make it easy to generate a calendar for a certain month/year? I need to have some sort of admin interface for a "event planner" part of a CMS for a local youth group and I'm at a loss as to how to generate a decent calendar.
Note: I only need something to generate the calendar HTML, not manage events. I'll be coding that part.
Comment: APIs generally don't come with full admin interfaces. If you want an admin system, why not just use Google Calendar and export it to your site?
Comment: I mean I'm coding my own admin interface but for the "events" part I want to have a calender that displays all the events for the month and then the admin would click a link to edit it. I only need to have something generate the html for the calender
Answer: Two Spring to Mind

PHP Calendar - Free
Easy PHP
Calendar - Paid ($29.99 per
domain) but a lot slicker than PHP
Calendar
Answer: I ended up using a jQuery plugin instead. Thanks for the suggestions
http://plugins.jquery.com/project/fullcalendar

Creating a calendar in PHP


Integral representation of a Meijer G-function

Question: How to prove that, the integral
$$I_{a,b}:=\int_{1}^{+\infty}e^{-at}(1-t^{-1})^b\,dt ; \, a,b>0$$
 is given by   $\Gamma(b+1)$ times a Meijer G-function, i.e.,
$$I_{a,b}:=\Gamma(b+1) \times G^{m,n}_{p,q}(a_1,...,a_p; b_1,...,b_q/ z),$$
where $m,n,p,q,a_i,b_i$ and $z$ to be determined ?
Thank you in advance
Answer: $\int_1^\infty e^{-at}(1-t^{-1})^b~dt$
$=\int_1^\infty t^{-b}(t-1)^be^{-at}~dt$
$=\int_0^\infty(t+1)^{-b}t^be^{-a(t+1)}~d(t+1)$
$=e^{-a}\int_0^\infty t^b(t+1)^{-b}e^{-at}~dt$
$=e^{-a}\Gamma(b+1)U(b+1,2,a)$ (according to http://en.wikipedia.org/wiki/Confluent_hypergeometric_function#Integral_representations)
$=\dfrac{e^{-a}}{\Gamma(b)}G_{1,2}^{2,1}\left(a\,\middle|\begin{array}~~-b\\0,-1\end{array}\right)$ (according to http://functions.wolfram.com/HypergeometricFunctions/HypergeometricU/26/02/01)


WebApiConfig.Register is not run

Question: I had an ASP.NET MVC project* that was created when VS 2013 first came out. (Aside: how do I find out the MVC version used for an existing project?).  I have it now opened in VS 2015 and added a Web API 2 controller.
A static WebApiConfig class was added by VS. However, the Register method wasn't called. As a result, my api route is not recognized.
How/where can I call the WebApiConfig.Register method and what is the parameter that has to be passed to this method?

* This is the version where there is an App_Start folder with BundleConfig.cs, FilterConfig.cs, IdentityConfig.cs, RouteConfig.cs, StartupAuth.cs, WebApiConfig.cs.
Answer: As stated in this post, you should use GlobalConfiguration.Configure and not WebApiConfig.Register for any new (or migrated) Web API 2 project:
protected void Application_Start()
{
    GlobalConfiguration.Configure(WebApiConfig.Register);
    //MVC Registrations
}

Also be sure to update any NuGet Package in your project to the last version.
Comment: Thanks. This solved the problem.  Both the normal MVC and api routes work nicely.
Comment: Applies to Web API 1.  Web API 2 does not work this way.  If you created project with Visual Studio 2017 or your Web API project uses .NET Core 2, then you probably use Web API 2 and this is not the solution.
Answer: In your Global.ascx.cs
using System.Web.Http;

protected void Application_Start()
{
    //other stuff
    //update: do not use WebApiConfig.Register(GlobalConfiguration.Configuration)
    GlobalConfiguration.Configure(WebApiConfig.Register);
}

how do I find out the MVC version used for an existing project?

What MVC does it reference? ie what is the version number of theSystem.Web.Mvc assembly which your web project will reference
Comment: I have just added more information in my question regarding the project type. In my `Application_Start`, `GlobalConfiguration` is not in scope. Where can I find this class or object?
Comment: add `using System.Web.Http;`
Comment: Thanks. If I put `WebApiConfig.Register` before `RouteConfig.RegisterRoutes`, the browser in debugger mode will just close by itself.  If I reverse the sequence, things seem to be normal, but /api/xx still give a 404. What could still be wrong?  *BTW, my System.Web.Mvc has a `Runtime Version` of v4.0.30319 and a `Version` of 184.108.40.206 as seen in Properties.)
Comment: yes so you are using mvc5. (runtime version is the version of the *framework* itself, ie .NET4 CLR in this case) - re: your 404, pls see my answer on mixing web api and mvc http://stackoverflow.com/questions/34371613/exposing-a-few-calls-from-an-existing-asp-net-mvc-site-to-other-rest-clients-wit/34584670#34584670

as per that link `WebApiConfig.Register` shld be before `RouteConfig.RegisterRoutes` - i'm not sure what you mean by 'close by itself' <-- you should break on Exceptions or figure out why its doing that -
Comment: The browser closed because the server had a 500 error had pushed out `Content-Type:application/xml;` An error has occurred.

WebApiConfig.Register is not run


WP Query - Unable to query by category slug

Question: I have four categories in my Custom Post Type of "projects" that are 'live', 'heal', 'work', and 'play'.  I have a few 'projects' posts with no category that I would like to omit from the archive page.  In my archive, my query is as follows:
<code>     <?php $args = array( 'post_type' => 'projects','post_status' => 'publish', 'posts_per_page' => $projects_number, 'paged'=> $paged, 'category_name' => 'work,play,live,heal'); ?>
        <?php $wp_query = null; ?>
        <?php $wp_query = new WP_Query( $args ); ?>
            <?php if ( $wp_query->have_posts() ) : ?>
</code>
But my archive is not returning any projects. I also tried the 'cat' parameter with id's but no avail there either.  What am I missing?
Answer: For anyone who comes across this...the 'category' argument needed to be in its own array


Linear Algebra - independent vectors or not

Question: Determine if the vectors $(1,1,1,0),(0,-1,-1,1),(1,0,-1,1),(1,0,-2,1)\in \mathbb{R}^4$ are linearly independent and they can be used as a base for $\mathbb{R}^4$.
How I solved this?
Well, first I let $$x(1,1,1,0) + y(0,-1,-1,1) + z(1,0,-1,1) + c(1,0,-2,1)  = (0,0,0,0).$$
So, it's about solving equations system following:
\begin{align}
x+z+c&=0\\
x-y&=0 \\
x-y-z-2c&=0\\
 y+z+c&=0
\end{align}
Then, I got $x = 1 , y = 1 , z = -2$ and $c = 1$.
Is that correct?
Comment: Yes, that means that they are linearly dependent. Notice that any common scalar multiple of $x, y, z$ and $c$ will also give a linear dependence relation among the vectors. Do you now know whether they can be used as a basis for $\mathbb{R}^4$?
Comment: they cant be used as a basis for R^4 because they are linearly dependent, but please can you confirm if x = 1 , y = 1 , z = -2 and c = 1 got correct numbers ? thank you.
Comment: Indeed, because $x,y,z, c \neq 0$ you know that they are not linearly independent. The answer $x = 1 , y = 1 , z = -2$ and $c = 1$ is the correct one.
Comment: Thank you guys for the help <3
Answer: Expanding on what BRIC-Fan said the reason this work is because when you have the sets (1,1,1,0),(0,−1,−1,1),(1,0,−1,1),(1,0,−2,1) $\in R^4$ to know its linearly indepedent you need to get a linearly to show that the only solution to the given equation a(1,1,1,0) + b(0,-1,-1,1) + c(1,0,-1,1) + d(1,0,-2,1) = 0 is the trivial solution i.e that a = b = c = d = 0;
This corresponds to 4 equations with 4 unknowns
a + c + d = 0
a - b = 0
a - b - c -2d = 0
b + c + d = 0
So putting this into matrix form we get
\begin{pmatrix} 1 & 0 & 1 & 1 \\ 1 & -1 & 0 & 0 \\ 1 & -1 & -1 & -2 \\ 0 & 1 & 1 & 1 \end{pmatrix}
times the coefficient matrix and that is equal to 0, so to show it has solution it must be invertible so that is why you need to calculate the determinant!
Comment: or another way is just do row-reduced echelon form and you either get the 4x4 identity hence the only solution for the coefficients are 0 or if its Linearly dependent you will find it won't row reduce to the 4x4 identity.
Answer: Hint: calculate $\text{ det }\begin{pmatrix} 1 & 0 & 1 & 1 \\ 1 & -1 & 0 & 0 \\ 1 & -1 & -1 & -2 \\ 0 & 1 & 1 & 1 \end{pmatrix}$, and if its $0$, then they are dependent, if not they are independent.
Comment: Does i need to use gaussian elimination here or i calculate like this 1+0+1+1 = 3 and so on?


While function stuck on first block of if-elif-else

Question: I'm trying to code a small pomodoro-timer, it uses a while loop with an if-elif-else statement to check which timer to start.
As expected it starts with the first if-block and then modifies the variable, I would expect it to go the elif-block after that, however it seems to be stuck in the if-block. And doesn't reiterate the entire while loop code.
How to overcome this?
import os
import time

pomodoro = ['Pomodoro', 1500]
short_break = ['Short Break', 300]
long_break = ['Long Break', 1800]
pomodori_count = 0

def countdown(time_frame):
    duration = time_frame[1]
    while duration:
        os.system('clear')

        mins, secs = divmod(duration, 60)
        timer = '{:02d}:{:02d}'.format(mins, secs)

        print(f"{time_frame[0]} | {timer}")
        time.sleep(1)
        duration -= 1

while True:
    last = ""

    if last != "Pomodoro":
        countdown(pomodoro)
        last = "Pomodoro"
        pomodori_count += 1
    elif pomodori_count % 4 != 0:
        countdown(short_break)
        last = "Short Break"
    else:
        countdown(long_break)
        last = "Long Break"

Comment: That's not how it works. As soon as *one* condition evaluates to `True`, the entire `if/elif/else` statement completes. I think the `elif` should simply be `if`.
Comment: But on the second iteration, it shouldn't evaluate to ```True```, since it modified the variable ```last```.
Comment: Oh: you rest `last = ""` at the top of each loop. That should probably go *before* the loop.
Answer: So what is wrong with this code is that you reset the last value in each repeat of the while loop, so it never persists its state for the next cycle.
You should declare the variable before the while loop to fix this issue
last = ""
while True:

    if last != "Pomodoro":
        countdown(pomodoro)
        last = "Pomodoro"
        pomodori_count += 1
    elif pomodori_count % 4 != 0:
        countdown(short_break)
        last = "Short Break"
    else:
        countdown(long_break)
        last = "Long Break"


Change option of sass-loader in vue.config

Question: I am confused how to change sass-loader settings using vue.config in this documentation there is a webpack.config but my project doesn't have one and I don't think I should have one because according to this documentation I should use vue.config.
The command vue inspect contains the string loader: 'sass-loader', 8 times so I'm not sure what to change.
My source code is the following:

Then I would like to adjust the values for webpack using vue.config to:
    {
      loader: 'sass-loader',
      options: {
        prependData: '$alert: ' + process.env.ALERT_COLOR + ';',
      }
    }

I suspect I have to change the following entry (coming from vue inspect):
    /* config.module.rule('scss').oneOf('vue-modules') */
    {
      resourceQuery: /module/,
      use: [
        {
          loader: 'vue-style-loader',
          options: {
            sourceMap: false,
            shadowMode: false
          }
        },
        {
          loader: 'css-loader',
          options: {
            sourceMap: false,
            importLoaders: 2,
            modules: true,
            localIdentName: '[name]_[local]_[hash:base64:5]'
          }
        },
        {
          loader: 'postcss-loader',
          options: {
            sourceMap: false
          }
        },
        {
          loader: 'sass-loader',
          options: {
            sourceMap: false,
            implementation: {
              run_: function() {
                        return _call(f, Array.prototype.slice.apply(arguments));
                      },
              render: function() {
                        return _call(f, Array.prototype.slice.apply(arguments));
                      },
              renderSync: function() {
                        return _call(f, Array.prototype.slice.apply(arguments));
                      },
              info: 'dart-sass\t1.23.0\t(Sass Compiler)\t[Dart]\ndart2js\t2.5.1\t(Dart Compiler)\t[Dart]',
              types: {
                Boolean: function() {
                          return _call(f, Array.prototype.slice.apply(arguments));
                        },
                Color: function() {
                          return _call(f, this, Array.prototype.slice.apply(arguments));
                        },
                List: function() {
                          return _call(f, this, Array.prototype.slice.apply(arguments));
                        },
                Map: function() {
                          return _call(f, this, Array.prototype.slice.apply(arguments));
                        },
                Null: function() {
                          return _call(f, Array.prototype.slice.apply(arguments));
                        },
                Number: function() {
                          return _call(f, this, Array.prototype.slice.apply(arguments));
                        },
                String: function() {
                          return _call(f, this, Array.prototype.slice.apply(arguments));
                        },
                Error: function Error() { [native code] }
              }
            }
          }
        }
      ]
    }

Answer: Reading through the docs you linked I would guess it's something like this:
vue.config.js
module.exports = {
  chainWebpack: config => {
    const cssRule = config.module.rule('css')

    // clear all existing loaders.
    // if you don't do this, the loader below will be appended to
    // existing loaders of the rule.
    cssRule.uses.clear()

    // add replacement loader(s)
    cssRule
      .use('sass-loader')
        .loader('sass-loader')
        .tap(options => {
          // modify the options...
          return options
        })
  }
}

And add the sass options you want were is says modify the options.
It's worth noting that cssRule.uses.clear() will clear the previous CSS rules. Which I think you will need to do otherwise you might have conflicting rules. If you find that it is removing a rule you need, I would add it back manually (the same way you are adding sass.
Comment: I cannot confirm if that works but I went with [this solution](https://vueschool.io/articles/vuejs-tutorials/globally-load-sass-into-your-vue-js-applications/). Thank you for your answer and I'll give it a go later and let you know if it worked.
Answer: The following seems to work, in my vue.config
const path = require('path');
module.exports = {
  css: {
    loaderOptions: {
      sass: {
        data: `
          @import "Theme/_colors.scss";
        `,
      },
    },
  },
  configureWebpack: {
    resolve: {
      alias: {
        Theme: path.resolve(
          __dirname,
          `src/themes/${process.env.THEME || 'light'}/`
        ),
      },
   },
  },
};

In _colors.css I can just set the variables: $alert:red;


How to filter nodes using date field

Question: I have a content type of "Class" that has a date field attached to it field_class_date.
When a node of the type "Class" is viewed, I would like to display links to other classes that are on the same day of that particular class.
I tried doing this with views, but couldn't quite figure it out.
Answer: To solve this, (1) I placed code in node--class.tpl.php which retrieved the current class date
$date = entity_metadata_wrapper('node', $node)->field_class_date->value->value();

Then, (2) I modified that value to get the start of the day and the end of the day ($start and $end) in the following format: Y-m-d H:i:s
(3) Perform a query using EFQ to grab a list of the nodes that share the same date:
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'class')
  ->fieldCondition('field_class_date', 'value', array($start, $end), 'BETWEEN')
  ->fieldOrderBy('field_class_date', 'value', 'ASC');
$result = $query->execute();

(4) Loop through each result and create the content I want to display later in node--class.tpl.php
foreach($result['node'] as $i) {
  $node = node_load($i->nid);
  $date = entity_metadata_wrapper('node', $node)->field_class_date->value->value();
  $name = entity_metadata_wrapper('node', $instructor)->field_class_instructor->value();
  // Build a string of output that I want to display later in the $content array
  $classes_today = etc...
}

(5) Finally, I added the $classes_today string to the $content array:
$content['more_classes']['#prefix'] = '
Classes on this Day:

';
$content['more_classes']['#markup'] = $more_classes;
$content['more_classes']['#weight'] = '4';
$content['more_classes']['#suffix'] = '
';

Answer: Hi for this you can simply place a filter for date field in your view.

Select Operator as " Is equal to" and then type "NOW" in the selection for filtering.
This should filter down your class content as per present/current date.
Comment: I don't want to filter classes to "NOW."  I want to filter them to the date of the class node being viewed, which is specified by field_class_date, which is attached to all classes.
Comment: oh all right...

How to filter nodes using date field


Migration from Joomla

Question: I am going to start work on a website that is already developed in Joomla 1.5
What are the possible ways to migrate the contents from Joomla.
PS: I have looked into joomla module but no luck!
Any ideas will highly be appreciated!
Comment: I have also used a sandbox module joomla2drupal which is based on migration but it is not working either
Answer: I've used Feeds and Menu Export/Import to migrate Joomla sites to Drupal a few times. It's a little tedious but it works.
I think the next time I have to migrate  Joomla site to Drupal I will use the Joomla to Drupal module. It doesn't appear to be regularly updated but looks like it should work for Joomla 1.5 and less. I don't think it will be useful for Joomla 2.x and up though.
Comment: Do I need to have joomla site setup on my local machine or we can migrate it from remote site as well - @awasson
Comment: If you use the Joomla to Drupal module, you can migrate from Joomla from a different server but the Drupal site needs to be able to access the Joomla database and file system (to copy the files).
Comment: I am using the same module, I can't access the file path as I don't have ftp. I have used ninja explorer plugin in joomla to find configuration and db info.
http://i.imgur.com/UDuEZqU.png
How can I find path of Joomla installation
Answer: You can use Migrate module which provides a flexible framework for migrating content into Drupal.
There is one GitHub project available at piyuesh23/joomla_drupal which has already some Drupal classes to migrate Joomla into Drupal.
For more technical details, check Joomla related Issues for Migrate or example code of migrating images, setting url, alt, title in prepareRow.

If you'd like to avoid coding classes, alternatively check Joomla to Drupal module or XJoomla at GitHub.

Migration from Joomla


Add image file programmatically in drupal 6

Question: i want to upload an image on my site. I have a custom form in a module with
  $form['picture'] = array(
  '#type'   => 'file',
  '#title'  => t('Avatar'),
  '#prefix' => 'picture . '">'
  );

  $form['#validate'][] = 'product_validate_picture';

and in my validate fucntion :
$validators = array('file_validate_extensions' => array('jpg png'),
                    'file_validate_image_resolution' => array('500x500'));

$file = file_save_upload('picture', $validators);
dsm($file);

The problem is that i do not get the picture returned by the form, i only get "0" which is an error. So, did i do something wrong, or another method is better to get and save a picture returned by a custom form?
Thanks.
Answer: This is not good job save file in validation phase and really  where you get file from posted data ?
file exist in $form_state['value']['picture]
mybe below code help you
function yourmodule_form_submit($form, &$form_state) {

    $file = $form_state['values']['picture'];

    $validators = array();
    $file = file_save_upload('file', $validators, 'public://');
....

Comment: @Clive I didn't notice that he using drupal 6. :(
Comment: Sorry but this is incorrect - Both Drupal 6 and 7 use validate handlers to move/save uploaded pictures. See [`user_validate_picture()`](https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_validate_picture/6)
Comment: It's the same for Drupal 7, uploaded files get handled in the validate handler then persisted in the submit handler. "Incorrect" might be too strong, perhaps better to say that this isn't the "best" way to do it, simply because core does things differently. This will still work. I think semantically this _does_ belong in the validation step, because it's validating the picture whilst saving
Comment: @Clive  yes,I agree with you.tnx :)
Comment: I did not want to use it into the validate, but i search for example and everywhere, they validate it before sending it to the form_submit. As you suggest in the other post, i'll try to change the right on the folder and save it into my node from there. thx
Comment: @SavaryNicolas do u check my other answers?
Answer: I found a sample for implement it in drupal 6
maybe your problem occur because of 2 thing,

permission of directory
$form['#attributes'] = array('enctype' => "multipart/form-data");

made this example for you...explain how to working with cvs
   /**
    * Form function
    */
     function _form_cvs_import($form_state) {
      $form['#attributes'] = array('enctype' => "multipart/form-data");
      $form['container'] = array(
        '#type' => 'fieldset',
        '#title' => t('CVS UPLOAD') ,
      );
      $form['container']['cvs_file'] = array(
        '#type' => 'file' ,
        '#title' => t('CVS FILE') ,
        '#description' => t('insert your cvs file here') ,
      ) ;
      $form['container']['submit'] = array(
        '#type' => 'submit' ,
        '#value' => t('SEND') ,
      ) ;

       return $form ;
    }

/**
* form validate
*/
function _form_cvs_import_validate($form, $form_state) {
 $validators = array(
  'file_validate_extensions' => array('cvs'),
 );
 if(!file_save_upload('cvs_file', $validators)) { // the file is not submitted
    form_set_error('cvs_file', 'Please select the cvs file') ;
 }else{ // the file is submitted another validation for extension
   $file = file_save_upload('cvs_file', $validators, file_directory_path()) ;
   if($file->filemime != 'application/octet-stream' ) {
     form_set_error('cvs_file', 'Extensions Allowed : cvs') ;
   }
 }
}

/**
*  form submit
*/
function _form_cvs_import_submit($form, $form_state) {
    $file = file_save_upload('cvs_file', $validators, file_directory_path()) ;  // this is the cvs file in the tmp directory
    $file_handler = fopen($file->filepath, 'r') ; // open this cvs file
    $line_num = 0 ;
    $fields = array() ;
    while(!feof($file_handler)) {
        $line_num++ ;
        $line = fgets($file_handler) ; // this is the line/row
        $line_array = explode(",", $line);  //  array of row fields
        $field_num = 0 ;
        foreach($line_array as $field) {
            $field_num++ ;
            $fields[$line_num][$field_num] = str_replace('"', '', $field );  // E.g you can access second row and third field by $fields[2][3]
        }
    }
    fclose($file_handler);
    unlink($file->filepath);

}
Comment: Sorry for late return, i do not work on a single project... The problem was the form enctype:
$form['#attributes'] = array('enctype' => "multipart/form-data");
Without it, the $file always return 0 instead of the object file. So problem solve, many thx!


If conditions as inline style

Question: I am trying to add an inline-style to an element with HAML.
Somwhow, the style does not show up inside the tag - any idea whats wrong with it?
<code>%span.proceed-to-checkout.four.columns.offset-by-six{ :style => (@order.empty? ? 'display: none;' : 'display: inline;)'}
</code>
Comment: Assuming the `)'` at the end is just a typo and should be `')`, this appears to work for me. Can you provide an example of the HTML you are seeing and what you want to get?
Answer: You are not correctly closing last parenthesis. I think you can even remove them. Try:
<code>{ :style => @order.empty? ? 'display: none;' : 'display: inline;' }
</code>

If conditions as inline style


Erro código 991

Question: Alguém sabe o que pode gerar o erro 991? meu site escolaedti não está abrindo, ja tentei entrar em contato com o suporte do meu servidor mas nem eles sabem resolver o problema!
Comment: Até onde sei o código de erro 991 e de Acesso restrito.
Answer: Esse é um erro gerado pela KingHost para problemas com pagamento, já aconteceu com alguns clientes meus.
Comment: Perfeito, era exatamente isso , obrigado!
Comment: Se te ajudou marque a pergunta como resolvida
Comment: com certeza ajudou sim, está resolvido, muito obrigado!

Erro código 991


How to give classes on improvisation

Question: I'm giving a 6 times 3 hours workshop on musical improvisation. The participants are 5 to 10 mostly classical musicians, skilled with their instruments, slightly interested in jazz, and all keen on improvisation.
(Assume that I'm good at improvising solo and in a group, and that I can teach all sorts of music theory.)

How do I entertain such an amount of people? They are enough to form at least two jazz ensembles from them, but I'm only one teacher. Are there good introductory group games to learn improvisation that don't bore people who are already good at playing their instrument?
What pieces of theory are important? Right now I'm thinking of teaching them how to play and recognise the different modes (ionian, dorian etc.), but I'm probably missing something.

I'm sorry that this is a little vague since I haven't said anything about what style of improvisation I want to do. Let's say that it should be loosely jazz-based, accessible for people with a background in classical european music. So funk, blues, Yann Thiersen style, impressionism would all be ok, asian music probably not.
Comment: This seems really, really broad.
Comment: @MatthewRead, indeed. Maybe we can collect answers in a Community Wiki style.
Answer: I think an excellent piece to start with is Duke Ellington's C-Jam Blues. It's about the simplest 12-bar blues you're ever going to find.
Start by discussing the overall form of the piece: play through the head, play solos over the changes, repeat the head, stop. You could go over a few styles of soloing like strict-pentatonics, full blues scales, various modes over the changes, trading eights, bass solo, drum solo. Then spend the whole remaining first class on that song. Don't even stop. Just keep the rhythm section going, and take a chorus or two between each soloist to point out good things the previous soloist did or throw out ideas no one has tried yet.
I feel that this could make for a really solid start. But I'm not sure where to go from there for the remaining five classes. A really ambitious curriculum might end up with free-jazz in the last class. Choosing a final piece might make the intermediate ones easier to select.
Or you could develop time-wise and maybe do an early Rock-n-Roll or Rhythm-n-Blues tune like Johnny B. Goode or Twist-n-Shout.
...all of these ideas so far are for working with the full group. But you may want to break into smaller ensembles to work on communication and listening. This may depend upon the space you have to work with.
Comment: Super idea. A guess a lot of classical musos may not be aware of the 12 bar blues sequence, so a great start. Pents and blues will work well, not forgetting major as well as minor pent. Ostinati for two or three musos to keep playing goes down well. This can be swapped around the group. Trading fours, etc., should come towards the end of the whole thing.
Comment: I would add that they should learn C-Jam Blues and progression in all 12 keys, being able to arpeggiate the chord changes. A good introductory class might be having them focus on *listening* by having musical "conversations" either in groups or as a full group. You can make up rules like "only 4 people improvising at a maximum time" using only body percussion. Imposing limits / frameworks forces people to be creative. Arbitrary or ridiculous rules ("must use an animal sound") can get people to think differently, thus, more creatively, thus improvising will be more fun.
Comment: @jjmusicnotes, that's the kind of ideas I'm hoping for, care to write an answer?
Comment: @luserdroog, thanks a lot, I already have some song material to improvise over. I'd prefer modal jazz without scale changes for absolute beginners, because in the C-Jam Blues they'll often play E in the F7 part. But I'd be interested whether you think that blues would still be fun to play on violins.
Comment: @Turion I'll try to elaborate tomorrow if I get some time.  Something a little bit more simple for soloing would be *So What?* - people just move over two different minor-7 chords; it's pretty straightforward. The big thing to remember about all this is that you're teaching people to think *creatively*as opposed to specific jazz techniques.  Anything I write out would be through that vein - focusing on improvising in a general sense.
Answer: I'm coming at this from a completely different perspective, but I'll throw my idea out there because it sounds like you need several different activities.
There is a tradition of improvisation and ornamentation in baroque music that might feel more accessible to classical musicians.  There's lots of good information out there on this, but here's an example and here's another one.  You could have the musicians start with a simple melody or even a scale and add trills, grace notes, divisions, etc.  La Fontegara by Ganassi is really thorough and offers plenty of examples, but I'm having trouble tracking down a copy of this on the internet.
There are also numerous examples of ground basses in classical music.  La Folia is one example, although probably not one familiar to most of these musicians.  It would be an interesting exercise to have them listen to an example of a piece written based on the Folia and then have them do the same.
While this type of baroque music is not typically familiar to modern "classical" musicians, it might help them to see examples of improvisation in their "tradition."  Sometimes classical musicians approach improvisation with an attitude that classical musicians just don't do that, and historically nothing could be further from the truth.
Answer: I guess it depends on time and level of skill.
For a beginner's introduction, I'd start with recording a rhythm track of 12-bar blues, teach the class the pentatonic scales and blues cliche's.
For a masterclass, take a look at the question Does improvisation in the classical idiom differ significantly from jazz and folk improvisation?.
See if you can get the books

"Improvising: How to Master the Art" by Gerre Hancock which explains improvisation in the classical idiom
"The Guitarist's Guide to Composing and Improvising" by Jon Damien which introduces an analytical method of improvising that doesn't just work with guitarists.

For the masterclass sample tunes to improvise over I would suggest two Miles Davis modal tunes:

All Blues
So What

Play the tunes from the original recordings for the class.  Then teach them the chords and key centers for the tunes.  Introduce the concept of motifs and jazz cliche's/riffs.  Finally teach the pentatonic scales for each key center.
For both the beginners and the masterclass, break the students up into groups of 3 or 4, preferably in separate rooms.  Have a backing track of one of the tunes play. Band in a Box, Jamey Aebersold or Music Minus One should suit for the tracks.  In these groups, play a version of the band Phish's Circle Game.  For the details see the question Does Phish base their improvisational style off of any predetermined techniques?
Answer: At Turion's request, I'm writing out a few ideas for conducting improvisation classes.  If using my suggestions, they should be approached and reinforced cyclically, as they all support one another. For the sake of brevity, I'll provide one example for each.

Listening / "Talking"
Call & Response
Response & Variation
Variation & Extension
Knowing Your Instrument
Thinking Creatively - imposing limitations

Listening / "Talking"
Just as in a real conversation, you can't just talk whenever you feel like it, the same is true for music. If you're constantly interrupting who you're talking to, no one will want to talk with you. Same for music.
Idea for class
Give your students a prompt; they can only speak when you point to them; you gradually get faster until it falls apart. You can extend this activity by having a student be a pointer or by having them take turns with no one assisting / pointing. This activity can also be extended by using instruments / body percussion instead of voices.
Call & Response
Brainstorm situations where somebody might respond to you (saying "hello", a phone call, waving to a neighbor, etc). A response can be a direct quote or a related acknowledgement of what people just heard.
Idea for class
Divide into groups of two, have students practice listening to a statement from their partner, and try repeating exactly back to the other with the same vocal inflections. For a group, play "telephone" by whispering a word or phrase in a student's ear. They must continue this all the way around the circle until it gets back to you. If it changes, you get a point, if it's the same, they get a point. Activity is easily extended by substituting speaking for instruments with the same concept - you can even still have them play telephone.
Response & Variation
Very similar to the previous technique, the only difference here is that instead of reproducing the sound exactly, students add a tiny variation to it to make it unique. The same activities can be done.
Variation & Extension
Again, a graduated technique. Now, instead of just providing motivic variation, students are also tasked with extending their ideas through repetition.
Idea for class
Depending on ability, a great piece for structured improvisation would be In C by Terry Riley, or some pieces by James Tenney.
Knowing Your Instrument
When improvising, your instrument should be an extension of you. If you're limited by your knowledge of your instrument, you'll be limited in your ability to improvise.
Idea for class
Spend some time each class with students just fiddling around on their instruments. Encourage them to come up with five or ten unique sounds. Even if they only make one unique, new sound, that's still progress. Alternatively, you can give them a goal for more structure: "I want you to create a squeaky sound". This activity can be extended by having them create soundbanks, choosing 2-3 sounds, and then having an improvisation session where they can only use those sounds.
Thinking Creatively - imposing limitations
One of the difficult things about improvising / creating music is that there are simply too many options to choose from.  Imposing limitations gives people something to push against, and pushing against something is where creativity comes from - you're forced to think differently.
Idea for class
Your options for limitations are endless.  You can limit the time people play, the sounds they can make, their dynamic, the number of people who can play, the instruments they can use, or any number of other variables you want to influence.  Remember that for students, structured improvisation is almost always more successful than improvisation that is completely free.
Good luck.
Comment: Awesome. This is the kind of ideas I was hoping for. I will definitely use lots of these in the course. Hopefully I won't forget commenting here how it went.
Comment: @jjmusicnotes I think I found an [orphaned account of yours](http://music.stackexchange.com/users/3516/jjmusicnotes). I think you can use the 'contact' link below and ask for them to merge the accounts.
Comment: @Turion Hope you find them helpful; I use these ideas when I myself teach improvisation. Do let us know how it goes!
Comment: @luserdroog Wow, I can't believe you found this...yeah, I had an issue with email at the time and lost the account. I will have them merge the accounts; thank you for finding this.
Answer: Improvisation is at its core completion of a melody. If I was to give a class on it I would take various famous melody as extracts and then I would look critically at what happens in them.
These extracts would form basis on the improvisation  you do. Students would have to learn to listen attentively at the passage you play and then together you can think critically about the melody.
What is the rhythm? How can my improvisation build on the rhythm of the given passage? What are the chords in the each bar? How can my improvisation build on the chord usage? What is the form of the passage? Wave? Runs? Pyramid?
All these ideas or idioms in the given should form part of how the improvisation is played. Good improvisation is simply an further development of a musical idea.
It is analogous as to how you may write a creative writing exercise at school. You may be given an article and asked to write an essay on the given passage. You can be greatly creative in what you write but what you write can not completely ignore the given passage. So it also with musical improvisations.
If you think about how improvisation began in Jazz music it really teaches you how to approach it. As the story goes in the late nineteenth century the African American settlers in the US would get jobs at clubs and bars to play music.
They only knew a certain amount of music but was required to play extended lengths of time. So they had to learn to take the music they knew and make long extended songs out of it. So they learned to improvise and eventually it became ingrained in the style.
Comment: I disagree that improvisation is all about producing melodies. Improvising accompaniments is also an important part. And if you take Debussy, who composed a lot of his pieces based on improvisations, you'll see that it's possible to improvise beautiful music without melody. Otherwise, yes, good point, we should analyse improvisations and build on that.
Comment: @NeilMeyer I also sincerely disagree with your assertions about improvisation, melodies, and jazz. Improvising has been around for milennia, jazz has only been around for about 130 years.

How to give classes on improvisation


Can sendmail be configured to discard routed email that has been rejected by the next hop?

Question: Background:

We have a handful of hosts (running sendmail) acting as the MXs for a few domains each.
Each domain is handled via the sendmail/cf /etc/mail/virtusertable, with a set of known recipients and a catch-all reject rule.
Mail to postmaster on each host is aliased to root, and root is aliased to root+<host>@ourdomain.com.
The MX for ourdomain.com is Google Apps, and email@example.com is a simple group that forwards to the admins.
Google Apps will reject some emails at the SMTP stage, usually because of illegal attachments (instead of accepting them and filing them as spam).

Problem:
Given a particular spam email sent to a domain in a virtusertable entry:

If the recipient address rejects the mail, then sendmail will try and send a DSN to the sender.
If that sender also rejects the mail (because it's a falsified sender, and the MX for the sender rejects the mail as spam), then sendmail sends a DSN to the postmaster.
The routing detailed above takes place, and...Google Apps rejects the mail as well.
sendmail now gives up with a "savemail panic", and leaves the mail in the queue forever.
Our mail queue fills up with garbage

Is there any way I can get sendmail to discard messages that have been rejected by the next virtusertable hop (i.e. after step 1 in the Problem description)?  Or does anyone have any other solutions to this?
Comment: I have _no idea_ because I asked this question nearly 10 years ago :)
Comment: Your queue didn't ditch it after 4 days?
Comment: Ah, sorry!  I've worked with copious note-takers for so long I made an assumption.  Sorry again.
Answer: In the end we gave up on fixing this at the sendmail end, bit the bullet, opened our wallets and paid for Google Apps Premium which allowed us to tell GA to accept all emails from the servers acting as MXs.


Will disk compression impact the performance of a MySQL database?

Question: I've recently setup a TrueNAS storage server and hosted on it is a MySQL database. It's about 3GB; I'm not too concerned with how much space it's utilising.
By default, TrueNAS enables LZ4 compression on the ZFS filesystem. There's nothing else on this disk.
I'd like to know if this disk compression is going to have a significant effect on the performance of the database, if I should use something else (MySQL's own compression system potentially) or nothing at all.
Comment: Please define your understanding of **significant effect**
Comment: Yes it will affect performance.
Comment: @RomeoNinov I want to know best practice for performance. If disk compression is known to cause problems with MySQL databases for little gain then that would be my answer, or alternatively if the impact is little-to-none for decent storage gains etc.
Comment: "Cause problems" -- The FS would not exist if that happens.  "Performance" -- Maybe.
Answer: It will likely make little to zero difference in terms of performance. Unless your workload is heavily based on performing full table scans, MySQL performance is governed by IOPS/disk latency. If you are performing these r/w's across the network (TrueNAS), then that will be the performance bottleneck.
The other detail to keep in mind is that ZFS compression is per block, and performs a heuristic (byte peeking) to determine if compression will have a material effect upon each block. So depending on the data you store in MySQL, it may not even be compressed.
With that said, MySQL on ZFS in general is known to need tuning to perform well - see:
https://www.percona.com/blog/mysql-zfs-performance-update/
Answer: Based on my personal experience and this page compression of ZFS have insignificant effect on overall performance. Of course it depend on the hardware you have - slow CPU may lead to slow operations, but on contemporary hardware IMHO you will have no problem. And at the end you can always disable it for database pool.
About MySQL compression - it is not good practice to try to compress already compressed data. This will lead (generally speaking) to increase of the used disk space.
When sizing MySQL get in mind the size of records (blocks) which is 128kb by default (in Solaris)
Comment: Thanks for your advice, I'll have a read through that blog too
Comment: Solaris is an oddball implementation of MySQL.  Still, I agree that compression is not what it is cracked up to be.


Is a squeeze bunt with a runner on third and one out a good play?

Question: In Game 5 of the 2016 NLDS between the Dodgers and the Nationals, the Nationals on three occasions had a runner on third with one out (the third, fourth and seventh innings).
Do any of the generally accepted statistical models of baseball indicate that a squeeze bunt would have been a good play in any of these situations?
Answer: According to Baseball Reference, in 2016 there were 127 plate appearances containing sacrifice Bunt Attempts  at-bats with 3rd base occupied and 1 out (precisely).
Of those 127, 61 RBIs were recorded on 56 successful SHs (not all of which recorded RBIs, 1st/3rd can still be a SH when 1st advances to 2nd).  3 times a runner reached on error.  20 hits were recorded, meaning the player was attempting a sacrifice bunt but reached base without an error or a fielders' choice.
11 strikeouts were recorded on sacrifice bunt attempts, 2 double plays, and a total of 51 non-sacrifice outs (meaning they did not rule it a successful sacrifice - so it was 71 "at bats", 20 hits 51 outs, and 56 sacrifice hits which don't count against ABs.
The overall WPA (win probability added) was -1.5 for the season (meaning about -0.01 per attempt).  RE24 was a -15 (meaning the overall run expectancy for the season was that they scored 15 fewer runs than they would have otherwise).
This data isn't perfect, it's not really possible to get perfect with the free BR data, but what it tells me is that squeeze bunts are slightly negative but close to neutral - and in situations where you only need one run, they may be useful.
Limiting it to situations that are clearly squeeze attempts (3rd or 2nd/3rd only) and adding a few years' data, you have 198 attempts from 2011-2016 with 2nd and 3rd or 3rd occupied (not 1st) and 1 out exactly.
122 RBI were recorded, on 99 SHs and 27 hits.  22 times a FC/SH was recorded without recording an out (meaning they attempted to throw the runner out at home and failed), and 7 times the runner reached on error, meaning 22+7+27=56 times no outs were recorded and 198-56=142 times an out was recorded (and three of those 142 times, 2 outs were recorded).  Total RE24 for the period was -7 (again, meaning this was more or less even with not doing it, but very slightly negative).
122/198 is not bad, 61.6% success rate - far higher than most things in baseball really on the hitting side.  However, because the run expectancy with runner on 3rd, 1 out, is 0.9223, and 1.32 with 2nd/3rd occupied, and then the run expectancy with 2 outs is very low (0.36 for 3rd, 0.57 for 2nd/3rd), you give up a lot (more than half) of run expectancy for a failure even if its just the runner is thrown out at first.
My interpretation of this: if you need one run (either to tie or win) and is late in the game (9th, or maybe 8th), and have a competent bunter, it's probably worth doing it - the reason the RE for the play in general is so high is because you can score several runs, especially 2nd/3rd.
But in the 2nd or 3rd or 4th, or even 7th?  You're preventing yourself from having a big inning by giving up the out, and you're only scoring a run about 2/3 to 3/4 of the time anyway.  It's less dumb than a regular sacrifice bunt with one out, which takes you from RE of 0.526 to RE of 0.317 even when it succeeds (comparing on [this page] the RE of 1-0-0 with 1 outs to 0-2-0 with 2 outs), but it still doesn't really look like a good idea.
Add to that the specifics of the players.  Jayson Werth was up for two of these opportunities, and while he's not the player he once was, he is probably more likely to have a SF than to Sac Bunt successfully.  Lobaton was up for the one in the 2nd inning, and while he does seem like a better choice for the squeeze bunt, he's also the 8th batter (meaning Scherzer was up after him), so the RE for the 39% of the time he fails to score an RBI is nearly 0.


Como ordenar o conteúdo de um Array

Question: Tenho a seguinte Array com os respectivos dados aplicados:

Número do Cartão
Mês (Validade ou Vencimento)
Ano

Recebo esses dados de uma API externa, porém de forma "desorganizada". Gostaria de tratar esses valores para seguir um padrão específico. Tentei utilizar a função sort() do php, mas sem sucesso.
Recebo-os desta forma (desordenada/aleatoriamente)
Array
(
    [0] => Array
    (
        [0] => 5522 8600 0000 0000
        [1] => 2020
        [2] => 09
    )

    [1] => Array
    (
        [0] => 09
        [1] => 5522 8600 0000 0000
        [2] => 2020
    )

    [2] => Array
    (
        [0] => 5522 8600 0000 0000
        [1] => 20
        [2] => 9
    )
)

Nota-se que ...
os valores das chaves [0], [1] e [2] são diferentes em relação aos demais elementos. O que era pra ser:

[0] = Número do Cartão
[1] = Mês
[2] = Ano

Portanto, gostaria de criar/usar uma função na qual fosse possível padronizá-los desta forma:
Array
(
    [0] => Array
    (
        [0] => 5522 8600 0000 0000
        [1] => 09
        [2] => 2020
    )

    [1] => Array
    (
        [0] => 5522 8600 0000 0000
        [1] => 09
        [2] => 2020
    )

    [2] => Array
    (
        [0] => 5522 8600 0000 0000
        [1] => 9
        [2] => 20
    )
)

independente de suas posições...

Vale ressaltar também
Que, de acordo com este cenário, onde o ano de 2020 é mostrado com apenas 2 casas decimais, ou seja, 20 haveria um conflito com os valores do Mês, mas tratando-se de validade, para obter o Mês sem saber sua posição (além de recebe-los de forma desordenada..)
Array
(
    [0] => Array
    (
        ["mes"] => 09
        ["cartao"] => 5522 8600 0000 0000
        ["ano"] => 20
    )
)

No entanto, por não existir chaves "nomeadas", basta simplesmente criar condições, onde:

valor menor ou igual que 12 refere-se ao mês

seguindo o número de meses que temos em 1 ano. Já

valor maior que 12 refere-se ao ano

Com isso consigo obter os respectivos valores, o contrário do Número do cartão que só basta utilizar o Algoritmo Luhn para validar números de cartão de Crédito/Débito que resolve!
Comment: É isso sim. Você pode dizer qual é a API e fornecer um link para documentação da função.
Comment: Isso não pode ocorrer, é um erro grave de projeto que deve ser corrigido no backend visando uma padronização dos dados. É grave pois se buscar um registro do começo do século, por exemplo, surge a possibilidade dos dados serem indistinguíveis.
Comment: tem que tornar o retorno dessa chamada uniforme. Consertar isso no forntend é gambiarra.
Comment: O backend é processo interno. Um dos processos interno desse código php(que não deixa de um processo interno da sua aplicação) é essa API em questão que não é amigável ao desenvolvedor pois não assegura a consistência dos dados pois não apresenta hierarquia e estrutura hegemônica nas respostas as solicitações, o que pode implicar situações onde a informação é indecifrável, o exemplo já citado de buscas por registros datados do inicio do século até 2012. Essa API é quem deve ser corrigida ou substituída.
Comment: Como assim @AugustoVasques ?
Comment: mas o meu propósito é justamente consertar no back-end, eu recebo esses valores de forma `desordenada` de uma API externa (um outro servidor) e ordena-la para passar para o front-end de forma `ordenada` do meu projeto
Comment: @AugustoVasques entendi, a solução deve vir a partir da API né isso? então para obter esses valores de forma ordenada eu precisaria fazer o que necessáriamente? (infelizmente essa é a unica API até então que pode fornecer esses dados..)
Answer: Fiz um pequeno processo para te ajudar, certamente não é a melhor maneira mas pode ser o seu ponto de partida nessa ordenação.
    <?php

// Dado o array inicial
$arr = [
    [
        0 => '5522 8600 0000 0000',
        1 => '2020',
        2 => '09'
    ],
    [
        0 => '09',
        1 => '5522 8600 0000 0000',
        2 => '2020'
    ],
    [
        0 => '5522 8600 0000 0000',
        1 => '20',
        2 => '9'
    ]
];

// Vamos normalizar o tamanho dos elementos para eles poderem ser comparáveis com o min e max mais adiante
$arr_normalizado = [];

foreach($arr as $i)
{
    $arr_normalizado[] = [
        0 => str_pad($i[0], 4, "0", STR_PAD_LEFT),
        1 => str_pad($i[1], 4, "0", STR_PAD_LEFT),
        2 => str_pad($i[2], 4, "0", STR_PAD_LEFT)
    ];
}

// Criando o novo array
$arr_new = [];

foreach($arr_normalizado as $i)
{
    // O maior elemento certamente é o número do cartão
    // e o menor elemento ceertamente é o mês (porque já passamos de 2012)
    $ordenado = [
        0 => max($i),
        1 => substr(min($i), -2)
    ];

    // O último elemento que precisamos buscar é o ano
    // como não sabemos em que posição estava no array normalizado
    // é só buscarmos pelo elemento que não é nenhum dos outros dois
    // que já obtemos pelo min e max
    foreach($i as $v)
    {
        if (!in_array($v, $ordenado))
        {
            $ano = (int) $v;

            if ($ano < 2000)
            {
                $ano += 2000;
            }

            $ordenado[2] = $ano;
        }
    }

    $arr_new[] = $ordenado;

}

print_r($arr_new);

Como ordenar o conteúdo de um Array


how to find the top 3 most-wanted waterskis, ordered in descending order by number of offers made;

Question: SELECT waterski.id
FROM images (
    SELECT DISTINCT offer
    FROM offer a
    WHERE 3 <= (
        SELECT COUNT(DISTINCT offer) FROM offer b WHERE b.offer >= a.offer
    )
    ORDER BY a.offer DESC"
);

Answer: SELECT waterski.id FROM images (
    SELECT DISTINCT offer
    FROM offer a
    WHERE 3 <= (SELECT COUNT(DISTINCT offer) FROM offer b WHERE b.offer >= a.offer)
    ORDER BY a.offer DESC"
);


Is there an easy way to stop the stage?

Question: I want to show "time is up" movie clip when the main time's over.Then goes to specific frame when 3 seconds countdown is over.I use the remove event listener,but I'll have write to code for all listeners and all levels.Is there an easy way of doing this?
import flash.net.SharedObject;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.TouchEvent;
import flash.ui.Multitouch;
import Turn;
import ScoreHolder;

timeisup.visible = false ;

//This timer start when the main timer stop.
var threesecond:Timer = new Timer(3000,0);

////MAIN TIMER
var minute:Number = 0;
var second:Number = 15;

//This timer check to timer and set to what happen if time over.
var timercheck:Timer = new Timer(1000,0);
timercheck.addEventListener(TimerEvent.TIMER, timercheck1);
timercheck.start();

function timercheck1(evt:TimerEvent):void {
if (minute <1 && second <1)
{
timer.stop();
timeisup.visible = true;
timeisup.play();
threesecond.start();

stage.removeEventListener(Event.ENTER_FRAME, h1);
stage.removeEventListener(Event.ENTER_FRAME, h2);
stage.removeEventListener(Event.ENTER_FRAME, h3);
stage.removeEventListener(Event.ENTER_FRAME, h4);
stage.removeEventListener(Event.ENTER_FRAME, h5);

    }
}

////What gonna happen to when threesecond over
threesecond.addEventListener(TimerEvent.TIMER, zamanbittia);

function zamanbittia(evt:TimerEvent):void
{
gotoAndPlay(392);
}

// Create the timer
// Checks the clock function every 1000 milisecond (1 second)

var timer:Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, clock);
timer.start();

// Function that increments the timer
function clock(evt:TimerEvent):void {
// every time this function is checked increment second by one
second -= 1;
// If the second is 59
if(second < 0){
// The minute will be plussed with 1
minute -= 1;
//and the zero will be set to 00
second = 59;
}

Also I tried
stage.frameRate = 0.01;

But it's to slow and If the timer stops while moving to objects then I get error.
Comment: It's not clear to me exactly what you want to do.   If you want to stop all nested movie clips, then you can simply do: `stage.stopAllMovieClips();`
Comment: My buttons moving randomly on the stage I trying stop of them.Is not working.
Comment: It's unclear though how you are moving your buttons, where your buttons are in context to what you've shown and what much of your code is doing (eg all those ENTER_FRAME remove event listeners)
Answer: stop(); in your main script
See different scenarios of implementation here Stop the main timeline from within a Class function
Comment: Stop(); it's couldn't stop the moving buttons.
Comment: You have to put the frame code wherever the animation is or target it from your main frame code by doing this.whateverButton_mc.stop();

Is there an easy way to stop the stage?


Reference On Panel Data Analysis

Question: I'm looking for good panel data analysis references. I've Baltagi & "Panel Data Econometrics in R". But I want something which is short (max 100 pgs), lucid (know this criteria differs) & have examples to work through.
I'll be grateful if somebody can give me some references.
Answer: This doesn't meet your criterion for short, but Fitzmaurice, Laird and Ware is very highly regarded.  I would say it's clear, and it does have examples and problems to work through (with a website that has all the datasets in the book).  The examples in the book are done with SAS, whereas I would prefer R, but it is possible to figure out the R code to conduct the analyses.
Comment: This book came highly recommended to me, and we now have it in our library at work: http://www.amazon.com/Applied-Longitudinal-Data-Analysis-Occurrence/dp/0195152964/ref=pd_sim_b_1
Comment: Thank you Gung! I'll certainly look through it. Actually I was asking for short version as I won't get time to go through the methods rigorously. But this book might help to clear my basic ideas about panel data analysis.
Answer: I can recommend you Marno Verbbek's "Guide to Modern Econometrics". In the meantime there exists a third edition, but note that the first and second editions will do the job as well. The datasets used in the book are downloadable.
The book is not  entirely dedicated to panel data. However, it has a chapter of some 50 pages dedicated to the topic. It is well explained and illustrated.
The book is a very good point to start with panel data and to get the main ideas.
Comment: Even though Gung's book is very lucid & covers a lot of topics on Panel Data analysis, but your book fulfill my basic requirement of being short. Also, it covers majority of Panel Data methods.

Reference On Panel Data Analysis


Hiding the site domain name from the content writers

Question: I'm in dilemma. I'm hiring content writers etc for my new sites who risk getting fired from me for not meeting my expectations. I want to keep my site names confidential from the world because of competition and other concerns.
How can I hide the domain name but also allow users to add content straight-forwardly at my production site?
I was thinking to symbolic link another idle domain name to point to my site. I'd use relative URLs in my site content so the Pathauto module would take of this. Content writers would see this idle domain when working on my site.
A site can be visible from multiple domains. For example I can install the same site on my localhost PC. Secondly there are more than 50 million sites. For new sites it'd take a couple of months for a site to start appearing in the top 100 results in Google. How'd a naive person find the site in short time? Hiding the domain name means suppose I've a site name myjobs.com I want to make it visible in somejunk.com domain too and editors will add content in this site.
Comment: What do you mean 'hide the domain name'? How will people browse to your site if they don't know the domain name? Are you just going to give them an IP address and be done with it? I also can't see how this would relate to Drupal, surely it's a DNS/server issue? How does Drupal (6 AND 7 apparently) come into this?!
Comment: Firstly, I agree with Clive.  Secondly, there's really no effective way to do this.  They could always Google a string of their own words and find your site.

I do not think this is a technical issue at all. The real solution would be to have some contracts/NDA signed by your employees.
Answer: As long as you have your server configured properly (ie, have your ServerName and ServerAlias directives set right for Apache), then this should work our of the box as long as you don't explicitly set the cookie domain or base URL in your settings.php.  A potential complication is if you have any rewrites for canonical URLs on your site.
However, I think your best approach is to use the Domain Access module to run two sites out of the same installation.  Have one affiliate be for the live domain, and the other affiliate be for the authoring domain.  Then separate the content / themes as needed.  When content is OK, just move it from the authoring affiliate to the live affiliate.
Comment: +1 for this.  In addition, set up the `robots.txt` for the authoring domain to prevent indexing of this site.  As long as you keep sub-standard content off the live domain. it will never show up in search.
Answer: I don't think anything you do is a realistic option.
Content writer A (let's call him Bill) doesn't meet your expectations, and as a result gets fired.  Because of your approach Bill doesn't know what site he was writing for.  Bill then uses Google or Bing (apparently that's still an option) to search for a sentence or two of the content that he wrote and it lo and behold it appears in the SERPs. Bill now knows where his content went, and all the hard work in hiding the domain was a waste.
If I were Bill, I would then write a scathing blog post about how annoying that whole situation was. From what I've read around the web, the two worst kinds of people for a company/employer to p*ss off are social media managers, and content writers ;-)
I apologise if this sounds too chatty or too informal, but I think you are trying to fight the wrong fire here. Just get a ROCK SOLID contract written up for the content writers. Also get a SOLID NDA (you can get basic ones for free here) as part of it, and make sure you set out your expectations fully and clearly from the beginning.
Ask for employment references for your content writers - if they have only written for a couple of sites, find out how long they have been writing for them.  Get a history. Then still get them to sign the contract!
You also might want to try posting a similar question to one of the following members of the SE Network. Don't be put off by the beta status - the more members a beta community gets, the more likely it is to become fully fledged. Drupal Answers was a whole different community during the beta phases, now look at us ;-)
Project Management Beta
OnStartups Beta
The Workplace Beta
Personal Finance and Money