Avoid call to a nested resolver if all the response fields have been already fulfilled

Question: I have a schema that receive a timeInterval iput on root query and the pass it to nested levels/resolvers. I'm trying to add validation to that input on root level, so if the validation fails then I should return and error and return null for other fields. The issue is that if I do this on root level then I don't know how to avoid graphql-tools calling nested resolvers (which fails because they don't have the timeInterval variable defined in the obj of each resolver).
Let me know know if you need and schema example and more details, thanks!
Answer: This is built in to how GraphQL.js, the reference implementation from Facebook, works. GraphQL-Tools is just a library on top that makes writing resolvers and schemas a bit nicer.
In GraphQL.js, the child resolvers are called whenever the parent resolver returns anything other than null or undefined, or if it throws an error.
So it sounds like in your case you are returning some data but with a single field missing, in which case GraphQL.js has no idea that it should avoid calling nested fields. Having more detail about your schema and resolvers would definitely help me come up with a specific solution.


NFTables Masquerade Not Working

Question: I am trying to setup NFTables to forward traffic coming in on a specific UDP port to another server with a different IP address. However, it appears my masquerade rule isn't working. When I send packets to this specific UDP port, it attempts to forward the traffic, but it doesn't change the source IP to the forwarding server's IP address. To my understanding, this should happen with a masquerade rule. Though, even an SNAT rule didn't work.
Here's TCPDump output showing what the issue is:
01:04:12.437619 fe:00:02:b8:34:ff > 56:00:02:b8:34:ff, ethertype IPv4 (0x0800), length 51: <MyIP>.7130 > <ForwardIP>.27015: UDP, length 9
01:04:12.437657 56:00:02:b8:34:ff > fe:00:02:b8:34:ff, ethertype IPv4 (0x0800), length 51: <MyIP>.7130 > <DestIP>.27015: UDP, length 9
01:04:14.145003 fe:00:02:b8:34:ff > 56:00:02:b8:34:ff, ethertype IPv4 (0x0800), length 51: <MyIP>.7130 > <ForwardIP>.27015: UDP, length 9
01:04:14.145051 56:00:02:b8:34:ff > fe:00:02:b8:34:ff, ethertype IPv4 (0x0800), length 51: <MyIP>.7130 > <DestIP>.27015: UDP, length 9

I want it to look like this:
01:04:12.437619 fe:00:02:b8:34:ff > 56:00:02:b8:34:ff, ethertype IPv4 (0x0800), length 51: <MyIP>.7130 > <ForwardIP>.27015: UDP, length 9
01:04:12.437657 56:00:02:b8:34:ff > fe:00:02:b8:34:ff, ethertype IPv4 (0x0800), length 51: <ForwardIP>.7130 > <DestIP>.27015: UDP, length 9
01:04:14.145003 fe:00:02:b8:34:ff > 56:00:02:b8:34:ff, ethertype IPv4 (0x0800), length 51: <MyIP>.7130 > <ForwardIP>.27015: UDP, length 9
01:04:14.145051 56:00:02:b8:34:ff > fe:00:02:b8:34:ff, ethertype IPv4 (0x0800), length 51: <ForwardIP>.7130 > <DestIP>.27015: UDP, length 9

Here's how my current NFTables is setup:
root@forwardtest:~# nft list tables
table ip compressor_forward

root@forwardtest:~# nft list table compressor_forward -a
table ip compressor_forward { # handle 1
        chain prerouting { # handle 15
                type nat hook prerouting priority dstnat; policy accept;
                udp dport 27015 dnat to 188.8.131.52 # handle 17
        }

        chain postrouting { # handle 16
                type nat hook postrouting priority srcnat; policy accept;
                masquerade random # handle 18
        }
}

I've tried removing the random NAT flag along with adding the persistent NAT flag. I do need the random NAT flag for my case. Adding/removing the flags didn't make a difference, though.
IPv4 forwarding is also set:
root@forwardtest:~# sysctl net.ipv4.ip_forward
net.ipv4.ip_forward = 1

IPTables (NAT) should also be removed. Here are some commands I've ran:
root@forwardtest:~# rmmod iptable_nat
rmmod: ERROR: Module iptable_nat is not currently loaded

root@forwardtest:~# lsmod | grep "iptable"

root@forwardtest:~# lsmod | grep "nft"
nft_masq               16384  1
nft_nat                16384  1
nft_chain_nat          16384  2
nf_nat                 40960  3 nft_nat,nft_masq,nft_chain_nat
nf_conntrack          139264  3 nf_nat,nft_nat,nft_masq
nf_tables             135168  8 nft_nat,nft_masq,nft_chain_nat

root@forwardtest:~# iptables -t nat -L -n
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination

root@forwardtest:~# iptables -L -n
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Please keep in mind lsmod | grep "iptable" returned nothing. I've also tried creating the postrouting chain with priority 1, but that made no difference.
The forwarding server is running Ubuntu 20.04 LTS on kernel 5.4.0-26-generic.
Is there anything I am missing in this case? With that said, I am new to NFTables. Therefore, I apologize if I am missing something obvious.
If you need additional information, please let me know!
Any help is highly appreciated!
Thank you for your time.
Answer: I resolved this issue. I upgraded the forwarding server's kernel from 5.4.0-26-generic to 5.6.11-050611-generic and it started working correctly. With that said, I did try restarting the forwarding server while on the older kernel and the issue continued after the restart. Therefore, I do believe the kernel was actually the issue here.
Definitely a strange issue. I will setup another test server soon running on 5.4.0-26-generic to confirm.
Thank you!
Comment: 2 years late, but on Ubuntu Server 20.04/focal 5.4.0-26-generic I have exactly the same issue. After hours of debugging and testing different configurations, I used HWE to upgrade to 5.15.0-56-generic, **and nftables NAT suddenly works**. Did you ever figure out the issue?

NFTables Masquerade Not Working


create class dynamically in c# from a list of string

Question: I have a list of string which would have a different event type names. The code is given below,
<code>public class Main
{
    public void Run()
    {
        List<string> classList = new List<string>
            {
                "Event_one",
                "Event_two"
            };

        foreach (string item in classList)
        {
            IEvent ent;
            switch (item)
            {
                case "Event_one":
                    ent = new EventOne();
                    ent.HandlEvent();
                    break;
                case "Event_two":
                    ent = new EventTwo();
                    ent.HandlEvent();
                    break;
            }
        }
    }
}

public class EventOne : IEvent
{
    public void HandlEvent()
    {
        throw new NotImplementedException();
    }
}

public class EventTwo : IEvent
{
    public void HandlEvent()
    {
        throw new NotImplementedException();
    }
}

public interface IEvent
{
    void HandlEvent();
}
</code>
How can I remove the switch statement and make the code more loosely coupled?.
My code sits inside the website/app_code.
Comment: You could use a dictionary instead of a switch statement, that might make the code a bit cleaner. See https://gist.github.com/jcebuck/6d57e70761ebabf1a3aa83fb27af077a
Comment: `remove the switch statement` what exactly do you want, then?  You clearly want a factory pattern, but you have to do some sort of test on your input to know which instance you want.  You could use reflection, but i wouldn't argue that it is better in your case until you have a reason to use it.
Comment: @james Buck thanks this is much cleaner.
Answer: You can do something like this:
<code>    public void Run()
    {
        List<string> classList = new List<string>
        {
            "EventOne",
            "EventTwo"
        };

        string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;

        foreach (string item in classList)
        {
            IEvent ent = Activator.CreateInstance(Type.GetType(assemblyName + "." + item)) as IEvent;
            if (ent != null)
              ent.HandlEvent();
        }
    }
</code>
Answer: Use a Factory that would return an instance of IEvent from a string, then call HandlEvent on it. However, that basically means you are moving the switch in the factory.
Comment: Yeah but I wanna do it without the switch.
Comment: Well, you have to make a decision sooner or later, however your code would abstract away your decision. If the strings were actual type names you could use some code to get the type based on name and then get an instance of it using Activator.
Answer: You could use reflection to instantiate the type specified by the name/identifier you have (possibly with an additional abstraction through an attribute on the types to map names).


Determining all possible values of $n$ in terms of $x$ of the following tree.

Question: Let $T$ be a maximal heap tree. Let $T$ hold the integers $1$ to $n$ as its nodes without duplicates. Let $x$ be a child of the root. What are the possible values that $n$ could take, in terms of $x$?
Clearly $x$ is not the maximum, so $n$ is greater than $x$. But I'm struggling with a more concrete description of all the possible values $n$ could be in terms of $x$.
Answer: The biggest possible number is clearly $n-1$.
Let $t = 2^{\lfloor \log_2(n)+1 \rfloor}$.
The size of the tree without the last layer is $t-1$.
We have $\min(\frac{t}{2}, n-t)$ nodes on the additional layer of the left subtree and $\max(0, n-t-\frac{t}{2})$ on the additional layer of the right subtree.
So the size of the left subtree is $\frac{t}{2} -1+ \min(\frac{t}{2}, n-t)$, and the size of the right tree is $\frac{t}{2} -1+ \max(0, n-t-\frac{t}{2})$
Each child of the root must be bigger than all the number in the corresponding subtree, so at least $\frac{t}{2}-1 + \max(0, n-t-\frac{t}{2})$ (the right subtree is the smallest one).
This can be easily achieved by filling the tree from the maximal value to the minimal one with a DFS.


set up an automated task/group of mysql queries to be run specified date of each month

Question: I need to update some records in the database on the 5th of every month. i know its time dependent so either i'll have to rely on server time or client time. As client time isn't reliable and my server is located in a different time zone and country, what is the best way to accomplish this?
Comment: you can use event scheduling or cronjobs.
Answer: Lets say your time is 5 hours ahead of your server time and you want to have this job run at 10 am your time, then you can simply schedule it to run at 5 am on 5th of each month. Now even if you change your computer's clock this will not effect server time. Unless you change server time. You can schedule a cron job to run like that easily.
Edit:
There is no other reliable way of scheduling that I know of. for NIX based systems its cron jobs and for windows its task scheduler. However if you rely on client connection being open at 10 am on every 5th then rather do it manually, cause its no more automated then as you asked.
I don't really know if there are more ways, but best yes surely, for me, is Cron Job.
Also, for cron jobs you do not need to write any code. You can call your existing PHP script on a scheduled time by the cron job manager itself. It just needs to see which program to call, which on your cause is php and then which file to call.
Edit
Since you mentioned you use a cPanel, here is the guide on cPanel from official cPanel documentation
Cron Jobs
Comment: @NikhilVerma Yea sure thing, but first would you please like to mention which operating system does your server have and which administration panel you use
Comment: what if you are only using a free host? is it possible to use a cron job?
Comment: are cron jobs the best/only way? i have never tried that. can you write a sample code or point to some resource? and yes as @Vainglory07 said, does every host provide a cron job facility? mine is a shared server.
Comment: @HankyPankyㇱ is right..me too is really interested on want what you are asking **Nikhil Verma** .. but i have no choice because my host doesn't provide a cron job facilty..hoping for more/some alternatives..
Comment: @HankyPankyㇱ  some cronjob tutorial or resource you can point to.
Comment: i have a lamp stack installed with cpanel.


Preciso criar um Arraylist em Java

Question: Preciso criar um programa que funcione como uma biblioteca. Eu consegui criar uma parte do programa que cria um livro, dados as informações como parâmetros. Agora preciso criar uma ArrayList que dê para armazenar vários livros, ir adicionando e removendo usando outras funções. Vou mandar o código para criação de um livro, se alguém puder me ajudar, eu agradeço.
public class biblioteca {
    public class Livro {
        private String titulo;
        private String autor;
        private short ano;
        private String codigo;
        private boolean disponibilidade;
        ArrayList<Livro> livros;

        public Livro(String novoTitulo, String novoAutor, short novoAno, String novoCodigo, boolean novaDisponibilidade){
            this.titulo = novoTitulo;
            this.autor = novoAutor;
            this.ano = novoAno;
            this.codigo = novoCodigo;
            this.disponibilidade = novaDisponibilidade;
        }

        }

Comment: é estranho por que tem uma lista de livros dentro de sua classe de Livro, provavelmente esse não compila pois não está sendo instanciado também essa lista.
Answer: Primeiro separe as duas classes. Uma classe para Livro contendo todos os atributos de um livro e uma classe para Biblioteca com o atributo
ArrayList<Livro> livros = new ArrayList<>();

A partir daí basta fazer um livros.add e adicionar um livro novo.
    public class Biblioteca {
        private ArrayList<Livro> livros = New ArrayList<>();

    //Getter e setters...

        public void addLivro(String novoTitulo, String novoAutor, short novoAno, String novoCodigo, boolean novaDisponibilidade){
            livros.add(new Livro( novoTitulo,  novoAutor,  novoAno,  novoCodigo,  novaDisponibilidade));
       }
     }

Livro.java

    public class Livro {
        private String titulo;
        private String autor;
        private short ano;
        private String codigo;
        private boolean disponibilidade;

    //Getter e setters

        public Livro(String novoTitulo, String novoAutor, short novoAno, String novoCodigo, boolean novaDisponibilidade){
            this.titulo = novoTitulo;
            this.autor = novoAutor;
            this.ano = novoAno;
            this.codigo = novoCodigo;
            this.disponibilidade = novaDisponibilidade;
        }
    }

Preciso criar um Arraylist em Java


Angular switched buttons logic

Question: I have a simple problem, but I'm a beginner so I can't understand the logic,
I have 2 buttons one and two, when I click on one I would like to display instead of one and two the other buttons so three and four? made a switch.
What is the best way to do this? Is using if else in the HTML correct or should we move this logic to the ts file?
Thanks in advance.
html

  <button> one</button>
  <button> two</button>

  <button> three</button>
  <button> four</button>

ts.file
isButtons:boolean = false;

Answer: The logic is simple enough to remain in the template, you don't need any more code in your component. A simple (click) and a <ng-template> will do the trick:

  <button (click)="isButtons=true"> one</button>
  <button> two</button>

<ng-template #threeAndFour>

        <button> three</button>
        <button> four</button>

</ng-template>

Answer: Given your code example, you can just

add *ngIf="isButtons" to the second div so you'll handle the final state
add the click handler on the button you want to trigger the change: (click)="isButtons = true"

Final snippet:

  <button (click)="isButtons = true"> one</button>
  <button> two</button>

  <button> three</button>
  <button> four</button>

Jeremy Thille's answer is just as good, but most likely not something a beginner can handle (ng-template and more complex *ngIf usage).

Angular switched buttons logic


How to preform insert into BigQuery table of list of values using dbapi

Question: I have a question regarding performing insert into a table in BigQuery using the DBAPI .
The simple insert of 1 value I was able to preform , my question is how to preform insert of list of values.
I couldn't find an example on how to do it, I want to preform something like :
query ="insert into test.test values (%s)"
self._cursor.execute(query,(('4'),('3')))

But I am getting an error
Thanks,
Nir
Answer: You can try the command executemany. This method is used to insert multiple rows in a single operation.
Your code should look something like:
query ="insert into test.test values (%s)"
self._cursor.executemany(query,[('4'),('3')])

Also what is the error that you are getting?


Want to group keys in a dictionary and then average each group

Question: I want to average the sentiment scores for some video game reviews in a csv file. I've created a dictionary for these, but want to group each result for each row in the csv together.
  blob = TextBlob(review_text)
  for sentence in blob.sentences:
   ssp = {"Game": index, "Polarity":sentence.sentiment.polarity}
   print(ssp)

This gives an output like so:
{'Game': 1, 'Polarity': -0.49687499999999996}
{'Game': 2, 'Polarity': 0.3865909090909091}
{'Game': 2, 'Polarity': 0.0}
{'Game': 2, 'Polarity': 0.2142857142857143}
{'Game': 2, 'Polarity': 0.2142857142857143}
{'Game': 2, 'Polarity': 0.04999999999999999}
{'Game': 2, 'Polarity': 0.0}
{'Game': 2, 'Polarity': -0.02500000000000005}
{'Game': 2, 'Polarity': 0.4715909090909091}
{'Game': 2, 'Polarity': 0.26666666666666666}

So how do I group by Game 1, Game 2, Game 3? I then want to average the scores for each.
Thanks
Answer: You can put the dictionary into a list and then group it/compute average afterwards:
from statistics import mean

# your code:
blob = TextBlob(review_text)
lst = []
for sentence in blob.sentences:
    ssp = {"Game": index, "Polarity": sentence.sentiment.polarity}
    lst.append(ssp)

# group it:
out = {}
for dct in lst:
    out.setdefault(dct["Game"], []).append(dct["Polarity"])

# compute average:
for k, v in out.items():
    print("Game:", k, "Average:", mean(v))

Prints:
Game: 1 Average: -0.49687499999999996
Game: 2 Average: 0.17537999037999039

Answer: Another possible solution, based on the previous conversion from dictionary to pandas.DataFrame (concatenating, successively, the several dictionaries into the dataframe):
import pandas as pd

x = [{'Game': 1, 'Polarity': -0.49687499999999996},
{'Game': 2, 'Polarity': 0.3865909090909091},
{'Game': 2, 'Polarity': 0.0},
{'Game': 2, 'Polarity': 0.2142857142857143},
{'Game': 2, 'Polarity': 0.2142857142857143},
{'Game': 2, 'Polarity': 0.04999999999999999},
{'Game': 2, 'Polarity': 0.0},
{'Game': 2, 'Polarity': -0.02500000000000005},
{'Game': 2, 'Polarity': 0.4715909090909091},
{'Game': 2, 'Polarity': 0.26666666666666666}]

df = pd.DataFrame(dtype = 'object')

for y in x:
  df = pd.concat([df, pd.DataFrame([y])], ignore_index = True)

df.groupby(['Game']).mean()

Output:
      Polarity
Game
1    -0.496875
2     0.175380


Ordering TableViews by latest time

Question: Currently I am having trouble ordering my table views in the right order. As of right now, they don't change order no matter what. I'm not sure what to add to fix this.
import UIKit

class ListNotesTableViewController: UITableViewController {
    var notes = [Note](){
        didSet{
            tableView.reloadData();
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        notes = CoreDataHelper.retrieveNotes()
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return notes.count;
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath : IndexPath) ->ListNotesTableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "listNotesTableViewCell", for: indexPath) as! ListNotesTableViewCell

        let row = indexPath.row
        let note = notes[row]
        cell.noteTitleLabel.text = note.title
        cell.notePreview.text = note.content;
        cell.noteModificationTimeLabel.text = note.modificationTime?.convertToString()
        return cell
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let identifier = segue.identifier {
            if identifier == "displayNote" {
                print("Table view cell tapped")

                let indexPath =  tableView.indexPathForSelectedRow!
                let note = notes[indexPath.row]
                let displayNoteViewController = segue.destination as! DisplayNoteViewController
                displayNoteViewController.note = note

            } else if identifier == "addNote" {
                print("+ button tapped")
            }
        }
    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {

            CoreDataHelper.delete(note: notes[indexPath.row])

            notes = CoreDataHelper.retrieveNotes()
        }
    }

    @IBAction func unwindToListNotesViewController(_ segue: UIStoryboardSegue){
        self.notes = CoreDataHelper.retrieveNotes()
    }
}

Comment: Why not sorting during the CoreData fetch?
Answer: It seems like your notes is not sorted by time. Whenever you get  self.notes = CoreDataHelper.retrieveNotes() you need to sort your array. You can do it like this:
self.notes.sorted(by: { $0.date < $1.date })

Note that the date variable can differ depending on what variable name you have for your time and structure on your Note class.

Ordering TableViews by latest time


Coloring the vertices of $K_n$ and showing existence of a monochromatic triangle

Question: Looking for some hints on a homework problem. As far as I know, it's not from any textbook.
Color the vertices of $K_n$, the complete graph on $n$ vertices, red or blue. For how many $n$ will there be no monochromatic triangles (vertices all the same color). Note this question is not the one about coloring the edges.
My conjecture: for $n\ge 5$, there will always be a red or blue triangle.
I'm hoping the "pigeonhole principle" will apply somewhere. I don't think the instructor is asking us to delve into Ramsey theory.
Thanks in advance.
Answer: Since all vertices are connected, it's sufficient to show that there are 3 vertices with the same color. Since you are coloring with two colors, for all $n > 4$ there will be three vertices with the same color.
Comment: You should use the pigeonhole principle here.
Comment: you should work on edges not vertices.
Comment: for n=5 i.e. pentagon you can draw edges without a triangle of same color
Answer: In the case that edges are irrelevant:
Your conjecture is completely correct. Here's how to apply the pigeonhole principle: with four vertices, there may be two of both colors. However, when you add a fifth vertex, it must be either red or blue, which forms a triangle with the other two of the same color. Another way to ask the same kind of question is how many integers does one need to have in order to have three even numbers or three odd numbers?
In the case that edges are relevant:
Your conjecture is almost correct. You can color the outside 5 lines forming a regular pentagon blue and the inner 5 lines (a star) red and yet not have a monochromatic triangle. However, it is true that for $K_n$ with $n \geq 6$ a monochromatic triangle WILL be forced.
Step 1: Take a vertex on $K_6$ and note that at least half of the lines from it must be one color or another. Now color three lines from it either color (say, blue).
Step 2: Apply pigeonhole principle; between the other vertices connected by a blue line to the first one, can the lines be blue or red?
Does that suffice?
Comment: I'm coloring vertices and not edges. Or am I missing something?
Comment: @userJD-512: Well, in order to have a monochromatic triangle, one must have 3 edges of the same color, yes? It's possible that your instructor may be considering edges to be irrelevant, in which case your conjecture is correct is as stated. I'll edit my answer to reflect both cases.


Uniform convergence of $\prod\limits_{n=1}^{\infty} \left (1 - \frac {z} {n} \right )$ on compact sets.

Question:
Does the infinite product $\prod\limits_{n=1}^{\infty} \left (1 - \frac {z} {n} \right )$ converge uniformly on compact sets?

I know that a necessary and sufficient condition for the convergence of an infinite product which is that the required product converges if and only if $\sum\limits_{n=1}^{\infty} \log \left (1 - \frac {z} {n} \right )$ converges. But I don't have any idea about the sum of the logarithm. Another simple sufficient condition is that $\sum\limits_{n=1}^{\infty} \frac {|z|} {n}$ converges uniformly on compact sets which doesn't hold in this case since the harmonic series $\sum\limits_{n=1}^{\infty} \frac {1} {n}$ diverges. So how to deal with this problem? Any cooperation would be highly solicited.
Thanks in advance.
Rabin.
Comment: Note that, if $n>|z|$, then $$\log\left(1-\frac{z}{n}\right) = -\frac{z}{n} + \mathcal{O}\left(\frac{1}{n^2}\right). $$ So, if $z \notin \{1,2,3,\ldots\}$, then as $N\to\infty$ we have $$\prod_{n=1}^{N}\left(1-\frac{z}{n}\right)=\exp\{-z \log N + \mathcal{O}(1)\}. $$ If in addition $z \neq 0$, then this diverges as $N\to\infty$.
Comment: Putting this in another way, you can show that $$ \prod_{n=1}^{N} \left(1-\frac{z}{n}\right)e^{z/n} $$ converges as $N\to\infty$ for any $z$, and the limit is non-zero precisely when $z\neq1,2,3,\ldots$. (This is an example of Weierstrass product, and it is also closely related to the Gamma function.) Then the original product is $$ \prod_{n=1}^{N} \left(1-\frac{z}{n}\right) = e^{-z H_N} \prod_{n=1}^{N} \left(1-\frac{z}{n}\right)e^{z/n}, $$ where $H_n=1+\frac{1}{2}+\cdots+\frac{1}{n}$ is the harmonic number, which is asymptotically $\log n + \mathcal{O}(1)$ as $n\to\infty$.
Comment: What you said is absolutely correct. My apology for being less clear, but in my comment I was talking about the particular choice $a_n=\left(1-\frac{z}{n}\right)e^{z/n}$, rather than about general sequences. If all the terms of this sequence are non-zero, then by noting $\log a_n=\mathcal{O}(n^{-2})$, we can prove that $\sum_{n=1}^{\infty}\log a_n$ converges (even absolutely!).
Comment: I believe you can get your answer from Ramanujan's lost note_part-II
Comment: @Polymath oh God! Could you please share some link where I can find it? Not sure whether I can able to understand it properly though.
Comment: @Sangchul Lee$:$ How to show that?
Comment: @Rabin Kumar Chakraborty chapter: Sums of Powers, Bernoulli Numbers, and the Gamma Function also you can he has mentioned this above problem too!

$$\prod(1-\frac z{n})$$ is available for sure!
Comment: @Polymath$:$ It will be more than helpful for me if you share some screenshot of the book.
Comment: @RabinKumarChakraborty sure! I'll try to add books link....(It's available online: *Springer*)
Comment: @Sangchul Lee$:$ I am not convinced to how do you get the sequence of partial product to be $\exp \left \{-z \log N + \mathcal {O} (1) \right \}.$ Could you please elaborate a little bit? Thanks in advance.
Comment: @Sangchul Lee$:$ Very nice argument. One another question I have in mind. How do I show that the product $\prod\limits_{n=1}^{\infty} \left (1 - \frac {z} {n} \right )$ or the product $\prod\limits_{n=1}^{\infty} \left (1 - \frac {z} {n} \right ) e^{\frac {z} {n}}$ converges to some **non-zero** complex number if $z \notin \mathbb N\ $? For $z \notin \mathbb N$ why doesn't the product approach $0\ $? Infinite product of non-zero numbers may be $0.$ Isn't it so?
Comment: You already know one sufficient condition for that, as you mentioned in your OP. :)
Comment: @Sangchul Lee$:$ Sorry, I don't get your point. My concern is not the convergence of the infinite product. What confuses me is that why can't the product you mentioned (in your penultimate comment) have a zero at non-integer points?
Comment: I am referring to the following [convergence criterion](https://en.wikipedia.org/wiki/Infinite_product#Convergence_criteria): $\prod_{n=1}^{\infty}a_n$ converges to a non-zero number if and only if $\sum_{n=1}^{\infty}\log a_n$ converges. Applying this to $a_n=(1-\frac{z}{n})e^{z/n}$, the only obstruction for $\sum_n \log a_n$ to converge is that some $a_n$ becomes zero (hence $\log a_n$ becomes undefined). And you know exactly when this obstruction happens.
Comment: @Sangchul Lee$:$ I don't think that the only obstruction that $\sum\limits_{n=1}^{\infty} \log a_n$ converges is that $a_n = 0$ for some $n.$ There could be many other reasons for an infinite series to diverge. For instance if $a_n = \frac {1} {n}$ then neither of the $a_n$'s would actually be $0$ but $\sum\limits_{n=1}^{\infty} \log a_n$ is divergent.
Comment: What I think since the product you mentioned converges uniformly on compact sets the limit function would be entire and hence any zero of it will have finite multiplicity. So in the factorization only finitely many factors will appear corresponding to the zero. Now apart from the non-vanishing exponential factor each term in the product is linear. Since these two factorizations match it should be the case that the factors which appear in the factorization of the entire function should also appear in the product in some order. But any such linear factor would correspond to a integer root.
Comment: @Sangchul Lee$:$ By showing that $\sum\limits_{n=1}^{\infty} \log a_n(z)$ converges uniformly on compact sets for $z \notin \mathbb N$ we can conclude that the product converges to a holomorphic function on $\mathbb C \setminus \mathbb N.$  Also at every natural number the product vanishes. So if we denote the product by $f(z)$ then there exists a holomorphic function $g$ on $\mathbb C \setminus \mathbb N$ such that $$f(z)= \begin{cases} g(z)& z \in \mathbb C \setminus \mathbb N\\ 0& z \in \mathbb N \end{cases}$$
Comment: @Sangchul Lee$:$ From here how do I conclude that $f$ is entire i.e. $f$ is also holomorphic at each natural number?
Answer:
This may answer you with proper substitution
Comment: This is neither my answer nor I'm trying to answer it's in the request of OP's comment.


Javascript set cookie max size is exceeded due to a large JWT token

Question: I am using JWT token for the authentication and since the server is stateless, the client (Javascript app) uses cookies to store the JWT token, read the token every time from cookies and set the authorization header accordingly on any call to the server. The issue I am facing is the token can become larger than 4KB and this is causing a failure on the javascript part. Apparently, Javascript has a limitation of 4KB for the cookie size. Therefore, this is causing an issue.
Set-Cookie header is ignored in response from url: xxxxx. Cookie length should be less than or equal to 4096 characters

My question is what can I do to address the cookie limitation from the javascript point of view? Is that even a right thing to set the JWT token in the cookie? I would imaging having a JWT token larger than 4KB can happen with some applications. What would be the alternative (and yet secure) approach to handle it in a stateless way and manage the javascript limitation?
Answer:
Is that even a right thing to set the JWT token in the cookie?

If you are using an httponly cookie then yes. It is safe, a lot safer than using Web Storage(localStorage or sessionStorage). Actually storing your JWT token in localStorage or sessionStorage allows an XSS attacker to steal users token and send them to his/her own server, On the other hand since httponly cookie cannot be accessed from javascript running on browsers, then in case of an XSS attack, the attacker won't have access to the user's JWT.
If you set JWT in cookie you don't have to set the token in Authorization header on every request since the browser will automatically send it for you to the server which has set the cookie for you.
Keep in mind that as I mentioned, saving JWT in cookie means that server automatically will send the JWT for you to the server, which means it makes you vulnerable against CSRF attacks(if you put the JWT in localStorage or sessionStorage you won't be vulnerable to CSRF attack but as I said you would be vulnerable against XSS attacks). So you should prevent CSRF attacks by using CSRF tokens in your application.

What would be the alternative (and yet secure) approach to handle it in a stateless way and manage the javascript limitation?

As I said, put your JWT in an httponly cookie and in order to bypass the cookie max size limitation enforced by browsers, You can chunk your cookies once they reach the 4kb limit in size. This is what some popular libraries do e.g. next-auth and dotnet
it works like this:
Once your cookies exceeds the 4kb size. You will chunk them and prefix or postfix them with numbers so you know the order in which they should be merged later. For instance if you are trying to set a JWT whose size is 130kb in a cookie named accessToken then since 130/40 = 3.25 you at least need 4 cookies named accessToken_1 and accessToken_2 and accessToken_3 and accessToken_4
Note that you should try to avoid large cookies since larger cookie means, more data being sent over the internet which means slower request/response.
Answer: You could store the token in the sessionStorage or localStorage  and append the token in all requests in the Authentication header. You could implement Bearer Authentication in your application.
You could save data in the sessionStorage or localStorage upto 5 MB And these methods are more secure than cookie.
Session Storage:

The sessionStorage property accesses a session Storage object for the current origin. sessionStorage is similar to localStorage; the difference is that while data in localStorage doesn't expire, data in sessionStorage is cleared when the page session ends.

A page session lasts as long as the browser is open, and survives
  over page reloads and restores.
Opening a page in a new tab or window creates a new session with
  the value of the top-level browsing context, which differs from how
  session cookies work.
Opening multiple tabs/windows with the same
  URL creates sessionStorage for each tab/window. Closing a tab/window
  ends the session and clears objects in sessionStorage

Local Storage:

The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions. localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends — that is, when the page is closed.
Comment: Thanks for the reply. I can see using local storage is possible in my case. However, I am worried about the security vulnerabilities I may run into. I can find lots of articles about this. Some say cookies are more secure some say local storage is a better option. I will keep investigating, though.
Answer: You can use both localStorage and sessionStorage, for clear understanding of both kindly see the here! answer.


What's the difference between these two transformations of functions?

Question: I'm about to graph the transformation of a function, but in this problem I encountered something new. The function transformation looks like this:
y=12(f(x)+2)
Thing is, I've never seen the f encapsulated in parentheses, so I'm unsure what effect it has. Essentially, I'm wondering what the difference between the above transformation and this one is:
y=12f(x)+2
What do I do differently on the top one when compared to what is done to the bottom one? Is there even any difference?
Comment: Af(x)+B is f(x) vertically stretched by a factor of A and vertically shifted by a factor of b. Expand y=12(f(x)+2), and see what happens.
Comment: I'm still lost.. What do you mean by expand? English isn't my native language, so I'm not too familiar with its math terminology.
Comment: To expand is to remove parentheses. Here this is done by multiplication. For example, 2(a+b)--expand-->2a+2b
Answer: It has to do with order of operations. Recall that when doing arithmetic, we do multiplication before addition. If we want to do addition before multiplication, we must use brackets. For example:
$$
1 + 2 \times 3 = 1 + 6 = 7
$$
while on the other hand:
$$
(1 + 2) \times 3 = 3 \times 3 = 9
$$

Likewise, the transformation $y=af(x) + b$ can be interpreted to mean: "Vertically expand $f(x)$ by a factor of $a$, then vertically translate the result up by $b$ units."
On the other hand, the transformation $y = a(f(x) + b)$ can be interpreted to mean: "Vertically translate $f(x)$ up by $b$ units, then vertically expand the result by a factor of $a$."
Comment: Ah, that makes sense. Resolve what's within parentheses first.. In other words for example y=2(f(x)+1) on the point (2, 2) would make it (2, 6), whereas y=2f(x)+1 would make it (2, 5). Am I understand it correctly?
Comment: Yes, that's correct.


PIG UDF: How could I change the .jar package which has been registered?

Question: I have got the .jar package registered before and the functions could be run well. But when I want to debug the PIG UDF functions, I need to change the functions, and after that I will re-generated the jar package.
But the situation is when I regenerate the jar package with updated functions and register it again, the PIG still run the original functions which is in the original jar package registered before. Even I package the jar with a new name and register again, PIG still use the original one.
So did anyone encounter with this problem? and how to solve it? Thanks a lot. I have been stuck by this problem for two days. T_T
Comment: Check the location of where you are saving the .jar file and the location from where you are registering the .jar.If these two paths are different then that is reason it is failing.
Comment: Yes. I have checked it for many times. The path is right. I  think it may because the register command cached some jar packages registered before. So no one encountered the same situation?
Answer: I finally get this issue resolved by restart the pig -x local and then it works.


Proving that every torsion-free Abelian group $(A, +)$ can be linearly ordered

Question: Show that every torsion-free Abelian group (A, +) can be linearly ordered so
that
$$(a < b) ∧ (c \le d) → (a+c < b+d).$$
(Hint: First show this for finitely generated groups. Then use compactness.)
I got this question in logic class and I have yet to partake in a group course, my proffesor gave me this hint:
Any finitely generated torsion-free Abelian group is a direct sum of a finite number of groups of integers ($Z$,+) (which I don't understand how can it help me here..).
I am just wondering if my attempt makes sense:
given $A$ which is a finite generated torsion-free Abelian group let $$(g_1,g_2,....,g_n)$$
be $A$'s basis, let $v$ belong to $A$ then exist
$$\beta_1,\beta_2,\ldots,\beta_n \in F$$
such that
$$v = \sum_{i=1}^n g_i*\beta_i$$
lets create a function from $A$ to $R^n$ lets call her $f$ such that for any $v$ in $A$
$$f(v) = (b_1,b_2,\ldots,b_n),$$
I am sending v to its coordinate vector.
Then I will create a linear order $R$ as follows:
$$aRb = f(a) \le f(b).$$
I have two probeloms: first lets say I define $\le$ as Product order relation, then does it work for a vector with n coordinates? and if it does and I managed to find a relation that linearly orders a finite generated group $A$ then how does compactness theorm help me? Can I claim that given B which is torsion-free Abelian group such that
$A \subseteq B$, since $A$ is general finite generated group who has a model for that linear order then by compactness therom $B$ also has a model?
Thx in advance any help would be appreciated!
Comment: Please try to use MathJax for writing equations.
Comment: [Here's a MathJax tutorial](https://math.meta.stackexchange.com/q/5020/104041) :)
Comment: Without [mathjax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference), your math formulas are just a jumble of unreadable symbols :-<
Comment: I have edited it thank you very much! I have always wondered how to write like that, I hope its more clear its kinda hard for me to write in English so I hope its not too messy.
Comment: Your subject line and first paragraph do not mention finite generation, but your attempt begins with the assumption of finite generation. For a f.g. torsion free abelian group, you have $A\cong \mathbb{Z}^n$, and then the lexicographic order solves the problem. Are you assuming f.g. or not?
Comment: I see ima try using that, but what can I do now? How can I prove using compactness theorm that any A has a model that proves that ? If I assume that by given A that is a torsion free abeliian group , let B be a sub group of A, if I prove that on B can I use compactness and say that A also has a model?
Answer: To show that it is possible to choose basis (so that your $f$ is well-defined and coefficients can be added as integers) is equivalent to showing that group is isomorphic to $\mathbb Z_+^n$.
Product order relation isn't linear, it's only partial. However, if you multiple linearly ordered sets (for example, multiple copies of $\mathbb Z$ as in your case) it's easy to define linear order on them: we say that $(a_1, \ldots, a_n) < (b_1, \ldots, b_n)$ if either for some $j$ we have $a_i = b_i$ for $i < j$ and $a_j < b_j$ - in other words, on the first position where $a$ and $b$ differ, $a$ is less then $b$, for example $(0, 1) < (1, 0)$. This is called lexicographic order.
Using compactness, we can prove that for group $G$, if all finitely generated subgroups of $G$ can be linearly ordered, so can be $G$. Given that finitely generated subgroups of torsion-free abelian group are, of course, torsion-free finitely generated abelian groups, this shows necessary result.
Assume all finitely generated subgroups of $G$ can be linearly ordered. Consider some theory strong enough to speak about groups and their ordering (for example, ZF), add to it as a constant $G'$ and for every element $g \in G$ add constant $g'$.

$G'$ is a group that can be linearly ordered.
For every element $g \in G$, add axiom $g' \in G$.
For every elements $x, y \in G$, add axiom $x'y' = (xy)'$.
For every different elements $x, y \in G$, add axiom $x' \neq y'$.

By compactness, this new theory has a model if when we add any finite number of this axioms the result theory will have a model. However, if we add only finite number of our axioms, they use only finite number of elements, and this theory will have a model - just use subgroup of $G$ generated by these elements for $G'$.
So, our theory has a model. Take such model, and notice that subset of $G'$ consisting of all $g'$ is a group isomorphic to $G$, and it can be linearly ordered by order induced from $G'$.


Erro ao introduzir dados na BD usando mysqli

Question: Estou a tentar inserir em 2 tabelas dados, mas tenho sempre o erro de
Cannot add or update a child row: a foreign key constraint fails ou seja isto quer dizer que não consegue inserir na segunda tabela, porque na primeira a PK ainda não existe.
Eu fiz assim:
 $insere_um = "INSERT INTO utilizadores(n_processo,nome,password,id,cod_grupo)
  VALUES('".$n_processo."','".$nome."','".$pass."', '".$tipo['id']."', '".$grupo['cod_grupo']."')";

  if(!mysqli_query($conexao,$insere_um))
  {
    echo mysqli_error($conexao);
  }
  else
  {

    $insere_dois = mysqli_query($conexao,"INSERT INTO utilizador_modulos(codigo_ut_mod,n_processo,cod_modulo)
    VALUES
    ('".$n_processo."1',LAST_INSERT_ID(),'".$sql_mod1_001['cod_modulo']."'),
    ('".$n_processo."2',LAST_INSERT_ID(),'".$sql_mod1_002['cod_modulo']."'),
    ('".$n_processo."3',LAST_INSERT_ID(),'".$sql_mod1_003['cod_modulo']."'),
    ('".$n_processo."4',LAST_INSERT_ID(),'".$sql_mod1_004['cod_modulo']."'),
    ('".$n_processo."5',LAST_INSERT_ID(),'".$sql_mod1_005['cod_modulo']."'),
    ('".$n_processo."6',LAST_INSERT_ID(),'".$sql_mod2_001['cod_modulo']."'),
    ('".$n_processo."7',LAST_INSERT_ID(),'".$sql_mod2_002['cod_modulo']."'),
    ('".$n_processo."8',LAST_INSERT_ID(),'".$sql_mod2_003['cod_modulo']."'),
    ('".$n_processo."9',LAST_INSERT_ID(),'".$sql_mod2_004['cod_modulo']."'),
    ('".$n_processo."10',LAST_INSERT_ID(),'".$sql_mod2_005['cod_modulo']."'),
    ('".$n_processo."11',LAST_INSERT_ID(),'".$sql_mod3_001['cod_modulo']."'),
    ('".$n_processo."12',LAST_INSERT_ID(),'".$sql_mod3_002['cod_modulo']."'),
    ('".$n_processo."13',LAST_INSERT_ID(),'".$sql_mod3_003['cod_modulo']."'),
    ('".$n_processo."14',LAST_INSERT_ID(),'".$sql_mod3_004['cod_modulo']."'),
    ('".$n_processo."15',LAST_INSERT_ID(),'".$sql_mod3_005['cod_modulo']."'),
    ('".$n_processo."16',LAST_INSERT_ID(),'".$sql_mod4_001['cod_modulo']."'),
    ('".$n_processo."17',LAST_INSERT_ID(),'".$sql_mod4_002['cod_modulo']."'),
    ('".$n_processo."18',LAST_INSERT_ID(),'".$sql_mod4_003['cod_modulo']."'),
    ('".$n_processo."19',LAST_INSERT_ID(),'".$sql_mod4_004['cod_modulo']."'),
    ('".$n_processo."20',LAST_INSERT_ID(),'".$sql_mod4_005['cod_modulo']."')"
    );
  }

Comment: Interpretação estranha essa que vc fez da mensagem de erro: _"Cannot add or update a child row: a foreign key constraint fails ou seja isto quer dizer que não consegue inserir na segunda tabela, porque na primeira a PK ainda não existe."_ - poderia dizer como chegou nessa conclusão para entendermos melhor a dúvida?
Comment: De curiosidade, pq vc ta fazendo a `insere_um` 2 vezes, uma vez no if e outra no else? Acho que assim vai ficar dificil funcionar. Seria legal você aprender a fazer as coisas mais básicas antes, esse código seu tá muito complicado pro tipo de erro que está comentendo. Vá aos poucos, degrau por degrau, que ajuda a dominar as etapas, senão acumula muito lugar pra depois achar o problema.
Comment: Eu costumo complicar aonde não existe @Bacco :) Mas essa conclusão surgiu porque tive já me tinha acontecido antes este erro porem funcionou desse jeito mas com o mysql normal em vez de mysqli. Também encontrei várias pessoas com o mesmo erro, e disseram que se tratava disso. Isto é uma parte do código inteiro, basicamente o que preciso é de saber o que se costuma fazer quando é preciso inserir dados em 2 tabelas ligadas
Comment: Quanto ao _"Eu costumo complicar aonde não existe @Bacco"_ fique sossegado, que praticamente todo ser humano domina essa arte de complicar :)  - Só mencionei, pq de repente o problema é bem mais simples, e é importante você não confiar em analisar uma possibilidade só e esquecer de outras. Provavelmente a inserção dupla já está atrapalhando você. Experimente tirar a segunda ocorrência, no else. e veja se muda o problema/erro.
Comment: Verdade @Bacco :p. Mas eu ja tinha experimentado isso, daí pus assim para tentar, mas não deu. So insere os dados na primeira tabela :\
Answer: Eu só achei estranho uma coisa, você usa no primeiro INSERT a variável $n_processo, entretanto, no segundo INSERT você concatena $n_processo com mais um carácter, será que não é isso que esteja fazendo o script dar o erro para realizar a inserção?
Comment: Da maneira que você usou não iria dar certo, ele precisa saber de qual tabela ele vai solicitar a chave primária.
Comment: Isso foi uma forma que eu arranjei para ser a chave primária da segunda tabela. usando a primária da tabela anterior com um "incremento". :) Mas esse não é o problema.
Comment: Mas esse deve ser o problema, se na tabela 1 o registro tem a chave primária com o valor 10, ele tem que se relacionar na tabela 2 com o valor 2, do contrário, eu creio que não vai existir um vínculo entre os registros.
Comment: Já consegui meter a funcionar, apenas troquei o `LAST_INSERT_ID()` para `$n_processo` que é a chave primária da primeira tabela e FK da segunda. Mas o `LAST_INSERT_ID()` supostamente não fazia o mesmo?


What is the best workflow to migrate a site using domain access?

Question: i have a site with 20 subdomains using the domain access module on a dev server and i want to migrate them to a production server.
There is only a change from

subdomain.maindomain.eu

to

subdomain.maindomain.de

What is the best to do it ?
Answer: Can you be a little more specific, are you just wanting to migrate the whole database to a new installation or are you migrating content into an existing installation
In the first case it should be fairly simple,

Put your site in maintenance mode and then flush all the caches.
Take a backup of your sites directory.
Copy the database to the new server.
Upload the drupal installation and then the sites directory to your new server
Modify the settings.php to connect to the database on the new server.
Using a DB admin tool such as phpmyadmin modify the "domain" table in the database on the new server, there is a field in this table called "subdomain" this relates to the url of your domains so just modify this to suit your needs.
Comment: yes i want to move to whole installation to a new server with .de domain. i was unsure about how to change the domain settings on the new server. i will take a look modifieng the database directly. thx!


Exclude specific domains from Apache2 serverAlias while using a catch all *(wildcard) alias

Question: I have a web application that needs to support custom domains, in that regard I have set-up the following name based virtual server:
<VirtualHost *:80>
    ServerName example.com
    ServerAlias * *.example.com www.example.com example.com
    RailsEnv production
    RackEnv production
    DocumentRoot /srv/www/example/current/public
    <Directory /srv/www/example/current/public>
             AllowOverride all
             Options -MultiViews FollowSymLinks
    </Directory>
    ErrorLog /srv/www/example/log/error.log
    TransferLog /srv/www/example/log/access.log
</VirtualHost>

Notice the * as the server alias? that catches all the domains on that server. However, I have other sites on this server which I want to be excluded from this list. It is more economical for me to have a list of excluded domains than manually set every domain a user may register with at this service as a serverAlias...
Perhaps this is not the best way to go, but I'm looking for help, in the best (relatively simple) way to set up a web-app that may catch any domains, while allowing other specific domains to be routed to different apps.
Answer: Apache searches for a match in the order that the domains are defined.
If I understand your problem correctly then it can be solved by defining your hosts to be excluded before the catch all host.
Example:
<VirtualHost *:80>
    ServerName excluded.example.com
    ServerAlias  something.example.com ...
    ...
</VirtualHost>
<VirtualHost *:80>
    ServerName example.com
    ServerAlias * *.example.com www.example.com example.com
    RailsEnv production
    ...
</VirtualHost>

Comment: Yes, you are right, but I am puzzled about how to do this on a default Ubuntu 10.4 stack, where the whole shenanigans is managed by having a sites-available and sites-enabled directories, and each virtual host definition exists in its own exclusive file... how do I control the order in that case?
Comment: for a site definition that needs to come first, name it something like `000-excluded.example.com.conf` in the sites-available dir.
Comment: The files are loaded in alphabetic order (the default sort order for ls).
Comment: I was looking to do exactly the same thing, and this does not work for me. The excluded.example.com VirtualHost which had "ServerName excluded.example.com\n Redirect / https://example.com/excluded" caused all requests to the more general VirtualHost to get redirected (which definitely followed the specific VirtualHost in the config).


Setting Ansible vars with set_fact results

Question: Im running ansible 2.9.18 on RHEL7.
I am using hvac to retrieve usernames and passwords from a Hashicorp vault.
  vars:
    - creds: "{{ lookup('hashi_vault', 'secret=tst2/data/cisco token= url=http://10.80.23.81:8200') }}"

  tasks:
    - name: set Cisco creds
      set_fact:
        cisco: "{{ creds['data'] }}"

    - name: Get nxos facts
      nxos_command:
        username: "{{ cisco['username'] }}"
        password: "{{ cisco['password'] }}"
        commands: show ver
        timeout: 30
      register: ver_out
    - debug: msg="{{ ver_out.stdout }}"

But username and password are deprecated and I am trying to figure out how to pass the username, password as a "provider" variable. And this code doesn't work:
vars:
    asa_api:
      - creds: "{{ lookup('hashi_vault', 'secret=tst2/data/cisco token= url=http://10.80.23.81:8200') }}"
        set_fact:
          cisco: "{{ creds['data'] }}"
        username: "{{ cisco['username'] }}"
        password: "{{ cisco['password'] }}"

  tasks:
      - name: show run
        asa_command:
          commands: show run
          provider: "{{ asa_api }}"
        register: run
        become: yes
        tags:
          - show_run

I cannot figure how syntax for making this work. I would greatly appreciate any help.
Thanks,
Steve
Comment: Just as an add-on to my below answer: What you have tried "doens't work" `set_fact` is a module which must be used in a task. Here you are basically creatin a list containing a key called `set_fact` and a subkey `cisco` declaring a value from a variable `creds` that does not exist (i.e. your are creating `asa_api[0].creds` and you cannot self reference an element on declaration in yaml).
Answer: Disclaimer: This is a generic answer. I do not have any network device to test this fully so you might have to adapt a bit after reading the documentation

Your are taking this the wrong way. You don't need set_fact at all and both method you are trying to use (user/pass or provider dict) are actually deprecated. Ansible treats you network device as any host and will use the available user and password you have configured if they exist.
In the following example, I'm assuming your playbook only targets network devices and that the login/pass stored in your vault is the same on all devices.
- name: Untested network device connection configuration demo
  hosts: my_network_device_group

  vars:
    # This indicates which connection plugin to use. Default is ssh
    # An other possible value is httpapi. See above documentation link
    ansible_connection: network_cli

    vault_secret: tst2/data/cisco
    vault_token: verysecret
    vault_url: http://10.80.23.81:8200
    vault_options: "secret={{ vault_secret }} token={{ vault_token }} url={{ vault_url }}"

    creds: "{{ lookup('hashi_vault', vault_options).data }}"

    # These are the user and pass used for connection.
    ansible_user: "{{ creds.username }}"
    ansible_password: "{{ creds.password }}"

  tasks:
    - name: Get nxos version
      nxos_command:
        commands: show ver
        timeout: 30
      register: ver_cmd

    - name: show version
      debug:
        msg: "NXOS version on {{ inventory_hostname }} is {{ ver_cmd.stdout }}"

    - name: An other task to play on targets
      debug:
        msg: "Task played on {{ inventory_hostname }}"

Rather than vars at play level, you can store this information in your inventory for all hosts or for a specific group, even for each host. See how to organise your group and host variables if you want to use that feature.
Comment: Very helpful. Thanks so much for your input. I am still trying to figure out "connection: local" versus "ansible_connection: network_cli". When I used "network_cli" I got a message that ansible could not "automatically determine the os". I reverted to "local" and the playbook works.
Comment: `(ansible_)connection: local` basically connects to your localhost => https://docs.ansible.com/ansible/latest/user_guide/connection_details.html#running-against-localhost. The ansible prefix depends on wether it is a play level option or a variable.
Comment: Right, that both makes sense and is confusing. I have "connection: local" and ansible successfully SSH's to my cisco boxes and does what I ask. "connection: network_cli" fails.


Unwanted sanitizing (escaping) in knitr due to update

Question: Last Spring, I used code similar to my minimum working example (MWE) below to make this: https://cdn.advocacy.sba.gov/wp-content/uploads/2019/04/23142650/2019-Small-Business-Profiles-MA.pdf
According to the knitr documentation, the table code should not get sanitized. If you knit the MWE however, you will see that several characters do get sanitized (escaped). For example, \ is sometimes turned into \textbackslash{}. So, it seems that some package update has changed when code gets sanitized. If you simply copy the RMD table code from below and paste it into the TeX output, it compiles fine.
I have tried reverting back to many of last year's packages, yet to no avail.
---
title: "MWE"
output:
  pdf_document:
    keep_tex: yes
---
\begin{tabular}{@{}lll}
\begin{tabular}{ll}
A & B \\
A & B \\
\end{tabular}
&
 \begin{tabular}{ll}
A & B \\
A & B \\
\end{tabular}
&
\begin{tabular}{ll}
A & B \\
A & B \\
\end{tabular}
\end{tabular}

*[In my original code it was part of an "asis" chunk. You can try this, and find the same problem.]
Answer: This is a known problem and the solution is to add raw attributes to pandoc, which ensures that content inside the block is not escaped.
1) Add md_extensions: +raw_attribute
2) Add a latex block
For your examples this works as follows:
---
title: "MWE"
output:
  pdf_document:
    md_extensions: +raw_attribute
    keep_tex: yes
---

```{=latex}
\begin{tabular}{@{}lll}
\begin{tabular}{ll}
A & B \\
A & B \\
\end{tabular}
&
 \begin{tabular}{ll}
A & B \\
A & B \\
\end{tabular}
&
\begin{tabular}{ll}
A & B \\
A & B \\
\end{tabular}
\end{tabular}
```

or when using it inside a code chunk:
```{r, results = "asis"}
cat("```{=latex}")
// your latex code
cat("```")
```

P.S.: pandoc version 2.0.0 is needed for this feature


Using stringbuilder put time into string (class) C#

Question:    public string getTime()
   {
       StringBuilder RetString = new StringBuilder();
       RetString.Append(Hours.ToString().PadLeft(2, '0') + "-" + Min.ToString().PadLeft(2, '0') + "-" + AMPM.PadLeft(2, '0'));
       return RetString.ToString();
   }

I'm attempting to return a time (in string format) back to a form string variable using this. I have the user setup to enter a time and the time is stored in this class, and all im doing now is bringing that data to the form im working in. I've verified that the data is going into the class and being stored in the variables.
The error i get is :

Not really sure what the problem is.
I have the variables declared of course
    private int Hours;
    private int Min;
    private string AMPM;

I have get sets setup:
public int _hours
    {
        get
        {
            return Hours;
        }
        set
        {
            if (value <= 12 && value >= 1)
            {
                Hours = value;
            }
            else
                Hours = 0;
        }
    }

    public int _min
    {
        get
        {
            return Min;
        }
        set
        {
            if (value <= 59 && value >= 1)
            {
                Min = value;
            }
            else
                Min = 0;
        }
    }

    public string ampm
    {
        get
        {
            return AMPM;
        }
        set
        {
            if (AMPM == "AM" || AMPM == "PM")
            {
                AMPM = value;
            }
            else
                AMPM = "";
        }
    }

and my call to the class:
string timefromclass;
timefromclass = timec.getTime();

The only thing that I think it could be would be my call to the class where i store the time is
C_Time time = new C_Time();

but in the other form i setup another one as well.
C_Time timec = new C_Time();

Possibly i'm trying to retrieve the time from an empty instance?
EDIT:
public void setTime(int hours, int min, string aMPM)
    {
        Hours = hours;
        Min = min;
        AMPM = aMPM;

That's really the only place I assigned that variable anything.
Comment: just a side note - your casing is somewhat off, based on standard c# conventions. Public methods and properties should be `PascalCase`, while private members should be `camelCase`. Use of underscore prefixes usually applies to private variables but you're using them for public properties.
Comment: Your setter code for ampm is wrong. Should be `if(value == "AM" || value == "PM")` The current if condition you have will never be met based on your class design.
Comment: When looking at the null reference exception in visual studio, you should be able to isolate the actual object that is null. That would point you in the right direction. As others have said likely AMPM.
Comment: Well it seems that AMPM is in fact null and empty. But now my problem is, the numbers i passed to this class for the time they entered isn't showing up in this instance.
Comment: Alright i changed that over to what you suggested, the error still occurs however. >_< I'm not sure what i'm missing here. when i view all of the values on the variables when i first assign them they end up right but when i go to retrieve the values they are 0 or like that string is empty.
Answer: Do you initialize AMPM somewhere in the code. If not it will be null (the default value for a reference type variable) and calling PadLeft on it will give you a NRE.
Answer: From you code, I assume your AMPM field is null.
You do not seem to instantiate it anywhere apart from the setter, which you are not calling in your code.
Initializing it should solve the issue:
private string AMPM = string.Empty;

Comment: Thank you! this fixed the issue. :D Now the values just aren't being showing up like they should be.
Answer: The error you are getting means that you are trying to read a "reference type" that hasn't been initialized and is therefore null.
int is a "value type" and value types can't represent null values.
string is a "reference type" and is the only reference type you have in your class (AMPM).  This must be where the problem is.
You will need to initialize AMPM to stop the error.  If you don't already have one, adding a constructor to your class is a nice way to handle initializations.  For example:
public C_Time()
{
    AMPM = "";
}

Answer: As other have pointed out AMPM is the problem. You should define it like this
private string _ampm;

public string AMPM
{
    get
    {
        return _ampm ?? ""; // Returns "" if _ampm == null
    }
    set
    {
        _ampm = value;
    }
}

Then work with the property
AMPM.PadLeft( ...

But why not just use
String.Format("{0:00}-{1:00}-{2}", Hours, Min, AMPM.PadLeft(2, '0'));

It would be safer to work with an enum
public enum AmPm
{
    Undefined,
    AM,
    PM
}

This clearly enumerates the valid entries. Otherwise you could enter something like "afternoon" or "am" instead of "AM".


How to produce a polynomial trend line equation that takes three arrays as parameters?

Question: Does anyone know of any programming code for producing a polynomial trend line equation that takes three arrays as parameters, ie X, Y and Weight?
Or even if you could explain in English how such a program would work.
Answer: If you mean polynomial regression, then a good resource is the found at Rosetta Code, in the programming language of your choice. I personally enjoy using the C/GSL example.
Generally speaking, the gist of polynomial regression is the same as linear regression (or weighted regression) in that you have to solve for the least squares/maximum likelihood estimates of the coefficients $\hat{\beta}=(X^TWX)^{-1}X^TWY$, except that columns of your matrix $X$ now include polynomial transformations of the original data.
A more complex alternative would be locally weighted regression, which involves fitting the above model, weighted polynomial regression, to each observation. However, the weights $W$ used at each observation are a function of how far the other observations are from the current one. An example of such a function would be the Gaussian kernel.


React doesn't update state when browsing a different website or application

Question: I am currently learning react right now. I am following a react tutorial for a stopwatch application where it just increments the time every second. The code perfectly works as it indeed increments the time every second. However, if I open a new browser tab, or even open a different application, it seems that react doesn't update the state, meaning, the timer stops incrementing the value. But if I visit the react application, it begins to increment (once again).
I literally watch the timer go to '00:00:10' and then click another tab and wait for about 10 seconds. When I go back to the react application, the timer is still at '00:00:11', instead of '00:00:20'.
Is there something I am missing? Why is react behaving this way? It is because of performance issues? I am pretty sure this is a nature of react but I can't seem to find an explanation anywhere else.
I am also not sure if I should provide the code for the stopwatch application as I am sure that it's not a bug, nor a problem relating to the code itself. Let me know if I need to include the code so that I can edit this question.
Answer: If your website isn't active (in an active browser tab) then the Browser doesn't execute your JavaScript code. It does that to save CPU time - people tend to have a lot of tabs open.
For a timer application you want to remember the timer start time (e.g. with <code> new Date().getTime()</code>) and then every second you calculate the difference to this start time. This way if the user leaves the tab and comes back then the timer is correct again after latest a second.
Another benefit is that your timer will be more accurate even if the browser tab remains focused all the time. The timer calls aren't exact so your code isn't called exactly every second, but only about every second and the errors sum up over time. If you have a start time available then these errors don't matter.
Edit: There is more to this topic, the best thing I could find quickly is this discussion How do browsers pause/change Javascript when tab or window is not active?
Comment: I see. So it is a browser feature, not a react feature. Also, using `new Date().getTime()` seems to be the correct way for creating a timer application. Thanks a lot!


High performance DB Cluster with Drupal

Question: I am looking for a system where I can cluster MySQL. I saw an article which guided me to custom Drupal schema for NDBCluster engine for MySQL clustering, Btw. I am using Drupal 7 with Varnish, memcache etc.
Drupal MySQL NDBCluster High availability
And I also saw another solution for clustering MySQL using Galera Cluster
(MarinaDB and Percona also uses this for Clustering)
Scaling Drupal stack with Galera
The reason why I need a cluster is because my fields are over 8 kilobytes
There will be a minimum of  15.000 Users visiting the site at the same time.
what is the performance expectations? and what would be the ideal DB to choose?
Answer: Galera Replication for Drupal
Things you need to watch out for:

Caching
Sounds like you are using memcached, that good because drupal caching needs to be disabled because if one drupal node modifies the cache stored in the db and that change
replicates the other drupal nodes don't know about it creating conditions in which the drupal cache can serve stale content. Most people use memcached for caching to get around this.
Deadlocks
On websites that are high writes you can incur deadlocks when two drupal nodes try to update the same row at the same time. In this case you would want your app to retry the action but Drupal doesn't always do that. In the Galera settings you can set up some settings in my.cnf (wsrep_retry_autocommit=n) to enable retries at the Galera layer to prevent deadlocks being sent to drupal. Although for a website with low writes and mostly reads you may never encounter the issue.

Other than perf testing a realistic workload I don't know of a formula for performance expectation.
For Galera I've used both MariaDB and Percona. Percona does have additional information it can expose for performance and troubleshooting. Not a lot of difference in how they use Galera replication. I've moved innodb databases between percona and maria and had no issues.
I've found a Percona whitepaper on galera performance and best practices for drupal. It seems to cover all the issues I've encountered plus some additional info: http://www.percona.com/files/presentations/percona-live/nyc-2012/PLNY12-galera-cluster-best-practices.pdf
At this time I would use Percona Galera or Maria Galera. I don't touch mysql from Oracle anymore.
hope that helps
Comment: Unfortunately the link isn't available anymore.

High performance DB Cluster with Drupal


javascript prototype loop for in array

Question: I am working on a project, which use a lot of "javascript".
I have lot of "ajax" calls, which returns always à "json" array.
For usefull reasons, I created two prototypes of Array object ("in_array" function and "shuffle" function).
Since I did the prototypes, all my "for in" loops are broken (two times showing "undefined" ...)
I looked into google and stackoverflow, and I know my mistake now.
Of course, if I delete my prototypes, the "undefined" go away.
But, I don't find all my answers.
First, I see lot of times, that using "for in" loops are bad, why ?
I develop in "PHP" or "python" too, and I DO love "for in" or "foreach" loops.
Secondly, I got a really lot of "for in" loops, so honnestly I prefer changing my prototypes, than changing my loops. Is this that much dirty to switch my prototypes to normal functions, and keep "for in" loops ?
Thirdly, I read that JQuery can correct this bug. My project did got JQuery, what is solution talking about (I only read that JQuery can correct this, not how).
Thank you,
EDIT :
My prototypes code :
// FONCTIONS ARRAY
Array.prototype.shuffle = function () {
for (var i = this.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var tmp = this[i];
    this[i] = this[j];
    this[j] = tmp;
}

return this;
}

Array.prototype.in_array = function (needle) {
    for(var i = 0; i < this.length; i++) {
       if(this[i] == needle)
           return true;
    }
    return false;
}

Comment: How did you define your prototype? How are you doing your `for .. in` loop? Did you add the `hasOwnProperty` check? (which skips the prototype). Don't use `for` or `for .. in` in non-framework code, write a map function.
Comment: No, my aim is to try to no add something over all my loops (got more than 50 "for in" in my code.
Comment: Then write a map function.
Comment: what is map function ? Like array_map in PHP ?
How do we do in JS ?
Thank you :)
Answer: Here is what a map function could look like. I wrote this out of the top of my head so there may be bugs.
function object_map(object, callback) {
    var key, ret = {};
    for (key in object) {
        if (Object.prototype.hasOwnProperty.call(object, key)) {
            ret[key] = callback(key, object[key]);
        }
    }
    return ret;
}

Answer: Your problem occurs:

because you're adding (enumerable) functions to Array.prototype which will then appear any time you enumerate any array.
because you shouldn't use for ... in to enumerate arrays, only for enumerating object keys.

If you know you're running on ES5 browsers, you can safely add functions to Array.prototype using Object.defineProperty:
Object.defineProperty(Array.prototype, 'shuffle', {
    value: function() {
        ...
    }
});

which defaults to creating non-enumerable properties.

javascript prototype loop for in array


How differentiate a song between major and relative minor scale (E.g differentiate B major from G# minor)?

Question: Since the major scales and their relative minor uses the same key signature, how differentiate a major song from minor?
Below is a screenshot of a sample from musescore (the key signature is used for both Db major and Bb minor):
Comment: @b3ko - there are ***9*** Bbs in that melody!
Comment: @b3ko - you actually were right. There *is not one Bb*..!
Comment: @tim Pre coffee. Not sure what I was thinking.
Answer: When a song is written in a major or minor key melodic line will typically accentuate the root of the key or one of the chord tones of the Tonic.  In other words melodic ideas will seem to start and end on the sixth if the song is in the relative minor key rather than in the major.  This is just one possible clue and can be tricky on its own as one can write clever melodies that have key ambiguity.  For example, the 3rd of the Major scale is the 5th of the relative minor.  The 7th of the minor is the 5th of the Major.
Chords can be deceiving.  Take for example the Major 6 chord played on the Tonic.  In the key of C this is {C, E, G, A}.  The minor 7th chord on the relative minor (Submediant) is {A, C, E, G}.  These chords are just inversions of each other.  If you are playing Jazz it is very common to use substitutions to make progressions a little more interesting.  For example I like to play All Of Me in the key of C maj but with the entire chord progression starting on A minor.  It works, it sounds a little dark but I do NOT transcribe the melody to A minor and it works.
In classical music (and my extension many forms of modern music) the two key are not strictly identical.  If a song is written in a minor key the melodies would necessarily include the leading tone.  They would be based on the harmonic or melodic minor.  This is the real clue in most cases.  If you see melodies that do not contain the leading tone to the minor scale it will not have the classic cadence.  A lot of rock music ignores this in my opinion but Jazz does not.  To the point about chords, if the song is truly in the relative minor and respects the leading tone then you will likely see a Dom7 chord played on the 3 of the major scale rather than the expected min7.  This is because of the leading tone in the harmonic minor scale.
In short, if it were in the minor key I would expect to see accidentals, specifically the 7th and 6th degrees of the minor scale.  Other than that one piece of information may not be enough to distinguish the key but a collection of clues would do it.  For example if the only chords are A minor and D minor and melody lines gravitate towards A, C, and E I'd call it A minor even with the absence of a G#.
Comment: To someone hearing your All of Me and not knowing it (is there anybody?!) It would come over as Am, as the very next chord would be perceived as the V of Am, which then throws it all with A major following. A cunning plan! And that leading note in minor isn't obligatory! (Your 3rd para.)
Comment: I, for one, do *not* know your All of Me!
Comment: I agree it's not obligatory but based on the historical evidence quite ubiquitous.   My point is there is a  bit of room to play.  And I don't move to the E7 but its substitute this softening the apparent minor sound
Comment: I do this live, have never recorded it.
Answer: Pieces can easily stray from major to relative minor on their journey, and vice versa.
The key sig. is only half the story. Listen carefully, and when the piece feels like it could end at that point, which we call 'home', then that probably is the piece's key. That can also be done by looking at the music and spotting the cadence points.
Another clue is that it's not that often the relative minor sticks to exactly the notes stated in the key sig. - which of course includes all the notes which don't need sharpening or flattening - they're implied within any key sig. That's why key C shows no ♯  or ♭.
The leading note in a minor key is often raised by a semitone, but that's not included in any key sig., unless it's Bartok! So finding Fx in your title's key sig. piece would usually mean the piece is in G♯m rather than B major.
Another obvious one would be to listen to the accompanying harmony. That's a great giveaway.
The same problem can occur in pieces that are modal. There may be a key sig. of one flat, but 'home' is G, thus making the piece in G Dorian, not either F major or D minor.


Multiple "unused" Views displays

Question: I'm creating a heavily customised website in Drupal. I want to use Views as a data source for a page with several options, where each option corresponds to a different display in a View. The reason I want to use Views is that they are easily configurable through a UI, so they are easy to tweak/change later if the need arises.
Unfortunately though, it seems like I can't create a display of a view that doesn't have some form of side effect (ie, a page display will create a new page). Does anyone have any bright ideas?
Answer: http://drupal.org/project/embed_views  "This is a views display based on the default views display that does not have any additional features or "cruft" that you can use to create embed views for your site."
Answer: As far as I know you can't just "unpublish" a view...
My suggestion would be to set the "access" setting of a view and make it only acessible for your own user or an admin role, that way its there but no-one can access it.
Comment: Attachments have zero side effects :)
Comment: I suppose what I was looking for was a different display type provided by a third-party module that doesn't have any side effects.
Answer: You can embed a view in code as well. You'd want to edit your template.php file and in hook_preprocess_page or hook_preprocess_node (depending on what you're actually adding the views to) you can embed a view with the following snippet:
<code>function mytheme_preprocess_page(&$variables) {
  // check $variables for your particular page
  ...
  // embed a particular view's default display
  $variables['embeded_view'] = views_embed_view('view_name', 'default');
}
</code>
In the example I've created a new variable ('embeded_view') which can then be printed in your page's tpl file.
Comment: I know how to embed it, the issue was I can't create multiple displays of the same view without creating extra pages/blocks/etc.
Answer: I often create multiple page displays that go to the same page.  Does only one path is added (that should solve your problem)
Then I take advantage of the fact that Views always returns the first display that the user has access to.  so I make sure that add restrictions in accordance to that rule.
So if if I have an admin-type display and a regular display, I make sure that the admin display is first and the regular display is second.  I add a restriction to the first one and add no restriction to the second one.
Comment: I'm embedding the views, not using a normal view page so this doesn't help since I want **no** pages created.

Multiple "unused" Views displays


The minimal free resolution of a module with a direct summand is not periodic

Question: Assume that $R$ is a local ring and that $M$ is a finitely generated $R$-module with a free direct summand, then why its minimal free resolution cannot be periodic?
Answer: If $M$ has a periodic free resolution of period $d\ge 1$, then $M$ is isomorphic to its $d$th syzygy. Now apply Lemma 0.1(ii) in Eisenbud's paper Homological algebra on a complete intersection, with an application to group representations which says that the kernels of the minimal free resolution starting from some rank (depending on $\operatorname{depth} R$) have no free direct summands.


Algebraic solution to $2x + \ln x=2$

Question: The answer to $2x+\ln x=2$ is $x=1$, which can be easily guessed after a failed attempt at solving it. I've tried to manipulate this into some inverse function of $2x+\ln x$, more specifically if $f(x)=2x+\ln x$, then I've tried to find $f^{-1}(x)$. But all I've gotten to is $xe^{2x}=e^2$, and I'm not sure how to simplify further.
Is there an algebraic solution to this? It seems like the product logarithm might be used, but I've only seen that function from Wolfram Alpha, and I'm not entirely sure how to use it.
Comment: take cases x>1 x<1 x=1
Comment: You might be lucky enough to have specifically named non-elementary functions such as the Lambert-W function.  In other cases however writing the solution is no better than just calling the solution "*the solution.*"  At that point, your only option might be to approximate the solution using numerical methods.  Even just altering your question to $2x+\ln(x)=3$ instead, you won't be able to write the value of $x$ any cleaner than "*the solution to $2x+\ln(x)=3$ near $1.349961838\dots$*" without using non-elementary functions like Lambert-W
Comment: If you multiply by $2$ on both sides to get to $2x \cdot e^{2x} = 2 \cdot e^2$, the answer might be clearer.
Comment: Just because an equation is easy to write doesn't mean it is easy to solve.  In general, when you mix exponentials and polynomials, or logarithms, or functions of different types in general and then ask to solve the equation... you will very quickly enter the realm of "*non-elementary functions.*"  It is possible that you can get lucky and find a solution by inspection.  It might even be easy to prove that there must exist a solution.  Actually analytically finding the solution without inspection however can be very difficult if not outright impossible.
Comment: Take the "simple" example $x = e^{-x}$. How would you find a solution in closed form?
Answer: Reiterating comments and complaints.
The way I read your question, you are asking for some function or method to algebraically/analytically solve the equation.  If we were told for instance that $x^2=4$ and were asked to find the positive value of $x$ satisfying this, sure we could say "Oh, $2$ is the answer because look here... $2^2$ does in fact equal $4$" but if we were to be asked about a similar question such as $x^2=3$ we would be hard-pressed to say "Oh, $1.732050807568877\dots$ is the answer because $(1.732050807568877\dots)^2=3$."
For the question of solving $x^2=3$ for $x$, we were able to introduce a notation and concept... the square root... which allows us to answer this easily.  $x^2=3\implies x=\sqrt{3}$.  The way I read your question, you are looking for the analogous "operation" which lets us extract the value of $x$ from the above equation which uses this operation rather than just spotting the solution.  Spotting the solution for a particular case and proving it is indeed the solution is all well and good however it does nothing to help us find a solution in a similar problem with slightly changed values.
The answer to whether or not there is such an operation to solve for $x$ is that hoping for such an operation which solves a transcendental equation such as this is futile.  Any such operation will only be as useful as saying the solution is "the solution" and will be non-elementary.  In some related problems you will not have any conveniently named function to use.  In other problems you may have a function such as the Lambert-W function (a.k.a. the product-log function as you alluded to in your post) but actually using the Lambert-W in practice will generally require numerical methods to evaluate.
For this specific problem, looking at the generalized equation of $2x+\ln(x)=a$ you can indeed use the Lambert-W function.  Modifying the equation a bit, we have $e^{2x+\ln(x)}=e^a$ and $xe^{2x}=e^a$ and so $(2x)e^{(2x)}=2e^a$
This is of the form $we^w=z$ whose solution is $w=W_k(z)$ for some integer $k$ where $W_k$ is the Lambert-W function on the $k$'th branch.  That is, replacing the values of $w$ and $z$ for what we had $2x = W_k(2e^a)$ giving us
$$2x+\ln(x)=a\iff x = \frac{W_k(2e^a)}{2}$$
In the specific case of $a=2$ this does simplify to $W_k(2e^2)/2$ which simplifies to $1$, again using that $we^w=z\iff w=W_k(z)$
In the specific case of $a=3$ (so the equation $2x+\ln(x)=3$) this would not simplify well and would just be written as $W_k(2e^3)/2$ which one can find via numerical methods is approximately $1.3499618380\dots$
Answer: $f$ increases, which says that our equation has one real root maximum.
But $1$ is a root, which says that we got the answer.
Comment: There is a mistake in your understanding of what is being asked.  Consider if the question were instead to solve for $x$ in $2x+\ln(x) = a$.  Yes, in the case that $a=2$ we have a fortuitous happenstance that $x=1$ works... which can be spotted by inspection and/or trial and error, etc... however the point is that it is unclear how to proceed (*if it is even possible to proceed*) in the case that a solution is *not* so easily spotted from the onset, for example in the case that $a=3$.
Comment: The fact that $1$ is the answer is besides the point.  The question is how to find $1$ analytically without trial and error, intuition, or inspection.
Comment: Right back at you.  Please learn what it means to "*read between the lines*" and understand the reason why the OP asked this question.  Simply verifying that $1$ is the answer to this specific instance is hardly useful.  Learning a technique to have found the corresponding solution(s) without inspection which can be applied to similar questions with slightly changed values is.
Comment: @JMoravitz I understand your point entirely, but let's not dismiss Rozenberg's logic on how there can only be one solution, too. Even though that partially answers the problem, and in fact the focus is, as you stated, more on how to systematically derive the solution, out of all the answers here, Rozenberg's is the most elegant. In theory it might sound great to employ more rigorous techniques to find the solution - in practice, if the question has such a trivial solution on inspection it doesn't provoke a strong need to tackle it as so. Problem is we *are* answering in benefit of the OP so...
Comment: @JMoravitz  What to you mean? Is there mistake in my solution? I wait your reaction.
Comment: @JMoravitz  Read please, what is it an equation and what is it to solve an equation. I can give a link if you want. Now, think please, what do you say.
Comment: @JMoravitz The theory, which you tell us, has no any relation with math. Sorry, but it's which I see. Bye.
Answer: $$f(x)=2x-2-\ln x \implies f'(x)=2-\frac{1}{x}, f''(x)=\frac{1}{x^2}>0$$.
$f_{min}=f(1/2)=\ln 2-1<0$ and $f(0)=\infty, f(\infty)=\infty$, hence $f(x)=0$ has even number of roots. The only min at $x=1/2$ implies $f_{min}<0$, so there are only two real roots.
Further $f(0)=+\infty, f(1/2)<0$ implies one root on $(0,1/2)$ and $F(1)=0$ confirms the other root at $x=1$. Only graphical or numerical method can give the root in $(0,1/2)$.
Answer: As noticed in the comments, in general we can't find elementary algebraic solutions to this kind of equations.
To proceed by elementary inequalities, in this special case we have that
$$2x + \ln x=2\iff \ln (x)=2(1-x)$$
and since

for $x<1 \quad \ln (x)<0 \,\land\, 2(1-x)>0$
for $x>1 \quad \ln (x)>0 \,\land\, 2(1-x)<0$
for $x=1 \quad \ln (x)=2(1-x)=0$

$x=1$ is the unique solution for the given equation.
Comment: How does this help us solve a related question such as $2x+\ln(x)=3$ and in general $2x+\ln(x)=a$?
Comment: @JMoravitz I've reformulated the answer. I think that a solution by elementary inequalities could be fine in a precalculus context.
Comment: I reiterate the question in the previous comment.  How does this help us solve $2x+\ln(x)=3$?  Sure... we can do similarly and talk about what happens when $x<1.349961838$ and talk about what happens when $x>1.349961839$ and show that a solution must exist between those... but what is $1.349961838\dots$ equal to specifically and how to find/write it?  The ease of finding the breakpoint of $1$ by inspection in the original question should not be misconstrued as implying ease of finding the breakpoint in the $2x+\ln(x)=3$ problem.
Comment: @JMoravitz The solution here is referring to the specal case $2x + \ln x=2$ and we can prove with elementary arguments that $x=1$ is the unique solution. Of course I agree with you that in general we can't apply the method to find a particular solution but only to prove that it exists. However here, in this particular case, the solution seems fine to me also in a precalculus context.
Comment: @JMoravitz Which approach should you suggest instead? It would be useful to have a full answer also from you. Thanks
Comment: posted full answer above

Algebraic solution to $2x + \ln x=2$


Creation of billing agreement can not be confirmed by customer Payum/paypal-express-checkout-nvp

Question: I am trying to create a recurring profile using express-checkout (Payum/paypal-express-checkout-nvp).
Howto from Payum
private function createAgreement(Purchase $purchase)
{
    $storage = $this->payum->getStorage('Coachup\PaymentBundle\Entity\PaymentAgreement');

    $agreementDetails = $storage->createModel();
    $agreementDetails['L_BILLINGTYPE0'] = Api::BILLINGTYPE_RECURRING_PAYMENTS;
    $agreementDetails['L_BILLINGAGREEMENTDESCRIPTION0'] = 'test';
    $agreementDetails['PAYMENTREQUEST_0_AMT'] = 0;
    $agreementDetails->setPurchase($purchase);

    $storage->updateModel($agreementDetails);

    $captureToken = $this->securityTokenFactory->createCaptureToken(
        $this->paymentName,
        $agreementDetails,
        'payment_checkout_progress_payment',
        ['purchaseId' => $purchase->getId(), 'paymentType' => $this->getId()]
    );

    $agreementDetails['RETURNURL'] = $captureToken->getTargetUrl();
    $agreementDetails['CANCELURL'] = $captureToken->getTargetUrl();
    $storage->updateModel($agreementDetails);

    return $captureToken->getTargetUrl();

}

A token seems to be generated with paypal, the user gets redirected to paypal (sandbox) and once i log in to confirm the agreement, i get a generic error message (loosely translated)
"The request can not be processed, please return to the store and choose another option".
Not even an error code...
Any help?
Comment: I'd advice you to look at http://sandbox.payum.forma-dev.com/. there is an example of recurring payment. It is written on symfony2. The code could be found here: https://github.com/Payum/PayumBundleSandbox/blob/master/src/Acme/PaypalExpressCheckoutBundle/Controller/RecurringPaymentExamplesController.php
Comment: when trying to set up a profile with the demo page, i still get the same error. So i guess the problem might be with my sandbox account. Personal/Verified(Premier)/CC and Debit/Enough balance.
Answer: Its possible that the initial payment of 0.00 is failing, which is making it so the billing agreement is not created. Here is a way that you can override this and create the profile anyway. This comes directly from the PayPal documentation:
By default, PayPal does not activate the profile if the initial payment amount fails. To override this default behavior, set the FAILEDINITAMTACTION field to ContinueOnFailure. If the initial payment amount fails, ContinueOnFailure instructs PayPal to add the failed payment amount to the outstanding balance due on this recurring payment profile.
If you do not set FAILEDINITAMTACTION or set it to CancelOnFailure, PayPal creates the recurring payment profile. However, PayPal places the profile into a pending status until the initial payment completes. If the initial payment clears, PayPal notifies you by Instant Payment Notification (IPN) that it has activated the pending profile. If the payment fails, PayPal notifies you by IPN that it has canceled the pending profile.
If you created the profile using Express Checkout, the buyer receives an email stating that PayPal cleared the initial payment or canceled the pending profile.
Here is the direct link in case you need it:
Recurring Billing Integration Guide
Comment: Thanks for your answer. But this did not solve the problem. Right now i suspect the problem being with my sandbox-account, since i get the same error when using payums demo sandbox.
The account i use for payment is personal, bank verified, has a valid CC and nearly 1000USD balance.


Notice: Undefined offset: 14 in user_node_load() (line 3682 of modules/user/user.module)

Question: I'm getting the following error:
Notice: Undefined offset: 14 in user_node_load() (line 3682 of modules/user/user.module).
What fields in the db do I need to alter to fix this?
I've tried "users" table, creating new admin and altering the UUID to 1 as I thought this would fix it, but no.
Can anyone offer any advice of how to fix this?
Many thanks
Answer: You're either trying to load node 14 or user 14 and that doesn't exist.
Comment: I see. Node 14 exists and it appears to be loading fine. Is that user ID 14? thanks Colin.
Comment: Without seeing your system I have no idea, but you mention you have been fiddling in the database and I suspect that one or more nodes have authors that don't exist anymore.
Answer: This happened when you exported the content to another installation and viewed the content - the new install was looking for the same user id that created the content on the original site.
Solution -
 Create a new user and update author in corresponding node.


Como implementar um player de vídeo com opções de qualidade para reprodução online?

Question: Alguém sabe de alguma biblioteca ou outra forma de reproduzir os vídeos do meu servidor com controle de qualidade para evitar carregamento lento, estilo o do youtube, para que o usuário selecione a resolução (por exemplo).
Desde já agradeço.
Answer: Existe o Video.js, uma biblioteca open-source com boa popularidade no GitHub, utilizada em mais de 400,000 websites, segundo a própria página.
Há também o JW Player, o mais popular player embarcado do mundo, segundo a própria página.
Outras opções para tecnologias de mídia podem ser vistas neste site de estatísticas.


On the definition of (small) inductive dimension

Question: A regular topological space $X$ has inductive dimension smaller or equal to n if and only if:
($n=-1$) $X=\emptyset$;
($n>-1$) The space $X$ has a base of opens $\mathscr{B}$ such that, for all $B\in\mathscr{B}$,  $\delta B$ (the boundary of B) has inductive dimension smaller or equal to $n-1$.
Now.. if $X$ has inductive dimension smaller or equal to $n$, can we say something about the dimension of the boundary of a general open subset of $X$?
Answer: I would be surprised if there was a general result regarding boundaries of general open sets in spaces such that $ind(X)=n$. The only thing that comes to mind is the following:
Prop: If $X$ is a regular space such that $ind(X)=n<\infty$ then for each $m=-1,0,1,\ldots,n-1$ there is a closed subspace $C\subseteq X$ such that $ind(C)=m$.
In proving this it's actually a lot easier to use a different characterization of $ind$ in regular spaces.
Prop: A regular space $X$ satisfies the inequality $ind(X)\leq n\geq 0$ ($n<\infty$) if and only if for every point $x\in X$ and closed subset $B\subseteq X$ no containing $x$, there is some closed set $L\subseteq X$ such that $L\cap(B\cup\{x\})=\emptyset$ and $L$ separates $X$ between $x$ and $B$ and $ind(L)\leq n-1$.
When we say that $L$ separates $X$ between $x$ and $B$ we mean that there are disjoint open sets $U,V\subseteq X$ such that $x\in U$, $B\subseteq V$, and $X\setminus L=U\cup V$. Depending on the book you are looking at the set $L$ can be called a separator between $x$ and $B$ or a partition between $x$ and $B$.
With this particular characterization in hand it's a bit easier to prove that first proposition I stated, because if $ind(X)=n<\infty$ then there must be some $x\in X$ and some closed set $B\subseteq X$ not containing $x$ such that for every partition $L$ between $x$ and $B$ one has $ind(L)=n-1$ or $ind(L)=n$. Then you can proceed to the subspace $L$ and find subspaces of even smaller dimension.
I suppose one general result that could be stated is that if $U\subseteq\mathbb{R}^{n}$ is an open set then one necessarily has that $ind(\partial U)\leq n-1$ as a set in $\mathbb{R}^{n}$ has dimension $n$ if and only if it has nonempty interior.
It is also pretty easy to find subspaces of $\mathbb{R}^{n}$ with open subspaces in which boundaries of open sets have to have arbitrarily small dimension. Just attach lower dimensional cubes to higher dimensional cubes.


The year appears every 12 lines, but I want on all lines

Question: I have an odd problem. Look at df:
Year <- c(1994, rep("NA", 11),1995,rep("NA",11))
Month <-c(1:12, 1:12)

df <- data.frame(Year,Month)

The year appears every 12 lines, but I want on all lines, like:
Year <- c(rep(1994, 12), rep(1995,12))
Month <-c(1:12, 1:12)

df_2 <- data.frame(Year,Month)

> df_2

   Year Month
1  1994     1
2  1994     2
3  1994     3
4  1994     4
5  1994     5
6  1994     6
7  1994     7
8  1994     8
9  1994     9
10 1994    10
11 1994    11
12 1994    12
13 1995     1
14 1995     2
15 1995     3
16 1995     4
17 1995     5
18 1995     6
19 1995     7
20 1995     8
21 1995     9
22 1995    10
23 1995    11
24 1995    12

I was trying a loop approach, but I wasn't able to solve this.
PS: this df goes until 2020, so the Month column goes until 11 in 2020.
I appreciate it if someone can help :)
Answer: We can have NA without the quotes, and use fill
library(dplyr)
library(tidyr)
df %>%
   mutate(Year = na_if(Year, "NA")) %>%
   fill(Year)

-output
#    Year Month
#1  1994     1
#2  1994     2
#3  1994     3
#4  1994     4
#5  1994     5
#6  1994     6
#7  1994     7
#8  1994     8
#9  1994     9
#10 1994    10
#11 1994    11
#12 1994    12
#13 1995     1
#14 1995     2
#15 1995     3
#16 1995     4
#17 1995     5
#18 1995     6
#19 1995     7
#20 1995     8
#21 1995     9
#22 1995    10
#23 1995    11
#24 1995    12

Answer: You can do it in base R this way:
yr <- rep(1994:2020, each = 12)
yrs <- length(1994:2020)
mth <- rep(1:12, yrs)
df <- data.frame(cbind(yr, mth))

Answer: Here is a solution with package zoo.
First of all, make the strings "NA" real NA values.
is.na(df$Year) <- df$Year == "NA"

Now fill down, the default of function na.locf.
df$Year <- zoo::na.locf(df$Year)