Getting an error while updating core to version 8.7.0

Question: When update Drupal 8.6 to 8.7 getting the following error. Anyone help would be appreciated.
<code>TypeError: Argument 3 passed to Drupal\views\EntityViewsData::mapFieldDefinition() must implement interface Drupal\Core\Field\FieldDefinitionInterface, null given, called in /Users/punya/htdocs/un-nip/core/modules/views/src/EntityViewsData.php on line 290 in Drupal\views\EntityViewsData->mapFieldDefinition() (line 387 of core/modules/views/src/EntityViewsData.php).

Drupal\views\EntityViewsData->mapFieldDefinition('file_managed', 'type', NULL, Object, Array) (Line: 290)
Drupal\views\EntityViewsData->getViewsData() (Line: 16)
Drupal\file\FileViewsData->getViewsData() (Line: 178)
views_views_data()
call_user_func_array('views_views_data', Array) (Line: 392)
Drupal\Core\Extension\ModuleHandler->invoke('views', 'views_data') (Line: 243)
Drupal\views\ViewsData->getData() (Line: 160)
Drupal\views\ViewsData->get('node_field_data') (Line: 85)
Drupal\views\Plugin\ViewsHandlerManager->getHandler(Array, NULL) (Line: 889)
Drupal\views\Plugin\views\display\DisplayPluginBase->getHandlers('sort') (Line: 1040)
Drupal\views\ViewExecutable->_initHandler('sort', Array) (Line: 898)
Drupal\views\ViewExecutable->initHandlers() (Line: 2267)
Drupal\views\Plugin\views\display\DisplayPluginBase->preExecute() (Line: 1692)
Drupal\views\ViewExecutable->preExecute(Array) (Line: 1627)
Drupal\views\ViewExecutable->executeDisplay('page_1', Array) (Line: 77)
Drupal\views\Element\View::preRenderViewElement(Array)
call_user_func(Array, Array) (Line: 378)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array, ) (Line: 226)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 227)
Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object, Object) (Line: 117)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object)
call_user_func(Array, Object, 'kernel.view', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 156)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 693)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)
</code>
Answer: I just worked through a similar issue.  Yours may not be exactly the same, but I had to do two things. (1) Remove all old code associated with 8.6 and older versions.  Basically, instead of copying 8.7 on top of 8.6, I deleted everything except my sites directory from 8.6, and copied the 8.7 files and folders fresh.  (2) In sites/all/modules, I was using profile.  Apparently, this module is not compatible with 8.7, at least the version I am using.  Removing this folder completely allowed my site to upgrade with no further issues.  There may be other contributed modules that also have issues with 8.7.


Is reading notes without an instrument a good way to practice?

Question: As an amateur self-learner pianist, I can't take my piano with me, but I can take the sheet music books.
On my current (low) level of skill, I need substantial time to read a musical piece; for instance I cannot recognise the tone of a "distant" note instantly and I usually need to read out chords note-by-note.
I believe I should be able to recognise both single notes and chords at a single glance in order to be able to play a piece without memorising the whole of it (am I correct here?)
Hence, my idea was to start taking sheets with me all the time (instead of fantasy and s-f, of which I definitely read too many)  and read them whenever I have some time: name the notes and chords, or even clap the rhythm. I hope to become able to read the sheets more quickly, so that my speed of reading will get closer to the speed of play.
Is this method of practice commonly recognised and known to be beneficial, or shall I just stay with regular practice with the piano?
Answer: It certainly won't replace the time you need to practice with the piano, but it will definitely help. In addition it gives you create chances to build a theoretical background knowledge by analyzing the structure of the piece, the chords used and relationship of the notes.
Reading the notes and chords and even clapping or just "thinking" the rhythm is a good start. But I'd also suggest trying to determine the intervals between notes. Although you probably don't see a direct benefit of this exercise, it'll help you tremendously when trying to transcribe/memorize or analyze pieces later.
Comment: Yes, I agree that analysing the **structure** of the piece itself *(intervals! and also chord progressions, for instance)* is an important benefit of this kind of exercise, because that's what I *don't* do at all when I practice with an instrument (as I need to stay focused on the notes and the technique).
Comment: Ideally, you should also imagine yourself hitting the correct keys on the piano and hear what it sounds like in your head without your piano. Of course, this can only be achieved after much practice.
Comment: I would add that if Kos does the analysis he suggests on piano pieces he's working on (or will work on in future) it will also make his practice at the piano more efficient - because instead of perhaps playing incorrect rhythms or notes and them starting to take root in muscle memory before he corrects them, he's more likely to play the right thing, albeit slowly, first time.  Also, once he's started playing a piece, if he later reviews the music without the piano, there will be tiny twitches in the muscles as they 'practise' without the piano. All helpful!
Answer: Practicing on where finger placement is could help as well. You could create a type of mockup piano with paper so that you can practice on stretching the fingers to the chords or such since playing music is also in part of using muscle memory. However, you will not improve by only doing this and will need to practice on the actual piano so that you can get used to how hard or soft you need to press the keys and to practice with the pedal.


Execute sequence of commands in fortinet

Question: I would like to execute three commands in a fortinet firewall, the commands are:
#To enter in the config mode:
config vdom
#To select the virtual domain:
edit "name"
#To see the info I want:
get router info routing-table static

But I need to do it remotely, to do that, I try this:
ssh xx@xx "config vdom; edit "xxx"; get router info routing-table static"

When I do that, it executes only the command 1 and gives an error in the second and the third.
I tried changing the command to something like this and it executes 1 and 2, but not the third:
ssh xx@xx "config vdom edit "xxxx"; get router info routing-table static"

And I tried the same for the third one but it does not work...
Looks like it executes the commands independently and not in a sequence.
Is there a way to do that in a single command?
Answer: I did it by using paramiko in a python script.
The command to introduce in the exec_command is this one:
command = "config vdom\nedit %s\nget router info routing-table static" % (vdom)


Supremum and maximum

Question: I'm asked to tell whether the supremum and maximum of the following functions exist and to derive them when $x \in B$:
$1- B = [0, 4 \pi)~\text{and}~g(x)=\cos x$
$2- B = [0, 4 \pi)~\text{and}~g(x)=\sin^2x+\cos^2x$
For the first one, I found that $\max f(x)_{x \in B}$ doesn't exist and $\sup f(x)_{x \in B} = -\infty$. Is it correct ?
For the second one, I need help.
Thanks!
Comment: Is that $1-B$? Or is that $B$ for problem 1? What is $f(x)$? The problems say $g(x)$. Can cosine ever equal negative 2?
Comment: How did you conclude 1?
Comment: No, B for problem 1.  I meant for the answer $g(x).$
Comment: I've been doing some kind of framing
Answer: Hint: your conclusion for the first one seems absurd, since $\cos x$ takes values in $[-1,1]$. For the second, observe that $\sin^2 x + \cos^2 x = 1$.
Comment: Does this means that $\max f(x)_{x \in B} = \sup f(x)_{x \in B} = 1$ for the first one ?
Comment: The function $\cos $ reaches its maximum at e.g. $0$, so since $B$ contains $0$ maximum and supremum coincide.
Comment: For the second one, $\max g(x)_{x \in B} = \sup g(x)_{x \in B} = 1$. Is it good ?
Comment: Yes, because the function is constant.
Comment: Okay, Thanks. There's one more thing I didn't understand. How do you know that $\cos x$ takes values in $[-1,1]$?
Comment: Because of the definition of $\cos$ (and $\sin$).
Comment: Okay. For the first one, $\arg\max_{x} f(x) = 0$. Right ?

Supremum and maximum


Otimização no sql

Question: Considerando essas duas tabelas no banco de dados:
Tabela Produto:
| id  | nome      |
|-----|-----------|
| aaa | Produto A |
| bbb | Produto B |
| ccc | Produto C |

Tabela Atributos:
| id_produto | atributo | valor   |
|------------|----------|---------|
| aaa        | cor      | azul    |
| aaa        | tamanho  | M       |
| bbb        | cor      | preto   |
| bbb        | tamanho  | P       |
| ccc        | cor      | amarelo |
| ccc        | tamanho  | G       |

e a seguinte consulta SQL:
select
    p.nome,
    c.valor,
    t.valor
from
    Produto p,
    Atributos c,
    Atributos t
where
    p.id = c.id_produto and
    p.id = t.id_produto and
    c.atributo = 'cor' and
    t.atributo = 'tamanho'

Há alguma forma de fazer esse select sem duplicar a tabela atributos?
Edit #1
Resultado:
| nome      | cor     | Tamanho |
|-----------|---------|---------|
| Produto A | azul    | M       |
| Produto B | preto   | P       |
| Produto C | amarelo | G       |

Observação: Não posso alterar a estrutura das tabelas, o banco real tem diversos tipos de atributos diferentes (são gerados dinamicamente) e milhares de registros.
Comment: Você está usando letras na `primary_key`?
Comment: Está dando lentidão?
Comment: Todos os dados são recebidos via integração, e sim, pode ter letras na primary key. o ponto não é a estrutura do banco, mas sim como o select é feito
Comment: Acredito que o que você quer é transpor o resultado da tabela `atributos` para cada ocorrência do `produto`. Pesquisa sobre `pivot`
Comment: Como eu obteria esse resultado usando pivot?
Comment: Postei como resposta baseado no seu modelo de exemplo. Aplica lá no seu cenário real e confere se a molhora de performance se reflete. Acredito que sim, porque para cada 'atributo' que você quisesse incluir no resultado você teria que gerar um produto cartesiano na tabela `atributos` se seguir a abordagem atual.
Answer: É bom você verificar se compensa com relação à performance para o seu caso real, mas para o exemplo apresentado seria o seguinte:
SELECT NOME,
       COR,
       TAMANHO
FROM (
    SELECT
        P.NOME AS NOME,
        A.ATRIBUTO AS ATRIBUTO ,
        A.VALOR AS VALOR
    FROM PRODUTO P
        JOIN ATRIBUTOS A ON A.ID_PRODUTO = P.ID_PRODUTO ) AS FONTE
        PIVOT ( MIN(VALOR) FOR ATRIBUTO IN (COR, TAMANHO)) AS PVT

No caso do seu snipet de exemplo, executando as consultas nas duas abordagens a primeira (cruzando a tabela) custa 71% enquanto a segunda forma, 29%, ou seja, aproximadamente 1 /3 do esforço. Acredito que o mesmo se reflita para você no caso real, mas não deixe de mensurar.
Answer: Não, pois são duas linhas diferentes sendo buscadas.
A melhor solução aqui seria você refazer as tabelas, evitando a comparação de
strings dos atributos (o que mesmo com as strings indexadas, seria mais lento do que a declaração do atributo direto no tipo):
Tabela Produto:
| id  | nome      |
|-----|-----------|
| aaa | Produto A |
| bbb | Produto B |
| ccc | Produto C |

Tabela Atributos:
| id_produto | tamanho | cor     |
|------------|---------|---------|
| aaa        | M       | azul    |
| bbb        | P       | preto   |
| ccc        | G       | amarelo |

Comment: Não posso alterar a estrutura do banco, esses atributos são gerados dinamicamente, e podem não ser os mesmos para diferentes produtos
Comment: Qualquer outra solução também fará a tabela aparecer 2x na consulta. Mas o mais importante é: Qual o principal motivo por trás disso? Tem como adicionar um `EXPLAIN` para ver se existe um motivo real de otimização?
Comment: O custo dessa consulta está em 76364714160, estou usando uma representação mais simplificada aqui
Comment: Então você precisa remodelar o seu banco de dados, seja adicionando um novo índice ou pedindo o remodelamento dele inteiro. Otimizações em query no geral devem ser feitas em casos bem específicos - e como nesse caso está procurando no BD inteiro, não há nada que vc possa fazer
Answer: Podes fazer fazer uma cláusula with da atributos por id e casa um dos atributos da tabela atributo e depois cruzar com a produto.
 Utiliza o hint de performance " Materialize" para otimizar a performance. Podes ativar o parelismo também.
Assim não duplicas informações.
Se for preciso tento explicar melhor
Comment: Seria interessante você incluir a query mencionada em sua resposta
Answer: Segue um exemplo com Pivot, veja se serve para seu caso:
Script Pivot:
SELECT
    p.nome,
    p.cor,
    p.tamanho

FROM
    (
    select
        p.nome,
        a.atributo,
        a.valor
    from #produto p
    inner join #atributos a on p.id = a.id_produto
    group by p.nome, a.atributo, a.valor
    ) as x
 PIVOT (max(valor)
FOR atributo IN ([cor],[tamanho]))P
ORDER BY 1;

Resultado
**nome | cor | tamanho**

Produto A | azul |  M

Produto B | preto | P

Produto C | amarelo |   G

Script para criação do banco (SQL Server):
create table #produto(
    id varchar(50) primary key,
    nome varchar(50)
);

create table #atributos(
    id_produto varchar(50) references #produto(id),
    atributo varchar(50) not null,
    valor varchar(50) not null
);

insert into #produto values
('aaa', 'Produto A'),
('bbb', 'Produto B'),
('ccc', 'Produto C')

insert into #atributos values
('aaa', 'cor', 'azul'),
('aaa', 'tamanho', 'M'),
('bbb', 'cor', 'preto'),
('bbb', 'tamanho', 'P'),
('ccc', 'cor', 'amarelo'),
('ccc', 'tamanho', 'G')

Otimização no sql


Standard deviation of assets?

Question: Let $E(R)_X$ denote the expected return of asset $X$.
Given a market with only 3 assets; $A$, $B$ and $C$, the following three things can happen at the next timepoint:
With probability $ p = 0.5$: $$E(R)_A = 0.4, E(R)_B = 0.02, E(R)_C = 0.3$$
With probability $p = 0.4$: $$E(R)_A = 0.2, E(R)_B = 0.02, E(R)_C = 0.25$$
With probability $p = 0.1$: $$E(R)_A = 0.1, E(R)_B = 0.02, E(R)_C = 0.15$$
Now, I'm trying to find the standard deviation for each asset.
Hence, I've found the expected return for each asset, via the following (for example,  asset $A$): $$E(R)_A = 0.5(0.4) + 0.4(0.2) + 0.1(0.1) = 0.29$$
Now, how do I find the standard deviation?
Do I simply do: $$ \sigma = \sqrt{\frac{(0.4-0.29)^2 + (0.2-0.29)^2 + (0.1-0.29)^2}{3}}$$
or do I need to somehow incorporate the probabilities in to this formula?
Answer: You need to incorporate the probabilities so
$$\sigma = \sqrt{0.5(0.4-0.29)^2 + 0.4(0.2-0.29)^2 + 0.1(0.1-0.29)^2}$$
This is also
$$\sigma = \sqrt{0.5(0.4)^2 + 0.4(0.2)^2 + 0.1(0.1)^2 -0.29^2}$$
Answer:
or do I need to somehow incorporate the probabilities in to this formula?

Yes,  You do need.

Standard deviation of assets?


How to read a text file containing strings into an array in Fortran

Question: I'm trying to read a text file into an associative array. For example, 'text.txt' contains
1. ABC
2. XYZ

I'd like to read this text file and print them out such such Array[0] is 1. ABC and Array[1] is 2. XYZ
I have 6 lines of input in total!
Here is what I have right now
program readText
OPEN(1,FILE='text.txt')
    READ(1, *) A ,B, C, D, E, F
    WRITE (*, *) A,B,C,D, E ,F
CLOSE(1)
end program readText

After this i get
Error termination. Backtrace:
#0  0x10bde99ac
#1  0x10bdea645
#2  0x10bdeadd9
#3  0x10bfb3ecb
#4  0x10bfacab6
#5  0x10bfae509
#6  0x10bdddc82
#7  0x10bddde78

Hence, i am not even printing the text file to the screen. After this, I'd like to assign them into an array and print the array. Please let me know what I could do to solve this problem. Thanks!
Comment: BTW: https://people.sc.fsu.edu/~jburkardt/f_src/f_src.html Secret tip ;)
Comment: Did you try good ol google ? And BTW which kind of fortran...https://www.math.fsu.edu/~dmandel/Fortran/ReadingArrayData.pdf or https://web.stanford.edu/class/me200c/tutorial_77/15_files.html
Comment: That was the first hit in "fortran read file in array" :D
Comment: @ThomasLudewig Thanks for your reply! I will look at them. and Fortran90!
Answer: Let me provide you an example where the content of the text file is written into a dynamic character array. If you are using FORTRAN then I highly recommend you to use explicit variable declaration. This can be forced by the command
implicit none

Otherwise you have to care about the implicit variable definition of FORTRAN, which can be found here:

Variables beginning with I .. N are INTEGER
  Variables beginning with other letters are REAL

Extending your input file text.txt to 6 lines:
1. ABC
2. XYZ
3. FOO
4. BAR
5. BYE
6. CKE

Please use this program to create and fill the character array as well as to print it to standard output:
program readText
implicit none

integer :: FID = 1
character*256 :: CTMP

! 1. Assuming that no line of text.txt contains more than 256 characters
character*256, allocatable :: MY_ARRAY(:)
integer :: I = 0, IERR = 0, NUM_LINES = 0

open(unit=FID,file='text.txt')

! 2. Get number of lines
do while (IERR == 0)
  NUM_LINES = NUM_LINES + 1
  read(FID,*,iostat=IERR) CTMP
end do
NUM_LINES = NUM_LINES - 1
write(*,'(A,I0)') "Number of lines = ", NUM_LINES

! 3. Allocate array of strings
allocate(MY_ARRAY(NUM_LINES))

! 4. Read the file content
rewind(FID)
do I = 1, NUM_LINES
  read(FID,'(A)') MY_ARRAY(I)
end do

! 5. Print array to standard output
do I = 1,size(MY_ARRAY,1)
  write(*,*) trim(MY_ARRAY(I))
end do

deallocate(MY_ARRAY)
close(FID)

end program readText

The output looks like this:
Number of lines = 6
 1. ABC
 2. XYZ
 3. FOO
 4. BAR
 5. BYE
 6. CKE

Hope it helps.


Is this a subtlety in the icing rule?

Question: I feel like I have a good grasp of hybrid icing in the NHL, but every couple of games I notice what looks to be a missed icing call.

The defensive team gains possession of the puck in their own zone.
Both teams immediately begin changing some players (benches are on each team's defensive side of the rink), as one defensive player slowly carries the puck into the neutral zone.
Two opposing defensemen -- slowly retreating, anticipating a trip to the bench -- have left a small lane for the player to carry the puck just past the center line, but the defensive player does not take it.
While between his team's blue line and the center line, the defensive player clears the puck past the opposing defensemen to the opposing goal line, but not directly at the goal. The puck leaves his stick at least 3 feet before the center line.
The opposing team will clearly be the next to touch the puck.
All skaters are now changing or have just come onto the ice. Fresh opposing defensemen skate back to their goal to retrieve the puck.
The opposing goalie may or may not come out to play the puck, but it was apparent before this fact that icing would not be called.

Since the puck crosses the center line and goal line, and no players touch the puck before it crosses the goal line, I always expect an icing call. The body language of the players on the ice indicates that they know it won't be called for icing, so the goalie's choice to come out and play it does not seem to be a factor.
Is icing called off when both teams are substituting, even if the cleared puck meets all criteria of an icing?
Otherwise, are the officials missing an occasional icing call, or do they allow the puck to be released less than some distance (like 5 feet) behind the center line when possession is clearly being exchanged for a full change? The defensive player is trending toward his bench as he clears it, so he knows it won't be called. I'm wondering if this has something to do with bench location, as I only see this play when the bench is on the defense's side.
Answer: To be clear: player substitution does not affect any determination of icing. Neither does the location of the bench.
In the situations you are describing, it is most likely that the official does not have a clear enough view of the location of the release of the puck to make a sound determination of icing, so he lets play continue.
Keep in mind, what you see is going to be very different from what the official sees. From a broadcast camera angle, or line of sight from the stands, it might look like the puck is leaving the offensive defenseman's stick 3 feet from the center line. To an official, who's likely in motion, avoiding collisions with players, and looking from a much lower angle, things might not be so obvious.
While the rule specifies that "gaining the line" is achieved by the puck, not the player's skate, I have observed that officials generally give the benefit of non-icing if it appears that the player is making effort to gain the line with body position as much as with the puck itself.
See NHL Rule 81 or USA Hockey Rule 624.
Conversely, a determination of icing DOES affect player substitution: if icing is called, the violating team is not allowed to make any player substitutions prior to the ensuing faceoff.

Is this a subtlety in the icing rule?


Submit form as anonymous user

Question: Case:
Anonymous user visits the website, fills in a form and wants to submit it.
As you can see it doesn't differ with the creaton of an entity as if I am logged in.
<code>   // Enlist a volunteer
           $scope.enlist = function () {

           $scope.isSaving = true;
           myEntity.save($scope.volunteer, onSaveSuccess, onSaveError); <-- same method
      };
</code>
The thing is I cannot reach the Restfull Service because it is somehow binded to an authentication.
When submitting the form, I get the following:

POST [XHR] http://localhost:3000/api/myentity [HTTP/1.1 401 Unauthorized 11ms]

Followed by an redirect to the sign in page.
Is there a way to reach the rest endpoint (i.e. save) as an anonymous user?
Answer: Look at the SecurityConfiguration class and unprotect the URL for your entity
<code>   .antMatchers("/api/myentity").permitAll()
</code>
Comment: Already tried that, but somehow Springboot keeps its settings.
Comment: Please note that the order of antMatchers is important

Submit form as anonymous user


Creating fuzzy values for binary data

Question: I am doing a logistic regression where my dependent variable is whether or not a person owns a particular product.
Among the variables in the model is an indicator of marital status, 1 for married, 0 for not married. This is reliable data taken directly from an application the client filled out, for example. In many cases, the data is missing (maybe the person never filled out an application) but there is a second data source which is somewhat accurate, but not completely so. Would it make sense to fill in the missing values  - not with 0 or 1, but something in between? Like if they are probably married, based on the second data source, I give them 0.8 or else a 0.2 if they probably are not married.
Comment: Welcome to our site!  Your statement shows you can be rusty at something and still ask a good question. :-)  I would suggest making your question a little more open-ended, though (and to that end I have attached the [tag:data-imputation] tag): rather than asking our opinion of a particular procedure that comes to mind, why not ask for suggestions about how to deal with your missing data problem?  That in turn suggests you might want to provide some additional information about the *purpose* of your analysis.
Comment: Do you have any measure on the degree of inaccuracy of your second file?
Comment: I have not done it yet, but I could look at how frequently the two sources agree, when there is data from both. I just want to be sure that it is a reasonable thing to do.
Answer: I have never seen this done, and I doubt other people have either. One usually gets informed answers on this site within a couple of hours of posting something. It's been a day, and no joy.
My thinking is this: if you want to tell the model that some values are more trustworthy than others, use weights. If you downweight values where you doubt the accuracy of the data, the model will basically accept a worse fit at that point -- which is what you want.
Example: suppose you have a very "married" set of covariates for someone coded "unmarried" in the dodgy data set. Without weights, the fitting algorithm could distort the parameter estimates in order to get some kind of fit. With weights, the algorithm need not try so hard. In effect, it lets you have bigger residuals when you don't trust the data.
If you want to go with your first idea of substituting data with probabilities, I would iterate: estimate probabilities that someone is married or not, then fit the model with my best guesses, then go back and adjust the estimates. This is an EM approach. So, I would not replace 0's and 1's with 0.8 and 0.2 in the fit. I would use 1 and 0 according as the probabilities were less than or greater than 0.5 - but then I would go back and adjust the probabilities on the basis of lack of fit at those points.
If you look at what happens in a logistic regression model, the math involved really expects that the data are going to be 0's or 1's. I think you want to stick with that. My advice boils down to using weights or estimating marital status from the rest of the data.
Comment: Thanks Placidia. When I come back to this at the beginning of next week I will be pressed for time as well as stretching my brain cells back to my graduate level econometrics, so I want to keep this as simple (yet as accurate) as possible. I think after poking at the data I will either count the less trusted data the same as the good data or just not use it. In fact, as I sit here right now it is not obvious what sign would be on the coefficient for marital status. Maybe I will get lucky and it will be not significant.
Comment: That's probably the safest way to go.

Creating fuzzy values for binary data


Why are Drupal hosting providers using Solr 3.x instead of 4.x or 5.x?

Question: As of April 2016,

Acquia offers Solr 3.5.
Pantheon offers Solr 3.6.
Platform.sh offers Solr 3.6 by default, with 4.10 as an option.

The current release of Solr is 5.5.0 (2016-2-20).
3.5 was released on November 25, 2011.
3.6 was released on April 11, 2012.
4.10 had its final release on October 14, 2015 (but it was first released on September 2, 2014).
Is there a reason to stick with 3.x vs. Solr 4 or 5?  Search API Solr supports all three versions.  Normally I would just use the latest version, but when major hosts that specialize in Drupal are on a version that is more than three years old, it makes me wonder.
Answer: It probably comes down to LTS and backwards compatibility, though you'd have to ask each organisation for their specific motivation.
Solr 5 is not backwards compatible with 4, 4 is not BC with 3. So if there are users on legacy systems using older versions, upgrading would require all customers to upgrade their schema/integration too. Installing newer versions on new servers might mean customers can't migrate from one server to another, might break the generic model of system deployment, etc, etc.
Some companies will offer newer versions, but you'll probably find the older versions are always available too, otherwise the company is likely to have at least a few pretty irate customers when they switch it off.
Basically, if you tell someone that you're going to support a version of software for the foreseeable future, you have to do that. It's why so many shared hosting companies support obsolete versions of PHP - because the people hosting there have no intention of upgrading their code, but their sites still need to work.
There's no Drupal-specific reason (that I know of) to choose one version of Solr over another, as long as the contrib module you're using has support for that version.
Answer: There is one reason you would need newer Solr.
Older versions cannot parse Japanese because Japanese does not have spaces between words, so there is an open source parser called Kuromoji that can be installed to make Solr usable with Japanese content. Newer Solr versions like 5 and 6 include it in the Lucene project, but older versions require that you install it separately.
Pantheon, for example, will not install Kuromoji and will not allow you to use a higher version, so if you want the option of using Chinese, Japanese, or Korean content to appeal to those markets, you will have to maintain and host your own Solr elsewhere. This will mean additional hosting and support costs, paying extra for a static IP connection to your Solr, and more time spent on paperwork and maintenance.


Uniform White Noise

Question: I found a contradiction I couldn't resolve by my self.
It's about a "Uniform White Noise".
Let ${x}_{t}$ be a "White Noise" i.i.d. Random Process:
$ \forall t \in  \mathbb{R}, \ {x}_{t} \sim U[-1, \  1] $
If we chose to go by the PSD definition of "White Noise" (Constant all over the Frequencies) we get:
$ {R}_{xx}( \tau ) = var({x}_{t}) \delta ( \tau ) $
Yet, Clearly:
$ E[{x}_{t} {x}_{t +  \tau}] \underset{ \tau = 0}{=}E[{x}_{t} {x}_{t}]= \frac{1}{3} $
Intuitively, a Process with bounded variance and values can't be "White Noise".
Please mind this is a Continuous Random Process. We don't have such problem in the Discrete case.
What am I missing here?
Either there's no such "White Noise" (Why?) or There's a good explanation (Could someone derive it Mathematically) how to get the Delta in The Variance.
Thanks.
Answer: Apparently, saying that $(x_t)$ is a continuous white noise process simply refers to the fact that $(x_t)$ is a continuous time process, that is $(x_t)$ is indexed by a continuous parameter set. That is, the sample paths of $(x_t)$ are not assumed to be continuous, and in fact may be expected to be discontinuous at every fixed point (almost surely). Indeed, consider a continuous Gaussian white noise process. Then, $E[x_s x_t]=0$, $s \neq t$, implies that $x_s$ and $x_t$ are independent, and hence the sample paths must be discontinuous at every point (almost surely). The case of "Uniform White Noise" is essentially the same.
Comment: Hello Shai. I don't care about how smooth are the paths. Continuous as I meant means t can get any real value. I want to know how to explain the contradiction between calculating the Variance using the PSD to calculating it by using the Distribution of the Variable at certain time.
Comment: By the PSD definition (DC all over the Frequencies) E[Xt Xt] = Variance * Delta -> Infinite Energy. Yet using the Uniform Distribution you get 1/3, with no Delta, Finite Energy.
Comment: No, there's a big difference. Using the delta notation means it has infinite amount of variance. A function f(x) which equals to 1 at x = 0 and zero everywhere else isn't a delta. A delta means that at zero its value is infinite. You are using Delta just like Indicator Function, Where it means something else.
Comment: I now see your point.
Comment: So probably you cannot assume $X_t \sim U[-1,1]$. Maybe the following example can help, in the setting of Gaussian white noise. If $Z_1,\ldots,Z_n$ are i.i.d. ${\rm N}(0,1)$, then their sum is ${\rm N}(0,n)$, which has mean zero but variance which tends to $\infty$.
Comment: What I mean is that probably $X_t$ can theoretically be viewed as some limit $X_t^n$ as $n \to \infty$, where each $X_t^n$ has zero mean, but variance tending to $\infty$.
Comment: That's what I'm looking for. Someone who could explain it rigorously.
Comment: At least you should now realize that there is no contradiction, since $X_t$ is not ${\rm U}[-1,1]$.
Comment: That's what I'm looking for. someone to show me why if I started from a R.V. which is U[-1 1] we get Xt which is not.
Comment: I think there is a mistake in this answer.  $E[x_s x_t]=0$, $s \neq t$ is a much weaker property than independence.  Independence requires that $P(x_t) = P(x_t | x_s)$, doesn't it?

Uniform White Noise


node title preprocess_views_view_field();

Question: I want to save the node title in a variable using: themename_preprocess_views_view_field(), becuase I want to print a the node title above the field.
But when I try to save the title with:
themename_preprocess_views_view_field() {
$variables['node_title'] = $variables['field']->original_value ->    string;
}

I get Error: Cannot access protected property Drupal\Core\Render\Markup::$string in themename_preprocess_views_view_field() (line 123 of themes/custom/themename/themename.theme).
how can I save this variable so I can print it in the views-view-field.html.twig file?
Answer: Solution: The way to do this is to add an address Field in the View as Content datasource: address in the Admin GUI.
And select Use entity field rendering.
Under REWRITE RESULTS
 Select: Override the output of this field with custom text
And in the textbox I added in my case:
{{ title }}
{{ field_address }}


Using an RSA Public Key to decrypt a string that was encrypted using RSA Private Key

Question: I know the main answer I am likely to get is why the hell would you want to do that?!
Unfortunately despite my protests I have to do it, even though I know it makes little sense.
I have functions written in .Net to decrypt using a private key, encrypt using a public key.
I also RSA sign and verify and have a reasonable understanding of how this all work I think.
I am now being sent a value that is RSA encrypted using a private key which I am supposed to derive a usable value by decrypting using the public key.
I can't seem to figure out how to do this. Am I being an idiot? Is this a normal thing to do?
I am told by the person sending me the value that this is no problem in PHP. I don't know and haven't used PHP yet. I can't find a library to do it in any of the main languages I know i.e. C++, Java, C#. The server I am working on uses .Net.
I am hoping someone might be able help me.
It would be great if there is some kind of reasonable solution besides begging them to change what they are doing.
This is my method (updated from my previous bad one as pointed out by Iridium) but when I try to decrypt the value I get an exception
"Error occurred while decoding OAEP padding."
If I use rsa.Decrypt(bytes, false) I get a bad key exception.
public static string DecryptUsingPublic(string dataEncrypted, string publicKey)
    {
        if (dataEncrypted == null) throw new ArgumentNullException("dataEncrypted");
        if (publicKey == null) throw new ArgumentNullException("publicKey");
        try
        {
            RSAParameters _publicKey = LoadRsaPublicKey(publicKey, false);
            RSACryptoServiceProvider rsa = InitRSAProvider(_publicKey);

            byte[] bytes = Convert.FromBase64String(dataEncrypted);
            byte[] decryptedBytes = rsa.Decrypt(bytes, true);

            ArrayList arrayList = new ArrayList();
            arrayList.AddRange(decryptedBytes);

           return Encoding.UTF8.GetString(decryptedBytes);
        }
        catch
        {
            return null;
        }
    }

    private static RSAParameters LoadRsaPublicKey(String publicKeyFilePath, Boolean isFile)
    {
        RSAParameters RSAKeyInfo = new RSAParameters();
        byte[] pubkey = ReadFileKey(publicKeyFilePath, "PUBLIC KEY", isFile);
        byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
        byte[] seq = new byte[15];
        // ---------  Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob  ------
        MemoryStream mem = new MemoryStream(pubkey);
        BinaryReader binr = new BinaryReader(mem);    //wrap Memory Stream with BinaryReader for easy reading
        byte bt = 0;
        ushort twobytes = 0;

        try
        {

            twobytes = binr.ReadUInt16();
            if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                binr.ReadByte();    //advance 1 byte
            else if (twobytes == 0x8230)
                binr.ReadInt16();   //advance 2 bytes
            else
                return RSAKeyInfo;

            seq = binr.ReadBytes(15);       //read the Sequence OID
            if (!CompareBytearrays(seq, SeqOID))    //make sure Sequence for OID is correct
                return RSAKeyInfo;

            twobytes = binr.ReadUInt16();
            if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
                binr.ReadByte();    //advance 1 byte
            else if (twobytes == 0x8203)
                binr.ReadInt16();   //advance 2 bytes
            else
                return RSAKeyInfo;

            bt = binr.ReadByte();
            if (bt != 0x00)     //expect null byte next
                return RSAKeyInfo;

            twobytes = binr.ReadUInt16();
            if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                binr.ReadByte();    //advance 1 byte
            else if (twobytes == 0x8230)
                binr.ReadInt16();   //advance 2 bytes
            else
                return RSAKeyInfo;

            twobytes = binr.ReadUInt16();
            byte lowbyte = 0x00;
            byte highbyte = 0x00;

            if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81)
                lowbyte = binr.ReadByte();  // read next bytes which is bytes in modulus
            else if (twobytes == 0x8202)
            {
                highbyte = binr.ReadByte(); //advance 2 bytes
                lowbyte = binr.ReadByte();
            }
            else
                return RSAKeyInfo;
            byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };   //reverse byte order since asn.1 key uses big endian order
            int modsize = BitConverter.ToInt32(modint, 0);

            byte firstbyte = binr.ReadByte();
            binr.BaseStream.Seek(-1, SeekOrigin.Current);

            if (firstbyte == 0x00)
            {   //if first byte (highest order) of modulus is zero, don't include it
                binr.ReadByte();    //skip this null byte
                modsize -= 1;   //reduce modulus buffer size by 1
            }

            byte[] modulus = binr.ReadBytes(modsize);   //read the modulus bytes

            if (binr.ReadByte() != 0x02)            //expect an Integer for the exponent data
                return RSAKeyInfo;
            int expbytes = (int)binr.ReadByte();        // should only need one byte for actual exponent data (for all useful values)
            byte[] exponent = binr.ReadBytes(expbytes);

            RSAKeyInfo.Modulus = modulus;
            RSAKeyInfo.Exponent = exponent;

            return RSAKeyInfo;
        }
        catch (Exception)
        {
            return RSAKeyInfo;
        }

        finally { binr.Close(); }
        //return RSAparams;

    }

 private static RSACryptoServiceProvider InitRSAProvider(RSAParameters rsaParam)
    {
        //
        // Initailize the CSP
        //   Supresses creation of a new key
        //
        CspParameters csp = new CspParameters();
        //csp.KeyContainerName = "RSA Test (OK to Delete)";

        const int PROV_RSA_FULL = 1;
        csp.ProviderType = PROV_RSA_FULL;

        const int AT_KEYEXCHANGE = 1;
        // const int AT_SIGNATURE = 2;
        csp.KeyNumber = AT_KEYEXCHANGE;
        //
        // Initialize the Provider
        //
        RSACryptoServiceProvider rsa =
          new RSACryptoServiceProvider(csp);
        rsa.PersistKeyInCsp = false;

        //
        // The moment of truth...
        //
        rsa.ImportParameters(rsaParam);
        return rsa;
    }

    private static int GetIntegerSize(BinaryReader binr)
    {
        byte bt = 0;
        byte lowbyte = 0x00;
        byte highbyte = 0x00;
        int count = 0;
        bt = binr.ReadByte();
        if (bt != 0x02)     //expect integer
            return 0;
        bt = binr.ReadByte();

        if (bt == 0x81)
            count = binr.ReadByte();    // data size in next byte
        else
            if (bt == 0x82)
            {
                highbyte = binr.ReadByte(); // data size in next 2 bytes
                lowbyte = binr.ReadByte();
                byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
                count = BitConverter.ToInt32(modint, 0);
            }
            else
            {
                count = bt;     // we already have the data size
            }

        while (binr.ReadByte() == 0x00)
        {   //remove high order zeros in data
            count -= 1;
        }
        binr.BaseStream.Seek(-1, SeekOrigin.Current);       //last ReadByte wasn't a removed zero, so back up a byte
        return count;
    }

    private static bool CompareBytearrays(byte[] a, byte[] b)
    {
        if (a.Length != b.Length)
            return false;
        int i = 0;
        foreach (byte c in a)
        {
            if (c != b[i])
                return false;
            i++;
        }
        return true;
    }

The two methods above InitRSAProvider and LoadRsaPublicKey were gotten out of tutorials to allow PEM keys as Strings to be used with .Net.
Comment: Say what? That is exactly what the algorithm is supposed to do. Decrypt using a private key what was encrypted using the corresponding public key. Either you are confused big time or I am! C# perfectly supports RSA :)
Comment: Okay, sorry. I should have read through my question properly. Made a total mess of this one. I have the standard decrypt with Private key, not public. If I try to decrypt the value that was encrypted using the private key with the public key I get an exception - The data to be decrypted exceeds the maximum for this modulus of 128 bytes. I've been researching a trying many things but I keep getting exceptions.
Comment: What are you referencing for "ReadFileKey"  ??
Comment: **Warning:** encryption with a private key and decryption with a public key is inherently unsafe and is not the same as signature generation / verification. OK, you have been warned, you can proceed shooting yourself in the foot now.
Comment: Sorry. Edited my question. I wrote it completely wrong. Brain starts to scramble a bit on Fridays.
Comment: What can't you figure out? You say you already have functions to decrypt using a public key.
Comment: What do LoadRsaPublicKey and InitRSAProvider do? Can you provide the code for these methods too?
Comment: Sure the code is quite long but I will add it. The keys are PEM keys got from a database as strings.
Comment: hey I have same issue tried your code , but still got Key does not exist, how exactly does you readFileKey looks, what is the format of your key?
Comment: Sorry Oscar Cabrero. This was a while back and I can't remember the precise details. I know the code in my question is wrong and didn't work. I eventually resolved it using this tutorial: codeproject.com/KB/security/PrivateEncryption.aspx and the details in the accepted answer. I regret now not posting my entire solution. I no longer have the code and definitely don't have a good enough memory to replicate it correctly without taking a bit of time. As for the key, I read that as a String from a database. I got the keys as PEM files, copied the values to the DB and read from there.
Answer: RSA is built into .NET: System.Security.Cryptography.RSA.
Encrypting using the public key and decrypting with the private key is one of the most common things people do with asymmetric algorithms, it allows anybody to send you something securely.
If you do it the other way: encrypt using the private key, and decrypt with the public key then it proves the message was sent by the holder of the private key. But because anyone presumably can get hold of the public key, people don't tend to encrypt the whole message, they instead just sign a hash of the data using the private key. Hence RSACryptoServiceProvider has Sign__ and Verify__ methods to do just that.
Still, there are Encrypt/Decrypt methods if your partner insists.
Saying that, I've found the Microsoft crypto classes a bit tricky to deal with and lacking in certain areas and much prefer the Bouncy Castle libraries.
Comment: Thought so! Updated the answer.
Comment: Sorry I am an idiot. I got my question completely backwards. I have edited it to show what I actually meant.
Comment: Thanks very much for your answer. I can't seem to get the decrypt method to work in this case. I have updated my question to show where it is going wrong. I am probably doing something silly and will mark this as the answer as soon as I figure out what it is.
Comment: Added a suggestion to try the Bouncy Castle libraries - they tend to inter-operate with the non-MS world a bit better.
Comment: Will look in to Bouncy Castle. Thanks for your suggestion.
Comment: This code example signs and verifies data:

https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rsacryptoserviceprovider.signdata?view=net-8.0
Answer: Having looked at some of the information on RSA encryption modes, it would appear that PKCS#1 v1.5 (which you're using, because you're calling Decrypt(..., false))

"...can operate on messages of length up to k - 11 octets (k is the octet length of the RSA modulus)"

(RFC 3447, emphasis mine).
Based on the error message, which indicates that your key is 128 bytes, that means that you can't perform RSA (en|de)cryption using PKCS#1 v1.5 on a message with more than 128 - 11 = 117 bytes.
Instead of encrypting your message directly using RSA, you should be using a symmetric algorithm to encrypt the body of the message, and encrypt only the symmetric encryption key using RSA. Only if your message is reasonably short (i.e. below 117 bytes for your key size) should you consider encrypting the message directly with RSA.
I have added the following, assuming that your input is Base64 encoded as you indicate in your comment below:
public string DecryptUsingPublic(string dataEncryptedBase64, string publicKey)
    {
        if (dataEncryptedBase64 == null) throw new ArgumentNullException("dataEncryptedBase64");
        if (publicKey == null) throw new ArgumentNullException("publicKey");
        try
        {
            RSAParameters _publicKey = LoadRsaPublicKey(publicKey, false);
            RSACryptoServiceProvider rsa = InitRSAProvider(_publicKey);

            byte[] bytes = Convert.FromBase64String(dataEncryptedBase64);
            byte[] decryptedBytes = rsa.Decrypt(bytes, false);

            // I assume here that the decrypted data is intended to be a
            // human-readable string, and that it was UTF8 encoded.
            return Encoding.UTF8.GetString(decryptedBytes);
        }
        catch
        {
            return null;
        }
    }

Comment: Thanks for your response. I have been reading RFC 3447 all day trying to find a solution. The main problem is that I have no control over how the  value is encrypted. Basically I am given a value i.e. value = BASE64[RSA_PRIVATE_ENCRYPT(some_text)] It has been left to me to figure out how to decrypt and use this value. I have tried lots of things but no joy. I have asked for a working example for decryption from the person sending me the value. If I get it I will post it here.
Comment: That isn't what your code snippet suggests, as you have no Base64 decoding. (You shouldn't be using Encoding.ASCII for this purpose either, as it's only 7-bit). If your input is Base64, you should be using Convert.FromBase64String(dataEncrypted) to get a byte array for use with the RSA functions.
Comment: Whilst my original answer still applies, I have added some code to my answer that may correct your problem, based on the assumption that the input is in fact Base64 encoded as you mention in your comment above.
Comment: Thanks. You are right. I was supposed to be using Base64. It was a stupid mistake made as I was trying to reverse the encrypt method. I have updated my question.
Comment: Finally got it working using your advice and source code from here http://www.codeproject.com/KB/security/PrivateEncryption.aspx
Answer: RSA is not meant to encrypt arbitrary data, even less arbitrary data length (like @Iridium already told you). The limit depends on the padding used and using the padding is very important (enough that MS won't let you call EncryptValue and DecryptValue directly).
The right way to do this is to encrypt your string using a symmetric cipher (like AES) then encrypt the secret key using the RSA public key.
The other party will be able to decrypt the secret (AES) key using the RSA private key. Then using the key decrypt your string.
I have an old (but still up to date) blog entry on the subject that includes source code (C#).
Comment: Thanks for your response. I completely agree with you. The problem is I am not encrypting the value. I have a private key and a public key. I am being sent a value that has been encrypted using the private key and now I have to figure out how to decrypt it. It may not make sense and there may not be a simple solution but I am not very experienced with this so i appreciate all comments and suggestions.
Comment: If you stuck on the **decrypting** end then you have no choice (safe or not) than doing the reverse operations to get back the data. Hopefully it will not require you to use `DecryptValue` (it should not if the other, encrypting, party use .NET) but even then there are solutions for that :) Let us know!
Comment: I dont understand this from your blog `It also make sense "security wise" because a 128 bits symmetric key is more secure than a 1024 bits asymmetric keypair (at least for RSA)`. Could you explain more about how AES is more secure than RSA ?
Comment: It's not about AES or RSA themselves (too different), it's about the key length used for both (i.e. how hard to break them). IOW it *should be* easier to break RSA 1024 than AES 128. Suggested read http://security.stackexchange.com/questions/38015/key-size-difference-between-aes-and-rsa


Why (must one) inherit from std::iterator?

Question: To my understanding, iterators are a mechanism for providing an interface for the client to observe/iterate/pass through the contents of, for example, a custom collection, without breaking the information hiding principle. STL containers have iterators of their own, so we can use for ( : ) and for_each loops on them with no problems.
My question initially was: why inherit from std::iterator? What additional functionality does it provide, in contrast to the following example:
SimpleArray.h
class SimpleArray
{
    int *arr;
    int n;
public:
    explicit SimpleArray(int = 1);
    ~SimpleArray();

    friend ostream& operator<<(ostream&, const SimpleArray&);
    friend istream& operator>>(istream&, SimpleArray&);

    // encapsulated "iterator"
    class Observer
    {
        int *p;
    public:
        Observer(int *value = nullptr) : p(value) {}
        Observer& operator++() { p++; return *this; }
        Observer operator++(int) { int *temp = p; p++; return Observer(temp); }
        bool operator==(Observer other) const { return p == other.p; }
        bool operator!=(Observer other) const { return p != other.p; }
        int& operator*() const { return *p; }
    };

    Observer begin() { return Observer(arr); }
    Observer end() { return Observer(arr + n - 1); }
};

Source.cpp
int main()
{
    SimpleArray array(5);
    cin >> array;

    for (int item : array)
    {
        cout << item << " ";
    }

    cin.ignore();
    cin.get();
}

Input
1 2 3 4 5

begin() and end() functions are public and the Observer encapsulates all the necessary operators for the loop to function. The code compiled.
Output
1 2 3 4 5

After trying the same with std::for_each
std::for_each(array.begin(), array.end(), [](int item) { cout << item << " "; });

I got some compiler errors:
C2062: type 'unknown-type' unexpected   Observer
C2938: '_Iter_cat_t<SimpleArray::Observer>' : Failed to specialize alias template
C2794: 'iterator_category': is not a member of any direct or indirect base class of 'std::iterator_traits<_InIt>'

After reading about for_each, I found out its type parameters must meet some requirements, in short - to be Iterators.
My question now is: why is this function (and many others for certain) designed in a way that enforces this criteria, if it is fairly easy to create a regular class that provides the iterating functionality?
Comment: You don't have to inherit from `std::iterator`. In fact [it has been deprecated](http://en.cppreference.com/w/cpp/iterator/iterator) and should not be used.
Comment: @PeteBecker The OP is considering writing a new iterator class for which I would say you should not use deprecated features. In your scenario you remove features from working code. Totally different scenario.
Comment: Also your `Observer` does not have all the features that [a proper iterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator) must have. Inheriting from `std::iterator` gave you some of them, but it turned out too confusing and you should just do it by hand.
Comment: See `std::iterator_traits` http://en.cppreference.com/w/cpp/iterator/iterator_traits
Comment: It's a convenience. If you prefer to write out the required typedefs yourself, go for it.
Comment: @nwp -- "deprecated" and "should not be used" are two completely different notions. "Deprecated" means "might be removed in the future". That's all. Some people have coding guidelines that say to never use deprecated features; that can result in a great deal of wheel-spinning in removing fully supported features from existing code before those changes are actually needed.
Comment: @nwp -- "it has been deprecated and should not be used" is, nevertheless, far too broad. Your correction is reasonable.
Comment: @nwp "…it has been deprecated…"-fact. "…and should not be used" I beg to disagree.
Comment: Pretty orthogonal to your question -- but in your example, if `n` is the size of the array, then your `end()` function should return `Observer(arr + n)`. `end()` normally returns a pointer "one past" the last item. As it is, a foreach loop will skip the last element -- and terrible things will happen if SimpleArray is empty.
Answer: The only thing std::iterator provides are the member types iterator_category, value_type, difference_type, pointer, and reference, which are defined from the template parameters you provide. It doesn't have any other members. You can just define these member types yourself.
The real answer is that you don't need to inherit from std::iterator at all and it doesn't give you any real advantage. As far as C++ is concerned, if it looks like an iterator, it is an iterator. You just need to make sure your iterator type follows the concepts outlined here: https://en.cppreference.com/w/cpp/named_req/Iterator
std::iterator was deprecated in C++17 because of how relatively useless it is.
Comment: _"if it looks like an iterator, it is an iterator"_ or also known as [duck typing](https://en.wikipedia.org/wiki/Duck_typing)


android native plugin seems unusable

Question: I'm fairly new to Unity development. I have followed many different tutorials regarding the use of native plugins in Unity. Those which consist in compiling .dll libraries and running them in the editor work just fine.
But compiling a .so file using android NDK and calling it in a C# script in Unity seems impossible. Even with this trival example, it always throws DllNotFoundException. The library in this example doesn't include anything else, so the problem can't be that I'm missing additionnal libraries.
I'm using Unity 2018.3.7f1, and made sure that the libraries are marked as Android compatible, as well as having a Build set for Android. My machine is Windows 10.
[Edit] : I tried to deploy it on a samsung galaxy s7. The device is 64 bits so I had to make a few changes in the Unity Editor (select IL2CPP in the player settings etc.) I understand that Unity Editor will always throw errors since it is not able to detect the Android plugin. However the result in the Editor and on the device are the same, that is an empty blue screen. I figured the DllNotfound was the issue but now I realize this may not be the case.
Answer: Are you Trying to Run in Editor? If yes it will throw an exception. Try to take Build in Mobile
or you have to add Platform dependent compilation code to run without error in Editor
<code>#if !UNITY_EDITOR
    [DllImport("native")]
    private static extern float add(float x, float y);
#endif
    void OnGUI ()
    {
        float x = 3;
        float y = 10;
#if !UNITY_EDITOR
        GUI.Label (new Rect (15, 125, 450, 100), "adding " + x  + " and " + y + " in native code equals " + add(x,y));

#endif
    }
</code>
Comment: Indeed it's in the editor that I see DllNotFoundException. However when building on mobile the message still doesn't appear... Which makes me believe that the issue is the same.
Comment: I tried building in 32 and 64 bit too to see if it made a difference. It doesn't seem to.
Comment: I tried both in editor and on device, and neither worked

android native plugin seems unusable


Multiple overlapping changelists in perforce?

Question: I've looked at this similar question but I'm still fairly lost. I have one file which I want to be a part of multiple changelists. I seem to remember that doing this involves creating multiple clients, but that's stumping me, too. I can create a client just fine, but I can't figure out how to "check out" that client and start creating a separate CL in that client, one that is independent from the CLs I have started in my original client.
Any help would be hugely appreciated!
(It's also worth mentioning that I'm working on a source control system that's forked from perforce, not exactly perforce).
Answer: One file can only be part of multiple submitted changelists if each changelist has a different revision -- e.g. if you add a file to the depot its revision #1 is in one changelist, when you edit it and submit that its revision #2 is in another changelist, and so on.  Same file, different revisions.
One file can be part of multiple pending changelists at the same time (all derived from the same revision) if each changelist is on a different client.  If you're creating different clients on one machine, make sure that each has its own unique client root, since you'll want to have unique copies of the file(s) on your local machine.  Then you don't need to do anything special to open the file; each client is independent of the others.  Just "p4 sync" and "p4 edit" the same way you did on your first client.  (Make sure to use P4CLIENT or the equivalent to specify which client you're using at any given time; P4CONFIG files make this easier by associating a P4CLIENT setting with a particular working direcotory.)  The only difference you'll see is an informational message from "p4 edit" that the file is already open by another client.  Creating changelists works the same way as it always does; run "p4 change" to create a pending change, "p4 reopen -c change" to move files around between changes.
There is also shelving, which is similar in some ways to having multiple pending changelists on different clients (except that the changelists are all stored on the server rather than in a bunch of different client workspaces) but if you happen to be using a very old version of Perforce (or something similar to it) that's probably not an option.


WordPress plugin document title parts not working

Question: I have a wordpress plugin that uses add_filter to change the title of the page.
In an empty wordpress website it just works fine. But I have two other websites where I want to use my plugin, but for some reason there it will not work at all.
function hooks() {
    if(get_query_var('car_id') != "") {
        add_action('wp_head', 'fillHead');
        add_filter('document_title_parts', 'addTitle', PHP_INT_MAX);
    }
    add_shortcode('auto', 'showCar');
}

I tried to deactivate some plugins and the theme etc. But nothing seems to work. I don't know where the title is changed. Is there a way to see what is happening in wp_head() or why this code is not executed at the right time?
EDIT
In the header.php there is a bit of code that makes the title. If I delete this part it is still not working. It will make the url as the title.
But how can i overrule this  tag in my plugin?
Comment: the second argument of add_shortcode should be hooks and not showCar
Comment: That's just fine. its the function that the shortcode will execute
Answer: Your plugin code is most likely going to run before the theme code and will run before anything is added to the hook. You will need to the code that processes the file inclusion to some other hook that runs after all of the plugins load, like after_setup_theme
This is the wordpress loading sequence?
Comment: The after_setup_theme is not working for me but thanks for the loading sequence
Answer: So I finally found a way to get it to work.
In the theme there is a header-details.php. I deleted everything between the  tags and only added the following:
<?=wp_title( '|', true, 'right' )?>

Then to the plugin I used the filter wp_title instead of document_title_parts.
It works for now but I will still have to test this on other sites


Android/iOS unlimited Apps tied to a single website subscription

Question: I have a website that provides a service that customers pay a monthly subscription fee. I have created apps for Android and iOS to connect to the subscribed account. With this subscription they can connect an unlimited number of users with android/iOS applications to the account.
If I release the App into the Market as free but customers need to register for a paid subscription for the main account on the website then will be seen as a breach of the Market T&Cs for the Play Store and the App Store?
Thanks for any help.
Answer: You should be fine - some large companies do this, examples off the top of my head are: Rdio, Economist.
You can only purchase via their website, but by linking accounts you get full functionality.
The company gets to save on 30% fees, but the app is not allowed to provide any links to your purchase workflow on your website - otherwise that will violate the terms.
This is the same for both Android and iOS.


Meaning of $x∈ℝ^d$ notation in matrix approach to regression

Question: How does one interpret the $x ∈ ℝ^d$ in the context of regression, see below
in the following context:
I understand the d refers the dimension of the x vector, but I don't get what this notation tells me. Note that I am not familiar with linear algebra, which may explain my confusion.
Answer: Mathematically, your understanding is correct, $d$ is the dimension of the vector $x$ and so $x$ exists in the real space of dimension $d$ denoted as $\mathbb{R}^d$. By real space we mean the elements of $x$ are all real numbers.
In the context of regression, consider the simple case of $d=1$. Let's say we have a linear model for a house price $y$ as a function of its size in square feet $x_1$. Then we just have the linear equation
$$
y = \theta_1 x_1 + b
$$
where $\theta_1$ and $b$ are some model parameters. Now let's say we want to add another variable, the number of bathrooms $x_2$. Then we can write
$$
y = \theta_2 x_2 + \theta_1 x_1 + b
$$
The more variables we add, the longer this equation becomes. So let's write it in matrix form instead. We can define the column vectors
$$
\mathbf{x} = \begin{bmatrix} x_1 \\ x_2 \\ ...\\x_d
\end{bmatrix}\ \in \mathbb{R}^d\ ,\
\mathbf{\theta} = \begin{bmatrix} \theta_1 \\ \theta_2 \\ ...\\ \theta_d \end{bmatrix}\ \in \mathbb{R}^d
$$
So now we can simply write the linear regression problem as
$$
y = \mathbf{\theta}^T \cdot \mathbf{x} + b
$$
Where we've taken the transpose of $\mathbf{\theta}$ to compute its dot product with $\mathbf{x}$.
TL;DR Matrix form let's us write equations in a simpler form, otherwise things get messy when there are many features and many samples in the input space. The equation may look different however the underlying model is the same. Getting familiar with linear algebra would be valuable.
Comment: You can interchange between row and column vectors simply by taking the transpose. There's no hard and fast rule that $d$ refers to the dimensionality of a row or column vector, it depends on the context. It's more important to understand what $d$ represents in the problem, and in both cases (row or column) it represents the number of features in each datapoint.
Comment: Thanks. Please me comment to the post by 'generic_user'.
Comment: It's more standard to write the error term as $\epsilon$ (rather than $b$).
Comment: Thank you. If I may, I would like to ask a follow-up question. How then does one interpret the following: Gaussian density in d dimension, where data _1,...,_n. Each _i ∈ℝ^. Why would each datapoint, _i, be represented by a vector of d dimensions?
Comment: It's hard to say without full context, but from what you've written, the dimension $n$ is the number of datapoints, and the dimension $d$ is the number of features in each data point. Using the example of house prices, think of each $x_i$ as a row vector with $d=2$ columns, the sq. feet and # bathrooms. You have $n$ such rows for $n$ houses, which you can use to form an $n\times d$ matrix. If it's still unclear you can post a new question with more details on the problem and I can try to answer.
Comment: Thanks again. But then, is there a way to figure out if the d dimensions on a vector refer to d-columns (column vector) or d-rows (row vector)? For some reason, I always thought of d-dimensions as d-rows, rather than d-columns.
Answer: It's needlessly pretentious.  They're saying that $x$ is a $N \times d$ matrix (N rows, d columns), where $N$ is the number of observations and $d$ is the number of variables.  The elements of the matrix are real numbers.
Likewise, they're saying that "y is in the reals" which is to say "y is a vector of real numbers."
I prefer the convention that lower-case italic ($x$) are constants, upper-case ($X$) are vectors, and bold $\mathbf{X}$ are matrices.  It gets harder of course when you get past two dimensions.
I think that a lot of people use pretentious notation in order to demonstrate to others how sophisticated their math is, probably because they're feeling a little bit of imposter syndrome.
Bottom line:  if you're confused, it could be because the author is really smart and knows things you don't.  More likely however, it's because they can't write clearly or are afraid that you'll understand them and see that their ideas are actually pretty simple.
Comment: The purpose of mathematical precision *is* clarity. We who teach this are obliged to familiarize this notation, and not belittle it. Yes, you *can* learn it. No it *isn't* particularly hard. $x$ is a point not a matrix in your description of the problem, so @sudo's answer is correct in spirit and content and in the extension of $x$ from a point/vector to matrix of points, which is the next thing to learn. You can do it! :)
Comment: At a quick glance this makes sense to me. But then I read the other reply to my question (by user 'sudo') and I'm confused. You say d represents no. of columns and 'sudo' says d represent no. of rows. This was part of my confusion to begin with.
Comment: Either way. The "transpose" of a matrix flips it on its side, switching the row and column indices. I suppose that I assumed one configuration, rather than the other.
Comment: @PeterLeopold that sort of attitude is commonly window-dressing on gatekeeping. Many people, in many fields, want to exclude people who haven't spent the time that they have in a given community, and they do so in part with thick jargon. Yes it is clearer to say that x is in the reals than x is a matrix, because you can preserve a notion if sampling and future data. But this sort of marginal improvement comes at the cost of comprehensibility to otherwise-smart people who aren't part if your club.
Comment: All the haters can go to $x\in (you know where)$


Erro no JavaScript ao tentar remover elemento

Question: Fiz um método pra remover um item da minha tabela feita em HTML que é suprida por um formulário normal mas as informações vai pra tabela em questão... Até aí tudo normal, mas na hora de remover um item novo, sem ser o que já estava previamente cadastrado, não remove.
Aqui está meu projeto com o erro, hospedado pra vocês darem uma olhada no que estou falando: https://wesleyvicen1535.000webhostapp.com/CadastroPaciente.html
Até aí tudo tranquilo, o script remove tranquilamente os itens com a classe "remover", mas os novos itens implementados não. Podem inspecionar elemento que vai mostrar que os novos estão indo com a classe.
Meu repositório no Github com o código fonte: https://github.com/wesleyvicen/ProjetoWebOdontologia
Método remover:
var removerTds = document.querySelectorAll('.remover');

removerTds.forEach(function (item) {
    item.addEventListener('dblclick', function () {
        var confirmacao = confirm('Deseja realmente remover este item?')
        if (confirmacao) {
            item.parentNode.remove();
        }
    })
});

Implementa a tabela:
var botao_cadastrar = document.querySelector("#btn_cadastrar");

 botao_atendimento.addEventListener("click", function () {
        event.preventDefault();
        adicionar_atendimento();

    });

function adicionar_cadastro() {
    var nome = document.querySelector('#nome').value;
    var sobrenome = document.querySelector('#sobrenome').value;
    var cpf = document.querySelector('#cpf').value;
    var endereco = document.querySelector('#endereco').value;
    var numero = document.querySelector('#numero').value;
    var bairro = document.querySelector('#bairro').value;
    var cep = document.querySelector('#cep').value;
    var cep2 = document.querySelector('#cep2').value;
    var uf = document.querySelector('#uf').value;
    var cidade = document.querySelector('#cidade').value;
    var municipio = document.querySelector('#municipio').value;

    var tabela = document.querySelector(".tabelaCadastroCliente");

    var linha = document.createElement('tr');
    var td_nome = document.createElement('td');
    var td_sobrenome = document.createElement('td');
    var td_cpf = document.createElement('td');
    var td_endereco = document.createElement('td');
    var td_numero = document.createElement('td');
    var td_bairro = document.createElement('td');
    var td_cep = document.createElement('td');
    var td_uf = document.createElement('td');
    var td_cidade = document.createElement('td');
    var td_municipio = document.createElement('td');
    var td_remover = document.createElement('td');

    td_nome.textContent = nome +' '+ sobrenome;
    td_cpf.textContent = cpf;
    td_endereco.textContent = endereco;
    td_numero.textContent = numero;
    td_bairro.textContent = bairro;
    td_cep.textContent = cep +'-'+ cep2;
    td_uf.textContent = uf;
    td_cidade.textContent = cidade;
    td_municipio.textContent = municipio;
    td_remover.textContent = 'Remover';
    td_remover.classList.add('remover')

    linha.appendChild(td_nome);
    linha.appendChild(td_cpf);
    linha.appendChild(td_endereco);
    linha.appendChild(td_numero);
    linha.appendChild(td_bairro);
    linha.appendChild(td_cep);
    linha.appendChild(td_uf);
    linha.appendChild(td_cidade);
    linha.appendChild(td_municipio);
    linha.appendChild(td_remover);

    tabela.appendChild(linha);
};

Comment: **Wesley**, isso acontece porque o elemento não foi renderizado quando a página foi carregada, pelo contrário, você criou o mesmo depois de todo o processo, para resolver, você deve definir o evento dentro da função `adicionar_cadastro` veja: `td_remover.addEventListener('dblclick' ... `
Comment: eu entendi o que você falou, mas não entendi como posso resolver @NoobSaibot
Comment: Muito obrigado, resolveu meu problema, mas existe algum jeito de chamar novamente o método sem ser repetindo código?
Comment: Tem sim, você pode criar uma função e passar ela: `td_remover.addEventListener('dblclick', funcaoParaRemover);` , só tem que alterar `td_remover.parentNode.remove();` para `this.parentNode.remove();`
Comment: **Wesley** seja bem vindo, como um usuário novo, é importante saber como funciona o site, recomendo que leia o [tour] e caso necessite de ajuda em sobre como utilizar a ferramenta, acesse a [help].
Comment: [**Veja aqui**](http://jsfiddle.net/9rw4xhyd/5/) o exemplo de como eu disse anteriormente.
Comment: Muito obrigado, me ajudou bastante
Answer:

/**
*
* Use assim que funciona
*
*/
var removerTds = document.querySelectorAll('.remover');

for(i = 0; i < removerTds.length; i++)
{
 removerTds[i].addEventListener('click', function(){
  var confirmacao = confirm('Deseja realmente remover este item?')
  if(confirmacao){
   this.parentNode.remove();
  }
 });
}
Answer: Adicione o evento dblclick ao objeto document e verifique se o elemento clicado possui a classe .remover. Desta forma irá detectar o clique duplo também nos novos botões adicionados de forma dinâmica, e você não precisará fazer forEach para adicionar o evento a cada botão.

Lembrando que a função .remove() não funciona no Internet Explorer.
  Se isso for um inconveniente, troque por .outerHTML = '';.

Veja a abaixo o que foi removido e o que foi acrescentado no seu código original:
// CÓDIGO REMOVIDO

//var removerTds = document.querySelectorAll('.remover');

//removerTds.forEach(function (item) {
//    item.addEventListener('dblclick', function () {
//        var confirmacao = confirm('Deseja realmente remover este item?')
//        if (confirmacao) {
//            item.parentNode.remove();
//        }
//    })
//});

// CÓDIGO ADICIONADO
document.addEventListener('dblclick', function(e){

   if(e.target.className == 'remover'){
        var confirmacao = confirm('Deseja realmente remover este item?')
        if (confirmacao) {
            e.target.parentNode.remove();
        }
   }

});

O e.target é o elemento clicado que disparou o evento, o
  .className retorna a classe do elemento.

Funcionamento:

// CÓDIGO REMOVIDO

//var removerTds = document.querySelectorAll('.remover');

//removerTds.forEach(function (item) {
//    item.addEventListener('dblclick', function () {
//        var confirmacao = confirm('Deseja realmente remover este item?')
//        if (confirmacao) {
//            item.parentNode.remove();
//        }
//    })
//});

// CÓDIGO ADICIONADO
document.addEventListener('dblclick', function(e){

   if(e.target.className == 'remover'){
        var confirmacao = confirm('Deseja realmente remover este item?')
        if (confirmacao) {
            e.target.parentNode.remove();
        }
   }

});
// FIM CÓDIGO ADICIONADO

var botao_atendimento = document.querySelector("#btn_atendimento");
var botao_cadastrar = document.querySelector("#btn_cadastrar");

//O IF agora vai selecionar qual dos botões foi clicado, se foi o do atendimento ou do cadastro.
if (botao_atendimento) { // criei este If e o proximo para não ficar sempre puxando o preventDefault()
    botao_atendimento.addEventListener("click", function () {
        event.preventDefault(); // Pega o evento e interrompe o evento normal
        adicionar_atendimento();

    });
} else if (botao_cadastrar) {
    botao_cadastrar.addEventListener("click", function () {
        event.preventDefault();
        adicionar_cadastro();

    });
}

//Metodo usado para o atendimento
function adicionar_atendimento() {
    var nome = document.querySelector('#nome').value; // Seleciona um elemento, neste caso o ID Nome
    var data = document.querySelector('#data').value;
    var descricao = document.querySelector('#descricao').value;

    var tabela = document.querySelector(".tabelaAtendimento");

    var linha = document.createElement('tr'); // Cria um elemento, neste Caso um tr
    var td_nome = document.createElement('td');
    var td_data = document.createElement('td');
    var td_descricao = document.createElement('td');

    td_nome.textContent = nome; // Retorna um nó do createElement, neste caso do td_nome
    td_data.textContent = data;
    td_descricao.textContent = descricao;

    linha.appendChild(td_nome); // Devolve uma referência ao nó adicionado, neste caso o td_nome
    linha.appendChild(td_data);
    linha.appendChild(td_descricao);

    tabela.appendChild(linha); // aqui retorna a referência ao nó adicionado no linha
};

function adicionar_cadastro() {
    var nome = document.querySelector('#nome').value;
    var sobrenome = document.querySelector('#sobrenome').value;
    var cpf = document.querySelector('#cpf').value;
    var endereco = document.querySelector('#endereco').value;
    var numero = document.querySelector('#numero').value;
    var bairro = document.querySelector('#bairro').value;
    var cep = document.querySelector('#cep').value;
    var cep2 = document.querySelector('#cep2').value;
    var uf = document.querySelector('#uf').value;
    var cidade = document.querySelector('#cidade').value;
    var municipio = document.querySelector('#municipio').value;

    var tabela = document.querySelector(".tabelaCadastroCliente");

    var linha = document.createElement('tr');
    var td_nome = document.createElement('td');
    var td_sobrenome = document.createElement('td');
    var td_cpf = document.createElement('td');
    var td_endereco = document.createElement('td');
    var td_numero = document.createElement('td');
    var td_bairro = document.createElement('td');
    var td_cep = document.createElement('td');
    var td_uf = document.createElement('td');
    var td_cidade = document.createElement('td');
    var td_municipio = document.createElement('td');
    var td_remover = document.createElement('td');

    td_nome.textContent = nome +' '+ sobrenome;
    td_cpf.textContent = cpf;
    td_endereco.textContent = endereco;
    td_numero.textContent = numero;
    td_bairro.textContent = bairro;
    td_cep.textContent = cep +'-'+ cep2;
    td_uf.textContent = uf;
    td_cidade.textContent = cidade;
    td_municipio.textContent = municipio;
    td_remover.textContent = 'Remover';
    td_remover.classList.add('remover')

    linha.appendChild(td_nome);
    linha.appendChild(td_cpf);
    linha.appendChild(td_endereco);
    linha.appendChild(td_numero);
    linha.appendChild(td_bairro);
    linha.appendChild(td_cep);
    linha.appendChild(td_uf);
    linha.appendChild(td_cidade);
    linha.appendChild(td_municipio);
    linha.appendChild(td_remover);

    tabela.appendChild(linha);
};
/* RESET */

body {
    margin: 20px 0 0 0;
    padding: 0;
    font-family: Tahoma;
    box-sizing: border-box;
    border: none;
    outline: none;
    background-color: #f5f5f5
}

.corpo {
    width: 100%;
    height: 180px;
    text-align: center;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%);

}

.tabela {
    border: 2px solid white;
    position: absolute;
    text-align: center;
    width: 100%;
}

.centro {
    text-align: center;
    width: 100%;
}

article {
    display: inline-grid;
    margin-bottom: 20px;
}

article:hover {
    border: 5px inset;
}

article span {
    color: ce2e3c;
    font-weight: 550;
}

/* Campos de formulário genéricos */

table {
    border-collapse: collapse;
    padding-right: 20px;
}

th,
td {
    padding: 10px;
}

tr:nth-child(odd) {
    background-color: #f7f7f7;
    border-bottom: 1px solid #444
}

tr:nth-child(even) {
    background-color: #f1f1f1;
    border-bottom: 1px solid #444
}

td:hover {
    background-color: #dedede;
}

tfoot td {
    background-color: #444;
    color: #fff;
    text-align: center;
    font-weight: bolder;
}

tfoot td:hover {
    background-color: #444;
}

textarea {
    width: 500px;
    height: 200px;
    padding: 20px;
}

#cep {
    width: 6%;
}

#cep2 {
    width: 5%;
}

.btn {
    border-radius: 12px;
    width: 330px;
    height: 45px;
    margin: 0.5em;
    background-color: #f48888;
    color: white;
    font-weight: 600;
}

#acao {
    background-color: red;
    color: white;
}

.remover {
    background-color: darkred;
    color: white;
    cursor: hand;
}

.remover:hover {
    background-color: red;

}

.btn:hover {
    background-color: #f26464
}

textarea,
input[type="text"],
input[type="datetime-local"],
input[type="search"],
input[type="number"] {
    border: 2px #cccccc solid;
    border-radius: 10px;
    padding: 0 20px;
}

input[type="text"],
input[type="datetime-local"],
button[type="submit"],
input[type="search"],
input[type="number"] {
    height: 32px;
    font-family: Tahoma;
    font-size: 14px;
}

textarea:hover,
input[type="text"]:hover,
input[type="datetime-local"]:hover,
input[type="search"]:hover,
input[type="number"]:hover {
    background-color: #ddddff;
}

textarea:focus,
input[type="text"]:focus,
input[type="datetime-local"]:focus,
input[type="search"]:focus,
input[type="number"]:focus {
    background: #ffcccc;
}

        <form class="form">
            <input id="nome" type="text" placeholder="Nome" name="nome" autofocus>
            <input id="sobrenome" type="text" placeholder="Sobrenome" name="sobrenome">

            <input id="cpf" type="number" placeholder="CPF" name="cpf" maxlength="11">

            <input id="endereco" type="text" placeholder="Endereço" name="endereco">
            <input id="numero" type="number" placeholder="Número" name="numero">

            <input id="bairro" type="text" placeholder="Bairro" name="bairro">

            <input id="cep" type="text" name="cep" size="3" maxlength="5" placeholder="CEP"> - <input id="cep2" placeholder="CEP" type="text" name="cep2" size="3" maxlength="3">

            <input id="uf" type="text" placeholder="UF" name="uf" maxlength="2">

            <input id="cidade" type="text" placeholder="Cidade" name="cidade">

            <input id="municipio" type="text" placeholder="Distrito" name="municipio">

            <button id="btn_cadastrar" class="btn" type="submit" style="cursor:hand" name="cadastrar">Cadastrar</button>
        </form>

                    Nome
                    CPF
                    Endereço
                    Número
                    Bairro
                    CEP
                    UF
                    Cidade
                    Distrito
                    Ação

            Wesley Vicente
            11951606400
            Praça Joaquim Nabuco
            10
            Centro
            55850-000
            PE
            Vicência
            Vicência1
            Remover

                Isso é tudo

Comment: Muito bom cara, resolveu complementarmente o que eu estava procurando e ficou mais enxuto o código.
Comment: Que bom. Vc deve escolher a melhor resposta que achou e marcar ✔.


Como adaptar para que todos os itens  puxem uma div diferente?

Question: Olá, tenho o seguinte código:

<?

if(isset($row)){
    $row_pedido = $row;
}

if (!isset($situacoes_andamento))
    $situacoes_andamento=$row_pedido->situacoes;

foreach($situacoes_andamento as $situacao){
    if(in_array($situacao->id_situacao, $situacoes_layout)){
        ?>
        <li class="situacao-<?=$situacoes_layout_classes[$situacao->id_situacao];?> <?=$row_pedido->id_situacao == $situacao->id_situacao ? 'atual' : ''?>">

            <?=$situacao->nome_situacao;?>
            <div id="botao-mais-detalhes" class="show-hidden-menu-<?=$situacoes_layout_classes[$situacao->id_situacao];?>" style="text-transform: lowercase;">˅ mais detalhes

        <div id="box-mais-detalhes" class="hidden-menu-<?=$situacoes_layout_classes[$situacao->id_situacao];?>" style="display: none;">

                <?=$situacao->nome_situacao;?>
                em <?=$ecommerce->getDate($situacao->data);?> às <?=$situacao->hora;?>
                <?=$situacao->observacao_loja;?>

<?  }
} ?>

Acontece que a ação da div 'mais detalhes' só funciona no último item  gerado.
Alguém pode me explicar onde estou errando?
Answer: Vai dar errado mesmo porque o script está fora do laço e o último valor de <?=$situacoes_layout_classes[$situacao->id_situacao];?> só vai pegar a última div relacionada.

Note também que você está repetindo as id's id="texto-mais-detalhes",
  id="seta" e id="botao-mais-detalhes" dentro do laço. Não é correto repetir a mesma id em mais
  de um elemento na mesma página. Se essas id's não servem pra nada,
  você deve removê-las ou então usar como class.

Pra resolver seu problema, você não precisa usar nenhum tipo de identificação que relacione um elemento ao outro. Você pode usar métodos do jQuery:
$(document).ready(function() {
   $('.show-hidden-menu').click(function(){
      $(this)  // div clicada
      .closest('li')  // busca a
 onde está a div
      .next()  // busca o próximo elemento, que é a div a ser mostrada
      .slideToggle("slow");  // faz o slide
   });
});

A div a ser clicada ficaria apenas assim, sem id e sem o código PHP:

˅ mais detalhes

Bem como você deve retirar os outros id's repetidos e os códigos PHP que está adicionando nas classes.
No entanto, segundo as especificações HTML5, você não pode usar uma div como filho direto de uma ul. Você teria que colocar cada div dentro de cada li, logo após a div a ser clicada. Daí mudaria o código jQuery para abrir:
$(document).ready(function() {
   $('.show-hidden-menu').click(function(){
      $(this)  // div clicada
      .next()  // busca o próximo elemento, que é a div a ser mostrada
      .slideToggle("slow");  // faz o slide
   });
});

Comment: Muito obrigado pela solução e pelas dicas!!!


Android - How to retrieve text from edit Text to radio button?

Question: Actually I am creating a trivia app. For creating questions, I need to assign the options to radio buttons in a radio group, which has to be done dynamically. For giving the options, i want to enter the option in an editText and grab it into radio group on clicking a button. This has to be done for every option which has to be placed in the radio group. Please help me.
Comment: possible duplicate of [Dynamically Change the Text of RadioButton](http://stackoverflow.com/questions/11013835/dynamically-change-the-text-of-radiobutton)
Comment: My assignment is regarding pulling the information from edit Text field and assigning it to radio buttons each item clicked on a button. I am told to do this way because we are creating questions and options for those in an app.
Answer: RadioButton extends Textview basically, which means you can call getText() and setText (CharSequence text) on any object instance of  RadioButton
to get text from EditText is EditText.getText().toString() all these widget's mother is TextView
Helpful??
Comment: Yes. I already knew this. But this scenario was not applicable for the radio button text setting from edit text
Comment: what?? i dont get you, all i am saying is do this `RadioButton.setText(EditText.getText().toString());` and you are saying it is not applicable? how @VarunVarma
Answer: Use edittext.addTextChangedListener() and onaftertextchange call    radioButton.setText(edittext.getText().toString());
Code
    uid = (EditText) findViewById(R.id.ed_UserId);

    radioGroup = (RadioGroup) findViewById(R.id.radioInstall);
    uid.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
            int selectedId = radioGroup.getCheckedRadioButtonId();
            RadioButton radioButton = (RadioButton) findViewById(selectedId);
            radioButton.setText(uid.getText().toString());
            if (radioButton.getText().equals("Install Now")) {
                Toast.makeText(getApplicationContext(),
                        radioButton.getText(), Toast.LENGTH_SHORT).show();
            } else
                Toast.makeText(getApplicationContext(),
                        radioButton.getText(), Toast.LENGTH_SHORT).show();
        }
    });


Python Key/Value point to same random number

Question: I have a function in Python where I need a Key/Value to point to the same random number that is chosen, I can't figure this out and couldn't find any examples on doing this. Does anyone have any suggestions:
def generatePhrase():
        print '\n'
        print 'Now Generating Phrase....'
        print 'And Here we go!!!'
        print '\n'
        phrase = {'Created by ATNT in 1970s':'UNIX','Developed by Sun Microsystems':'Java','Worst Operating System in the World':'Windows','Containerizing Environments':'Docker','Built by Python, used for Automation':'Ansible'}
        randomPhrase = random.choice(phrase.keys())
        print randomPhrase + '\n'
        randomValue = random.choice(phrase.values())
        print randomValue.replace(randomValue,"_ " * len(randomValue))
        return randomPhrase

So what happens when I run the code is this:
Now Generating Phrase....
And Here we go!!!

Created by ATNT in 1970s

_ _ _ _ _ _ _

I need the randomValue variable to use the same random number that was generated as randomPhrase. Can someone tell me how to do this?
Comment: I can't see how this was down voted
Comment: Once you randomly chosed the key of your dictionary, you can access the value by accessing your dictionary using that key.
Comment: Yeah i figured that would be the case..
Answer: You can use:
randomValue = phrase[randomPhrase]

This will ensure you'll get corresponding value.
import random

phrase = {'Created by ATNT in 1970s':'UNIX','Developed by Sun Microsystems':'Java','Worst Operating System in the World':'Windows','Containerizing Environments':'Docker','Built by Python, used for Automation':'Ansible'}
randomPhrase = random.choice(phrase.keys())
randomValue = phrase[randomPhrase]

print randomPhrase, randomValue

>>> Developed by Sun Microsystems Java


Norm and Cauchy sequence.

Question: If someone could please show me how to show that if $x_n$ is a Cauchy sequence then $x_n \over ||x_n||$ is a Cauchy sequence as well?
Thanks, I hope I've been clear enough.
Comment: It's not true. Let $x_n=(-1)^n/n$ in $\Bbb R$.
Comment: No. Take $x_0\ne0$ and $x_n=nx_0$. Your statement does hold if there is a $c>0$ with $\Vert x_n\Vert\ge c$ for all $n$.
Comment: I see, you seem to be right. Does the invers of this statement at least hold?
Comment: @DavidMitra: Why do not you convert this as an answer. You nicely explain all the things. Thank you.
Answer: Let our working domain be $\mathbb{R}$ and $(x_n)$ be a non-zero sequence of points of real numbers. Then First we have to note that $$y_n=\dfrac{x_n}{|x_n|}=\pm 1.$$ If $x_n>0,\forall n\in\mathbb{N}$ then $(y_n)=(1)$ is Cauchy.
Similar thing is valid for, if  $x_n<0,\forall n\in\mathbb{N}.$
Conversely, suppose $(x_n)$ be any divergent sequence of positive reals (or divergent sequence of negative reals). Then although $(x_n)$ is not cauchy, $(y_n)$ is Cauchy.

Norm and Cauchy sequence.


How to present Popover modal in ReactJS

Question: Could someone help me to create popover in ReactJS UI, Something like below image.
Answer: You can do this quite easy using one of the popular ui component frameworks. For example bootstrap/jquery.
Follow the steps below and you will be fine:

In render method of the parent component prepare html layout in accordance with guidelines for the component:

Toggle popover

In componentDidMount method of the parent component:

$("#mypopover").popover();

And finally in componentWillUnmount:

$("#mypopover").popover('destroy')

How to present Popover modal in ReactJS


Evaluation of the integral $\int_0^1 e^{2t^2 -at} dt$

Question: I would like to integrate a function in the range $[0,1]$. I tried a lot of ways including Mathlab. All solutions come in terms of some error function.
I would like the answer in terms of $a$.
$$\int_0^1 e^{2t^2 -at} dt$$
Comment: Not possible. No closed form in terms of elementary functions for that integral.
Answer:
All solutions come in terms of some error function. I would like the answer in terms of a.

Since those error functions had a in their argument, you already got what you wanted.


Correlation analysis for a single sample: Correcting for multiple comparisons?

Question: I ran a study with a single group of participants and with 12 variables. I conducted 2 planned regression analyses (i.e., I hypothesized a specific predictor for 2 DVs prior to running the experiment), but I first conducted exploratory correlations between the 12 variables to evaluate potential covariates. Do I need to correct for multiple comparisons? Why or why not, and if so, is there a preferred method for this situation? Also, if I need to adjust, do I need to do so only for the set of exploratory correlations, or also for the planned regression analyses?
Answer: It is worth to think back why one corrects for multiple comparisons. If you work in the Neyman-Pearson framework (which you probably do), you use inferential statistics (for example p-values) in order to reduce the number of times you will be wrong (in the long term). Notice how being wrong is not related to statistics per se, but rather to the theoretical inferences which you as a researcher attach to them. So, regarding the 2 planned tests you performed, the need for a correction depends on how they are related to the claims you want to make.
Scenario 1: you claim there is an association if either outcome variable ('DV') is associated with the predictor
In this case, you need to control for multiple comparisons, as otherwise the type I error rate increases from 5% to 9.75%.
Scenario 2: you claim there is an association if, and only if, both outcome variables ('DV') are associated with the predictor
In this case, you do not need to control for multiple comparisons, quite the opposite. You can increase the alpha level to 0.2236. Under the null, a p-value below this level in both tests only has a chance of 0.2236 * 0.2236 = 0.05.
Scenario 3: you wanto to make two independent theoretical claims, one for the association between predictor and variable 1, and another claim for predictor and variable 2.
In this case, you do not need to control for multiple comparisons as the theoretical inferences are independent.
For more on this, I can highly recommend this blog post by Daniel Lakens.
As to your exploratory work, given that it was not planned in advance I do not believe that p-values are interpretable in the Neyman-Pearson framework. I would report them uncorrected and clearly indicate that these are exploratory analyses warranting replication.
Comment: The Perneger article at http://obgyn.queensu.ca/assets/pdf/Bonferroni.adjustments.BMJ.1998.pdf, referenced by Lakens, is good food for thought.


Extend PHP Class only if other class is defined

Question: Some may argue that this could be bad practice due to potential inconsistencies, however, I am wondering how (if possible) I could tell a class to extend another class, but only if it's defined.
I'm aware this doesn't work, but what I'm effectively after is:
class MyClass extends (class_exists('OtherClass') ? OtherClass : null)

Or maybe a function that would run in the constructor to set up the extend if the class exists.
I of course want to avoid..
if(class_exists('OtherClass'))
{
    class MyClass extends OtherClass
    {
        //The class
    }
}
else
{
    class MyClass
    {
        //The class
    }
}

.. because of the massive duplication of code.
I've looked for answers on Google and around the site, but found nothing - if I have duplicated a question however, do let me know.
Answer: You could create a middle-man class that's created inside the class_exists() condition, but without its own behavior:
if (class_exists('OtherClass')) {
    class MiddleManClass extends OtherClass { }
} else {
    class MiddleManClass { }
}

class MyClass extends MiddleManClass {
    // The class code here
}

This makes the class hierarchy include one more class, but has no duplicated code (has no code actually) and methods inside MyClass can reach the OtherClass with parent:: or $this as usual if it was available.
Comment: Yes of course! I was pseudo-coding something like this in my head, but couldn't fabricate anything useful. Cheers.
Comment: Yesterday I saw the same code In the legacy code of one project in which I am working.

Then I am wordering how Is the better way to do that operation.

I think that there are several solutions respecting the standard of PHP.

Also, I am not able to see the problems that this solutions could causes, for example: autoload, apc, etc.

Thanks.