Mesmo pop up em várias páginas

Question: No meu projeto, o usuário pode fazer login de qualquer página em que estiver. Eu poderia construir o mesmo pop up em cada uma das páginas, mas gostaria de saber se existe alguma maneira de eu construir o pop up em um arquivo separado e só chamá-lo nos links das páginas.
Answer: se for PHP, vocé pode usar:
include_once('nome_do_arquivo_popup.php') no template principal.

caso não haja template principal, use o
include_once('nome_do_arquivo_popup.php')

em todos os arquivos. Dessa forma, você estará atingindo o seu objetivo.

Mesmo pop up em várias páginas


Get path to folder outside document root for uploading photos from PHP

Question: Problem:
This problem is three-fold.

After reading this advice (How do I secure a folder used to let users upload files?) to store photos in a folder outside document root I encountered a problem when working with Cloud9. The problem is to write the PHP code in a effective way that points to one level above document root and then into the images folder.
What permissions should a folder have outside the document root for allowing users to upload photos? I have seen that a number of pages recommend 666 so users can read/write but not execute. The question is, do users really need to read photos? If you are working with database you allow the reading to be done by PHP, not by users. If this is a good case, what permission is then recommended?
What is the recommended way to access images that are outside of the document root?

Code:
Currently when I apply this example to the Cloud9 environment I have to write the folder hardcoded.
$upload_dir = '/home/ubuntu/images/';

While the photos upload with success, I feel that hardcoding the path is not a proper way.
Desired outcome:
To find the path to /images folder that is one level outside document root, set correct permissions for the folder, and access uploaded images according to best-practices in PHP.
Comment: I think that all upload storage should be on services like amazon S3 or cloudinary. don't start messing around with upload directories. it might cause some troubles. or open another server instance for storage only
Answer: 1) How find path:
define ( DOCUMENT_ROOT, realpath(
        $_SERVER['DOCUMENT_ROOT']
    ) . DIRECTORY_SEPARATOR
);

define ( UPLOAD_DIR, realpath(
        DOCUMENT_ROOT .
        DIRECTORY_SEPARATOR . ".." .
        DIRECTORY_SEPARATOR . "images"
    ) . DIRECTORY_SEPARATOR
);

2) By user is meant in this case, a user who runs the web server. For example, "www-data".


Menu para selecionar cor

Question: Estou fazendo uma ferramenta, e preciso de um menu para seleção de cor.
Alguém poderia me dizer como fazer?
Algo semelhante a isso:
Answer: Com HTML5 simplesmente use input tipo color:

Escolha a cor: <input type="color">

Observação: nem todos os browsers suportam esse tipo de input.
Ou então usar um plugin Javascript, como o http://jscolor.com/
Comment: @Superbomber tenha em mente que nem todos os browsers suportam esse tipo de input, [ver aqui](http://caniuse.com/#feat=input-color).
Comment: Obrigado, era tudo que eu precisava.
Não conhecia esse type color rsrs.
Answer: Este picker da imagem em particular é o me parece ser o Spectrum. Com ele, basta fazer a inclusão dos arquivos

<link rel='stylesheet' href='spectrum.css' />

e fazer a chamada como um plugin jQuery no seu seletor, algo como:
$("#custom").spectrum({
    color: "#f00"
});

Comment: Inspect Element do Mozilla

Menu para selecionar cor


What does 'train NLL' and 'test NLL' mean?

Question: I've just started reading ML papers and occasionally I encounter the word 'train NLL' and 'test NLL', which I cannot figure out the meaning. What does they mean?
Answer: NLL is an abbreviation for "negative log likelihood".
It serves the same purpose as the Maximum Log Likelihood. However, since most optimization problems typically attempt to minimize a function, the negative log likelihood is what is preferred to the Maximum Log likelihood.
Comment: I've extended the answer to provide more information, however the original question seemed to be based on not know what the abbreviation stood for.
Comment: as it stands, this answer is quite short by CV standards and would be more appropriate as a comment to the original question. Maybe you could explain what the likelihood function is.
Comment: yes, it looks like the original poster doesn't know what a likelihood function is. That's exactly why I suggested you to explain that (which is different from just saying why neg log is used instead of max log).


how to separate mysql cell in PHP by given symbol

Question: Suppose that in MySQL I have a row called "favourite_websites". If there are more then 1, then they are separated by comma ( , ).

Example user 1 has "favourite_websites" set as "facebook.com"
Example user 2 has it set as "facebook.com,google.com"
Example user 3 has it set as "facebook.com, google.com"

What I need is to loop each user and then get each their website separately as
[website]

If there are more then 1 website in the cell then it should echo smt like this
[website]
[website]

Comment: use `preg_eplace()`..
Answer: Convert your string to array by using explode : documentation.
Example :
<?php
    $favourites = "facebook.com, google.com";
    $favourites_array = explode(',', $favourites);
    foreach($favourites as $website){
        $website = trim($website); //remove space characters
        echo ''.$website.'';
    }
?>

Answer: First set your input element name as an array name, like myname[];
while posting the data,
$var1 = explode(",",$_POST['myname']);

now your query goes here,
mysql_query('INSERT INTO tblname (fieldname) values ($var1)');

Comment: You've got it wrong, it's the other way round. He gets favorites as a string from database, and want to display them separately.


os sites pwa funcionan no iphone como no android?

Question: Boa noite a todos!!!
A minha dúvida é a seguinte: sites feitos com PWA funcionam da mesma forma no iphone e ipad, como no android?
é necessária alguma alteração para iphone?
Sem mais, obrigado pela atenção!!!
Comment: Recomendo: https://www.opus-software.com.br/pwa-no-ios/
Comment: vou ler com calma, mas assim, apenas a instalação do mesmo, por exemplo, fixar na tela inicial, como um app, (como faço no android) é possível sem grandes problemas?
Vou ler o conteúdo agora mesmo, obrigado!
Answer: Sim amigo existem uma série de cuidados a ser tomados quando o PWA vai rodar no iOS.
O primeiro é que para sava-lo como atalho na tela inicial vc precisa identificar qual é o browser de acesso para descobrir se é o Safari e ai instruir o usuário do procedimento correto para salvar o PWA localmente.
Sobre o ícone do App vc vai precisar de um link no  com  rel="apple-touch-icon" para definir a imagem do ícone.
<link rel="apple-touch-icon" href="/custom_icon.png">

Outro ponto é que a tela de carregamento padrão costuma ser branca, o que não da um feedback para o usuário. Para tratar isso se usa a tag um link rel="apple-touch-startup-image" no tb no  do documento para durante o carregamento mostrar uma imagem e não a tela branca.
<meta name="apple-mobile-web-app-capable" content="yes" />
<link href="/apple_splash_2048.png" sizes="2048x2732" rel="apple-touch-startup-image" />

Aqui vc pode consultar o guia de desenvolvimento e outras tags exclusivas para dispositivo Apple https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
Além disso existem vários outros cuidados a serem tomados, recomendo que leia esse artigo https://medium.com/@oieduardorabelo/pwa-no-ios-como-deix%C3%A1-lo-mais-nativo-e022f6c67b9c


kafka confluent .NET 1.8.2 How to override max.poll.interval.ms in the consumer config?

Question: My application has to consume messages from a kafka topic at specific time or when triggered.
So when my consumer sits there without consuming messages, it gets removed from the consumer group.
Application maximum poll interval(300000ms) exceeded by 277ms (adjust max.poll.interval.ms for long-running message processing): leaving group

My understanding is that it is the consumer itself sending the request to the broker to be removed from the consumer group once the maximum poll interval is exceeded.  Is this config setting exposed in the Confluent Kafka .NET API version 1.8.2?
Answer: ConsumerConfig accepts a MaxPollIntervalMs attribute


Center of the group $D_{10}$ is trivial

Question: I am trying to prove that the center of the dihedral group $Z(D_{10})$ is trivial.
The only way I've been able to do it so far is to draw the group table, but I am trying to find a more elegant way of proving the result. If I fix an $a \in Z(D_{10})$ and assume $ab = ba$ for all $b \in B$, I am not able to prove that $a = e$ because there isn't a way to, for example, multiply by inverses. If I broke it into cases, I could possibly use the fact that reflections invert themselves.
Comment: You only have to check $ab = ba$ for all generators $b$.
Answer: You could use the normal form: every element can be written uniquely as $r^is^j$ with $0\leq i\leq 4$, $0\leq i\leq 1$, subject to the rules $r^5=s^2=e$, $sr=r^4s$.
Suppose $r^is^j$ is central; then $s(r^is^j) = r^{5-i}s^{j+1}$ must equal $(r^is^j)s = r^is^{j+1}$, which tells you that $r^i=r^{-i}$, but this only holds when $i=0$ in this dihedral group. That means the element is either $e$ or $s$; but $s$ is not central, since $sr = r^4s\neq rs$. So the center is trivial.
(Alternatively, if $r^is^j$ is central, then $r^{i+1}s^j = r(r^is^j) = (r^is^j)r = r^{i-1}s^j$ if $j=1$, hence $r^{i+1}=r^{i-1}$, which is impossible. So $j=0$, but $r^i$ does not commute with $s$ if $i\neq 0$, as above.)
Answer: This follows from  a general fact. Every dihedral group $D$ of order $2n$ (the group of symmetries of the regular $n$-gon), $n>2$, consists of $n$ rotations $\rho_i$ through angles $2\pi i/n$, $i=0,1,2,...,n-1$ and of $n$ reflections about lines that connect either opposite vertices or a vertex and the midpoint of the opposite side or two opposite midpoints.
Suppose $n$ is odd. Then none of the reflections commute with $\rho_1$ and none of the rotations $\rho_i, i>0$ commutes with all reflections. Hence the center of group $D$  is trivial $=\{\rho_0\}$.
If $n$ is even then the center consists of two rotations through angles $0$ and $\pi$ which are $\rho_0$ and $\rho_{\frac n2}$.

Center of the group $D_{10}$ is trivial


Gerar menu e submenu com PHP

Question: Situação:
Estou construindo um menu com submenu de informações que recupero do banco de dados, estes dados são categorias e subcategorias de produtos, este menu esta pronto e funcionando porém quando não há subcategorias (que é um submenu do menu) esta gerando uma
 vazia.
Tecnologias envolvidas:

CakePHP 3.0 que recupera os dados do banco através de seu ORM. (julgo pouco impactante no problema).
Templates padrão do CakePHP com extensão .ctp.
PHP usado para renderizar o menu e submenu.

SQL das tabelas categoria e subcategoria
CREATE TABLE categories (
  id INT AUTO_INCREMENT PRIMARY KEY,
  category_name VARCHAR(255) NOT NULL,
  created DATETIME,
  modified DATETIME
);

CREATE TABLE sub_categories (
  id INT AUTO_INCREMENT PRIMARY KEY,
  sub_category_name VARCHAR(255) NOT NULL,
  category_id INT NOT NULL,
  created DATETIME,
  modified DATETIME,
  FOREIGN KEY category_key (category_id) REFERENCES categories(id)
);

Template que gera o menu e submenu

    <?php foreach($categories as $category): ?>

             <?= $category ?>

                <?php foreach($subCategories as $subCategory): ?>
                    <?php if($subCategory['category']['category_name'] == $category): ?>

                             <?= $subCategory['sub_category_name'] ?>

                    <?php endif; ?>
                <?php endforeach; ?>

    <?php endforeach; ?>

OBS $categories é um array de string simples e $subCategories é um array de objetos (que possui como uma de suas propriedades um objeto que representa uma categoria onde uma propriedade deste objeto e o nome da categoria).
Foto do menu e submenu (o problema de acentuação é devido a collation do mysql, mudarei posteriormente).

Menu renderizado no browser

         Alimentos

                 Industrilizado

                 In natura

                 Comida pronta

         Bazar

Answer: Falta-te um if de verificação se existem subcategorias:
  <?php if(/*existem subcategorias*/){ ?>

            <?php foreach($subCategories as $subCategory): ?>
                <?php if($subCategory['category']['category_name'] == $category): ?>

                         <?= $subCategory['sub_category_name'] ?>

                <?php endif; ?>
            <?php endforeach; ?>

  <?php } ?>

A
 vai aparecer sempre, se não queres nenhuma tens de verificar antes da
 se existem subcategorias.
Answer: Como bem disse o Jorge, você tem de ter um if antes do
.
Algo como isto:

    <?php foreach($categories as $category): ?>

             <?= $category ?>

           <?php if($subCategories): ?> ///////verifica se a variável está vazia////////

                <?php foreach($subCategories as $subCategory): ?>
                    <?php if($subCategory['category']['category_name'] == $category): ?>

                             <?= $subCategory['sub_category_name'] ?>

                    <?php endif; ?>
                <?php endforeach; ?>

          <?php endif; ?>////fim do if////

    <?php endforeach; ?>

Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Gerar menu e submenu com PHP


Use custom marker when specific checkbox is checked

Question: I am building an events page. The page is using Gmap, Locations and Views modules.
In the content type "Events", I have set a checkbox for "Featured Event", I want these events to stand out in the map, so I would like to use a different marker in the map if the event is a "Featured Event".
Please let me know how to do this. Thanks in advance
Answer: I would use CSS for this.

Add your featured checkbox field
Add a views-row class, in the format settings, with the replacement pattern of the value for the checkbox

Now I can't remember if GMap will add that class to the marker rows too. If it does not, I would advise you to override the template for the view and in the class section, add $fields['field_featured'], making sure that there is a space before it

Using that class, you can style it however you want using CSS and/or JS

Hope that helps!
Comment: Sounds like a great idea, thanks for the post. I will try this and get back to you.
Comment: There is no way to add a class to gmap marker row, could you help please? this is the html that I am seeing:
Comment: I fixed this issue with the help of the "GMap Taxonomy Markers" module. Thanks for your time.


How can I make my keyboard sound like a Hammond organ?

Question: I have a keyboard. It can play the basic MIDI sounds. I would like it to have a Hammond organ sound. Since I'm not sure if I can upload new sounds to its MIDI bank, I'm looking for a way to 'effect' my keyboard, so it would sound like a Hammond organ while I'm playing. I do not wish to record what I play, I need this live.
The keyboard has MIDI input/output, so I'm thinking about a setup like this: I connect the MIDI output to my laptop, and the laptop sound output to the amplifier. And as I play, the sound actually comes from the laptop sounding like a Hammond organ. Is there a software to do this, or any other method? (Preferably a free one, but I don't mind paying for it either.)
Comment: You may find it worthwhile reading a brief [introduction to MIDI](http://www.midi.org/aboutmidi/intromidi.pdf)
Comment: Try Bristol organ/synth emulation free software ....(http://bristol.sourceforge.net/emulations.html)
Comment: FerroFish B4000+
Unbelievable! I use one for gigs: https://www.youtube.com/watch?v=Psw8FE9zwvU
Answer: This is a deep subject. I can tell from your initial question (before we edited it) that you are unfamiliar with the concepts involved with using a MIDI controller keyboard with a computer, with virtual software instruments, and with interfacing the audio output of a computer with a PA system or amplifier. You need to learn about all these concepts.
You need to purchase a virtual software instrument that emulates a Hammond.
You also need to get an understanding of how MIDI controller keyboards work, a USB MIDI interface, and an external audio interface for a computer. Then there's the question of Mac versus PC, and whether or not your computer has the necessary hardware specifications to support virtual software instruments and professional-quality audio output.
Meanwhile, back to the Hammond question. There are many software programs that can do this, far too many to mention.
Apple Logic Studio has a tremendously accurate re-creation of a Hammond organ, among many, many other features. Of course it costs money.
LinPlug Organ 3 just does Hammond sounds.
Native Instruments Vintage Organs might suit your needs.
Comment: The Garageband "Hammond" isn't too bad, either.
Comment: The GarageBand Hammond is pretty good, but you can't control individual drawbar settings, which is what a real Hammond player requires.
Comment: I may be reading too much into the original poster's question, but I got the impression that the request was for a B3-ish organ sound, with the percussive attack and Leslie, not that the poster was thinking drawbars at all. Agreed that if you want to be able to really tweak the sound in a Hammond-like way, you really need the drawbars!
Answer: The obvious solution is indeed to use a hammond plugin on a laptop, but you will need a good audio interface to use this live because otherwise you will either not get the latency low enough or risk audio dropouts. The more trouble-free solution is a hardware expander module specialized for hammond organ.
Answer: I was pretty happy with the organ sounds from the Boss 'Dr. Rhythm-Section'. It only had 4 or 5 organ choices, but they all sound good (and only one was "churchy"). It can be used as a MIDI module (as the sound-generator connected by MIDI to a keyboard controller).
I've also seen drawbar controllers available but I don't know how (well) they work.
More generally, I'd recommend a stand-alone midi sound module. Hardware, all "in the box". A virtual one is cheaper, but it ties you to the computer.
Comment: Stand-alone MIDI sound modules are good in that they don't have the latency problems you so often get with PC USB based solutions. However PC-based Virtual instruments have the virtue of cheapness (assuming you already have the laptop)
Answer: Well, one thing to note is that you are planning to use this live and presumably in settings with an audience of less than 1000.
Most answers here focus on getting the best kind of Hammond sound (or actually any) for recordings or a P.A.  The least-effort answer for that is to get a keyboard/expander with a good Hammond sound.
But there is another consideration I have not seen mentioned here yet, and that is that an essential part of what is perceived as "the Hammond sound" is a rotating Leslie speaker.  "The Hammond sound" on its own is supposed to be a "portable" electromechanic substitute for a church organ.  And it looks like one, too, so the Hammond organ players in rock bands tend to look quite out of style with their living-room furniture-style organ.
With regard to the sound, the rotating Leslie speaker makes most of the difference, and here is the main thing: you cannot accurately record and replay a Leslie.  Nothing sounds like a live Leslie speaker in reasonable vicinity.  You can perfectly replicate a recording of a Leslie speaker.  And the sound of a Leslie speaker from far away is also static enough (namely not interacting with the listeners' head movements in complex ways) that you don't lose much by putting it through a recording, mixer, and/or PA.
But for a smallish live audience, the Leslie cabinet will be what you want in order to be in style.  The Hammond organ driving it can be reasonably replaced with electronic or digital substitutes without affecting the listeners much (of course, as a player having the full console or not is making things feel different).
Now that's still bulkish and heavy vintage equipment we are talking about, but considerably less so than a genuine Hammond organ itself.
Answer: The EmU B3 module is a pretty good Hammond emulator but of course you don't get the drawbars.
But if you set up lots of your favourite presets you can scroll between them.
This connects to your MIDI keyboard.
Adding rotary speaker and distortion externally can really give good results.
Comment: Is there not already the Leslie effect already available on an Emu B3? If not, since it's more than just part of the Hammond sound, how to get it?
Answer: Get a cheap MIDI to USB cable, to connect the keyboard to the laptop. Then look for a suitable software synth that will give you the sounds you're after, (amongst other features).
Alternatively (and more costly) get a MIDI "sound module" which has Hammond organ sounds - this is hardware, and you won't need the laptop. The sound module connects directly to the keyboard via a MIDI cable but it will also need some amplification on it's output.
Answer: ORGANIZED TRÍO is the best VST, use it with your DAW (i use it with FL Studio), it comes with a demo mode window but after a few minutes playing its disappears and you can review the program and save your preset.
Answer: Plug your keyboard into a Leslie/tremelo guitar pedal (100 bucks) or a dunlop univibe for speed control on the leslie effect. Also a guitar volume pedal, most organ players play a chord or lick and then roll off or on the volume for effect.  What you won't get is drawbar settings which is like half the thing, like John medeski will hold a chord and mess with drawbars continually. But a univibe and a volume pedal will help. It will still sound like a casio organ but hey, try it out.
Answer: Rich is right: you can't get a clone that sounds like a Hammond.
However, it only needs to sound as good as the audience's perception of what a Hammond sounds like.
I was and still am a big fan of the B4 and B4mk2 software, which IMHO beat the hell out of VB3 and most of the other software offerings available. As for hardware clones, they fall into either the older Analog keyboards -like the original BX and Cx from Korg and the Roland VK1 which have character but don't sound like a Hammond- Or the Digital Clone Wheel types, which mostly are either remodeled software or sampled.
I have tried most of the Nord C2d Vk8 Vk7 Cx3mk2 and even cheaper stuff, like the Viscount DB3. I have yet to get near a HOAX or a Legend, which both look promising. I also recently stumbled across software called Blue3. I tried the demo version, and for $99, it wasn't half bad. IMO, it was better than VB3 and as good as B4 Mk2, if not better. I also tried several clones with Hammond written on them.
For small venue gigs, I use an original ventilator pedal and either B4 on a laptop or DB3, which despite its shortfalls (the vibrato and percussion being wrong) has a good basic tone, and with the Vent, it does the job. I have found that most clones will pass in the middle of the keyboard and fall down badly at the top end. And to be honest, if you're trying to emulate J DeFrancesco, then frankly anything can be passed off as a Hammond, but will come up short if you're trying to do a Stevie Windwood or an Ian Mclagen.
Answer: So sorry, but you can't.  NOTHING in the world sounds like a B-3+Leslie.  I have heard ALL the so-called "electronic" and "digital" fakers, and anyone who cannot pick out a fake either is not a musician, has no ear, or simply is uninformed about a real, live B-3+Leslie sound.
You might get "close" and that may be good enough for you, but don't fool yourself.  Only a B-3+Leslie sounds like a B-3.  Kind of like "electronic" drums--they don't sound like drums no matter what you do.
Cheers, and keep the music going!
Comment: I don't agree with your assertion that somebody that cannot pick out a Hammond emulation from a B3 is not a proper musician. As such your core argument is diluted with needlessly emotive language.


Table validation rule error: Unknown function 'Nz' in validation expression or default value on 'TableName'

Question: In Microsoft Access, I am trying to enforce table validation to have one and only one foreign key filled using table validation rule on Long Integer ...ID fields:
Nz([MeasurementPointID], 0) = 0 Xor Nz([MeterID], 0) = 0

But when saving table definition (table name is Readout), the following error is displayed:
Unknown function 'Nz' in validation expression or default value on 'Readout'

and this is correct, because on pressing the … button, function Nz() is missing from Expression Builder.
How to implement the above requirement without Nz()?
Answer: A more general rewrite is just use IIF, which is available, and is a dropin replacement for Nz
Nz([MeasurementPointID], 0) becomes IIF([MeasurementPointID] IS NOT NULL, [MeasurementPointID], 0)
Generally, casting back and forth to a string will take a large performance hit.
Comment: The difference between `Iif` and `Nz` is that `Nz` is only implemented at the application level, while `Iif` is implemented at the database level. This also means you can't use `Nz` when querying an Access database over ODBC connections, and in some other cases. However, I haven't found a good resource yet on which functions are and aren't implemented at the database level in Access, so I can't point you to more general guidance on what is and isn't allowed in constraints.
Comment: Hi Erik, a good catch! The confusing point was that `IIf()` similarily to `Nz()`, is not listed  in the Expression Builder. I thought that `Nz()` throws errors because it is not listed and therefore `IIf()` will follow the suit. Obviously, there is a inconsistency there and each function has to better tested even if not listed what is my greatest lesson from this Q/A. Your last sentence is a bit superfluous, because I would definitely prefer `IIf()` if its availability was obvious. Without `IIf()`, there is no other way than casting.


Displaying values that were removed from list

Question: Hello I'm currently removing elements from list doing this:
candidateList.RemoveAll(x => versionslist.Any(y => y.Name == x.Name && y.Parent.Name == x.Parent.Name));

I want to see what is actually being removed so i can compare it after with versionList to see why not all the values are being removed. I know this because version list is a sublist of canadidateList and after the removeall the math doesnt add up.
Answer: Before you RemoveAll do:
var removedList = candidateList.Where(x => versionslist.Any(y => y.Name == x.Name && y.Parent.Name == x.Parent.Name));

Now you have the list of what will be removed, then perform the remove all:
candidateList.RemoveAll(x => versionslist.Any(y => y.Name == x.Name && y.Parent.Name == x.Parent.Name));

Comment: can i then get the elements that were different ?
Answer: There is no built in way to see what items are removed from list.
If you need it for debugging - one easy way would be to just use .Where(...).ToList() with the same condition before call to .RemoveAll and inspect the result.
If you need that information at run-time consider using ObservableCollection<T> instead of regular list and listen to "removed" notifications.
Comment: can i then get the elements that were different ?
Comment: rnadom question does removeall remove duplicates as well so something that fits the predicate exsits more than once the exact same one


Validation of multiple response codes

Question: I have to use a REST api that creates a user. This api returns response code 201 (accepted), 409 (user already exists) or some other code in case something went wrong. I want to validate that the received response code is either 201 or 409 (and not something else).
Now my code only checks one of these response codes:
http()
      .client(AddUserClient)
      .receive()
      .response(HttpStatus.CONFLICT)

Is it possible to change this, so both values results in an OK-test?
Cheers,
Ed
Answer: The Citrus Http Java fluent API does not support this kind of validation at the moment. I will add this as soon as possible, thanks for the hint!
In the meantime you will need to use the default receive fluent API for this special operation:
receive(AddUserClient)
    .payload(...)
    .header(HttpMessageHeaders.HTTP_STATUS_CODE, "@assertThat(anyOf(is(200), is(409)))@")
    .header(HttpMessageHeaders.HTTP_VERSION, "HTTP/1.1");

You can combine Http fluent API and default fluent API in a Citrus test case without limitations.

Validation of multiple response codes


Nature of $\Delta$ in polynomials$?$

Question:
Suppose there is a function $f(x)=a_nx^n+a_{n-1}x^{n-1}+a_{n-2}x^{n-2}+\cdots +a_1x+a_0$ and it is given that $a_n>0$ and  $f(x)>0\:\: \forall x\in \mathbb{R}$ Then will it be accurate to say that the $\Delta$ of $f(x)$ will always be $<0$$?$

There was a question this which led me to this feeling of uncertainty.
Because, as far as I know the theory of

$\Delta \lt0$ if $f(x)\gt0$ (assuming that the leading coefficient is positive) is only applicable when $f(x)$ is a quadratic polynomial.

Or am I wrong$?$ Any ideas will be greatly appreciated.
Comment: See this article, https://en.wikipedia.org/wiki/Discriminant, on the section "real roots". For high degrees, the discriminant does not carry all the information
Answer: As pointed in the comments, for higher degree polynomials discriminant does not carries all the information.Discriminant becomes more and more complex as you go higher and higher. And you should try to find some counterexamples (if they exist)
.

Nature of $\Delta$ in polynomials$?$


Prove that the sequence satisfying $a^{p^n}\equiv a^{p^{n-1}}$mod $p^n$ for $n\geq 1$, converges to the Teichmuller Representative

Question: Prove that for any $a\in\mathbb{Z}_p$, the sequence satisfying $a^{p^n}\equiv a^{p^{n-1}}$mod $p^n$ for $n\geq 1$, converges to the Teichmüller Representative congruent to $a$ mod $p$.
So a p-adic integer has general form $a = a_0+a_1p+a_2p^2+...$ , for $a_i\in\{0,...,p-1\}$.
Now if $a^p\equiv a$ mod $p$, then $a^p$ and $a$ must have the same constant term.  And if $a^{p^2}\equiv a^p$ mod $p$ then $a^{p^2}$ and $a$ must agree in their first two coefficients. Continuing on in this way, this sequence seems to be approaching $a$, which is what I started with, but this can't be right, what am I not understanding?
Edit:  Ok I'm revising this, $a^{p^{n}}$ picks up its $p^{n-1}$ coefficient from $a^{p^{n-1}}$, could someone still give me some clarification on how one shows this becomes the Teichmuller Representative?  I think I just need someone to tell me the 'right' way to think about it.
Comment: Why should $a^{p^2}$ and $a$ agree in their first two digits?
Answer: I'd separate this into two claims.

The limit of your sequence converges $p$-adically.  This follows because it is Cauchy (and $\mathbb{Z}_p$ is complete).  If $\ell$ denotes this limit, then $a \equiv \ell \mod p$.  (This latter assertion is obvious.)
The limit $\ell \in \mathbb{Z}_p$ is a $(p-1)$-th root of unity (or $0$, I suppose).  This is equivalent to the assertion that $\ell^p = \ell \in \mathbb{Z}_p$.  This holds provided that $\ell \equiv \ell^p$ mod $p^k$ for all integers $k$, and this fact follows from the limit definition of $\ell$.
Answer: I answered this to a large extent earlier:

Suppose $a\in{\bf Z}_p$. Then using the binomial theorem, $$\left|\frac{p\cdot p\cdot p\cdots p}{1\cdot 2\cdot 3\cdots k}p^n\cdot(p^n-1)\cdots(p^n-(k-1))\right|_p\le\frac{1}{p^n}, $$ $$\left|(1+pa)^{p^n}-1\right|_p\le \max_{1\le k\le p^n}\left|{p^n\choose k}p^k\right|_p\le\frac{1}{p^n}\to0,$$ and hence $(1+pa)^{p^n}\to1$ (compare with $t^\epsilon\to1$ as $\epsilon\to0$ in $\bf R$ for $t$ in a nbhd of $1$). If $x\in{\bf Z}_p$, then $x^{p-1}\in1+p{\bf Z}_p$ (reduce mod $p$ and invoke Euler's theorem), hence $(x^{p^n})_{n=0}^\infty$ is Cauchy and has a limit in the $p$-adic integers, since $x^{p^{n+1}}-x^{p^n}=x^{p^n}\left((x^{p-1})^{p^n}-1\right)$. In an ultrametric space, the distance between successive terms tending to $0$ is sufficient to be Cauchy. Since multiplication and hence fixed powers are by definition continuous in a topological ring, $x\mapsto x^p$ is continuous, so $$\omega(x):=\lim\limits_{n\to\infty}x^{p^n}\implies \omega(x)^p=\left(\lim_{n\to\infty} x^{p^n}\right)^p=\lim_{n\to\infty}x^{p^{n+1}}=\omega(x),$$ in which case we have $\omega(x)^{p-1}=1$ when $\omega(x)$ is a unit. Since $x^p\equiv x\bmod p$, and ${\bf Z}_p\to{\bf Z}/p{\bf Z}$ is a continuous topological ring homomorphism, $\omega(x)\equiv x\bmod p$. This tells us the image of units under $\omega$ consists of the $(p-1)$th roots of unity.

It is not necessarily the case that $a$ and $a^{p^2}$ agree on the first two terms, or that $a^{p^n}$ shares more and more terms with $a$. Setting $p=3$, $a=2+1\cdot3$, we have $a^{3^2}=2+2\cdot3+\cdots\not\equiv 2+3\bmod 9$.
Comment: I guess continuity was the issue that was stumping me.  Since the only way to represent this Teichmuller Representative is with an infinite sequence (or series), the best I could hope to do was to show better and better approximations of the number were evaluated closer and closer to zero by $x^p-x$, but that would rest on the continuity of polynomials in $\mathbb{Q}_p$, which I'm not sure I was suppose to know.


Div filha sobrepor a div pai que possui overflow: hidden

Question: Estou querendo que a div filha 'sobreponha' a div pai que possui um overflow: hidden e um tamanho fixo. Essa div pai é um item de um de uma biblioteca de carrousel feita com JS e ele adiciona um tamanho fixo e um overflow: hidden e dentro dessa div eu tenho uma outra div que é no caso é um select personalizado feito em HTML e JS. Fiz um exemplo para mostrar qual é a situação:

.pai{
  width: 150px;
  height: 60px;
  overflow: hidden;
  border: 3px solid red;
  margin-bottom: 50px;
  text-align: center;
}

.pai.sem-overflow{
  overflow: inherit;
}

.pai .filha{
  width: 70px;
  height: 150px;
  margin: 0 auto;
  border: 3px solid blue;
  margin-top: 15px;
}

Como está atualmente

    div pai com overflow

        div filha

Como eu gostaria que ficasse

    div pai sem overflow

        div filha

Comment: Não bastaria mudar a propriedade `overflow` tal como fez no exemplo?
Comment: Até onde eu sei é impossível da forma que está feita. Somente tirando a div filha de dentro do `overflow: hidden;` ou retirando o overflow.
Comment: Eu tentei mudar a propriedade do overflow, mas ao fazer o slider ele fica todo quebrado. Eu perguntei pois se eu for usar um  ele funciona mesmo a div pai tendo o overflow
Answer: A única forma de ser feita seria removendo o overflow da div pai, talvez pelo próprio javascript ou então pelo css
overflow: visible !important;

Caso essa div filha só apareça após algum evento, você pode reposicionar a div filha para outro lugar onde não haja a div pai com overflow, ou remover o overflow após o evento.


Parsing hexadecimal numbers into array

Question: I have a variable char* etag="8a964ee2a5e88be344f36c22562a6486";.
How can I convert this into an array of byte, where byte is actually typedef unsigned char byte?
Comment: It is hex already, just as a string. What type were you thinking of storing it in? It's a tad long for a `unsigned long long` even
Comment: I want to store it as a `byte[16]` type, where `byte` is actually `typedef unsigned char byte`.
Comment: Duplicate: http://stackoverflow.com/questions/3381614/c-convert-string-to-hexadecimal-and-vice-versa?
Comment: @Jay the answers there are all C++, but this is tagged C
Comment: @Jay no - the other question is for C++ not C
Comment: @the_naive - edit that comment into tour question not as a comment
Comment: @awoodland Is the question any clear to you now? Could you figure out what I should do?
Comment: Duplicate: http://stackoverflow.com/q/10653499/971127
Answer: byte bytes[16];
int i=0;
for (;i<16;++i) {
  int value;
  sscanf(etag+2*i,"%02x",&value);
  bytes[i] = value;
}

Comment: @H2CO3 - to give him the benefit of the doubt, he only posted a few minutes after you and his answer is is different enough from yours that it would have taken more than three minutes to turn your answer into his, so I don't believe he did copy you. So I've given you both +1. Hope that's some consolation for you.
Comment: Copying my answer and using a slightly more complicated function is not fun.
Answer: If I understand correctly, you want to make the 2-letter groups of hex chars to bytes, then store those bytes in your char array. Try this:
char *str = "long hex string";

int i;
unsigned char bytes[16];
char tmp[3] = { 0 };
for(i = 0; i < 16; i++)
{
    memcpy(tmp, str + 2 * i, 2);
    bytes[i] = (unsigned char)strtol(tmp, NULL, 16);
}

Answer: you probably use strtol
below is the example program:
/****************************************************************
 *
 * Purpose: To show examples of the strtol function.
 * Author:  M.J. Leslie
 * Date:    06-Nov-94
 *
 ****************************************************************/

#include <stdlib.h>

main()
{
  char num[10];

                /* Test a valid number      */
  strcpy(num,"13");

  printf("%s(Oct) is %i(Dec)\n", num, strtol(num, NULL,  8));
  printf("%s(Dec) is %i(Dec)\n", num, strtol(num, NULL, 10));
  printf("%s(hex) is %i(Dec)\n", num, strtol(num, NULL, 16));

  puts("----------------------------------");

                /* Test a slightly valid number
                 * Returns the same results as
                 * above.           */
  strcpy(num, "13hzcd");

  printf("%s(Oct) is %i(Dec)\n", num, strtol(num, NULL,  8));
  printf("%s(Dec) is %i(Dec)\n", num, strtol(num, NULL, 10));
  printf("%s(hex) is %i(Dec)\n", num, strtol(num, NULL, 16));

  puts("----------------------------------");

                /* Test an invalid number
                 * Returns ZERO         */
  strcpy(num, "hzcd");

  printf("%s(Oct) is %i(Dec)\n", num, strtol(num, NULL,  8));
  printf("%s(Dec) is %i(Dec)\n", num, strtol(num, NULL, 10));
  printf("%s(hex) is %i(Dec)\n", num, strtol(num, NULL, 16));

  puts("----------------------------------");

                /* Test 0 base.
                 * This will look at the number
                 * and decide the base for its self!
                 */
  strcpy(num, "13");
  printf("%s is %i(Dec)\n", num, strtol(num, NULL, 0));

  strcpy(num, "013");
  printf("%s is %i(Dec)\n", num, strtol(num, NULL, 0));

  strcpy(num, "0x13");
  printf("%s is %i(Dec)\n", num, strtol(num, NULL, 0));

}

/****************************************************************
 *
 * Results of the program:
 *
 *  13(Oct) is 11(Dec)
 *  13(Dec) is 13(Dec)
 *  13(hex) is 19(Dec)
 *  ----------------------------------
 *  13hzcd(Oct) is 11(Dec)
 *  13hzcd(Dec) is 13(Dec)
 *  13hzcd(hex) is 19(Dec)
 *  ----------------------------------
 *  hzcd(Oct) is 0(Dec)
 *  hzcd(Dec) is 0(Dec)
 *  hzcd(hex) is 0(Dec)
 *  ----------------------------------
 *  13 is 13(Dec)
 *  013 is 11(Dec)
 *  0x13 is 19(Dec)
 *
 ****************************************************************/

Comment: can you add an example showing how to use it to break down into an array of bytes?

Parsing hexadecimal numbers into array


Setting radgrid page numbers programmatically and assiging varying sized set of data to each page

Question: Afternoon folks.
I am using a radgrid as this has lots of functionality that I wish to keep (exporting, line selection, scrolling, etc) but I have come across a request I'm not sure how to handle and as such, I'd like some advice!
I have a radgrid attached to an object datasource implementing a SelectMethod  of GetProductList and a SelectCountMethod of CountProductItems.This would return something along the lines of:

With CountProductItems returning 9.
What I need to do with this is dynamically set the radgrid so that the paging is defined by the guid i.e. one page for each guid present.
So in the above example, we'd have 3 pages.
On page load you'd be shown Page 1:

With the pager items displaying 1, 2, 3.
Click on page 2 and you'd see:

and clicking on page 3:

Does that makes sense? Is it possible and if so, any pointers greatly appreciated.
Answer: I'm not sure if this is possible with paging. However I think it is very possible to set up some buttons with custom queries depending on the "page" they are on.  So a "<" and ">" button underneath the grid.  I implemented something similar to this a while ago for a project depending on their member groups, and queried using Linq.


How can I filter traffic using a layer 3 switch?

Question: I have a layer 3 switch which needs to route traffic to 2 different networks which don't see each other.
What would be the simplest and most efficient way to do this? And is there any straight forward documentation I could follow to get this done?
Comment: Wow.  Complete lack of effort here.  How about the make/model of the switch for starters?
Comment: Your question title refers to filtering traffic while the actual question refers to routing traffic. Which is it? I'm assuming you're referring to routing traffic between these 2 networks, right?
Comment: I apologize for not being clear.

I am using a Cisco Catalyst 3560 switch, all the traffic that comes through the internet will reach this switch.

Once it reaches the switch, the switch needs to determine where to send the traffic to. Certain IP's are only allowed to network 1, and other IP's are only allowed to go to network 2.

What would be the best and efficient way to get this set up?

Thanks for the help!
Answer: Q. What would be the simplest and most efficient way to do this?
A. Routing
Q.  Is there any straight forward documentation I could follow to get this done?
A. http://www.dummies.com/how-to/content/exploring-tcpip-routers.html


Sylow $5$-subgroup in $S_{16}$

Question:
Find two different $5$-Sylow subgroups in $S_{16}$.
Hint: use group multiplication.

Any hints?
Comment: I thought the definition of Sylow-p-subgroup is a subgroup of maximal $p$ power, i.e. maximal $k$ such that $p^k \Big | |G|$. In your question it seems to me there are higher powers of $5$ that divide $|S_{16}| = 16!$. Can someone point out to me what I'm missing? Thanks!
Comment: @Matt: where is the problem? the 5-sylow groups here will be of order $5^3$, cause 16! = ..5..10..15..
Comment: my bad, I read your question as if you were looking for subgroups of order $5$.
Comment: Does conjugation work here? In this case we just need to find a 5-sylow subgroup of $S_{16}$ which is not normal which will fulfill the condition, don't we? If I miss something, please tell me, thanks. By the way, to type $S_{16}$ is better to use S_{16} instead of S_16 as far as I am concerned.
Answer: What does a permutation of order 5 look like?
Can you give a condition when two permutations of order 5 commute?
Comment: You should look at the multiplication of the three (cyclic) groups generated by these cycles, as indicated by your hint, noting that the generators mutually commute.
Comment: well it can be a cycle of order 5, when they are disjoint?  should I look at the multiplication of 3 disjoint cycles of order 5, hm?
Answer: Since $16!$ is divisible by $5^3$, but not $5^4$, the $5$-Sylow subgroups of $S_{16}$ are the subgroups of order $5^3$.
An example is
$$\langle (1\ 2\ 3\ 4\ 5), (6\ 7\ 8\ 9\ 10), (11\ 12\ 13\ 14\ 15)\rangle.$$
(Since any pair of generators commutes, the group has isomorphism type $\mathbb Z/5\mathbb Z\times\mathbb Z/5\mathbb Z\times\mathbb Z/5\mathbb Z$ and in particular order $5^3$.)
Another example is
$$\langle (1\ 2\ 3\ 4\ 5), (6\ 7\ 8\ 9\ 10), (11\ 12\ 13\ 14\ 16)\rangle.$$
Both examples have a unique common fixed point of all elements.
In the first example, it is $16$, and in the second example it is $15$.
So the examples give two different $5$-Sylow subgroups of $S_{16}$.

Sylow $5$-subgroup in $S_{16}$


is there an option on Ruby like mysql_insert_id() for PHP?

Question: Does ruby support a way to retrieve the id for the last inserted row simliar to php's mysql_insert_id() method for mysql databases?
Answer: It's pretty much the same in ruby, except that the mysql connection is wrapped by an object and that the library is available trough rubygems ( gem install mysql )
require 'mysql'
db = Mysql.connect(hostname, username, password, databasename)
db.execute("INSERT INTO mytable VALUES 1,2,3");
db.insert_id
# => last inserted id

see http://www.tmtm.org/en/mysql/ruby/
Usually you don't do that and rely on a sql abstraction library like ActieRecord, DataMapper, Sequel, DBI, ... all of them have this method available but under different modules.
Comment: I think the methods have changed a bit. It's now `db.last_id`
Answer: you can always use SELECT last_insert_id() query instead.
Answer: Why would you need that? Chances are that you're not using ActiveRecord to its full power. However, you can access the id of a created record by just accessing @record.id.
I would recommend to not use plain SQL syntax in Rails...
Update: Sorry, just realized you may in fact NOT be using ActiveRecord. Of course it's feasible to use the suggested SELECT syntax then (and it's the right way to obtain this value). Personally, I'd still prefer to use ActiveRecord.


Polygon Vertices as complex numbers

Question: Here is the problem:

i) A regular n-sided polygon has vertices $p_0,p_1 , ... p_{n-1}$ that lie on a circle of unit radius.
By considering the complex roots of the equation $z^n = 1$ or otherwise, prove that the product of the
distances $p_0p_1,p_0p_2 , ... p_0p_{n-1}=n$ [1]

My logic so far is that the equation $z^n=1$ has $n$ many solutions by the Fundamental Theorem of Algebra, therefore we can write $1=z^n=(z-z_1)(z-z_2)\cdots(z-z_n)$. We can take the absolute value of both sides to get $|1|=|z-z_1|\times|z-z_2|\times\cdots\times|z-z_n|$. This close to what is desired with the only difference beeing that $z$ is a generic point on the circle not equal to one of the roots. Could somebody give me a hint as to how to proceed with this problem?
Comment: If $z^n=1$ then $|z|^n=1$ so $|z|=1,$ so $z$ is on the circle of unit radius centered at $0.$ Thus $z= \cos\alpha + i\sin\alpha$ for some $\alpha\in[0,2\pi).$ So
$$\begin{align}
z^n & = (\cos\alpha + i\sin\alpha)^n \\ {} \\
& = \cos(n\alpha) + i\sin(n\alpha) \\ {} \\
& = 1 \text{ if and only if } \cos(n\alpha)=1 \text{ and } \sin(n\alpha) = 0.
\end{align}$$
Comment: So we have
$$
\alpha \in \left\{0, \frac{2\pi} n ,\frac{4\pi} n, \frac{6\pi} n, \ldots, \frac{2(n-1)\pi} n \right\} = \left\{ \frac{2k\pi}  n : k=0,1,2,\ldots, n-1 \right\}.
$$
So $p_k = e^{2\pi ki/n}$ and in particular $p_0=1.$
$$\prod_{k=1}^{n-1} \operatorname{distance}(p_0,p_k) = \prod_{k=1}^{n-1} \big| e^{2\pi ki/n} - 1\big|$$
Answer: Differentiate your equation
$$nz^{n-1}=\frac{d}{dz}(z-z_1)...(z-z_n)$$
All the terms formed when we differentiate vanish when we put $z=z_1$ except for $$(z-z_2)...(z-z_n)$$ which becomes
$$(z_1-z_2)...(z_1-z_n)$$
So $$n=n|z_1|^{n-1}=|z_1-z_2|...|z_1-z_n|$$
Is that OK now?
Comment: Hello, when I do that I get $nz^(n-1)=0$. From here I can use the expansion for $z^n$ from before to get similar to the desired equation but I get that the product is equal to zero. Could you clarify on what you meant as the next step? Thanks!
Comment: Much clearer, thank you for your explanation.

Polygon Vertices as complex numbers


How to "age" guitar strings?

Question: Well I know this question sounds stupid, or at least extremely unusual. All the advertisements related to guitar strings talk about how to slow down guitar string aging and hoe hot to prevent the loss of brightness of the new strings. Coating is about to prevent aging (oxidation) and some manufacturers vacuum or oxigen free sealed packaging are all about this.
However here is the thing: For me, the bright, and very "steely" sound of the new strings do not sound so good. Actually more than 1 year old Thomastik GB flatwound now sounds awesome. In the other hand on my other guitar I've just changed to a new string set (to the very same Thomastik) , and its bright new, and steel like sounds are very disturbing for me.
Is there any way not to wait months to get the sound I like?
Comment: You could boil or better, make a tensioner (a 2x4 with two clamps or bolts on each end) that you can "string" and apply proper tension to the strings that will allow them to "wear" without using them(could be kept in a moist free environment).
Comment: Possibly you should shop around for better strings. It may be the string combination on your guitar. If your guitar is very bright naturally then adding bright strings might make it brighter. Anything done to the string will effect the timbre on some level. Usually the stiffer the string the brighter it will be. The more things added will dampen the higher frequencies.  I would not self-age strings using any type of "grease" because these affect overall intonation. You need something that will be consistent. Shopping around for strings is probably your best bet.
Answer: The loss of brightness in old strings is due to increasing damping of high frequency vibrational modes.  Any substance with visco-elastic behavior will cause this effect when applied to the strings.
For example, you could use grease taken from your own skin (which is what ultimately happens to strings anyway).  The sides of the nose are a good place to harvest some grease.
Comment: I have no success with proving the "visco elastic dirt"  damping theory. I deep cleaned my old Thomastic flatwounds with no sound change. I released the strings and used alcohol wrapping around the alcohol soaked cloth and moving the cloth  up and down on the total length of the strings.. Theese are flatwound strings so supposedly not so much place left to the grease to left. By touching the strings they feel drastically cleaner, but they sound almost exactly the damped aged way as before. (not forgetting the original goal was  make new strings to sound aged, but this was also an experiment)
Comment: It sounds reasonable, but not according the manufacturers opinion which is it caused by the oxidation. This is why the coated string (preventing oxidation) invented, also gas or vacuum packing. Cleaning old strings with appropriate solvent and tools, never restores the steely sound of a new string, the change is noticable, but minor.
However I agree on oxidation should not be the main factor,  I accidentally opened an extra pack of Thomastik one year ago, this is which I put on the new guitar now: It has brand new steely sound. Should be the same sound as on my old guitar if that is about oxi
Comment: revised my opinion. I did some research,  and it seems that the general recommendation is play with dirty oiled hand only different by auto engine repair-> then play, or eat pizza -> then play.
Comment: It's the regions between the core and winding where grease makes the biggest difference.  Grease on the surface experiences little strain during string vibration, and therefore provides little damping.
Comment: Well, it can be true. However this case greasing _outside_ still will have no or little effect for similar reason. It will take time the dirt to achieve the core...
Answer: Another change that strings undergo is flattening at the frets. It might help to store the strings on a guitar neck with many capos forcing contact at the frets.
Some of the higher-pitched shimmer of the new strings may be due to a length-wise springy motion in the wrapping. Once flattened at the frets, the wrapping is also cinched at those spots.
Comment: This sounds interesting. Especially the side effect what you describe.
Answer: After spending ten days to prove or confute theories I have only partial results, so here are my conclusions:
Theory #1: Oxidation
Confuted (imho). These confuting experiences was included in my original question but for have it in an organized answer I list here:
I had a one and half year old, accidentally opened (originally vacuum packed) D'Addario Chromes (flatwound), and I stringed my guitar with them ten days ago. The strings sounded the most typical new string like. (still no significant changes after ten days). So its not the oxidation, because the opened and same age strings were oxidated almost identically, but sounded way different.
Theory #2: Visco elastic dirt
Confuted in two ways.
a) Reverse confuting: I've tried to clean (I mean deep cleeaan) my old strings. (See details of the process in my comment on user2790167's answer.). No hearable changes at all. Maybe the clean was not "deep" enough, as user2790167 answered: we did not reach the core... Still I would expect some sound changes, but there was not any.
b) I've tried to artificially speed up aging the new strings by dirting them with a chapstick. It is kinda gluey fat so it's a candidate replacing nose grease with the benefit it is available in limitless amount...  (nose grease credits goes to user2790167)
I even extra strengthen the strings during the process to dilate the ways to the "core". No changes. I thought it takes some time while the dirty travels to the core so waited five days before concluding the result in this answer: Still no changes.
Theory #3:  My own
Note: This is not proven at all. This is only a theory what based on that neither Theory #1 and Theory #2 seems to be not provable. (although both sound reasonable).
So... That's a fact, that new strings sound are well noticable changing in the first 1-3 month after applying them. If it is not the oxidation and not the dirt, then what else? The only thing what comes in my mind is the "usage". The steel's attribute must change somehow, my bet is its flexibility. This could be because of the micro dilatation, or some microscopic changes in the matter itself. The steel gets tired and tired.
Comment: Yes :-). Only the minor problem remains I can not find out how to age the strings...
Comment: @g. Ah I hadn't seen that the article was promotional material, but I think some points are valid: strings are deformed and relax when you pluck them, and over time, the stresses imparted to the string will lead to fatigue.  It could be this fatigue that causes the change in tone. I'm assuming that if you put the string on a device that vibrates the string sufficiently, you will simulate the effects of playing, and hopefully 'age' the string.
Comment: You might have found a gap in the market - 'pre-aged strings', like stonewashed jeans...
Comment: Just found [this blog which explains metal fatigue in strings](http://graphtechsblog.com/why-guitar-strings-break/) quite nicely

Similar to AbstractDissonance's comment above, you could build [a device similar to this one](http://demoweb.physics.ucla.edu/content/130-rudnicks-string#)
Comment: @ChristopheLynch I read the article, it is about string breaking and not string sound change. It also seems to have a light smell of Graph Tecy's "String Saver saddle" advertisement...  Actually in the last 30 years I had only one string broken, a Thomastik GB E (0.012) and it was a new one, done a few days after I stringed it :-(
Answer: I read an article a few years ago by Eric Clapton's guitar tech that stated He was only allowed to change a string when it broke. Doing strings this way minimized the brightness effect that happens when a complete set of strings is changed on a regular basis. For someone who plays on a regular basis, I find it doesn't take very long for my strings to lose most of that brightness, and I can time my string changes to coincide with rehearsals and have a mellower sound by the time I step up for performance. That's the way I do it.
Answer: I have heard that boiling guitar strings may "stabilize" them, reducing some of the "new string" character that typically ages out. This may help you acheive the sound that you are seeking. I have never tried this myself. YMMV.
Comment: This is exactly the opposite effect I would like to achieve it it works at all. But probably it is not working, see: http://www.get-tuned.com/boiling-guitar-strings.php. (Note, and read the comments, the author is intended the article as a joke.)
Comment: I meant: "...if it works at all..."
Answer: It might be best to shop around and try different brands of string, some of which might sound 'mellower' out of the packet.  The metal used to wind the strings is ultimately very important for the tone produced - nickel-wound strings sound mellower than steel-wound strings.
Comment: Well, I did my homework some years ago, and concluded that 014-055 _flatwound_ Thomastik GB is probably the most jazzy mellow.
Comment: Good advice in general. But OP has TI George Benson flatwounds! AFAIK there *is **no** mellower string*.
Answer: I also want aged strings. i have no idea what the string are on my guitar (bought in a market) but they are near the end of their life. one broke already and two more have breaks in the wound metal so that only the nylon inner makes contact with the frets.
When i had to replace a string the bright sound was really out of keeping with the rest of the sound. i ended up adding a small tab of fabric tape about 2cm from the bridge. this had the effect of dampening the string. it helped a lot. perhaps more experimentation would lead to better materials for this and perhaps even better positioning. after a couple of months the string is better. but i still prefer the sound of the older strings on the guitar.
Answer: I just now rubbed a bunch of dirt on my out-of-the-package strings on the guitar and it helped me get a more muffled sound (to me) out of the strings.

How to "age" guitar strings?


use of CLLocationManager class in iPad?

Question: Can we use CLLocationManager class to determine the position of the user in an iPad app  or is it used only for iPhones?
Answer: Yes, it works fine on iPads.  However, the location accuracy is based on WiFi only unless it is a 3G iPad which has GPS.
Comment: Thanks dude....can u tell me that can we determine the location in an iPod touch also because it also supports WiFi using CLLocationManager and how accurate will it be?
Comment: It will vary significantly depending on how many wifi spots can be seen by the device.  See [this blogpost](http://www.jeremyjohnstone.com/blog/2010-04-08-ipad-geo-location-accuracy.html).  Location accuracy on an iPod Touch would be the same as a WiFi only iPad.
Comment: Thanks for the information.It is quite helpful for me.Is there any refrence or some sample app available ...it will be quite helpful.thx
Comment: [Searching](http://www.google.com/search?hl=en&q=CLLocationManager+OR+CoreLocation+tutorial+OR+example+iphone&aq=f&aqi=&aql=&oq=&gs_rfai=) finds several examples and tutorials.

use of CLLocationManager class in iPad?


Show that an irregular 1-set in the plane is totally disconnected

Question: A $1$-set is a Borel set such that $0 < \mathcal{H}^1(A) < \infty$, where $\mathcal{H}^s$ is the Hausdorff measure.
Let $A$ be an irregular $1$-set in the plane. Deduce from the theorem below that $A$ is totally disconnected.

Definition of $Proj_{\theta}$ is

and definition of irregularity is

and here is my definition of totally disconnected.

A set $F$ is totally disconnected if and only if $\forall x \in F$, if $U$ is connected subset of $F$ and $x \in U$ this implies that $U=\{x\}$.

I think that you should be able to do this by contradiction. So...

Suppose for contradiction that $\exists x \in F$ and $U$ which is connected subset of $F$ such that $x \in U$ and that $U$ contains at least two points with $x \neq y$. Let us denote one of the other points by $y$. Now the projection of any connected set is a connected set and any connected subset of $\mathbb{R}$ is an interval. Now as F is an irregular $1$-set in $\mathbb{R}^2$ we may apply Theorem 5.4.2 so the $proj_{\theta}$ has zero length. Therefore as $U \neq \emptyset$ $U=\{x\}$ and $x=y$. This is contradiction as $x$ and $y$ were distinct, therefore $F$ is totally disconnected.

However I am not sure how to choose my $\theta$ (or how to apply Theorem 6.4). I feel that the last half of my attempted proof fades in rigour.
Comment: Could you add the definition of irregularity and $\text{proj}_\theta$?
Answer: Let $F,U,x,y$ be as in your attempt.

For every $\theta$ the projection map $\operatorname{proj}_\theta$ is continuous; hence, $\operatorname{proj}_\theta (U)$ is connected.
A connected subset of a line with two distinct points has positive length.
For all $\theta\in [0,\pi)$ except one (the one parallel to the line segment $xy$), $\operatorname{proj}_\theta(x)\ne \operatorname{proj}_\theta(y)$.
Combining 1,2, and 3, we have a contradiction with Theorem 6.4.


fortran get system environment info in openvms

Question: Is it possible to get system environment information on Fortran 90 (OpenVMS operating system)? I use compiler VSI Fortran V8.3-104957-50Q83.
I won't realize the next C-code on Fortran
<code>char *bind_addr= getenv("MYSQL_TEST_BINDADDR");
</code>
Comment: Have a look at _Section 10.10_ of the [VSI Fortran for OpenVMS User Manual](https://vmssoftware.com/docs/VSI_FORTRAN_USER.pdf). It explains how you can link a Fortran program with a self written C-library. So you could quickly write a wrapper for `getenv` in C and link it with Fortran according to the procedure defined that document.
Comment: Did you try whether `getenv` exists in your compiler? There is nothing standard in Fortran 90, everything is compiler specif, just like your previous question about  command line arguments.
Comment: After checking the documentation of vmssoftware, I'm unable to find any compiler extension that allows you to extract environment variables. It also only supports Fortran 90/95 and not 2003. The latter has the subroutine `GET_ENVIRONMENT_VARIABLE`. However, your compiler does not support Fortran 2003. The only suggestion I might make is an attempt to call the C-function `getenv` directly into Fortran, but that is again a compiler dependent hack.
Answer: This topic is one in a series of questions on what appears to be a porting effort for an
"C" application to Fortran on OpenVMS. In order to provide the best possible answers it may help to know a bit more background - WHY the effort is taking place, WHAT is the source platform?
That said, Environment Variables as most of us know them do NOT exist as such on OpenVMS.
OpenVMS DCL SYMBOLS and User/group/system LOGICAL NAMES which can and will be treated as environment variables by support libraries such as available through the C-RTL, Perl and Python.
To define them, one expects a shell (DCL) action selecting either symbols or logical names as the vehicle. Knowing that mechanism the application to be ported may just want to call the native OpenVMS functions to get or set the values (SYS$TRNLNM, LIB$GET_SYMBOL, LIB$SET_SYMBOL).
Writing your own 'my_getenv' wrapper to call the C-RTL provided getenv may be a good solution if you have access to a C compiler.
Another workaround could be to reverse engineer and call the actual C support function (likely called DECC$GETENV - not verified!) this may require some initialization to be called first (again, not verified)
Surely there are more articles on this out there. Google?
For some background on symbols and logicals the documentation and FAQ should help.
For example - http://www.hoffmanlabs.org/vmsfaq/vmsfaq_012.html
Good luck,
Hein.


Server timezone changed to PHT but logs still written in MST?

Question: A couple of days ago, I updated the timezone on an Ubuntu 12.04 LTS server using $ sudo dpkg-reconfigure tzdata.
Today I noticed while tailing the mail log, that the times were still 15 hours behind. I immediately checked the server date but it's set to PHT as expected.
The following shows the last line of the terminated, tailed log (written just seconds earlier), followed by the data command.
Sep 20 01:24:07 s2 postfix/smtpd[13740]: disconnect from mail1282.news.laredoute.co.uk[220.127.116.11]
^C
root@s2:~# date
Fri Sep 20 16:24:12 PHT 2013

I've tried reloading Postfix, to no avail.
Answer: If Postfix is chrooted, you may need to copy /etc/localtime to your chroot/etc dir i.e: /var/spool/postfix/etc/localtime for Postfix to see it.
Make sure /etc/localtime is not a symlink, if it is, then you will need to copy the actual timezone file from /usr/share/zoneinfo/country/city
Comment: After backing up `/var/spool/postfix/etc/localtime`, I over-wrote it with the copy form `/etc/localtime` and restarted Postfix. It still hasn't picked up the changes, although I do note that the old localtime file that I backed up does have references to MST in it.
Answer: After changing the system time zone, you need to restart the system logger (or any other service that uses the timezone).


Auto Round Off in Python3

Question: I wrote a code for finding the 'j' for the General Annuity
from __future__ import division

R = float(38973.76)
n = int(3)
r = int(8)
m = int(4)
mSubj = int(1)
t = int(3)
ans = ((1 + r / m) ** m)**(1 / mSubj) - 1

print(ans)

now the answer is 80.0
instead of 0.008243216 that I solved in Scientific Calculator.
Comment: Can you explain on how you are expecting `0.008243216`? What formula are you trying to emulate?
Comment: You don't need to specify types with `int()` and `float()`. `38973.76` is the literal notation for a `float`, `3` is the literal notation for an `int`.
Comment: Can you post the math formula? Python is indeed correct.
Comment: 0.008243216 is the answer in Scientific Calculator with the same calculations of formula
Comment: @L3viathan Line 1 doesn't give `0.008243216` either.
Comment: @L3viathan Oops. Unrelated: that line isn't necessary if the OP really is using Python 3.
Comment: https://imgur.com/3FDDz5c
Comment: wait the frick up I forgot to convert the r (rate) into decimal. Its ok now! Thanks to all of you`
Answer: Your R variable is the capital one, not r.
so it should be ans = ((1 + R / m) ** m)**(1 / mSubj) - 1
Comment: so you declared `R` for what?
Comment: This also doesn't give the expected result though.
Comment: nah mate, r and R is different.
Comment: I just forgot to convert the r (rate) into decimal
Comment: for the next formula! HAHAHA

Auto Round Off in Python3


$arr = array (1,2,3,4,5,6,7,8,9,10); como faço para somar apenas os numeros pares dentro do array em php?

Question: tenho um Array:
$arr = array (1,2,3,4,5,6,7,8,9,10);

Gostaria de saber como faço para somar apenas os números pares dentro do array do vetor em PHP?
Comment: Caro rafael o basico é fundamental, podem até lhe sugerir array_filter, como se fosse a solução de todos problemas, mas o básico é essencial para se aprender programação, então for e foreach sempre resolverão de forma mais clara e reaprovetavel a aprender sem recursos avançadados, com a resposta https://pt.stackoverflow.com/a/110927/3635 basta dentro da IF para checar se é par, somar a uma variavel fora do `for` e após o ciclo do for terá o resultado.
Comment: para somar usaria isso: <?php $arrays = array (1,2,3,4,5,6,7,8,9,10); $soma = 0; foreach($arrays as $array){ if(is_int($array/2)){ $soma = $soma+$array; } } echo "soma: ". $soma;
Answer: Use a função array_reduce que reduz um array para um único valor através de um processo iterativo via função callback.
<?php

$arr = array (1,2,3,4,5,6,7,8,9,10);

//Para cada elemento array aplica uma função redutora
$soma = array_reduce($arr, function($carry, $item){
  //Testa par ver se o número é par se for soma o elemento senão mantém o valor
  return $item % 2 == 0 ? $carry + $item : $carry;
});

echo $soma;

Teste no Repl.it
Outra possibilidade é iterando sobre os elementos da array e testando para ver se são pares
<?php

$arr = array (1,2,3,4,5,6,7,8,9,10);

$soma = 0;

//Para cada elemento do array
foreach($arr as $item){
   if ($item % 2 == 0) $soma += $item; //O Soma apenas se for par
}

echo $soma;

Teste no Repl.it
Comment: Caro Augusto, vale ressaltar na resposta o porque usou o terceiro parametro como `$arr, callbac, 1`, para resumir, a conta é de multiplicação, se o argumento fosse omitido o resultado seria zero, já que `$carry` iniciaria como NULL mesmo, logo internamente o PHP trataria a operação matematica como zero a multiplicação https://repl.it/@inphinit/multiplication-vs-null-php
Comment: um dos motivos do porque não formulei a resposta e raramente sugiro funções como `array_reduce`, é porque eventualmente isto leva a pessoa a pular passos importantes do aprendizado básico, não estou dizendo que devam seguir o que eu acredito, mas em quase todas areas da TI vejo o mesmo problema, uso de coisas sem entendimento real, e me sou obrigado a dar o braço a torcer, o SOen e pt viraram sites de copia e cola
Comment: Não é sindrome do TOC não (apesar de muita gente insistir que sofro disto :P) ... mas parenteses não são necessários antes do `?` em `return ($item % 2 == 0) ? $carry + $item : $carry;` ... quero dizer, se fosse separas a lógica ou até organizar a identação acaso houvesse quebra de linha seria OK, mas ali é um pouco redundante. PS: +1 pelo edit
Comment: @GuilhermeNascimento eu não sei de onde tirei a multiplicação. Fiz a correção. E sim na multiplicação um `$carry == 0` zeraria o resultado. Adicionei também um exemplo utilizando iteração por laço.
Comment: @GuilhermeNascimento que isso. Toda orientação para melhoria é bem vinda. Eu vou não mexer agora porque estou jantando e passei só para dar uma olhada mesmo. Quando eu voltar eu acerto. Porém se você sentir a necessidade de editar qualquer uma de minhas publicação eu tenho plena confiança em sua intervenção.


How to detect the Task Scheduler trying to terminate a program due to the "Stop if the computer switches to battery power" option

Question: Background
I am writing a PowerShell script that runs from Windows Task Scheduler and resides in the task tray.
Problem
When you create a new task in Task Scheduler, the option Start the task only if the computer is on AC power and Stop if the computer switches to battery power are on by default.
But I don't want to stop the script when the AC adapter is plugged off. So I want to detect the Task Scheduler trying to stop the script when it switches to battery power and let the user set these options off.
Question
In a PowerShell script, is there any way to detect the Task Scheduler trying to terminate the script due to the "Stop if the computer switches to battery power" option?
Answer: You can likely detect that it is has happened, but you can probably only stop it from happening by changing the options on the scheduled task.
There should be an entry in the Task Scheduler's event log when a task is stopped due to battery power switches, and another when tasks are not started due to not being on AC power.
Since I type this on a desktop, I don't have easy access to what those event IDs would be.
I'd create a test task and see what the event IDs are, and then, if you'd like, you could create a scheduled task that triggers on either of those events.


Proving that for a set $U\subset C$, $U$ is open if and only if for all $x \in U$, there exists a region $R$ such that $x \in R \subset U$.

Question:
Prove that for a set $U\subset C$, $U$ is open if and only if for all $x \in U$, there exists a region $R$ such that $x \in R \subset U$.

I just have no idea how to start and was wondering if anyone could maybe help me at least get started or get an idea on the intuition behind this theorem? I'm having trouble even visualizing why it would be true. Thanks!
The definition for an open set used in class is that a set $U$ is open if the complement $C\setminus U$ is closed where $C$ is the continuum.
The continuum is defined as being non-empty, having no first or last point, and having an ordering $<$. A closed set is one that contains all of its limit points and a region (a,b) is a set containing all points $x$ between a and b.
Comment: I think I have to somehow connect the region $R$ existing with the complement $C\setminus U$ being closed, but not sure how I would go about doing so.
Comment: Some definitions are not clear here. What do you mean by the *continuum* $C$: the real numbers? What is a *region*: an open interval? What is the definition of *closed* in your class: a set that contains all its limit points? As written your question is too vague and confusing.
Comment: Sorry about that, fixed the question!
Answer: Here's the idea of the proof: show the contrapositive.
Take an $x \in U$  such that for every open interval $R$ that contains $x$ we have $R \not \subset U$. This means that $x$ is a limit point of $C\setminus U$ without $x$ in $C\setminus U$. This means that $C\setminus U$ is not closed, so $U$ is not open.
Can you fill in the details?
Comment: Ok, thank you so much! I'm having a bit of trouble seeing how the first sentence implies that x is a limit point of the complement of U however? I think it has something to do with every region R having an $x\in R$ and a $y\in C\setminus U$ but I can't figure out how that connects with the definition of a limit point. Thanks again!
Comment: @Twis7ed: I do not know what your particular definition of limit point is. But in some books, a limit point of a set is a point for which every open interval containing the point also contains another point in the set. That definition leads directly to $x$ is a limit point of $C\setminus U$. What is your given definition of limit point?


How to define R squared on a subset of the original sample?

Question: Suppose I fit a linear model
$$y = X\beta + \epsilon$$
and I can derive the coefficient of determination, also known as the R squared, by calculating
$$R^2 = 1 - \frac{SS_{res}}{SS_{tot}}$$
where
$$SS_{res}=\Sigma e_i^2$$ and
$$SS_{tot}=\Sigma (y_i-\bar{y})^2$$
Now I also want to know how well the $e>0$ side and $e<0$ side fits, respectively. Is there a measure to determine the "R squared" of a linear model on a subset of the original sample which also results in $[0,1]$?
I notice there's a concept called partial R squared but it is about measuring the fitness of a subset of regressors rather than a sub-sample.
Answer: $$R^2 = \dfrac{SSTot-SSRes}{SSTot}$$
Let's break down what those mean.
$$SSTot = \sum_i (y_i - \bar{y})^2$$
The regression that you're doing wants to predict the mean of the distribution of your response variable conditioned on some predictors. In the absence of knowing anything about how your data are generated, why not guess the overall mean? $SSTot$ is the total sum of squares and measures your error when you use the overall mean of $y$ as the prediction, no matter what predictors you have. This may be a naive approach, but it's a good baseline.
$$SSRes = \sum_i (y_i - \hat{y})^2$$
However, now that you've run your regression, you think you have more insight than you did when you were just guessing the overall mean of all $y$ values. Now see how much error you have when you use your predictions from the regression!
With those two values calculated, you can do the arithmetic to find $R^2$. Now, you want to do it on a subset of the data. I see two options. Let there be $j$-many observations in your subset.
1) $\dfrac{\sum_j (y_j - \bar{y})^2 - \sum_j (y_j - \hat{y})^2}{\sum_j (y_j - \bar{y})^2}$
2) $\dfrac{\sum_j (y_j - \bar{y}_{subset})^2 - \sum_j (y_j - \hat{y})^2}{\sum_j (y_j - \bar{y}_{subset})^2}$
The first option uses the same average value as you get when you look at the whole data set, while the second computes the average of your subset. I think I can squint and see a reason to do option #2, but I wouldn't do it. $R^2$ is a way of measuring how you do compared to naively guessing the overall mean, so I'd want to see how each subset does compared to guessing the overall mean.
Edit: Thinking about it more, I completely reject option #2. If you want to compare to the mean of the subset, rerun the regression on just the subset and calculate $R^2$ the usual way, but then you're not using the same regression equation or even the same significant parameters (it's a totally different problem).
Answer: R-squared (R2) can be calculated as:
R2 = 1.0 - (absolute_error_variance / dependent_data_variance)
so if you can calculate these variance values for the data subset, it should work as you want.


how to output the minimum value from array on the website

Question: i have the input values and js creates the array. I need that all values should be sorted by values and output the min value on the web page. User should see  smth like this: the subject where u get (3(for example)) should be improved in next few days. please guys!

document.querySelector('button').addEventListener('click', function(e) {
  var inputs = document.querySelectorAll('input');

  var obj = [].reduce.call(inputs, (accumulator, currentValue, currentIndex) => {
    accumulator[`val${currentIndex}`] = currentValue.value
    return accumulator
  }, {})

  console.log(obj)
});
<form>

            Biology:<input type= "text" >

            Chemistry:<input type= "text" >

            Physics:<input type= "text" >

            Math:<input type= "text" >

  <button type="button">Go</button>
</form>
Answer: Put all the values in an array and use this: Math.min(...name_of_array) ;
Example:
var arr = [4,1,2,0,9,5];
Math.min(...arr) ;

The output will be: 0
Answer: create an array of scores, then calculate min value:
const scores = [...inputs].map( x => Number(x.value) );
const min = Math.min( ...scores );

Answer: Instead of reduce, you can use map to save inputs value into an array and sort it.
document.querySelector('button').addEventListener('click', function(e) {
  var inputs = document.querySelectorAll('input');

  var values = [].map.call(inputs, inputEl => inputEl.value);
  values.sort();

  console.log(values);
});

The minium value is values[0]
Answer: you can do like this by using jquery
<!DOCTYPE html>

<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>

<form>

            Biology:<input type="text" />

            Chemistry:<input type="text" />

            Physics:<input type="text" />

            Math:<input type="text" />

    <input type="button" onclick="MinValue('input')" value="Go" />
</form>

Answer: Details are commented in demo

// Reference the DOM elements
// Get the first <form> on page
const form = document.forms[0];
// Collect all form controls with [name=grade] into a NodeList
const inputs = form.elements.grade;
const minCell = document.querySelector('.MIN');
const maxCell = document.querySelector('.MAX');

// Register the <form> to the click event
form.onclick = calc;

// Event handler passes event object
function calc(e) {

  // if clicked tag (ie e.target) is a button tag...
  if (e.target.tagName === "BUTTON") {

    /*
    covert NodeList into an array
    create an array of input values
    and convert them into Numbers
    then return the array of Numbers
    in order from least to greatest
    */
    let ordered = [...inputs].map(input => Number(input.value)).sort((a, b) => a - b);
    console.log(ordered);
    // Display the first Number of the Number array
    minCell.textContent = ordered[0];
    // Display the last Number of the Number array
    maxCell.textContent = ordered[ordered.length - 1];
  }
}
:root,
body {
  font: 700 small-caps 2vw/1.45 Consolas;
}

table,
td {
  table-layout: fixed;
  border-collapse: collapse;
  width: 200px;
  border: 1px solid #000
}

td {
  padding: 2px;
  width: 50%;
  text-align: right;
}

tfoot tr:first-of-type td {
  text-align: left;
}

tfoot tr:first-of-type td::before {
  content: attr(class)': ';
}

caption {
  font-size: 1.25rem
}

input {
  font: inherit;
  text-align: right;
  display: block;
  width: 85px
}

button {
  font: inherit;
  text-align: right;
}

.as-console-wrapper {
  width: 350px;
  min-height: 100%;
  margin-left: 45%;
}
<form>

Grades

        Biology:
        <input name='grade' type="number" min='0' max='100' value='0'>

        Chemistry:
        <input name='grade' type="number" min='0' max='100' value='0'>

        Physics:
        <input name='grade' type="number" min='0' max='100' value='0'>

        Math:
        <input name='grade' type="number" min='0' max='100' value='0'>

        <button type="button">GO</button>

</form>


Trying to display the content of radio buttons in a form

Question: I am creating a quiz using jQuery.
I have established the quiz questions and answers in a 2-dimensional array.
I have the answer choices (1-5) displayed in a separate array.
I have stored the answer choices to temporary variables and want to display them next to radio buttons.
The answer choices (noted in my code as answerA=answerChoices[j][0], etc) are being input correctly but they are not displaying. When I inspect the elements in Chrome, I see that they are being brought in. However they are not displaying next to the form element in #quizQuestion.
I am sure I am doing something silly but cannot identify it. CAN YOU HELP?
Here's the html:

  <INPUT type="submit" value="Start quiz now" id="startQuiz" class="viewable">

      <form name="answerForm">
        <input type="radio" value="a" id="answerA" name="quizAnswer">

        <input type="radio" value="b" id="answerB" name="quizAnswer">

        <input type="radio" value="c" id="answerC" name="quizAnswer">

        <input type="radio" value="d" id="answerD" name="quizAnswer">

        <input type="radio" value="e" id="answerE" name="quizAnswer">

      </form>

And here's the jQuery:
var questionAnswer=[
['How many moons does Earth have?',1],
['How many moons does Saturn have?',31],
 ['How many moons does Venus have?',0]
];

var answerChoices=[
[1,2,3,4,5],
[18,32,15,1,9],
[3,5,1,0,9]
]

function askQuestion(j){
    //create radio button answer choices a-e
    //var radioBtn =$('<input type="radio" name="rbtnCount" value="a"  id="q1a"/>'+question[0,1]+'
');
    //display questions
    //console.log(radioBtn);
var answerA=answerChoices[j][0];
var answerB=answerChoices[j][1];
var answerC=answerChoices[j][2];
var answerD=answerChoices[j][3];
var answerE=answerChoices[j][4];

    if($('#startQuiz').is(':visible')) {
        $('#startQuiz').toggle();
        }
    if($('.answerBox').is(':hidden')) {
        $('.answerBox').toggle();
        $('.answerBox').css('margin-top','20px');

        }
        // display the question
        $(".theQuestion").css('margin-top','75px');
        $("#quizQuestion").text(questionAnswer[j][0]);
        //display the answers
        $('form #answerA').text(answerA);
        $('form #answerB').text(answerB);
        $('form #answerC').text(answerC);
        $('form #answerD').text(answerD);
        $('form #answerE').text(answerE);

    };

$(document).ready(function(){

    $('#startQuiz').on('click',function(event){
        event.preventDefault();

        for (var i=0; i<=questionAnswer.length; i++)
            {
                askQuestion(i);
            }
        });

});

Comment: It would be helpful if you can put your code in a JSFiddle
Answer: You can't set text() to a radio button, so you have to have some kind of label next to the radio button:
update:
<input type="radio" value="a" id="answerA" name="quizAnswer">

to
<input type="radio" value="a" id="answerA" name="quizAnswer">

and update your jQuery:
$('form #answerA').text(answerA);

to:
$('form label[for="answerA"]').text(answerA);

JSFiddle Example
http://jsfiddle.net/moogs/RWk3E/1/


Open .html page within same window only once. File run locally

Question: I have a html file that will be run locally using IE. I want it to function more like an app, it will not be published to a site, I'm only using IE to view it. The code that follows will provide basic functions to do simple calculations. I've not been able to successfully use the window.onload event to create a new window that removes the scroll bar, title bar, menu, etc without it looping. I'm not sure if an If statement or a while statement is best for testing if the page is already open to stop the loop and I'm having a hard time understanding the syntax of how to test if the window.onload already has the window open. I guess I'm looking for some guidance on setting this up or a reference easily understood by a beginner. Thank you.
I at present have two html files. The first, its only purpose in life is to trigger the second to load as I want it to show.
<code>function openWindow()
        {
            window.open("CouchShifts.html", "", "status=no,toolbar=no,menubar=no,navigationbar=no,location=no,resizable=no,scrollbars=n, width=440,height=200'");
        }
        window.onload = openWindow()
        window.close("test.html")
</code>
I had tried to incorporate this idea into the original html file without success. Any starts on how to better handle this so that when the standalone html file is double clicked from the desk top it open as specified above only once without looping?
Answer: It's not wise to check window is open or not in the same windows onLoad. You should check it rather in the event that actually opens the window.
Here are some solutions for this.
Check if window is already open window.open
https://stackoverflow.com/a/10467344/672455


Odds of two names appearing together in a print ad - help with a gift to boyfriend.

Question: A print ad (for Loving Embrace pendants) used my name, Jennifer and my boyfriend's name, Matthew in their sample pendant.  What are the odds that those two names would be choosen?  Howmanyofme.com shows that there are 1,521,455 Jennifer's in the US and 1,075,792 Matthews.
It doesn't have to be perfect; I'm just going to send him the advertisement with a note and would like to let him know what the odds are that we'd be paired together.
Answer: Assuming that the probability of them picking your names out of all the available names for your gender is equal to the frequency of your name in the population of women/men (probably not a great assumption but it makes use of the data you gave!) and using the first figures on google that came up, that there are $157$ million women and $151.8$ million men in the US, the probability of both your names being chosen is: $$ \frac{1,521,455}{157,000,000}\frac{1,075,792}{151,800,000} \approx \frac{1}{14561}$$
Note answer for entertainment purposes only :)
Comment: As your disclaimer suggests, this is an estimate of the probability that, when picking a woman and a man at random from the US population, their names are Jennifer and Matthew.  Whoever prepared the ad probably chose from a small set of popular names.


How have I incorrectly calculated the area A inside the curve $r =1$ and outside the curve $r = 2\cos(\theta)$

Question: I hope this isn't against guidelines but I want to show how I solved this on white paper, it might be clear where my logic went wrong in solving.
Find the are A of the region inside the curve $r = 1$ and outside the curve $r = 2cos(\theta)$

Thank you
Comment: Not checked all this through - but how do you go from $\cos^2(x)$ to $\frac{1}{2} + \frac{1}{2}\sin(2x)$ I would agree if you had $\cos(2x) = 2\cos^2 x - 1$
Comment: I've been trying to visualize the area that $0.5\int_{\frac{\pi}{3}}^{\pi} (2\cos (\theta))^2$ represents and if that's the area that we want to take off. It doesn't seem like it.
Comment: Here's what I came up with there's no way that is going to be what we want to take off. Think about $\int_{\frac{\pi}{2}}^{\pi} 0.5(2\cos (\theta))^2 d\theta$ represents. It represents the area of the top semi-circle. The best approach I can see is to split the area into parts.
Comment: @Chinny84 I thought that was the double angle identity?
Comment: @AhmedS.Attaalla Can't we just integrate from the first intersection point to π and since we know that's half of the area we need can't we can double that amount? That's the approach I am most comfortable with doing. But I need to learn the others too.
Answer: You cannot integrate both over the interval $\left[\frac{\pi}{3},\pi\right]$.
The largest part is the quarter circle in the second quadrant which we know must have area equal to $\dfrac{\pi}{4}$ but it can be easily verified:
\begin{equation}
\frac{1}{2}\int_{\pi/2}^\pi 1\,d\theta=\left[\frac{\theta}{2}\right]_{\pi/2}^\pi=\frac{\pi}{4}
\end{equation}
It is only the part in quadrant I that is bounded by both functions:
\begin{eqnarray}
\frac{1}{2}\int_{\pi/3}^{\pi/2}1-4\cos^2\theta\,d\theta&=& \text{ continue from here}\\
\end{eqnarray}
Comment: By the way, $\cos^2\theta=\dfrac{1+\cos(2\theta)}{2}$ not $\dfrac{1+\sin(2\theta)}{2}$ as you wrote on your paper.
Comment: Thank you! I see I had that ID wrong. Please can you explain why we cannot both integrate over pi/3 to pi? I thought since pi/3 is where it intersects then we can just start there and integrate till pi, and since that is the same area under the x-axis we could just double it? What am I misunderstanding?
Comment: The $r=2\cos\theta$ graph goes to $0$ at $\dfrac{\pi}{2}$ so it does not form a lower bound for the region between $\dfrac{\pi}{2}$ and $\pi$. In fact it crosses over into the fourth quadrant. So if you include $r=2\cos\theta$ on that interval you are actually subtracting that portion of the region lying in the third quadrant from the actual sum. Try just integrating from $\dfrac{\pi}{2}$ to $\pi$ using both functions. You know you should get $\dfrac{\pi}{4}$ but you get instead that value *minus* the area in quadrant IV.
Comment: To be very honest, I am totally confused by what you said. Why did you bring up 0 to π/2? what do you mean it does not form a lower bound for the region between π/2 to π, this statement confuses me, what do you mean by lower bound?
Comment: I did not bring up the interval $[0,\frac{\pi}{2}]$, I said that $r=2\cos\theta=0$ when $\theta=\frac{\pi}{2}$. As far as upper and lower bounds in polar coordinates, think of a ray going out from the pole $(0,0)$. The first curve it encounters is the "lower bound" and the second curve it encounters is the "upper bound."  For $\frac{\pi}{2}\le\theta\le\pi$ there is no lower bound for the region, only the upper bound $r=1$. The $r=2\cos\theta$ is completely "out of the picture" over that range of $\theta$ values.  @Ahmed S. Attaalla's diagram explained it well, and with the correct answer.
Comment: I have made a desmos.com graph of the problem, but it is just a duplicate of your hand drawn diagram. Notice that what you are looking for is just two-thirds of the area of the circle minus the two red regions. So find the area of one of the red regions and subtract twice that amount from $\frac{2\pi}{3}$. That should give the correct answer.
    https://www.desmos.com/calculator/bmvphdj43l
Answer:
The area of the blue and yellow pieces together is,
$$\int_{\frac{\pi}{3}}^{\pi} \frac{1}{2}(1)^2 d\theta=\frac{\pi}{3}$$
The area of the blue piece by itself is,
$$\int_{\frac{\pi}{3}}^{\frac{\pi}{2}} \frac{1}{2}(2\cos (\theta))^2 d\theta$$
$$=\int_{\frac{\pi}{3}}^{\frac{\pi}{2}} 2\cos^2(\theta) d\theta$$
$$=\int_{\frac{\pi}{3}}^{\frac{\pi}{2}} 2\left(\frac{1+\cos(2\theta)}{2} \right) d\theta$$
$$=\frac{\pi}{6}-\frac{\sqrt{3}}{4}$$
Thus the area of the yellow piece is,
$$\frac{\pi}{3}-(\frac{\pi}{6}-\frac{\sqrt{3}}{4})=\frac{\pi}{6}+\frac{\sqrt{3}}{4}$$
The area you are interested in is twice this:
$$A=\frac{\pi}{3}+\frac{\sqrt{3}}{2}$$
Comment: Thank you, I feel like I still don't understand what I was doing wrong. In your answer I see how we area getting ALL that area with the first equation. But I don't understand how we are getting the blue piece by itself with the second equation, could you please explain more about that.
Comment: Please tell me what I did wrong. My idea was to integrate from the first intersection point till pi, therefore that would give me exactly half of the area, then I just doubled that area. For the integral I thought the idea would be, (wanted area minus not wanted area) . Then compute.
Comment: What happens (especially to $r=2\cos(\theta)$) when $\theta \in [\frac{\pi}{2},\pi]$ are we bounded below by $r=2\cos(\theta)$ and above by $r=1$? @yre
Comment: The second integral gets the blue piece because the blue price is bounded below by $r=0$ and above by $r=2\cos(\theta)$ as $\theta$ ranges between $\frac{\pi}{3}$ and $\frac{\pi}{2}$.
Comment: Sorry, still not understanding. When we rotate between pi/2 to pi, wouldn't there be no $2cos(\theta)$? Because pi/2 is where $r = 2cos(\theta)$ ends, the yellow is from 0 to to 2pi or a full circle right? There is something I am not getting here.
Comment: Isn't from pi/3 to -pi/3 only the stuff within yellow? so anything in between is only r = 2?
Comment: No from $\frac{\pi}{2}$ to $\pi$  you are tracing out the top of the semicircle $r=2\cos(\theta)$ (in a clockwise path). Look at the values you have in your table.
Comment: Why clockwise? I thought all of these polar graphs followed a strictly counter clockwise motion? Yeah, I am really not understanding at all, still thank you, I wish this made sense to me....


How to tell the gcc to look in the include folder for the header files?

Question: I'm using c. And I have a include folder inside my project myProject/include and inside I have all the header files from the SDK I downloaded from the Internet. So my question is how can I tell the gcc to look for the header files inside the include folder?
Answer: You can use the -I option with gcc to tell the path where to look for the header files.
From online gcc manual

-Idir
  Add the directory dir to the head of the list of directories to be searched for header files. This can be used to override a system header file, substituting your own version, since these directories are searched before the system header file directories. [...]

You can use this option multiple times,

[...] If you use more than one -I option, the directories are scanned in left-to-right order; the standard system directories come after.


How to solve Rails/RedundantPresenceValidationOnBelongsTo offense detected without rubocop autofix (which breaks the code)

Question: I have some work which doesn't touch the file in question but due to some rubocop update it's now showing:

Rails/RedundantPresenceValidationOnBelongsTo: Remove explicit presence
validation for creator

Which later mentions is auto-correctable but using autofix breaks the code
Answer: I was able to solve this by doing two things:

Adding the file path to the your rubocop file

<code>    Lint/RedundantCopDisableDirective:
      Exclude:
         - 'path/to/my/file.rb'

</code>

Wrap the offending lines around with disable and enable comments

<code>    # rubocop:disable Rails::SkipsModelValidations
    validates :something,        presence:  true, on: :create
    # rubocop:enable Rails::SkipsModelValidations
</code>


Should my JSON data contain a nested field versus duplicate information?

Question: I will be importing data in a JSON file into Google BigQuery and would like to know if it is best practice to nest fields and add a field with schema mode "repeat" in order to avoid duplication or leave the duplicated information to have less nesting. Another reason to leave the duplicated information is, because, as far as I can tell, BigQuery works best with denormalized data. However, I am not sure if this denormalization should be done after or before the data import.
For example, assume my data is:
Nested version
{
   "store": "Pete's Market",
   "city": "NYC",
   "product": [
      {
          "id": "2468",
          "item": "apple",
          "price": "$1"
      },
      {
          "id": "1357",
          "item": "cereal",
          "price": "$3",
          "brand": "Cheerios"
      }
   ]
}

# The actual JSON data file will have this in one row:
# {"store":"Pete's Market","city":"NYC","product":[{"id":"2468","item":"apple","price":"$1"},{"id":"1357",item":"cereal","price":"$3","brand":"Cheerios"}]}

Duplicated information version
{
   "store": "Pete's Market",
   "city": "NYC",
   "product":
      {
          "id": "2468",
          "item": "apple",
          "price": "$1"
      }
}
{
   "store": "Pete's Market",
   "city": "NYC",
   "product":
      {
          "id": "1357",
          "item": "cereal",
          "price": "$3",
          "brand": "Cheerios"
      }
}

# The actual JSON data file will have this in two rows:
# {"store":"Pete's Market","city":"NYC","product":{"id": "2468","item":"apple","price":"$1"}}
# {"store":"Pete's Market","city":"NYC","product":{"id":"1357",item":"cereal","price":"$3","brand":"Cheerios"}}

Extra notes
There could be be thousands of products, the field with mode repeat in the nested version. Some products may have fields that others do not. The fields in each product could have 2-3 more nested levels.
Question reiterated
Is it best practice to nest fields and add a field with schema mode "repeat" in order to avoid duplication or leave the duplicated information?
Answer: If your data is write-once or append-only, then there is only slight usability difference (explained below), either one works fine, with normalized one being slightly cheaper to store and scan.
Minor usability difference:
-- With nested schema
SELECT *  -- here all product's sub fields are entering parent namespace and no way to rename them in batch
FROM table, UNNEST(product) prd

But if you want to update only certain Product later, nested Product makes it pretty difficult to do, because there is no way to update single item in REPEATED field, you have to load the whole array, scan and change, and repack to update a column. You will be writing something like:
UPDATE table
SET product = (SELECT ARRAY_AGG(...) FROM UNNEST(Product) WHERE ...)
WHERE ... -- filter to specific products

In this case, denormalized form will be easier to deal with.


Putting Back button on waze, while navigation

Question: I am opening waze from my app and i want a button which will take me back to my app when clicked, i have already done it for google maps like we have to do as :
NSString *urlString = @"comgooglemaps-x-callback://";
NSString *backButton =@"&x-success=MyApp://?resume=true&x-source=MyApp";

if ([[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:urlString]])
{

urlString = [NSString stringWithFormat:@"comgooglemaps-x-callback://?daddr=%@%@", [[NSString stringWithFormat:@"%@",
address] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],backButton];

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];

}

Can something like be done in waze?
Answer: Try this
NSString *stringURL = @"waze://?ll=37.331689,-122.030731&z=10";
NSURL *url = [NSURL URLWithString:stringURL];
[[UIApplication sharedApplication] openURL:url];

Comment: i am able to open the waze with the location, but what i want is to have a back button into the waze which will take me to my application
Comment: You can't do that... iOS 9 will allow to go back to the previous app with a button in the top left of your screen, but that's the only possible thing.
Comment: Well i guess then it is the google api which is allowing a back button to the google map, using `comgooglemaps-x-callback:`