Including PortableDevice.h causes a lot of errors

Question: I read this article and just created a cpp console project in VisualStudio 2017 including some headers.
stdafx.h:
#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>

#include <PortableDeviceApi.h>
#include <PortableDevice.h>

All I've done is this and I got a lots of errors.
오류  C4430   형식 지정자가 없습니다. int로 가정합니다. 참고: C++에서는 기본 int를 지원하지 않습니다. ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\propkeydef.h 35
오류  C2143   구문 오류: ','이(가) '&' 앞에 없습니다. ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\propkeydef.h 35
오류  C2803   'operator =='에는 클래스 형식의 정식 매개 변수가 적어도 하나는 있어야 합니다.  ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\propkeydef.h 35
오류  C2805   이항 'operator =='에 매개 변수가 너무 적습니다.   ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\propkeydef.h 35
오류  C2065   'pkeyOne': 선언되지 않은 식별자입니다.  ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\propkeydef.h 35
오류  C2228   '.pid' 왼쪽에는 클래스/구조체/공용 구조체가 있어야 합니다.    ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\propkeydef.h 35
오류  C2065   'pkeyOther': 선언되지 않은 식별자입니다.    ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\propkeydef.h 35
오류  C2228   '.fmtid' 왼쪽에는 클래스/구조체/공용 구조체가 있어야 합니다.  ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\propkeydef.h 35
오류  C3861   'IsEqualIID': 식별자를 찾을 수 없습니다.   ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\propkeydef.h 35
오류  C4430   형식 지정자가 없습니다. int로 가정합니다. 참고: C++에서는 기본 int를 지원하지 않습니다. ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\propkeydef.h 36
오류  C2143   구문 오류: ','이(가) '&' 앞에 없습니다. ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\propkeydef.h 36
오류  C2803   'operator !='에는 클래스 형식의 정식 매개 변수가 적어도 하나는 있어야 합니다.  ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\propkeydef.h 36
오류  C2805   이항 'operator !='에 매개 변수가 너무 적습니다.   ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\propkeydef.h 36
오류  C2065   'pkeyOne': 선언되지 않은 식별자입니다.  ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\propkeydef.h 36
오류  C2065   'pkeyOther': 선언되지 않은 식별자입니다.    ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\propkeydef.h 36
오류  C2065   'GUID_DEVINTERFACE_WPD': 선언되지 않은 식별자입니다.    ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 18
오류  C4430   형식 지정자가 없습니다. int로 가정합니다. 참고: C++에서는 기본 int를 지원하지 않습니다. ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 18
오류  C2440   '초기화 중': 'initializer list'에서 'int'(으)로 변환할 수 없습니다. ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 18
오류  C2065   'GUID_DEVINTERFACE_WPD_PRIVATE': 선언되지 않은 식별자입니다.    ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 23
오류  C4430   형식 지정자가 없습니다. int로 가정합니다. 참고: C++에서는 기본 int를 지원하지 않습니다. ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 23
오류  C2374   'DEFINE_GUID': 재정의. 여러 번 초기화했습니다.   ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 23
오류  C2440   '초기화 중': 'initializer list'에서 'int'(으)로 변환할 수 없습니다. ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 23
오류  C2065   'GUID_DEVINTERFACE_WPD_SERVICE': 선언되지 않은 식별자입니다.    ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 28
오류  C4430   형식 지정자가 없습니다. int로 가정합니다. 참고: C++에서는 기본 int를 지원하지 않습니다. ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 28
오류  C2374   'DEFINE_GUID': 재정의. 여러 번 초기화했습니다.   ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 28
오류  C2440   '초기화 중': 'initializer list'에서 'int'(으)로 변환할 수 없습니다. ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 28
오류  C2065   'WPD_EVENT_NOTIFICATION': 선언되지 않은 식별자입니다.   ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 404
오류  C4430   형식 지정자가 없습니다. int로 가정합니다. 참고: C++에서는 기본 int를 지원하지 않습니다. ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 404
오류  C2374   'DEFINE_GUID': 재정의. 여러 번 초기화했습니다.   ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 404
오류  C2440   '초기화 중': 'initializer list'에서 'int'(으)로 변환할 수 없습니다. ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 404
오류  C2065   'WPD_EVENT_OBJECT_ADDED': 선언되지 않은 식별자입니다.   ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 408
오류  C4430   형식 지정자가 없습니다. int로 가정합니다. 참고: C++에서는 기본 int를 지원하지 않습니다. ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 408
오류  C2374   'DEFINE_GUID': 재정의. 여러 번 초기화했습니다.   ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 408
오류  C2440   '초기화 중': 'initializer list'에서 'int'(으)로 변환할 수 없습니다. ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 408
오류  C2065   'WPD_EVENT_OBJECT_REMOVED': 선언되지 않은 식별자입니다. ConsoleApplication1 c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\portabledevice.h 412
...

I have no idea to handle this since I am not familiar with Windows development and this is first time to create an Windows app. How can I solve this problem or how can I get an information about this?
Comment: It complains about C++ specific declarations.  The compiler somehow thinks it is compiling a .c file but still has the `__cplusplus` macro defined.  Don't define it yourself, I guess.  Be sure to use a project template to get started, don't wildly make changes without telling anybody about it.
Answer: Update: I left the initial answer, but I think it's irrelevant. Are you positive that you included files in the following order as in your question?
#include <PortableDeviceApi.h>
#include <PortableDevice.h>

As this doesn't produce any errors in the empty console app, however, should you reverse the order as below, the list of errors matches your question:
#include <PortableDevice.h>
#include <PortableDeviceApi.h>

All above assuming you have SDK installed.
Initial answer (most likely irrelevant to the problem)
This is just a guess since your question is incomplete (as it doesn't have full code to reproduce the problem), but I think you might have forgotten to add proper main returning int which could result in C4430 to your console application or some other simple error as next one in your error list C2143. Some missing ; after a statement or int in definition or declaration.
Perform binary search in your source code by commenting parts of it to see what exactly causes the errors and if you can't find it yourself in a small code snippet, post your source code in your question.
Comment: I just created empty console app project and add two code. "#include " and "#include ". This two code cause error.
Comment: @RedLaboratory, does it make a difference if you move those 2 lines of code from stdafx.h into your console app's app_name.cpp (or wherever your main() is)? Does it produce same errors or different ones?


Question if a class in Python like this is correct

Question: I'm a beginner. I have a question if this code snippet is acceptable in creating a Class in Python. It is a class of a ball for a pong game in python.
It works but is it good programming practice what I am doing. As you can see I am using pygame and using it directly in the draw method. Particularly this part I wonder if this is ok.
class Ball(pygame.rect.Rect):
   def __init__(self,left,top,width,height):
      super() .__init__(left,top,width,height)
      self.color = (255,0,0)

   def draw(self,screen):

       pygame.draw.rect(screen,self.color,self)

Comment: No it is not, because the indentation is incorrect.
Comment: Do not derive from `pygame.rect.Rect`. The "PyGame" way is to use a [`pygame.sprite.Sprite`](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite) object
Comment: Yes I see thanx @Rabbid76 the methods are not indented here it is in my program but apart from that ? And if I chose to derive from pygame.rect.Rect anyway is it in essence correct?
Answer: Do not derive from pygame.rect.Rect. The "PyGame" way is to use a pygame.sprite.Sprite object


How do I display a simple string array in a custom xamDataGrid field?

Question: I have this problem with xamDataGrid. It is working perfectly fine with a Dictionary datasource with two custom fields if I set their Names to Key and Value.
So I set the datasource to the array (Binding to a Custom Property.SubProperty <- that is the string[]). I set up a custom FieldLayout (I need a custom label, that is why I need a custom field.). For my Field I require a "Name" property. But it does not have a Name. I tried "Value", I even tried Binding to Property and setting FieldLayout Key to Subproperty.
So the code looks somehow like this:
    <igDP:XamDataGrid DataSource="{Binding ElementName=listBox, Path=SelectedItem.Property.StringArraySubProperty}">
      //...FieldLayoutSettings...
      //...FieldSettings...
      <igDP:XamDataGrid.FieldLayouts>
        <igDP:FieldLayout>
          <igDP:FieldLayout.Fields>
            <igDP:Field Name="???Value???orWhat?"
                        Label="Stuff"/>
        <igDP:FieldLayout.Fields>
      </igDP:FieldLayout>
    </igDP:XamDataGrid.FieldLayouts>
  </igDP:XamDataGrid>

If I set it to AutoGeneratedFields, it is perfect. The values appear in a field with the label "Value". But anyhow, what do I do?
Answer: Try using a TemplateField
<igDP:FieldLayout.Fields>
    <igDP:TemplateField >
        <igDP:TemplateField.DisplayTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}" />
            </DataTemplate>
        </igDP:TemplateField.DisplayTemplate>
    </igDP:TemplateField>
</igDP:FieldLayout.Fields>

Comment: Except TextBlock wouldn't have a Label property. Otherwise I'd agree.
Comment: @Hey.There Try adding PresentationTraceSources.TraceLevel=High to the binding. See what you see in the debug pane. Are there empty rows, or really nothing at all?


How do I extend QUnit with new assertion functions?

Question: I'd like to add new assertions to QUnit.
I've done something this:
QUnit.extend(QUnit.assert, {
  increases: function(measure, block, message){
    var before = measure();
    block();
    var after = measure();
    var passes = before < after;
    QUnit.push(passes, after, "< " + before, message);
  }
});

When I use increases(foo,bar,baz) in my test, I get

ReferenceError: increases is not defined

From the browser console I can see increases is found in QUnit.assert along with all the other standard functions: ok, equal, deepEqual, etc.
From the console, running:
test("foo", function(){console.log(ok) });
I see the source of ok.
Running:
test("foo", function(){console.log(increases) });
I am told increases is not defined.
What is the magic required to use my increases in a test?  Also, where (if anywhere) is the documentation for that?
Thanks
Answer: I have found the solution is to accept a parameter in the test callback function. That parameter will have the extra assertion type. So we can call it like so:
//the assert parameter accepted by the callback will contain the 'increases' assertion
test("adding 1 increases a number", function(assert){
    var number = 42;
    function measure(){return number;}
    function block(){number += 1;}
    assert.increases(measure, block);
});

Comment: That is the correct approach. If you want to use your custom assertion via a global reference like other QUnit assertions, you have to explicitly add it to the global object, usually `window`.
Answer: I tried to add a custom assertion today and came to the same problem. Only Original assertions functions are defined also in the global object. Custom assertions are not.
From debugging QUnit code it seems the original assertions functions are placed on the global scope - the window variable - intentionally. This happens at the initialization of QUnit, so it only applies to the original assertions functions already defined at that time.
1.QUnit.js : Definition of the original assertions functions
assert = QUnit.assert = {
  ok: function( result, msg ) {

...

2.QUnit.js : Original assertions function -> QUnit.constructor.prototype
extend( QUnit.constructor.prototype, assert );

3.QUnit.js : QUnit.constructor.prototype -> window
// For browser, export only select globals
if ( typeof window !== "undefined" ) {
    extend( window, QUnit.constructor.prototype );
    window.QUnit = QUnit;
}

Solution
So as you answered, in order to use custom assertion function, one needs to:

Catch the assert argument that is passed to each assert function and use it.
ex.
test("test name", function(assert) {
  assert.cosutomAssertion(..);
...});

Or use the full namespace to reach the assert function.
ex.
QUnit.assert.customAssertion(..)


How to obtain row with a column name that exists in two tables which is not unique?

Question: I have two tables, vendors and customers, with the following fields:
vendors:
vendor_id         name                  UUID
---------    --------------          ---------------
1               V1 vendor               01ffd02
2               V2 vendor               02daaa2
3               V3 vendor               41ddasa

customer:
customer_id         name                  UUID
---------    --------------          ---------------
1               cust1                  71ffd02
2               cust2                  92daaa2
3               cust3                  11ddasa

The UUIDs above are not foreign keys, and not unique for both the tables.
I have to write a single query to capture all rows in either table with a given UUID. For example, if UUID = '11ddasa', the result should be the last row in customer above.
Answer: SELECT  *
FROM    vendors
WHERE   uuid = '11ddasa'
UNION ALL
SELECT  *
FROM    customers
WHERE   uuid = '11ddasa'

Answer: Is this what you're looking for?
SELECT name,UUID from vendors where UUID='11ddasa'
UNION
SELECT name,UUID from customer where UUID='11ddasa'

This will return all rows from either table with UUID.


Prove $E$ is disconnected iff $\exists$ nonempty sets $A$ and $B$ in $M$ satisfying $A\cap \bar B=\emptyset$, $B\cap \bar A=\emptyset$ and $E=A\cup B$

Question: Prove that $E$ is disconnected if and only if there exists nonempty sets $A$ and $B$ in $M$ satisfying $A\cap \bar B=\emptyset$, $B\cap \bar A=\emptyset$, and $E=A\cup B$.
My attempt:
$(\Rightarrow)$ Suppose $E$ is disconnected. Then there exist nonempty open sets $A$ and $B$ such that $A\cap B=\emptyset$ and $A\cup B=E$.
Since $A$ and $B$ are both open and closed in $E$, then $A=\bar A$ nad $B=\bar B$. So $A\cap \bar B =\emptyset$ and $B\cap \bar A=\emptyset$, and $E=A\cup B$.
$(\Leftarrow)$ Suppose $A\cap \bar B=\emptyset$, $B\cap \bar A=\emptyset$, and $E=A\cup B$.
$A\cap \bar B=\emptyset$ $\Rightarrow$ $A\cap B=\emptyset$.
$B\cap \bar A=\emptyset$ $\Rightarrow$ $B\cap A=\emptyset$.
However, I don't know how to show that $A$ and $B$ are open.
Answer: HINT: Can you show that $A=(\overline{B})^c$? Why does that imply that $A$ is open? (And similarly for $B$.) Remember that the closure of a set contains the set itself . . .
Answer: Since $E = A \cup B$ and $A\cap \overline{B} = \emptyset$ we must have $\overline{B}\subseteq B$. Therefore $A$ is open.
Answer: Note that $A^c=\overline{B}$. This means that $A$ is open.


Selecionar determinado item de um spinner

Question: Qual o metodo que faz um spinner estar com determinado item selecionado, ex:
tenho os itens:
1
2
3 e
4
e quero que ele inicie com o '3' selecionado
Answer: Uma vez que você criou programaticamente ou obteve o seu Spinner através de um layout, basta utilizar o método setSelection passando a posição desejada como parâmetro:
spinner.setSelection(2);


Comparing cosine similarities for tf-idf vectors for documents with different length

Question: I'm computing cosine similarities between 2 vectors.
These vectors are information retrieval query and document representations respectively.
They have been computed using tf-idf weights.
Since my documents have different length, tf-idf weights are theoretically unbounded.
The question is: is cosine similarity still a valid measure? Can I compare several cosine similarities for each doc?
Answer: According to Wikipedia's article of tf-idf:

The term count in the given document is simply the number of times a given term appears in
  that document. This count is usually normalized to prevent a bias towards longer documents
  (which may have a higher term count regardless of the actual importance of that term in the
  document) to give a measure of the importance of the term t within the particular document d

So, normalize the frequency of a term t by the length of the document d in which it occurs.  Then you can compute cosine similarity between your tf-idf vectors.
Comment: This was 8 years ago, so it's a bit fuzzy, but I guess one solution would be to insert the same words into both vectors, setting their frequencies to 0 when they don't appear in a document.  For instance, if the word APPLE appears in Document A, but not in Document B, insert it into both vectors, setting it to 0 for Document B's vector.  Again, 8 years ago, so there may be far better ways, but this is one way to tackle it.
Comment: I'm trying to implement tf-idf in MATLAB from scratch. I have written functions to calculate tf and idf vectors for any document. The next step is to get cosine distance between every pair of tf-idf vectors representing each document. The problem is that since there are different number of unique words in every document, the tf and idf vectors I calculate for every document have different lengths. In such a case, how do I calculate the cosine similarity? Any help is appreciated.
Comment: That makes sense. Thank you so much for your response!
Answer: The cosine similarity is still a valid measure. Actually, this is the rule that tf-idf weights have different lengths for different documents, simply because they do not use exactly the same words. Notice that a missing word in a tf-idf vector is actually a word with a frequency of 0.
So you elongate both vectors to the same length by adding and couple of 0's and youb compute the cosine similarity.


Por que COBOL ainda é a linguagem preferida no mundo dos negócios?

Question: Como todos sabem COBOL é muito usado por instituições financeiras, onde apenas a interface é feita utilizando linguagens atuais como Java.

O custo para manter mainframes é grande, mas a migração para uma linguagem atual é maior?
Atualmente é muito usado mas daqui a 20 anos, ainda vai continuar vantajoso continuar utilizando mainframes e dando manutenção em sistemas legados COBOL?
Existe alguma limitação que faça essa migração do COBOL não ser feita? (Ex: Consistência de dados)
Na época que COBOL começou a ser popular na área de negócios, não existia outra linguagem semelhante ou ela é única que continua viva?
Comment: Não tenho absolutamente nada de útil a contribuir, mas sempre que vejo algo relacionado ao COBOL me vêm à mente uma frase de Osvaldo Santo André: "Quem diz que o Cobol morreu, cuidado! Pois sofre o grande risco de ter seu atestado de óbito e a Nota Fiscal de seu caixão feitos por um sistema Cobol"
Comment: Primeiro para responder a pergunta deveria ser respondido se o fato é verdade, COBOL ainda domina o mercado corporativo ? Qual a métrica ?
Comment: Tem mais um ditado que garante a sobrevivência de sistemas feitos em COBOL: não tente consertar o que não está quebrado.
Comment: Onde COBOL é utilizado em Mainframes, COBOL domina em Mainframes. Onde COBOL não é usado em Mainframes, obviamente que não domina. Não há inquéritos que não são capazes de refletir essa realidade é qualquer uso para medir alguma coisa a ver com COBOL. "Eu vou fazer um levantamento de todos os elementos do planeta Terra, por amostragem a atmosfera" Não se surpreenda se algo, o que não entrar na atmosfera está perdida.
Comment: Negativei as respostas baseadas em "achismo", como disse @BillWoodger: `Pessoas que não sabem sobre COBOL, falando sobre COBOL; pessoas que não sabem sobre Mainframes, falando sobre Mainframes.` . . . . Memória histórica: meu primeiro estágio foi com COBOL, foi quando resolvi abandonar Ciencia da Computação e fazer Comunicação Social o.O
Comment: @AndréFigueiredo Editei.
Comment: Acredito eu é pq é custoso atualizar todo o sistema legado, não só em dinheiro, mas em esforços, recursos, tempo e etc.
Comment: Esta pergunta não cumpre os padrões deste site e deve ser encerrada.
Comment: Discussão interessante, mas que não pertinente a filosofia do site. E olha que trabalhei anos com COBOL.
Comment: Não vejo motivo porque fechar, deixei aberta porque a pergunta é direta, bem-estruturada e **não** tem nada a ver com opinião, e sim com respostas únicas e objetivas (A única exceção poderia ser a segunda dúvida).
Comment: http://redmonk.com/sogrady/2014/01/22/language-rankings-1-14/  http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html http://www.computerworld.com/slideshow/detail/98085#slide9
Comment: [COBOL IS EVERYWHERE, EVERY DAYi](http://pt.slideshare.net/Micro-Focus/114593-mf-cobol-everydayinfographicfinalhr?from_search=1)
Answer: Mais alguém consegue ver o problema com essa pergunta? Pessoas que não sabem sobre COBOL, falando de COBOL, pessoas que não sabem sobre Mainframes, falando de Mainframes.
Vamos dividir o "negócio" de forma mais apropriada.
Quanto menor a empresa, menos relevante o idioma, sistema operacional e hardware se tornam.
À medida que progredimos para empresas cada vez maiores, as escolhas se tornam mais importantes.
Nas maiores empresas, com uma quantidade enorme de coisas para fazer, transações financeiras, registrando volume enorme e variado de ações, esse tipo de coisa, com precisão e rapidez: lá você encontrará os sistemas existentes em Mainframes, da IBM, com o programas dentro desses sistemas rodando principalmente em COBOL. Com maior ou menor nível de "interoperabilidade" com outras "coisas" (outros sistemas não-mainframe, serviços web, bancos de dados externos, quaisquer que sejam).
Por que COBOL é tão rápido? Por que a atenção a isso?
Devido ao tipo de linguagem que COBOL é. Campos de comprimento fixo. Decimais aritméticos. Desenvolvido muitos anos antes da existência da teoria moderna sobre linguagens de programação, há pouco para proteger o programador. Um alfanumérico pode ser tratado como um número, e não no sentido que uma linguagem interpretada pode fazer, mas por ponderação por parte do programador.
Obviamente uma descrição mais completa do idioma, mesmo sem comparações, iria preencher pelo menos um livro.
Adicione a isso, o Mainframe IBM, com registros fixos ou de comprimento conhecido (sem delimitadores de registro) e instruções de máquina decimais disponíveis.
Mais uma vez, pelo menos, mais um livro.
Acrescente a isso a experiência acumulada de muitos anos de sistemas massivos.
Acrescente a isso... Eu poderia continuar...
01  BRANCH-TOTAL COMP-3 PIC S9(9)V99.
01  ACCOUNT-TOTAL COMP-3 PIC S9(9)V99.

...

ADD ACCOUNT-TOTAL TO BRANCH-TOTAL

Esse ADD pode (dependendo das opções de compilação) gerar uma instrução de máquina. Uma instrução de máquina. Entendeu? Uma. Sem problema de arredondamento algum. Precisão decimal de 100%. Em uma CPU com uma velocidade de clock que qualquer um poderia desejar.
Substituir um sistema que está cheio disso, em uma combinação de hardware/OS que pode funcionar por anos sem a necessidade de um re-start (IPL), sem constantes melhorias de segurança, e que será executado inalterado (mesmo sem uma re-compilação), em 20-50 anos de tempo, não é uma tarefa trivial.
E se alguém encarar essa tarefa, é melhor fazer ela direito.
Lembre-se, você não pode depender só do hardware ficar mais rápido, porque ao mesmo tempo o negócio demanda mais, então o excesso de capacidade/poder nunca existe de verdade (ou pelo menos não por muito tempo).

COBOL foi desenvolvido em uma parceria entre sete grandes fabricantes de computadores e o governo dos EUA (incluindo os militares) para fornecer uma linguagem padrão em diferentes tipos de hardware, especificamente para a programação de negócios.
Não haviam outras linguagens naquela época que funcionavam desta forma  para fins comerciais. (cada fabricante tinha sistemas de programação específicos para os suas linhas de máquinas, muitas vezes diferentes, mesmo entre suas próprias máquinas)
Os custos de propriedade e operação de Mainframes hoje referem-se à quantidade de poder de processamento envolvido. A capacidade de processamento é necessária para a enorme quantidade de processamento transacional efetuada.
IBM tem planos de desenvolvimento para COBOL para os próximos 50 anos (ver https://www.youtube.com/watch?v=JLMqkuou2-s). Isto, obviamente, significa que eles têm planos de desenvolvimento para computadores mainframe para o mesmo período.
Migrando do Mainframe para outro hardware para o processamento de "back end" não tem limites, mas o sistema de substituição tem de ser: tão  preciso quanto; tão confiável quanto; não custe mais para ser mantido; estável por longos períodos de tempo ("compatibilidade retroativa") - A arquitetura IBM System/360, que recentemente comemorou seu aniversário de 50 anos, ainda é a base para a atual z/Architechture para mainframes IBM. Os programas aplicativos escritos há 50 anos, ainda tem uma chance excepcionalmente boa chance de funcionar hoje. É rotina para sistemas escritos na década de 1970 ainda estarem em execução hoje.
Uma abordagem comum tem sido a implementação de novos sistemas em um novo hardware com novas linguagens, e executar os sistemas de Mainframe existentes ao lado, à procura de oportunidades para reduzir a carga de trabalho dos Mainframe a medida que ela cresça. Para estes, o Teste Do Tempo ainda não foi concluído.
RPG e suas variantes é uma outra linguagem "longa vida" da IBM, mas que sempre foi destinado a sistemas menores (Mini-computadores).
Mainframes (e os sistemas que correm) ainda são importantes? Olhe para os relatórios financeiros da IBM. Somas importantes ainda estão sendo gastas em novo hardware e novo hardware ainda está sendo constantemente desenvolvidos, a um custo considerável. A partir disso, tire as conclusões você mesmo.
Para mais informações sobre Mainframes, a IBM tornou todos os manuais disponíveis ao público, e tem publicado um grande número de Redbooks sobre vários assuntos de Mainframe. Para os interessados em mais pesquisa, mas sem conhecimento de Mainframes, este é um bom ponto de partida: http://www.redbooks.ibm.com/abstracts/sg246366.html
Desculpas pelo Google Translate

Can anyone see the problem with the question? People who don't know about COBOL, talking about COBOL, people who don't know about Mainframes, talking about Mainframes.
Let's split the "business" up into something more appropriate.
The smaller a business, the less relevant the language, operating system and hardware become.
As we progress through larger and larger businesses, the choices become more important.
At the very largest of businesses, with massive amounts of stuff to do, financial transactions, recording enormous volume and variety of stock, that type of thing, accurately and rapidly: there you'll find existing systems on Mainframes, from IBM, with the programs within those systems being mainly COBOL. With a greater or lesser amount of "interoperability" between other "things" (other non-Mainframe systems, web services, external databases, whatever).
Why is COBOL so fast? Why the attention to that?
Because of the type of language COBOL is. Fixed-length fields. Decimal arithmatic. Developed many years before the existence of modern theory on programming languages, there is little to protect the programmer. An alphanumeric can be treated as a number, not in the sense that an interpreted language might do, but by deliberation on the part of the programmer.
Because there is lots of stuff to do, and to do it within time to meet the business needs, it has to be done fast.
Obviously a fuller description of the language, let alone comparisons, would fill at least a book.
Add to that, the IBM Mainframe, with fixed- or known-length records (no record delimeters) and decimal machine instructions available.
Again, at least another book.
Add to that the cumulative experience of many years of massive systems.
Add to that... I could go on...
01  BRANCH-TOTAL COMP-3 PIC S9(9)V99.
01  ACCOUNT-TOTAL COMP-3 PIC S9(9)V99.

...

ADD ACCOUNT-TOTAL TO BRANCH-TOTAL

That ADD can (depending on compile options) generate one machine instruction. One machine instruction. Go it? One. No rounding problems at all. 100% decimal accuracy. On a CPU with a clock speed anyone would wish for.
To replace a system which is full of that, on a hardware/OS combination which can run for years without requiring a re-start (IPL), without constant "security" upgrades, and which will run unchanged (without even a re-compile) in 20-50 years time, is a non-trivial task.
If that task is taken on, you'd better get it right.
Remember, you can't just rely on hardware getting faster, because at the same time the business wants more, so the excess capacity/power never really exists (or not for long).

Original, recovered from a "recently closed tab" (thanks FireFox) and including some minor edits. Please feel free to edit google's attempt at your language:
COBOL was developed in partnership between the seven large computer manufacturers and the US Government (including the military) to provide a standard language across different hardware specifically for business programming.
There were no other languages at the time which would operated in this way (each manufacturer had specific programming systems for their own ranges of machines, often different even between their own ranges) for business purposes.
Costs of owning and operating Mainframes today relate to the amount of processing power involved. Processing power is required for the massive amount of transactional processing carried out.
IBM has development plans for COBOL for the next 50 years (see https://www.youtube.com/watch?v=JLMqkuou2-s). This obviously means they have development plans for Mainframe computers for the same period.
Migrating from Mainframe to other hardware for the "back end" processing has no limits, but the replacement system has to be: as accurate: as reliable; not more expensive to run; stable for the coming many years ("backwards compatable") - IBM's System/360 Architechture, which recently celebrated its 50th birthday, is the basis for today's z/Architechture for IBM Mainframes. Application programs written 50 years ago, still stand an exceptionally good chance of working today. It is routine for systems written in the 1970s to still be able to run today.
A common approach has been to implement new systems on new hardware with new languages, and run the existing Mainframe systems alongside, looking for opportunities to reduce the Mainframe workload as they arise. For these, The Test of Time has not been completed yet.
RPG, and its variants, is another long-lived IBM language, but that was always aimed at smaller (Mini-computer) systems.
Are Mainframes (and the systems they run) still important? Look at IBM's financial reports. Considerable amounts of money are still being spent on new hardware, and new hardware is still being constantly developed, at considerable cost. Draw what conclusions you like from that.
For more information on Mainframes, IBM has made all their manuals publicly available, and have published a large number of Redbooks on various Mainframe subjects. For those interested in more research, but with no Mainframe background, this one is a good starting-point: http://www.redbooks.ibm.com/abstracts/sg246366.html
Comment: Desculpe, fonte é a minha cabeça. Você quer uma referência para alguma parte?
Comment: COBOL will outlive most of us `ou` o COBOL vai enterrar a maioria de nós :D
Comment: @BrunoRozendo updated with original text. A bit lucky on that...
Comment: pelo menos posta o Fonte de onde retirou o texto
Comment: I liked your answer, you have the original? In portuguese has errors of agreement
Comment: Uma leitura tão curta e uma ótima visão de Cobol e Mainframe quanto as suas diferenças com relação a outras plataformas. Thanks.
Answer: Uma instituição bancária precisa processar uma quantidade imensa de dados diariamente, não pode se dar ao luxo do sistema ficar "fora do ar" de vez em quando, e necessita de uma resposta correta para cálculos complexos em um tempo predeterminado. Por essa razão, migrar sistemas - principalmente de uma plataforma para outra completamente diferente - não é algo que se possa fazer rotineiramente, dado seu alto custo e principalmente risco.
Não sei como são as versões modernas de COBOL, mas pelo que sei há uma vantagem explícita em utilizá-lo no sentido de que ela é capaz de manipular o banco de dados diretamente (pelo menos os bancos que foram projetados para fazer interface com essa linguagem). Embora o processamento de SQL seja relativamente leve nos usos mais corriqueiros, ainda é um overhead que faz diferença se for eliminado. Nem todo uso de COBOL evita SQL, é claro, e não saberia dizer que porcentagem dos sistemas atuais - se é que alguma - ainda usa essa técnica, mas ainda é fato conhecido (acreditado?) que essa plataforma oferece um desempenho além do usual em sistemas transacionais.
Quanto a se manter mainframes, é bom lembrar que a crescente virtualização de servidores permitiu que se trouxesse essa plataforma para a era do cloud computing: não apenas há constante manutenção a esse ambiente como também ele se modernizou para tanto dar suporte a aplicações legadas, permitir aplicações novas em linguagens modernas (não todas, mas algumas) e inclusive aprimorar os compiladores COBOL para tornar esses sistemas ainda mais eficientes.
Hoje em dia um profissional que domina COBOL é difícil de ser encontrado, mas por outro lado ele é muito bem pago, de modo que sempre existirá uma porcentagem de desenvolvedores que seguirá por esse rumo. O mesmo vale para Fortran - linguagem ainda muito utilizada no meio científico.
Por fim, quanto ao último item, não sei te dizer ao certo, mas uma rápida olhada na "linha do tempo de linguagens de programação" (Wikipedia, em inglês) noto que a cada década (inclusive a nossa) surgem diversas linguagens novas, umas ficam populares e outras vão sendo esquecidas. Com certeza as linguagens da época eram mais semelhantes entre si do que entre elas e as linguagens de hoje, porém suficientemente distintas quanto, digamos, Java e Python. Ou seja, acredito que seja sim o caso de COBOL ser "a única que continua viva".
Comment: Disclaimer: embora eu tenha trabalhado *com pessoas* que já utilizaram COBOL e Fotran extensivamente, eu próprio nunca o fiz, de modo que não falo por experiência própria, mas sim o que me recordo do relato de terceiros.
Answer: Não tem nada haver com ser preferido ou não. O que acontece muito é que, imagine sua empresa que tem um baita sistemão que faz um monte de coisa e que te satisfaz e não dá problema nenhum. Nunca deu inconsistencia de dados, é rápido para resgatar e/ou visualizar as informações que você precisa.
Um empresário se pergunta: Pra que zorra vou trocar este sistema? É mais barato comprar/desenvolver um novo e com novas tecnologias ou pagar um funcionário/terceirizado que possa fazer alguma implementaçõezinhas "quando" necessário?
Por mais que eu seja um programador, acho que esta é a visão dos empresários.
Comment: Meu Português não é suficiente para a nuance. Poderíamos estar concordando. Não devemos levar o negócio em algo mudo que entra em colapso depois de cinco anos de desenvolvimento e implementação. Nem devemos deixar tal negócio dedicarem um caminho sem reclamar. Isto não é para dizer que há uma solução pronta de um tamanho para todos. Não altere. Fazer a mudança. Nem faz sentido fora do contexto específico. É por isso que eu sinalizado a questão de opinião. Rejeitado.
Comment: Ser um programador não faz diferença. É um caso de negócio, o que deve ser influenciada com cuidado pelo departamento de TI, e não com emoção ou preferência. Entendi errado, e os custos podem ser enormes. Por outro lado, super computadores experientes tendem a se aposentar ou morrer nos próximos anos :-) Isso é um factor a ter em conta.
Comment: ^_^... Então, como eu disse "Por mais que eu seja um programador, acho que esta é a visão dos empresários.", quis me fazer entender o motivo de existir ainda muitos sistemas em COBOL. Porquê quem paga é o empresário e não o programador, analista, gerente de TI, etc... Então o responsável pela TI é quem deve analisar, documentar e apresentar ao empresário os contras e prós de ainda utilizarem-no. Mas só dependerá desta visão/motivação que o empresário terá e aceitará a mudança.
Comment: COmplementando... Tenho esta idéia de ainda existir muitos sistemas em COBOL por falta de conhecimento técnico do empresário, eles só entendem "números", na maioria.
Answer: O custo para manter mainframes é grande, mas a migração para uma linguagem atual é maior?
O custo para manter mainframes é grande, contudo, os mainframe são conhecidos pela disponibilidade "nine nines" 99,9999999%. Como cliente de um banco, eu gosto de ter o meu dinheiro sempre acessível!
O custo para uma migração para uma linguagem actual depende de empresa para empresa e do retorno sobre o investimento dessa migração. Adicionalmente, o risco de se migrar um sistema pode não compensar essa migração.
Atualmente é muito usado mas daqui a 20 anos, ainda vai continuar vantajoso continuar utilizando mainframes e dando manutenção em sistemas legados COBOL?
Claro que sim! Há sistemas que têm código a funcionar desde 1980 e ainda hoje estão em funcionamento!
Existe alguma limitação que faça essa migração do COBOL não ser feita? (Ex: Consistência de dados)
Em termos técnicos não. Contudo, o COBOL em mainframe usa um encoding que a maior parte das pessoas não conhece, que é o EBCDIC. Como é um sistema que só os dinossauros conhecem (sim, porque os dinossauros ainda existem!), são necessários muitos dinossauros para migrar um sistema cobol!
Na época que COBOL começou a ser popular na área de negócios, não existia outra linguagem semelhante ou ela é única que continua viva?
Penso que o Fortran é da mesma altura do COBOL, no entanto, só os dinossauros é que sabem COBOL!
Comment: IBM has announced, this month, Version 6 of Enterprise COBOL. This follows on from V5.2 a year ago, and V5 in 2013. New Mainframes over the last year are the z13, LinuxOne, and the z13s (announced this month). No, it is not just dinosaurs.
Comment: I agree with you... I know COBOL and I'm not a dinasaur (at least I think I'm not)! I'm anxious to see whats new with the integration between COBOL and Java with V6.
Answer: COBOL, hoje, é uma das linguagens mais seguras e rápidas do meio comercial. Não estou dizendo que C ou JAVA sejam "frágeis", mas o COBOL, por não ter tanta documentação e material disponível para consulta (não da mesma forma que outras linguagens), se tornou uma ferramenta muito interessante para quem visa a segurança. Ao contrario de que muitos pensam, o COBOL não esta "desatualizado" ou "morto". Assim como o C, ele sofre constantes mudanças. Ainda existe uma evolução nele, mesmo que sua sintaxe seja antiga. Deixando assim, seu desenvolvimento, de certa forma, lento. Ele não parou no tempo. E com certeza migrar um sistema todo, principalmente bancário, para uma outra linguagem, ainda quando a atual está cumprindo seu papel, é perda de dinheiro e um retrabalho enorme sem grandes retornos.

Na época que COBOL começou a ser popular na área de negócios, não existia outra linguagem semelhante, ou ela é única que continua "viva"?

Ele foi criado para esse propósito, ser uma linguagem de bancos, comércio, etc.
Comment: -1 porque segurança por ofuscação (neste caso, por falta de documentação e de material) não é segurança de verdade. Uma pessoa com vontade de atacar um sistema feito em COBOL não teria mais dificuldades do que no caso de sistemas feitos em outras tecnologias. Na verdade, devido justamente a falta de documentação, fica até mais fácil, pois torna-se também mais custoso para os próprios desenvolvedores COBOL fazerem algo seguro de verdade.
Comment: @Renan, Se você não sabe segurança Mainframe, então por favor não falar sobre isso. Se você não sabe segurança Mainframe, você sabe que é um disparate. Todos os manuais da IBM geralmente disponíveis, estão disponíveis on-line, da IBM. Isto inclui blocos de controle, segurança, idiomas, serviços públicos, bancos de dados, comunicações, tudo. Tudo o que você pode pensar, e muito, muito mais. Ao longo de muitos lançamentos.
Comment: Não custa lembrar o BOL é de linguagem orientada (a) negócios ...
Comment: Não vejo necessidade, já que como ele não esta estagnado e vem provando cada dia que passa ser seguro. Se não surgir uma linguagem mais eficiente eu acredito que irão manter o COBOL ou utilizar uma variação dele para novos desafios
Comment: @brhvitor6 Mas esses hackers de tutorias não existem, são apenas Script Kiddies.
Comment: A longo prazo não seria interessante a migração?
Comment: @Renan Concordo, citei a falta de documentação como um fator que pode modificar o nível de segurança pois a grande maioria de "hackers" são hackers de tutoriais e que não tem a capacidade de descobrir algo sozinho. Seu comentário se torna válido para o 1% que são hackers de verdade.
Comment: @NULL haha também, mas como frequentei muito tempo forums de desenvolvimento de cheats para jogos vi que existem muitos "desenvolvedores" que aproveitam classes/arquivos dupados (dump) de outros desenvolvedores mais "skilleds" e desenvolvem os seus próprios programas, em sua maioria tem um conhecimento até razoável em C/JAVA/LUA, mas não tem um nohall em engenharia reversa por ex.
Comment: Então a linguagem é segura por ter pouca documentação? Tomara que não seja esse o motivo!
Comment: "mas o COBOL, por não ter tanta documentação e material disponível para consulta (não da mesma forma que outras linguagens), se tornou uma ferramenta muito interessante para quem visa a segurança." Desculpa mas você falou uma besteira muito grande. A IBM disponibiliza um vasto material sobre a linguagem e todo o ambiente de mainframe. Aqui no stackoverflow as pessoas só falam do que sabem e têm certeza. Essa foi uma afirmação muito leviana de alguém que não trabalha com COBOL.
Answer: Algumas estatísticas recentes para reforçar o uso do COBOL e do ambiente Mainframe nas empresas:
92 dos 100 maiores bancos do mundo usam cobol/mainframe;
23 dos 25  maiores revendedores do mundo usam cobol/mainframe;
Todas as 10 empresas mais seguras do mundo usam cobol/mainframe;
cobol/mainframe suportam 90% de todas as transações de cartão de crédito
cobol/mainframe executam 30 bilhões de transações por dia
Antes de pensarmos qual a tecnologia ideal, temos que pensar como consultores, como empresários. Avaliação custo/benefício além da segurança de informação ditam a regra sobre implementação de sistemas em empresas.
Outro ponto relevante é que não importa a linguagem se a solução não for bem sucedida, bem aplicada.
Answer: Bem vamos lá:
Inicialmente COBOL não é a linguagem preferida no mundo dos negócios, por ser uma linguagem antiga, é largamente utilizada em Bancos e Instituições Financeiras.
Além desses segmentos, as Estatais de Infra-estrutura também utilizando muito linguagens de Mainframe.
A saber:
Devido ao grande volume de processamento de dados, o Cobol e outras linguagens mainframe como Natural, Adabas (os dois da SoftwareAG), Cobol, Easytrieve dentre outras se tornaram linguagens extremamente populares.
Hoje acredita-se que mais de 70% dos códigos existentes no mundo ainda sejam em alguma linguagem Mainframe.
Além disso, a "dificuldade" em se invadir um ambiente Mainframe também sempre foi muito grande, dando um "q" de segurança aos dados bancários.
Outro fator que faz com que o Cobol e outras linguagens ainda sejam amplamente utilizado é o fato acima citado de que ainda existe muito código nessa linguagem e a reescrita desses códigos seria extremamente caro, e se está funcionando bem, não tem motivo para investir em reescrita.
Hoje, através de diversas ferramentas, pode-se fazer integração de diversas linguagens com o Mainframe, tornando essa linguagem ainda mais "imortal".
Comment: Olá @Andre. Tente estruturar melhor a sua resposta, está bem confusa para leitura.


MikroTik beep on RDP

Question: I am a newbie in MikroTik RouterOS.
How can I add a rule or script to beep when some one tries to connect to a special port on one of interfaces?
For example I need to know if someone is trying to ftp to my server from outside world.
Comment: "I need to know if someone is trying to ftp to my server from outside world" <-- If it's connected to the Internet, then someone is attacking it. I guarantee it.
Answer: As far as I know, there is no way to do that directly.
Workaround could be using firewall rule to add source ip to addresslist:
/ip firewall filter add action=add-src-to-address-list address-list=beeplist
    address-list-timeout=1m1s chain=input disabled=no dst-port=21 protocol=tcp

and then run script to check'n'beep:
:if ([ :len [ip firewall address-list find where list=beeplist]]>0) do={:beep}

periodically via scheduler:
/system scheduler add interval=60s name=beeplist on-event=":if ([ :len [ip firewall address-list find where list=beeplist]]>0) do={:beep}"

Entries in address-list are going to be deleted via address-list-timeout settings.
Still, you are going to hear a lot of beeps...
Comment: +1. Noone likely considers this a good feature to impolkement because mosst routers wont have anyone hearing them scream, being in cabinets, server rooms or - in the case of mikrotik - up on towers :)
Comment: Also, the last time I looked at firewall logs I get attacked a few times a minute. I might as well just set it to beep every few seconds, would but just as accurate.

MikroTik beep on RDP


composer and Lightning

Question: I have composer.jon to require
"acquia/lightning": "2.1.3",

This installs Drupal core 8.3.3. Can I change this to Drupal core 8.3.2 or does Lightning force you to use the Drupal version its packaged with?
I updated this post after fixing the problem. I changed the composer.json file and specified what drupal core version to use like this.
    "acquia/lightning": "2.1.3",
    "drupal/core": "8.3.2",

Answer: Looks like you've largely answered your own question. But to confirm, Lightning generally does not pin to a specific version of core in it's composer.json file. The current constraint is ~8.3.1 (note the tilde) which means the current release of Lightning should work with core 8.3.1 to 8.3.9(repeating) but not 8.4.0.
Core is the exception to the rule. Lightning normally pins to specific versions of dependencies if they are patched (see Lightning's dependency constraint logic). But since core follows SemVer, has predictable releases, and Lightning releases every time core does, Lightning doesn't pin core - even when it is patched (which is pretty much always).
Lightning increments the second digit of its release numbers (the minor release) when Drupal makes a minor release. In the current release of Lightning (2.1.4) the one relates to the three in the current release of core (8.3.3). So Lightning 2.1.x should run on any core 8.3.x. That's why Lightning uses the tilde (~) modifier and three digits when specifying Drupal core constraints.
Comment: Thank you. I did not know that lightning had its own composer.json file until you said that. I see it now in: docroot/profiles/contrib/lightning/. And I see the tilde for the Drupal core version. If the composer.json is higher up in the project folder does it override lower composer.json files? The main composer file is in the root folder of the project. And I specifically entered drupal/core": "8.3.2.
Comment: Higher up in the folder hierarchy does not make a difference. Nor does the mere existence of a composer.json file actually do anything. When you require a dependency from your root composer.json file (as you have done for Lightning), the dependencies dependency's are then negotiated. Higher specificity will "win" as long as it doesn't conflict with another dependency's constraints.

composer and Lightning


Calculating RMSEC and RMSECV of PCA in R

Question: I have been trying to calculate the root mean squares error of calibration (RMSEC) and the root mean squares error of cross validation (RMSECV) for a PCA model made in R using the mdatools package.
My dataset is too complex to upload, however I followed the same method as shown in the link below:
http://mdatools.com/mdatools/models-and-results.html
Am I right in saying that both RMSEC and RMSECV are calculated as the square root of the residuals^2 divided by the number of samples? From the cross validated model, I am given values for Q distance. Are these the data that I use as the residuals when calculating the RMSEC and RMSECV? If so, I would have Q residuals for the calibration model, and Q residuals for the cross validated model.
Thanks in advance
Answer: I'm trying to figure this out too, and it seems that RMSECV is related to PRESS as
$$
RMSECV = \sqrt\frac{PRESS}{n*p}
$$
Where PRESS is the sum of Q-residuals of each sample against a cross validated model, n is your number of samples, and p, the number variables in the original dataset
Similarly, RESS is the sum of the Q-Residuals for each sample of the model against itself, so I imagine RMSEC is similarly defined using the model Q-residuals.


Angular 4 Reset status form

Question: I have a modal with a form, and some required fields.
When I open the modal I correctly see the fields empty, if I write something in the field required and then I cancel the words writed I correctly see the field as invalid.
The problem is that if I close and reopen the modal I want to see the empty fields like if it's the first time I open it but for some reason I see the previous invalid status also if I reset the form.
This is my modal after I close it, it seems that the status never be resetted:

                              <form #modelForm="ngForm">

                                                {{'checkpoint.table.dialog.labels.name'
                                                    | translate }}*
                                                 <input class="form-control" id="name" name="name" required
                                                    [(ngModel)]="checkpoint.name" #name="ngModel" />
                                                    {{'checkpoint.table.validations.required' | translate }}

                                                {{'checkpoint.table.dialog.labels.passStockAlert'
                                                    | translate }} <input pattern="[0-9]*"
                                                    class="form-control" name="passStockAlert"
                                                    id="passStockAlert"
                                                    [(ngModel)]="checkpoint.passStockAlert"
                                                    #checkPoint="ngModel" />
                                                    {{'checkpoint.table.validations.invalid' | translate }}

                                                * {{ 'form.requiredfields' |
                                                translate }}

                                        <button type="button" class="btn btn-info btn-round"
                                            (click)="save();resetForm(modelForm)" data-dismiss="modal"
                                            [disabled]="modelForm.form.invalid || modelForm.form.pristine"
                                            label="Save">{{'checkpoint.table.dialog.save' |
                                            translate }}</button>
                                        <button type="button" class="btn btn-danger btn-round"
                                            (click)="resetForm(modelForm)" data-dismiss="modal">{{'checkpoint.table.dialog.close' |
                                            translate }}</button>

                                </form>

And this is my reset form method:
  resetForm(myForm: NgForm) {
    myForm.form.reset();
  }

Comment: Please format your code. it's unreadable
Comment: Use myForm.reset(); instead of myForm.form.reset();
Comment: @Chandru it doesn't change
Comment: @yurzui updated
Answer: I have successfully implemented this:
my-component.html
  <form (ngSubmit)="resetFormFlags(myForm)" #myForm="ngForm">

 title

      <button type="submit"> btnText</button>
  </form>

my-component.ts
resetFormFlags(myForm: any) {
   myForm.reset();
}

Hope it helps!
Comment: Does it change if you use submit and I don't?
Comment: I don´t think so, Actually I think that your problem is in myForm.form.reset(); try to change to  myForm.reset();
Comment: Doesn't change, same result
Comment: I made a plunker showing the functionality:

https://plnkr.co/edit/d7GNQ5HgWkQZcnEhyTGl?p=preview
Answer: Try like this below code :
<form name="modelForm" role="form" novalidate (ngSubmit)="resetForm(modelForm)" #modelForm="ngForm">

                {{'checkpoint.table.dialog.labels.name'
                    | translate }}*

                <input class="form-control" id="name" name="name" required [(ngModel)]="checkpoint.name" />

                    {{'checkpoint.table.validations.required' | translate }}

            <button class="btn btn-primary" [disabled]="modelForm.form.invalid" type="submit">{{'checkpoint.table.dialog.save' | translate }}</button>
            <button class="btn btn-white" type="button" (click)="resetForm(modelForm)"> {{'checkpoint.table.dialog.close' | translate }}</button>

</form>

componen.ts
resetForm(editForm: NgForm) {
    editForm.reset();
}

Comment: i did't add #name="ngModel" in my answer it will be working for me. try this answer

Angular 4 Reset status form


How to override module classes in Kohana 3?

Question: In Kohana 3, how can I override/extend a module class?
E.g. I want to add functionality to the Auth module that is specific to my application. In this case I want to extend the abstract Auth class located in the classes folder of the Auth module.
What naming convention should I use for my Auth class and where in the file system do I place my class file?
Answer: To solve this issue it's important to understand the hierarchical nature of the Kohana 3 framework. When it comes to overriding or extending modules you need to do the following.
Let's extend the Auth module. When you look at the Auth module file system structure you notice that in the classes directory there is a file called auth.php. When you open this file you see the following:
<?php defined('SYSPATH') OR die('No direct access allowed.');

abstract class Auth extends Kohana_Auth { }

Here an abstract class named Auth is defined which is extending the Kohana_Auth class. When you use any references to the Auth class in your application you're referring to this abstract class. The actual implementation of Auth is actually kept in the Kohana_Auth class which is located in the Kohana folder which part of the module directory structure.
To extend the Auth module, i.e. add your own functionality, you simply place an auth.php file in the classes folder of your application directory. In your auth.php file you extend your version of the Auth module by extending the Kohana_Auth class. Like so:
<?php defined('SYSPATH') OR die('No direct access allowed.');

class Auth extends Kohana_Auth {

   public function get_user()
   {
      $result = parent::get_user()

      // implement your functionality here.

      return $result;
   }

   public function my_added_functionality()
   {
   }

}

Because of the hierarchical nature of the framework, the abstract class Auth defined as part of the module will never be loaded because the framework loads your Auth class first because it takes precedence. The class you extend, Kohana_Auth, provides all the auth original functionality you can no extent and/or override.
For more information on the behavior checkout this part of the documentation.


Expand Tumblr shortened link

Question: I have a Tumblr link like this: http://tumblr.com/XXXXXXXX
In order to communicate with their API I need the hostname of the blog, therefore I need to expand the link to the complete link. Something like: http://blogname.tumblr.com/post/XXXXXX
How can I expand a tumblr shortened link?
Answer: Within the Tumblr API, I do not believe it is possible as mentioned by Derek Gottfrid. If you are using it within your app or service you can try looking at the headers.
For example in python, you can use urllib2
import urllib2
tumb = urllib2.urlopen('http://tumblr.com/XXXXXXXX')
print tumb.url

In PHP, you can use the get_headers method
$url = 'http://tumblr.com/XXXXXXXX'
print_r(get_headers($url))

Comment: Thanks for the answer. I answered on the thread. I might check the backend solutions, although I would prefere a straight API for that.
Answer: Here's another way to do it in Ruby. It needs to follow tumblr redirection. From http://tmblr.co/XXXXX to http://www.tumblr.com/XXXXX and lastly to the expanded URL. From Net::HTTP documentation:
require 'net/http'
require 'uri'

def get_permalink(uri_str, limit=5)
  # You should choose better exception.
  raise ArgumentError, 'HTTP redirect too deep' if limit == 0

  response = Net::HTTP.get_response(URI.parse(uri_str))
  case response
    when Net::HTTPOK then uri_str
    when Net::HTTPMovedPermanently
      get_permalink(response['location'], limit-1)
    when Net::HTTPFound
      get_permalink(response['location'], limit-1)
  end
end

Hope it helps someone

Expand Tumblr shortened link


Solving $\int{\sqrt{x^2+1}} \ \mathrm{d}x$ using integration by parts, given that $\int{\frac{1}{\sqrt{x^2+1}} \ \mathrm{d}}x=\ln(x+\sqrt{x^2+1})+k$.

Question: Here is the question once again:

Deduce the integral $\int{\sqrt{x^2+1}} \ \mathrm{d}x$ using integration by parts, given the following identity: $$\int{\frac{1}{\sqrt{x^2+1}} \ \mathrm{d}}x=\ln(x+\sqrt{x^2+1})+k$$

I know that the integral can be solved by using trigonometric substitutions, but I am looking for another way as that's not what is asked in the question.
Here is what I have done so far:
$$\int{\sqrt{x^2+1}} \ \mathrm{d}x=x \cdot \sqrt{x^2+1}-\underbrace{\int{\frac{x^2}{\sqrt{x^2+1}} \ \mathrm{d}x}}_{\text{$I_1$}}$$
$$I_1=x^2 \cdot \ln{(x+\sqrt{x^2+1})}-\underbrace{\int{\ln{(x+\sqrt{x^2+1})}\cdot 2x \ \mathrm{d}x}}_{\text{$I_2$}}$$
Solving $I_2$ using integration by parts gives an expression which includes $I_1$ so I got into a loop. I'm out of ideas so I would be glad if you could help me out, thank you for your time.
Comment: $\sqrt{x^2+1} = \frac{(x^2 + 1)}{\sqrt{x^2+1}}$
Answer: Notice that
$$\int \sqrt {x^2 + 1} \ \Bbb d x = \int (x')\sqrt {x^2 + 1} \ \Bbb d x = x \sqrt {x^2 + 1} - \int x \frac {x} {\sqrt {x^2 + 1}} \ \Bbb d x = \\
x \sqrt {x^2 + 1} - \int \frac {x^2 + 1 -1} {\sqrt {x^2 + 1}} \ \Bbb d x = x \sqrt {x^2 + 1} - \int \sqrt {x^2 + 1} - \frac 1 {\sqrt {x^2 + 1}} \ \Bbb d x = \\
- \int \sqrt {x^2 + 1} \ \Bbb d x + x \sqrt {x^2 + 1} + \ln (x + \sqrt {x^2 + 1})$$
whence it follows that
$$2 \int \sqrt {x^2 + 1} \ \Bbb d x = x \sqrt {x^2 + 1} + \ln (x + \sqrt {x^2 + 1}) $$
so that
$$\int \sqrt {x^2 + 1} \ \Bbb d x = \frac 1 2 x \sqrt {x^2 + 1} + \frac 1 2 \ln (x + \sqrt {x^2 + 1}) + C$$
where $C \in \Bbb R$ is an arbitrary integration constant added at the end of the calculations.


Duplicate paragraphs from node type FOO to node type BAR

Question: I have two content types: FOO and BAR. These content types have a field called "field_paragraphs" of type "paragraph". And other fields of course.
Now in a situation my user can click a button (that call one of my function defined via hook_menu) and "copy" content of type FOO to a new content of type BAR, so I need to copy, NOT CLONE, field_paragraphs from FOO to BAR: I need to create a standalone copy of "field_paragraphs"; like two different insert.
I have searched on google but all talk about "clone", but in my case I need to copy so I can not use "clone" module.
How can I do this ?
M.
Comment: When does the user copy the content? When he clicks save? does he just manually copy it?

You are talking about copying the content inside the **paragraph bundle** that's attached to the **paragraph field**, and then moving that content to another content type's **paragraph bundle** inside that other content types **paragraph field**correct? Paragraphs is all about reusing paragraph bundles. Duplicating a paragraph field (displays bundles) makes little to no sense to me..
Comment: Sorry @DMAC you are right: my user click a button that start one function defined via hook_menu() that create the copy. I don't understand the rest of your comment: I need to copy value of some fields from FOO to BAR, and one of this field is a paragraph field, not a paragraph bundle. Think to a magazine where I need to recreate a news, where the main content of this "news" is a paragraph field. Now I need to create a new version because in the new content type there are other fields that they are in context into BAR content type but without context into FOO content type. M.
Comment: You are talking about the [Paragraphs](https://www.drupal.org/project/paragraphs) module correct? A paragraph field is literally nothing without paragraph bundles. you need to define paragraph bundles then associate them with the paragraph field when using the paragraphs module. This is why i'm so confused. are you talking about the `Body` field? or a text field you happened to call paragraph?
Answer: EDIT: You can now find a better explanation with the code here.
I know this is old but maybe someone comes here looking for an answer like me, this is tested on Drupal 8.
I found this issue and after looking at last patch, I implemented :
$nodeDuplicate = $node->createDuplicate();

foreach($nodeDuplicate->field_paragraphs as $field){
    $field->entity = $field->entity->createDuplicate();
}

$nodeDuplicate->save();

And I got a duplicate node with duplicated paragraphs fields. If you look at the patch you will see how to add a button to Drupal etc.
Just a note field_paragraphs is the name of my field in the content type, change it with your own.
I didn't have any problem doing it this way, maybe someone has a better way but I did not find it, also at the time of writing this there is still no ported modules for cloning nodes in Drupal 8.
Answer: This is an example that could give you an idea how to do it.
   function copy_node_foo($node) {
      if ($node -> type == "FOO") {
          $node_bar = new stdClass();  // Create a new node object
          $node_bar->type = 'BAR';  // Content type
          $node_bar->language = LANGUAGE_NONE;
          node_object_prepare($node_bar);  //Set some default values
          $node_bar->title = 'Your node title';
          node_bar->field_paragraphs = node->field_paragraphs;
          /* others properties .... */
          node_save(node_bar);
      }
    }

Comment: Hi, with your line "node_bar->field_paragraphs = node->field_paragraphs" drupal doesn't create a copy of node_bar's paragraphs, it link/use node_bar's paragraphs for "node" too (If I change paragraphs in "node" I see these modify in node_bar too). And this is wrong. And I don't want this: I want a new copy of field_paragraphs.
Comment: I see, do this :
load the entity with the id  contained in  node->field_paragraphs, create a new entity of type paragraph,
copy the values of the original paragraph in the new paragraph nod the id,
save the new  paragraph entity
and save the id in the node_bar->field_paragraphs.

If you can load the entity  referenced in node->field_paragraphs and send me the dpm result I can send you back the code.
Comment: I have found this code:
 'name_of_field_in_node', 'bundle' => 'name_of_paragraph_bundle'));
$paragraph->is_new = TRUE;
$paragraph->setHostEntity('node', $node);
$paragraph->save();
?>
but in this code node is already present. In my case is new (never saved). How can I add a paragraphs to a new node ?


Why is the hook shot used so little in the NBA?

Question: Understandably, the NBA is centered around the 3 point shot so most players are not working in the paint. However, there are many big men out there who lack much offensive game other than dunking on a pick and roll.
Defensively most big men these days are just rim protectors and don't have to worry about defending against players who play with their back to the basket.
Doesn't this create somewhat of a defensive deficiency where a player who could reliably make a hook shoot could crush an opposing team offensively because today's modern offenses are field players who simply lacked the size to defend it?
Answer: Because the hook shot is not an efficient shot, largely.
Hook shots are much more difficult than other "close-in" shots; while they solve the issue of the defender blocking you (somewhat), they are harder to aim.
You say "a player who could reliably make a hook shot could crush an opposing team".  Sure!  But that player doesn't exist.
Looking at this analysis of hook shots from last year, nobody makes 60% - and only a small number of players even make 50%.  Sure, nearly 60% is pretty good (it's better than most shots from anywhere other than just at the rim), but it's not earth-shatteringly good; remember this chart?  1.2 EP is your average three point shot from the side.
So maybe Robin Lopez should take some more hook shots; but Robin was also making 33.3% of his three point shots, so it's not like he was leaving a ton of points on the table.  And you can't ignore the difficult of getting the ball in to the player to take the hook shot, nor the likelihood that, were Robin (or Nikola or Brook) to start taking more hook shots, defenders would play them differently and defend the hook better.
I'd also slightly object to your premise; "big men" aren't just rim protectors.  Plenty of big men are also shooters from the outside - see the Lopez brothers for example.  But that's the thing - the ones who might be able to make a decent living with the hook shot are also the good outside shooters.
Comment: To clarify, when I said, "Defensively most big men these days are just rim protectors" I was only referring to their defensive roles, not their offensive skill sets.


Why is Views ignoring nid as second argument?

Question: I create a view with two arguments: Taxonomy ID (tid) and Node NID (nid). I leave the default settings for tid and set a default argument for nid to a fixed value (let's say: 1). The tid argument is configured so that all values are shown in case it is not present. This should show all nodes except the one with NID 1.
BUT: This only works if the NID argument is the first argument. If it's the second argument, it is excluded from the query:
Query with nid as first argument:
SELECT node.nid AS nid
FROM node node
WHERE node.nid != 1  OR node.nid IS NULL

Query with nid as second argument:
SELECT node.nid AS nid
FROM node node

I'm wondering why that is? What I want to accomplish is actually to exclude the result of one view from another. To do that, I add nid as an argument, get the nids of a different view and tell views to exclude them. That works just fine, but only if nid is the first argument. But I need to have taxonomy as the first argument and I don't understand why that excludes my nid argument.
Although in a different context, I think I had the same problem here:
https://stackoverflow.com/questions/20248929/filter-a-drupal-view-displayed-in-a-panel-by-taxonomy-term-depending-on-domain
Comment: For the record: This issue also appears in Views 7.x-3.8 and is handled in your Drupal issue [#2273267](https://www.drupal.org/node/2273267).
Answer: It seems that views ignores the second argument in case the first argument is not present, although the first argument is configured to show all values if it is not present. Setting the following PHP code as default argument for the taxonomy term solves my problem:
if (arg(0) != 'taxonomy') {
  return 'all';
} else {
  return arg(2);
}


Why doesn't the batch process start?

Question: I've created a class that extend the 'FormBase' class to create a form where I can upload a XLSX file to import into custom DB table.
To process the import I would use the 'Drupal batch process' to show to the user the progress of import.
These are the methods I wrote.
    class CommissionerImportUmpiresListForm extends FormBase {

      public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
        $form_file = $form_state->getValue('my_file', 0);
        if (isset($form_file[0]) && !empty($form_file[0])) {
          $f = File::load($form_file[0]);
          $f->setPermanent();
          $f->save();
          $this->setSheetData($this->commissioner_read_file($f->getFileURI()));
          $orig = $this->getSheetData();
          $clean = array_shift($orig);
          $this->setSheetData($orig);
          $operations = [];
          $c = count($this->getSheetData());
          foreach ($this->getSheetData() as $row) {
            $operations[] = [
              ['Drupal\commissioner\Form\CommissionerImportUmpiresListForm', 'batch_run'],
              [$row, $c],
            ];
          }

          $batch = [
            'title' => t('Importing the umpires list...'),
            'operations' => $operations,
            'finished' => ['Drupal\commissioner\Form\CommissionerImportUmpiresListForm', 'batch_finished'],
            'init_message' => t('Importing is starting.'),
            'progress_message' => t('Processed @current out of @total.'),
            'error_message' => t('Importing has encountered an error.'),
          ];
          batch_set($batch);
          batch_process('admin/config/content/umpire_list');
        }
      }

      private function commissioner_read_file($file) {
        $sheetData = [];

        try {
          $real_path = \Drupal::service('file_system')->realpath($file);
          $inputFileType = IOFactory::identify($real_path);
          $reader = IOFactory::createReader($inputFileType);
          $spreadsheet = $reader->load($real_path);
          $sheetData = $spreadsheet->getActiveSheet()->toArray(NULL, TRUE, TRUE, TRUE);
        }
        catch (Exception $catch) {
          \Drupal::messenger()->addMessage($catch->getMessage(), \Drupal\Core\Messenger\MessengerInterface::TYPE_ERROR);
        }

        return $sheetData;
      }

      public static function batch_run($row, $count, &$context) {
        if (empty($context['sandbox'])) {
          $context['sandbox']['progress'] = 0;
          $context['sandbox']['max'] = $count;
        }

        $context['sandbox']['progress']++;
        $context['sandbox']['current_umpire'] = $row;

        // Do something with the row.
        $result = \Drupal ::database()
          ->insert('mytable')
          ->fields([
            'cognome' => $row['A'],
            'nome' => $row['B'],
            'categoria' => $row['Z'],
            'qualifica' => $row['AA'],
            'livello' => $row['AB'],
            'comitato' => $row['AC'],
            'email' => $row['T'],
            'cell' => $row['S'],
          ])->execute();

        $context['results'][] = $row;
      }

      public static function batch_finished($success, $results, $operations, $elapsed) {
        if ($success) {
          $message = \Drupal::translation()
            ->formatPlural(count($results), 'One umpire imported.', '@count umpires imported.');
        }
        else {
          $message = t('Finished with an error.');
        }

        \Drupal::messenger()->addMessage($message, \Drupal\Core\Messenger\MessengerInterface::TYPE_STATUS);
      }
    }

I tried executing the form, but after the initial XLSX reader, that created the array with the rows in the file, the batch process doesn't start.
What's wrong? Why doesn't the batch process start?
Answer: Check out the example on Batch operations. And remove batch_process() from your code. Since you are starting the batch in a form submit handler batch_process() is interrupting that. Just batch_set() and Form API takes care of the rest.

// Only needed if not inside a form _submit handler.
// Setting redirect in batch_process.
batch_process('node/1');

Why doesn't the batch process start?


Como criar sub pastas para controllers, model e view no Phalcon?

Question: Estou procurando uma forma de colocar níveis de pastas na estrutura de models, views e controllers. A estrutura que eu quero montar seria a seguinte:

Já olhei e implementei esse link mas não funcionou. O retorno do erro é o seguinte:
<code>meuApp\Controllers\SegurancaController handler class cannot be loaded
#0 [internal function]: Phalcon\Mvc\Dispatcher->_throwDispatchException('meuApp\Contr...', 2)
#1 [internal function]: Phalcon\Dispatcher->_dispatch()
#2 [internal function]: Phalcon\Dispatcher->dispatch()
#3 C:\Projetos\meuApp\Source\public\index.php(42): Phalcon\Mvc\Application->handle()
#4 {main}
</code>
Alguma sugestão de como implementar?
Comment: Não posso afirmar que este é o problema, mas geralmente em linux tudo é case-sensitive, talvez o Phalcon também seja case-sensitive para facilitar a portabilidade entre linux, mac e linux.
Comment: @GuilhermeNascimento, desconfiei disto, mas coloquei tudo em letras minúsculas, somente a primeira maiúscula e nada surtiu efeito...
Comment: Pode ser o namspace que esta errado, poste o seu routes, porque pelo nome `meuApp\Controllers\SegurancaController` parece estar bem errado :/
Comment: @GuilhermeNascimento realmente tinha erro nas rotas e nos nomes... acabei de ajustar, e parou o erro! obrigada!
Comment: Imaginei pelos nomes, que bom.
Answer: Corrigido as rotas o problema foi resolvido.
Os nomas das rotas não estavam compatíveis com o arquivo router.php


Consistency of $f( x| \theta ) = \exp(-(x- \theta ))$

Question:
Prove that the second smallest observation in a random sample of size
n from following pdf is consistent estimator of $ \theta $
$$   f( x| \theta  ) = \exp(-(x- \theta )) , \qquad x >  \theta   $$

I just need a hint on how to start this question, because I dont have any idea on how to and where to start on this.
With the hints provided, I tried it further:
$P( |X_{(2)} - \theta | > \ e  ) <  \dfrac{\operatorname{Var}(X_{(2)})}{\ e^{2}}$  is the required condition for consistency
Using order statistics, the pdf of $\ X_{(2)}  =  \dfrac{n(n-1)[1- \ exp(-(x- \theta ))]\ exp(-(x- \theta ))^{n-1}}{2}$
Now I need to find the $\operatorname{Var}(X_{(2)})$
Which I am struck at, need a little assistance!
Comment: You could start with the definition of consistent estimator.  The second smallest observation is greater than the smallest observation which in turn is greater than $\theta$ so both would be biased upwards and the second smallest is more biased; but you need to show that this does not matter if they get close enough to $\theta$ (as required by the definition of consistent estimator) as the sample size increases.
Comment: Also note that the event $|X_{(2)}-\theta|>\epsilon$ is the same event that at most one of the $n$ observations are smaller than $\theta+\epsilon$ so this gives you a way of deriving an expression for the corresponding probability.  Then take the limit.
Comment: Maybe one more hint will help you think about this effectively: show that for *any* whole number $r,$ the $r^\text{th}$ smallest observation is a consistent estimator of $\theta.$ In fact, see whether you can prove this for any location-family distribution whose support is bounded below. The generality of this statement might force you to think in terms of the concepts rather than just applying theorems or formulas.
Comment: Please add the [tag:self-study] tag & read its
[wiki](https://stats.stackexchange.com/tags/self-study/info).
Answer: Apply the definitions.
An estimator is a definite mathematical rule $t$ to compute a value given any finite dataset $(x_1,x_2,\ldots, x_n).$
When datasets are obtained by sampling a distribution $F,$ they produce independent and identically distributed random samples $(X_1,X_2,\ldots, X_n)$ for any $n\ge 1.$
Consider a family of distributions $\mathfrak F.$  Let $\theta$ be some property of these distributions.  All that means is for any $F\in\mathfrak F,$ $\theta(F)$ is a definite number.
An estimator $t$ is consistent at $F$ for a property $\theta$ when $t(X_1,X_2,\ldots,X_n)$ converges to $\theta$ in probability.  (This means the chance that $t(X_1,\ldots, X_n)$ differs from $\theta$ by any arbitrarily small but positive amount will eventually approach zero as $n$ grows large.)
An estimator $t$ is consistent at the family $\mathfrak F$ for a property $\theta$ when it is consistent at all $F\in\mathfrak F$ for $\theta.$
This all means you can employ a consistent estimator to obtain a reasonable guess of the value of $\theta$ even when you don't know which $F\in\mathfrak{F}$ is generating the samples.
Reformulate the question.
Suppose every $F\in\mathfrak F$ has a greatest lower bound.  A lower bound  is some finite number $\theta(F)$ (depending perhaps on $F$) for which $\Pr(X \le \theta(F)) = 0$ when $X$ has $F$ for its distribution.  $\theta$ is a greatest lower bound when, in addition to being a lower bound, it's always the case that $\Pr(X \ge \theta(F)) \gt 0.$
The exponential family in the question is a good example of this condition: it (implicitly) assigns zero probability to any values less than $\theta$ while for any $x\gt \theta$ the chance it assigns to values less than or equal to $x$ is given by $1-\exp(\theta-x),$ which is positive.
Here is the essence of the problem:

In any sample $\mathbf X = (X_1,\ldots, X_n),$ let $t_r(\mathbf X)$ be the $r^\text{th}$ smallest value among the $X_i$ (where $r$ is any fixed whole number).  Prove that $t_r$ consistently estimates the greatest lower bound $\theta.$

The solution follows immediately.
According to the definitions, we need to show that for any $F\in\mathfrak F,$ the $r^\text{th}$ smallest value in a sample of size $n$ is highly likely to be very close to the greatest lower bound $\theta(F).$
The idea should now be clear: by choosing $n$ very large, $r$ will eventually be smaller than any specified fraction of $n,$ say $n\delta.$  When $\delta$ is tiny, the $n\delta$ quantile of $F$ (no matter what $F$ might be) must be close to the greatest lower bound $\theta(F).$  Thus, the $r^\text{th}$ smallest value of a sample consistently estimates $\theta,$ QED.

If you need to see the details, here they are spelled out.
Let $\epsilon \gt 0$ indicate just how close you want $t_r$ to get to $\theta.$  Let $n$ be any sufficiently large possible sample size (so we may assume $n\ge r$).  Define $$p(\epsilon; n, r, F) = F(\theta(F)+\epsilon).$$  This is relevant because $q=1-p$ is the chance that any single value drawn from $F$ exceeds $\theta(F)+\epsilon.$  (For convenience I will drop the "$(\epsilon;n,r,F)$" after $p$ and $q.$)
Because $\theta$ is a greatest lower bound, $p \gt 0$ and therefore $q \lt 1.$
Let $\mathbf{X}_n$ be a sample of size $n$ from $F.$  Consider the chance that $t_r(\mathbf{X}_n)$ is close enough to $\theta(F).$  That is, let's contemplate the chance that the $r^\text{th}$ smallest sample value does not exceed $\theta(F)+\epsilon.$  Put another way, at most $n-r$ of the sample values may exceed $\theta(F)+\epsilon.$
We can estimate this chance.
Each of the $X_i$ individually has a chance $q$ to exceed the threshold (because they all have $F$ for their distribution). And since the $X_i$ are independent, the chance that $n-r$ or fewer of them are this large is given by the Binomial$(n,q)$ distribution evaluated at $n-r.$
We know the mean of this Binomial distribution is $nq$ and its variance is $nq(1-q).$  Thus, $n-r$ differs from the Binomial mean by
$$\frac{(n-r) - nq}{\sqrt{nq(1-q)}} = \sqrt{n}\frac{(1-q) - r/n}{\sqrt{q(1-q)}}$$
standard deviations.  Chebyshev's Inequality asserts the chance of a deviation from the mean of this magnitude (or greater) can be no larger than the reciprocal square of this value,
$$\begin{aligned}
\Pr(t_r(\mathbf{X}_n)\le\theta(F)+\epsilon) &\le \left(\sqrt{n}\frac{(1-q) - r/n}{\sqrt{q(1-q)}}\right)^{-2} \\
&= \frac{1}{n}\frac{q(1-q)}{(1-q-r/n)^2} \\
&\le \frac{1}{n}\frac{q}{1-q}\left[1 + \frac{2}{1-q}\right].
\end{aligned}$$
Clearly, no matter what $0\lt q\lt 1$ might be and no matter how large $r$ might be, the limiting value of this expression as $n$ grows large is zero.
Obviously there is no chance that $t_r(\mathbf{X}_n)$ is less than $\theta(F),$ because this estimator always equals one of the $X_i$ and since $\theta$ is a lower bound, none of the $X_i$ have any chance of being this small.  We have thereby shown that as $n$ grows large, $t_r$ is squeezed between $\theta(F)$ and $\theta(F)+\epsilon$ with arbitrarily high probability, no matter how small (but positive) $\epsilon$ might be.
This completes the proof that $t_r(\mathbf{X}_n)$ converges to $\theta(F)$ in probability for any $F\in\mathfrak F,$ and that's what it means for $t_r$ to be a consistent estimator.
Comment: Practice and reflect.  Aim to answer homework questions and exercises by recognizing and applying concepts.  Don't apply any formulas you couldn't sit down and derive on the spot.  (And do that: every time you use a new formula, re-derive it until you can do that instantly.)  Don't be satisfied with just getting answers: return to your work from time to time and consider how you could improve on it.  Study answers produced by others.  That experience will translate to finding better solutions more quickly, whether on exams or with real-life problems.
Comment: I should also add: memorize definitions.  Once you are familiar with the definitions, your entire answer can be derived as shown in the two paragraphs below "Solution."  The rest is a matter of technique, not insight.
Comment: thank you sir , I will try to focus more concept than on just answer
Comment: I understood the solution,  but I had one doubt , that how to process such information in exam , suppose if I am in exam then how do I know I have to think like this ? Or if you could give a tip on it ( on general basis in inference)  because I am facing doubt in every third question of inference??


Regular Expression which check the number of characters

Question: I have to write a .NET Regular Expression which validates if a string is alpha-numeric and has 4 or 8 characters (nothing less, nothing more). How can I do that? I tried with ([a-zA-Z0-9]{4})|([a-zA-Z0-9]{8}) but it doesn't work.
Comment: Can you please give an example string where it fails?
Answer: You need to include start and end of line anchors otherwise it can match part of the string:
<code>^([a-zA-Z0-9]{4}|[a-zA-Z0-9]{8})$
</code>
Here's a quick example of how to use this regular expression:
<code>Regex regex = new Regex("^([a-zA-Z0-9]{4}|[a-zA-Z0-9]{8})$");
string[] tests = { "abcd", "0123", "01234567", "012345", "0123456789" };
foreach (string test in tests)
{
    Console.WriteLine("{0}: {1}", test.PadRight(10), regex.IsMatch(test));
}
</code>
Result:

abcd      : True
0123      : True
01234567  : True
012345    : False
0123456789: False

An alternative way to write the regular expression is as follows:
<code>^(?:[a-zA-Z0-9]{4}){1,2}$
</code>
Comment: just curious, which language is this?
Answer: You should try a word boundary or beginning/end of line features. For example, you want to make a string that is alpha numeric with 4 or 8 characters and has no extra space:
<code>\b([a-zA-Z0-9]{4}|[a-zA-Z0-9]{8})\b   or the string is the entire line
^([a-zA-Z0-9]{4}|[a-zA-Z0-9]{8})$
</code>
You can shorten this using \w as a word character
<code>\b(\w{4}|\w{8})\b
^(\w{4}|\w{8})$
</code>
Since you're in .NET, don't forget to escape the backslashes when building the regex pattern (if it's enclosed in quotes).
Also, you do not need parentheses around each 4 or 8 character (but you do need it around the alteration) because the alteration pipe (vertical bar) has the lowest precedence.


Two version of "it.next()" + "it.nextIndex()" but in difference order, why result is different

Question: I'm trying to learn the ListIterator interface. I have came up with two version of the code,
List<Integer> list1 = new LinkedList<>(Arrays.asList(11,22,33,44));

ListIterator<Integer> it = list1.listIterator();

while (it.hasNext()){

    //version 1
    System.out.println("value: " + it.next() + " index: " + it.nextIndex());

    //version 2
    System.out.println("index: " + it.nextIndex() + " value: " + it.next());
}

Result of version 1:
value: 11 index: 1
value: 22 index: 2
value: 33 index: 3
value: 44 index: 4

Result of version 2:
index: 0 value: 11
index: 1 value: 22
index: 2 value: 33
index: 3 value: 44

I was expecting the result to be the same, but obviously they are not. Could someone please tell me why?
Comment: Why doesn't ```nextIndex``` increase the index ?
Answer: When calling it.next() first, it.nextIndex() will return the index of the element after it.next()s result, since it.next() will return the value at the current index and then subsequently increment the index.
Visual example:

it.next() first:
      v
index 0  1  2  3
value 11 22 33 44

call it.next() -> returns 11, increments index by 1

         v
index 0  1  2  3
value 11 22 33 44

call it.nextIndex() -> returns 1

it.nextIndex() first:
      v
index 0  1  2  3
value 11 22 33 44

call it.nextIndex() -> returns 0

      v
index 0  1  2  3
value 11 22 33 44

call it.nextIndex() -> returns 11, increments index by 1

         v
index 0  1  2  3
value 11 22 33 44

Comment: Why doesn't ```nextIndex``` increase the index ?
Comment: @DachuanZhao Because sometimes you want the next index without iterating. https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/ListIterator.html#nextIndex()
Answer: The string concatenation expressions are evaluated from left to right. This means in
"value: " + it.next() + " index: " + it.nextIndex()

nextIndex() is called after next() is called, in
"index: " + it.nextIndex() + " value: " + it.next()

it's the other way round.
Since next() moves the position of the iterator, the value returned by nextIndex() is different in both cases.


closure-compiler-js and grunt

Question: Tl;dr: I want to use npm instead of java when compiling my JS with closure compiler.
Hi all,
So apparently, closure compiler is getting rid of the dependency to Java and instead use JS (https://github.com/google/closure-compiler-js).
My question to you guys and gals is if there is any way of using Grunt for this, or if I need to use Gulp as a build system? Currently they do not mention it on the link i pasted above, and I haven't seen anything about it elsewhere.
I am aware that the version that is dependent on Java can use grunt, but i would rather not to have to install Java (there are multiple developers using C#.NET 4.6 in this project, and I think they are all allergic to Java because they all are hissing when i mention it).
Comment: I added a comment to the thread that was referenced to in that page. Thanks!
Answer: Closure-compiler does not plan to remove the java version. The JS version is simply another option. It doesn't require java, but is also a bit slower on large code bases. It also doesn't expose nearly as many options currently.
You can use the java version via NPM - https://www.npmjs.com/package/google-closure-compiler and it does have a grunt option.
There isn't a grunt option for the JS version because nobody has created one yet. The maintainers will most likely accept a pull request that adds grunt support if it is well written.
In the mean time, the java version still has a grunt option.
Comment: I am marking this answer as solution as it answers my question.
Thank you for the response!

closure-compiler-js and grunt


Django formsets

Question: I'm making a survey site with django. I am pretty newbie with django so I apologize in advance if I can not explain well. My question focuses on the following models:
class SurveyType(models.Model):

    name = models.CharField(max_length=200)

    def __unicode__(self):
        return self.name

class Question(models.Model):

    ANSWERTYPE_CHOICES = (
        (u'T', u'Text'),
        (u'R', u'Range'),
        (u'M', u'Media'),
    )

    question = models.CharField(max_length=200)

    surveytype = models.ForeignKey(SurveyType)

    answertype = models.CharField(max_length=1, choices=ANSWERTYPE_CHOICES)

    order = models.IntegerField(default=0)

    def __unicode__(self):
        return self.question

class Survey(models.Model):

    course = models.ForeignKey(Course)

    surveytype = models.ForeignKey(SurveyType)

    def __unicode__(self):
        return u"%s %s" % (self.course, self.surveytype)

class Answer(models.Model):

    answer = models.CharField(max_length=400)

    survey = models.ForeignKey(Survey)

    question = models.ForeignKey(Question)

    def __unicode__(self):
        return self.answer

Django receives survey id. With the survey id it gets the surveytype and shows questions that must be displayed.
def survey(request, survey_id):
    survey_data = get_object_or_404(Survey, pk=survey_id)
    survey_type = survey_data.surveytype
    questions = Question.objects.all().filter(surveytype = survey_type).order_by('order')

I have read the django documentation about formsets but I don't understand what I have to write in forms.py, so I can't call the form in views.py to render de form in the template that shows the questions and write the answers in the answer model.
Thanks in advance and sorry for my english.
Answer: Solved using modelforms and a foor loop.
Models.py
class Question(models.Model):
    question = models.CharField(max_length=200)
    surveytype = models.ForeignKey(SurveyType)
    answertype = models.ForeignKey(ContentType,
    limit_choices_to = Q(name='text answer', app_label='surveys')| \
    Q(name='media answer', app_label='surveys')| \
    Q(name='range answer', app_label='surveys'))

class RangeAnswer(models.Model):
    answer = models.IntegerField(max_length=1, choices=CHOICES_RANGE, default=0)
    def __unicode__(self):
        return u'%s'%(self.answer)

class TextAnswer(models.Model):
    answer= models.CharField(max_length=200)
    def __unicode__(self):
        return u'%s'%(self.answer)

class MediaAnswer(models.Model):
    answer= models.ForeignKey(Media)
    def __unicode__(self):
        return u'%s'%(self.answer)

Forms.py
class RangeAnswerForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(RangeAnswerForm, self).__init__(*args, **kwargs)
        self.fields['answer'].label = "Mi valoración"
    class Meta:
        model = RangeAnswer
        widgets = {
            'answer': forms.RadioSelect(renderer=RadioRenderer)
        }
RangeAnswer.form = RangeAnswerForm

class MediaAnswerForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MediaAnswerForm, self).__init__(*args, **kwargs)
        self.fields['answer'].label = "Medio"
    class Meta:
        model = MediaAnswer
MediaAnswer.form= MediaAnswerForm

class TextAnswerForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(TextAnswerForm, self).__init__(*args, **kwargs)
        self.fields['answer'].label = "Respuesta"
    class Meta:
        model = TextAnswer
TextAnswer.form = TextAnswerForm

Views.py
for q in questions :
    q.form = q.answertype.model_class().form(prefix="%s"%q.id)

Answer: Have you import the form to your views.py?
After that you just have to create a view that will pass the form to a template.
For example in the views.py
def your_form(request):
    form = RegisterForm()
    return render_to_response('your_template.html', {'form': form}, RequestContext(request))

and then in your template you can render the form simply by writing
{{ form }}

Comment: Yes, but the problem is that I don't know what to write in forms.py. Django documentation shows how to work with forms that use one or two models, not four :S. The problem I have is to create the form.py

Django formsets


Can someone shed light on linear vs. nonlinear mixed-effects?

Question: I am about to dive into learning R and my learning project will entail applying mixed- or random-effects regression to a dataset in order to develop a predictive equation.  I share the concern of the writer in this post
How to choose nlme or lme4 R library for mixed effects models? in wondering whether NLME or LME4 is the better package to familiarize myself with.  A more basic question is:  what's the difference between linear and nonlinear mixed-effects modeling?
For background, I applied M-E modeling in my MS research (in MATLAB, not R), so I'm familiar with how fixed vs. random variables are treated.  But I'm uncertain whether the work I did was considered linear or nonlinear M-E.  Is it simply the functional form of the equation used, or something else?
Comment: I can elaborate on the work I did in my MS thesis if needed, also.
Answer: There are several distinctions between linear and nonlinear regression models, but the primary mathematical one is that linear models are linear in the parameters, whereas nonlinear models are nonlinear in the parameters. Pinheiro and Bates (2000, pp. 284-285), authors of the nlme R package, elegantly described the more substantive considerations in model selection:

When choosing a regression model to describe how a response variable varies with covariates, one always has the option of using models, such as polynomial models, that are linear in the parameters. By increasing the order of a polynomial model, one can get increasingly accurate approximations to the true, usually nonlinear, regression function, within the observed range of the data. These empirical models are based only on the observed relationship between the response and the covariates and do not include any theoretical considerations about the underlying mechanism producing the data.
  Nonlinear models, on the other hand, are often mechanistic, i.e., based on a model for the mechanism producing the response. As a consequence, the model parameters in a nonlinear model generally have a natural physical interpretation. Even when derived empirically, nonlinear models usually incorporate known, theoretical characteristics of the data, such as asymptotes and monotonicity, and in these cases, can be considered as semi-mechanistic models. A nonlinear model generally uses fewer parameters than a competitor linear model, such as a polynomial, giving a more parsimonious description of the data. Nonlinear models also provide more reliable predictions for the response variable outside the observed range of the data than, say, polynomial models would.

There are also some big differences between the nlme and lme4 packages that go beyond the linearity issue. For example, using nlme you can fit linear or nonlinear models and, for either type, specify the variance and correlation structures for within-group errors (e.g., autoregressive); lme4 can't do that. In addition, random effects can be fixed or crossed in either package, but it's much easier (and more computationally efficient) to specify and model crossed random effects in lme4.
I would advise first considering a) whether you will need a nonlinear model, and b) whether you will need to specify either the within-group variance or correlation structures. If any of these answers is yes, then you have to use nlme (given that you're sticking with R). If you work a lot with linear models that have crossed random effects, or complicated combinations of nested and crossed random effects, then lme4 is probably a better choice. You may need to learn to use both packages. I learned lme4 first and then realized I had to use nlme because I almost always work with autoregressive error structures. However, I still prefer lme4 when I analyze data from experiments with crossed factors. The good news is that a great deal of what I learned about lme4 transferred well to nlme. Either way, Pinheiro and Bates (2000) is a great reference for mixed-effects models, and I'd say it's indispensable if you're using nlme.
References
Pinheiro, J.C., & Bates, D.M. (2000). Mixed-effects models in S and S-PLUS. New York: Springer-Verlag.
Comment: This is an excellent response; thank you very much for the elaboration.  I just found another reference for that book today, and I will certainly track it down now that I know I'll need NLME.
Comment: Great Response! Your snippet of Pinheiro & Bates has me convinced I have a book to go grab from the library this evening...
Answer: For the linear-nonlinear part, see: CrossValidated article on the topic, particularly the second-ranked answer by Charlie. I don't think there are any changes when dealing with mixed effects.


Creating facets for custom contents added by CCK in apache Solr module

Question: I was unable to create Facet for a CCK field, in the sense that for a specific CCK content type i was unable to group.
This could be summarised as my problem statement
Ex. CCK Field - Article Author
Actual Result :
No Group (No of Search Records)
Expected:

Author 1 (2)
Author 2 (5)

etc....
This is my primary concern, I need to create facet for the custom content types.
Please let me know if any of you have previous experiences with implementing Apache Solr for Drupal. Also let me know your kind suggestions and feedback.
My drupal version is 6.22.
Note: Based on my googling experiment i set the CCK field type in question as text and not string but still didn't help me much.
Answer: I was finally able to get this done with good assistance from one of the module's maintainer.. This is the issue list query comprising further details and some sample code. Hope this servers of some help to anyone using solr search.
Cheers!!