Does nginx ingress able to export headless service?

Question: Does nginx ingress controller able to export a headless service?
The underlaying pod is using hostNetwork.
Is there documentation for this?
Specifically, I'm trying to export node-export service(manifest comes from kube-prometheus) by nginx ingress controller.

a short code of ingress:
...
       - path: /node-exporter
         pathType: Prefix
         backend:
           serviceName: node-exporter
           servicePort: 9100
...

a short code of service:
...
spec:
  clusterIP: None
  ports:
  - name: https
    port: 9100
    targetPort: https
  selector:
    app.kubernetes.io/name: node-exporter
...

Comment: In theory yes, headless service can be exposed with nginx ingress controller - though it is not pretty much recommended as per  [kubernetes docs](https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types). Could you please specify how exactly the ingress was configured?
Comment: Hello @anarxz, I don't see the document about kubernetes not recommended expose headless service... Which passage are you referring to? I post my code above. By the way, I realized that I don't need a service to expose because they are already exposed using `hostNetwork`.
Comment: I've posted my explanation as answer, please check.
Answer: According to my test result,
I can't export a hostNetwork service by ingress.
Here is my result matrix:

headless
clusterIP

hostNetwork: True
502
502

hostNetwork: False
✔
✔
Answer: Basically, headless Services  are of the same type as default ClusterIP, which exposes Service on a cluster-internal IP -  the only difference is that headless service allows clients to connect to pod directly without proxy.
I was referring to this part in Kubernetes doc, where it is stated that ClusterIP is supposed to be accessible only from within the cluster, while ingress would expose it outside of the cluster :

ClusterIP: Exposes the Service on a cluster-internal IP. Choosing this value makes the Service only reachable from within the cluster. This is the default  ServiceType.

As per  hostNetwork,  when it is set to True, a pod is granted access to the services listening on localhost, it can use the node network namespace and therefore see and use network interfaces of the host machine. In its turn, the pod would  be accessible on these network interfaces  and it can receive outside traffic directly.


Proof for the product of an infinite series

Question: Taking for example 2 x 2 x 2 ..., I know that we can represent this as r = 2r, which should result to be r = 0.
Now my question arises when attempting to prove whether the (k+1)th element is greater than the kth element, i.e.
2k+1 = 2k x 2, which should suggest 2k+1 > 2k, thus by induction the product should continuously increase by a product of 2, i.e. r > 2, but how is the result r = 0 justified?
Comment: The product $2 \times 2 \times 2 \times \ldots$ is divergent. The reasoning that results in $r = 2r$ assumes the product converges to $r$, which in this case, it does not.
Comment: @Shreyas what are you asking exactly?
Comment: You've proved that if it converges, then it converges to $0$.  Since it doesn't converge to $0$, it diverges.
Answer:
Taking for example 2 x 2 x 2 ..., I know that we can represent this as r = 2r, which should result to be r = 0.

Only if the product actually converges. For a sequence of numbers $a_n$, we say
$$\prod_{i=1}^\infty a_n \text{ converges if and only if } \lim_{n \to \infty} \prod_{i=1}^n a_n \text{ exists}$$
Moreover, the value attributed to the infinite product is given by that limit if it exists.
Let $a_n = 2$ for all positive integers $n$. Then $\prod_{i=1}^n a_n = 2^n$. Obviously, this diverges as $n \to \infty$, and thus so does the infinite product. However, if $a_n = 1/2$ for example, then you can show the infinite product is zero.
Clearly, the claim $r=0$ is totally unjustified in this light. Such operations are not always justified.


react-spring and typescript not callable error

Question: I am unable to make the simplest example of react-spring work:
import { useSpring } from 'react-spring/three'

export const myComponent = () => {
    const [spring, setSpring] = useSpring(() => ({ xpos: 0 }))
    setSpring({xpos: 10})

    return (
        <Canvas />
    )
}

It gives me this:

Uncaught TypeError: setSpring is not a function
Answer: There's more discussion on this here: https://github.com/pmndrs/react-spring/issues/1359
Current work-around: use setSpring.current[0].start() rather than setSpring()
Answer: Well, it works with react-spring v9.0.0 beta.
Comment: This isn't true - I'm using the react-spring v9.0.0 beta and running into the exact same problem.


Como ler os dados do Censo Escolar no R (Matrículas)

Question: Estou tendo dificuldades para analisar os dados do censo escolar 2019 no R.
Li algumas coisas em outros fóruns e optei por usar o pacote ffbase que lida com bases de dados muito grandes.
Usando o comando abaixo consigo baixar a base no R:
matriculas<- read.csv.ffdf(file="MATRICULA_NORDESTE.csv",header=TRUE)

O problema é que não consigo trabalhar com ela depois, por exemplo, ao tentar rodar:
Analise<-subset.ffdf(matriculas,CO_UF==27)

Me é retornado:
"Error in gsub(varre, varsub, es) :
  expressão regular inválida "

Alguém poderia me ajudar? A ideia é criar uma base menor (selecionando apenas a UF 27 para que eu consiga trabalhar nela como se fosse um csv normal).
Agradeço desde já.
Comment: Difícil responder sem uma amostra dos dados, mas tente usar `CO_UF == "27"`
Answer: Para ler os dados e filtrá-los ao mesmo tempo vou usar o pacote sqldf que acho ser ideal para isso uma vez que permite filtrar os dados com instruções SELECT da linguagem SQL. Isto evita sobrecarregar o .GlobalEnv e a memória com dados inúteis.
1. Ver quais os ficheiros a ler
csv_files <- list.files(pattern = "MATRICULA_.*\\.CSV")
csv_files
#[1] "MATRICULA_CO.CSV"       "MATRICULA_NORDESTE.CSV"
#[3] "MATRICULA_NORTE.CSV"    "MATRICULA_SUDESTE.CSV"
#[5] "MATRICULA_SUL.CSV"

2. Qual o tamanho do ficheiro da pergunta
Para saber quantas linhas tem o ficheiro utilizo o comando unix/Linux wc. A chamada ao sistema operacional é feita com system2 que é atualmente o comando R recomendado para tal.
system2("wc", csv_files[2])
#  15304590   15304590 3927158117 MATRICULA_NORDESTE.CSV

O ficheiro tem mais de 15 milhões de linhas e 3,6 GB.
3. Ler os dados
library(sqldf)

SQL <- "select * from file where CO_UF = '27'"
t0 <- system.time(
  dados <- read.csv2.sql(csv_files[2], sql = SQL, sep = "|")
)
t0
#  usuário   sistema decorrido
#  324.799    20.892   514.291

dim(dados)
#[1] 933873    104

No meu sistema foram precisos 8.5 minutos para ler e filtrar os dados. Não houve qualquer erro.
A base final tem cerca de 930 mil observações de 104 variáveis, o que representa
100*nrow(dados)/15304590
#[1] 6.101915

apenas 6,10% dos dados do ficheiro.


Teclado não reconhece Edittext

Question: Tenho vários EditText dentro de um item da minha lista ExpandleListView.
Sempre ao clicar nos EditText aparece a mensagem abaixo e não é digitado texto no campo:

getSelectedText on inactive InputConnection
  getTextBeforeCursor on inactive InputConnection
  getTextBeforeCursor on inactive InputConnection

public View buscaView(int groupPosition){
        if(listaHolder.size() > 0){
            for(int i = 0; i < listaHolder.size(); i++){
                if(listaHolder.get(i).position == groupPosition){
                    return listaHolder.get(i).convertView;
                }
            }
        }
        return null;
    }

 @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

        if(buscaView(groupPosition) == null) {
               LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(
                        Context.LAYOUT_INFLATER_SERVICE);
                convertView = layoutInflater.inflate(R.layout.adapter_aneurisma, null);

                holder = new ItemSuporte();
                // Editexts
                holder.aneurismaLargura = (EditText) convertView.findViewById(R.id.et_largura);
                holder.aneurismaComprimento = (EditText) convertView.findViewById(R.id.ed_comprimento);
                holder.ed_colo = (EditText) convertView.findViewById(R.id.ed_colo);
                holder.ed_causa = (EditText)  convertView.findViewById(R.id.ed_causa);
                holder.ed_descricao = (EditText) convertView.findViewById(R.id.ed_descricao);
                holder.ed_tratamento = (EditText)  convertView.findViewById(R.id.ed_tratamento);
                holder.ed_resultado_imediato = (EditText)  convertView.findViewById(R.id.ed_resultado_imediato);
                holder.ed_n_clips = (EditText) convertView.findViewById(R.id.ed_n_clips);
                holder.ed_tempo_clipagem_temporaria = (EditText) convertView.findViewById(R.id.ed_tempo_clipagem_temporaria);
                holder.ed_n_coils = (EditText) convertView.findViewById(R.id.ed_n_coils);
                holder.ed_descricao_complicacoes_especificas = (EditText) convertView.findViewById(R.id.ed_descricao_complicacoes_especificas);

                // Checkbos
                holder.cb_insucesso_terapeutico = (CheckBox) convertView.findViewById(R.id.cb_insucesso_terapeutico);
                holder.cb_paralisia_incompleta = (CheckBox) convertView.findViewById(R.id.cb_paralisia_incompleta);
                holder.cb_paralisia_completa = (CheckBox) convertView.findViewById(R.id.cb_paralisia_completa);
                holder.cb_clipagem_temporaria = (CheckBox) convertView.findViewById(R.id.cb_clipagem_temporaria);
                holder.cb_balao = (CheckBox) convertView.findViewById(R.id.cb_balao);
                holder.cb_stent = (CheckBox) convertView.findViewById(R.id.cb_stent);
                holder.cb_complicacoes_especificas_procedimento = (CheckBox) convertView.findViewById(R.id.cb_complicacoes_especificas_procedimento);

                // View
                holder.conainner = (View) convertView.findViewById(R.id.container);

                //holder.convertView = convertView;
                holder.position = groupPosition;
                holder.convertView = convertView;
                //holder.convertView.setTag(holder);

                // Adicionando cada view  do ExpandleListView.
                listaHolder.add(holder);

                Log.e("Adapter", "Criou uma nova instância da View...");

        }
        else{
           Log.e("Adapter","Retornou uma instância existente..., Total de holders: " + listaHolder.size());
           holder = (ItemSuporte) buscaView(groupPosition).getTag();
        }

         return buscaView(groupPosition);
    }

Comment: Você poderia postar a parte do seu código onde faz a declaração e inicialização dos EditTexts? Acho que isso ajudaria a resolver este problema de forma mais rápida.
Comment: Coloquei o código
Comment: O problema é que meu Edittext perde o foco.
Answer: ExpandleListView é muito bugado, acabei utilizando um ListView comum que ficou idêntico ao Expandle...
Escondendo e mostrando o layout a cada clique para "expandir" o item da lista, assim como a manipulação da seta de Up e Down a cada "abertura" da lista. Ficou idêntico ao ExpandleListView só que sem bugs, recomendo para quem for utilizar essa abordagem.
Abraço.
Comment: mesmo que sua resposta esteja correta, é aconselhável adicionar ao mesmo um código para melhor entendimento, pois tem muita gente iniciando no mundo android e não faz a minima ideia do que voce está falando.

Teclado não reconhece Edittext


TPL Tasks and ReaderWriterLockSlim

Question: I've got a strange bug in my current project. Thats why I have two questions:
1) Why does this occur?
2) How do I solve this?
Some additional info: I'm running this on a System with a QuadCore CPU (Intel Core2Quad Q9650)
I have a Function "DoSomething()" that could be called from multiple Threads at a time:
public class SingletonClass
{

    // Singleton
    public static SingletonClass Instance
    {
        get { return _instance ?? (_instance = new SingletonClass()); }
    }

    private readonly ReaderWriterLockSlim _workLock = new ReaderWriterLockSlim();
    private bool _isWorkDone = false;

    // bool returns true for "Inner Task executed" and false for "Inner Task had been executed earlier"
    public bool DoSomething()
    {
        // workaround to fix: Thread.Sleep(50);
        _workLock.EnterWriteLock();
        try
        {
            if (!_isWorkDone)
            {
                Task.Factory.StartNew(DoWork());
                _isWorkDone = true;
                return true;
            }

            return false;
        }
        finally
        {
           _workLock.ExitWriteLock();
        }
    }
}

In order to test if this function works I used the TPL to create multiple Tasks calling this function nearly simultaniously:
for (int i = 0; i < 10; i += 1)
{
    Task.Factory.StartNew(() =>
    {
        bool success = DoSomething();
        Console.WriteLine(success);
    });
}

I expected to get an output like this:

true, false, false, ....

But what I got was this:

true, true, true, true, false, false ....

Remember:
1) Why?
2) How to solve?
EDIT: I added a sample-project: [DELETED - Problem solved]
Comment: You should of said it was a Singleton method. Always post a full reproduce. You should edit the code and add the class encapsulating the method
Comment: there is (of course) an other function using EnterReadLock. But that's not the point. I tried to use lock(_lockObject) instead but got the same unexpected output.
Comment: I tried reproducing this and i get the expected outcome.
Comment: May I ask, what CPU you have? If I add Thread.Sleep(50) before `_workLock.EnterWriteLock();` it worked for me. But this is a workaround at most.
Comment: It was a hyper-v Intel i7 QuadCore
Comment: Can you add `volatile bool _isWorkDone`? I think `volatile` in C# means **atomic**.
Comment: Thank you for your Response! But there was no effect. 4 Threads entering simultaniously.
Comment: Than it may be time for Interlocked. I don't think the problem is in the lock, but in the cache - the other thread just don't see it has changed.
Comment: I made a small test-program, too and there the problem disappeared ... I'll keep you updated ...
Comment: You may try this: http://msdn.microsoft.com/en-us/library/system.threading.interlocked.memorybarrier%28v=vs.110%29.aspx ...but the lock itself should be a barrier, I do not understand.
Comment: I reproduced this bug: you remember `bool success = DoSomething();` ?
`DoSomething()` is a public function of a Singleton-Class in a DLL referenced by the ConsoleApplication ... (you might to run it multiple times)
Comment: This thread says an explicit memory barrier is not needed with ReaderWriterLockSlim - http://stackoverflow.com/questions/20564489/do-i-need-memorybarrier-with-readerwriterlockslim.  Strange...
Answer: No way, the problem is not in the lock but in the creation of the Singleton!
public static Dll Instance
{
    get { return _INSTANCE ?? (_INSTANCE = new Dll()); }
}

The above is not protected by the lock => you get 4 different instances! Four Different locks!
private void CreateThreadsToAccess()
{
    Task[] tasks = new Task[10];
    for (int i = 0; i < tasks.Length; i += 1)
    {
        tasks[i] = Task.Factory.StartNew(() =>
        {
        //  here you get four different instances
            bool success = Dll.Instance.DoSomething();
            Console.WriteLine(success);
        });
    }

    Task.WaitAll(tasks);

    Console.WriteLine("Press any key to exit");
    Console.ReadKey();
}

How to correct:
private static readonly object mylock = new object();
public static Dll Instance
{
    get
    {
       if (_INSTANCE == null)
       {
           lock (mylock)
           {
              if (_INSTANCE == null)
              {
                 _INSTANCE = new Dll();
              }
           }
       }
       return _INSTANCE;
    }
}

Comment: Thanks a lot. I think I should make a break ^^
Comment: BTW: Look at this question: http://stackoverflow.com/questions/12316406/thread-safe-c-sharp-singleton-pattern

TPL Tasks and ReaderWriterLockSlim


prometheus: how prometheus handles the data type overflow?

Question: The prometheus client keeps updating the metric and seems do not consider overflow. For example, the counster Add():
func (c *counter) Add(v float64) {
    if v < 0 {
        panic(errors.New("counter cannot decrease in value"))
    }
    ival := uint64(v)
    if float64(ival) == v {
        atomic.AddUint64(&c.valInt, ival)
        return
    }

    for {
        oldBits := atomic.LoadUint64(&c.valBits)
        newBits := math.Float64bits(math.Float64frombits(oldBits) + v)
        if atomic.CompareAndSwapUint64(&c.valBits, oldBits, newBits) {
            return
        }
    }
}

The c.valInt would overflow and wrapped around from 0.
How prometheus handles this case when it scrapes such rewind metric?
Answer: Prometheus is designed to handle counter resets like this, the rate function has code for it. It more commonly happens when a process restarts.
An overflow is also quite unlikely. Even if you were incrementing by a billion a second it'd take several hundred years to overflow.
Comment: what about the `sum` of `histogram` type? The addition may be arbitrary big value, so it may overflow the `sum` quickly. https://github.com/prometheus/client_golang/blob/master/prometheus/histogram.go#L248
Comment: Similar logic applies, as long as you restart your applications at least once a decade you should be fine.


"Can't bind to 'ngFor' since it isn't a known native property"

Question: Can't tell what I'm doing wrong here. Tried explicity defining the ngFor directive through CORE_DIRECTIVES, and using let. Is there something I missed?
import { Component, Input , Output , EventEmitter} from 'angular2/core';
import {CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/common';

@Component({
  selector: 'panel',
  moduleId: module.id,
  templateUrl: './panel.component.html',
  styleUrls: ['./panel.component.css'],
  directives: [FORM_DIRECTIVES, CORE_DIRECTIVES]
})

export class panelComponent {

  list: String[];
}

Getting an error on all ngFors

{{thing}}

Comment: What Angular2 version are you using?
Answer: remove
 directives: [FORM_DIRECTIVES, CORE_DIRECTIVES]

use # instead of let in Angular2 beta that you're obviously using.
Comment: Thanks for the help! I guess that's what happens when you don't read the change logs :^)


Nginx proxy: redirect to http://private-service/

Question: I'm trying to configure a nginx reverse proxy. I'm using htpasswd but it's unrelated in my case.
I want the following:
when visit https://public-nginx/kibana I want that it redirects to the proxied url (to my private kibana), but it keeps the public-nginx URL.
My nginx.conf looks pretty basic:
worker_processes 1;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
include /usr/share/nginx/modules/*.conf;
events {
    worker_connections 1024;
}
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    access_log  /var/log/nginx/access.log  main;
    server_names_hash_bucket_size 128;
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;
    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;
    include /etc/nginx/conf.d/*.conf;
    index   index.html index.htm;
    server {
        listen       8080 default_server;
        listen       [::]:8080 default_server;
        server_name  localhost;
        root         /usr/share/nginx/html;
        include /etc/nginx/default.d/*.conf;
        location / {
        }
        error_page 404 /404.html;
            location = /40x.html {
        }
        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
}

my conf.d/kibana.conf looks like:
server {
    listen 80;
    server_name _;
    location / {
        proxy_pass https://private-url/kibana/;
        proxy_redirect https://private-url/kibana/ /;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Authorization "";
        proxy_hide_header Authorization;
        auth_basic "Username and Password are required";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
}

When I check it seems that the /kibana url is redirecting me to the right path (/kibana/app/..). But I see a 404.
Answer: Drop proxy_redirect https://private-url/kibana/ /; from kibana.conf.
It adds a 301 redirect to the private-url to all replies sent to the client, which is exactly what you are trying to avoid.
See http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_redirect
From your question it's not clear if you want kibana to be served from http://public-url/kibana or from http://public-url/
If you want it to be under http://public-url you also need to double check your basePath setting in kibana.yml.
server.basePath enables you to specify a path to mount Kibana at if you are serving it from behind a reverse proxy.
See https://www.elastic.co/guide/en/kibana/current/settings.html


Git branch merged to master causes "No Known Class Method for Selector" errors in Xcode project

Question: I'm working on an iOS app and the first release of it went onto the app store last week, I've had some ideas on things to add to it and some things I want to change based on user feedback. I decided to do feature branches for every major new section. I completed the first feature branch and verified the app works properly without any warnings or errors.
I merged the branch into master without any conflicts, after opening the successfully merged master in Xcode and attempting to run it I'm receiving a lot of "No known class method for selector", "Duplicate interface definition for class", and "Property has a previous declaration" errors. I've looked through all of the files it mentions and they all are exactly as they were in the feature branch. The biggest problem causing files are the Reachability one's from Apple.
Here's an example of one of the files throwing "No known class method for selector". It's doing it for the create, update, and remove methods. All of these methods were added in the feature branch.
The .h file:
//
//  Services.h
//  MovieQueue
//
//  Created by Joshua Kendall on 2/22/13.
//  Copyright (c) 2013 Simple App Group LLC. All rights reserved.
//

@interface Services : NSObject

+ (NSArray *)search:(NSString *)movieTitle;
+ (NSDictionary *)getMovieDetails:(NSInteger)movieId;

+ (void)create:(NSDictionary *)record;
+ (void)update:(NSDictionary *)record;
+ (void)remove:(id)movieId;

@end

And the redacted .m file:
//
//  Services.m
//  MovieQueue
//
//  Created by Joshua Kendall on 2/22/13.
//  Copyright (c) 2013 Simple App Group LLC. All rights reserved.
//

#import "Services.h"

@implementation Services

#pragma mark - API Access

+ (NSArray *)search:(NSString *)movieTitle {
...
}

+ (NSDictionary *)getMovieDetails:(NSInteger)movieId {
...
}

#pragma mark - CRUD

+ (void)create:(NSDictionary *)record {
...
}

+ (void)update:(NSDictionary *)record {
...
}

+ (void)remove:(id)movieId {
...
}

@end

Comment: It's nice that you've given us some code, but unfortunately it's irrelevant.  Give us an example of a line that's causing you problems.
Comment: The line's causing the problems are `[Services create:item]`, `[Services update:item]`, and `[Services remove:item]`. Regardless of where they are called its throwing a "No known class method for selector". The Services header is being loaded in the app's .pch file.  The methods are clearly defined in both the header and implementation files. I don't believe it's an issue with the code, but an issue caused by branch merging with Git.
Comment: Diff the project and see what's changed then.  I'll bet you're missing some import statements, but you might be right about git being the problem.  Xcode and git are... Not the most compatible entities
Comment: Ok, I went through and it was an issue with imports. I was using the .pch file to import the Services header file, once I removed it from there and placed it in the headers for the classes that call it's methods it solved the issues. I was under the impression that the .pch file was a good place to put imports that are used by the entire project, but apparently that's not a good thing to do. This [link](http://qualitycoding.org/precompiled-headers/) explained the problems with it.
Comment: Just do you know, it is perfectly acceptable to answer your own question!
Answer: Ok, it turns out this was an issue with imports, I had all of my common files like the Services class imported in the application's .PCH file. I've done this in all of the app's I've ever built because it made more sense than importing the same file in every view controller.
I took CodaFi's suggestion and checked imports, after importing the services header into one of the classes that was having an issue build without issue I started looking at the .PCH file since it seemed to be the cause.
It turns out that the .PCH file is not a replacement for importing the file in each class that uses it. They have to still be imported into each class. This page "4 Ways Precompiled Headers Cripple Your Code" explained the issue to me specifically the section entitled "Find and fix the missing #imports".
I'm guessing I've never had an issue with it before this because I've never used branches for an iOS project before.


How to use form_with in Rails for multiple models that don't have controllers

Question: I am trying to create recipe app that users can take. Part of the app is an admin users getting to create the recipes and instructions.

There is a User model/table with all the users. This has a
controller.

There is also a recipe table with all the recipes created.

Finally there is an instructions table that are each associated with a
recipe

What I am trying to make happen is the admin user visits a page to create a recipe. This page also has a list of existing recipes. The user can click on one of the recipes which brings the user to an edit page where they can edit the instructions for the recipe. The edit page shows a list of instructions. You can also add an instruction.
The problem is the form_with on the recipe create page is showing an error:
undefined method `recipes_path'

I don't have a recipe controller. The only controller is the user controller. Inside this controller I have defined an admin action a create_recipe action an edit_recipe action and an update_recipe action:
def admin
        @recipe = Recipe.new(
            recipe_params
        )

        @Recipes = Recipe.all

    end

    def create_recipe

        if @recipe.save
            redirect_to root_url
        else
            render 'new'
        end

    end

    def edit_recipe
        @recipe = Recipe.find(params[:id])

        @recipe_instructions = RecipeInstructions.where(recipe_id: @recipe.id)

    end

    def update_recipe
        @recipe = Recipe.find(params[:id])
        @recipe_instructions = RecipeInstructions.where(recipe_id: @recipe.id)

        if @recipe.update(recipe_params)
           redirect_to root_url
        else
           render :edit
        end

The routes look like this:
  get 'admin', to: 'users#admin', as: :admin
  get 'recipes/:id/edit', to: 'users#edit_recipe', as: :edit_recipe_instructions
  post 'recipes/:id/update', to: 'users#update_recipe', as: :update_recipe_instructions

Here is the view of the recipe page:

        <%= form_with model: @recipe do |newRecipe| %>

 <%= newRecipe.label :recipe_name, "Recipe name" %>

                    <%= newRecipe.text_field :recipe_name, class: "form-inputs form-text-inputs"%>

                <%= newRecipe.submit "SAVE", class: "btns submit-btns", id: "signup-submit-btn" %>
            <% end %>

Though I get the error.  I'm also worried a similar error will happen with the  instructions page because I'm using a similar form, but with multiple models.
<%= form_with model: [@recipe, @recipe_instructions], url: update_recipe_instructions_path(@recipe) do |newRecipe| %>

                     <%= newRecipe.fields_for :recipe do |recipeData| %>

 <%= recipeData.label :recipe_name, "Recipe name" %>

                      <%= recipeData.text_field :recipe_name, class: "form-inputs form-text-inputs"%>
                    <% end %>

                     <%= newRecipe.fields_for :recipe_instructions do |recipeInstructions| %>

 <%= recipeInstructions.label :instruction, "Instruction" %>

                      <%= recipeInstructions.text_field :recipe_instructions , class: "form-inputs form-text-inputs"%>
                    <% end %>

                <%= newRecipe.submit "SAVE", class: "btns submit-btns", id: "signup-submit-btn" %>
            <% end %>

I'm thinking it's the fact that the models don't have controllers that's causing the issue?
Answer:

        <%= form_with model: @recipe do |newRecipe| %>

 <%= newRecipe.label :recipe_name, "Recipe name" %>

                    <%= newRecipe.text_field :recipe_name, class: "form-inputs form-text-inputs"%>

                <%= newRecipe.submit "SAVE", class: "btns submit-btns", id: "signup-submit-btn" %>
            <% end %>

When you pass model: @recipe in the form, the resulted form action is '/recipes', that is the path to create a new recipe, but you don't have a path to create a recipe, or at least that's what I think, you're showing only three routes, one route to the admin, one to show the edit form and one to update the recipe, this last must be a patch or put route instead of post.
Create a new route like:
post '/recipes', to: 'users#create' # this must be a post route because you will create a new recipe

Despite this could resolve your problem, this isn't the correct way to do what you are doing.
In the Users controller you are creating a recipe, this is incorrect. In your project, you could have two controllers, one for the Users and one for the Recipes.
Also, you could create the routes with:
resources :users
resources :recipes

This a quickly way to create the 7 basic routes index, show, new, edit, create, update and destroy. See Rails routing from the outside
If you have two different tables, one for recipes and one for instructions, in your Recipe model must have:
has_many :instructions

and in your Instructions model you must have:
belongs_to :recipe

Of course, you also must have the required Foreign Keys to make the relation between this two tables. And then, when you create a new recipe could do something like:
@recipe.instructions << params[:instructions]

See Active Record Associations


Cassandra Order By Updated At

Question: I'm trying to build a cassandra schema to represent chat.
The one thing i can't seem to figure out is how to query most recently updated rooms (similar to most chat app list view)

Fields desired in list view ordered by updated_at desc

*room id
room title
room image
*user
*updated_at
*message entry
*message type
*metadata

Current Tables
Create TYPE user(
   id uuid,
   name text,
   avatar text
);

CREATE TABLE rooms(
  id uuid,
  "name" text,
  image text,
  users set<user>,
  archived boolean,
  created_at timestampz,
  updated_at timestampz,
  PRIMARY KEY(id)
);

CREATE TABLE messages(
  room_id uuid,
  message_id timeuuid,
  user user,
  message_type int,
  entry text,
  metadata map<text, text>,
  PRIMARY KEY(room_id, message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);

CREATE TABLE rooms_by_user(
  user_id uuid,
  room_id uuid,
  PRIMARY KEY(user_id, room_id)
);

Possible solutions that i can come up with.

Duplicate all room details to each message

allows easy query with SELECT * FROM messages PER PARTITION LIMIT 1
this would be a lot of duplicate data per message...

Query latest messages which user belongs to get room ids then query rooms

This doesn't seem to be the cassandra way?

Is there a better way to model my data?
Answer: By looking at the schema it looks like you need relational database.
In Cassandra usually you use one table per query, it means you you should design your table by how you will structure query.
Also you can query by partition key or clustering column (second one should be partition key + clustering column).
So in order to query by updater_at, you need to make that column as clustering column. And keep in mind that in Cassandra you cannot alter keys.
Comment: materialized views are not production ready.
Comment: yeah, there is materialized views i could use for the altering updated at. also please read the rest of the post... if you could also elaborate more otherwise this answer doesn't really help anyone...
Comment: @jklaw90 Hey, I understood what you are saying, I proposed you to make `updated_at` as clustering column so you can sort it and query by the value.

Cassandra Order By Updated At


Why do we talk about Trace Operator?

Question: What is the importance of a Trace operator in PDE . Although I have read the Wiki page on this but I am not able to connect it to the aspect of solving PDE's.
Particularly why do we define Trace operator as $T\colon W^{1,p}(u) \to L^p(\partial U)$.
Also why do we deal with only exponent $1$ . What is great about operator from $W^{1,p}$ to $L^p$?
Please help me to understand this concept of trace operator. Thank you very much .
Comment: When we work with a PDE, we may ask a condition at the boundary of an open set. Unfortunately, it have a measure $0$ and the function of $W^{m,p}(\Omega)$ are defined up sets of measure $0$. The trace operator avoid these complications.
Comment: For example $\Omega$ is the unit disk in $\Bbb R^2$. Then we can have a PDE of the form $-\operatorname{div}(u)=f$ on $\Omega$ and $u=g$ on the boundary. In fact, we have $T(u)=g$ and it's well-defined (but it's not necessarily the restriction of $u$ at the boundary, except when $u$ is regular).
Comment: @DavideGiraudo : Can you please help me to understand this with an example :)
Answer: We take $U$ a smooth open set, regular enough in order to have density of $C^{\infty}_0(\overline U)$ in $W^{1,p}(U)$.
We define $T$ on $C^{\infty}_0(\overline U)$ by taking the restriction of these functions to the boundary (it's well-defined, these one are not equivalence classes of functions). We check that this operator is continuous on this space of functions, then we extend it by continuity to $W^{1,p}(U)$.
We get functions in $L^p(\partial U)$, which is a space of which can be defined using charts. Thanks to that, we can define an element of the Sobolev space on the boundary, even if this one has measure $0$, and it extends the concept of trace for function.

Why do we talk about Trace Operator?


Node child_processes not executing concurrently

Question: Background
I want to navigate to multiple websites in separate browser tabs programmatically. Ideally, I want to be able to have these websites loading in parallel, when the code is triggered.
Problem
As a proof of concept, I have the following code to open a browser through a command.
const { exec } = require("child_process");

exec('xdg-open https://www.google.com').on('exit', () => {console.log('child 1 exited')})
exec('xdg-open https://www.github.com').on('exit', () => {console.log('child 2 exited')})

What happens when I run the code above:

Both child 1 exited and child 2 exited were logged almost immediately after I run the code
A browser tab opens and starts loading one of the pages. I had to wait about 3 seconds after the first page is loaded, before the 2nd tab opens and starts loading the second page.

++
I expected both tabs to open and start loading the pages almost at the same time, but this is not happening.
Other Observations
I tried running xdg-open https://www.google.com and xdg-open https://www.github.com in separate terminals (executing both at around the same time), and I am able to have 2 tabs open and start loading pages at around the same time (this is the behavior I am aiming for)
However, the code above seems to behave similarly to running xdg-open https://www.google.com && xdg-open https://www.github.com
Question
If exec() spawns a new child_process, why is the code above not triggering multiple page navigations simultaneously? How do I achieve this behavior?
Comment: Not able to reproduce this. Worked fine for me - both tabs opened at the same time.
OS - MacOS 10.15.7
Comment: @Archit I see. Will try it on a Mac. The behavior above was observed on Ubuntu
Answer: I would suggest you to use open from npm. It will be a good option to just open multiple URLs from the Node.js APP.
const open = require('open');

const main = async () => {
  await open('https://www.github.com');
  await open('https://google.com');
}

main();

This code will open these URLs in parallel and it will open in the default browser selected. However, you can change the configuration in open to pass dynamic configuration to it. Please check here for more details.
You should not use the child_process to open such task as it doesn't require any computation. These are generally called when CPU is unable to handle the blocking requests as Node.js main loop runs on single thread. You can check here for more details when to use child_process.
Comment: I tried this lib too, and found that it does not open multiple URLs in parallel, i.e. there is a delay in between, which is similar to the behavior in my original post.
Comment: How much delay are you encountering? Does it hampering the flow?
Comment: The delay is similar to what I described in the original post. If you look at the `open` source code, a `child_procssed` is summoned under the hood as well.
Comment: I realized that this issue only happens if i'm using `open` with firefox. Getting `open` to use chrome, for example, is able to open multiple websites without delay.
Answer: I found this issue to only occur when my default browser is set to Firefox. If my default browser is set to chrome, both browser tabs will open at the same time and start fetching data from both websites (at the same time).
I'm posting this observation here in case someone might find it useful, but I have not come across a solution to make this work with Firefox.
EDIT:
More Observations
When I tried to open more websites in the same way (e.g. 10 websites), firefox will open in 2 batches (with some delay in between each batch). In each batch, multiple websites will open concurrently. So far, it seems like it will always open in 2 batches.


Ola, Tenho um Banco de dados - mysql e gostaria de diminuir um valor em uma coluna inteira

Question: Gostaria de usar o comando update para diminuir uma hora no valores que ja tem na tabela de valores diversos  na coluna inteira.
EX:
Nome da Coluna         Gostaria da coluna assim
     HORA                      HORA

    13:45                     12:45
    15:00                     14:00
    17:00                     16:00

O valor na coluna eh esse mesmo 13:00 gostaria de diminuir 1hr na coluna inteira ... com o comando update.
Comment: Supondo que seu campo seja do tipo time, tente: `UPDATE sua_tabela SET seu_campo = SUBTIME(seu_campo, '01:00:00');`
Answer: Existem diversas formas de se resolver isso, uma delas é utilizando a função SUBDATE() Ela serve para decrementar qualquer tipo de informação de um campo DATETIME.
Exemplo:
UPDATE sua_tabela SET
    hora = SUBDATE(hora, INTERVAL 1 HOUR);

Segue um exemplo no SQLFiddle.


Determining all $f : \mathbb R \to \mathbb R$ that satisfy $f\bigl(xf(y)\bigr) = x^{2002}f\bigl(f(y)\bigr)$

Question:
Determine all $f : \mathbb R \to \mathbb R$ that satisfy
$$f\bigl(xf(y)\bigr) = x^{2002}f\bigl(f(y)\bigr); \ \forall x,y \in \mathbb R.$$

What I know is $f(0) = 0$. I don't know how to deal with $x^{2002}$. Can anyone give me hints (or solution) please. Thank you very much!
Comment: Replace $x$ by $\frac x {f(y)}$.
Comment: Hint: If there is a real number $y_0$ s.t. $f(y_0)\ne 0$, then replace $x$ by $x/f(y_0)$ and $y$ by $y_0$ to get $f(x)=kx^{2002}$ for all $x$.  If there doesn't exist such $y_0$, then $f(x)=0$ for all $x$.
Answer: Replacing $x$ by $x/f(c)$ for some $c \in \mathbb{R}$ (where $f(c) \ne 0$) and putting $y=c$ we get:
$$f(x)=x^{2002}\cdot \frac{f(f(c))}{f(c)^{2002}}=kx^{2002}$$
for some $k \in \mathbb{R}$.
Now substituting in the original equation we get that it works for all $k \in \mathbb{R}$.
Otherwise, $f(c)=0$ for all $c \in \mathbb{R}$, and substituting back it also works.
Note: that works because I originally wanted to do it with $c=1$ and then I noticed that it has to be $f(1) \ne 0$. So if $f(1)=0$ then we can choose $c=2$ where $f(2) \ne 0$, and the other case if $f(2)=0$ then we can choose another $c$, and so on until $c$ covers all reals making $f(c)=0$. I know this sounds a bit obvious, but it makes perfect sense.
Comment: Be careful.  You can't divide by $f(1)$ if $f(1)=0$.  This FE has two solutions: $f(x)=0$ for all $x$, and $f(x)=kx^{2002}$ for all $x$ for some $k\ne 0$ (although these two solutions can be combined into one family: $f(x)=kx^{2002}$ where $k\in\Bbb R$).
Comment: I edited it, thanks guys for the illumination.
@WETutorialSchool
Comment: @miracle173 same thing but I don't know couldn't mention 2 users in one comment


MSBUILD Executing only Changed SQL Scripts

Question: I need to construct an MSBUILD script executes .SQL Scripts which have changed since last build.
I initially thought that I could copy all scripts from one folder to another using the <Copy> task and using the CopiedFiles <Output> for the copy task. However the copy task returns All files that it Attempted to copy, not actual copied files.
I am able to get MSBUILD to execute SQL Scripts via MSBUILD.ExtensionPack but Im scratching my head on this one
Comment: it seems some of my text was interpreted as tags, Second paragraph should read:
I initially thought that I could copy all scripts from one folder to another using the COPY task and using the CopiedFiles OUTPUT for the copy task. However the copy task returns All files that it Attempted to copy, not actual copied files.
Answer: You can do this with a concept known as incremental building. The idea is that you would create a target and then specify the inputs and outputs, which would be files. MSBuild will compare the timestamps of the input files to the output files. If all outputs were created after all outputs then the target is skipped. If all inputs are newer then all the target will be executed for all files. If only a portion are out of date, then only those will be passed to the target. For more info on this see the section Using Incremental Builds in my article Best Practices For Creating Reliable Builds, Part 2.
Also for more resources on MSBuild I have compiled a list at http://sedotech.com/Resources#MSBuild
Answer: <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="RunScripts">

  <Import Project="$(MSBuildExtensionsPath)\ExtensionPack\MSBuild.ExtensionPack.tasks"/>

  <PropertyGroup>
    <ConnStr>Server=Example;Database=Example;Trusted_Connection=True</ConnStr>
    <BuildFolder>Build\</BuildFolder>
  </PropertyGroup>

  <ItemGroup>


throwing 3 dice and obtaining "4" "2" "1"

Question: How are you ?
There is an exercise that I want to do (not a homework) and I need some help to understand my mistakes:
We play "$421$" by simultaneously throwing three dice until the moment we get the values $4,2$ and $1$. What is the probability that the goal is reached in less than $4$ throws?
Well,I tried this :

E = "Having $4$ and $2$ and $1$"
P(E) = $\frac{1}{6} * \frac{1}{6} * \frac{1}{6} * 3$ (three possible way of having $421$) = $0.138$
P(E*) = 0.9861
List item

Using geometric law:

$P(X=1) = 0.138 * 0.9861^0 = 0.138$
$P(X=2) = 0.138 * 0.9861^1 = 0.01360956$
$P(X=3) = 0.138 * 0.9861^2 = 0.01342174$
$P(X<4) = 0.16503013$

I know that i'm wrong and the solutions manual says that the answer is $0.081$. I just want some help and sorry for my bad english.
Comment: $3!=6$ ways to get there: 124 142 214 241 412 421
Comment: That's true ! My bad, thank you and have a nice day. :-)
Answer: The probability to have the triplet $\{1,2,4\}$ where the order is not requested (you have 6 possibile ways, not 3) is $\frac{1}{36}$ thus using geometric CDF you have
$$P(X\le 3)=1-(35/36)^3\approx 0.081$$
Comment: You're right , Thanks and have a nice day :)


Concepts of mixed effects in statistics and econometrics, how to cope with them?

Question: When I search for the definition about fixed-effects, random-effects or mixed-effects model here or elsewhere on the internet, there are a lot of discrepances. My first exposure to linear mixed-effects model was in longitudinal data analysis in Biostatistics.  The definition is clear to me that the fixed-effect is the population-averaged effect, and random-effects is the subject-specific effect. Then the mixed-effects model is the model that contains both fixed-effects and random-effects. The mixed-effects model is usually the random effects model because it contains at least one fixed-effects parameters. Like time slope, you have one mean slope for all individuals in the data, and random-effects are those subject-specific slope deviating from the mean slope.
However in Econometrics, the deveoplments of fixed-effects and random-effects models have distinct definitions, which is whether heterogeneity correlates or not with the error term.  Some statistical tests were developed to test whether fixed-effects or random-effects model should be used. There are lot of social science analyses adopting the Econometric approach as well. Therefore when I read the discussions about fixed-effects, random-effects or mixed-effects models posted by people from different areas, they always confuse me. Even though sometimes the mathematical defintions are similar, the modelling process and consideration behind it are quite different.
I hope there are some general discussions on Statistics and Econometrics about their discrepance in defintions or concepts rather than methodologies or algorithms used.
Comment: Of note: http://stats.stackexchange.com/questions/27662/what-are-the-major-philosophical-methodological-and-terminological-differences
Comment: Also related: http://stats.stackexchange.com/q/4700/2970
Comment: The term mixing is misleading.  There are conditions on probability distributions that are called mixing conditions that refer ro types of weak dependence in stochastic processes.  Consequently I am editing your title becuase it refers to mixed models and not mixing.
Comment: Thanks for pointing out this, I didn't realise it in my initial search.
Comment: I suggest you to first differentiate FE and RE as both terms are used heterogeneouly in econometrics and even stats: This will help
http://stats.stackexchange.com/questions/33984/concepts-behind-fixed-random-effects-models/34019#34019
Answer: Perhaps another way of seeing the difference is to focus on what the "fixed effect" is defined to be.  In econometrics, a panel (longitudinal) model is typically specified as
$$
y_{it} = X_{it}*b + a_{i} + e_{it}
$$
where the $X$ matrix would be called the "right hand side" variables, the "design matrix", or the "independent variables", etc.   The $a_i$ is an "unobserved error component".   The term "Fixed Effect" or "Random Effect" has to do ONLY with the assumptions about the unobserved component ($a_i$).
If one assumes it is a "fixed effect", then the beta-hat statistics are robust to correlation between $a_i$ and $e_{it}$.  That is, the beta-hat statistics are conditional on the "fixed" unobserved component being controlled for.  One can either include a dummy variable for each individual $i$ in the data as part of the $X$ matrix to calculate this (bad idea) or it can just be partial-ed out (better idea).
The "Random Effect" assumption about $a_i$ allows for $a_i$ to be a random (unobserved) variable, but assumptions must be made about the independence (or at least lack of correlation) between $a_i$ and $e_{it}$.
Another way to state this is that under most assumptions, assuming that $a_i$ is "fixed" will result in consistent asymptotic estimates, whereas ONLY under the independence assumption will "random" effects be consistent.   A Hausman-style test can be used to see if the Random effect assumption is valid.  In most of the cases for the observational data that economists use, the random effects assumption (i.e. the assumption of non-correlation between the unobserved random component and the error term) is invalid ... and this is why economists tend to favor the "Fixed-Effect model" when using longitudinal data.
I too have seen a lot of confused jargon in the literature, mostly because people from different disciplines are talking past each other, and the term "Fixed" and Random" when applied to "Effects" are not used to communicate, but rather used as inertial labels, and  cause inadvertent confusion.   At this stage, most of what goes under the rubric of "Mixed Models" would simply be the "Random Effects" model from the typical Econometrician's perspective (which would tend to use the label "random coefficient model" for the equivalent math).   That is, all the worry economists have about the inconsistency of the random effects assumption for panel data would (in observational data) still hold for any Mixed Model.
Answer: I think the problem is that you are focusing on properties of the random effects rather than the actual meaning of random effect.  It is simply a term in the model where the observed effect is considered to be a particular realization of a random variable that is characterized by a variance in the model.  When you look at the random effect in this general way rather than thinking in terms of specific cases such as subject-specific slopes you might see commonality in the examples in econometrics and statistics.
Having seen other answers and other discussions there may be cases where random effect has a different meaning and it does not just seem to be econometricians versus statisticians. But I still think that the most common and appropriate definition is the one I gave above.


Submit not executed

Question: Why is my submit function never been executed?
/**
 * Implements hook_menu().
 */
function simpleexample_menu() {

  $items['simple-example-page'] = array(
    'title' => 'Simple Multi-Step Form',
    'page callback' => 'create_request_custom',
    'access callback' => TRUE,
  );

  return $items;
}

function create_request_custom() {
  module_load_include('inc', 'node', 'node.pages');
  $form = node_add('request');

  $form['simpleexample'] = array(
    '#type' => 'value',
    '#value' => simpleexample_get_session(),
  );
  $form['actions']['submit']['#submit'][] = 'create_request_custom_submit';

  return $form;
}

function create_request_custom_submit($form, &$form_state) {
  // never executing that
  $params = array(
    'nid' => $form_state['values']['nid'],
    'session_id' => $form_state['values']['simpleexample'],
  );
  .....

}

Answer: Forms need to be called via drupal_get_form() that processes your $form array into a form. Including the submit handling. So it should look like more like this:
/**
 * Implements hook_menu().
 */
function simpleexample_menu() {

  $items['simple-example-page'] = array(
    'title' => 'Simple Multi-Step Form',
    'page callback' => 'drupal_get_form', // Tell drupal to use the drupal_get_form function.
    'page arguments' => array('create_request_custom'), // Pass the form function as argument for the page callback.
    'access callback' => TRUE,
  );

Also you'll probably want to add the $form and &$form_state variables to the form function.
function create_request_custom($form, &$form_state) {
  // Your form function
}

Submit not executed


How to set or get the triggering element upon submit a form using JQuery?

Question: I have a Drupal 8 form with checkboxes.
The form submits upon clicking on a checkbox using JQuery.
Here is my code.
 $('#edit-event-types input[type=checkbox]').on('change', function(event, ui){
    $('#events-to-doc').submit();
  })

Unfortunately, if there isn't any submit button in the form, then function submitForm in the form class doesn't execute. But I don't need in a submit button on the form, I want to submit the form clicking on the checkboxes.
Can I somehow set the checkboxes element as the triggering element with Jquery? I need the function submitForm to execute and $form_state->getTriggeringElement() return the checkboxes as the triggering element.
Answer: Submit buttons (and their names) are special for Drupal. I'm not sure how this changed in D8, but in D7, the submit button name was used (IIRC) to determine which one was clicked.
I would suggest adding the submit button, hiding it with CSS and triggering a .click() to the button instead of doing .submit() directly. You can then either get the checkbox value if that's enough, or use a hidden field and some JS to determine which checkbox triggered the submit event (last clicked checkbox).


views in D7 :: remove doubles in exposed filter list

Question: I have two content types, one (A) refering to the other (B). I also have two languages and I want to create a view where I show a list of all content type nodes of type A with an exposed filter, filtering the refering content type nodes of type B. this will show me all nodes of A that refer to B.
so my filters are

content type (A)
language (en)
refering node (exposed)

this works great but inside my exposed filter list of all nodes of type B every node is shown two times, representing every language translation.
I now want to only show the english nodes of type B in the exposed filter list.  how could I do that?
thnx!
ps: I tried to use the filter groups, but this did not work.
Comment: How are you planning to select the language for the exposed filter?
Comment: I only wanted to show the english (original) ones.
Answer: The Views exposed filters block is a Drupal form, one that can be modified via a hook_form_alter or hook_form_FORM_ID_alter implementation. Here is a simple sample implementation of the more generic hook_form_alter.
/**
 * Implements hook_form_alter.
 */
function foo_helper_form_alter(&$form, &$form_state, $form_id = NULL) {
  if($form['#id'] == 'views-exposed-form-content-page') {
    // Do something with mah filters...
  }
}

If you are in doubt of what #id to use, you can always just implement this hook, go to your Views page, and watch the output of the $form variable to figure out what is the correct id to use. If you are in D7, the ID you are looking for will most likely be prepended with views-exposed....


How should the text file describing mobile app ad providers be handled

Question: I understand, that the app-ads.txt file should be hosted under a domain (or a subdomain) root.
The problem is that currently we do not have any registered domain/subdomain, the link we provide in Google play store points to our Facebook page.
I've tried a free app-ads-txt.com service, and it almost works, except it would not allow comment strings (starting with "#") and crashes when trying to update the file content with a second google.com entry...
Any suggestions on other ways to host the app-ads.txt file?
Answer: I've tried the next steps and apparently, now it allows # comment strings and it doesn't crash when duplicating a record

Visit app-ads-txt.com
Register an account
Add your application
Generate your APP-ADS.TXT
Publish your APP-ADS.TXT: You will get one link to publish on your Developer Console (Store listing Website option) and wait 24 hours.


How do I modify the query parameters?

Question: I want to modify query parameters used when accessing a Drupal page. I tried implementing hook_url_inbound_alter(), but it only allows to parse/modify the path, and it doesn't allow any interaction with the query string.
I see there is also drupal_get_query_parameters(), which allows to read the query parameters.
I could detect the presence of a query value in index.php and do a string replacement on the value if needed, but I don't want to pollute the front controller.
Do you have any better advice?
Comment: You would need to modify the global `$_GET` at some early stage, maybe `hook_boot`
Answer: 1) you need to implement EventSubscriber, use KernelEvents::REQUEST in getSubscribedEvents() method
2) then you use \Drupal::request()->query->set('key', 'value');
Comment: Thanks for your answer but is this for Drupal 8? I am using 7.
Comment: Add \Drupal::request()->overrideGlobals(); after modifying the query parameters in order to persist changes when further reading the query parameters

How do I modify the query parameters?


Show full post on front page?

Question: When I publish to the front page, it shows part of the posts. My posts consist of just a file upload. However, the user must click on the post/click on the "Read more" button to see the file upload. How would I make Drupal display this file on the front page within the post?
Answer: If you are using Drupal 7 you may change the teaser format for the content types promoted on front page. Navigate to "Home » Administration » Structure » Content types » YOUR CONTENT TYPE » Manage display" and click the "teaser" sub tab; then change the format for the body field from "Summary or trimmed" to "Default".
Notice that this will affect some other pages (taxonomy and views).
Answer: I would replace the frontpage with a view provided by the Views module; there is even a default View that comes with the module. Initially, it emulates the standard frontpage, but is far more configurable. I can't post a full "How to use Views" answer here, but in short, what you will want to add is a "Field", pick the "File" category, and there you can output a direct link to the file.
Video series about using Views.
Answer: ya.teck and kiamlaluno are correct except that you may not see a "teaser" tab. If this is the case, then be sure to check the custom display options for your content type and activate "teaser" - it should be one of the check boxes available. Then save the content type and you should then see the teaser tab/button mentioned above.

Show full post on front page?


Algorithm to determine if integer matrix is similar to symmetric integer matrix with nonnegative entries

Question: Let $A\in M_n(\mathbb{C})$ be a matrix with integer entries (treated as a matrix over the complex numbers).
Is there an efficient way to check if $A$ is similar to a symmetric matrix with nonnegative integer entries?
Partial answers will be appreciated as well (for example, discard the condition of positivity, or give interesting necessary conditions).
Ofcourse, such $A$ must be diagonalizable, and my $A$ is indeed diagonalizable.
Answer: This is a partial answer. Let's look only for matrices that are similar to matrices with positive entries (not necessariy symmetric). Some simple sufficent conditions can be obtained.
For example, let $A$ be a matrix of order $n$ with integer entries. Let us assume that the eigenvalues of $A$ are $\lambda_1,\ldots,\lambda_n$. Notice that the trace of $A$ can not be  negative. Thus, $\lambda_1+\ldots+\lambda_n\geq 0$.
A sufficient condition for this $A$ to be similar to a matrix with non negative integer entries is $$\lambda_1>0>\lambda_2>\ldots>\lambda_n\text{ and }\lambda_1+\ldots+\lambda_n\geq 0 .$$
Proof:
The minimal polynomial $m_A(x)$ of $A$ is the caractheristic polinomial since $A$ has distinct eigenvalues. So, $m_A(x)=(x-\lambda_1)\ldots(x-\lambda_n)=x^n+a_{n-1}x^{n-1}+\ldots+a_1x+a_0$.
Let's prove by induction on the degree of the polynomial that $a_{i}\leq 0$ for $0\leq i\leq n-1$. Notice that $a_i$ is an integer, since the entries of $A$ are integers. For $n=1$, $m_A(x)=(x-\lambda_1)$.
Suppose the result is true for $n=k$.
Consider $(x-\lambda_1)\ldots(x-\lambda_k)=x^{k}+b_{k-1}x^{k-1}+\ldots+b_1x+b_0$.
By induction hypothesis $b_i\leq 0$ for $0\leq i\leq k-1$.
Now $(x-\lambda_1)\ldots(x-\lambda_k)(x-\lambda_{k+1})=(x^{k}+b_{k-1}x^{k-1}+\ldots+b_1x+b_0)(x-\lambda_{k+1})$
$=x^{k+1}+(b_{k-1}-\lambda_{k+1})x^k+(b_{k-2}-\lambda_{k+1}b_{k-1})x^{k-1}+\ldots+(b_0-\lambda_{k+1}b_1)x+(-\lambda_{k+1}b_0)$.
Notice that $b_{k-1}-\lambda_{k+1}=-\lambda_1\ldots-\lambda_{k+1}\leq 0$
Notice that $b_{k-s-1}-\lambda_{k+1}b_{k-s}\leq 0$, because $\lambda_{k+1}<0$ and $b_{s}\leq 0$.
Thus,all coefficients are smaller or equal to $0$.
Finally, by the rational canonical form this matrix $A$ is similar to the companion matrix of the polynomial $m_A(x)$, which has non negative integer entries.  $\square$


Pre-Processing audio data for whale sound classification using CNN

Question: Previous researchers have used techniques like Denoising using Spectral Subtraction method and calculating Short Time Fourier Transform (STFT) by dividing the audio data into fixed size chunks and then calculating the frame spectrogram for each of these chunks.
The image below shows how the author has pre-processed his data by manually extracting the frame and calculating it's spectrogram after applying the above-mentioned methods.
What pre-processing techniques exist for such kind of audio data where you need to use the spectrogram images for developing a CNN model, given that all audio files will be of varying length and bit-rates?
Answer: The best way is to split the audio files (or live input) into analysis windows of fixed size. Then combine each window prediction into a file-level prediction. The classifier can be trained per analysis window. Or per audio file using Multiple Instance Learning.
The window size must be set based on the event of interest, normally a bit longer than the typical event duration. If some files are shorter then the analysis window, pad the input. Based on your image, 1 second may be a reasonable starting point.


Write 22 correct to 2 decimal places.

Question: The book says 22.00 but surely one can't go ahead and write this number correct to 2 decimal places as we don't know what they are. Unless it is standard practice to use zeros when are certain number of decimal places are required. What is the correct answer here?
Comment: "we don't know what they are": we know they are all zeroes.
Comment: if you had 22 pounds - how would you write that as pounds and pence?  £22.00 is the answer - UK and US money is often written to 2 decimal places.  In book keeping they would write £22.01 and £22.99 - but also £22.00 for a whole amount
Comment: If you are asked to write a whole number to k decimal places, then what could you do besides writing k zeros after the decimal point? Your book is correct.
Answer: The correct answer is $22.00$. We know all infinitely many decimal places of the integer $22$ in its usual decimal representation: every one of them is $0$.
Say the decimal expansion of $22$ is $22.d_1d_2d_3\ldots\;$; by definition this means that
$$22=22+\frac{d_1}{10}+\frac{d_2}{10^2}+\frac{d_3}{10^3}+\ldots\;,$$
where each $d_k\in\{0,1,2,3,4,5,6,7,8,9\}$. And this is the case if and only if
$$\frac{d_1}{10}+\frac{d_2}{10^2}+\frac{d_3}{10^3}+\ldots=0\;,$$
which in turn is the case if and only if $d_k=0$ for $k=1,2,3,\ldots\;$. Thus, every decimal place in the (usual) decimal expansion of $22$ is $0$, and when we round to two places, we get $22.00$.
In fact $22$ does have another decimal expansion: $22=21.999\ldots\;$, because $0.999\ldots=1$. However, rounding this to two decimal places again results in $22.00$.
Comment: Nice elementary explanation as usual.
Answer: In the case of an integer such as 22 we do know what the decimal places are. There are an infinite number of zeroes. However it is common practice not to write any of them, so we tend to think of an integer as having no decimal places. So any integer $N$ to two decimal places is $N.00$.
Answer: Perhaps you are confused with the use of so-called significant figures in other sciences. Here, the number $22$ sometimes means "a number in the range $[21.5,22.5)$ that we did not determine more precisely.
However, in mathematics, all numbers are exact. The number $22$ means exactly $22$, to any precision.

Write 22 correct to 2 decimal places.


Aplicação Android Incompatível com Tablet (Informação PlayStore)

Question: Desenvolvi recentemente uma app que publiquei na google play store com todos os requisitos necessários, no entanto ao tentar efetuar o download num tablet Asus Zenpad 3S 10 Z500M este surge como incompatível e não permite efetuar o download.
Andei a ver a lista de equipamentos compatíveis com a  minha app que a google play store divulga e dezenas de tablet's são compatíveis...
Porque será que este modelo em específico não é compatível? A versão android é compatível 6.0.1, será pela resolução do ecrã? 9.7'' 1536 x 2048 pixels (~264 ppi pixel density), no entanto eu criei para todas as Views os layout-normal, layout-large e layout-xtra-large.
Aqui está o manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.nuno.bombeiros.bombeirospt">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.SEND_SMS" />

    <application
        android:name="android.support.multidex.MultiDexApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity.MainActivity" />

        <activity android:name=".SplashScreen.SplashScreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Pre_Hospitalar.Pre_Hospitalar" />
        <activity android:name=".User_Config.User_Config" />
        <activity android:name=".Pre_Hospitalar.Calculadora_Coma_Glasgow" />
        <activity android:name=".Incendios_Urbanos.CalculadoraAutonomiaARICA" />
        <activity android:name=".Incendios_Urbanos.IncendiosUrbanos" />
        <activity android:name=".Noticias.UI.Feed.RssFeedActivity" />
        <activity android:name=".Noticias.UI.Article.ArticleActivity" />
        <activity android:name=".Materias_Perigosas.MateriasPerigosasActivity" />
        <activity android:name=".Materias_Perigosas.DatabaseHandler.ONU_UI.OnuResultActivity" />
        <activity android:name=".Materias_Perigosas.DatabaseHandler.NAME_UI.NomeResultActivity" />
        <activity android:name=".Materias_Perigosas.DatabaseHandler.Error_UI.ErrorMessageMateriasPerigosas" />
        <activity android:name=".Corpos_de_Bombeiros.CorposBombeirosActivity" />
        <activity android:name=".Corpos_de_Bombeiros.DetailCB.CorposBombeirosDetailActivity" />
        <activity android:name=".Incendios_Florestais.IncendiosFlorestaisActivity" />
        <activity android:name=".Incendios_Florestais.PontosAgua.PontosAguaActivity" />
        <activity android:name=".Incendios_Florestais.PontosAgua.ListaConcelhoActivity" />
        <activity android:name=".Incendios_Florestais.PontosAgua.ListaActivity" />
        <activity android:name=".Incendios_Florestais.PontosAgua.Error_UI.ErrorMessagePontosAguaActivity" />
        <activity android:name=".Incendios_Florestais.PontosAgua.DetailActivity.PontosAguaDetailActivity" />
        <activity android:name=".Incendios_Florestais.FDI.FDIActivity" />
        <activity android:name=".Incendios_Florestais.FDI.FDI_Baixo.FDI_BaixoActivity" />
        <activity android:name=".Incendios_Florestais.FDI.FDI_Moderado.FDI_ModeradoActivity" />
        <activity android:name=".Incendios_Florestais.FDI.FDI_Alto.FDI_AltoActivity" />
        <activity android:name=".Incendios_Florestais.FDI.FDI_Muito_Alto.FDI_Muito_AltoActivity" />
        <activity android:name=".Incendios_Florestais.FDI.FDI_Extremo.FDI_ExtremoActivity" />
        <activity android:name=".Creditos.CreditosActivity" />
        <activity android:name=".Incendios_Urbanos.GlossarioIncendiosUrbanosActivity" />
        <activity android:name=".Materias_Perigosas.Materias_PerigosasMenuActivity" />
        <activity android:name=".Materias_Perigosas.Pictograma.PictogramaDetailActivity" />
        <activity android:name=".Materias_Perigosas.Pictograma.PictogramaActivity"></activity>
    </application>

</manifest>

Alguém me poderá ajudar e tentar perceber o que que se possa estar a passar?
Comment: Analisei melhor os dispositivos compatíveis, e penso que o problema da compatibilidade estará no uso da funcionalidade de telefone, neste caso SMS. Existe possibilidade de eu poder usar também em tablet's sem cartão sim? desativando neste caso a funcionalidade? Se sim, como poderei fazer?
Comment: Se eu usar
 haverá algum problema futuro recorrente? Dentro da app não haverá problema, pois eu tenho a condição que verifica se tem cartão SIM ou não na funcionalidade de envar SMS
Comment: [Algumas permissões](https://developer.android.com/guide/topics/manifest/uses-feature-element.html#permissions) relacionadas a hardware implicam que os recursos subjacentes de hardware sejam obrigatórios por padrão. Por isso tem de utilizar `` para que a aplicação possa ser instalada em dispositivos que não sejam telefones.
Answer: O Android pode ser executado em diferentes tipos de dispositivos. Ele está presente em telefones, tablets, televisões e até em carros.
O hardware de cada um desses dispositivos têm características diferentes, o que obriga a que as aplicações sejam construídas de forma a tê-las em consideração, caso queiramos que elas corram no maior número de tipos possível.
Para facilitar esse objectivo, o Android fornece um framework de desenvolvimento de aplicativos dinâmico que permite ao programador disponibilizar recursos a serem utilizados em função das características do dispositivo, por exemplo diferentes layouts para diferentes dimensões de tela ou diferentes tamanhos de imagens para diferentes densidades de telas.
Por outro lado a aplicação pode ter requisitos de hardware que o dispositivo não pode satisfazer, como por exemplo enviar SMS ou ter um determinado sensor.
É da responsabilidade do programador indicar, no AndroidManifest.xml, quais são esses requisitos através
do elemento <uses-feature> e, programaticamente, lidar com facto de eles poderem não estarem disponíveis.
O uso, só por si, de algumas permissões implicitamente obrigam à existência de requisitos de hardware, tornando a aplicação incompatível com determinados dispositivos.
O Google Play apenas deixa instalar aplicativos compatíveis com o dispositivo.
Essa filtragem é feita baseada nos requisitos implícitos e nos explicitamente declarados.
No seu caso, pelo facto de ter a permissão
<uses-permission android:name="android.permission.SEND_SMS" />

implicitamente requer que o dispositivo seja um telefone. É como tivesse declarado
<uses-feature android:name="android.hardware.telephony" android:required="true" >

no AndroidManifest.xml.
Para que a sua aplicação possa ser instalada em dispositivos que não sejam telefones tem de explicitamente indicar que tal requisito não é necessário, usando o atributo android:required
<uses-feature android:name="android.hardware.telephony" android:required="false" >

Referências:

Device Compatibility
Elemento <uses-feature>


There is no token table

Question: I installed the latest Drupal 8 version (8.9.18) on my host with the Rules (8.x-3.0-alpha6), the Token, and the Rules Token modules.
I can't see any table showing the list of the allowed tokens, in the rules action form. I want to use the node title or the node author for the Send mail action, but there is no token information or guidance.
I tried to add [node:title] and [node:nid] in the mail body, but they aren't replaced with the node title and the node ID.
What's the problem? How can I resolve it?
Answer: Note: What you refer to as the "token table" is actually a form element (named "token_tree") that is provided by the contributed Token module.  You need the contributed Token module in both Drupal 7 and Drupal 8 if you want to use this form element - it is not part of Token module functionality included in core Drupal 8, you still need the contributed Token module.
That said, Token module tokens are not used by Rules in Drupal 8. Instead, Rules uses typed-data Twig tokens, similar to how Views works. See for example https://www.drupal.org/docs/contributed-modules/d8-rules-essentials/token-replacement and related pages in that documentation guide (which includes many examples of how to use these tokens, how to find out what tokens are available, how to modify token values, etc.)
Comment: thanks a lot. it was very helpful for me. but I think there must be a token statement generator in rules page based on twig protocols. exactly same as drupal 7. because nobody can memorize all tokens and for each token I have to go into data selection mode, find a token and then return to direct input and put found token into {{ }}
Comment: There will eventually be a 'token browser' UI element included in Rules, but that requires someone to do the work and create that UI element. That does not currently exist. If this is important to you, please help in the Rules issue queue.

There is no token table


Examples of stochastic processes that don't exist

Question: $B_t$ is said to follow a Brownian motion if i) $B_0=0$, ii) $B_t$ is continuous a.s. iii) $B_t$ has independent increments iv) $B_t-B_s\sim N(0,t-s)$. Then Wiener would go on to show that such a process does indeed exist.
What are some examples of simple and interesting stochastic processes, that can be proven to not exist?
Answer: A simple attempt to model "white noise" would be a process $W(t)$ on  $[0, \infty)$, such that $\int_0^s W(t)\; dt = B(s)$ is a Brownian
motion.  But that does not exist because Brownian motion is almost surely nowhere differentiable.  A more sophisticated formulation of white noise must be used, using generalized functions.


Oreo - Autofill Framework background highlight color

Question: Is it possible to change EditText autofill highlight color? By default  it has yellow background that may be incompatible with application design.
Answer: According to Android documentation, to change highlight color you have to edit application theme. You can set color or drawable to android:autofilledHighlight parameter.

To apply theme to an application set theme in AndroidManifest.xml
<application ...
android:theme="@style/AppTheme">


React Datepicker Error: Cannot read properties of null (reading 'usestate')

Question: I'm creating a test for the react datepicker, but nothing I do seems to make it work correctly. Whenever I try adding a datepicker to my function, it throws an error.
import React, { useState } from "react";
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

const DatePickerTest = () => {
    const [startDate, setStartDate] = useState(new Date());

    return (

            <DatePicker selected={startDate} onChange={(date) => setStartDate(date)} />

    );
}

DatePickerTest.defaultProps = {};

export default DatePickerTest;

I am completely stumped on this. I already checked the version of react, and I believe 18.2.0 is compatible with even the highest version of the datepicker. I checked all other existing code, and it really only happens when I add the datepicker in. The rest of the code works great even if I add other objects rather than the DatePicker.
Comment: Are you using React Server Components ? Perhaps you need to add `"use client"` at the top; Otherwise the code, as is, should work.
Comment: @GabrielePetrioli I tried that, and I'm still getting that error for some reason. I don't understand what's going on at this point.
Answer: Have you imported the necessary CSS for react-datepicker?

import 'react-datepicker/dist/react-datepicker.css';

?
Comment: Yeah, I added that. I still get the usestate error.


Why does $\min(X,Y)$ and $|X-Y|$ have the same distribution when $X,Y\sim U(0,1)$?

Question: Say $X,Y \sim U(0,1)$ be two independent uniform random variables, and $T=|X-Y|$. I would like to find the CDF of $M=\max(X,Y)$, $L=\min(X,Y)$, and  $T$. I find the CDF of $M$ and $L$ as
$$P(M\leq t ) = P(X\leq t)P(Y \leq t) =t^2$$
$$P(L \leq t) = 1-P(X\geq t ) P(Y\geq t) = 1-(1-t)^2$$
To find the CDF of $T$, I draw a rectangle with unit length and width, and compute the area within the region $|X-Y| \leq t$, which turns out to be $1-(1-t)^2$.
My question is how come the CDF of $L$ and $T$ are the same when one is the minimum of two uniform r.vs and the other is the absolute difference of two uniform r.vs? Is there something wrong with my computation?
Thanks.
Answer: Your calculations are correct! Just for the sake of completeness, you have to write
$$F_M(t)=t^2\mathbb{1}_{(0;1)}(t)+\mathbb{1}_{[1;\infty)}(t)$$
...and similar notation for the other CDF's. This because the CDF is defined over all $\mathbb{R}$
Why the law of L and T are the same? As you did to find $F_T$ do the same drawing to find $F_L$ and you will realize that the integration area is the same
Comment: Cool explanation. Thanks a ton.
Answer: Imagine a line segment $OA$ of unit length.
On this line segment imagine two points $X,Y$ each at a distance of $x, y$ from point $O$ respectively.
These two points divide $OA$ into three smaller segments, whose length is equal to $min(x,y)$; $|x-y|$ and $1 - max (x,y)$.
From symmetry it can be seen that the three values should have same Expectation values.
Comment: $max(X;Y)$ has not the same expectation of the other rv's. This is self evident if you look at the drawing in my answer.
Comment: @tommik yes, it's a typo. I'll correct it.
Comment: Sorry I don't get why all three segments should have same expectations. I find $E[M]=2/3$ and $E[L]=1/3$. Am I correct?
Comment: Symmetry. The only rule you have is the sum of lengths of three segments should be one. And this rule is same to all three segments, which means their Expectation should be equal and be equal to one.
Comment: @ForumWhiner Yes, E[L] = E[T] = E[1 - M] = 1/3
Comment: Got it. Thanks.
Comment: xax and @tommik may you please help out in these related questions: [More random points on a circle](https://math.stackexchange.com/questions/4058726/more-random-points-on-a-circle) ?


duvida quanto a variavel session_start()

Question: Eu coloquei o método session_start() para fazer com que o nome do utilizador apareça na tela quando ele fizer o login nas paginas seguintes, mas eu queria colocar o "nome" dele em vez do "email" segue o código que eu fiz:
Código para validar a entrada do usuário.
<?php

session_start();

require_once("conexao.php");

$conn = mysqli_connect('localhost', 'root', '') or die ( mysqli_error() );

mysqli_select_db($conn, 'projeto') or die ( mysqli_error() );

$user = $_POST['email'];
$pwd = $_POST['senha'];

$query = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM nutricionista WHERE email = '$user' AND senha ='$pwd'"));

if($query == 1){
    $_SESSION['email'] = $user;
    $_SESSION['senha'] = $pwd;

    header("location: menuNutricionista.php");
} else {
    echo "";
}

?>

Aqui já é a pagina HTML aonde vai aparece bem-vindo + nome do usuário
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="../css/style.css">

    <link href="https://fonts.googleapis.com/css?family=Merriweather" rel="stylesheet">
    <link rel="shortcut icon" href="imagens/favicon.png" />

    <?php

    session_start();

    if((!isset ($_SESSION['email']) == true) and (!isset ($_SESSION['senha']) == true))
    {
    unset($_SESSION['email']);
    unset($_SESSION['senha']);
    header('location:index.php');
    }

    $logado = $_SESSION['email'];
    ?>

        <?php echo"Bem-vindo
$logado "; ?>

Answer: Ignorando todos os problemas, que existem pelo menos quatro, você deve fazer uma nova query para pegar essas informações, supondo que você tenha a informação do nome salva em alguma coluna do banco de dados, relacionado ao e-mail.
<?php

session_start();

// Se não houver as informações você encerra a página e redireciona
if(!isset($_SESSION['email'], $_SESSION['senha'])) {
     unset($_SESSION['email'], $_SESSION['senha']);
     session_destroy();

     header('Location: index.php');
     exit();
}

$email = $_SESSION['email'];

// Havendo a sessão você busca o nome
$stmt = mysqli_prepare($conn, 'SELECT nome FROM nutricionista WHERE email = ?');
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);

mysqli_stmt_bind_result($stmt, $logado);
mysqli_stmt_fetch($stmt);

?>

Isto tem o mesmo principio que fez na outra página, na primeira. Selecionamos o nome (supondo que este seja o nome da coluna do MySQL) onde houver o email igual ao da sessão, definimos o e-mail em mysqli_stmt_bind_param para que ele seja o valor do primeiro ? da nossa query.
Depois, o resultado no nome será definido em $logado, como indicamos em mysqli_stmt_bind_result.
Então para exibir você utiliza:

    Bem vindo

    <?= htmlentities($logado, ENT_QUOTES | ENT_HTML5, 'UTF-8'); ?>

No método de "segurança vai com deus", você pode também usar:
$result = mysqli_query($conn, 'SELECT nome FROM nutricionista WHERE email = "'. $_SESSION['email'] .'"');

list($logado) = mysqli_fetch_row($result);

Que é exatamente o mesmo que você fez na primeira página.
Answer: Bom se não for pra mexer muito no seu código, creio que você só vai precisar criar uma nova query que lhe traga um array.
Faça:
$query2 = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM nutricionista WHERE email = '$user' AND senha ='$pwd'"));

Então defina na SESSION o array do usuario. Exemplo:
$_SESSION['nome'] = $nome

Isso claro, contando que no seu Banco de Dados já exista uma coluna "nome". Substitua pelo nome correto que está na sua tabela.
Na sua página HTML você pode substituir a linha que define o usuario logado por:
$logado = $_SESSION['nome'];
E na chamada para mostrar o nome do usuário pode usar o $logado mesmo.
Não lembro se a chamada do mysqli está correta, se não der certo me avisa que reescrevo aqui de novo.


Views exposed filter, filter on multiple fields with dropdown and one textbox

Question: I'm working on a views integration where the table and its fields are exposed to views. I want to give users the ability to filter on results of this view based on 1 of 3 fields.
I want each of the three fields in a drop down, and one text field where the user can input search terms.
Then once submitted, views will filter on the specific field and terms entered.
Is this possible? I found this discussion which has no resolution: https://drupal.org/node/732458
I'm thinking I may need to just create exposed filters for each of the three fields, and then alter the form a bit to get it how I need it.
To clarify further:
I want to expose three filters, each one searches a field by the text a user entered. I can do this in Views no problem, and it produces three distinct text fields for each of the three filters. Instead, I want the user to have just one text field, and a drop down to select which one they want to search on.
Comment: do you mean dropdown with textbox
Comment: I clarified in a comment below.
Comment: @Brian comments are for asking for clarifications. To provide them, edit your question.
Comment: @Mołot updated post
Comment: I also need this and still not an easy way of doing it in Drupal
Answer: You have a couple of options to do this:

As you suggested just provide the user with drop-down field with the list of the criteria and single text field, then implement hook_views_query_alter where you change the where clause based on the dropdown field value. More can be found here
Your second option is to use a 'Combine fields filter` with all the fields you want to search with and let the user know how your search works using a help text.
Answer: If I understand correctly: you want to expose 3 dropdown filters, but allow only 1 of them for input.
You can hide or show filters by using views dependent filters: https://drupal.org/project/views_dependent_filters, but then you need a filter that sets up 3 values for showing 1 of your 3 independent filters.
But, why don't you use OR instead of AND with those filters? It would give results and you can sort it as you want.
Comment: I don't want to expose three dropdown filters. I want to expose three filters, each one searches a field by the text a user entered. Normally this produces three distinct text fields, one for each field. Instead, I want the user to have just one text field, and a drop down to select which one they want to search on.


Sonar Qube plugin Failed to install on Mule Studio

Question: I tried to install sonar qube plugin from http://downloads.sonarsource.com/eclipse/eclipse/ in Mule Studio Version (3.5.0)  with Mule runtime (3.4.0). For my requirement I cannot got with the latest version of studio.
The following is the error message I am getting when trying to install the plugin in Mule studio
The operation cannot be completed.  See the details.
Details:
Cannot complete the install because one or more required items could not be found.
  Software being installed: SonarQube Integration for Eclipse 188.8.131.5250804-1512-RELEASE (org.sonar.ide.eclipse.feature.feature.group 18.104.22.16850804-1512-RELEASE)
Answer: I tried installing the Sonar Qube plugin from the Eclipse marketplace, SonarQube 3.5.0 was listed there, but it was also mentioned that it has been deprecated and SonarLint 1.1.0 should be used instead.

I went ahead with the installation but as you reported it couldn't be completed as there seems to be a problem with the SonarQube Integration for Eclipse component.
However, can you try creating an offline copy of the update site and then try installing the plugin in studio?
http://mcuoneclipse.com/2014/07/03/replicating-an-eclipse-update-site-for-offline-usage/
EDIT
I continued with the same SonarQube installation, it took a lot of time and eclipse had to look for various alternate solutions (15 in total), but it finally came up with this dialog.

So, while installing the plugin, unselect the 2 components (if you don't need it) and move ahead with installation, I was able to successfully complete it, eclipse restarted and it was all done.
-Shanky G.


IE8 Google Visualization Permission Denied

Question: I have a Google charts solution working in most browsers except IE8. When I move the mouse over the chart I get a permission denied error from a Google visualization API script (line 83, char 16).
The script in question is this one: http://www.google.com/uds/api/visualization/1.0/c3581c99759b4a64cb69ca21ab634266/format+en_GB,default+en_GB,ui+en_GB,corechart+en_GB.I.js
Here is a screenshot of the IE8 error: http://screencast.com/t/Ccyqfmuv
Just to be clear, the chart renders correctly and the error only seems to occur when the chart is hovered over.
I have tested in IE9/10 and all is fine. I have also tested in http://www.browserstack.com/ in case there was some odd local multiple IE thing going on.
Any suggestions on what it might be?
Comment: Post javascript code reproduces the problem and I'll look into it.
Answer: see if the following fix works:
function drawChart() {
   var __instance__ = arguments.callee;
   var data = google.visualization.arrayToDataTable(<your data here>);
   var chartCnt = document.getElementById('chart-container');

   !__instance__.testChart &&
       (__instance__.testChart = new google.visualization.BarChart(chartCnt));

    __instance__.testChart.clearChart();
    __instance__.testChart.draw(data, { width:600, height:400 });
 }

ref: https://groups.google.com/forum/#!topic/google-visualization-api/QoCPFv1tKkQ
Comment: Or you could simply call .clearChart() when you discard a chart instance from the DOM.. worked for me.


Write a logical expression for "Everyone who has studied medicine and practises medicine is someones doctor."

Question: This question was on my exam. I cannot remember the exact sentence but this was basically it. How can I write a logical expression for this sentence using universal and existential quantifiers? Can someone explain to me please?
Comment: $S \:  \mbox{AND} \: P \implies D$?
Comment: Or more complicatedly, perhaps: If $X$ is the set of people then: For all $n \in X$ we have $$S(n) \: \mbox{AND} \: P(n) \implies [\exists m \in X \: \mbox{such that} \:  n=D(m)]$$ where $S(n)$ is true if person $n$ studies medicine, $P(n)$ is true if person $n$ practices medicine, and $D(m)$ is the doctor for person $m$.
Comment: Can you please explain which sentences did you assign the letters for?
Answer: "Everyone who has studied medicine and practices medicine is someones doctor."
So it looks like we have a few main concepts we need to be able to describe:

A person who has studied medicine: Call it $S(x)$ when $x$ has studied medicine
A person who practices medicine: Call it $P(x)$ when $x$ practices medicine
A person who is another person's doctor: Call it $D(x, y)$ when $x$ is $y$'s doctor

(alternatively, you could say $x = D(y)$, if you're ok with having equality as a concept rather than just using propositions)
So $S(x) \wedge P(x)$ means "$x$ studied medicine and $x$ practices medicine", i.e. it represents a person who both studied and currently practices medicine.
To describe "is someone's (i.e. an unspecified but existent person's) doctor", we mean that we know that there is someone for whom $x$ is that person's doctor, i.e. $\exists y\  D(x, y)$.
Hence, "Everyone who has studied medicine and practises medicine is someones doctor." becomes "For all people $x$ where $x$ has studied medicine and $x$ practices medicine, there is another person $y$ for whom $x$ is $y$'s doctor", or in our current notation:
$$\forall x \left(S(x) \wedge P(x) \rightarrow \left( \exists y\ D(x, y)\right) \right)$$
Comment: Thank you so much for the detailed answer!
Answer: You first need an impicit domain and some predicates.
For the domain of people:

$S(x)$ "$x$ has studied medicine",
$P(x)$ "$x$  practices medicine",
$D(x,y)$ "$x$ is the doctor of $y$".

So "Everybody who studied medicine and practices medicine, is somebody's doctor."
So "Everybody $x$: $S(x)\wedge P(x)$, is for somebody $y$: $D(x,y)$."
$$\forall x~((S(x)\wedge P(x))\to \exists y~D(x,y))$$
Or in Prenex canonical form:
$$\forall x~\exists y~((S(x)\wedge P(x))\to D(x,y))$$
Comment: Thank you for your answer!


Adjusting URL showed in address bar with routing

Question: I would like to optimize my URL showed in web browsers. I know Routing is perfect for that but I don't know if it is possible the way I want. I have a list of projects in a list. Each project have an ID, a name and a category. When navigating to the detail product page, the URL showed should be "/category/name". I know I can pass the ID, the category and the name in the ActionLink and adjusting the routing in Global.asax. I already do that but I still have the ID which is concatenate to the rest of the URL. This is ugly.
Here is an example:
The ActionLink in my view:
@Html.ActionLink(@p.Name, "Detail", new { projectID = @p.ProjectID, category = @p.Category, name = @p.Name })

the Global.asax:
routes.MapRoute(null,
    "{category}/{name}",
    new { controller = "Project", action = "Detail" }
);

The resulting URL:

As you can see, the projectID is always added to the end of the URL. How can I avoid that behaviour?
Thanks.
Comment: If category and name are sufficient, why do you need to pass projectId in your ActionLink?
Comment: @counsellorben: category and name are interesting to show in the URL in the address bar. ProjectID is necessary in the action controller to get the right project to pass to the detail view.
Comment: Then you should accept rouen's answer, since it will provide a clean URL.
Answer: routes.MapRoute(null,
"{category}/{name}/{projectID}",
new { controller = "Project", action = "Detail", projectID = UrlParameter.Optional }

);
will give you
/INDUSTRIE/Mailing/16
is that what you want ?
Comment: No, In the view, I would like to create an ActionLink with several things (projectID, name, category). projectID is used in the action controller to get the right project. Next, in the URL I don't wanna see the projectID. I think this is not possible.


Can NSURLSession objects be created multiple times with different configurations?

Question: Can I make a session object whenever I need with different configurations or  is there any constraint on creating session objects?
Answer: There are no constraints on creating session objects. In fact, the documentation clearly encourages creating additional sessions for handling requests with the same session configuration:

With the NSURLSession API, your app creates one or more sessions, each of which coordinates a group of related data transfer tasks. For example, if you are writing a web browser, your app might create one session per tab or window, or one session for interactive use and another session for background downloads.

This, of course, does not imply that you should create a separate session for each and every request you make.
Comment: The only constraints I know of are that A. each session consumes some memory, and B. limits on the number of simultaneous connections per host are IIRC per session, so you should generally use a small number of sessions and override various behaviors in the NSURLRequest where possible.
Comment: Thanks for the reply..  Looking forward for some more answers.. If none I'll mark your answer as correct. :)


Como alterar o valor do meta tag?

Question: Estou tentando alterar o valor das tags meta com dados advindos do database porém eles não são preenchidos dentro das tags. O valor é recuperado normalmente e exibido dentro do script quando o view-source é ativado porém o content da tag meta continua vazio.

<meta name="author" content="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta property="og:title" content=""/>
<meta property="og:url" content=""/>

Answer: "View source" mostra o a resposta servida para a requisição HTTP. Não é possível alterar o conteúdo desta resposta utilizando uma linguagem client-side.
JavaScript altera o DOM que é a representação estrutural do documento. Você pode visualizar uma representação serializada do DOM através das ferramentas de desenvolvedor (F12 no Chrome, Firefox ou IE), onde verá que seus elementos meta possuem o content atualizado pelo JS.

Dito isto, vários crawlers não executam (ou executam limitadamente) JavaScript, então para fins de SEO é mais recomendado printar o conteúdo das meta tags direto no source original:
<meta name="author" content="<?php echo $owner->name ?>" />
...

Comment: Porém, ainda vale lembrar que o Google realiza o parser tanto do JavaScript quanto do CSS para saber o que acontece na página e para dar relevância. O próprio Matt Cutts já falou sobre isso aqui: http://www.youtube.com/watch?v=B9BWbruCiDc
Comment: @RonnyAmarante sim, o Google funciona em cima de bruxaria. `;)` Brincadeiras aparte, eu ainda não tinha visto este vídeo, obrigado pela informação. `=]`
Comment: Obrigado, pessoal!

Como alterar o valor do meta tag?