Readers-writers problem with writer priority

Question: Problem
In the book "Little Book of Semaphores", p. 71, there is the following problem:

Write a solution to the readers-writers problem that gives priority to writers. That is, once a writer arrives, no readers should be allowed to enter until all writers have left the system.

I arrived at a solution, but it's a bit different from the one given in the book.
My solution
Shared variables:
readSwitch = Lightswitch()
writeSwitch = Lightswitch()
noWriters = Semaphore(1)
noReaders = Semaphore(1)

Semaphore(1) means a semaphore initialized to 1, and Lightswitch is defined in the book like this:
class Lightswitch:
  def __init__(self):
    self.counter = 0
    self.mutex = Semaphore(1)

  def lock(self, semaphore):
    self.mutex.wait()
    self.counter += 1
    if self.counter == 1:
      semaphore.wait()
    self.mutex.signal()

  def unlock(self, semaphore):
    self.mutex.wait()
    self.counter -= 1
    if self.counter == 0:
      semaphore.signal()
    self.mutex.signal()

Reader logic:
noReaders.wait()
noReaders.signal()

readSwitch.lock(noWriters)

# critical section for readers

readSwitch.unlock(noWriters)

Writer logic:
writeSwitch.lock(noReaders)
noWriters.wait()

# critical section for writers

writeSwitch.unlock(noReaders)
noWriters.signal()

Book's solution
Shared variables:
readSwitch = Lightswitch()
writeSwitch = Lightswitch()
noWriters = Semaphore(1)
noReaders = Semaphore(1)

Reader logic:
noReaders.wait()
readSwitch.lock(noWriters)
noReaders.signal()

# critical section for readers

readSwitch.unlock(noWriters)

Writer logic:
writeSwitch.lock(noReaders)
noWriters.wait()

# critical section for writers

noWriters.signal()
writeSwitch.unlock(noReaders)

Questions
1) In the reader logic, in my solution, noReaders.signal() immediately follows noReaders.wait(). The idea here is that noReaders behaves as a kind of turnstile that allows the readers to pass through it, but is locked by a writer as soon as one arrives.
However, in the book's solution, noReaders.signal() is done after calling readSwitch.lock(noWriters).
Is there any reason why my ordering would produce an incorrect behavior?
2) In the writer logic, in my solution, writeSwitch.unlock(noReaders) comes before noWriters.signal(). However, the book places them in the reverse order. Is there any reason why my ordering would produce an incorrect behavior?
Edit: additional question
I have an additional question. There is something that I am probably misunderstanding about the book's solution. Let's say that the following happens:

Reader 1 acquires noReaders (noReaders becomes 0)
Reader 2 waits in noReaders (noReaders becomes -1)
Writer 1 waits in noReaders (noReaders becomes -2)
Reader 3 waits in noReaders (noReaders becomes -3)
Reader 4 waits in noReaders (noReaders becomes -4)
Reader 1 acquires noWriters (noWriters becomes 0)
Reader 1 signals noReaders (noReaders becomes -3; Reader 2 gets unblocked)
Reader 2 passes through noWriters lightswitch; signals noReaders (noReaders becomes -2,
Reader 3 gets unblocked)

In the above situation, it seems that additional readers can keep arriving and entering the critical section although a writer is waiting.
Besides, considering that reader and writer are looping, a reader that finished the critical section could loop around and wait on noReaders again, even if there are writers already waiting.
What am I misunderstanding here?
Answer: With your solution, the following situation is possible:

A new writer comes after writeSwitch.unlock(noReaders) but before noWriters.signal()
New writer executes writeSwitch.lock(noReaders)
A reader executes readSwitch.lock(noWriters), going into critical section even if there is a writer.

The book's solution wakes up waiting writers first before waking up the readers. Your solution wakes up readers first, and also allows readers to queue up at readSwitch.lock(noWriters) so they can run even if there is a writer waiting.
Comment: Thank you. I agree that, in the writer, the order of the last two lines in my solution should be reversed: the writer should signal `noWriters` before it unlocks `noReaders`, so that it gives priority to waiting writers. However, it's still not clear to me why the first two lines of my solution's reader are in the wrong order. I also added an "Edit: additional question" section with additional doubts. Thank you for your patience.
Comment: For the new addition to your question: note that readers are in critical section without `noReaders` lock. So, as soon as a reader goes into its critical section, a writer can execute a lock on `noReaders`, preventing other readers. True, by the time that happens other readers can go in, but reader the spec: once a writer arrives, all writers must be processed. It doesn't say as soon as a writer arrives it must be admitted.
Comment: Your reader solution, with its lock/unlock, allows readers to queue up at `readSwitch.lock(noWriters)`. So when a writer completes and releases `noWriters`, readers may go in even if there is a new writer.
Comment: It seems a lot clearer now. After the reader acquires `noReaders`, it must lock `noWriters` _before_ signaling `noReaders`. Otherwise, a reader may be able execute `readSwitch.lock(noWriters)` and go into the critical section as soon as a writer signals `noWriters`, even if there are other writers waiting.


Consume RESTFull service and insert them into Context broker

Question: I have an external service that provides weather data via Restfull API with authentication.
What would be the best option to able to consume the services and send/insert the data to a Context broker.
I was thinking to develop a custom IoT Agent with json file to provide the external Restfull service endpoint and configuration for the Context broker.
Is any other option to achieve the same functionality?
Answer: The big question here is whether you need to inject the data into the context broker, or just inform the context broker that such data exists. If you want to consider the weather station as a device, then indeed, your proposed architecture makes sense:

Create a chron job to fire periodically
Generate a file in a known format (e.g. JSON) and pass the file to a custom micro-service
The micro-service interprets the file and runs a batch upsert to send all the data as measures into the context broker

An example of this with a code walkthrough is discussed in the following webinar
The alternative would be to create a micro-service which listens to the registration endpoint(s) - for NGSI-v2 uses the <code>/v2/op/query</code> batch endpoint for this, for NGSI-LD it is a direct forwarding of a request. In this scenario, the weather-station data remains outside of the context broker itself and can be used to augment existing entities. A working example can be found within the FIWARE Tutorials
Obviously the route you choose will depend upon what you need to do with the data, if you need to subscribe to temperature changes for example, then it is better to treat the weather station as a device providing context data in the form of measures and go for Option 1.
Comment: And here is the link for the code from the above webinar for the 1rst architecture https://github.com/jason-fox/csv-to-json, csv-to-json Thanks @jason-fox


How to configure Hudson to use Maven for dependecies and run JUnit

Question: In Eclipse I have my "Dynamic Web Project" configured with Maven taking care automatically of all my dependencies (once I specify them in pom.xml). After implementing my Unit Tests I can simply run them all by right-clicking on project and selecting: Run As -> JUnit Test.
How/where can I now configure Hudson so after checkout of all my sources from SVN repository it would automatically invoke(?) Maven (to download all dependencies) and then run all available tests with JUnit?
Answer: When you set up a project in Hudson (now Jenkins) in the configuration page you may choose the build phases that Jenkins will run. Then it will run them in the order you specify. There you will have Maven steps where you'll define your goals.
Jenkins itself has to know where to find a Maven installation (or Ant, or any other command that it must run to build). This could be done in the server configuration page.
Answer: I think that's the default behavior of Hudson (compiling + running tests).
Did you commit on your svn repository the pom.xml file?
Comment: So just create on your hudson instance a job pointing to your svn project repository and you are done.
Comment: It is the default.  In the "goals and options" textbox on the configuration page enter "install", "clean install", "deploy", etc. and the unit test lifecycle will run.  Jenkins should automatically detect the junit output files and generate the appropriate graphs/reports.


Naming conflict in rails with "Account" model

Question: I have a model Account located under /app/models/account.rb:
class Account < ActiveRecord::Base
end

when I now request the controller I get undefined method all for Account:Module:
class AccountsController < ApplicationController
  def index
    @accounts = Account.all
  end
end

I tried renaming the model to Accounte which does work. However I see a lot of rails tutorials working with Account models and it is really hard to find other names.
How do I locate and disable the Account module to clear this naming conflict?
I can access the bad Account through rails console.
Comment: I assume you don't have a module named `Account` in your own codebase, what gems are in your Gemfile
Comment: Also, [try this](http://stackoverflow.com/a/10407131/877472), it might help you figure out where this other `Account` module is being defined.
Comment: Ah I just found out that I initially ran `rails new account` so `config/application.rb` defines `module Account`.
Comment: Do you have any gems that might be adding an `Account` module?
Comment: @UriAgassi I have `rails~4.1.8`, `mysql2~0.3.17` and `spring`.
Comment: @PaulRichter I only get an empty array back with your method.
Comment: Glad you figured it out :p
Answer: Problem was that I used rails new account which creates a module Account in config/application.rb. This caused the naming trouble.


How can I design a relationship between two types of users?

Question: I have two types of users in drupal-7: children users and parents users. How can I design a relationship between these types of users?
Also How can I maintain this relationship in the code? i.e. getting the parent of the child or vice versa.
Answer: You can use the User Relationships module for that.

Administrators are able create relationship types (friend, coworker, etc). Relationship types can be setup to be one-way or mutual. If a relationship type is one-way (subscriber) only the requester is shown as relating to the requestee. Relationship types can also be set as needing or not needing approval.

I've used this module for one of my project. It works great!
Answer: Consider using the relation module. You can:

Create binary and n-ary relations among various entities.
Store meta information about the relationship in fields, as relations are fieldable entities.
Export/Import the relationship via features.
Specify the directional nature of the relationship.

Relations also ships with views integration, so you get that for free without any coding, plus, its got a neat API.
Answer: From official  Dynamic Entity Reference module page on Drupal.org:

Dynamic Entity Reference provides a field type/widget/formatter combination for Drupal 8 that allows an entity-reference field to reference more than one entity type

DER has active development for Druapl 8 also


Calling stored procedure and getting the results back

Question: Hey all this is the first time i am calling a stored procedure via vb.net and i would like to make sure i have everything correct before i execute it.
This is my code:
Dim connectionString As String = GetConnectionString()
Dim intCount As Integer = 0

Using connection As New SqlConnection(connectionString)
   Dim command As SqlCommand = connection.CreateCommand()

   Try
      connection.Open()
      command.CommandType = CommandType.StoredProcedure
      command.CommandText = "Complete_S_H"
      command.Parameters.Add("@J_ID", SqlDbType.Int)
      command.Parameters.Add("@O_Nbr", SqlDbType.VarChar)
      command.Parameters.Add("@R_Nbr", SqlDbType.VarChar)
      command.Parameters("@theOutput").Direction = ParameterDirection.Output

      Dim dataReader As SqlDataReader = command.ExecuteReader()
      Do While dataReader.Read()
         ListView1.Items.Add(Trim(dataReader(0)))
         ListView1.Items(CInt(intCount)).SubItems.Add(Trim(dataReader(1)))
         ListView1.Items(CInt(intCount)).SubItems.Add(Trim(dataReader(2)))
         ListView1.Items(CInt(intCount)).SubItems.Add(Trim(dataReader(3)))
         ListView1.Items(CInt(intCount)).SubItems.Add(Trim(dataReader(4)))
         ListView1.Items(CInt(intCount)).SubItems.Add(Trim(dataReader(5)))
         intCount = intCount + 1
      Loop

      dataReader.Close()
      connection.Close()
   Catch ex As Exception
      Console.WriteLine(ex.Message)
   End Try
End Using

The stored procedure returns 6 colums worth of data and i would like to add that data to a listview. I'm not sure i have the correct sytax for doing that but this is what i used in my previous sql code (running a query with, not a stored procedure).
Also, i'm not sure how to go about getting data for the @xxx names above from a textbox? How do i pass the values into the @xxx names from the users textbox?
The MS SQL mangement studio code is this for the the stored procedure:
 EXEC [dbo].[Complete_S_H]
@J_ID = 208660,
@O_Nbr = NULL,
@R_Nbr = NULL

Two of the passed varibles can be NULL. Only one needs to be filled out in order for it to return data.
Any help would be great!
David
Answer: You are pretty close.
Couple of notes:

You can get a local reference to the list item that was added, which speeds up and cleans up the code
Unless you know that the DB values will never be null, you should always test them for DbNull before using them.
To use the values from the textbox, you can use Parameters.AddWithValue. I have modified the code to show how.

The alternative is to set the Parameter's .Value property once it is added:
command.Parameters.Add("@J_ID", SqlDbType.Int).Value = CInt(TextBox1.Text)

or
command.Parameters("@J_ID").Value = CInt(TextBox1.Text)

Here is a rewrite with these ideas and a bonus loop for setting the subitems (not required):
    Dim connectionString As String = GetConnectionString()

    Using connection As New SqlConnection(connectionString)
        Dim command As SqlCommand = connection.CreateCommand()

        Try
            connection.Open()
            command.CommandType = CommandType.StoredProcedure
            command.CommandText = "Complete_S_H"
            command.Parameters.AddWithValue("@J_ID", CInt(TextBox1.Text))
            command.Parameters.AddWithValue("@O_Nbr", TextBox2.Text)
            command.Parameters.AddWithValue("@R_Nbr", TextBox3.Text)
            command.Parameters("@theOutput").Direction = ParameterDirection.Output
            'command.ExecuteNonQuery()

            Dim dataReader As SqlDataReader = command.ExecuteReader()
            Do While dataReader.Read()
                Dim oItem As ListViewItem

                oItem = ListView1.Items.Add(Trim(dataReader(0)))

                For nI As Integer = 1 To dataReader.FieldCount - 1
                    If Not dataReader.IsDBNull(nI) Then
                        oItem.SubItems.Add(Trim(dataReader(nI)))
                    Else
                        oItem.SubItems.Add(String.Empty)
                    End If
                Next
            Loop

            dataReader.Close()
            connection.Close()
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
    End Using

Comment: Awesome CT! It worked great with your little tweaks! Thanks! :o)


Frobenius theorem

Question: I came across the following conclusion in a textbook, but can't really understand it. I would be grateful if anyone could elaborate:
Assume that we have two linearly independent vector fields $V_{1},V_{2}$ on $\mathbb{R}^{3}$. Then,for a function $f$ on $\mathbb{R}^{3}$,
if $[V_{1},V_{2}]=0$ and $V_{1}f=0$, $V_{2}f=0$, it follows from the Frobenius theorem that $f$ is a function of one variable.
I only have a basic understanding of Frobenius theorem, namely, if the vector fields $V_{i}$ are linearly independent and commute, then a PDE system $V_{i}f=0$ is solvable. But how do I get "function of one variable" statement?
Thank you for any help.
Comment: You wrote *three* where you meant *two*.
Answer: The Frobenius theorem implies that you can find a chart which has $V_1=\frac{\partial}{\partial x^1}$ and $V_2=\frac{\partial}{\partial x^2}$, so locally your $f$, which is a function of $(x^1,x^2,x^3)$, is such that $$\frac{\partial f}{\partial x^1}=\frac{\partial f}{\partial x^2}=0.$$
Of course, this means that (in an appropriate neighborhood of each point) $f$ depends only on $x^3$.
Comment: Thank you for the answer. As a follow up: would the same be true if the commutator of $V_{1}$ and $V_{2}$ was a linear combination of $V_{1}$ and $V_{2}$?
Comment: @GregVoit, in that case  $V_1$ and $V_2$ are everywhere tangent to a family of surfaces (the distribution is integrable), and $f$ is constant on each of those surfaces. You can still choose coordinates so that these surfaces are given by $x^3=\text{constant}$ and $f$ will depend just on $x^3$.
Comment: as a follow up question: is it equivalent to say that there is a coordinate system, say $(x_{1},x_{2},x_{3})$, such that $V_{1}=\frac{\partial}{\partial x_{1}}$ and $V_{2}=g(x_{1},x_{2},x_{3})\frac{\partial}{\partial x_{1}}+h(x_{1},x_{2},x_{3})\frac{\partial}{\partial x_{2}}$? @TedShifrin
Comment: or does it have to be in the exact form $V_{1}=\frac{\partial}{\partial x_{1}}$ and $V_{2}=\frac{\partial}{\partial x_{2}}$? @TedShifrin
Comment: @GregVoit, the former. The latter can happen only when the Lie bracket is $0$.
Comment: @TedShifrin I see. Just to make sure I understood correctly: If the Lie bracket is zero, then *both* options are possible, i.e. $V_{1}=\frac{\partial}{\partial x_{1}}$, $V_{2}=\frac{\partial}{\partial x_{2}}$ and $V_{1}=\frac{\partial}{\partial x_{1}}$, $V_{2}=g\frac{\partial}{\partial x_{1}}+h\frac{\partial}{\partial x_{2}}$. Right?
Comment: @TedShifrin could you maybe clarify?

Frobenius theorem


Normalização de tabelas MySQL

Question: Estou criando um sistema para cadastrado de funcionário, porem, gostaria de começar de forma normalizada; pensei algo assim
tb_funcionario (id_func, id_funcao, id_depto, nome_func, data_nasc, end_fun, dt_admissao, dt_demissao)

tb_funcao (id_func,id_depto,nome_funcao)

tb_depto (id_depto, nome_depto)

O que da para melhorar ou acrescentar de tal forma que fique dentro dos padrões., grato pela colaboração.
Comment: Poderia descrever melhor como o sistem vai funcionar isso ajuda identificar como devem ser os relacionamentos entre as tabelas. Como está parece adequado.
Answer: Antes de falar a respeito de normalização, algumas coisas a serem observadas são:

Na normalização de nomes não tenha medo de escrever bastante, é muito melhor algo como: id_funcionario_externo em vez de id_fun_ex. Além de mais fácil de entender não vai deixar seu banco de dados mais pesado.
Utilizar os tipos de dados mais adequados, assim sendo:

IDs: utilizar um tipo de dado inteiro, possivelmente que o tipo SMALLINT é mais do que o suficiente mas pode escolher algum outro que se enquadre também (Link: Tipos Inteiros).
Datas: Utilizar tipos Date pois está querendo guardar apenas a data e assim vai poder utilizar funções para fazer Selects facilmente.
Campos de Texto: Em campos de texto que o tamanho pode ser variável (como em nome_func) opte por usar varchar em vez de char pois o char armazena todo o espaço definido e o varchar conforme necessário (Link: Varchar e Char)

Recomendo ainda que na tabela tb_funcionario você insira um campo para RG e/ou CPF para que defina ele como unique key para garantir que exista nenhum funcionário duplicado. Apesar de ser algo raro duas pessoas podem ter exatamente o mesmo nome.

Problemas de normalização -> Primeira Forma Normal:

Sua tabela tb_funcao e tb_funcionario possuem o id_depto, isso pode gerar duplicidade de dado desnecessário ou mesmo informações incorretas.
Primary Keys: Definir os campos id_func, id_func e id_depto como Primary Key.
Foreigns Keys: Nos campos id_func,id_depto da tabela tb_funcao definir como Foreign Key e fazer a relação correta.

Para mais informações recomendo: Normalização em BD
Answer: Uma sugestão usando o que postou:
tb_funcionario (id_func, id_funcao, id_depto, nome_func, data_nasc, end_fun, dt_admissao, dt_demissao)

tb_funcao (id_func,id_depto,nome_funcao)

tb_depto (id_depto, nome_depto)

Ficaria assim:
person(
  id unique,
  datebirth,
  person_name,
  person_surname
)

person_addresses(
  id unique,
  person_id,
  country_code,
  postal_code,
  province_code,
  city,
  address
  address_add
)

person_roles(
  id unique,
  role_id,
  person_id
  date_ini (data de início ou admissão)
  date_end (data de término ou demissão)
)

roles(
  id unique
  title
)

department(
  id unique
  title
)

department_roles(
  id unique
  role_id
)

Abaixo, vou explicar apenas alguns motivos da modelagem acima, sem abranger os tipos de dados (integer, var, date, etc).
O primeiro passo é padronizar a nomenclatura e, para tal, o recomendado é seguir um padrão internacionalizado usando o idioma inglês, pois é o mais difundido no mundo.
Conforme comentado pelo Giovani, evite abreviar os nomes das colunas. Descreva-os com clareza.
Removi redundâncias dos nomes das tabelas e nomes de colunas, exemplo, usar "tb_" para tabelas é desnecessário pois já são uma tabelas.
A coluna end_fun é um tanto confusa, lembrando algo como "end function", "fim de função?"..
Mas pensando bem, parece ser "endereço do funcionário".
Se for endereço, então como fazer se o funcionário possuir mais de um endereço?
Aí nesse ponto a modelagem está engessada. Terá problemas futuros e muito trabalho para remodelar para múltiplos endereços.
Note que na tabela "person_addresses" possui uma coluna para código do país.
Então muitos pensam, "mas o sistema será só no meu país por quê preciso de código de país?".
Mais uma vez caímos na questão de globalização.
Pense num funcionário imigrante, um boliviano, argentino, colombiano, e isso é muito comum no Brasil. Então a empresa precisa registrar esse funcionário mas ele não possui endereço fixo no Brasil mas obviamente tem endereço fixo no país natal. Se o sistema não permitir endereços internacionais, terá então uma limitação no sistema.
Por quê troquei tb_funcionario por "person"?
Para que a estrutura seja útil para outras situações e não fique amarrada somente a cadastro de "funcionários".
Essa mesma tabela pode ser usada para clientes, por exemplo, e esse também o motivo de remover outras colunas como id_depto, id_funcao, etc, e organizá-los em tabelas de  relacionamentos.
Em "person_roles" é onde faz os relacionamentos entre o id da pessoa e o id da função.
Nessa tabela contém também data de início/admissão e término/demissão. As datas poderiam estar também numa outa tabela, mas acho desnecessário.
Pode ter casos onde uma mesma pessoa entra e sai de um cargo num departamento e retorna ao mesmo cargo e departamento. Por isso, deve permitir múltiplas entradas para uma mesma pessoa.
Prefira algo mais genérico pois nem sempre a data de término num cargo quer dizer demissão.
A pessoa/funcionário pode ser transferido ou promovido ou simplesmente terminou algum estágio, faleceu, adoeceu, gravidez, aposentou, enfim.
O interessante seria criar mais uma tabela para fazer o relacionamento de motivos do término, caso queira ter maior controle.
Perceba também que a tabela "person_roles" permite que uma mesma pessoa tenha vários cargos. E isso é muito comum em muitas empresas ter pessoas que trabalham em 2 ou mais departamentos exercendo funções as vezes iguais ou totalmente diferentes.
Citando um exemplo, um executivo poliglota.
É do departamento administrativo cuja função principal é de trader.
Durante o tempo que não está viajando pelo mundo, fica no escritório exercendo função de tradutor ou qualquer outra coisa. Esse é um mero exemplo de funcionário com múltiplas funções.
Sobre a modelagem proposta, como saber qual ou quais departamentos pertence um determinado funcionário?
Através do relacionamento na tabela "department_roles" obtém-se a informação.
Perceba que as tabelas são independentes umas das outras. O importante é as tabelas de relacionamento. É isso que torna o sistema flexível e reutilizável.
*As nomenclaturas, tal como a modelagem proposta é meramente uma sugestão.
Não quer dizer que deve ser exatamente como apresentado. Apenas procure entender como organizar as tabelas e criar os relacionamentos de forma mais dinâmica.
Pense sempre na reutilização da estrutura e flexibilidade do sistema.

Normalização de tabelas MySQL


Linux Read-Ahead Downsides

Question: Are there any downsides to raising the size of the read-ahead cache?
On our farm, we're currently running at 256, and upon raising that higher, we are seeing significant throughput gains.

[root@server~]# hdparm -tT /dev/sda /dev/sda:
Timing cached reads: 7352 MB in 2.00 seconds = 3677.62 MB/sec 3
Timing buffered disk reads: 244 MB in 3.10 seconds = 78.68 MB/sec

[root@server ~]# blockdev --setra 10240 /dev/sda

[root@server ~]# hdparm -tT /dev/sda /dev/sda:
Timing cached reads: 11452 MB in 2.00 seconds = 5728.52 MB/sec
Timing buffered disk reads: 422 MB in 3.17 seconds = 133.04 MB/sec

We are running on 2.6.
Answer: The downsides are

Wasted IO.  Your computer may spend time reading things from the drive it doesn't need
Wasted memory.  The stuff it read that didn't need to be read is stored in memory that could have been used for something else.

You probably need to come up with a test that is more representative of your real-world usage then hdparm -t.  hdparm -t does sequential access which is case where a large read-ahead will be very helpful.  When you have lots of random access the gains may not be nearly as useful and probably harmful.
As far as I know there is no danger to your data, just a potential for you performance to get worse depending on your specific work load.  This is probably one of the types of things that you are going to have to tweak and test.  I don't think I would make such a large change (from 256-10240) in a single step though.

Linux Read-Ahead Downsides


By the continuity of the inner product, a subspace of a Hilbert space is closed?

Question: Let $(e_n)$ be an orthonormal sequence in a Hilbert space $H$. The following are equivalent:

$(e_n)$ is complete.
$\text{clin}\{e_n \ | \ n\in \mathbb{N}\} = H$,
$||x||^2 = \sum_{n=1}^\infty |(x,e_n)|^2, \quad \text{for all} \ x\in H$.

For showing $(2)=>(1)$, the following text is used in the proof

Let $x\in H$ such that $(x,e_n)=0$ for all $n$. Define $$ E = \{y\in H
: (x,y) = 0\}. $$ $E$ is a subspace of $H$ and by the continuity of
  the inner product it is closed.

I don't understand how the continuity of the inner product is used to state $E$ is closed?
Answer: Let $(y_n)$ be a convergent sequence in $E$ and denote by $y_0$ its limit.
We have $(x,y_n)=0$ for all $n$ and, by continuity of the inner product:
$(x,y_n) \to (x,y_0)$.
This shows $ (x,y_0) =0$, hence $y_0 \in E$.
Comment: I know what you said is the same thing, but it was helpful for me to rephrase that as: "Clearly, $(x,y_n) \to 0$. Then, by continuity of the inner product $(x,y_n) \to (x, y_0)$, we determine that $(x, y_0) = 0$. Hence, $y_0 \in E$.
Answer: Fix $x \in H$, and consider the function
$$ H \to \mathbb C$$
sending
$$ y \mapsto (x, y).$$
As you say, this is a continuous function.
Being continuous, the preimage under this function of every closed subset of $\mathbb C$ is a closed subset of $H$. In particular, the preimage of $\{ 0 \} \subset \mathbb C$ is
$$ E = \{ y \in H \ : \ (x, y) = 0 \},$$
and this is a closed subset of $H$.


Covariates and degrees of freedom

Question: Consider a problem, when one is interested in finding influence of variable set {X} on Y (assuming reverse causal relation is infeasible), when confounding influences from a set of variables {Z} are present.
I am familiar with two approches to disentangle effect of {Z} on Y from effect of {X}:

Partial correlation / residualization in a "fixed" effect model, when the number of covariates $p_Z =$ |{Z}| is small compared to the number of available samples, $p_Z \ll N$, as by fitting multiple regressions one removes degrees of freedom, and given linearly independent factors Z, the degrees of freedom will be depleted as $p_Z$ approaches $N$.
Expressing correlation structure of confounding effects as "random" effect, which requires $p_Z > N$ to estimate covariance matrix.

Question: What are alternative approaches? Are there approaches that work for $p_Z \approx N$ or all mentioned regimes? Have sparse regression models been applied to this problem?
Answer: Other (non-experimental) approaches are instrumental variables, regression discontinuity and propensity score matching, to name a few. If you can, you should conduct a randomized control trial to estimate the impact of X on Y. You can find a discussion of these approaches in: Angrist, J. D., & Pischke, J. S. (2008). Mostly harmless econometrics: An empiricist's companion. Princeton university press.
Comment: my question is not about experiment design; I see that instrumental variable approach directly relates to partial correlation I mentioned, just puts it in causal inference terms. My question is what analysis method to use when the number of covariates is a bit below sample size.

Covariates and degrees of freedom


Pointwise infimum of uncountably many measurable functions

Question: Let $F$ be a family of measurable real functions on the domain $(0,1)$ satisfying the following two conditions:
(1) $f_1, f_2 \in F$ implies $\min\{f_1, f_2\} \in F$;
(2) $g = \lim_n f_n$  for some $\{f_n\in F: n\in \mathbb N\}$ implies $g\in F$;
[Claim] If we set $h = \inf \{f: f\in F\}$, then $h \in F$.
The motivation of the [Claim] is the following. We know infimum of countably many measurable functions is a measurable function. However, it is absurd to say that infimum of uncountably many measurable functions is again a measurable function. I wonder that, if it may be possible to have a measurable infimum, when we add two closedness conditions above to the family of functions.
Answer: That's wrong. Let
$$ F = \{f \colon (0,1) \to \mathbf R: f[(0,1)] \subseteq\{0,1\}, f^{-1}[\{0\}] \text{ is countable}\}$$
Then each $f \in F$ is measurable, the two closedness conditions are fulfilled, but $\inf F = 0 \not\in F$.

If you want $\inf F$ to be non-measurable, almost the same trick works. Let $A \subseteq (0,1)$ a non-measurable set, and set
$$ F' = \{f \colon (0,1) \to \mathbf R: f[(0,1)] \subseteq \{0,1\}, f^{-1}[\{0\}] \text{ is a countable subset of $A$}\} $$
Then both closedness conditions are fulfilled (because a countable union of countable subsets of $A$ is a countable subset of $A$), but
$$ (\inf F')(x) = \begin{cases} 0 & x \in A \\ 1 & x \not\in A \end{cases} $$
is non-measurable.


I need some help optimizing my database schema

Question: Here's a layout of my data:
Heading 1:
   Sub heading
   Sub heading
   Sub heading
   Sub heading
   Sub heading

Heading 2:
   Sub heading
   Sub heading
   Sub heading
   Sub heading
   Sub heading

Heading 3:
   Sub heading
   Sub heading
   Sub heading
   Sub heading
   Sub heading

Heading 4:
   Sub heading
   Sub heading
   Sub heading
   Sub heading
   Sub heading

Heading 5:
   Sub heading
   Sub heading
   Sub heading
   Sub heading
   Sub heading

These headings need to have a 'Completion Status' boolean value which gets linked to a user Id.
Currently, this is how my table looks:
id  |  userID  |  field_1  |  field_2  |  field_3  |  field_4  | etc...
-----------------------------------------------------------------------
1   |     1    |    0      |     0     |     1     |     0     |
-----------------------------------------------------------------------
2   |     2    |    1      |     0     |     1     |     1     |

Each field represents one Sub Heading. Having this many columns in my table looks awfully inefficient...
How can I go about optimizing this? I can't think of any way to neaten it up :/
Answer: Don't use boolean values but simple relations:
table completion_status
id user_id field_id

1  1       3
2  2       1
3  2       3
4  2       4
...

From that it's easy to see that user 1 has completed field 3, and user 2 fields 1, 3 and 4.
This way you don't have to change your database schema whenever you want to change the amount of fields.
Comment: I was using a similar method to begin with but the table ended up having 27 rows for the one user. This number will likely grow in the future. Is this not bad? Shouldn't I try to limit the table size as much as possible?
Comment: Yup. But this way, you only use the rows that have data - your way, you have lots of unused columns. Also, imagine having to add a new type - this way it's a blink of an eye - your way would involve changing the table and the queries.
Comment: i don't think having multiple rows for the same user is a problem. modern DBMS can handle millions of rows without issues. just make sure that you add proper indexes.
Comment: No, this is not bad, as long as you define proper indices. Have a look at [this Wikipedia article on first normal form](http://en.wikipedia.org/wiki/First_normal_form)
Comment: @Steffan, the amount of rows does not have any significance in your case. Actually this way you end up _saving_ space as in your example all users have all the fields defined either 0 or 1. With my proposed solution, users' fields will only take as much space as minimally required.
Comment: I'll change up my structure. Thanks for the help :}
Comment: @Steffan, don't forget to mark the answer accepted so others don't have to bother any more :)
Answer: You could have the sub-headings in a different table, and then link that table to the first table.
id  |  userID  |  field_id |
-----------------------------
1   |     1    |    0      |
-----------------------------
2   |     2    |    1      |

where table field looks like this
id  | field_1 | field_2   | etc..
-----------------------------
1   |     1   |    0      | etc..

Comment: That doesn't really change anything, just splits the data into two tables. The problem with too many columns still exists.
Answer: Why dont you make a table like this?
id  | User Id | Field ID | Status
---------------------------------
1   |   1     |   1      | 0
2   |   1     |   2      | 1

You can have another master table for Fields with the field names
Comment: No need for `status`, if the `field_id` exists, it's done, otherwise it's not.
Comment: Well, if you decide to add an "in-progress" status later, this will help. :)


Unbiased estimator for truncated poisson

Question: This is supposed to be a classic problem but I could not seem to find a solution anywhere.
Let $X$ be a random variable with zero-truncated Poisson distribution s.t. it's pmf is given by:
$f(x)=\frac{e^{-\theta}\theta^x}{(1-e^{-\theta})x!}$  $x=1,2...$
Find an unbiased estimator for $1-e^{-\theta}$
Comment: I tried a few things..couldn't get it (+1)
Comment: The answer is supposed to be absurd but analytically accurate. Specifically, 0 if X is odd and 2 if it is even. I still can't figure out how to make that happen though.
Comment: https://stats.stackexchange.com/q/544225/119261
Answer: The answer you have given in a comment is correct. I will show (I am lazy so I will let maple do the work). Let
$$
   T(x)=\begin{cases}   0 &\text{if $x$ is odd}\\
                        2 &\text{if $x$ is even}
        \end{cases}
$$ be an estimator. We will show it is unbiased. The maple code is below:
<code>f := x -> exp(-theta)*theta^x/( (1-exp(-theta))*factorial(x) )
ans := sum( f(2*k)*2, k=1..infinity ) assuming theta>0;
                          -2 + 2 cosh(theta)
                   ans := ------------------
                            exp(theta) - 1
ans := convert(ans, exp)
                     -2 + exp(theta) + exp(-theta)
              ans := -----------------------------
                            exp(theta) - 1
</code>
which gives the expectation as
$$
{\frac {-2+{{\rm e}^{\theta}}+{{\rm e}^{-\theta}}}{{{\rm e}^{\theta}}-
1}}
$$
and this you can now simplify yourself to see that it is $1-e^{-\theta}$.  So we have found an unbiased estimator. And it is really absurd, since it can be only 0 or 2 so is extremely unhelpful. Now the real work would be to show there is no other unbiased estimator!


E[X| X>Y] for independent X, Y ~ N(0,1)

Question: I am looking for conditional expectation $E[X| X>Y]$ for independent $X, Y \sim N(0,1).$ I just showed that $P(X\leq a | X>Y) = \Phi(a)^2$, where $\Phi(a)$ is CDF for Normal$(0,1)$, but I don't know how to compute integral in order to obtain expected value.
Comment: This is simply $E(\max(X,Y))$ which is easy to find as the distribution of $\max(X,Y)$ is easy to find.
Answer: Rewriting and using linearity of expectation,
$$
E[X | X > Y] = E[X | X - Y > 0] = E[X - Y | X - Y > 0] + E[Y | X - Y > 0].
$$
Define now $X' = -X, Y' = -Y$. Then
$$
E[Y | X - Y > 0] = E[-Y' | Y' - X' > 0] = -E[Y' | Y' - X' > 0].
$$
However, note that $Y', X' \sim X, Y$, so we have $E[Y' | Y' - X' > 0] = E[X | X - Y > 0]$. Inserting back, then,
$$
E[X | X > Y] = E[X - Y | X - Y > 0] - E[X | X > Y],
$$
implying that
$$
E[X | X > Y] = \frac{E[X - Y | X - Y > 0]}{2}.
$$
Finally, note that $X - Y$ is a a normal R.V. with mean 0 and variance 2, so $E[ X - Y | X - Y > 0]$ is easy to find.

E[X| X>Y] for independent X, Y ~ N(0,1)


How can I be notified of a bluetooth connection when the iOS app is backgrounded in Xamarin?

Question: We need our app to receive notifications from the OS when the connects or disconnects from a bluetooth audio device (specifically, the one in their car).
The app gets notified when the BT device initially connects, but it then immediately seems to disconnect and logs the error:

BTCentralManager::DisconnectedPeripheral > SoundCore mini(ATT)
  ERROR Error Domain=CBErrorDomain Code=7 "The specified device has disconnected from us."

...and the "DisconnectedPeripheral" event is never actually fired.
We're unsure how to simply receive connect and disconnect events while the app is backgrounded.
Do we need to connect the peripheral with the central manager? We only need to know if the audio device is connected or not - we don't need to interact with it in any way.
The events never call a second time from the background, after getting the disconnect peripheral.  Presumably because of the error message we are receiving.
Sample code below:
<code>public class BTCentralManager : CBCentralManagerDelegate
{
    public CBCentralManager centralManager;
    public static CBPeripheral peripheral;

    public BTCentralManager()
    {
        System.Diagnostics.Debug.WriteLine("BTCentralManager::Constructor > ");

        centralManager = new CBCentralManager(this, new DispatchQueue("myqueue"),
            new CBCentralInitOptions { ShowPowerAlert = true, RestoreIdentifier = "myRestoreIdentifier" });

        NSUuid[] arr = { new NSUuid("7e9002be-547f-42bc-8d56-209736f70aa2") }; //Sound core mini

        var devices = centralmanager.retrieveperipheralswithidentifiers(arr);
        peripheral = devices.firstordefault();

        //is the only way to trigger the events, we need to first connect the peripheral to central manager???
       centralManager.connectPeripheral(peripheral, new PeripheralConnectionOptions
       {
           NotifyOnConnection = true,
           NotifyOnDisconnection = true,
           NotifyOnNotification = true
       });

    }

    //Always is triggered inclusive in background
    public override void UpdatedState(CBCentralManager central)
    {
        System.Diagnostics.Debug.WriteLine("BTCentralManager::UpdatedState > " + central.State.ToString());
    }

    //Only is triggered when the device is first time connected  ( Inclusive in background)
    public override void ConnectedPeripheral(CBCentralManager central, CBPeripheral peripheral)
    {
        System.Diagnostics.Debug.WriteLine("BTCentralManager::ConnectedPeripheral > " + peripheral.Name);

        //After the connect made successfully I receive this error, and never connect again to the device
        //Error Domain=CBErrorDomain Code=7 "The specified device has disconnected from us."
    }

    public override void DisconnectedPeripheral(CBCentralManager central, CBPeripheral peripheral, NSError error)
    {
        System.Diagnostics.Debug.WriteLine("BTCentralManager::DisconnectedPeripheral > " + peripheral.Name + " ERROR>" + error.Description);
    }

    public override void DiscoveredPeripheral(CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI)
    {
        System.Diagnostics.Debug.WriteLine("BTCentralManager::DiscoveredPeripheral > " + peripheral.Name);
        //   base.DiscoveredPeripheral(central, peripheral, advertisementData, RSSI);
    }
}
</code>
Answer: as far as I understand your question, you need to observe the availability of a bluetooth audio device. I had some investigations in this a couple of time ago and the result was not really satisfying me. Here's my conclusion:
1.) CoreBluetooth is intented to be used for Bluetooth 4.0 / Bluetooth Low Energy devices only. Many Bluetooth headphones or even car radios are still not bluetooth 4.x. So, unless you can rely on your user's bluetooth audio device to be 4.x, CoreBluetooth might be a waste of time.
2.) Your app wont be notified about a audio device being connected when your app is in background.
So far no good. But, there might be some approaches that may help.
1.) By using the CLLocationManager, you may start observing e.g. the compass (not the location to save battery) to get notified whenever the phone has been moved. Simply check the connected audio devices when the app is calling the CLLocationManagerDelegate. This is of course not very efficient, but it might work.
2.) use iBeacons and CLBeaconRegions if available. Place an iBeacon in the user's car and start observing the beacon.
I know, this is not exactly what you want to hear, but I'm afraid there's no straight forward solution for your problem.
cheers,
Peter


Can statistics be used to answer the following question?

Question: Suppose I am an inactive person - I go for a walk on average a few times a .month (e.g. every day there is a 5% chance I go for a walk, independent of yesterday) . However, each time I go for a walk, I meet this man with a red hat.

Can statistics be used to infer that this man walks more often than I do? Or perhaps his walks are also decided by a random process? Knowing that I go on such few walks but still see this man each time, it seens more likely that he walks more often than me?

Suppose I go for walks every Sunday and still see this man. Is it more logical for me to believe that this man might have a busy schedule (a schedule similar to mine, e.g. we both work 6 days a week) and simply prefers to only walk on Sundays? (I.e. the other days of the week he doesn't walk)

Thanks
Answer: Statistics can absolutely be utilized for these scenarios
1)
Assuming independence of walking schedules (Man is not more likely to be walking if you are).
Probability you go for a walk on any day = $P_{you}$
Probability man in red hat goes for a walk on any day = $P_{red}$
Your hypotheses would be:
$H_{0}: P_{red} = P_{you}$
$H_A: P_{red} > P_{you}$
There are a few tests you could perform here, but logically, the likelihood of the man in the red hat walking on the same day as you each time when his probability of going for a walk is also 0.05 is very small.
This can be demonstrated using the binomial distribution:
(All calculated under null hypothesis...)

$p_{\text{both walking}} = 0.05 * 0.05 = 0.025$
$p_{\text{at least 1 person isn't walking}} = 0.975$
Number of days you go for a walk = n
Number of days you see man in red hat while walking = x

$f(n,x) = ({n \atop x})0.025^{x}0.975^{n-x}$
As you can see, as the amount of days you walk increases (assuming you see man in red hat each day), the likelihood of this happening is extremely small. So we can infer the man's probability of walking any given day is higher than 0.05
2)
In this scenario, I'm unclear on what exactly you're looking to prove, given you only observe Sundays. If you could be more specific in the theoretical behavior of the man in the red hat, we could probably use similar tests for your assumptions.

Are we assuming the man in the red hat still has some probability of walking any day of the week?

Are we assuming the man only walks once a week, and trying to figure out if he walks the same day each week or a random day?

Hope this helps
Comment: It's critical to lay out the assumptions underlying any statistical test, which in the first case is *independence* of the two people's walking schedules. If the man in the red hat is a stalker who follows you everywhere, the fact that you see him every time you leave the house does not indicate that he walks any more than you do; it instead indicates that his walking schedule is *not independent* of yours.
Comment: @NuclearHoagie you're absolutely right, I inferred independence from their question, I'll add that assumption to my answer


Minimizing distance of circles from points without overlapping

Question: I am designing a user interface, and I have encountered the following problem:
I have $p_1 ... p_n$ points in $\mathbb{R}^2$, and $c_1 ... c_n$ circles with constant $r$ radius. I want to minimize the distance of the $c_i$ circle's center and $p_i$ with the constraint that the circles can not overlap.
Is there a fast algorithm for that? I don't need an exact solution, but a fast one.
Comment: So the $p_i$ are fixed and you want to optimize over the location of the circles' centers?
Comment: Yes, the points are fixed.
Comment: Have you tried formulating the problem as a [SOCP](http://en.wikipedia.org/wiki/Second-order_cone_programming)? I am not sure that it is; just wondering if you've already looked at it.
Answer: This problem belongs to the family of the circle packing problems. In general is hard to solve to global optimality, but finding a feasible solution might not be that hard.
http://www.packomania.com/
Could you specify more what do you mean for "minimize the distance of the ci circle's center and pi"?
Moreover, I guess It cannot be formulated as SOCP due to the non overlap constraints:
|| c_i - c_j||_2 >= 2r
You can find some SOCP relaxation, not very tight usually.
UPDATE

Following the comment the model might be
$min \sum_i || c_i - p_i||^2$
$s.t. || c_i - c_j||_2 >= 2r \quad  \forall i<j$
This is difficult. If you constraints on the region in which the centers can be located, it might even be unfeasible. Otherwise, assuming r is small enough, and you don't really need the global optimum, you might just random generate the centers in a box containing the p_is and run a local search to get a feasible solution.
If you look for some more advanced, I suggest you to google for "circle packing" or "network sensors localization".
Comment: I want the circles to be as close to the fixed points as possible without overlapping.
Comment: ok...something like sum ||c_i - p_i||2 ?
Comment: Yes, exactly...


Can't Display Captured Image to an other Activity, how to make it work?

Question: I want to capture an image from custom camera and then display it on an other activity where i can add other png emoticons, i have this code but it doesnt show any photo after activity launches
Answer: Please see some changes which i have done in your code.
1. please call new Intent after taking photo and the pass the filepath as i do.
MainActivity :
<code>  ImageView mCaptureButton = (ImageView) findViewById(R.id.button_capture);
        mCaptureButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // get an image from the came
                        mCamPreview.captureImage(MainActivity.this);
    //starting(); // don't call Intent here
            }
        });

    }
</code>
CameraPreview class:
<code>private Activity _activity ;
    public void captureImage(Activity activity){
this._activity = activity;
    mCamera.takePicture(null, null, mJpegCallback);
}

PictureCallback mJpegCallback = new PictureCallback() {
    @Override
     public void onPictureTaken(byte[] data, Camera camera) {
        final Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

        // Store bitmap to local storage
        FileOutputStream out = null;
        try {
            // Prepare file path to store bitmap
            // This will create Pictures/MY_APP_NAME_DIR/
            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "AVORI");
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    Log.d(TAG, "failed to create directory");
                    return;
                }
            }

            // Bitmap will be stored at /Pictures/MY_APP_NAME_DIR/YOUR_FILE_NAME.jpg
            String filePath = mediaStorageDir.getPath() + File.separator + "Av.jpg";
            out = new FileOutputStream(filePath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
//call EditPicture.class here
 Intent i = new Intent(_activity, EditPicture.class);
    i.putExtra("FILE_PATH", filePath );
startActivity(i);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
};
</code>
Comment: it shows me error when i put intent there, any idea ?
Comment: What error it shows?
You need to pass CameraPreview.this as context
Comment: it shows the Constructor Intent (CameraPreview class) is undefined, i tried with CameraPreview.this, EditPicture.class
Comment: Again it shows me error at both in the Main Activity, and in Camera Preview,
in Camera Preview i did this,
protected MainActivity mActivity;

Intent i = new INtent (mActivity, EditPicture.class); etc...

but it shows me error on both sides, sorry to be such an annoying but i just have no idea what's going wrong , could you please try again to help me ?
Comment: Use this Activity mActivity; Intent i = new INtent (mActivity, EditPicture.class);
and have you did this    public void captureImage(Activity activity){
this.mActivity= activity;
    mCamera.takePicture(null, null, mJpegCallback);
}
Comment: i forgot to say that, it shows me error at the StartActivity(i), it shows me the method startActivity(intent) is undefined for the type new Camera.PictureCallback,!
Comment: mActivity.startActivity(intent);
Try this
Comment: i tried, it captures the image, but stops there, i can see the capture button on screen, , so hard to get it work, what is going wrong ?
Comment: No, there;s no any error, the code in logcat is yellow, that's all,
Comment: So what you wanna do after captured?
Comment: to display it in an other activity, as a preview and to add png emoticons over it, like smile, sad, this things, but to be previewed like it is in snapchat after capture it shows how many seconds to display ,, put text this things,  i want a simillar preview window where i can add emoticon


Converter milhões de STRING para INT - JavaScript

Question: Tenho uma string 123.456.789 e ao usar parseInt está retornando 123456, como fazer para para retornar 123456789 ?
Comment: Retire os pontos com replace.
Comment: Provavelmente ele está considerando o último ponto como ponto decimal e daí quando você converte para inteiro ele despreza a parte decimal ficando apenas a parte inteira.
Answer: Neste exemplo, primeiro fiz a formatação, removendo o pontos, em seguida fiz a conversão.

var numeroFormatado = `123.456.789`.replace(/\./g, ``)

numero = parseInt(numeroFormatado)

console.log(numero)
Comment: Exatamente, o ultimo ponto é visto como casa decimal na língua inglesa


I know the values of $P(A)$, $P(B)$, and $P(A \cup B)$, is this enough to find $P(A^c \mid B^c)$?

Question: $$ P(A) = .72, \qquad
P(B) = .6, \qquad
P(A \cup B) = .9 $$
I've tried to reason through this, but I don't know how to work out the conditional probability of complements $P(A^c \cap B^c)$. The farthest I got was this conditional probability $P(A \mid B)$.
Comment: @Tim I'm looking for a pointer in the direction of how to apply the complements rule in reasoning through to the conditional probability I'm searching for. I don't need the answer nor do I want it, just a hint, after having stared at this issue for over an hour.
Comment: @gopher The $^c$ notation for -complement is perfectly valid and widely enough used that it should be understood by anyone that has read more than one or two books on the subject. I think it would be ridiculous to impose one single notation when there are many in use. If I recall correctly there are at least five notations for complements. There's *no need whatever* to change it, though - as usual with notations that vary from book to book and course to course - it's best to define your notation in your question.
Comment: Yes, I used it to indicate the complement. Is there a notation that's preferred on Cross Validated?
Comment: The usual notation is $P(\neg A)$ which you get with `P(\neg A)`.
Comment: By far the most common notation is $A^c$ for the complement of the event $A$.  I hope you don't mind me editing the post to avoid confusion.
Comment: does this help?  $P(\neg A | \neg B) \cdot P(\neg B) = P( \neg A \neg B)$
if you're already there, do you know how $P( \neg A \neg B)$ relates to $P( A \cup B)$?
Answer: Remember DeMorgan's laws.  Namely, $A \cup B = (A^c \cap B^c)^c$ and so $P(A \cup B) = 1 - P(A^c \cap B^c)$.


Tagging for blogs?

Question: Is there a simple way to add the ability to add 'tags' to blog entries in Drupal?
Maybe I need to add a module for this functionality?
Comment: Have you tried to do with taxonomy module ?
Answer: Follow below instruction to enable tags on blogs.

Login using admin credentials.
Go to admin/structure/types/manage/blog/fields
Add Tags field by selecting "Select a Type Fields" as "Term Reference" and widget type as "Autocomplete term widget (tagging)"
Click on Save.
Select Vocabulary as Tags which comes with Drupal Core in next screen.
Click on Save Field Settings.
Click on Save Settings in next screen.

That's it !

Tagging for blogs?


Are there any methods to improve ability to hear multiple lines in your head?

Question: Over the summer I worked my way through Fux's strict counterpoint and am trying to write fugues without the aid of any instrument or computer.  I have some ear training up to the point where I can hear and sing a modulating melody in my head upon first sight relatively well, but composing multiple lines for me essentially boils down to hearing both lines separately and hoping they sound good together.  I can manually check the implied harmonies of each interval, but ideally I would like to improve my ability to hear multiple lines at once.
Does anyone know of a method to improve your ability to hear multiple lines in your head?
Answer: Practice, practice, practice.
The most effective sort of practice for me is to practice with two-voice counterpoint by playing one line while singing the other.  Then switch.  Then move on to three voices, and so on.  Sometimes I'll sing the viola part of an orchestral piece, singing along with a recording, then I'll go back to the beginning and sing the second violin part while also following the viola part.
But for starters, just try a simple round like Row, Row, Row Your Boat, Three Blind Mice, or Frère Jacques.  How many voices can you play along with yourself as you sing one voice?
Start by emphasizing singing aloud rather than in your head.  The ability to hear it in your head without singing aloud will follow if you cultivate it.


Converter loops aninhados em função recursiva para computar combinações

Question: Fiz uma função para computar todas as combinações de um array. O problema da minha abordagem é que ela só "gera" combinações de três dígitos (comprimento do array do valor passado ^ 3), já que tenho 3 laços aninhados. Se eu quiser, no entanto, que ela gere valores com 4 dígitos, teria que aninhar mais um loop.
Há algum meio de criar essa mesma função, mas de forma recursiva, de modo que eu consiga passar um argumento especificando o número de caracteres?
O resultado esperado é um array de comprimento L ^ N, sendo L o comprimento do array passado e N o número de caracteres por combinação.

const data = ['a', 'b', 'c'];

function all(data) {
  const final = [];

  for (const c1 of data) {
    for (const c2 of data) {
      for (const c3 of data) {
        final.push(c1 + c2 + c3);
      }
    }
  }

  return final;
}

const x = all(data);
console.log(x.length, ':' , x);
Comment: mano da uma olhadinha nesse código aqui, talvez dê clareada na sua ideia https://www.devmedia.com.br/permutacoes-de-objetos-um-algoritmo-recursivo-em-java/27512
Answer: Você pode utilizar a recursão para passar como parâmetro o último array gerado até chegar no tamanho desejado:

const montar = (opcoes, calculado = []) => {
  // Verifica o critério de parada, que neste caso é já ter preenchido todas as posições do array
  if (opcoes.length === calculado.length) {
    return [calculado];
  }

  let novos = [];

  // Percorre as opções para preencher no final do array que foi dado
  for (const possivel of opcoes) {
    // Chama a mesma função novamente passando o opção do for como complemento ao array inicial
    const complementos = montar(opcoes, [...calculado, possivel]);
    // Concatena os novos compelementos a list previamente calculada
    novos = [...novos, ...complementos];
  }

  return novos;
};

console.time('Calculando');
console.log(montar(['a', 'b', 'c', 'd']));
console.timeEnd('Calculando');
Answer: Podes criar arrays usando matemática para gerar as combinações. Um exemplo seria assim, usando o facto de as combinações possíveis ser comprimento da array elevada ao mesmo numero:

const all = (arr) => {
  const length = arr.length;
  const total = Math.pow(length, length);
  const entry = Array.from(new Array(length));

  return Array.from(new Array(total)).map((_, i) => {
    return entry.map((_, j) => {
      const index = Math.floor(i / Math.pow(3, j)) % length;
      return arr[index];
    });
  });

}

const data = ['a', 'b', 'c'];
const x = all(data);
console.log(x.length, ':', JSON.stringify(x));

Outra variante, mais à medida do tipo de lógica que pedes na pergunta seria:

const all = (original) => {
  const loop = (depth, acum = [], ...prev) => {
    if (depth === 0) {
      acum.push([...prev]);
      return acum;
    }

    for (let i = 0; i < original.length; i++) {
      loop(depth - 1, acum, ...prev, original[i]);
    }
    return acum;
  }
  return loop(original.length);
}

const data = ['a', 'b', 'c'];
const x = all(data);
console.log(x.length, ':', JSON.stringify(x));
Answer: Esse é possivelmente o o código mais feio e ineficiente que eu já fiz. Não o vote como correto.
Mas de qualquer forma, aqui está uma sugestão.

function all(data, len) {
  if (!len) return [];
  if (len === 1) return data;
  return recursao(data, len, data).sort();
}

function recursao(data, len, carry) {
  const arr = data.map(_ => [...carry]);

  for (let i = 0; i < data.length; ++i)
    for (let j = 0; j < arr[i].length; ++j)
      arr[i][j] += data[i];

  const final = arr.flat();
  return len > 2 ? recursao(data, len - 1, final) : final;
}

console.log(all(['a', 'b', 'c', 'd'], 2));
console.log(all(['a', 'b', 'c'], 3));
console.log(all(['a', 'b'], 4));


Why js click is not working except first click

Question: I want to change icon with every click. This code is worked But just first click. With every click after the first click, nothing happens. If i delete the if & else the click is work with every click. What is the problem ?
@foreach (var item in Model)
            {

                                    @if (item.Document == true)
                                    {

Document

                                    }

$ @String.Format(new CultureInfo("hr-HR"), "{0:# ##0}", item.Price)

            }

Answer: In your event handler, you replace the element for which the click handler is defined by setting the .innerHtml property of the parent element. The html fragment is parsed and integrated into the DOM but that does not preserve the event handler definitions associated with the original element.
Change your event handler to
this.classList.toggle("fas");
this.classList.toggle("far");

This toggles both classes on the i element with each click which is equivalent to switching between those classes on each click. Other classes (ie. fa-heart) are not affected. No modification of the DOM structure is necessary.
Ref:

MDN: Web API - classList
MDN: Web API - DOMTokenList
Comment: Thanks. This is worked. But i can't understand one thing. Why my method is not working. What was wrong ?


Wordpress - MySQL query to show posts only from a specific category

Question: I have the following query that bring the posts that contain a specific word in the title
SELECT posts_post.ID AS post_ID,
       posts_post.post_date AS post_post_date,
       CONCAT('',posts_post.post_title,'') AS post_title_with_link_to_post
FROM wp_posts AS posts_post
WHERE 1=1
  AND posts_post.post_title LIKE '%HOTARAR%'
  AND posts_post.post_type = 'post'
GROUP BY post_post_date

The problem now is that I need to bring the posts only from a specific category (tag slug for the category is hotarari-consiliu-local and has the ID 160), how could I modify the above query to bring posts only from a single blog posts category? Thanks!
Comment: Note that in the absence of any aggregating functions, a GROUP BY clause is never appropriate
Comment: @Strawberry - could you help me modify the query from first post to extract from only a single category? I would really appreciate it
Answer: Try the below query.
global $wpdb;
$make = $wpdb->get_results("
    SELECT * FROM
        $wpdb->posts
    LEFT JOIN
        $wpdb->term_relationships
    ON
        ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
    LEFT JOIN
        $wpdb->term_taxonomy
    ON
        ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
    WHERE
        $wpdb->posts.post_type = 'post'
    AND
        $wpdb->posts.post_title LIKE '%HOTARAR%'
    AND
        $wpdb->term_taxonomy.taxonomy = 'category'
    AND
        $wpdb->term_taxonomy.term_id = 160
    ORDER BY
        post_date DESC
");

Comment: Thanks a lot for the help @Bhautik. The thing is I am using wpdatatables plugin, and I need to have the query formatted like this [https://i.ibb.co/KzxvCDw/wpdatatables.png]
Comment: Will try again, should be ok now - https://i.ibb.co/KzxvCDw/wpdatatables.png . It will only work if I modify the query from initial post above.
Comment: This is an INNER JOIN
Answer: Assuming Bhautik is on the right path, then something like this should work (I don't know where 'hotarari-consiliu-local' belongs in this).
   SELECT p.ID post_ID
        , p.post_date post_post_date
        , CONCAT('',p.post_title,'') post_title_with_link_to_post
     FROM wp_posts p
     JOIN wp_term_relationships pt
       ON pt.object_id = p.ID
     JOIN wp_term_taxonomy t
       ON t.term_taxonomy_id = pt.term_taxonomy_id
    WHERE p.post_type = 'post'
      AND p.post_title LIKE '%HOTARAR%'
      AND t.taxonomy = 'category'
      AND t.term_id = 160
    ORDER
       BY  post_date DESC

Comment: Thanks @Strawberry, did the necessary changes to match the database prefix but i get this `Rendered query: SELECT p.ID post_ID, p.post_date post_post_date, CONCAT('',p.post_title,'') post_title_with_link_to_post FROM wpo8_posts p INNER JOIN wpo8_term_relationships pt ON pt.object_id = p.ID INNER JOIN wpo8_term_taxonomy t ON t.term_taxonomy_id = pt.term_taxonomy_id WHERE p.post_type = 'post' AND t.taxonomy = 'category' AND t.term_taxonomy.term_id = 160 ORDER BY post_date DESC LIMIT 10
MySQL said: Unknown column 't.term_taxonomy.term_id' in 'where clause'`
Comment: OK. Edited accordingly
Comment: That's it! Thanks for the help @Strawberry and Bhautik


Field API - which hook to use?

Question: I have successfully created a field with my module and managed to show it on user registration form. The next step would be validating my field. There are two hooks for this, and I'm confused as to which one to use. One is hook_field_validate and the other is hook_field_attach_validate. I'm also confused as to how to refer to the field. $instance['user']['field_tckn_no']? (This is what dpm(field_info_instances('user') shows me. Also, one thing that confuses me is that hook_field_validate iterates over the fields but all I have is one field. Is it still the one to use?
Regards,
K.
Comment: http://drupal.stackexchange.com/q/8336/1899
Comment: Can you explain in a little more detail how you defined this field and added it to the user entity? Can you share the relevant code you've written so far?
Comment: @marcvangend I've used field_create_field to create the field I've defined, and field_create_instance to attach it to 'user' entity. My .install file is at http://ur1.ca/i4zvi and my .module at http://ur1.ca/i4zxz. I didn't paste them here worried about how to format them.
Comment: Many apologies for my previous answer (now deleted) my understanding of the question was well off.
Comment: No problem at all, it happens :)
Comment: I've just tried a `dpm($entity)` in `hook_field_attach_validate` implementation, and it didn't get picked up when I filled the values in, and hit `Apply for an account`. Am I doing something horribly wrong?
Answer: Well, at last I was able to figure it out. Since the field was part of the form after creating the instance, I thought I could use hook_form_alter, and I was right!

Field API - which hook to use?


java usage of equals and hasNext

Question: why does this code doesn't stop? Aren't "scanner.equals(null)" and "scanner.hasNext() == false" the same or at least same role??
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int i = 1;
        while(true) {
            if(scanner.equals(null))
                break;
            else {
                String line = scanner.nextLine();
                System.out.println(i + " " + line);
                i++;
            }
        }
    }
}

Comment: The scanner is only equal to null if it wasn't created in the first place.
Comment: even if there is absolutely no input in next line??
Answer: scanner.equals(null) will always return false. It checks if an object instance is null, and it's not. In comparison, scanner.next() checks if the scanner can find a token.
Anyway, you are using the nextLine method, so you should be using hasNextLine, not hasNext:
    while(scanner.hasNextLine()) {
        String line = scanner.nextLine();
        System.out.println(i + " " + line);
        i++;
    }

Comment: Okay so that means if I want scanner.equals(null) to be true, there should be the null existing in next line?
Comment: No. `scanner.equals(null)` will **never** be true.

java usage of equals and hasNext


Remote communication with private docker registry issues

Question: I have set up the registry server as below:
docker run -d --name p_registry -e SETTINGS_FLAVOUR=local -e STORAGE_PATH=/reg_storage -v /data/private-registry/storage:/reg_storage -p 5000:5000 registry

So, now I can push to this registry locally using
docker push localhost:5000/hello:tag1

But when I tried to push it from another machine, to this registry, it bails out:
docker push 18.104.22.168:5000/hello:tag1

Error: Invalid registry endpoint https://188.8.131.52:5000/v1/: Get https://18.104.22.168:5000/v1/_ping: EOF. If this private registry supports only HTTP or HTTPS with an unknown CA certificate, please add `--insecure-registry 188.8.131.52:5000` to the daemon's arguments. In the case of HTTPS, if you have access to the registry's CA certificate, no need for the flag; simply place the CA certificate at /etc/docker/certs.d/18.104.22.168:5000/ca.crt

Now, after that I tried various other options:
Edit /etc/sysconfig/docker
other_args=--insecure-registry=188.8.131.52:5000

And then restarted docker using "service docker restart". This didn't work either. Every time, I tried to push, it gave me the invalid registry endpoint.
I even tried doing as below:
vi /etc/default/docker
DOCKER_OPTS="$DOCKER_OPTS --insecure-registry=18.104.22.168:5000"

even the one above gives the endpoint error.
Can somebody help here ?
Ref: Remote access to a private docker-registry
Answer: sudo service docker stop
sudo docker -d --insecure-registry 184.108.40.206:5000

This worked for me . Please try it and let us know.
Comment: Here is the reason, why it was not working before. I was adding DOCKER_OPTS on the Docker registry server and not the deamon/client. It works fine if I update the /etc/sysconfig/docker file with other_args=--insecure-registry=184.108.40.206:5000 and restart the docker service or when I run `sudo docker -d --insecure-registry 18.104.22.168:5000` on the docker client/daemon.
Comment: Error 1:
I think my issue is more related to the iptables rules. Have you made any changes there ??
Error 2:
Also, I am getting an EOF error:
FATA[0002] Error: Invalid registry endpoint https://18.104.22.168:5000/v1/: Get https://188.8.131.52:5000/v1/_ping: EOF
Error 3:
After getting error 2, I added the ip to the /etc/hosts on the docker host. If I try "docker push docker:5000/test" it tries to use https and if I try "docker push docker/test", it is asking me for a username and password. Is this expected ??
Comment: I have found out that the initial command specified...... docker run -d --name p_registry -e SETTINGS_FLAVOUR=local -e STORAGE_PATH=/reg_storage -v /data/private-registry/storage:/reg_storage -p 5000:5000 registry .......... had only -p 5000:5000(this serves as localhost) Please run using -p 18.104.22.168:5000:5000 Before doing this please restart docker with the commands which i have specified above. Also while pushing use docker push 126.96.36.199:5000/test.When you are try to use "docker push docker/test" it is asking username and password as it is trying to push image "docker/test"in the public domain
Answer: DOCKER_OPTS="--insecure-registry 188.8.131.52:5000" should work
Comment: I think your answer could be true. The issue that I later realized were with the network itself, I was not able to telnet to 5000 on 22.214.171.124 from the machine which was pushing the image. I am going to try something tomorrow and will provide an update.
Comment: Here is the reason, why it was not working before. I was adding DOCKER_OPTS on the Docker registry server and not the deamon/client. It works fine if I update the /etc/sysconfig/docker file with other_args=--insecure-registry=184.108.40.206:5000.


react.js can't import component

Question: i'm trying to export a component using export default project; and importing using
import project, {toggleCattegories} from './project';
i get the following warning:

./src/components/projecten.js
  Line 2:8:  'project' is defined but never used  no-unused-vars

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.

project.js code:
import React, { Component } from 'react';
import { Card, CardTitle, CardActions, Button, CardText } from 'react-mdl';

class project extends Component{

constructor(props) {
    super(props)
    this.state = { activeTab: 0 };
}

        toggleCategories() {
    if (this.state.activeTab === 0) {
        return (

                {/*Web*/}
                <Card shadow={5} style={{ minWidth: '450', margin: 'auto' }}>
                    <CardTitle style={{ color: '#000', height: '176px', background: 'url(https://miro.medium.com/max/3600/1*HSisLuifMO6KbLfPOKtLow.jpeg) center / cover' }}></CardTitle>

                    <CardText>
Mijn Portfolio

Mijn Portfolio heb ik in ReactJs geschreven. Bekijk het project op github via de button onder deze tekst.
</CardText>
                    <CardActions border>
                        <Button colored style={{ width: "100%" }}>Github</Button>
                    </CardActions>

                </Card>

                <Card shadow={5} style={{ minWidth: '450', margin: 'auto' }}>
                    <CardTitle style={{ color: '#000', height: '176px', background: 'url(https://miro.medium.com/max/3600/1*HSisLuifMO6KbLfPOKtLow.jpeg) center / cover' }}> </CardTitle>
                    <CardText>
Boodschappenlijst

In de applicatie meld je je via je google account aan en kun je een boodschappenlijstje opzetten. De objecten worden opgeslagen in een firebase database.
</CardText>
                    <CardActions border>
                    <Button colored style={{ width: "100%" }}>Github</Button>
                    </CardActions>

                </Card>

        )
    } else if (this.state.activeTab === 1) {
        return (

{/*Java*/}
                <Card shadow={5} style={{ minWidth: '450', margin: 'auto' }}>
                    <CardTitle style={{ color: '#000', height: '176px', background: 'url(https://www.biernet.nl/images/brouwerij/55296-Bavaria%20logo.jpg) center / cover' }}></CardTitle>

                    <CardText>
Bavaria Cashback

Tijdens mijn werkzaamheden bij Acorel Commerce in Alkmaar, heb ik met trots mee mogen werken aan het actieplatform van Bavria. Deze web-app is gebouwd in Java.
</CardText>
                    <CardActions border>
                        <Button colored style={{ width: "100%" }} >Website</Button>
                    </CardActions>

                </Card>

        )
    }
    else if (this.state.activeTab === 2) {
        return (

{/*Python*/}
                <Card shadow={5} style={{ minWidth: '450', margin: 'auto' }}>
                    <CardTitle style={{ color: '#000', height: '176px', background: 'url(https://indigo.amsterdam/wp-content/uploads/2017/05/python-django-logo-1024x576.jpg) center / cover' }}></CardTitle>

                    <CardText>
Foodify

Foodify is een schoolproject gebouwd voor het vak Praktijkvaardigheden 2. Deze applicatie is gebouwd zodat mensen die te veel hebben gekookt en mensen die niet hebben gekookt elkaar tegemoetkomen. Het doel is om voedselverspilling te voorkomen.
</CardText>
                    <CardActions border>
                        <Button colored style={{ width: "100%" }} >Github</Button>
                    </CardActions>

                </Card>

        )
    }
    }

}

export default project;

projecten.js code:
import React, { Component } from 'react';
import Project, {toggleCattegories} from './project';
import { Tabs, Tab, Grid, Cell, Card, CardTitle, CardActions, Button, CardText } from 'react-mdl';

class Projecten extends Component {
    constructor(props) {
        super(props)
        this.state = { activeTab: 0 };
    }

    render() {
        return (

                <Tabs activeTab={this.state.activeTab} onChange={(tabId) => this.setState({ activeTab: tabId })} ripple>
                    <Tab>Html / Css/ ReactJS</Tab>
                    <Tab>Java</Tab>
                    <Tab>Python / Django</Tab>
                </Tabs>

                <Grid>
                    <Cell col={6} hidePhone="true" hideTablet="true" >

 <toggleCattegories/>

                    </Cell>

                </Grid>

                <Grid>
                    <Cell col={2} phone={6} hideDesktop="true" hideTablet="true" >

{this.toggleCategoriesMobile()}

                    </Cell>

                </Grid>
                <Grid>
                    <Cell col={6} tablet={8} hideDesktop="true" hidePhone="true" >

{this.toggleCategoriesTablet()}

                    </Cell>

                </Grid>

        )
    }
}

export default Projecten;

Thank you for your help!
Comment: Point number 2, not relevant to your error message but worth for you knowing: by convention, all react components must start with a capital letter.
Comment: It's because it's "defined but never used" just like the error says. If you don't need it, remove it.
Comment: i am using it , i'm trying to render the imported component using
Comment: You aren't using "project" which is what the error states. It's an unused import, remove it. Do **exactly what the error message tells you to do**.
Comment: i think you don't understand what the problem is in the code. i want to use "project" by rendering an component from "project.js" but it doesn't work.
Comment: The confusion is arising from your code being incomprehensible. What is `toggleCategories`? Right now it is a method on the `project` component, by looking at your code, `toggleCategories` is not a component itself, nor can it be accessed by anything that is not the `project` component. What do you actually want to do?
Answer: You are not using Project correctly.
You have a toggleCategories function that should be renamed to render. Class components must have a render function that returns the JSX.
Once you have renamed the above, you no longer import { toggleCategories }, you only need to import Project and where you have <toggleCategories />, replace it with <Project />
Comment: If i use render instead of the toggleCategories, the constructor doesn't work.
Comment: Apologies for the crappy formatted answer, I'm on my phone :D feel free to upvote and accept if it solved your issue ;)
Comment: Thank you for your help , but If i use render instead of the toggleCategories, the constructor doesn't work.
Comment: What do you mean the constructor doesn't work?
Comment: in 'project.js' i have an constructor with a state that sets the activeTab. When i only render the toggleCategories function, the activeTab doesn't work anymore.
Comment: You shouldn't have a toggleCategories function, it should be `render`. It doesn't make sense to me why you have state in Project component because it never gets updated. You only ever seem to update the state of the `Projecten` component. State is specific to a single component, it is not shared between components

react.js can't import component


Is there a way to use type-level pattern matching rather than defining a type family

Question: Consider the following 3 Haskell files
HList.hs
{-# LANGUAGE DataKinds     #-}
{-# LANGUAGE GADTs         #-}
{-# LANGUAGE PolyKinds     #-}
{-# LANGUAGE TypeOperators #-}
module HList where

data HList :: (k -> *) -> [k] -> * where
  Nil :: HList f '[]
  (:&) :: !(f x) -> HList f xr -> HList f (x ': xr)

Snd.hs
{-# LANGUAGE DataKinds           #-}
{-# LANGUAGE KindSignatures      #-}
{-# LANGUAGE RankNTypes          #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies        #-}
{-# LANGUAGE TypeOperators       #-}
module Snd where

import           HList

hmap :: forall f g xs. (forall x. f x -> g x) -> HList f xs -> HList g xs
hmap f = go

  where
    go :: HList f xs' -> HList g xs'
    go Nil       = Nil
    go (x :& xs) = f x :& go xs

type family Snd x where
  Snd '(a, b) = b

type family MapSnd xs where
  MapSnd '[] = '[]
  MapSnd (y ': ys) = Snd y ': MapSnd ys

hmap2 :: forall f g (xs :: [(*,*)]). (forall x. f x -> g (Snd x)) -> HList f xs -> HList g (MapSnd xs)
hmap2 f = go
  where
    go :: HList f xs' -> HList g (MapSnd xs')
    go Nil       = Nil
    go (x :& xs) = f x :& go xs

NoSnd.hs
{-# LANGUAGE DataKinds           #-}
{-# LANGUAGE KindSignatures      #-}
{-# LANGUAGE RankNTypes          #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies        #-}
{-# LANGUAGE TypeOperators       #-}
module NoSnd where

import           HList

hmap :: forall f g xs. (forall x. f x -> g x) -> HList f xs -> HList g xs
hmap f = go
  where
    go :: HList f xs' -> HList g xs'
    go Nil       = Nil
    go (x :& xs) = f x :& go xs

type family MapSnd xs where
  MapSnd '[] = '[]
  MapSnd ('(_, y) ': ys) = y ': MapSnd ys

hmap2 :: forall f g (xs :: [(*,*)]). (forall x a b. (x ~ '(a, b)) => f x -> g b) -> HList f xs -> HList g (MapSnd xs)
hmap2 f = go
  where
    go :: HList f xs' -> HList g (MapSnd xs')
    go Nil       = Nil
    go (x :& xs) = f x :& go xs

Compiling Snd.hs works, but compiling NoSnd.hs gives
NoSnd.hs:27:20: error:
    • Could not deduce: x ~ '(a0, x0) arising from a use of 'f'
      from the context: xs' ~ (x : xr)
        bound by a pattern with constructor:
                   :& :: forall k (a :: k -> *) (x :: k) (xr :: [k]).
                         a x -> HList a xr -> HList a (x : xr),
                 in an equation for 'go'
        at NoSnd.hs:27:9-15
      'x' is a rigid type variable bound by
        a pattern with constructor:
          :& :: forall k (a :: k -> *) (x :: k) (xr :: [k]).
                a x -> HList a xr -> HList a (x : xr),
        in an equation for 'go'
        at NoSnd.hs:27:9
    • In the first argument of '(:&)', namely 'f x'
      In the expression: f x :& go xs
      In an equation for 'go': go (x :& xs) = f x :& go xs
    • Relevant bindings include x :: f x (bound at NoSnd.hs:27:9)

The difference between Snd.hs and NoSnd.hs is that, in the latter, instead of defining a type family Snd, I try to destructure types directly. This happens in two places: the definition of MapSnd and the type of (the parameter to) hmap2.
The two questions are: can someone explain the type error; and is there a way to write hmap2 without defining a Snd type family?
Thank you.
Comment: You can think of the first version of `MapSnd` as "lazier" than the second one. I believe you absolutely need that laziness if you want to be polymorphic in `f` like that.
Answer: The statement
exists a. x ~ '(a, b)

is slightly stronger than the statement
b ~ Snd x

For example, given
type family Any :: (*, *) where {}

It is valid to conclude
Snd Any ~ Snd Any

But it is not valid to conclude
exists a. Any ~ '(a, Snd Any)

because Any doesn't unify with anything else whatsoever.
You have an HList of things indexed by types of kind (*,*), but you don't know that each element actually has a type of the form '(a,b), so you can't pass a proof of that to the function you're given. Now if you had a less-polymorphic list, where the element type was indexed in a known way, then you could pattern match on the elements to get what you want. But that's not what you have, and it's considerably less general and useful. With your current (working) formulation, the passed function is responsible for working out whatever information it needs to know about the structure of the index. But that's perfectly fine; it's in a much better position to know the structure of f than you are. Take your winnings and go!


how to set list of data from database to display randomly at a android-based app?

Question: I've trying to display random data from the database example in my database i have total of 20 question. i want to display randomly 10 qns every time i access the app. And for the second time that i access it, it will display the other 10 qns that has not been display before.
my code:
ArrayList<Integer> randList = new ArrayList<Integer>();
    Random randGenerator = new Random();

    ArrayList<String> list2 = new ArrayList<String>(db.selectData("MCQ",new String [] {"_id"}, "testId=0", null, null, null, null));

    //random 10 n.o
    for(int i=0;i<10;i++)
    {
        int randNum = randGenerator.nextInt(list2.size());

        while (randList.contains(randNum))
        {
            randNum = randGenerator.nextInt(list2.size());
        }
        randList.add(randNum);
        Log.d("rand no:"+i,String.valueOf(randNum));
    }

    ArrayList<String> idList = new ArrayList<String>();
    //get the 10 _id that are chosen
    for (int i=0; i<10;i++)
    {
        idList.add(list2.get(Integer.valueOf(randList.get(i))));
        Log.d("id:"+i,String.valueOf((list2.get(Integer.valueOf(randList.get(i))))));
    }

    ArrayList<String> list3 = new ArrayList<String>(db.selectData("MCQ",new String [] {"Question"}, null, null, null, null, null));
    Log.d("size",String.valueOf(list3.size()));
    ArrayList<String> qnsList = new ArrayList<String>();

    // == set question in arrangement of randList == //
    for(int i=0;i<=list3.size();i++)
    {
        qnsList.add(list3.get(i));
        Log.d("_id:"+i,String.valueOf(list3.get(i)));
    }

i have tested it again and again and realized that weirdly, it could not read the data at _id=20
this is what i get in my log cat:
E/AndroidRuntime(1284): java.lang.IndexOutOfBoundsException: Invalid index 20, size is 20
E/AndroidRuntime(1284):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)

there are more, but i think it is useless as i have tried running with just _id=19 and it works but once i change to 20 it crashed.
Answer: Change this line:
for(int i=0;i<=list3.size();i++)

to be:
for(int i=0;i<list3.size();i++)

You were iterating through the loop 1 too many times (on the last iteration, when i = list3.size() you would get an IndexOutOfBoundsException when you do list3.get(i) since list indexes are 0-based so the twentieth and last element is actually at index 19).
Answer: Just keep in mind that SQLite's _id is not 0-based.


Testing a simple AngularJS service using Jasmine

Question: I have a simple service that I am trying to unit test. No matter what I try, either the searchService is an unknown provider, or service is null (which oddly enough won't cause my test to fail!!).
Anyone have an insight on what I might be doing wrong??
angular.module('app').service('searchService', function( $q, _ ) { // _ is lodash

  var cache = [
    {
      id: "current",
      name: "Current",
      description: "Search current data"
    },
    {
      id: "historical",
      name: "Historical",
      description: "Search historical data"
    }
  ];

  this.getSearchOptions = function() {
    var deferred = $q.defer();
    deferred.resolve( angular.copy( cache ) );
    return( deferred.promise );
  };

  this.getSearchOptionsByID = function( id ) {
    var deferred = $q.defer();
    var searchOption = _.findWithProperty( cache, "id", id );

    if ( searchOption ) {
      deferred.resolve( angular.copy( searchOption ) );
    } else {
      deferred.reject();
    }
    return( deferred.promise );
   };
  }
);

I am trying to create a unit test that loads in the searchService so I can check the cached values:
describe("Unit: Testing Services", function() {
  describe("Search Service:", function() {
    var service = null;

    beforeEach(function() {
      angular.module('app').service('_');
    });
    // I've also tried the commented out code below
    //beforeEach(inject(function(searchService) {
    //this.service = searchService;
    //}));
    //it('should contain an searchService', invoke(function(service) {

    it('should contain an searchService', function(searchService) {
      expect(searchService).not.to.equal(null);
    });

    it('should contain two search options', function(searchService) {
      expect(searchService.getSearchOptions()).to.equal(2);
    });
  });
});

Answer: The following should work for a service without parameter, maybe this can be a starting point:
describe("Unit: Testing Services", function() {
    describe("Search Service:", function() {

        beforeEach(function() {
            angular.module('app');
        });

        it('should contain a searchService',
           inject(function(searchService) {
                expect(searchService).not.to.equal(null);
        }));

        it('should contain two search options',
            inject(function(searchService) {
                expect(searchService.getSearchOptions()).to.equal(2);
        }));

   });
});

(You can also have a look here: How do I test an AngularJS service with Jasmine?)
Comment: Nice to hear. As a side note, actually module('app') is a shortcut for angular.mock.module('app') which allow you to create mocks of your real module.
Comment: It got me going in the right direction. Thanks! I dropped the angular.module('app') and just did module('app'). And then changed invoke to inject (it was late, guess my fingers had a mind of their own)


Campos para inserção de dados no formulario

Question: Ola gostaria de fazer um metodo onde o usuario clica no input e sempre direcionar para o ultimo caracter digitado, alguma dica?
Comment: Queres fazer isso quando o utilizador seleciona o input (no evento `focus`?)
Answer: Olá,
Com base nesta pergunta do stackEN, você pode fazer como o código abaixo.
https://stackoverflow.com/questions/4609405/set-focus-after-last-character-in-text-box
<code>(function($){
    $.fn.setCursorToTextEnd = function() {
        var $initialVal = this.val();
        this.val($initialVal);
    };
})(jQuery);

$('#meuTXT').setCursorToTextEnd();
</code>


string_replace replacing very first segment in loop

Question: This question is based on my previous question. This is my code.
$this->logger->debug($datauser);   // [ZN1961] => Array([#A] => 12 >  4 [#B] => 12 >  2 ), [ZN1962] => Array ([#A] => 20 >  4 [#B] => 20  >  2 )
logicexpression = ((#A) OR (#B) );

$newArr = array();
foreach ($datauser as $key => $value) {
    foreach ($value as $logname => $cond) {
        $this->logger->debug($cond);     /// WHEN DEBEG HERE it gives correctly the $cond in each iteration
        $logicexpression =str_replace($logname, $cond, $logicexpression);
    }
$this->logger->debug($logicexpression ); // here I am always getting (12 >  4) OR (12 >  2)
    }
`

So my problem  is as I mentioned in the code I am always getting (12 >  4) OR (12 >  2).
So the output is,
@547,12 >  4
@547, 12 >  2
@557, (12 >  4) OR (12 >  2)
@547, 20 >  4
@547, 20 >  2
@557, (12 >  4) OR (12 >  2) // here it should has to come as (20 >  4) OR (20 >  2)`

Even I am getting $cond correctly while debugging couldn't replace the relevant $cond in iteration. I couldn't understand why ? please help me.
Answer: You have to define a new variable $newlogicexpression inside the iteration, otherwise after the first iteration you don't have (#A) OR (#B) in $logicexpression anymore and the replace won't work...
$logicexpression = ((#A) OR (#B) );
foreach ($datauser as $key => $value) {
    $newlogicexpression = $logicexpression;
    foreach ($value as $logname => $cond) {
        $newlogicexpression = str_replace($logname, $cond, $newlogicexpression);
    }
    $this->logger->debug($newlogicexpression);
}

Comment: I have slightly change the codes. since if I add an array couldn't get the correct replacement at once. Could you please help me with that
Comment: guess i didn't understand what exactly are you trying to achieve?
Comment: I have to replace (#A) OR (#B) this with relavant $cond. like first iteration (12 >  4) OR (12 >  2) second iteration (20 >  4) OR (20 >  2). Here my problem is in every iteration I am getting the result as (12 >  4) OR (12 >  2)
Comment: It helped . Thanks


How to configure Review Board running under linux to use a LDAP user

Question: I have installed ReviewBoard before on windows successfully. I am now trying to install it on Ubuntu.
Steps so far:

Successfully installed
ReviewBoard (can login into the web
app)
Connected Ubuntu to the
windows Domain.
I can successfully
login as the user I wish to run
ReviewBoard under.
Tried to change
/var/www/review/apache-mod-python.conf to have the something like the following (NOTE: These aren't actually my details)
AuthLDAPBindDN "cn=LookUp,ou=People,dc=masd,dc=edu"
    AuthLDAPBindPassword masdsearch
    AuthLDAPAuthoritative off
    AuthLDAPCompareDNOnServer On
    AuthLDAPURL ldap://server1.masd.edu/ou=People,dc=masd,dc=edu?sAMAccountName

However doing all this when i try and post to review board from my local machine I get the following error
Error uploading diff: One or more fields had errors (105)

{u'fields': {u'path': [u'HTTPS certificate not accepted.  Please ensure that the proper certificate exists in /var/www/.subversion/auth for the user that reviewboard is running as.']}, u'stat': u'fail', u'err': {u'msg': u'One or more fields had errors', u'code': 105}}

Does anyone have ideas??
Answer: I fixed this using the following method
SVN checkout a file under the user Reviewboard is running under this will create a .Subversion/Auth/ directory in that users HOME.
I then simply recreated the .Suberversion/Auth/ directory in /var/www/ and everyhting worked as expected


How to use runner.py in sumo via command line and solving its common error(permission denied)

Question: When I try to use the runner.py example via the command line, I encounter the following error:
C:\Program Files (x86)\Eclipse\Sumo\doc\tutorial\traci_tls>runner.py
Traceback (most recent call last):
File "C:\Program Files (x86)\Eclipse\Sumo\doc\tutorial\traci_tls\runner.py", line 122, in
generate_routefile()
File "C:\Program Files (x86)\Eclipse\Sumo\doc\tutorial\traci_tls\runner.py", line 47, in generate_routefile
with open("data/cross.rou.xml", "w") as routes:
PermissionError: [Errno 13] Permission denied: 'data/cross.rou.xml'
Who knows how to solve this error?
Regards, Ali
Answer: Please make a local copy of the tutorial to your home directory before running it. You probably do not have write access to the installation directory.
Comment: I'm sorry Michael for my late reply. Thank you indeed. It works as you said.