Linguagem com Garbage Collector pode ser usada para jogos?

Question: Comecei aprender C# e até Java por interesse em desenvolvimento de jogos. Mas sei que muitos são desenvolvidos com C++, principalmente por não ter um garbage collector. Claro que eu sei que vários jogos são feitos em C# e Java.
Imagino que seja a pausa que causa problema. O que eu quero saber mesmo é como é resolvida a pausa no desenvolvimento de um jogo feito nestas linguagens.
Comment: Também tenho interesse em jogos e nessas linguagens - não entendi por que "a pausa" causaria qualquer problema - de que pausa você está falando?
Comment: @DanielGomes vc aparece no cenário em uma máquina, manda pra outra essa informação, o outro jogador verá você pra atirar, mas antes de mostrar começa uma coleta, o jogo atrasa por causa disto, aí aparece, ele dá um tiro, só que na sua máquina não teve pausa, você não está mais ali. Você deve tomar o tiro? Fica esquisito. Se não deve o outro jogador não conseguiu te matar porque o software não deixou e não por causa na inabilidade dele.
Comment: A linguagem Go tem dedicado muito esforço a diminuir a pausa causada pelo coletor de lixo, de modo a não ser um problema.
Answer: Qualquer linguagem que use um coletor de lixo em sistemas real time terá problemas porque o tempo de liberação da memória não é determinístico, que é uma característica fundamental para sistema em tempo real. Mesmo em memória manual é um problema quando há cascata ou o algoritmo de alocação ou liberação é eficiente em economia de memória e pode ter dificuldade de lidar com a free list de memória. Quando tem uso de memória dinâmica o real time de verdade não é possível.
Aplicações semi real time já ficam mais fáceis porque ninguém morrerá se tiver um pequeno atraso eventual. É o caso de jogos. Os frames precisam ser atualizados em tempo controlado e não pode ocorrer uma operação longa demais que faça perder o momento correto de atualização.
Um GC ingênuo certamente traz sérios problemas para jogos, mas não um geracional, que é o caso de C# ou Java.
A coleta da Gen0 é muito rápida, no computo geral costuma ser mais rápido que o gerenciamento manual de memória no heap, fora o ganho que pode obter pela localidade de referência.
A Gen1 não é tão boa, mas é curta e com tempo máximo mais ou menos definido. Desde que esse tempo seja considerado dá para manter uma confiabilidade.
A Gen2 é o problema, mas é bem minimizado já que ela é feito em background com a execução normal da aplicação. Em máquinas com mais de 1 core a pausa pode ser bem curta como nas gerações anteriores.
Deve saber que vários jogos são feitos em C#, principalmente com Unity. E eles têm bastante sucesso no gerenciamento de memória.
Infelizmente C# não pode(ia) configurar muita coisa no GC e não pode trocar o GC facilmente como o Java permite, ainda que as alternativas mais apropriadas para real time ainda costumam ser bem caras ($). O .NET Core não dá tanta facilidade, mas pode trocar por um outro coletor de lixo ou mudar pequenos detalhes. O Mono também permite configurar e trocar o GC. Outras implementações como a do XBox, Compact e Micro Framework podem ter GC determinístico (não sei como está hoje), mas provavelmente não usará os últimos para para jogos. De fato agora só sobreviveu o .NET Core.
Técnicas de otimização
A maioria do que vou dizer aqui vale para qualquer linguagem (C ou C++ por exemplo podem ser mais rápidas, mais controladas, mas ninguém diz que dá um trabalho monstro), uma com garbage collector só precisa de mais cuidado. Em alguns pontos as linguagens com memória gerenciada são até melhores.

Evite usar o heap tanto quanto possível, assim não tem o custo da coleta ou liberação. C# tem cada vez mais recursos para preferir a pilha.
Entenda como cada componente funciona e saiba onde ocorre alocações, especialmente aquelas que costumam ser invisíveis ao programador como boxing. Você só pode evitar alocações se souber que elas existem (exemplo de como evitar).
Se usar o heap procure fazer pré-alocações que nunca serão liberadas, use os chamados Object Pool (veja a ótima explicação do Luiz Vieira) ou Flyweight Pattern. Tem estruturas que já funcionam como pools se quiser, um exemplo é List onde você pode limpar em vez de apagar, assim mantém a alocação já feita para um novo uso da lista. Se apagar, gera um lixo e depois vai gerar outro objeto para essa nova lista.
Faça o código menos orientado a objeto que abusam de referências.
Nunca esqueça que os objetos devem morrer jovens ou viver para sempre.
Em alguns casos precisará construir suas próprias estruturas de dados ou utilizar bibliotecas de terceiros que sejam mais adequadas para a necessidade. O novo compilador do C# tem um monte de estrutura que parece duplicação do que já existe no .NET, mas elas foram escritas para a necessidade do compilador.
Em caso extremo aloque fora da memória gerenciada. Aí ela passa ser problema seu gerenciar, mas é uma forma de ter controle quando a liberação ocorrerá. Só cuidado pra não vazar memória. C#, ao contrário de Java permite você gerenciar a memória quando não há outra solução melhor.
Use TryStartNoGCRegion() sempre que houver um momento que não pode ter uma coleta, não é garantindo, mas ajuda.
Sabendo fazer, chamar a coleta manualmente quando está entre fases, pausa ou algo que não atrapalha ter uma pausa, pode minimizar a chance de pause durante a ação do jogo. Mas se fizer errado pode piorar a situação.
Não esqueça de manter configurado para usar o modo Workstation que diminui as pausas.
Perfile a aplicação para descobrir onde está o problema.
Especifique uma boa quantidade mínima de memória. GC trabalha melhor quando tem memória sobrando.
Faça as threads ajudarem na organização do software (algo bem mais avançado).
Tem técnicas de manter o jogo em atraso para evitar surpresas, mas isso não é simples de fazer corretamente e não resolve sempre.

Veja Como identificar e evitar memory leak no .NET?.
Em suma, produza menos lixo e faça o GC trabalhar a seu favor.
Coloquei no GitHub para referência futura.
Comment: muito obrigado pela resposta (mesmo não sendo eu a perguntar). Mas sabe me dizer como ficam os objetos carregados em uma cena no Unity, depois que essa cena se acaba? Por exemplo: Ao entrar em uma cena aonde é o "campo de futebol". Quando o jogo acaba, e você volta pro menu, saberia me dizer se a memória alocada pelo "campo de futebol" é totalmente liberada? Sei que aqui nesse comentário fiquei meio fora de contexto, mas estive procurando sobre e não achei coisas muito satisfatórias para ler.
Comment: @ArturoTemplário Sobre Unity sei quase nada.
Comment: @ArturoTemplário, eu particularmente nunca fiz um jogo tão grande assim, então sei pouco... Na Unity, ela só carrega os objetos da cena quando você manda carregar a cena; então, isso significa que ela vai evitar criar o futebol antes que você o mande fazer isso. Sobre abandonar cenas existentes (depois da partida, por exemplo), você precisa falar para a Unity fazer isso `SceneManager.UnloadSceneAsync`. Assets precisam ser liberados separadamente: `Resources.UnloadAllUnusedAssets`. Mais detalhes em [SceneManager](https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.html)
Answer:
Comecei aprender C# e até Java por interesse em desenvolvimento de
  jogos. Mas sei que muitos são desenvolvidos com C++, principalmente
  por não ter um garbage collector.

Isso não é necessariamente verdade. Muitos jogos são (ou eram) desenvolvidos em C++ primeiramente pelos motivos de portabilidade e desempenho. Só que essa realidade tem mudado consideravelmente com os motores de jogos como a Unity3D. Hoje é mais comum desenvolver o jogo quase todo numa dessas ferramentas, e usar C++ apenas para código crítico (por exemplo, algum teste de colisão especial que precisa ser feito, ou algum cálculo de Inteligência Artificial). Como já lhe foi bem explicado em outras respostas, mesmo uma linguagem em que não se tem GC vc pode ter problemas se planejar incorretamente o uso da memória.

Claro que eu sei que vários jogos são feitos em C# e Java.

Justamente por causa da produtividade obtida com ferramentas e/ou bibliotecas que usam essas linguagens. Mas eu ainda duvido que o principal motivador de uso seja a existência ou não do GC.

Imagino que seja a pausa que causa problema. O que eu quero saber mesmo é como é resolvida a pausa no desenvolvimento de um jogo feito nestas linguagens.

Eu não entendi de que pausa você se refere. Seria a pausa do jogo, ou o intervalo que o GC leva pra remover a memória não mais referenciada? Se você se referia à primeira, não há razão para isso ser um problema pois durante esse tempo nenhum objeto é criado ou deletado (supostamente, claro - afinal, vc pode ter cometido erros na sua implementação de pausa). Se você se referia à segunda (que eu acho mais provável), a resposta aceita te explica tudo em detalhes técnicos mas a essência tá em: "produza menos lixo e faça o GC trabalhar a seu favor".
Em um jogo, "produzir lixo" é criar objetos (isto é, alocar memória) e depois jogá-los fora (isto é, deixar de referenciar aquela memória). É algo muito fácil de acontecer. Por exemplo, imagine um jogo simples em que você atira em aviões com uma bateria antiaérea a partir do solo. O jogo constantemente irá instanciar:

Aviões
Projéteis lançados pela bateria antiaérea

Os aviões e os projéteis são ambos destruídos quando o primeiro é atingido pelo segundo, certo? Além disso, os aviões eventualmente sairão da tela se não forem atingidos, assim como os projéteis sairão da tela se não atingirem um alvo. Se você instanciar novos objetos dessas classes e destruí-los quando ocorrer um impacto ou quando saírem da tela, você não terá vazamentos de memória (isto é, memória eternamente presa e inutilizável), e o seu jogo funcionará super bem. Para jogos simples, em que poucos desses objetos são instanciados, você não precisa se preocupar e pode deixar o GC fazer o trabalho dele da forma que foi projetado.
Mas e se o seu jogo é suficientemente complexo para você precisar ter muitos desses objetos? Nesse caso, talvez não faça sentido criar e destruir os objetos continuamente, pois a carga sobre o GC será muito grande e constante (isto é, você estará produzindo muito lixo e não estará fazendo o GC trabalhar a seu favor). Uma alternativa nesses casos é utilizar "tanques" (pools em inglês) de objetos pré-criados que são realocados depois de utilizados (por exemplo, a mesma bala que sai da tela é feita invisível e "transportada" novamente para a boca do canhão para ser disparada novamente).
Deixar objetos pré-criados ajuda no desempenho porque não sobrecarrega o GC, mas é claro que a memória tem seus limites e você não pode simplesmente deixar esse "tanque" crescer indefinidamente. Por isso realocar os objetos costuma ser uma boa prática.
Enfim, isso tem que ser feito com cuidado, considerando não apenas os aspectos técnicos aqui discutidos, mas também a experiência do jogador (que é algo muito importante nesse tipo de software). Um exemplo clássico é o dos buracos de bala deixados nas paredes do CounterStrike. Eles provavelmente são objetos mantidos em um desses tipos de "tanques" e são realocados quando o "tanque" se esgota. Funciona bem, mas já causou quebra de imersão em jogadores que tentaram literalmente escrever em paredes com os tiros (as letras iniciais iam sumindo conforme os objetos dos buracos de bala eram realocados). :)
Comment: Muito boa explicação do *object pool* que é útil também mesmo quando se opta por gerenciamento por *malloc/free-like*.
Answer: Especificamente para o Java, há dois itens que eu destacaria sobre o assunto:
Primeiro, o GC do Java não é um mistério. Na verdade, existe mais de um e cada um com configurações diferentes que podem atender à demandas específicas, pois alguns tendem a ter pausas menores e frequentes enquanto outros pausas demoradas e raras. Além de pequenas técnicas e padrões que evitam o a criação e subsequente descarte desnecessário de objetos, se você desenvolve um jogo sério, você vai analisar a memória necessária em cada parte do jogo, monitorar as pausas, e simplesmente tentar alocar a memória suficiente para a JVM de modo que não seja necessário pausar a execução num momento inapropriado, possivelmente invocando o GC entre fases ou estágios do Jogo.
Segundo, existem otimizações mais avançadas usando memória alocada diretamente. Veja a documentação do ByteBuffer. Além disso grande parte dos componentes visuais pode ser gerenciado também via integração com drivers nativos, tal como memória das placas de vídeo, que não são gerenciadas pelo GC.
Enfim, não estou argumentando que Java é uma linguagem apropriada para jogos, muito menos jogos grandes, até porque GC é apenas um fator. Entretanto, se você sabe o que está fazendo - e certamente um jogo sério precisará de um especialista na plataforma usada - pausas do GC provavelmente não serão sua a maior preocupação.


How to run asynctask always even in app minimised sate?

Question: Hi i have completed a process in android which will call a web service containing calendar events. i parsed and added the events to android calendar successfully. I used asynctask to do this. But now this process has to run for every 30 seconds even if the app is in minimised state. i surfed and found that we can use thread,aynstask,service,alarm receiver to implement it. but iam not having knowledge in those things.Please help me if anybody knows.
My asynctask:
<code>public class SyncCalendar extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            progressdialog = new ProgressDialog(MainActivity.this);
            progressdialog.setCancelable(true);
            progressdialog.setMessage("Fetching Appointments and Tasks...");
            progressdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressdialog.setProgress(0);
            progressdialog.show();
        }

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            String taskresult = getCalendarData();
            Log.d("test", "" + taskresult);
            return taskresult;
        }

        protected void onPostExecute(String taskresult) {

            if (taskresult != "" && taskresult != null) {
                try {

                    if (response.contains("Appointment")) {
                        Log.e("called", "called");
                        try {
                            leadna_leadAppointaray = leadna_leadSyncCalendar
                                    .getJSONArray("Appointment");
                            if(leadna_leadAppointaray.length()!=0){
                            for (int i = 0; i < leadna_leadAppointaray
                                    .length(); i++) {
                                Log.e("called", "called"+i);
                                JSONObject c = leadna_leadAppointaray
                                        .getJSONObject(i);
                                String startDate = c.getString("StartDate");
                                String[] startDatearay = startDate.split("\\-");
                                String endDate = c.getString("EndDate");
                                String[] endDatearay = endDate.split("\\-");
                                String startTime = c.getString("StartTime");
                                String[] startTimearay = startTime.split("\\:");
                                String endTimeData = c.getString("EndTime");
                                String[] endTimearay = endTimeData.split("\\:");
                                long calID = 1;
                                long startMillis = 0;
                                long endMillis = 0;
                                Calendar beginTime = Calendar.getInstance();
                                beginTime.set(
                                        Integer.parseInt(startDatearay[0]),
                                        Integer.parseInt(startDatearay[1]),
                                        Integer.parseInt(startDatearay[2]),
                                        Integer.parseInt(startTimearay[0]),
                                        Integer.parseInt(startTimearay[1]));
                                startMillis = beginTime.getTimeInMillis();
                                Calendar endTime = Calendar.getInstance();
                                endTime.set(Integer.parseInt(endDatearay[0]),
                                        Integer.parseInt(endDatearay[1]),
                                        Integer.parseInt(endDatearay[2]),
                                        Integer.parseInt(endTimearay[0]),
                                        Integer.parseInt(endTimearay[1]));
                                endMillis = endTime.getTimeInMillis();
                                ContentResolver cr = getContentResolver();
                                ContentValues values = new ContentValues();
                                SimpleDateFormat formatter = new SimpleDateFormat(
                                        "dd/MM/yyyy");
                                String dateString = formatter.format(new Date(
                                        startMillis));
                                String edateString = formatter.format(new Date(
                                        startMillis));
                                Log.e("Date", dateString);
                                Log.e("EDate", edateString);
                                values.put(Events.DTSTART, startMillis);
                                values.put(Events.DTEND, endMillis);
                                values.put(Events.TITLE, c.getString("Subject"));
                                values.put(Events.DESCRIPTION,
                                        c.getString("Descrip"));
                                values.put(Events.EVENT_LOCATION,
                                        c.getString("Location"));
                                values.put(Events.CALENDAR_ID, calID);
                                values.put(Events.EVENT_TIMEZONE,
                                        "America/Los_Angeles");
                                Uri uri = cr.insert(Events.CONTENT_URI, values);
                                Log.e("called", "called");
                            }
                            }

                            leadna_leadTaskaray = leadna_leadSyncCalendar
                                    .getJSONArray("Task");
                            if(leadna_leadTaskaray.length()!=0){
                            for (int i = 0; i < leadna_leadTaskaray
                                    .length(); i++) {
                                Log.e("called", "called"+i);
                                JSONObject c = leadna_leadTaskaray
                                        .getJSONObject(i);
                                String taskDateTime = c.getString("task_date");

                                SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd hh:mm"); // I assume d-M, you may refer to M-d for month-day instead.
                                Date date = formatter1.parse(taskDateTime); // You will need try/catch around this
                                long millis = date.getTime();
                                Log.e("taskDateTime",String.valueOf(millis));
                                long calID = 1;
                                long startMillis = 0;
                                long endMillis = 0;
                                Calendar beginTime = Calendar.getInstance();
                                //beginTime.set();
                                startMillis = millis;
                                Calendar endTime = Calendar.getInstance();
                                /*endTime.set(Integer.parseInt(Date[0]),
                                        Integer.parseInt(Date[1]),
                                        Integer.parseInt(Date[2]),
                                        Integer.parseInt(Time[0]),
                                        Integer.parseInt(Time[1]));*/
                                endMillis = millis;
                                ContentResolver cr = getContentResolver();
                                ContentValues values = new ContentValues();
                                SimpleDateFormat formatter = new SimpleDateFormat(
                                        "dd/MM/yyyy");
                                String dateString = formatter.format(new Date(
                                        startMillis));
                                String edateString = formatter.format(new Date(
                                        startMillis));
                                Log.e("Date", dateString);
                                Log.e("EDate", edateString);
                                values.put(Events.DTSTART, startMillis);
                                values.put(Events.DTEND, endMillis);
                                values.put(Events.TITLE, c.getString("task_title"));
                                values.put(Events.DESCRIPTION,c.getString("task_note"));
                                values.put(Events.CALENDAR_ID, calID);
                                values.put(Events.EVENT_TIMEZONE,
                                        "America/Los_Angeles");
                                Uri uri = cr.insert(Events.CONTENT_URI, values);
                                Log.e("called", "called");
                            }
                            }

                            progressdialog.cancel();

                        } catch (Exception e) {

                        }
                    }
                } catch (Exception e) {

                }
            }
        }

        public String getCalendarData() {
            Date date1 = new Date();
            SimpleDateFormat postFormater = new SimpleDateFormat("yyyy-MM-dd");
            String toDate = postFormater.format(date1);
            URLSyncCalendar = URLSyncCalendar + "&today=" + toDate
                    + "&userId=" + LoginActivity.user_id + "&clientId="
                    + LoginActivity.user_client_id;
            System.out.println("URL-->>" + URLSyncCalendar);
            try {
                BufferedReader inStream = null;
                OutputStream out = null;
                HttpURLConnection httpconn = null;
                URI uri = new URI(URLSyncCalendar);
                URL url = uri.toURL();
                httpconn = (HttpURLConnection) url.openConnection();
                httpconn.setDoOutput(true);
                out = httpconn.getOutputStream();
                httpconn.connect();
                out.flush();
                inStream = new BufferedReader(new InputStreamReader(
                        httpconn.getInputStream()));
                if ((response = inStream.readLine()) != null) {

                    try {
                        leadna_leadSyncCalendar = new JSONObject(response);
                    } catch (JSONException e1) { // TODO Auto-generated catch //
                                                    // block
                        e1.printStackTrace();
                    }

                }
                out.close();
                httpconn.disconnect();
            } catch (Exception e) {

            }
            return response;

        }
    }
</code>
Comment: **"every 30 seconds"** - Seriously? How quickly do you wan't to drain the battery? I can't think why you'd need to update calendar events every 30 seconds.
Comment: You will should put this within a service instead of your activity, and use the [AlarmManager](http://developer.android.com/reference/android/app/AlarmManager.html) to start the service periodically.
Comment: i want to run it in a frequent interval, time is not a constrain. I have to implement this functionality in my app.
Answer: You definitely should use a Service for this.
One more thing though. Never ever send requests to a server every 30 seconds. Imagine there are one million client apps sending requests every 30 seconds. Or there are 50 apps installed on a device. Be reasonable.
Comment: Take a look at this https://github.com/thecodepath/android_guides/wiki/Starting-Background-Services
Answer: I think the best option in your case is to implement a service that does what you need.
You can read about it here and here.
The links also have example codes inside...


How to get Taxonomy Menu working properly with Contextual Filters in Views?

Question: I can't get taxonomy menu links working properly with contextual arguments in Views.
This is what I have done:
0) I create a menu called: Catalog menu
1) I create a Vocabulary called: Catalog terms and in the Taxonomy menu area I set Catalog menu for the Menu location (I have Taxonomy menu module enabled which allow me to do this)
2) I the Catalog vocabulary I added 2 terms: Cars and Phones
3) In admin/config/search/path/patterns I set Pattern for all Catálogo taxonomy paths to catalog/[term:name]
4) In admin/structure/block I enable the Catalog menu block to the First sidebar
So far so good. I have a menu in my first sidebar with the links: cars and phones.
5) I have a content type called Products with a field of the type Term reference called: field_catalog
6) Now I create a new view called: Catalog view where I need to show Products which has an specific term in the url. The path of this view is catalog
7) I added a RELATIONSHIP called: Content (field_catalog)
8) I added a CONTEXTUAL FILTERS called Taxonomy term: Name using the previous relationship
Now if I enter "cars" in the Auto preview Preview with contextual filters: area it works fine. It only shows products that has cars term.
So the Catalog Menus is fine and the view is fine.
But if I go to the url www.mysite.com/en/catalog/cars it takes me to the list of content that has the temr cars. Here I need to show the Catalog view passing cars as an argument and not that list.
Comment: Slightly off topic but I like how you started your ordered list with 0.
Answer: You have made one mistake that is easy to make. The alias created in the menu doesn't change the "true" url. So when you go to catalog/cars Drupal will perceive that as taxonomy/term/[tid].
What you could do instead is to enable the default taxonomy term view that ships with Views (which uses taxonomy/term/[tid] as the path) and then set it up like you want.
See Screen shot:
Comment: I don't get it. Could you please explain how to do it? Where do I do these changes?
Comment: IN the list of available views you will find one with the taxonomy/term/% path.  that is the one you want to enable and create your view in.
Comment: Thanks what you said is useful, but I will try a different approach. I will create a view listing terms as a html list, so that I'll get the menu as a block.


Clarification on finite multiply transitive permutation groups and bounds on trace of associated permutation matrices

Question: Given a group $G$ such that $G < S_n$, $G \neq A_n$, and $G$ acts faithfully and transitively on the set $\Omega_n$ where $n \geq 6$, is the following statement true?

Given any non-identity element $g \in G$ with associated permutation matrix $P_g$, is its trace bounded by $0 \leq \operatorname{Tr}(P_g) \leq 5$?

My reasoning is that any finite $k$-transitive group where $k \geq 6$ must either be $S_n$ or $A_n$. Since $G$ is neither by definition, it cannot have any non-identity group element which fixes $6$ or more disjoint points and the intersection of the maximal stabilizer subgroups of any set of $6$ or more disjoint points in $\Omega_n$ must be trivial. Therefore, in the language of permutation matrices, the trace (the count of fixed points) must be less than or equal to $5$ for each non-identity group element in $G$.
This seems like a very strong restriction on permutation matrix groups, so I'm looking to see if my logic actually works or if I've missed extra assumptions here.
Answer: No, there can be non-identity elements fixing arbitrarily many points.  For example, for integers $m, n > 1$, consider the wreath product $S_m \wr S_n := (S_m)^n \rtimes S_n$, where $S_n$ acts by permutation of the $n$ copies of $S_m$.  This acts faithfully and transitively on the set $$X = \{(i, j):  1 \leq i \leq m, 1 \leq j \leq n\}$$ of $mn$ points; it is the subgroup of $S_{mn}$ that preserves the partition of $X$ into $n$ blocks (or rows) of $m$ points of the form $(-, j)$.  This has a non-identity element that fixes $mn-2$ points, namely the element that switches $(1,1)$ with $(2,1)$ and fixes everything else.
The error in your reasoning is that $k$-transitivity is about more than just $k$-point stabilizers; it requires group elements sending any ordered $k$-tuple of distinct elements to any other.  The group described above contains some elements that stabilize a lot of points, but it doesn't mix points well enough to be $2$-transitive (or primitive for that matter):  for example, there is no group element sending $(1,1)$ to itself and $(2,1)$ to $(1,2)$.
It's also worth noting that $k$-transitivity doesn't actually imply there's a non-identity element fixing any $k$ points; in fact, this is false for groups that are sharply $k$-transitive.  (In a sharply $k$-transitive permutation group, there is a unique element sending any ordered $k$-tuple to any other, and this element will sometimes necessarily be the identity.)  What it does tell you (if $k < n$) is that there exist non-identity elements stabilizing $k-1$ points:  e.g. take an element sending $(1, 2, \dots, k-1, k)$ to $(1, 2, \dots, k-1, k+1)$, which must in particular not be the identity.
Comment: I really appreciate you pointing out the fault in my reasoning, and the counter example really helped drive it all home!


Windows 2008 R2 Memory Management

Question: How does Windows manage physical and virtual memory?  As I understand it, once the system fully utilizes physical memory, it will engage virtual memory.  How is virtual memory managed? If physical memory becomes available, will it move from virtual to physical? or remain in virtual until the process or application ends?
So in theory, if application Z starts and physical memory if fully utilized, it will use virtual memory.  Will application Z ever move to physical memory? or will it remain in virtual memory space until it closes or ends?
Thank You!
Comment: Does this question result from a specific problem you're having, or is it just general interest? The reason I ask is because you would do better to post your original problem if so. Windows memory management algorithms are more complex than simply using the pagefile if physical memory is exhausted. Even when physical memory is available, pages are written out to the page file for a variety of reasons. Best not to mess with it unless you have a very specific problem and you really know what you're doing.
Comment: We have some systems where we see physical memory utilization around 50% and virtual memory utilization above 80%.  Have a better understanding of how this works in general would be helpful down the line.  Thanks!
Comment: Also, "virtual memory" is actually an abstraction which includes physical memory and the page file. Your application is always using virtual memory and sees it as one big contiguous block of memory. The OS then decides where to actually store the data at any given moment. What I think you're referring to as virtual memory is actually the page file or swap file, which is stored on disk.
Comment: Are the machines in question actually experiencing any issues that caused you to look at the memory usage? If not, then I would just leave it. If ain't broke, don't fix it. EDIT: If they are experiencing issues, post that as a question - you could well be looking in the wrong place for the problem, but we can't help if we don't know the original issue.
Comment: Yes I am referring to the page files, but that actually raises another question.  If an SNMP monitor is showing 90% virtual memory, this is actually a combination of both physical and page file so from that counter you can't abstract how much of the page file is really in use?
Comment: This was a question posed to us from our applications team who noticed this from our monitoring system.  I am not aware of any issues regarding these systems, but if there are, I will research and post a better question.  Sorry for the ambiguity of the question.
Comment: There should be an SMTP monitor you can tap for page file usage specifically. When you post another question, I would explain a little more about what applications are running on the servers. Memory usage patterns vary widely depending on the workload, so it would help. High memory usage isn't necessarily a bad thing if you don't have perf problems. Apps like SQL and Exchange will try and load as much of a db into memory as it can to improve access time. Free memory is a waste!
Comment: Newt - Thanks for clearing up the details. I am aware of SQL and Exchange's behavior but wanted to have a better understanding of how memory was managed.  Thanks again!
Answer: The question is arguably off-topic, but there is at least one good answer:
Get the Windows Internals book(s) from MS Press and read them, specifically Chapter 10 (6th Edition)  These are probably the best overall guide to how Windows works (and the chapter on memory management is quite detailed).

Windows 2008 R2 Memory Management


How do i make my game link back to the start once user has made the wrong choice

Question: im currently creating a text based adventure game, and i need to get the game to go back to the beginning once the user has died or chosen the wrong answer. i need it to ask the user if they wish to play again and then loop back to the beginning of the game.
anyone know how to do this, the help would be greatly appreciated.
this is the code -
#Python Text Adventure Game
#Created By Callum Fawcett
#Created On 20/07/19
#Version 0.1

# Setup
yes_no = ["yes", "no"]
directions = ["left", "right", "forward", "backward"]

# Introduction
name = input("What is your name, adventurer?\n")
print("Greetings, " + name + ". Let us go on a quest!")
print("You find yourself on the edge of a dark Jungle.")
print("Can you find your way through? and find the Hidden treasure at the end?\n")

# Start of game
response = ""
while response not in yes_no:
    response = input("Would you like to step into the Jungle?\nyes/no\n")
    if response == "yes":
        print("You head into the Jungle. You hear crows cawwing in the distance.\n")
    elif response == "no":
        print("You are not ready for this quest. Goodbye, " + name + ".")
        quit()
    else:
        print("I didn't understand that.\n")

# Second part of game
response = ""
while response not in directions:
    print("To your left, you see a Tiger.")
    print("To your right, there is more Jungle.")
    print("There is a rock wall directly in front of you.")
    print("Behind you is the Jungle exit.\n")
    response = input("What direction do you move?\nleft/right/forward/backward\n")
    if response == "left":
        print("The Tiger eats you. Farewell, " + name + ".")
        quit()
    elif response == "right":
        print("You head deeper into the Jungle.\n")
    elif response == "forward":
        print("You cannot scale the wall.\n")
        response = ""
    elif response == "backward":
        print("You leave the Jungle. Goodbye, " + name + ".")
        quit()
    else:
        print("I didn't understand that.\n")

# Third Part of game
response = ""
while response not in directions:
    print("To your left, there is a waterfall.")
    print("To your right, you see a run down house.")
    print("Directly in front of you is a dark staircase.")
    print("Behind you is the exit.\n")
    response = input("What direction do you wish to take?\nleft/right/forward/backward\n")
    if response == "left":
        print("You look off the edge of the waterfall, taking the time to think about your choices.\n")
        response = ""
    elif response == "right":
        print("The house is a trap, the doors and windows all shut behind you and youre trapped, Farewell, " + name + ".")
        quit()
    elif response == "forward":
        print("You head down the strairs\n")
    elif response == "backward":
        print("You leave the Jungle. Goodbye, " + name + ".")
        quit()
    else:
        print("I didn't understand that.\n")

# Fourth part of game
response = ""
while response not in directions:
    print("You're now at the bottom of the staircase, it has a come to a fork")
    print("To the right is a well lit path with a sign that reads 'Death to all who continue'.")
    print("To the left is a dark and gloomy path with a sign that reads 'free passage to all those who continue'. ")
    print("Directly in front of you is a a 50ft drop.")
    print("Behind you is the exit.\n")
    response = input("What direction do you wish to take?\nleft/right/forward/backward\n")
    if response == "left":
        print("You are attacked by forrst deamons. Goodebye," + name + ".")
        quit()
    elif response == "right":
        print("You continue through the forrest.\n")
    elif response == "forward":
        print("You cant go down there youll die.\n")
        response = ""
    elif response == "backward":
        print("You leave the Jungle. Goodebye" + name + ".")
        quit()
    else:
        print("I Didn't understand that.\n")

#Fifth part of game
response = ""
while response not in directions:
    print("You have continued through the dark forrest, and found yourself at a cross road.")
    print("To your left is a beaten path with a man lying on the ground.")
    print("To your right is a door.")
    print("Straight ahead is a dark path that is over grown and full of brambles and thorns.")
    print("behind you is the way you came and the way out.\n")
    response = input("What direction do you wish to take?\nleft/right/forward/backward\n")
    if response == "left":
        print("You walk to help the man, but it was a trap and you are attacked and killed by savages. Goodbye, " + name + ".\n")
        quit()
    elif response == "right":
        print("You go through the door, and it takes you to a mystical realm that you do not know, and now youre traped there. Goodbye, " + name + " Have fun.\n")
        quit()
    elif response == "forward":
        print("You continue through the dark Jungle, getting deeper and deeper. Lets hope you're not lost ;)\n")
    elif response == "backward":
        print("You Leave the Jungle. Goodbye" + name + ".")
        quit()
    else:
        print("I Didn't understand that")

#sixth part of the game.
response = ""
while response not in directions:
    print("You have made it through the thorns and brambles, and have come to a T in the path.")
    print("To your left is a bridge that doesnt look very stable and could break with the slightest bit of weight on it.")
    print("To your right is a dark path with a metal bridge that looks sturdy and safe.")
    print("Directly in front of you is a wall.")
    print("Behind you is the way you came and the way out.\n")
    response = input("What direction do you wish to take?\nleft/right/forward/backward\n")
    if response == "left":
        print("The bridge was actually very safe and you make your way over it, and continue on your quest\n")
    elif response == "right":
        print("The bridge wasnt stable and you have fallen to your death. Goodbye" + name + ".\n")
        quit()
    elif response == "forward":
        print("You cannot scale the wall\n")
        response = ""
    elif response == "backward":
        print("You leave the Jungle. Goodbye" + name + ".")
        quit()
    else:
        print("I Didn't Understand That")

#Final Part of The Game
response = ""
while response not in directions:
    print("You have come to the jungle temple, you make your way in through the door. Once inside you see three doors.")
    print("The door on the left has a weird symbol above it, and what looks like blood coming out from under the door.")
    print("The door on the right has no symbol above it, but does have two large lion statues by the door.")
    print("The door straight in front of you has a crown symbol above it, but has two skelitons sat outside it.")
    print("behind you is the way you came in and the way out.\n")
    response = input("What direction do you wish to take?\nleft/right/forward/backward\n")
    if response == "left":
        print("You open the door and something drags you inside, for you to never be seen again. Goodbye" + name + ".\n")
        quit()
    elif response == "right":
        print("You open the door and go inside, only to find 10 large lions who have not been fed in a very long time, they eat you. Goodbye" + name + ".\n")
        quit()
    elif response == "forward":
        print("You open the door and walk down the strairs infront of you, as you get lower and lower you start to see all the gold and treasure that has been left.")
        print("CONGRATULATIONS " + name + ", you found the Hidden jungle treasure, along with an exit back to the world.")
    elif response == "backward":
        print("You leave the temple and there are re risen soldiers ready to kill you. you die, Goodbye " + name + ".\n")
        quit()
    else:
        print("I Didn't understant that")

Comment: put all your code inside new `while` loop - and it will repeat all your code again and again.
Comment: put all in `while` loop
Comment: @furas where would i put the while loop tho?
Comment: ive edited the question as what i asked was slightly off from what i wanted
Answer: put all your code inside a while loop and put continue to jump to the beginning of the loop
while True:
   ...
   ...
   if response == "some wrong answer": continue
   ...
   ...

Comment: tried this, but when it comes to the wrong answer i still need it to print out a message and i get an indent error
Comment: ive edited the question as what i asked was slightly off from what i wanted
Comment: if you mixed spaces and tabs you probably get an indent error sometimes, remove all white space and change them 4 spaces(or 2) or a tab for indentation
Answer: A possible solution: move all of your current code to a function, let's call it "gameplay",
and encapsulate it in a loop in the main function
def gameplay():

    # Setup
    yes_no = ["yes", "no"]
    ....
    ....
    ....

if __name__ == "__main__":
    while True:
        response = input("start a new game?y/n")
        if response != "y":
            break
        print("Starting a new game")
        gameplay()

Comment: ive added this to my code, but when i choose the wrong answer in the first set it just ends the game
Comment: ive edited the question as what i asked was slightly off from what i wanted
Comment: this works great, is there a way of making it an option to start a new game rather than just starting one anyway


What could be the advantage of doping in curling?

Question: I've seen reports that one of the OAR athletes in curling in these Olympics (Pyeongchang 2018) might have failed a Doping test.
I really wonder... what could be the advantages of doping in curling? Curling is not a sport of power, or endurance... they rarely throw the rock full power, and even then, a little bit more or less power will probably still to the job just fine.
So why could a curler be using performance enhancing drugs?
Comment: Not specific to curling, but some people have taken PED's to help recover from injuries.
Comment: @Fredy31 as we know all too well in Ireland - https://youtu.be/Xh6HFMBREB4
Comment: @Andre Ok I can see you have a great understanding of what is eating sh-- on ice. Greetings from Canada; another land that looks like north of the wall in GoT.
Comment: @JeffO What kind of injury could you get from curling..?
Comment: My step mother said she hurt her back while doing curling in her job's christmas party. She was faking it for months. But in all seriousness, you are standing on ice. You can slip and fall hard. It may not be as spectacular as hurting yourself in other sports, but you could.
Comment: @Andre - people get hurt in all sorts of ways. Curlers probably weight train and run. Even chess players exercise and train physically believe it or not. Also, you spend enough time on ice, everyone slips eventually.
Comment: @JeffO they should train with the hockey players so. Toughen them up a bit.
Comment: @Andre never did eat sh-- on a patch of ice. You can be the toughest guy in the world; a good slip on a patch of ice will take you down just as hard as anybody.
Answer: Endurance and power in curling are important during the sweeping action, and I can guarantee that after a match the players are tired (especially the two players who sweep more).
Here some evidence that talk about player training methods where you can find how physical training and endurance are important: 1 - 2 - 3
Furthermore, being able to maintain concentration fot all the match is a very important aspect and I think that some doping can "help" for it
Anyway the use of doping is breaking the rules of every sport (but this do not answer to the question)
Comment: Would be good if there are citations
Comment: @aqwert some links added, I hope it helps to understand the effort required to play curling
Comment: So I'll put curling in these sports where it doesn't look like it's hard physically but it actually does :p
Answer: The curling case is very puzzling, as the drug in question is meldonium, which basically allows slightly greater endurance by opening up blood flow and regulating energy in the cells. Even curlers are puzzled about it, as evidenced by this article.
One of the possible side effects is tachycardia, which would be detrimental to the fine control needed for curling. As the article mentions, beta blockers to slow the heart rate would be much more likely to be used (As they were in golf in a minor fashion, IIRC it was Davis Love that admitted to trying them in the book A Good Walk Spoiled).
Answer: I think you miss main point of doping. People take drugs not to get stronger or more powerful in general, but to get stronger and more powerful at the skill when competing with other athletes.
The point is that if you are a curler and take drugs, you will not magically start lifting 1000 pounds, but you will be better at curling that your equally able competitor. The nature of any sport is that athletes try to perform at 100% ability/capacity at some parameter.
Comment: "The point is that if you are a curler and take drugs, you will not magically start lifting 1000 pounds, but you will be better at curling that your equally able competitor." Explain how this is the case?
Comment: @andre "for such a minimal advantage" have you seen how little time/points is there between #1 and #2 in olympics? But you need to pretty damn good already
Comment: @andre why drugs not gonna make you lift 1000 pounds when you were lifting maybe 300? My point was that drugs can make you a little bit better at what you do, doesn't matter what. A bit extra brain-muscle coordination and you can throw that stone more precise. But drugs are not magic, but an ace card
Comment: for such a minimal advantage it's pretty stupid to do it. Assuming everyone is checked the same, you're getting a lot more for your risk if you do it for a more athletic event. I'd actually quite like to see a similar tournament to the Olympics for people who openly take enhancing drugs. It'd be quite interesting to see how far we can push our bodies.
Comment: not in curling, which is what I was referring to there. As a swimmer I see how it could have a huge difference. Even 0.01 of a second is a good advantage. I don't really know much about curling. It just looks like lawn bowls on ice to me.


Agent VMs of different sizes in Azure Container Service

Question: Is there any way to have VMs of different sizes in the private agents pool of an Azure Container Service (ACS)? I would like to support use cases where some services require compute intensive servers and others (e.g databases) memory intensive servers.
An acceptable solution could be to add multiple virtual machines scale sets (vmss) as private agents pools and each one of them have VMs of different sizes since a vmss supports one size of VM. Is such a feature supported in ACS?
A workaround could be to have different sizes of VMs in the public and private agent pools. However, this is not a best practice since public agents pool should be used to host services that are exposed publicly (e.g marathon-lb). Also, it limits the options to just two pools.
Answer: This feature is coming and if you need them today you can use ACS Engine (the open source code behind ACS). See examples at https://github.com/Azure/acs-engine/tree/master/examples/largeclusters
Comment: Thank you for the response. The solution that I found is to deploy another vmss with private agents and the size of vm that I need. I exported the template of my current infrastructure from Azure, added the new vmss and reposted the template. The resources that already existed were left untouched (as stated in [Azure RM documentation](https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-template-deploy-rest)) and the new vmss was created.
Comment: That is essentially what the ACS Engine does. If you get the opportunity to move your cluster to an ACS Engine cluster I would recommend doing so since most features in there will eventually make it into the SLA backed ACS and thus you will have a better long term experience.


Pass React Node as i18n Lingui value

Question: I have translated line of text with link. In past it was enough, when text and link was separed and has its own translation, but now copy was changed and in one language I need to place the link in the middle of sentence.
I would like to use Lingui marco prop values, but it doesn't seem to work with NextLink (or any React child). Simple text is working and showing in the translated text, but with NextLink I can't get closer then getting [Object object].
Is there a way to do this?
My code looks like this:
{i18n._('key_to_translated_text',
    { link: `${<NextLink
    href={routerCatalog.terms}
    target='_blank'
    rel='noopener noreferrer'>{t`key_to_link_text`}</NextLink>}`
})}

In translations file for key_to_translated_text:
msgid "key_to_translated_text"
msgstr "By registering, you agree to our {link}"

etc.
Whitch returns "By registering, you agree to our [object Object]" or "Du stimmst zu unseren [object Object] zu, wenn du dich registrierst."
Answer: <Trans>By registering, you agree to our <NextLink
    href={routerCatalog.terms}
    target='_blank'
    rel='noopener noreferrer'>terms</NextLink></Trans>

You will get in catalog:
msgid "By registering, you agree to our <0>terms</0>"
msgstr ""

Now you can translate however you want and move link in the message and change inner text as you wish:
you agree to our <0>terms and conditions</0>, when register
Also avoid manual ids as much as possible. This is not scalable and you have "naming things" problem multiplied to amount of messages you have.

Pass React Node as i18n Lingui value


Who wants a hat? Come and get your hats!

Question: 'Tis the season! Winter Bash is back on participating Stack Exchange sites in full effect, from 15 December 2014 until 4 January 2015.
For those of us who haven't seen it on other SE sites, as this would be the first for Expats.SE, Winter Bash is an annual event that can run on any Stack Exchange site that chooses to participate. Users earn "hats" for their gravatars by completing certain tasks (analogous to badges). Certain actions trigger the user receiving a hat, which their gravatar can "wear":

Sites vote explicitly to participate, and if the idea is welcomed by site's users, it will be enabled in the aforementioned period. It's important to know that even if Winter Bash is enabled, users can explicitly opt out if they want to (there will be "I hate hats" option on their profile page which will revert the site to its familiar look for the user).
So, it's time to decide if we want hats on our Expats.SE! Vote on the answers below until 30 November 2014. We'll enable hats only if there's sufficient support for it (for some yet undetermined value of "sufficient"). Please don't downvote an option, rather upvote only the one you choose. Of course, comment as necessary.
Your mod friends at Expats.SE remind you to enjoy hats responsibly.
Comment: @lswank I am not sure somebody without less than 15 rep has earned the right to decide if we wear hats.
Comment: While I voted yes, I imagine that there's got to be *someone* who wants to vote no but doesn't have the rep for it. ;)
Answer: YES!
Bring on the hats, can't ever get enough hats.
Comment: wow such fun, much hats!
Answer: No!
I'm a firm believer in bare heads.


Set Default color value to angularjs color picker

Question: I am trying to set default color value to my directive
my div is

   <color-picker ng-model="config.primaryColor"  options="options"></color-picker>

Comment: add `ng-init = config.primaryColor = "myAwesomeColor"`
Answer: just put
$scope.config = {};

$scope.config.primaryColor = '#FF0000';
this will work I think
Comment: gives this error "Cannot set property 'primaryColor' of undefined"
Comment: is the config.primaryColor your scope variable?
Comment: For this to work you should set the ng-model as the scope variable
Comment: sure, in controller used this
$scope.config.primaryColor = '#425ba1";
Comment: This is because that the config property is not defined in $scope. You either use a $sope.SelectedColor as model object or define $scope.config  to fix it
Comment: add $scope.config = {} in scope to define it before initializing $scope.config.primaryColor
Comment: yes you are right i just removed that config property from $scope.config.primaryColor. So now its working
Comment: You can use $scope.config.primaryColor as itself by declaring  $scope.config before initialization.
Comment: Please Approve my answer if this is what your requirement is
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/127287/discussion-between-ajay-dixit-and-nitheesh).
Answer: I think you should define $scope.config={} first then add to it the primary color


Weird findings initializing the array with numpy.NAN

Question: I'am having some trouble when  initializing a numpy array with numpy.NAN as below.
>>> import numpy
>>> a = numpy.zeros(2)
>>> a
array([ 0.,  0.])
>>> a[:] = numpy.NAN
>>> a
array([ nan,  nan])
>>> a[0] is numpy.NAN
False

Why is that? I have tried to initilize a single variable with NAN and get var is numpy.NAN as True. What happends when NAN is assign to an array?
And another question is when some of the elements in the arrary is NAN, how can I distinguish them from others? Thanks a lot!
Comment: Try with `numpy.isnan`.
Answer: It's a NaN. It's just that is doesn't work the way you think it does with NumPy arrays. When you assign
a[:] = numpy.NAN

NumPy doesn't actually fill a with references to the numpy.NAN object. Instead, it fills the array with doubles with NaN values at C level.
When you then access an array element with a[0], NumPy has no record of the original object used to initialize that cell. It just has the numeric value. It has to construct a new Python object to wrap that value, and the new wrapper is not the same object as numpy.NAN. Thus, the is check returns False.
Note that generally, comparing numbers with is is a bad idea anyway. Usually, what you want is ==, to compare their numeric values. However, == also returns False for NaNs, so what you need is numpy.isnan:
>>> numpy.isnan(a[0])
True
>>> numpy.isnan(a)
array([ True,  True], dtype=bool)


Exibindo dados com React JS

Question: Bom dia pessoal, estou tentando exibir na tela uma mensagem digitada pelo usuário, algo bem simples porem como sou novo no React não tenho muito noçao de como fazer isso. Bom, o código abaixo foi até aonde eu consegui chegar, ele nao esta pegando os dados do input e nem retornando quando eu clico no botao. Se puderem me ajudar eu ficarei muito grato, Obrigado !
import React, { Component } from 'react'

class Button2 extends Component {
   constructor(props) {
       super(props)

       this.state = {
           text: 'Your Name Here',
       }

   }

   clicked = (event) => {
       this.setState = ({ text: event.target.value })
   }

   handlerSubmit = e => {
       e.preventDefault()
       this.setState = { text: this.state.text }
   }
   render() {
       return (
           <form onSubmit={this.handlerSubmit}>
               {this.state.text}
               <input type="text" />
               <button onClick={this.clicked}>Click on me</button>
           </form>

         )

      }
  }

  export default Button2

Answer: Como você está naquele momento de aprendizado o nome do componente não faz referencia ao componente e o que ele representa, mas, você está precisando alterar o estado do input text, então precisa programar isso que é no eventoonChange desse input, exemplo:
handlerOnChangeInput = e => {
    const {name, value} = e.target;
    this.setState({[name]: value});
}

sendo esse função genérica podendo alterar para todo o estado do input, mas, para que isso funcione o nome do input tem que ser passado igual o nome da variável de estado criado que no seu caso em especifico é text.
De um modo geral é feito assim:
handlerOnChangeInput = e => {
    this.setState({text: e.target.value});
}

mas, fica restrito somente nesse input (pode ser feito assim também não há problemas, só vai escrever um pouco mais porque o código só vai funcionar para esse input e se houver mais que precisa guardar estado então tem que escrever para cada um, por isso eu coloquei o genérico antes, escolha o melhor para você)
O exemplo completo e funcional:

class Button2 extends React.Component {
   constructor(props) {
       super(props)

       this.state = {
           text: 'Your Name Here',
       }

   }

   handlerSubmit = e => {
       e.preventDefault();
       console.log(this.state.text);
   }

   handlerOnChangeInput = e => {
    const {name, value} = e.target;
    this.setState({[name]: value});
   }
   render() {
       return (
           <form onSubmit={this.handlerSubmit}>
               {this.state.text}
               <input type="text" value={this.state.text} name="text" id="text" onChange={this.handlerOnChangeInput} />
               <button onClick={this.clicked}>Click on me</button>
           </form>

         )

      }
  }
ReactDOM.render(<Button2/> , document.getElementById('root'));
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

Aguarde ...

Observação: o button nesse caso resgata o valor do estado do componente na chave criada, ou seja, é diferente, que no caso para pegar o valor do text precisa digitar this.state.text.
Comment: `const {name, value} = e.target;` é um como se você fizesse `const name = e.target.name;` e `const value = e.target.value;`  eu quero desconstruir `e.target` [leia](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/Atribuicao_via_desestruturacao) e a parte ***value, um name e um id no input mas não colocou nada no botão*** é porque tem que ser feito assim eu coloquei `name` e `id` mas, só precisava do `name` para que a função genérica funcionasse e o botão é um submit do form então o valor é resgatado do estado quando submit o form. @GiovanniManganotti
Comment: Olá, vc poderia me explicar melhor essas duas linhas de código ?
const {name, value} = e.target;
this.setState({[name]: value});

e eu tbm fiquei na duvida o pq vc colocou um value, um name e um id no input mas nao colocou nada no botão. Se puder me responder eu ficarei grato ! Obrigado.
Comment: Ok, Obrigado pela ajuda !
Comment: Se for a resposta do seu pergunta @GiovanniManganotti aceite

Exibindo dados com React JS


ORA-06503 Function returned with no value

Question: im getting the "ORA-06503 Function returned with no value "  error when i tried to execute this function. can you please let me know how to resovle tis?
Create Function Name(in_name) Return varchar2
Is
Cursor S
IS Select v1,v2,v3 from tablename;
Begin
    OPEN S
      Loop Fetch S into v_1, v_2, v_3;
         Exit when S%NOTFOUND;
        if (v_3 is null)
            Then For gm_rec in ( Select x,y,z,c from Tablename where
                        Tablename.x=V_1
                        and Tablename.y=V_2
                     )
            Loop
            RETURN(gm_rec.z)
            End Loop;

        if (v_3 is not null)
            Then For gm_rec1 in ( Select x,y,z,c from Tablename where
                        Tablename.x=V_1
                        and Tablename.y=V_2
                       )
            Loop
            RETURN(gm_rec1.c)
            End Loop;
                End IF;
           Close S;
       END

Answer: Create Function Name(in_name) Return varchar2
Is
Cursor S
IS Select v1,v2,v3 from tablename;
Begin
    OPEN S
      Loop Fetch S into v_1, v_2, v_3;
         Exit when S%NOTFOUND;
        if (v_3 is null)
            Then For gm_rec in ( Select x,y,z,c from Tablename where
                        Tablename.x=V_1
                        and Tablename.y=V_2
                     )
            Loop
            RETURN(gm_rec.z)
            End Loop;

        if (v_3 is not null)
            Then For gm_rec1 in ( Select x,y,z,c from Tablename where
                        Tablename.x=V_1
                        and Tablename.y=V_2
                       )
            Loop
            RETURN(gm_rec1.c)
            End Loop;
                End IF;
           Close S;
           -- add this line
           RETURN('')
       END


If a product of topological spaces is metrizable is it true that every topological space that constitutes the product is metrizable?

Question: If a product of topological spaces is metrizable is it true that every topological space is metrizable?
If not,could someone provide me with an example?
Comment: $X\times \varnothing=\varnothing$ is metrizable for any topological space $X$. Maybe you want to specify that your product is non-empty.
Comment: By "...every topological space is metrizable?", you're referring to the constituent topological spaces that form the product space?
Comment: GAM,I mean exactly that,I edited the post.
Answer: If $Y$ is not empty, say $y\in Y$, and $d$ is a metric on $X\times Y$, then consider $(x,x')\mapsto d((x,y),(x',y))$
Comment: Thank you for your answer!
Answer: Every factor $X_i$ of a non-empty product space $\prod_{i \in I} X_i$ is topologically a subspace of that product.
So every factor will inherit all hereditary topological properties (like metrisability and Hausdorffness, regularity, and many others).
Comment: @Matematleta That a subspace of a metric space just uses the restricted metric which induces the subspace topology is what I assume the OP already knows. As he hasn't specified any thoughts of himself we don't know what he knows.
Comment: Quibble: It's trivial in the case of metrizability of the product, but isn't your answer/comment just what the OP wants to show?
Comment: The restricted metric actually answers my question as well.


Zend form input fields next to eachother

Question: If you're reading this, you probably know how much of a pain it is to customize the layout of Zend form. What I want to achieve is a layout sort of like this:
Name: [Type your first name here][Type your last name here]
Address: [Type your street here][Type your number here][Type your addition here]

Does anyone know how to achieve this, or can anyone point me to a good example?
Answer: What I would try and do is create custom Decorators for the form and different types of fields.
A form decorator for surrounding form elements
<form>%rows</form>

A row decorator to separate the rows

%elements

An element decorator that shows both label and element and floats all to the left
%label%left_floated_element

An element decorator that shows only the element and float it to the left
%left_floated_element

The output would result in something like:

<form>

        Name<input type="text" name="firstname" style="float: left" .../>

        <input type="text" name="lastname" style="float: left" .../>

        Address<input type="text" name="street" style="float: left" .../>

        <input type="text" name="number" style="float: left" .../>

        <input type="text" name="addition" style="float: left" .../>

</form>

You can also change the used HTML to build a table rather than using divs to get the job done.
Check out the Zend Framework manual for more info on how to create your own custom decorators.
http://framework.zend.com/manual/en/zend.form.decorators.html
Answer: What ends up happening, and I think this is a weakness of Zend_Form in general, is that you often want to be able to freely place the label as you see fit. Creating a custom decorator makes sense if you're going to reuse a display style - like if you're creating a Sharepoint like application - but in situations where the form is not going to be reused, or must be customized for space constraints, visual style, etc, creating decorators for each situation is too expensive. Decorators should be your second resort, i.e. when you like a display style and would like to use it everywhere in your site.
What you can do to get around this little bit of nik nak in O'Phinney's design is to drop the label from the decorators, but still set the label. Use a viewscript like this:
$form->setDecorators(array('ViewScript',array('viewScript' => 'path/from/views/scripts/of/module'));

In the viewscript, layout html like normal. This way you will not have to create an arbitrary structure for each variation of visual / structural display you want.
$this->element->name;

will produce the label-less field.
$this>element->name->getLabel();

will produce the label text.
If you need some assistance as to how to enumerate the decorators to get this effect, usually if for instance you're using Dojo Elements, you'd have
array('DijitElement','Errors','HtmlTag','Label')

As your decorators.
Just drop label. If label is in an array like this
array('Label',array(...))

drop that array, since it represents the configuration for that decorator.
But of course, in the options make sure 'label'=> 'desired label' is set.
And now, in your form, you could drop in those elements as you please without having to be constrained where the labels should go!
Note if you're using default settings for decorators on your form fields, you might want to figure out what the default decorators ARE since when you begin setting them you may accidentally miss a decorator and lose something.


Script needed to log the name of attached USB drive to text file

Question: We rotate 2 TrueCrypt-encrypted USB hard drives ("BACKUP 1" and "BACKUP 2") off-site each week, for our data backup system.
For both drives, the physical drive has no drive letter assigned to it (not necessary); however, both mounted, virtual drives have the letter "V" assigned to them.

Can anyone suggest a script which would log the volume label of the external drive?
I will schedule this to run each night, so I can see which backup drive was on-site at any given point, allowing me to see if the disk rotations are not being done according to schedule.
Any ideas or suggestions would be much appreciated.
Comment: It isn't immediately clear why this should be closed, except that it's very strange to use USB drives for backups in a proper enterprise environment (but really as long as they are verified I'm not sure there is anything wrong with that).  Also, the term you're looking for is "volume label".
Comment: I am **not** impressed by the elitist attitude that people think they can somehow tell if there was "no research effort" on the part of the OP. There WAS research effort. It is much easier to research something than to wait hours for a response. I couldn't find what I was looking for, so I asked here as a last resort. This whole "research effort" thing is *very* relative and subjective. Someone with more experience might find it easy to research a problem, but someone with less may find it easier to explain the problem, so that those with more experience can nudge them in the right direction.
Comment: This question appears to be off-topic because it doesn't show any research effort.
Comment: If you *really* think this needs to be closed- why not add a short comment explaining why? As I've said many times before: it should be *mandatory* to leave a comment explaining why you want to vote to close a question. If nothing else, it would provide more useful feedback.
Comment: I agree that this would be strange- if it were an enterprise environment. However, this is a small, non-profit organization with only around 750GB of data on the file server. They neither have the budget nor the need for anything more advanced. Shadow Copy is enabled, which allows previous versions for the past 4 or 5 weeks to be retrieved.
Comment: I'm not sure I agree with a "close for lack of research effort" regardless.  Downvote maybe (I wasn't the one that did), but having to have a member that frequents the site often spell out that they tried to find a solution upfront without the benefit of the doubt seems a little overkill to me.  But again, voting is in the hands of the voter.
Comment: @Austin''Danger''Powers "does not ***show*** any research effort" (emphasis added).  i.e. "Tell us what you've tried and eliminated, so that we don't have to waste time telling you to do all the things you've already done." -- Not having that doesn't make your question Off Topic, but it does make it harder to answer. If you wish to discuss why this is part of our standards for a quality question please [open a discussion on Meta](http://meta.serverfault.com/questions/ask). I will be cleaning up comments on this question in the near future.
Comment: It was a very clearly-presented question, which even had a screenshot. There was enough information, as evidenced by the fact the *very first* answer (the same day I posted) completely nailed it. I feel this "show research effort" rule is not applied to everyone equally. If you look, you can see that a massive percentage of questions show no research effort, but get no close votes at all. I got 3. It's a lottery.
Answer: The command vol v: will tell the volume label.
The output will be something like this:

Volume in drive C is System
Volume Serial Number is 86DA-23A0

You might want to write the first line of the output to file like this:
vol v:|find "Volume in drive">>drivelog.txt
Comment: Good man. That's what I was looking for.
Answer: Here is what I eventually did... thanks to the information from ZEDA-NL's answer:
vol v:|find "Volume in drive" >>"d:\Admin\USB backup drive rotation log.txt"

echo %date% >>"d:\Admin\USB backup drive rotation log.txt"

echo %time% >>"d:\Admin\USB backup drive rotation log.txt"

echo. >>"d:\Admin\USB backup drive rotation log.txt"


If $(a,b)=1$ then there exist positive integers $x$ and $y$ s.t $ax+by=1$.

Question: How can i prove that
if $\gcd(a,b)=1$ there exist $x>0$ and $y>0$ such that $ax-by=1$?
Comment: Can you prove it without the restriction $x,y>0$ ?
Comment: @TonyK  OK.  I withdraw that. However, this question has been asked quite a number of times on this site.
Comment: Are $a,\:b$ positive?
Answer: (assuming $a,b>0$)
Let $S = ${$b,b^2, b^3,...$}, all taken mod $a$. There are only $a$ possible values in $S$, but the sequence in question has infinitely many terms; therefore, there is some $n<m$ so that $b^n \equiv b^m$ (mod $a$). Then $(b^{n})(b^{m-n}-1) = b^m - b^n = sa$ for some integer $s>0$. $(b, a) = 1$, so $(b^n,a) = 1$, so $b^n|(sa)\implies b^n|s$, so $x=\frac{s}{b^n}$ is an integer. Thus, we have
$$bb^{m-n-1}-1=b^{m-n}-1=xa$$
Setting $y = b^{m-n-1}$, we have the desired result. You can also see that we have $x, y > 0$.


Ansible: 'regex_replace' removing every character starting with "@"

Question: I have following registered variable with stdout and I want to remove every character starting with "@".
ok: [localhost] => {
    "msg": [
        "email@example.com"
    ]
}

Example: email@example.com should become wazuh.
Answer:
remove every character after "@"

---
- hosts: localhost
  gather_facts: false
  vars:
    my_string: email@example.com
  tasks:
    - debug:
        msg: "{{ my_string | regex_replace('@.*', '') }}"

Provides:
wazuh
Answer: One could also look at the use case as just interested in the left part of the @
delimitered string.
---
- hosts: localhost
  gather_facts: false

  vars:

    my_string: email@example.com

  tasks:

  # For Ansible v2.9 and later
  - name: Use of Python string method
    debug:
      msg: "{{ my_string.split('@') | first }}"

So not removing the part behind but only deliver the part before.
  # For Ansible v2.10 and later
  - name: Show left part with filter
    debug:
      msg: "{{ my_string | split('@') | first }}"

Comment: for ansible 2.9 doesn't recognize the "split"
Comment: It does, but in the Python way `"{{ my_string.split('@') | first }}"`. And there are more Python methods possible for strings ...
Comment: i need a solution regex that will work with all ansible versions..
Comment: `"{{ my_string.split('@') | first }}"` will work with all Ansible versions. Why it has to be regex?
Comment: doesn't work .. "fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'split'\n\nThe error appears to be in .. "
Comment: In an Ansible v2.9 setup I am not able to reproduce the error message. There it just work.
Answer: Also this solution it's working:
regex_replace('@.*$','')


Angular NgRx - How to view object from the store in my template html?

Question: Hey i have object in store and i want to view the object in the template.
My Ts File:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Store } from '@ngrx/store';
import { Comment } from '../../models/comment.model';
import { User } from '../../models/user.model';
import { AppState } from '../../app.state';

@Component({
  selector: 'app-ngrx-get-data',
  templateUrl: './ngrx-get-data.component.html',
  styleUrls: ['./ngrx-get-data.component.scss']
})
export class NgrxGetDataComponent implements OnInit {
  comment$: Observable<Comment[]>;
  userDetails$: Observable<User>;

  constructor(private store: Store<AppState>) {
    this.comment$ = this.store.select('comment');
    this.userDetails$ = this.store.select('user');
  }

  ngOnInit() {
  }

}

My template:

USER DETAILS FROM API

{{item}}

My Error in console:
ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

I try this and its not work:

USER DETAILS FROM API

{{item.key}} {{item.value}}

Image if my state:
Comment: userDetails should be an array.
Comment: Can you show us what is your state looks like?
Comment: I edit the post with image of my state
Answer: What you need is to combine async and keyvalue pipes together. Also the order of the pipes important :

USER DETAILS FROM API

{{item.key}}: {{item.value}}

Here's a demo stackblitz of this code: https://stackblitz.com/edit/angular-1rj8sc
Comment: That's cause your NGRX has no value for userDetails, your screenshot shows everything to be null
Comment: Hey man its work but now i see in my browser the name of the field (the key) but i dont see the value
Comment: Also thanks to @JamesD for fixing the syntax and adding stackblitz sample.
Comment: Yeah normally you'd dispatch a loadaction in the ngOnInit. Something like this.store.dispatch(UserCollectionActions.loadUser());
Answer: This is the correct way to do it:

USER DETAILS FROM API

{{item}}

First you need to let Angular subscribe to observable using async pipe, use that within an *ngIf otherwise it will try to iterate over something that does not exist yet. Next use *ngFor to create multiple
 elements, not

Answer: If your slice of state 'user' is normalized and stored as an object with the key: object structure, you'll need to convert that to an array to iterate over it in the template.
You can easily convert it to an array with something like this
  private userDetails: User;
  constructor(private store: Store<AppState>) {
    this.comment$ = this.store.select('comment');
    // Use Object.values() to convert to an array with all the values of that object
    this.userDetails$ = this.store.select('user').subscribe(userDetails => {
     this.userDetails = Object.values(userDetails);
    });
  }

  // Then

{{item}}

Though it's hard to know exactly what's going on without seeing the data structure.
Some other notes: If userDetails is just a single object, and you want to iterate over each property, and get the key and value, use Object.entries()
Comment: Type 'any[]' is missing the following properties from type 'Observable': _isScalar, source, operator, lift, and 5 more.ts(2740)


Performance: Better low end of eight string guitar

Question: I'm wondering how to get better, clearer low end tone from an active-pickup eight-string guitar? It's being played through a Vox AC30, used specifically for clean and layered loops in an ambient project. How would an equalizer or compressor help?
Comment: Have you tried playing it through a bass amp to see if the guitar itself is producing the sound you need at the low end?
Answer: There are a couple of things you'll need to look at here:
First - the amplifier.
A normal guitar amp (such as an AC30) is really only designed to work well in the frequency range of a guitar tuned from E to E. If your guitar is tuned similarly, you are adding a G and B below that low E - the amp is not going to faithfully recreate these.
So you'll need to look at an amp with a wider frequency range (or use an amp and a bass amp...) and ensure your speaker cabinet can cope with the lower range (there is a reason bass cabs are big!)
Secondly - the guitar
Choice of low string gauge can make a great difference in both playability and sound. Thicker strings usually give a greater volume through the pickups, but may not sound as clear on a normal guitar scale length.
Tone controls are generally basic - filtering treble is generally how they work - so using a graphic equaliser to boost a bit of the low end plus a bit of the top end can make the bass notes sound clearer.


printing whole binary tree on screen

Question: I want to store numbers in a binary tree, exit with 0, then output the numbers in ascending order. Most answers I've seen were on searching in the tree, and the few that were covering this exact topic used methods that I didn't understand. I believe the tree itself is created correctly, but the output function is at fault. Where did I go wrong?
<code>#include <iostream>
#include <stdio.h>
using namespace std;

struct thing {
    short num;
    short howmany = 0;
    thing* right;
    thing* left;
};

void insert(thing* akt, short x) {
    if (akt == NULL) {
        akt = new thing;
        akt->left = NULL;
        akt->right = NULL;
        akt->num = x;
        akt->howmany++;
    }
    else if (akt->num == x) akt->howmany++;
    else if (akt->num > x) return insert(akt->right, x);
    else return insert(akt->left, x);
}

void output(thing* root) {
    thing* akt;
    do {
        akt = root;
        while(akt->left!=NULL) akt=akt->left;
        if(akt->right!=NULL) return output(akt->right);
        cout << akt->num << " " << akt->howmany << "times\n";
        akt = NULL;
    } while (root != NULL);
}

int main() {
    thing* root = new thing;
    short x;
    cout << "number: ";
    cin >> x;
    do {
        insert(root, x);
        cout << "number: ";
        cin >> x;
    } while (x != 0);
    cout << endl;
    output(root);
    return 0;
}
</code>
Comment: Welcome to StackOverflow! To help us find the issue, please include *what output you are execting* (and why), and *what output you actually get* in your question (and try to create a [mcve]).
Comment: Check Boost Graph Library,it can print entire tree.
Comment: Your supposition of doing the insert correctly is wrong. Start with that. `akt = ...` means *nothing* to the *caller* of that function, *including itself*. Thankfully, at least that can be addressed easily in C++ by passing `akt` as a *reference* to a pointer, `thing *& akt`; not a pointer value as you're doing it now. Related, I cannot believe that function doesn't puke warnings, for several reasons, least of which is the `return` values specified for a `void` declared declared function.
Answer: There were multiple mistakes. First insert function was passing pointer by value so root was never modified.
Also corrected output function.
<code>#include <iostream>
#include <stdio.h>
using namespace std;

struct thing {
    short num;
    short howmany = 0;
    thing* right;
    thing* left;
};

void insert(thing* &akt, short x) {
    if (akt == NULL) {
        akt = new thing;
        akt->left = NULL;
        akt->right = NULL;
        akt->num = x;
        akt->howmany++;
    }
    else if (akt->num == x) akt->howmany++;
    else if (akt->num > x) return insert(akt->left, x);
    else return insert(akt->right, x);
}

void output(thing* root) {
    thing* akt = root;
    if(akt == NULL)
        return;

    output(akt->left);
    cout << akt->num << " " << akt->howmany << " times\n";
    output(akt->right);
}

int main() {
    thing* root = NULL;
    short x;
    cout << "number: ";
    cin >> x;
    do {
        insert(root, x);
        cout << "number: ";
        cin >> x;
    } while (x != 0);
    cout << endl;
    output(root);
    return 0;
}`
</code>
Comment: wow i screwed up badly. thank you for the corrected code, now i understand everything, it helped a lot!

printing whole binary tree on screen


Output logging in Java

Question: I'm currently working on applying genetic algorithms to a particular application, and the issue is that there is a large amount of data that I need to analyze, graph and simply, tabulate. Upto this point I have been using csv files, but they have been kind of limited as I still have to generate charts manually, and its an issue when this needs to be done on over 100 documents.
Are there any other options for output logging in Java, for analysis other than CSV files? Any link to any API of any kind would also be useful.
P.S: (The question seems common enough to have been asked already, but I couldn't find it.) I'm not asking about how to log data in Java, or how to redirect it to a file, but if there are any existing ways to easily tabulate and graph large amounts of output.
The kind of data I'm working with involves a lot of numerical data, specifically the attributes of different generations and different organisms inside those generations. I'm trying to find and interpret trends within the numerical data which would mean that I need to generate separate graphs for different populations or test runs, and also find representative values for each file and graph those against specific test run conditions.
Also, there is a time parameter which references the speed of the algorithm. Which methods let me log output without letting the post-processing and disk access affect my test runs? Is it possible?
Comment: Much depends on what kind of data you are working on and from where it's pulled; Java aside, are you using a RDBMDS? If not, why?
Answer: You could use Apache POI to write out an Excel spreadsheet directly.  You can also have it start with a spreadsheet already containing macros and whatever else you need to display your information.
Comment: Thanks. I was looking for something that didn't have much of a learning curve, this comes closest.
Answer: There are plenty of choices in exporting reports / data. There is an open source project call JasperReport that can do charts, PDF, XML, CSV, plain text exporting. But it is an involved process, but does offer Java API to accomplish that task.
Answer: How about writing table into a database, like MySQL?
Using such, you can search your data by better means than in a text file.
Have a look here: http://www.vogella.de/articles/MySQLJava/article.html
On linux, you also have the possibility to stay using your csv files and then generate plots using gnuplot scipts.
Answer: Sounds like you need to be saving the data to a database and then using Jasper Reports to build a report containing the graphs and whatever else you need using the data that you stored in the database instead of trying to use excel. Jasper is fairly easy to use and you can have your java application generate the report for you after the data has been stored in the database.

Output logging in Java


Pointing subdomain DNS to Google Apps location

Question: I want to point a sub domain to a google apps account, what is the best way to do this in DNS.
For example
email.example-site.com -> https://www.google.com/a/example-site.com.com
What should the DNS record look like?
Comment: Is it your own server or are you hosted with some company ?
Answer: To point it to Google Apps, you need to set a CNAME that points to ghs.google.com. For instance:
email.example-site.com IN CNAME ghs.google.com.

You'll also need to configure your Google Apps account to allow this. In your Dashboard, click on the Email link and it should take you to your Email settings page. At the top, you should see a section called: Web address, with a link called Change URL. Go through the wizard and it should provide you with instructions on what you need to do.
Answer: What you are trying to do is outside the scope of DNS on it's own. You can however point DNS to a web server that then does a HTML redirect.
Comment: the Google Apps instructions specify that this is done at the DNS level with a CNAME record, not with an HTTP or HTML redirect.
Answer: First you need to set up your mx records as per Google's instructions.  If you want to set up a sub domain to access web mail you create a cname that points to ghs.google.com.
You have to validate the subdomain in your Google Docs dashboard before you can use it.

You should also set up spf records to prevent your mail going to spam boxes.
SPF Records:

example.com 14400 in TXT "v=spf1 include:aspmx.googlemail.com ~all"

example.com 14400 in TXT "v=spf1 a mx ip4:xxx.xxx.xx.xxx include:aspmx.googlemail


Pushing an associative array onto each value of another array in Javascript

Question: Let's say I have the following JavaScript array:
var mainArray = ["thing1", "thing2", "thing3"];

And for each of these array elements, I want to add an associative array, so that it looks something like this:
var mainArray = [
  "thing1" {
    key1 => value1,
    key2 => value2,
    key3 => value3
  },
  "thing2" {
    key4 => value4,
    key5 => value5,
    key6 => value6
  },
  "thing3" {
    key7 => value7,
    key8 => value8,
    key9 => value9
  }
];

How would I push each associative array onto each element of mainArray?
Comment: Were you planning on referencing mainArray[0] or mainArray["thing1"] / mainArray.thing1?
Comment: [There are not associative arrays in javascript!](http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/) Please [edit] your question to reflect what you mean, and use valid js syntax in your example.
Answer: I believe you want an object containing objects.
var myObj = {
  "thing1": {
    "key1": "someValue",
    "key2": "someValue"
  },
  "thing2": {
     // etc
  }
};

alert(myObj.thing1.key1);

Answer: Using JavaScript forEach array method:
JSFiddle here.
var mainArray = ["thing1", "thing2", "thing3"]

var mainObj = {};
mainArray.forEach(function(curr, ii) {
    mainObj[curr] = { 'key1': 'value' + (ii * 3 + 1), 'key2': 'value' + (ii * 3 + 2), 'key3': 'value' + (ii * 3 + 3) }
})
console.log(mainObj)

Outputs:
{
    "thing1": { "key1": "value1", "key2": "value2", "key3": "value3" },
    "thing2": { "key1": "value4", "key2": "value5", "key3": "value6" },
    "thing3": { "key1": "value7", "key2": "value8", "key3": "value9" }
}

And can be accessed by mainObj.thing1

Alternatively, using JavaScript map method:
Another JSFiddle here.
var mainArray = ["thing1", "thing2", "thing3"]

var newArray = mainArray.map(function(curr, ii) {
    var obj = {}
    obj[curr] = { 'key1': 'value' + (ii * 3 + 1), 'key2': 'value' + (ii * 3 + 2), 'key3': 'value' + (ii * 3 + 3) }
    return obj
})
console.log(newArray)

Outputs:
[
    { "thing1": { "key1": "value1", "key2": "value2", "key3": "value3" } },
    { "thing2": { "key1": "value4", "key2": "value5", "key3": "value6" } },
    { "thing3": { "key1": "value7", "key2": "value8", "key3": "value9" } }
]

However map only returns an array. Therefore accessing elements would be like newArray[0].thing1 which I think is odd.

Or if you are wanting to simply weave them together:
JSFiddle weave.
var mainArray = ["thing1", "thing2", "thing3"]

var newArray = [];
mainArray.forEach(function(curr, ii, arr) {
    newArray.push(curr,
               {
                   'key1': 'value' + (ii * 3 + 1),
                   'key2': 'value' + (ii * 3 + 2),
                   'key3': 'value' + (ii * 3 + 3)
               }
    );
})
console.log(newArray)

Outputs:
[
    "thing1", { "key1": "value1", "key2": "value2", "key3": "value3" },
    "thing2", { "key1": "value4", "key2": "value5", "key3": "value6" },
    "thing3", { "key1": "value7", "key2": "value8", "key3": "value9" }
]

Answer: You can do it like that:
var mainArray = {"thing1":{}, "thing2":{}, "thing3":{}};
mainArray.thing1[key1]=value1;
mainArray.thing1[key2]=value2;

I added only 2 values, but you can add as much as you need.
Answer: JavaScript associative arrays are really just objects. You can use something like the following to create an array of associative arrays,
function createObject(key1, var1, key2, var2, key3, var3) {
    var newobj = {};
    newobj[key1] = var1;
    newobj[key2] = var2;
    newobj[key3] = var3;
    return newobj;
}

var a1 = [];
a1.push(createObject("var1", "a", "var2", "b", "var3", "c"));
a1.push(createObject("var4", "d", "var5", "e", "var6", "f"));
alert(a1[1].var4);
alert(a1[1]["var4"]);
alert(a1[0].var3);
alert(a1[0]["var3"]);

This will alert "d" twice and then "c" twice.
Answer: Here's my attempt:
function objectify(keys, values){
    return keys.reduce(function(obj, key, i){
        obj[key] = values[i];
        return obj
    }, {});
}

Example call:
objectify(
    ['a','b','c'],
    [{k:1, l:2, m:3},{k:4, l:5, m:6},{k:7, l:8, m:9}]
);

Demo on JSFiddle


Where do we use .i files and how do we generate them?

Question: I was going through the GCC man page, I found the following line:
 file.i
           C source code that should not be preprocessed.

I know that running gcc -E foo.c stops the compiler after preprocessing;
but what is the real world application of creating .i files.
Also is there a way of generating a .i files other than gcc foo.c -E > foo.i?
Comment: One real-world use is in reporting compiler bugs. You send the `.i` file that triggers the bug, so it can be reproduced by someone who doesn't have your headers. https://gcc.gnu.org/bugs/#need
Comment: Another way is `gcc --save-temps -o foo foo.c`
Comment: See also: [How to view C preprocessor output?](https://stackoverflow.com/q/3742822/4561887). I'm especially a fan of [this answer](https://stackoverflow.com/a/76127046/4561887).
Answer: The .i files are also called as "Pure C files". In preprocessing stage

Header files will be included.
Macros will be replaced.
Comments are removed.
Used for conditional compilation.
If you look at the .i file you can see these things.

Command to generate .i file is-
gcc -E foo.c -o foo.i

Answer: A .i file is an "intermediate" preprocessed file, or "single translation unit"
"Intermediate" means in this case: "between the stages of preprocessing and compiling", where the build process includes:

Preprocessing
Compiling
Assembling
Linking

Therefore, per man gcc, a file.i file is:

C source code that should not be preprocessed.

Source: man gcc then press the / key to search, and search for "\.i".
Detailed Steps: man gcc, then press the / key to search, then type in \.i, then press the Enter key, then press the n key repeatedly until you find it.
What this means is that a .i file is preprocessed source code, so it has already been preprocessed. Therefeore, it already contains:

all header files included
macros replaced
and comments removed

...as stated by @Sathish in his answer.
You'll also notice a ton of special "comments" added by gcc that now begin with the # character, such as these:

# 1 "main.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "main.c"
# 44 "main.c"
# 1 "/usr/include/stdio.h" 1 3 4
# 27 "/usr/include/stdio.h" 3 4
# 1 "/usr/include/features.h" 1 3 4
# 374 "/usr/include/features.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 1 3 4

I don't know what those are nor what they do. Someone please tell me if you know.
Note that a simple program such as this:
#include <stdio.h>

int main()
{
    printf("hello world\n");

    return 0;
}

Compiled with this:
gcc -Wall -std=c99 -O0 -save-temps=obj main.c -o ./bin/main

Will produce a main.i file that is about 682 lines long, with the main() function shown above being right at the very end.
How to generate all intermediate files, including the .i files:
My preference is to generate all intermediate files (.i, .o, .s, rather than just the .i file using -E) all at once in a local bin folder in the project by using the gcc -save-temps=obj option like this:
mkdir bin
gcc -save-temps=obj foo.c -o ./bin/foo

Now you have the following files in the "foo/bin" directory:

foo     # compiled binary program (AKA: combined "object file",
        # "executable", "binary", "program", or "machine code")
foo.i   # intermediate, preprocessed C file
foo.o   # individual object file
foo.s   # assembly file

Run the program of course with:
./bin/foo

Notes about "object files" and "executables"
Note that the final output, the foo executable file, is called the "compiled binary program", "program", (combined) "object file", "executable", "binary", or just "machine code", or "ones and zeros" (10101010). It is an object file in object file format, as are the individual *.o object files which are combined into one by the linker to create it. The linker combines all *.o object files into one in order to make the final foo executable, or combined object file.
The GNU linker (ld) manual states it as follows. See section "3.1 Basic Linker Script Concepts": https://sourceware.org/binutils/docs/ld/Basic-Script-Concepts.html#Basic-Script-Concepts (emphasis added, as well as content in square brackets []):

3.1 Basic Linker Script Concepts
We need to define some basic concepts and vocabulary in order to describe the linker script language.
The linker combines input files [individual *.o object files] into a single output file. The output file and each input file are in a special data format known as an object file format. Each file is called an object file. The output file is often called an executable, but for our purposes we will also call it an object file. Each object file has, among other things, a list of sections. We sometimes refer to a section in an input file as an input section; similarly, a section in the output file is an output section.

For more info. on object files, you can also see two of my other answers here:

How do I find out at compile time how much of an STM32's Flash memory and dynamic memory (SRAM) is used up?
Convert binutils `size` output from "sysv" format (`size --format=sysv my_executable`) to "berkeley" format (`size --format=berkeley my_executable`)

See also

This answer by @Ciro Santilli OurBigBook.com: How to view C preprocessor output?


Cox multi-state model - CIF confidence intervals

Question: Is it possible to get confidence intervals for the estimated CIF from a survival::coxph multi-state model?
This code produces the cumulative incidence function, but there are no options to get confidence intervals:
library(survival)

# 0 = Censored, 1 = Relapse, 2 = Death
rotterdam$status = ifelse(rotterdam$recur == 1, 1,
                          ifelse(rotterdam$death == 1, 2, 0))
rotterdam$time = pmin(rotterdam$rtime, rotterdam$dtime)

# Competing risks Cox model
m = coxph(Surv(time, as.factor(status)) ~ hormon, data = rotterdam, id = pid)

# Plot CIF for people without hormone replacement therapy
s = survfit(m, newdata = data.frame(hormon = c(0)))
plot(s, col = c('red', 'blue'), xlab = 'Time since diagnosis (days)',
     ylab = 'CIF') # Plots s$pstate[, 1, ] against time
legend(x = 0, y = 0.58, legend = c('Relapse', 'Relapse free death'),
       col = c('red', 'blue'), lty = 1)

Essentially I'm after adding confidence intervals to the lines in the plots.
I'm happy to use a different package if needed, but it needs to be a Cox model & not a Fine-Grey model.
Thanks in advance!
Comment: A confidence interval about what?
Comment: @StéphaneLaurent sorry I should have said - about the cumulative incidence function. I've added more info to the question
Answer: I am not familiar with this stuff, so I'm really not sure of what I do below. See the competing risks vignette and ?finegray. Below I follow the ?finegray example.
etime <- with(rotterdam, ifelse(recur == 0, dtime, rtime))
event <- with(rotterdam, ifelse(recur == 0, 2*death, 1))
event <- factor(event, 0:2, labels = c("censor", "recur", "death"))

pdata <- finegray(Surv(etime, event) ~ ., data = rotterdam)

fgfit <- coxph(Surv(fgstart, fgstop, fgstatus) ~ hormon,
               weight = fgwt, data = pdata)

sf <- survfit(
  fgfit,
  newdata = data.frame(hormon = c(0, 1)),
  se.fit = TRUE,
  conf.int = 0.95
)

summary_sf <- summary(sf)
# confidence bounds:
summary_sf$lower
summary_sf$upper
```


Finding Taylor Series of $\frac{1}{(i+z)^2}$ centered at $z_0 = i$.

Question:
Find the Taylor series of $$\frac{1}{(i+z)^2}$$ centered at $z_0 = i$.

Im thinking if I could find the Taylor series for $$\frac{1}{i+z}$$ I could use that $$\frac{d}{dz} \big(-\frac{1}{i+z} \big) = \frac{1}{(i+z)^2}$$ However Im struggling with finding the series of 1/(i+z) (I know I should use the geometric series), and also not sure how to make sure the series is centered at $z_0 = i$. Any help is appreciated.
Comment: *Hint*. To find the Taylor series of $1/(i+z)$ use the known geometric series for $1/(1-w)$ in powers of $w$.
Comment: @GEdgar How do I ensure its centered at $i$?
Answer: To find the Taylor series of $1/(i+z)$ in powers of $z-i$.  I could write $w = z-i$ and find the Taylor series of that in powers of $w$.
$$
\frac{1}{i+z} = \frac{1}{2i+w}
$$
and recognize this as a geometric series with first term $1/(2i)$ and ratio $-w/(2i)$
$$
\frac{1}{2i+w} =
\frac{1}{2i}\left(\frac{1}{1-\frac{-w}{2i}}\right)
=\frac{1}{2i} + \frac{-w}{4} + \frac{w^2}{-8i} + \frac{-w^3}{-16} + \dots
$$
Answer: $\frac 1 {(i+z)^{2}}=-\frac 1 4 (1+(z-i)/2i)^{-2}$. Now use the expansion $(1+w)^{-2}=1+\frac {(-2)} {(1)} w+\frac {(-2)(-3)} {(1)(2)}w^{2}+\frac {(-2)(-3)(-4)} {(1)(2)(3)}w^{3}+\cdots$ for $|w| <1$.