How to map 3 different objects on a table

Question: I am trying to map 3 different objects that I get when I make a call to an API.
The goal is to print async, one at a time so the page does not take many time to load.
There's just one call that gets these objects, it's a call to a dynamic URL, so I change the parameters on a loop and I get the response.
The objects come like this:
Object 1
{
  Name: one
  Group: one
}

Object 2
{
  Name: two
  Group: two
}

Object 3
{
  Name: three
  Group: three
}

What I was trying to achieve was mapping these objects one per line, like a table:
Name: one     Group: one
Name: two     Group: two
Name: three   Group: three

Instead, I get them on the same line. The object changes from the first one to the last. The last stays, as if iterating through all of them and stopping at the last one.
My call to the API:
export default function Machines({data}) {

     const classes = useStyles()
     const style = styles();

     const name_Machines = data.map((row)=>{
         return (row.name);
     });

     const resource_group = data.map((row)=>{
         return (row.resource_group);
     });

    let url
    const [MachinesRow, setMachinesRow] = React.useState([])
    React.useEffect(() => {
    resource_group.forEach((keyword, index) => {
     url = "/api/machine/" + keyword + "/" + name_Machines[index]
     fetch(url, {
       method: "GET",
       headers: {
         "Content-Type": "application/json",
         Authorization: "Bearer " + window.localStorage.getItem("access_token"),
       },
     })
        .then(resp => {
        return resp.json()
        })
        .then(data => {
        setMachinesRow([...MachinesRow, ...[data]])
        })
        .catch(error => {
        console.log(error)
        window.localStorage.removeItem("access_token")
        window.location.replace("/")
        })
     })
    }, [])

My code:
return (

Azure machines

        <TableHead>
          <TableRow>
            <TableCell align="left">name</TableCell>
            <TableCell align="left">resource_group</TableCell>
            <TableCell align="left">location</TableCell>
            <TableCell align="left">status</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {MachinesRow.map(row => (
            <TableRow key={row.name + row.resource_group}>
              <TableCell align="left" component="th" scope="row">

              </TableCell>
              <TableCell align="left">{row.resource_group}</TableCell>
              <TableCell align="left">{row.location}</TableCell>
               <TableCell  key= {row.name + row.resource_group}align="left">
                 <MachineStatusIcon
                  status_code={row.status_code}
                  status={row.status}
            />
               </TableCell>

          </TableRow>
         ))}
        </TableBody>

  )
}

Answer: When you set your callback functions to call:
setMachinesRow([...MachinesRow, ...[data]])

you are creating a new Array object while using the original MachinesRow which is an empty Array object (You create all 3 callbacks from the same scope). Doing it 3 times will leave you with the last data set, because each one will replace the previous with empty data + the request result.
Edit
Do this instead.
React.useEffect(() => {
    const resultsPromise = resource_group.map((keyword, index) => {
        url = "/api/machine/" + keyword + "/" + name_Machines[index]
        return fetch(url, {...})
            .then(resp => resp.json())
            .catch(error => {
                console.log(error)
                window.localStorage.removeItem("access_token")
                window.location.replace("/")
            })
    })

    Promise.all(resultsPromise).then(results => setMachinesRow([...MachinesRow, ...results]));
}, [])

You might need to work the data on results, this is just an example of how to set you in a position where you have all your data in one place
Comment: @PatrickJosé, you should have used your own object for the second parameter of fetch, he wrote that to shorten the code
Comment: Hi Gabriel, I' am new to react and this for me is quite advanced, what's the way to fix it? to get all api calls and print them on a table.
Comment: @PatrickJosé Asking him to give you fish while he is trying to teach you how to fishing =).
Comment: @ilkerkaran If i understood what he said, i would do it, them problem here is that i am very green in this language, and what i can make it's by looking from other examples, and simple things :)
Comment: @Gabriel but in that way the call will be all in the same array no? And what i am trying to achieve is an async call, one at time so the page loads faster
Comment: You'll be doing 3 calls at the same time. Notice I changed foreach to map. That will return you 3 promises which will be awaited on with Promise.All.
Comment: @GabrielFerrarini thanks, there is some Unexpected token error, that I'am trying to figure it out, it points to the `return fetch(url, {...})` on the {}
Comment: @ilkerkaran thanks, didn't notice that, newb here :)
Comment: @PatrickJosé, No worries, we all have been there. Happy Coding!


How to disable Auto Complete in Sublime Text (2&3)

Question:
I understand there are a few questions surrounding the auto_complete function in Sublime Text.
However, I have not been able to disable the auto_complete function in the Sublime Text settings (I've tried both Sublime Text 2&3). I just get the "Error trying to parse settings: Unexpected trailing characters in Packages/User/Preferences.sublime-settings:5:1" error when inputting the {"auto_complete": false,} command in user settings.
Would love to turn off the setting, but can't find a way to. Any help much appreciated!
Comment: Why did you put the settings in two separate sets of curly braces, as opposed to the original settings which had them comma-delimited in one? And if you have them in one set, make sure they actually are delimited by commas.
Answer: Put , after font-size:17 like:
{
  "font_size":17, //note a comma here after 17
  "auto_complete": false,
}

Answer: There are two options:
1:  In Preference --> User,  Check if TernJS plugin is Installed. If Yes, Unistall it from your editor (i.e. Sublime Text Editor).
2: In Preferences --> User, check for the auto_complete and change it to false

"auto_complete": false,

Restart Your Editor(Sublime Text)
Answer: This is the first result that pops up when Googling "Sublime Text disable autocomplete", and none of the answers answered my question completely, so I'd just like to add to the existing answers that if you are setting auto_complete to false and still having problems with Sublime Text auto-closing parentheses and brackets, then you also need to set auto_match_enabled to false.  This should solve the problem.  So as a whole, here is what I have:
{
    "auto_complete": false,
    "auto_complete_commit_on_tab": false,
    "auto_close_tags":false,
    "auto_match_enabled": false
}

Comment: This is the right answer -- finally (all of them must be put onto the Preferences > Settings > User)
Answer: This should be the option.
{
    "auto_close_tags":false
}

Comment: Thank you, this is what I was looking for.
Comment: This should be the answer for anyone trying to disable the tag autocomplete for HTML/XML specifically
Answer: My solution to this problem was to change "auto_complete_commit_on_tab" from true
to false. This way you aren't turning off autocomplete altogether, but the autocompletion is ignored unless you hit the tab key.
In preferences, user settings, add:
{
"auto_complete_commit_on_tab": false
}

Comment: Do you mean setting it to true? This is what prevented forced errors while typing for me. It also gives you a list with the most relevant suggestion on top. Recommended.
Answer: I came here looking for a Python-related solution, where autocompletion worked well for variable names etc. but was quite slow for methods etc.
So, to disable Python syntax autocomplete:

open the command palette with ctrl + shift + P
enter Package Control: Remove Package and select it
enter Jedi and remove the Jedi autocomplete package


Borel functional calculus (Detail in construction)

Question: In a course I've seen the proof of the following theorem:

Let $A\in\mathcal{L}(\mathcal{H})$ be a self-adjoint operator. Then there is a unique map
$\phi_{A}:\mathcal{B}(\sigma(T))\to\mathcal{L}(\mathcal{H})$
such that:

$\phi_{A}$ is a $\star$-algebra homomorphism

$\phi_A(\operatorname{id}_{\sigma(A)})=A$

$\phi_{A}$ is continuous.

Let $(f_{n})_{n\in\mathbb{N}}\subseteq\mathcal{B}(\sigma(A))$ be a bounded sequence s.t. $f_{n}(t)\to f(t)$ for all $t\in\sigma(A)$ for some $f\in\mathcal{B}(\sigma(A))$. Then $\langle f_{n}(A)v,w\rangle\to \langle f(A)v,w\rangle$

I give a sketch of the proof of the existence that we have seen:
Let $f\in C(\sigma(A))$. Consider the continuous linear functional $L_{v,w}(f):=\langle f(A)v,w\rangle$.
By the Riesz theorem(for $C_c$), there are complex measures $\mu_{v,w}$ such that
$$\langle f(A)v,w\rangle=\int_{\sigma(A)}\,f\,\mathrm{d}\mu_{v,w}.$$
Now we want to define $f(A)$ for $f\in\mathcal{B}(\sigma(A))$ as the operator that satisfies:
$$\langle f(A)v,w\rangle=\int_{\sigma(A)}\,f\,\mathrm{d}\mu_{v,w}.$$
Using Riesz theorem(for Hilbert spaces) it is wasy to show that this operator exists.
Now define $$\phi_A(f)=f(A)$$ and show that it satisfies all the properties.
The details were left as an exercise. I've been able to prove that $\phi_A$ fullfuills all the properties except that $\phi_A(fg)=\phi_A(f)\phi_A(g)$. I think that should be easy but I can't figure it out. Can you explain me how to prove it or give me same hint? Thank you
Comment: I would start by showing it for simple functions and then use a density arguement and 4.
Comment: Hint:  if $s= \sum_i a_i 1_{A_i}$ is a simple function then
$$ \phi(s) = \sum_i a_i E(A_i),$$
where $E \colon \sigma (A) \to \mathcal L(H) $ is (the spectral measure associated with $\phi$) given by $(E(A)x,y) = \mu_{x,y}(A)$.
Answer: As I said in the comments, you can show that
$$\phi(fg) = \phi(f) \phi(g)$$ for $f,g$ simple functions.
This then implies that
$$||\phi(s)|| \le ||s||_\infty  \tag {1} $$ for any simple function $s$. Indeed,  for $x \in H$,
\begin{align*}
||\phi(s) x||^2 &= (\phi(s) \phi(s)^* x,x) = (\phi(s) \phi(s^*)x,x) = (\phi(|s|^2)x,x)
\\
&= \int_{\sigma(T)} |s|^2 \ \mu_{x,x} \le \|s\|_{\infty}^2 \mu_{x,x} (\sigma(T))
\\ & = \|s\|_\infty^* \|x\|^2.
\end{align*}
[In fact, one can show equality in (1) but we don't need that.]
Let $f,g$ be bounded borel functions on $\sigma(T)$. We can approximate $f$ and $g$ in the supremum norm by a sequence of simple functions $(f_n) $ and $(g_n)$ respectively. Then by (1) the sequences $(\phi(f_n))$ and $(\phi(g_n))$ are  Cauchy in $B(H)$ and thus converge. Since  $\phi(f_n) \xrightarrow{WOT} \phi(f) $   and $\phi(g_n) \xrightarrow{WOT} \phi (g) $, we infer that $\phi(f_n) \to \phi (f) $ and $\phi(g_n) \to \phi(g)$ in the operator norm. Hence,
$$ \phi(fg) = \lim \phi(f_n g_n) = \lim \phi (f_n) \phi (g_n) = \phi(f) \phi(g) .$$
Comment: Thank you! I Will try ti show It for simple function, but it seems quite easy.
Comment: Can we do the same with continuous functions? I ask because of this [questions](https://math.stackexchange.com/questions/4250550/extension-of-functional-calculus-of-continuous-functions/4252420?noredirect=1#comment10268972_4252420).


"contact" SQL table: what is it for and where do I edit it?

Question: We are running a site with the Hotel Diamond theme. Today we received a bounced email: apparently, someone had tried using the contact form in the site to send us a message, and the system had tried sending it to "email@example.com".
Now, the Hotel Diamond theme has an option to configure the email for the contact page, but it is correctly configured (i.e., it's NOT "firstname.lastname@example.com"). So I decided to look for that address in the raw SQL dump of my site, and I found this:
INSERT INTO `contact` (`cid`, `category`, `recipients`, `reply`, `weight`, `selected`) VALUES
(1, 'Website feedback', 'firstname.lastname@example.com', '', 0, 1);

My question is: where do I edit that in the admin pages? And why is Drupal using this entry to send contact email, instead of the address we had configured in the Hotel Diamond config page?
Answer: Go to admin/structure/contact/edit/1 and change Recipients email address to whatever you want.


Attaching space, help on visualization

Question: Let $X$ be a topological space, $A\subset X$ a closed subspace. $CA$ means the cone of $A$, and by $SA$ I'll denote the suspension of $A$.
I need to prove that

$$ \left( \left( (X \cup CA) \cup CX \right) \cup C(X \cup CA) \right)/ C(X \cup CA)  \approx SX$$

I figured out that $((X \cup CA) \cup CX )/ CX \approx SA$ but for the first I can't even write down a sketch to help understanding the situation.
Can someone gives some advice about how to visualize the space in exam? I made some sketches for two easy cases, (where X and A are two concentric circles, or X is a disk and A a circle) but I can't generalize it an a satisfying way
Comment: It seems clear that $(((X ∪ CA) ∪ CX) ∪ C(X ∪ CA)) / C(X ∪ CA) \approx CX / X$. The parts you added are later glued to a point so you actually didn't have to add them. I visualized $X$ as a line segment and $A$ as its proper subsegment.
Comment: Hmmm, maybe it's not correct. I imagined $CX$ as a new cone independent from $CA$. So, is $CA ⊆ CX$ or are they independent?
Comment: @user87690 I think they are independent. The author says "added later"
Comment: What author are you talking about? Do you mean someone who gave you the question you posted or the author of the first comment? Note that the second comment is continuation rather than reaction to the first one. They are both by me.
Comment: @user87690 I'm trying to filling the details of the construction of the long exact sequence in K-theory. I'm referring to hatcher's k-theory book (pag. 52-53)
Answer: Let's first clear up the notation. Let $Y := (((X ∪ CA) ∪ CX) ∪ C(X ∪ CA))$. I assume that the meaning is such that the following hold: $X ∩ CA = A$, $CA ∩ CX = A$, $(X ∪ CA ∪ CX) ∩ C(X ∪ CA) = X ∪ CA$.
Now let's prove the following claim.

Let $A, B ⊆ X$, $A ∩ B ≠ ∅$. Then $(A ∪ B) / B \approx A / (A ∩ B)$.

Proof: Let $q: A ∪ B \to (A ∪ B) / B$ be the quotient and $i: A \to A ∪ B$ be the inclusion. Then $q \circ i$ is onto $(A ∪ B) / B$, is injective on $A \setminus B$ whereas $A ∩ B$ is contracted to a point. So to prove the claim it remains to see that $q \circ i$ is a quotient mapping. Let $(q \circ i)^{-1}[U]$ be open in $A$. Then either is is disjoint with $B$ and so is open in $A ∪ B$ or is joint with $B$ and so $q^{-1}[U] ⊇ B$ and $q^{-1}[U] ∩ A$ is open so again $q^{-1}[U]$ is open in $A ∪ B$. In both cases by $q$ being quotient, we have that $U$ is open which we wanted.
Now we can apply the claim to get the proposition: $(X ∪ CA ∪ CX ∪ C(X ∪ CA)) / C(X ∪ CA) \approx (X ∪ CA ∪ CX) / (X ∪ CA) \approx CX / X \approx SX$.
Note that we don't need that $A$ is closed, we just need that $X$ is non-empty.

Attaching space, help on visualization


Should I use async "all the way" for my GUI app?

Question: I'm a substantial way through developing a sizeable WPF application that will control a sophisticated piece of hardware via serial comms. At the very bottom of the application "stack" I have a serial comms tier (utilising the .Net 'SerialPort' class). Reading and writing to the h/w device is a fundamental part of the system, utilised by many different areas of the business logic tier, often interspersed with complex scientific calculations and other such logic; these BLL methods are in turn called from all over the UI tier.
Currently, everything in the business logic tier, including the SerialPort reading and writing, is synchronous. The only time I use async/await is in the UI tier, typically when calling into the business logic. Here I'll wrap the call in Task.Run(), e.g.:-
private async void SomeButtonClick(object sender, EventArgs e)
{
    await Task.Run(() => _someBLLService.TurnPumpOn());
}

This is a simple example that takes a matter of milliseconds. A more complex example would be starting a long-running process (again using the above technique); this business logic "service" will run for some seconds or minutes, collecting data from the hardware and performing other "control" functions during this time. Periodically it will broadcast data back to the UI for plotting on a chart (via a pubsub event aggregator framework). The above technique works well, allowing the UI to remain responsive while such business tier processes are taking place.
I've recently been considering going "async all the way", starting with the serial comms code (e.g. using .ReadAsync), but this would have repercussions across the system. Dozens (if not hundreds) of business logic methods would need to be refactored into async methods, right up to the UI tier. Here I would be able to simplify the above code slightly:
private async void SomeButtonClick(object sender, EventArgs e)
{
    await _someBLLService.TurnPumpOn();
}

While I'm not averse to tackling large refactoring jobs, I'm wondering what the benefits really are. A lot of folks (like Stephen Cleary) advocate the "async all the way" solution, but the main goal appears to be to keep the UI responsive when calling a long-running BLL process, which my Task.Run() technique already does.
Comment: To clarify, "async all the way" is another way of saying "don't block on async code" - it only goes one way. In the case of a UI app, the primary benefit of async is responsiveness, and `await Task.Run` is a perfectly fine solution if that works for you.
Answer: Since your app (presumably) is not under high load and is a GUI app the only reason to use async and await are productivity gains. Throughput and scalability do not enter the picture.
Therefore, do what is most convenient to you. This can very well be the await Task.Run pattern that you used in the sample code.

but this would have repercussions across the system

Yes. Async has a noticeable productivity cost and it is infectious. Only do that if you can clearly articulate the benefits you reap from that choice. Here, the only benefit would be that your UI code is a few characters shorter. It's the difference between your two code snippets. The entire rest of the system gets worse.
Maybe you have been following the C# community and picked up the trend to go async all the way. Programmers are very prone to jump to magic solutions without understanding them. Many advocates of async cannot even articulate the concrete benefits they derive from it. There is a lot of group think as well. Do not base your decision on internet advice alone. Factor that in and check for yourself what makes sense.
Comment: It's just a desktop app now, but there are plans to use SignalR to expose certain BLL methods, e.g. for a smartphone client to provide limited control of the h/w device (no more than one or two clients). My understanding is that SignalR handles client connections asynchronously, so presumably still not a good enough reason for async throughout?
Comment: SignalR supports you returning a task to it. That task can just be `Task.FromResult` or any other way to create a "dummy" task. If there is no load there are no perf concerns. SignalR will *internally* use efficient socket IO and you benefit from that.


Java not equals with OR

Question: I'm just wondering why this is not correct :
if ( !name.equals("abc") || !name.equals("cba") )`

And this is correct :
if ((!(name.equals("abc") || name.equals("cba") )))

thank you !
Comment: They do not mean the same thing.
Comment: I suggest you take an example of `name`, and think about what each part of the expression will evaluate to.
Comment: First condition will always return true as both the operands contradict each other.
Comment: This is basic logic. https://en.m.wikipedia.org/wiki/De_Morgan%27s_laws
Comment: *If name does not equal A or does not equal B* - it can't equal both at once, so is always true. — *Reverse of "name equals A or B"* - clearly a more sensible condition.
Comment: Thank you very much for the replies ! And it is not a matter of openning eyes, I'm just a beginner and I thought that it was a problem related to the code so I focussed on it. It is not because it is obvious for somebody at first sight that it is for everyone.
Answer: To understand the difference, it always helps to read out your condition statement in english.
if ( !name.equals("abc") || !name.equals("cba") )

Translates to

If name does not equal "abc" OR name does not equal "cba", then...

Whereas,
if ((!(name.equals("abc") || name.equals("cba") )))

If (name equals "abc' OR name equals "cba" ) IS FALSE, then...

or, by Boolean Logic,

If name does not equal "abc" AND name does not equal "cba", then...

The two are definitely not the same.
Answer: Think about how the ! works.
Take !(a || b)
whats the truth table:
a=f b=f = !(f || f) = !(f) = t
a=f b=t = !(f || t) = !(t) = f
a=t b=f = !(t || f) = !(t) = f
a=t b=t = !(t || t) = !(t) = f

Now take (!a || !b)
a=f b=f = (!f || !f) = (t || t) = t
a=f b=t = (!f || !t) = (t || f) = t
a=t b=f = (!t || !f) = (f || t) = t
a=t b=t = (!t || !t) = (f || f) = f

Now take the correct way to distribute  ! (!a && !b)
a=f b=f = (!f && !f) = (t && t) = t
a=f b=t = (!f && !t) = (t && f) = f
a=t b=f = (!t && !f) = (f && t) = f
a=t b=t = (!t && !t) = (f && f) = f

And for completeness sake take the same as (!a || !b) !(a && b)
a=f b=f = !(f && f) = !(f) = t
a=f b=t = !(f && t) = !(f) = t
a=t b=f = !(t && f) = !(f) = t
a=t b=t = !(t && t) = !(t) = f

Answer: The first code has this truth table

The second code instead has this truth table
Comment: Do you think this truth table is correct? Can you give me a case for which first condition has false value?
Comment: It was wrong. The online software I used is not working properly. Now I've corrected it. Thanks @SanketMakani
Comment: Still if you look conditions closely there are only three cases possible for both the condition. `a` and `b` can't be true at the same time.
Answer: Actually this is a math question. These are same logical equation:
!x || !y  ==  !(x && y)
!x && !y  == !x || !y

You can read more about logical operation here

Java not equals with OR


Shopping Questions - Home comforts

Question: What's our take on shopping questions? Specifically, ones around buying home comforts, such as foods from where you're from?
As an example, thinking of an Aussie expat living in London, who hankers after a taste of things from home, are any of these going to be ok?

Buying Australian Food in the UK?
Buying Australian Food in London?
Buying Vegemite in the UK?
Buying Vegemite in London?
Buying Vegemite in Southwark, London?
Buying Australian Food outside of Australia?
Strategies for finding foods from home when you're abroad?
UK customs rules on bringing a few jars of Vegemite into the UK?

Which do we think are too broad? Which too specific/localised? Which might qualify for Travel.SE but not here? Which ones (if any) look about right to ask here?
Answer: The answer is, we won't know until we find out.
Questions such as:

Where can I buy (food) in (country)?
Can I bring (food) to (country)?

.. will probably not give us the problems that lead to our general guidance of avoiding these types of questions. Why? They're quite narrowly scoped, which means that they won't attract a bunch of answers (in fact I worry if some will remain unanswered for extended periods of time) - and I don't think they'll overtake the site.
Where can I buy bock choy in China for less than (store X) sells it? is an obvious off-topic example. That's a purely regional question that has nothing to do with being an expat, we've got a good litmus test for that.
I'm not sure on the general strategy one, though I am a proponent of having a default canonical for when no regional specific question exists. If you can't find out where to get Utz chips in Panama, at least you've got some guidance to turn to, although I'm not quite sure what could go there.
However
These types of questions must be extremely narrowly-scoped, and the answers that we provide to them need to consist of much more than a link with a terse amount of text. These particular questions will be more aggressively moderated than others, so expect that.
Expats isn't Stack Overflow, or Programmers, or Super User - it's a brand new site that's going to have its own set of challenges and problems to solve. Lets solve problems as they become problems for us.
I'd love to be able to find out where I can get my hands on fresh Kale in Metro Manila, I love me some roughage. That fits our general rule about problems being exacerbated simply by living abroad, so, go for it as far as I'm concerned.
Everything in moderation, as they say - just keep that in mind.
Answer: I think these questions present a very interesting dilemma.  They are guaranteed to get asked, tons of them and often.  But they are of little use to most visitors aside from the question author.
And either most or least importantly, depending on your politics, is the simple fact that while expats may desire foods or other things from home, making it easy to get those things by staring at a website is actively harmful to the expat experience.  Being an expat can be about much more than eating your favorite cheese from home while working in China.  If you focus on keeping things the same when they are clearly not the same, you may limit the depth of your experience in many ways.  It's daunting to re-learn all the brands and products and shops and conventions, but isn't it great when you've done so?
With that out of the way, I'll take a crack at your specific examples:

Buying Australian Food in the UK?
Buying Australian Food in London?
Buying Australian Food outside of Australia?

Too vague, nobody can be sure what "Australian food" is, and it will end up being a popularity contest among foods that answer author A enjoys vs author B vs C.

Buying Vegemite in the UK?
Buying Vegemite in London?
Buying Vegemite in Southwark, London?

Too specific, and London is hardly uncharted territory.  A web search should get you started, or you can just pop over to Marks & Spencer, which you hardly need a Q&A website to tell you about.

Strategies for finding foods from home when you're abroad?

There can't be a right answer.  From what I know of other StackExchange sites, this would be a non-starter, as it is a sort of list or poll.

UK customs rules on bringing a few jars of Vegemite into the UK?

Customs rules, now we're talking!  This could have specific answers, which could address much more than Vegemite (canned spreads or so), and might not be immediately clear from a web search (I haven't checked this specific one, but similar ones definitely aren't always clear).  That said, there's no reason to have this on Expats instead of Travel--an existing site which if they'd take this question, would be a better fit as it would have a wider audience there.
Answer: As a new expat, I have to say "where can I buy X" is something I'm constantly asking myself and people around me. Sure, it's purely regional, but it's the kind of thing most people don't talk about unless they're new to the area.
Also, specific to my New Zealand locale, "Where can I buy X for less than Y sells it" is another question that I'm constantly asking, as it's quite often that certain items can be purchased in a big-box store or supermarket, but not for a reasonable price. However, there are all kinds of little places here which locals take for granted which offer good prices on specific items.
To generalize, I think it's good to allow purely regional information so long as it meets two criteria.

It's the kind of thing locals take for granted
It's the kind of thing expats ask with a disproportionate frequency, especially when they're new to an area.

Shopping Questions - Home comforts


how to echo a char instead of key pressed in JTextField

Question: I need to echo a particular character instead of the key pressed in JTextField.
the effect produced is like I press k key but * appears in the textfield.
Comment: Welcome to StackOverflow.Please read the FAQ before asking questions.
Answer: How about using a JPasswordField instead? It's a subclass of JTextField

that allows the editing of a single line of text where the view indicates something was typed, but does not show the original characters.

(Quote from Javadoc)
Regarding the addition that characters need to be transformed dynamically, you might want to look into the example of an UpperCaseField with an UpperCaseField from the Javadoc for JTextField. It can quite easily be transformed into some logic that transforms every character to another one.
Comment: it should work like : 'k' key pressed output 'a' in text area ,then press 'l' output append 'b' in text area and continue this process
Comment: I want to print something else everytime key is pressed and also use it as text field after certain condition is met
Comment: I'm not sure whether I understand your first addition. Regarding the latter, maybe replace the `JPasswordField` with a `JTextField` (be it read-only or not) once your condition is met. You can always get the text a user entered, even when it's a `JPasswordField`.
Comment: @user2076400 If this is what you want, kindly update your question accordingly. Your question (current version) only speaks of replacing 'k' with '*'
Answer: You neet to use JPasswordField for this. Using the setEchoChar(char) you can echo any character you want.
Update As per the OP comments, if the requirement is to echo different character based on differen key pressed by the user, keyTyped event can be used, as below:
sampleTextBox.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent event) {
            event.setKeyChar(getCharToEcho(event.getsetKeyChar()));
                            // getCharToEcho(char inputKey) will return the key to
                            // echo depending upon the key entered by the user
        }
    });


Consistency implies that bias & variance vanish?

Question: One can easily show using Markov's inequality that when Bias and Variance vanish, then an estimator is consistent with respect to the parameter of interest. Yet, I wonder why standard text books do not claim the reverse: If an estimator is consistent, both bias and variance must vanish. This should be trivial or is my intuition wrong?
Answer: There exist consistent estimators whose bias and variance do not vanish as sample size goes to infinity.
Indeed, let $X\sim \mathcal N (\mu,\sigma^2)$ and consider the problem of estimating $\mu$ with $n$ i.i.d. copies of $X$ that we denote $X_1,\ldots,X_n$, and let $\bar X_n := \sum_{i=1}^n X_i/n$ be the sample mean.
Next, let $(Y_n)$ be any sequence of random variables such that for all $n$, $Y_n$ is independent of $\bar X_n$, $\mathbb E[Y_n] = 0$ and $\text{Var} [Y_n] \ge c^2$ for some constant $c>0$.
It is easy to see that $Z_n := \bar X_n + Y_n$ is a consistent estimator of $\mu$, however it's variance is lower bounded by $c^2$ and thus $\text{Var} [Z_n] \not\to 0$ as $n\to\infty$.
Similarly, this Wikipedia article gives an example of a sequence of consistent estimators whose bias stays uniformly bounded away from zero.
I suggest you give a read to this excellent thread on stats.SE where the relationship between consistency and biasedness is discussed with many illuminating examples.


Unable to run Ajax Minifier as post-build in Visual Studio

Question: I've set up my post build config as demonstrated at http://www.asp.net/ajaxlibrary/ajaxminquickstart.ashx
I'm getting the following error though:
The "JsSourceFiles" parameter is not supported by the "AjaxMin" task.
Verify the parameter exists on the task, and it is a settable public instance property.
My configuration settings......
<Import Project="$(MSBuildExtensionsPath)\Microsoft\MicrosoftAjax\ajaxmin.tasks" />
<Target Name="AfterBuild">
<ItemGroup>
  <JS Include="**\*.js" Exclude="**\*.min.js" />
</ItemGroup>
<ItemGroup>
  <CSS Include="**\*.css" Exclude="**\*.min.css" />
</ItemGroup>
<AjaxMin
    JsSourceFiles="@(JS)"  JsSourceExtensionPattern="\.js$" JsTargetExtension=".min.js"
    CssSourceFiles="@(CSS)" CssSourceExtensionPattern="\.css$" CssTargetExtension=".min.css"  />
</Target>

I had a look at the AjaxMinTask.dll with reflector and noted that the publicly exposed properties do not match the ones in my config. There is an array of ITaskItem called SourceFiles though so I edited my configuration to match.
  <Import Project="$(MSBuildExtensionsPath)\Microsoft\MicrosoftAjax\ajaxmin.tasks" />
  <Target Name="AfterBuild">
    <ItemGroup>
      <JS Include="**\*.js" Exclude="**\*.min.js" />
    </ItemGroup>
    <ItemGroup>
      <CSS Include="**\*.css" Exclude="**\*.min.css" />
    </ItemGroup>
    <AjaxMin
        SourceFiles="@(JS);@(CSS)"  SourceExtensionPattern="\.js$;\.css$" TargetExtension=".min.js;.min.css"/>
  </Target>

I now get the error:
The "SourceFiles" parameter is not supported by the "AjaxMin" task.
Verify the parameter exists on the task, and it is a settable public instance property.
I'm scratching my head now. Surely it should be easier than this?
I'm running Visual Studio 2010 Ultimate on a Windows 7 64 bit installation.
Comment: i m also getting the same error what solution have you used ?
Comment: I rolled my own processor. You can get it on here on [nuget](http://nuget.org/packages/Cruncher). A Readme and source are here on [gihub](https://github.com/JimBobSquarePants/Cruncher)
Answer: I wouldn't recommend minifying during AfterBuild. Many build systems make the assumption that the source code is readonly and/or unchanging when the build is being executed, and that would include the .min.js files.
Instead, you can hook into the "CopyWebApplication" target and Visual Studio 2010's website deployment engine (WPP / Web Publishing Pipeline) to accomplish the same thing without .min.js files at all.
Have a look at my response on this question:
Concatenate and minify JavaScript on the fly OR at build time - ASP.NET MVC
To answer your question directly however, the "SourceFiles" property no longer exists. Some older blog posts weren't updated and now have the old information. Try placing "Js" in front of the properties - ie/ JsSourceFiles="@(JS)".
Latest version - http://ajaxmin.codeplex.com/
Documentation - http://ajaxmin.codeplex.com/wikipage?title=AjaxMinTask
Comment: Thanks for your reply. I've actually since written a mechanism since that compresses, gzips and caches the script on the fly which allows me a great deal of flexibility. Your answer is still very useful though soo I've marked it as the answer.


Como atualizar hora automaticamente usando strftime

Question: Estou colocando hora e data pra ta exibindo no meu site, estou fazendo assim:
echo utf8_encode(strftime("%X - %m %B, %Y" ))  ;

Mas a hora esta estatica so atualizando quando recarrega a pagina, queria saber como faço para ela ficar atualizando normalmente, como se fosse um relogio mesmo,
acho que deve ser com javascript. Alguém pode ajudar?
Answer: Sim, para isso é necessário fazer com JavaScript. As requisições HTTP não guardam estados no servidor (stateless) e, por isso, o script PHP deixa de ser executado após retornar a resposta à requisição. Desta forma, apenas será exibido o horário (do servidor) que foi executado o código.
JavaScript
Solução em JavaScript retirada daqui:

function checkTime(i) {
  if (i < 10) {
    i = "0" + i;
  }
  return i;
}

function startTime() {
  var today = new Date();
  var h = today.getHours();
  var m = today.getMinutes();
  var s = today.getSeconds();
  // add a zero in front of numbers<10
  m = checkTime(m);
  s = checkTime(s);
  document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
  t = setTimeout(function() {
    startTime()
  }, 500);
}
startTime();

Nada mais é que uma função que recupera os valores de hora, minuto e segundo através dos métodos getHours, getMinutes e getSeconds do objeto Date. Após, faz a formatação de minutos e segundos para exibir "01" ao invés de apenas "1", por exemplo. Também é utilizado a função setTimeout do JavaScript para manter a contagem de tempo rodando.


dig does not receive an answer

Question: bind config
zone "minskmag.by" {
  type master;
  file "/etc/bind/named/minskmag.by";
};

zone file
$TTL    3600
@            IN      SOA     ns1.thestudio.by. root.thestudio.by. (2012041615 10800 3600 604800 86400)
             IN      NS      ns1.thestudio.by.
             IN      NS      ns2.thestudio.by.
             IN      A       184.108.40.206

command:
dig minskmag.by @ns1.thestudio.by

doesn't receive answer section
could anyone help me?
Comment: Is this ns1.thestudio.by config and named config was reloaded after adding this? Does server has any views configured?
Comment: yes, it is configs from ns1.thestudio.by
and bind server successfully reloaded
server has no views
Comment: Can you provide the `dig` output?  Is the query getting an `NXDOMAIN` or `SERVFAIL` response, or simply timing out?  What about if you `dig @localhost` from the server?
Comment: `dig minskmag.by @184.108.40.206`

`; <<>> DiG 9.7.3-P3 <<>> minskmag.by @184.108.40.206`
`;; global options: +cmd`
`;; Got answer:`
`;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 31776`
`;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0`
`;; WARNING: recursion requested but not available`
`;; QUESTION SECTION:`
`;minskmag.by.   IN A`
`;; Query time: 472 msec`
`;; SERVER: 22.214.171.124#53(184.108.40.206)`
`;; WHEN: Mon Apr 16 21:15:54 2012`
`;; MSG SIZE  rcvd: 29`
Comment: `named-checkzone minskmag.by /etc/bind/named/minskmag.by`

`zone minskmag.by/IN: loaded serial 2012041600`

`OK`
Answer: Seems like your server simply does not know about zone you've configured.

Check permissions to zone file.
Check whether zone file lies where it should (you've used absolute file path - I'd avoid this as it complicates switching between chrooted and non-chrooted environment for named). Are you running named in chroot?
Check logs for any additional messages about your zone (enable logging in named or enable logging for daemon facility in syslog).
Answer:
Try this command:
route add default your.ip.address
service named restart
then try again the dig command.

dig does not receive an answer


How to align iconbuttons in card widget flutter?

Question: I am having trouble issues aligning my icon buttons to the middle of the card. As you can see in the picture, the icon buttons are on top attached to the top of the card.
How do I make it meet at the half size of the card? Any suggestions? (I want the buttons to be located at the middle of the card)
Tried: I tried putting padding or wrap my Row widget with a center, but it doesn't work.
 child: new Container(
            height: 150.0,
            width: MediaQuery.of(context).size.width,
            child: new Card(
              color: Colors.white,
              elevation: 8.0,
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Column(
                      children: [
                        IconButton(
                            onPressed: () {},
                            icon: Icon(Icons.sticky_note_2),
                            iconSize: 35,
                            color: Colors.lightBlue),
                        Text(
                          "Notes",
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 15,
                          ),
                        ),
                      ],
                    ),
                    Column(
                      children: [
                        IconButton(
                          onPressed: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => QuizRoute()),
                            );
                          },
                          icon: Icon(Icons.quiz),
                          iconSize: 35,
                        ),
                          Text(
                          "Quizzes",
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 15,
                          ),
                        ),
                      ],
                    ),
                    Column(
                      children: [
                        IconButton(
                          onPressed: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => EbooksRoute()),
                            );
                          },
                          icon: Icon(Icons.auto_stories),
                          iconSize: 35,
                        ),
                          Text(
                          "Ebooks",
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 15,
                          ),
                        ),
                      ],
                    ),
                  ]),
            ),
          ),
        ),
      ],
    ),

Comment: Try wrapping the `Row` widget with a `Center` widget.
Answer: Try below code and set mainAxisAlignment: MainAxisAlignment.center, to every Column widget.  Refer layout and Align
Container(
  height: 150.0,
  width: MediaQuery.of(context).size.width,
  child: Card(
    color: Colors.white,
    elevation: 8.0,
    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            IconButton(
                onPressed: () {},
                icon: Icon(Icons.sticky_note_2),
                iconSize: 35,
                color: Colors.lightBlue),
            Text(
              "Notes",
              style: TextStyle(
                color: Colors.black,
                fontSize: 15,
              ),
            ),
          ],
        ),
        Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            IconButton(
              onPressed: () {},
              icon: Icon(Icons.quiz),
              iconSize: 35,
            ),
            Text(
              "Quizzes",
              style: TextStyle(
                color: Colors.black,
                fontSize: 15,
              ),
            ),
          ],
        ),
        Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            IconButton(
              onPressed: () {},
              icon: Icon(Icons.auto_stories),
              iconSize: 35,
            ),
            Text(
              "Ebooks",
              style: TextStyle(
                color: Colors.black,
                fontSize: 15,
              ),
            ),
          ],
        ),
      ],
    ),
  ),
),

Result Screen->
Answer: What is the issue?
You are using center alignment in the row but not inside the column. Now column is taking the height of entire row but the children of the column is not aligned center.
Solution:
Try adding mainAxisAlignment: MainAxisAlignment.center in each of your column
Present Code:
Row
mainAxisAlignment:MainAxisAlignment.center
|_Column
|_Column
|_Column

Required Code:
Row
mainAxisAlignment:MainAxisAlignment.center
|_Column
  mainAxisAlignment:MainAxisAlignment.center  Add these to every column
|_Column
  mainAxisAlignment:MainAxisAlignment.center
|_Column
  mainAxisAlignment:MainAxisAlignment.center

For the complete code refer : @Ravindra's answer
Answer: Replace your "Row" widget with the following code, this will solve your issue.
Solution : Give your Column center alignment
mainAxisAlignment: MainAxisAlignment.center
      child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  IconButton(
                      onPressed: () {},
                      icon: const Icon(Icons.sticky_note_2),
                      iconSize: 35,
                      color: Colors.lightBlue),
                  const Text(
                    "Notes",
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 15,
                    ),
                  ),
                ],
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  IconButton(
                    onPressed: () {
                      // Navigator.push(
                      //   context,
                      //   MaterialPageRoute(
                      //       builder: (context) => QuizRoute()),
                      // );
                    },
                    icon: const Icon(Icons.quiz),
                    iconSize: 35,
                  ),
                  const Text(
                    "Quizzes",
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 15,
                    ),
                  ),
                ],
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  IconButton(
                    onPressed: () {
                      // Navigator.push(
                      //   context,
                      //   MaterialPageRoute(
                      //       builder: (context) => EbooksRoute()),
                      // );
                    },
                    icon: const Icon(Icons.auto_stories),
                    iconSize: 35,
                  ),
                  const Text(
                    "Ebooks",
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 15,
                    ),
                  ),
                ],
              ),
            ]),


$_FILES superglobal array key is not what file.inc expects

Question: I'm trying to do some custom stuff with a file upload field via the form API. I call to file_save_upload() but it thinks that the upload is empty because it's examining $_FILES['files'] but for some reason, my file is actually in $_FILES['CSV_file'] even when the file I uploaded is not a csv.
How might files superglobal end up with a CSV_file array key?
UPDATE
So apparently the form array
$form['my_menu_csv'] = array(
  '#name' => 'CSV files',
  '#type' => 'file',
  '#title' => t('Choose a CSV file'),
  '#title_display' => 'invisible',
  '#size' => 22,
  '#theme_wrappers' => array(),
  '#weight' => -10,
);

was causing the field to have the following HTML:
<input type="file" id="edit-my-menu-csv" name="CSV file" size="22" class="form-file">

and apparently the files array goes like $_FILES[$name], where $name = whatever the name attribute is in the HTML element. Makes sense! What doesn't make sense is why file_save_upload() expects to only ever encounter $_FILES['files'] but the form API uses a custom field name. Is this a bug in the form API?
Answer: I don't think it's a bug.
$_FILES['files'] is hard-coded into file_save_upload().
I believe you need to change how you construct your #name property.  The usage example in the Form API does it like this:
'#name' => 'files[' . implode('_', $element['#parents']) . ']',


Bash script to send all Wifi hotspot traffic over separate VPN tunnel on Ubuntu 18

Question: I'm working on a bash script that is supposed to create a hotspot on ubuntu 18. However I have special needs about what connection that hotspot is supposed to use.
I want all and any traffic from devices connected to my hotspot to go over a separate VPN tunnel and (not sure this part is relevant) I will randomize which VPN gets chosen from a set of options each time I activate the hotspot.
By default, when creating a hotspot on Ubuntu 18, it will simply share the existing connection whatever it currently happens to be.
When I open nm-connection-editor the GUI contains a VPN option, but I don't know how to create and modify a Hotspot by purely using bash.
I'm basically stuck not knowing how to make it happen programatically or if I lack some other knowledge to achieve this. Unless I missed something there, man pages for nmcli haven't been helpful to me.
What probably complicates things is that I'm already connected to a VPN on tun0, so I'm guessing I need to create a separate VPN connection, let's say over tun1 and make the hotspot use it.
Here is what I have so far
#that's the kind of call I use to activate my main VPN connection
#you can assume I have script already that gives me
#the value for mainconnectionuuid
nmcli con up uuid mainconnectionuuid #activates tun0, all traffic goes through tun0 after this

#now I want to activate a hotspot that uses a different VPN connection
#the following code activates the hotspot, but there is no option
#to separate the traffic to go over a different VPN
nmcli radio wifi on
nmcli device wifi hotspot ssid somessid password somepassword

What I need is something like this:
#activate main connection on tun0
nmcli con up uuid mainconnectionuuid

nmcli radio wifi on
#'useconnection' is a phantasy parameter here, but I need something like this
#assuming here that the connection under vpnforhotspotuuid would already define tun1 to be used
nmcli device wifi hotspot ssid somessid password somepassword **useconnection vpnforhotspotuuid**

Or like this:
#activate main connection on tun0
nmcli con up uuid mainconnectionuuid

#activate connection for hotspot on tun1
nmcli con up uuid vpnforhotspotuuid

nmcli radio wifi on
#'usetunnel' is a phantasy parameter here
nmcli device wifi hotspot ssid somessid password somepassword **usetunnel tun1**

How can I achieve this?
I'm not a major expert, I can write bash scripts and I know ufw but I'm somewhat scared of IPtables. I would appreciate a solution that is not too hard to understand as I also want to be able to write a script that undoes or at least deactivates the changes.
EDIT 1:
I tried the proposed solution by Piotr and it seems to almost work, but something goes wrong. When I connect to that hotspot with an android 9 device it seems to work until I execute the last command ip route add default via $TUN1IP table hotspot. After issuing that, I just have just enough time to request whatismyip.com with a browser on the phone and verify that I indeed have the tun1 ip. Short time later (maybe about 15-30 s), the phone wifi settings will start saying "no internet connection" and the phone starts reconnecting in an endless loop until I undo the routing with ip route del default table hotspot
Frist I wondered if this was some kind of firewall issue as my configuration is very strict and starts with
ufw default deny incoming
ufw default deny outgoing

and then I have some rules to allow vpn connections and local addresses, then regarding the hotspot so far I settled on:
ufw allow out on tun1 to 0.0.0.0/0
ufw allow out on wlan0 to 10.57.213.1/24

Edit 2
Before issuing the final command ip route add default via $TUN1IP table hotspot I see following UFW block (via dmesg), but the connection works anyways though:

[UFW BLOCK] IN=wlan0 OUT=
  MAC=xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx SRC=10.57.213.181
  DST=10.57.213.1 LEN=28 TOS=0x00 PREC=0x00 TTL=1 ID=xxxxx DF PROTO=UDP
  SPT=45104 DPT=4886 LEN=8

Those blocks disappear after issuing the routing command, so I'm guessing they are not significant, not sure though. However if I look at non-ufw messages I see following messages on each reconnection:

netlink: 'wpa_supplicant': attribute type 213 has an invalid length.

I googled a little and some people say it's a bug related to WPA2 and that the connection will work if I disable encryption, but even if I disable encryption nothing changes. The device is still reconnecting to the hotspot in an endless loop.
I should probably also mention that I tried ip route flush cache but it changes nothing
Edit 3
wpa_cli -i wlan0 log_level DEBUG and subsequent journalctl -u wpa_supplicant -e yields (I censored PID and MAC adresses using letter x):

Mar 05 20:59:22 machineone wpa_supplicant[xxxx]: nl80211: BSS Event 59 (NL80211_CMD_FRAME) received for wlan0
Mar 05 20:59:22 machineone wpa_supplicant[xxxx]: nl80211: RX frame da=ff:ff:ff:ff:ff:ff sa=10:xx:xx:xx:xx:xx bssid=ff:ff:ff:ff:ff:ff freq=2412 ssi_signal=-70 fc=0x40 seq_ctrl=0xd740 stype=4
Mar 05 20:59:22 machineone wpa_supplicant[xxxx]: wlan0: Event RX_MGMT (19) received
Mar 05 20:59:22 machineone wpa_supplicant[xxxx]: P2P: Not a P2P probe - ignore it
Mar 05 20:59:22 machineone wpa_supplicant[xxxx]: nl80211: BSS Event 59 (NL80211_CMD_FRAME) received for wlan0
Mar 05 20:59:22 machineone wpa_supplicant[xxxx]: nl80211: RX frame da=ff:ff:ff:ff:ff:ff sa=10:xx:xx:xx:xx:xx bssid=ff:ff:ff:ff:ff:ff freq=2412 ssi_signal=-72 fc=0x40 seq_ctrl=0xd750 stype=4
Mar 05 20:59:22 machineone wpa_supplicant[xxxx]: wlan0: Event RX_MGMT (19) received
Mar 05 20:59:22 machineone wpa_supplicant[xxxx]: P2P: Not a P2P probe - ignore it
Mar 05 20:59:33 machineone wpa_supplicant[xxxx]: nl80211: BSS Event 59 (NL80211_CMD_FRAME) received for wlan0
Mar 05 20:59:33 machineone wpa_supplicant[xxxx]: nl80211: RX frame da=ff:ff:ff:ff:ff:ff sa=20:xx:xx:xx:xx:xx bssid=ff:ff:ff:ff:ff:ff freq=2412 ssi_signal=-75 fc=0x40 seq_ctrl=0x8830 stype=4
Mar 05 20:59:33 machineone wpa_supplicant[xxxx]: wlan0: Event RX_MGMT (19) received
Mar 05 20:59:33 machineone wpa_supplicant[xxxx]: P2P: Not a P2P probe - ignore it
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: nl80211: BSS Event 59 (NL80211_CMD_FRAME) received for wlan0
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: nl80211: RX frame da=ff:ff:ff:ff:ff:ff sa=10:xx:xx:xx:xx:xx bssid=ff:ff:ff:ff:ff:ff freq=2412 ssi_signal=-72 fc=0x40 seq_ctrl=0xe430 stype=4
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: wlan0: Event RX_MGMT (19) received
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: P2P: Not a P2P probe - ignore it
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: nl80211: BSS Event 59 (NL80211_CMD_FRAME) received for wlan0
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: nl80211: RX frame da=ff:ff:ff:ff:ff:ff sa=10:xx:xx:xx:xx:xx bssid=ff:ff:ff:ff:ff:ff freq=2412 ssi_signal=-70 fc=0x40 seq_ctrl=0xe450 stype=4
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: wlan0: Event RX_MGMT (19) received
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: P2P: Not a P2P probe - ignore it
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: nl80211: BSS Event 59 (NL80211_CMD_FRAME) received for wlan0
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: nl80211: RX frame da=ff:ff:ff:ff:ff:ff sa=10:xx:xx:xx:xx:xx bssid=ff:ff:ff:ff:ff:ff freq=2412 ssi_signal=-71 fc=0x40 seq_ctrl=0xe470 stype=4
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: wlan0: Event RX_MGMT (19) received
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: P2P: Not a P2P probe - ignore it
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: nl80211: BSS Event 59 (NL80211_CMD_FRAME) received for wlan0
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: nl80211: RX frame da=ff:ff:ff:ff:ff:ff sa=10:xx:xx:xx:xx:xx bssid=ff:ff:ff:ff:ff:ff freq=2412 ssi_signal=-71 fc=0x40 seq_ctrl=0xe480 stype=4
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: wlan0: Event RX_MGMT (19) received
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: P2P: Not a P2P probe - ignore it
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: nl80211: BSS Event 59 (NL80211_CMD_FRAME) received for wlan0
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: nl80211: RX frame da=ff:ff:ff:ff:ff:ff sa=10:xx:xx:xx:xx:xx bssid=ff:ff:ff:ff:ff:ff freq=2412 ssi_signal=-71 fc=0x40 seq_ctrl=0xe490 stype=4
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: wlan0: Event RX_MGMT (19) received
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: P2P: Not a P2P probe - ignore it
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: nl80211: BSS Event 59 (NL80211_CMD_FRAME) received for wlan0
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: nl80211: RX frame da=ff:ff:ff:ff:ff:ff sa=10:xx:xx:xx:xx:xx bssid=ff:ff:ff:ff:ff:ff freq=2412 ssi_signal=-71 fc=0x40 seq_ctrl=0xe4a0 stype=4
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: wlan0: Event RX_MGMT (19) received
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: P2P: Not a P2P probe - ignore it
Mar 05 20:59:41 machineone wpa_supplicant[xxxx]: Ignore Probe Request due to DS Params mismatch: chan=1 != ds.chan=2

Edit 4
After activation of tun1 my routing table looks like this
Destination       Gateway           Genmask         Flags Metric Ref    Use Iface
0.0.0.0           10.10.2.1         0.0.0.0         UG    50     0        0 tun0
0.0.0.0           10.10.3.1         0.0.0.0         UG    50     0        0 tun1
0.0.0.0           192.168.xxx.xxx   0.0.0.0         UG    100    0        0 eth0
10.10.2.0         0.0.0.0           255.255.255.0   U     50     0        0 tun0
10.10.3.0         0.0.0.0           255.255.255.0   U     50     0        0 tun1
10.57.213.1       0.0.0.0           255.255.255.0   U     600    0        0 wlan0
the.vpn.ip.tun0   192.168.xxx.xxx   255.255.255.255 UGH   100    0        0 eth0
169.254.0.0       0.0.0.0           255.255.0.0     U     1000   0        0 virbr0
the.vpn.ip.tun1   192.168.xxx.xxx   255.255.255.255 UGH   100    0        0 eth0
192.168.yyy.0     0.0.0.0           255.255.255.0   U     0      0        0 virbr0
192.168.xxx.0     0.0.0.0           255.255.255.0   U     100    0        0 eth0
192.168.xxx.xxx   0.0.0.0           255.255.255.255 UH    100    0        0 eth0

I experimented with commands such as ip route add default dev wlan0 via default dev tun1 and ip route add default dev wlp8s0 via 10.10.3.1 dev tun1 but nothing worked. Additionally, sometimes the default gateway for tun0 happens to be the same as for tun1.
edit 5
I discovered there is a bug in the linux kernel (or rather wpa2_supplicant) where the kernel is extremely strict with arguments passed to it and makes wpa2_supplicant fail. I did the following
# nmcli connection edit hotspot
set 802-11-wireless-security.pmf disable
save
[CTRL+D]

This disables Protected Management Frames (PMF) for the hotspot connection I created which is where the kernel call happens that breaks wpa_supplicant. After having done this (and route add default dev wlan0 via 10.10.3.1 dev tun1) now my whole system (not just the hotspot) is running over tun1 instead of tun0. I still need to understand why I can't make it happen that tun0 would be used for eth0 while at the same time tun1 would be used for wlan0.
After I issue the following commands
ip route add default dev wlan0 via 10.10.2.1 dev tun1 proto static metric 50
ip route add default dev eth0 via 10.10.3.1 dev tun0 proto static metric 50

My routing table looks like this:
0.0.0.0          10.10.2.1        0.0.0.0         UG    50     0        0 tun1
0.0.0.0          10.10.3.1        0.0.0.0         UG    50     0        0 tun0
0.0.0.0          192.168.xxx.xxx  0.0.0.0         UG    100    0        0 eth0
10.10.2.0        0.0.0.0          255.255.255.0   U     50     0        0 tun0
10.10.3.0        0.0.0.0          255.255.255.0   U     50     0        0 tun1
10.55.213.1      0.0.0.0          255.255.255.0   U     600    0        0 wlan0
the.vpn.ip.tun1  192.168.xxx.xxx  255.255.255.255 UGH   100    0        0 eth0
169.254.0.0      0.0.0.0          255.255.0.0     U     1000   0        0 virbr0
the.vpn.ip.tun1  192.168.xxx.xxx  255.255.255.255 UGH   100    0        0 eth0
192.168.yyy.0    0.0.0.0          255.255.255.0   U     0      0        0 virbr0
192.168.xxx.0    0.0.0.0          255.255.255.0   U     100    0        0 eth0
192.168.xxx.xxx  0.0.0.0          255.255.255.255 UH    100    0        0 eth0

which looks the same as if I never issued them
edit 6:
when I try to make the vpn connection from the terminal
sudo openvpn --config myconfigfile.ovpn --dev tun1 --verb 3

following route commands get issued and everything will go through tun1 and tun0 is ignored:
Wed Mar 11 19:16:12 2020 /sbin/ip link set dev tun1 up mtu 1500
Wed Mar 11 19:16:12 2020 /sbin/ip addr add dev tun1 10.10.2.6/24 broadcast 10.10.2.255
Wed Mar 11 19:16:12 2020 /sbin/ip route add the.vpn.ip.tun1/32 via 10.10.3.1
Wed Mar 11 19:16:12 2020 /sbin/ip route add 0.0.0.0/1 via 10.10.2.1
Wed Mar 11 19:16:12 2020 /sbin/ip route add 220.127.116.11/1 via 10.10.2.1

I also find the 10.10.3.1 ip odd since it's related to tun0.
When I do
ip route delete 0.0.0.0/1 via 10.10.2.1

all my connections return to tun0 and ignore tun1. ip route show table looks like this:
default via 10.10.3.1 dev tun0
default via 10.10.3.1 dev tun0 proto static metric 50
default via 192.168.xxx.xxx dev eth0 proto dhcp metric 100
10.10.2.0/24 dev tun1 proto kernel scope link src 10.10.2.3
10.10.3.0/24 dev tun0 proto kernel scope link src 10.10.3.4 metric 50
10.55.213.0/24 dev wlan0 proto kernel scope link src 10.55.213.1 metric 600
184.108.40.206/1 via 10.10.2.1 dev tun1
the.tun0.vpn.ip via 192.168.xxx.xxx dev eth0 proto static metric 100
169.254.0.0/16 dev virbr0 scope link metric 1000 linkdown
the.tun1.vpn.ip via 10.10.3.1 dev tun0
192.168.aaa.bbb/24 dev virbr0 proto kernel scope link src 192.168.aaa.ccc linkdown
192.168.xxx.0/24 dev eth0 proto kernel scope link src 192.168.xxx.yyy metric 100
192.168.xxx.xxx dev eth0 proto static scope link metric 100
broadcast 10.10.2.0 dev tun1 table local proto kernel scope link src 10.10.2.3
local 10.10.2.3 dev tun1 table local proto kernel scope host src 10.10.2.3
broadcast 10.10.2.255 dev tun1 table local proto kernel scope link src 10.10.2.3
broadcast 10.10.3.0 dev tun0 table local proto kernel scope link src 10.10.3.4
local 10.10.3.4 dev tun0 table local proto kernel scope host src 10.10.3.4
broadcast 10.10.3.255 dev tun0 table local proto kernel scope link src 10.10.3.4
broadcast 10.55.213.0 dev wlan0 table local proto kernel scope link src 10.55.213.1
local 10.55.213.1 dev wlan0 table local proto kernel scope host src 10.55.213.1
broadcast 10.55.213.255 dev wlan0 table local proto kernel scope link src 10.55.213.1
broadcast 127.0.0.0 dev lo table local proto kernel scope link src 127.0.0.1
local 127.0.0.0/8 dev lo table local proto kernel scope host src 127.0.0.1
local 127.0.0.1 dev lo table local proto kernel scope host src 127.0.0.1
broadcast 127.255.255.255 dev lo table local proto kernel scope link src 127.0.0.1
broadcast 192.168.aaa.bbb dev virbr0 table local proto kernel scope link src 192.168.aaa.ccc linkdown
local 192.168.aaa.ccc dev virbr0 table local proto kernel scope host src 192.168.aaa.ccc
broadcast 192.168.aaa.255 dev virbr0 table local proto kernel scope link src 192.168.aaa.ccc linkdown
broadcast 192.168.xxx.0 dev eth0 table local proto kernel scope link src 192.168.xxx.yyy
local 192.168.xxx.yyy dev eth0 table local proto kernel scope host src 192.168.xxx.yyy
broadcast 192.168.xxx.255 dev eth0 table local proto kernel scope link src 192.168.xxx.yyy

I hope I edited all those ip's correctly as in reality some ip's change each time, so I'm matching them with my previous edits.
My poor intuition told me to try next
ip route replace 10.57.213.1/24 via 10.10.2.6 dev tun1 table AirSpot

But all I get is Error: Invalid prefix for given prefix length. and I don't understand what it means. I'm just not getting something. Routing is not exactly intuitive to me. With that line I want that any packets addressed from or to 10.57.213.1/24 (which is the manually set hotspot range) are to go through 10.10.2.6, which I would think (based on the verbose output of openvpn) is where the tun1 is.
Edit 7:
I think this is some kind of default route issue, but I'm not expert enough to solve it..
Comment: What you are looking for is called [policy routing](https://www.tldp.org/HOWTO/Adv-Routing-HOWTO/lartc.rpdb.simple.html).
Comment: I'm not sure I can manage with that information and that little explanation alone. Let's say my vpn tunnel `tun1` for hotspot runs on `10.0.0.10`. Would it be `echo 200 Hotspot >> /etc/iproute2/rt_tables` , `ip rule add from 10.0.0.10 table Hotspot` , `ip route add default [?] via dev tun1 table Hotspot` and then `ip route flush cache` to activate? I also don't know what IP adress to enter where the question mark is. I'm cable connected via `eth0`, router ip range 192.168.x.x. `tun1` will run over eth0. Or is this supposed to be some kind of ip that is assigned to the hotspot?
Comment: The netlink _"error"_ is just a warning to help fix broken software, while the firewall hit is Firefox Mobile _"wifi-tickle"_, which is used to keep Androids WiFi up. Your Android device has connections problems. Enable debug logging on the `wpa_supplicant` (`wpa_cli -i wlan0 log_level DEBUG`) and add some logs to the question (`journalctl -u wpa_supplicant -e`).
Comment: Another idea I had, maybe `nmcli` screws something up. Couldn't I just use `openvpn` command directly by passing the *.ovpn file to it? Would that make any difference? I'm enabling the tun1 connection using `nmcli` right now.
Answer: The solution you posted in a comment is almost correct. What is missing is the correct IP addresses to use.
Step 1: Retrieve information
You need to retrieve two pieces of information:

The IP addresses of the subnetwork of your hotspot. By default these are a random network of the form 10.42.*.0/24, so you need to fix the addresses. The easiest way is to create a new WiFi connection called hotspot using nm-connection-editor. You need to:

set the mode to Hotspot in the "Wi-Fi" tab,
set the method to Shared with other computers in the "IPv4 Settings" tab,
choose an subnet for the network by adding on IP address (e.g. 10.57.213.1 with netmask 24) in the same tab,
add some authentication method (e.g. a PSK)

After performing these steps, you should have a well configured /etc/NetworkManager/system-connections/hotspot.nmconnection file with a content like:
[wifi]
mode=ap

[ipv4]
address1=10.57.213.1/24
method=shared

and you can start the connection with nmcli connection up id hotspot.
The IP address of the VPN gateway. Whether this is fixed or variable depends on what kind of VPN you are using. Let's say it's 10.10.10.1.

Step 2: Configure policy routing

A one-time operation. We need an additional routing table. In order to be able to refer to it by name let's add:
200 hotspot

to /etc/iproute2/rt_tables.
Once per system boot. We need to tell  the kernel, that packets originating from 10.57.213.0/24 should use the hotspot table:
ip rule add from 10.57.213.0/24 table hotspot

Every time we connect to a VPN, we need to add a default route for the HotSpot addresses:
ip route replace default via 10.10.3.1 dev tun1 table hotspot

where 10.10.3.1 is the address of the other side of your VPN tunnel according to the routing table.
You can run this part in a NetworkManager dispatcher script, in which case the gateway address will be in the environment variable $IP4_GATEWAY.

Edit: To automatically establish the default route for the hotspot table add a dispatcher script /etc/NetworkManager/dispatcher.d/hotspot.sh like this:
#!/bin/bash
# Be verbose until you test this
set -ex

# First parameter passed by NM: interface
DEVICE="$1"
# Second parameter: action
CMD="$2"
IP=/bin/ip

# Delete the part after '/' from $IP4_ADDRESS_0
LOCAL_IP=${IP4_ADDRESS_0%/*}
if [ "$LOCAL_IP" != "" ]; then
  # Add a 'src' option to the route only if the IP is not empty
  SRC="src $LOCAL_IP"
fi

if [ "$CMD" = "vpn-up" ]; then
  $IP route replace default via $IP4_GATEWAY dev $DEVICE $SRC table hotspot
fi

I didn't test this.
Comment: I tried it and it seems to almost work, but something goes wrong. When I connect to that hotspot with an android 9 device it seems to work until I execute the last command `ip route add default via $TUN1IP table hotspot`. After issuing that, I just have just enough time to request whatismyip.com with a browser on the phone and verify that I have the `tun1` ip. Shortly after that (about 30 s maybe), the phone wifi settings will start saying "no connection" and the phone starts reconnecting in an endless loop until i undo the routing with `ip route del default table hotspot`
Comment: What are you using as `$TUN1IP`? It should be the (private) IP address of the remote peer (`ip addr` shows it as `peer`), not the IP address of the `tun1` interface.
Comment: oh, i see... I use the local tun1 address `10.x.x.x` of the `tun1` interface with this very (very) ugly expression: `TUN1IP=$(ifconfig | grep -A 2 "tun1" | grep inet | grep -o -E -e "inet(\s)*[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+"| grep -o -E -e "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+")` Do you mean I should use the external vpn ip address that `tun1` connects to and not its `10.x.x.x` address? I'll try that and come back here..
Comment: You should probably forget the deprecated `ifconfig` and use [iproute2](https://en.wikipedia.org/wiki/Iproute2) instead. Also, if you use a **NetworkManager** script as in the edited question, you have the local and gateway IP addresses served on a plate (in the `IP4_ADDRESS_0` and `IP4_GATEWAY` variables).
Comment: `ip route add default via $REMOTEVPNIP table hotspot` where `$REMOTEVPNIP` is just a string with manually set IP address of the remote VPN server that `tun1` connects to yields `Error: Nexthop has invalid gateway.` When defining the connection using `nm-connection-editor` I didn't set any gateway. Is that maybe an issue? Is that where I'm supposed to enter the `10.x.x.x` `tun1` address? Is that that what `IP4_GATEWAY` is supposed to be? I didn't want to use the dispatcher script right away as I felt, it requires additional study how to use it.
Comment: You need to use the private address of the VPN server. Basically `ip addr dev tun1` will give you a line `inet 10.210.77.17 peer 10.210.77.1/32 scope global tun1`: `10.210.77.17` is the address on your `tun1` interface, while `10.210.77.1` is the address of the other side of the tunnel. You need to use the latter.
Comment: In the output of `ip address` the word `peer` is nowhere to be seen. instead it says `brd` under tun1: `inet 10.x.x.x/xx brd 10.x.x.y scope global noprefixroute tun1` I'll try the brd address just in case..
Comment: `brd` is the broadcast address. You don't mention what kind of VPN you are using, so it's hard to guess how routing is configured, but the VPN software certainly configures some route: check `ip route` and look for `via 10.x.x.z`.
Comment: the via address for tun1 is the same as for tun0. Is that normal? `default via 10.x.x.a dev tun0 proto static metric 50
default via 10.x.x.a dev tun1 proto static metric 50
10.x.x.b/24 dev tun0 proto kernel scope link src 10.x.x.c metric 50
10.x.x.b/24 dev tun1 proto kernel scope link src 10.x.x.d metric 50` About the provider: Is it possible to send private messages here? Generally I use openvpn with *.ovpn files. The provider offers a client as well but I don't want to use it.
Comment: No, it isn't, but people lack imagination and out of 65536 possible values for `x.x` they always choose `0.0` or similar. If you use your VPN only to access the Internet, you shouldn't have too many problems.
Comment: Well, I don't want to disclose unnecessary details so the whole internet would know my security setup ;) I tried `ip route add default via 10.x.x.x table hotspot` with all possible ip's (doing `ip route del ..` between) that I could come up with and none of them worked. It seems the default is always the first vpn connection activated via `nmcli` and it is somehow forced for the hotspot. I wonder if I need to change other settings of the `tun1` connection. Basically I just edited it by replacing `tun` with `tun1` in advanced settings. Maybe I need make manual IPv4 settings for `tun1`?
Comment: Routing your packets through half the world so that they enter the Internet from another IP address is not security. Besides the addresses in the `10.0.0.0/8` network are private addresses, they are not unique and disclosing them has no impact. You should [learn more about Linux networking](https://opensource.com/business/16/8/introduction-linux-network-routing) to understand why two default routes are a bad idea.
Comment: I read the article, but I may need to read more. I think I got a rough idea already, but I still don't understand enough to solve it. I added my routing table to my question now. I thought that `ip route add default dev wlan0 via default dev tun1` would work, but it didn't. The routing table is form before I issued that command.
Comment: Yes, you should read other articles about basic networking. From what you posted, `10.10.3.1` is the gateway at the other end of the VPN tunnel (so `via 10.10.3.1`). Besides that `192.168.0.0/16` is another range of addresses for private use, masking them is not necessary (cf. [Wikipedia](https://en.wikipedia.org/wiki/Reserved_IP_addresses).
Comment: when I issue `ip route add default dev wlp8s0 via 10.10.3.1 dev tun1` all my 'tun1' and `tun0` traffic completely stops. `dmesg` shows `ufw` only blocks connections from `192.168.xxx.xxx` to `220.127.116.11` and from `192.168.xxx.xxx` to `192.168.xxx.yyy` which as far I understand it, should be irrelevant.
I'm more concerned about `netlink: 'wpa_supplicant': attribute type 213 has an invalid length`. Those only appear when I do  the `ip route add ...` command. I still don't understand where this is coming from. When doing `journalctl -u wpa_supplicant -e` should I look for smething specific there?
Comment: I solved the problem where my traffic stopped, it was an issue with `wpa_supplicant` and kernel, however I still can't get the correct interface to use the correct tunnel (see my edit)
Comment: The key element of the solution is to use another routing table (called `hotspot`) for traffic coming from the AP. You need to issue `ip route replace default via 10.10.3.1 dev tun1 table hotspot`. As far as I remember `ifconfig` only shows the `main` table (it is considered deprecated anyway), so check with `ip route show table hotspot` or `ip route show table all`.
Comment: I included the output of `ip route show table all` after starting `tun1` via openvpn in terminal and just after `ip route delete 0.0.0.0/1 via 10.10.2.1`. I'm assuming it's at that state where I have to issue the elusive routing command that is supposed to make my hotspot traffic go through `tun1` while everything else goes through `tun0`. I wouldn't have thought that something so simple could be so complicated to do :(
Comment: You don't need to touch your **main** routing table, just that called `AirSpot` in your question. Since your table is empty (`ip route show table AirSpot` gives you an empty output) you just need to add a default route `ip route add default via 10.10.3.1 dev tun1 table AirSpot` and check that the `ip rule` you added is still there `ip rule`.


a counterexample in Muckenhoupt $A_1$ class.

Question: We say $w$: $\mathbb R^N\to[0,+\infty)$ belons to Muckenhoupt $A_1$ class if there is a constant $C$ such that
$$
\frac{1}{|B|}\int_{B(y)}w(x)dx\leq Cw(y)
$$
for all $y\in \mathbb R^N$ and all balls $B(y)$.
Now given a finite Radon measure $\nu$, I want to construct a strictly positive function $w\in A_1$ but $w\notin L^1(d\nu)$. By $L^1(d\nu)$ I mean function $u$ such that
$$
\int_{\mathbb R^N}|u|\,d\nu<\infty.
$$
I don't have a good idea on how to get started... Since I only need an example, it is ok to explicitly write down a Radon measure $\nu$ if it makes the construction of example easier.
Thank you very much!
PS: Thanks @tryss for a nice and clear example. I also think would it be possible to prove that for every $\nu\in \mathcal M$, we can prove that there exists a $w$ as described in above question. Here $\mathcal M$ denotes the space of finite Radon measure.
Comment: You mean Radon measure I suppose?
Comment: @Tryss Yea of course! Fixed. Thanks for pointing out.
Answer: As you only want an exemple, take
$$\int_{\mathbb{R}} u d\nu = \int_0^{\infty} u(x) e^{-x} dx $$
Now take $u(x) = e^x$
$u$ is clearly not in $L^1(d\nu)$
Now for $0 < d < y$
$$\frac{1}{e^{-(y-d)}-e^{-(y+d)}}  \int_{y-d}^{y+d} 1 dx = \frac{2d}{e^{-(y-d)}-e^{-(y+d)}} = e^{y} \frac{2d}{e^d-e^{-d}}$$
And the function $d \mapsto \frac{2d}{e^d-e^{-d}}$ is bounded on $[0,+\infty[$, so you've got the result
Comment: Thank you! This is great. I actually thinking would it be possible to prove that for any $nu\in \mathcal M$, what about the existence of such $w$. It looks interesting, although I don't need it for now...


Is there a nonnormal operator with spectrum strictly continuous?

Question: Let $H$ be an infinite dimensional separable Hilbert space.
Definition : An operator $A \in B(H)$ is normal if $AA^{*} = A^{*}A$.
Definition : The spectrum $\sigma(A)$ of $A \in B(H)$, is the set of all $\lambda \in \mathbb{C}$ such that $A - \lambda I$ is not bijective.
It decomposes as follows:
 - Point spectrum: $\sigma_{p}(A) = \{\lambda \in \mathbb{C} : A - \lambda I \text{ not injective}   \}$
 - Continuous spectrum: $\sigma_{c}(A) = \{\lambda \in \mathbb{C} : A - \lambda I \ \text{ injective with a dense nonclosed range}   \}$
 - Residual spectrum: $\sigma_{r}(A) = \{\lambda \in \mathbb{C} : A - \lambda I \ \text{ injective with a nondense range}   \}$
Examples:

Let $S$ be the bilateral shift defined on $H = l^{2}(\mathbb{Z})$ by $S.e_{n} = e_{n+1} $.
Its spectrum is strictly continuous :   $\sigma(S) = \sigma_{c}(S) = \mathbb{S}^{1}$.
It's also a unitary operator ($SS^{*} = S^{*}S = I$), so a fortiori a normal operator.
Let $T$ be the unilateral shift defined on $H = l^{2}(\mathbb{N})$ by $T.e_{n} = e_{n+1} $.
Its spectrum is not strictly continuous because $0 \in \sigma_{r}(T)$.
It's a nonnormal operator because $[T^{*},T].e_{0} = e_{0}$.

Is there a nonnormal operator with spectrum strictly continuous ?

Bonus questions : Can we exclude the compact operators ? How classify these operators ?
Answer: Lets try the Volterra operator $(Vf)(t)=\int_0^tf(x)dx$ on $H=L^2[0,1].$ It is quasinilpotent (i.e. spectral radius is 0) so $\sigma(V)=\{0\}.$ Its range contains the set $\{f\in C^1[0,1]\mid f(0)=0\}$ which is dense. (To see this, note that $B=\{\sin\pi kx,\ k\in\mathbb N\}$ is an orthogonal base in $L^2[0,1].$) It means that $0$ belongs to continuous spectrum.
Comment: The set $\{f \in C^1[0,1]: f(0) = 0\}$ is still dense in $L^2[0,1]$, even the continuous compactly supported functions are dense.
Comment: **Ok, you are right !** Here is a more *conventional* approach: let $1$, $s_{n} = sin(2\pi nx)$ and $c_{n} = cos(2\pi nx)$ (with $n \in \mathbb{N}^{*}$) be an orthonormal basis of $H = L^{2}[0,1]$. Then $V.c_{n} = s_{n}/2\pi n$, $V.s_{n} = (1-c_{n})/2\pi n$ and $V.1 = x= 1/2 + \sum s_{n}/2\pi n$. Now $2V.(1-c_{1}-...-c_{r}) \to 1$. So $1 \in \overline{Im(V)}$, and finally $V$ is dense range.


How to sort month name in union query

Question: I have two query. query 1 dislay table by month name. Query two display table by workingweek. I union the two table but the problem is table 1 display not in correct order for month name.
I want to display like this:
October
November
WW52

SELECT Month, InputQuantity, ShippingQuantity FROM
(
   SELECT DATENAME(MONTH, dbo.SBR.SBR_DateCreated) AS Month,
   SUM(dbo.SBR.SBR_Quantity) AS InputQuantity,
   SUM(dbo.SBR.SBR_ShippingQuantity) AS ShippingQuantity
   FROM dbo.SBR WHERE DATENAME(MONTH, SBR_DateCreated) <> DATENAME(MONTH, GETDATE())
   GROUP BY DATENAME(MONTH, dbo.SBR.SBR_DateCreated)
UNION
   SELECT dbo.SBR.SBR_WorkingWeek AS Month,
   SUM(dbo.SBR.SBR_Quantity) AS InputQuantity,
   SUM(dbo.SBR.SBR_ShippingQuantity) AS ShippingQuantity
   FROM dbo.SBR
  INNER JOIN dbo.WorkingWeek
    ON dbo.SBR.SBR_WorkingWeek=dbo.WorkingWeek.WorkingWeek
  WHERE (dbo.WorkingWeek.DateFrom < GETDATE()
  AND dbo.WorkingWeek.DateTo > GETDATE())
  GROUP BY dbo.SBR.SBR_WorkingWeek
) AS UWAIS

And Current OUTPUT:

Month       InputQuantity   ShippingQuantity
November         12                12
October          12                12
WW52             13                10

Answer: Put ORDER BY SBR_DateCreated in the first subquery.
SELECT Month, InputQuantity, ShippingQuantity FROM
(
SELECT DATENAME(MONTH, dbo.SBR.SBR_DateCreated) AS Month, SUM(dbo.SBR.SBR_Quantity) AS InputQuantity, SUM(dbo.SBR.SBR_ShippingQuantity) AS ShippingQuantity FROM dbo.SBR WHERE DATENAME(MONTH, SBR_DateCreated) <> DATENAME(MONTH, GETDATE())
GROUP BY DATENAME(MONTH, dbo.SBR.SBR_DateCreated)
ORDER BY dbo.SBR.SBR_DateCreated
UNION
SELECT dbo.SBR.SBR_WorkingWeek AS Month, SUM(dbo.SBR.SBR_Quantity) AS InputQuantity, SUM(dbo.SBR.SBR_ShippingQuantity) AS ShippingQuantity
FROM dbo.SBR
INNER JOIN dbo.WorkingWeek ON dbo.SBR.SBR_WorkingWeek=dbo.WorkingWeek.WorkingWeek
WHERE (dbo.WorkingWeek.DateFrom < GETDATE() AND dbo.WorkingWeek.DateTo > GETDATE())
GROUP BY dbo.SBR.SBR_WorkingWeek

) AS UWAIS

Answer: I would add an additional column to each of the subqueries to represent one of the dates during the month.  This can then be used for order by.
SELECT Month, InputQuantity, ShippingQuantity
FROM (SELECT DATENAME(MONTH, s.SBR_DateCreated) AS Month,
             SUM(s.SBR_Quantity) AS InputQuantity, SUM(s.SBR_ShippingQuantity) AS ShippingQuantity,
             MIN(s.SBR_DateCreated) as mindc
      FROM dbo.SBR s
      WHERE DATENAME(MONTH, SBR_DateCreated) <> DATENAME(MONTH, GETDATE())
      GROUP BY DATENAME(MONTH,s.SBR_DateCreated)
      UNION ALL
      SELECT s.SBR_WorkingWeek AS Month, SUM(s.SBR_Quantity) AS InputQuantity,
             SUM(s.SBR_ShippingQuantity) AS ShippingQuantity,
             MIN(ww.<datecol>)
      FROM dbo.SBR s INNER JOIN
           dbo.WorkingWeek ww
           ON s.SBR_WorkingWeek = ww.WorkingWeek
      WHERE (ww.DateFrom < GETDATE() AND ww.DateTo > GETDATE())
      GROUP BY s.SBR_WorkingWeek
     ) UWAIS
ORDER BY mindc;

Unfortunately, I don't know which column to use for the second subquery.  But there is probably an appropriate date in one of the tables.
In addition:

I changed the union to union all.  There is no reason to incur the overhead of removing duplicates.
I added able aliases so the query is easier to read.

How to sort month name in union query


Encoding of categorical variables with high cardinality

Question: For unsupervised anomaly detection / fraud analytics on credit card data (where I don't have labeled fraudulent cases), there are a lot of variables to consider. The data is of mixed type with continuous/numerical variables (e.g. USD amount spent) as well as categorical variables (e.g. account number).
What is the most suitable way of including categorical variables that have a very large number of unique classes? My thoughts so far:

Label Encoding (scikit-learn): i.e. mapping integers to classes. While it returns a nice single encoded feature column, it imposes a false sense of ordinal relationship (e.g. 135 > 72).
One Hot / Dummy Encoding (scikit-learn): i.e. expanding the categorical feature into lots of dummy columns taking values in {0,1}. This is infeasible for categorical features having e.g. >10,000 unique values. I understand that models will struggle with the sparse and large data.

What other (more advanced?) suitable methods are there to include large categorical feature columns? Is it possible to still use One Hot Encoding with some tricks? I read about bin counting (Microsoft blog) though I haven't found any applications related to intrusion detection / fraud analytics.
P.S.: In my view, this problem seems very similar to encoding an IP-address feature column when dealing with unsupervised intrusion detection.
Comment: as @zhubarb mentioned, why would you even want to use account number as a feature? maybe if you explain that then the apporpriate encoding will become more obvious
Comment: See the good advice in https://stats.stackexchange.com/questions/146907/principled-way-of-collapsing-categorical-variables-with-many-levels
Comment: linear models have no problems with sparse data (nb bag of words models, where the words/ bigrams/trigrams are definitely in the 1000's) basically you just needs a model that supports sparse data (eg glmnet, vowpalwabbit etc). I have found sklearn is not so good for handling sparse data (  memory hungry).  vowpalwabbit does hash coding, but this is effectively one hot coding after hashing ( so you will typically have 10000 unique values after hashing too).  I have used (python-glmnet) with a dataset of (548823, 45544)  - which took 2 hours.  [dummy variables and their interactions etc]
Comment: If you are dealing with categorical sensitive data, you might want to consider the fairness implications https://dl.acm.org/doi/fullHtml/10.1145/3600211.3604657 I heard authors are super nice to reach out
Answer: This link provides a very good summary and should be helpful. As you allude to, label-encoding should not be used for nominal variables at it introduces an artificial ordinality. Hashing is a potential alternative that is particularity suitable for features that have high cardinality.
You can also use a distributed representation, which has become very popular in the deep learning community. The most common example given for distributed representation is word embeddings in NLP. That is not to say you cannot utilise them in encoding other categorical features. Here is an example.
Finally, account number would not be a wise input as it is more a unique identifier rather than a generalisable (account) feature.
Comment: By distributed representation you mean just learn embedding vector for each row and connect them with FC layers, correct?
Answer: This might help Quantile Encoder: Tackling High Cardinality Categorical Features in Regression Problems: https://link.springer.com/chapter/10.1007%2F978-3-030-85529-1_14

The most well-known encoding for categorical features with low cardinality
is One Hot Encoding [1]. This produces orthogonal and equidistant vectors for
each category. However, when dealing with high cardinality categorical features,
one hot encoding suffers from several shortcomings [20]: (a) the dimension of
the input space increases with the cardinality of the encoded variable, (b) the
created features are sparse - in many cases, most of the encoded vectors hardly
appear in the data -, and (c) One Hot Encoding does not handle new and unseen
categories.

An alternative encoding technique is Label/Ordinal Encoding [3] which uses
a single column of integers to represent the different categorical values. These
are assumed to have no true order and integers are selected at random. This
encoding handles the problem of the high dimensional encoding found in One
Hot Encoding but imposes an artificial order of the categories. This makes it
harder for the model to extract meaningful information. For example, when
using a linear model, this effect prevents the algorithm from assigning a high
coefficient to this feature.

Alternatively, Target Encoding (or mean encoding) [15] works as an effective
solution to overcome the issue of high cardinality. In target encoding, categorical features are replaced with the mean target value of each respective category.
With this technique, the high cardinality problem is handled and categories are
ordered allowing for easy extraction of the information and model simplification.
The main drawback of Target Encoding appears when categories with few (even
only one) samples are replaced by values close to the desired target. This biases
the model to over-trust the target encoded feature and makes it prone to overfitting.

It is not your exact case but the introduction has a bit of lit review that can be helpful and the pitfalls of some of this techniques.
Also, in arxiv https://arxiv.org/abs/2105.13783
Answer: Zhubarb had a very nice answer. I just want to provide more details on embedding and hashing and add one common approach binning.
Starting with the binning, this is a very common approach used in many fields, the key idea is many data follows 80-20 rules, that even we have a feature with many values but most of the data will concentred in few values. One simple example is nationality. There are many nations in the world, but if we want to build a statistical model using nationality, we will not use / encoding all of them (there are many reasons behind this, but generally, we may have overfitting if we use all of them). Instead we will pick top nationalities, and bin others int Others category. Note that this approach is also widely used in Deep Learning, where a word will have OOV(out of vocabulary) label when it is in Other category. This is an interesting paper to read: How Large a Vocabulary Does Text Classification Need?, In this paper, the largest vocabulary size is 60K.
Embedding is a very nice idea from Deep Learning and NLP. Suppose we are building a model that vocabulary size is 60K, we do not want to do one hot embedding because the vector is very sparse and the distance between vectors are not meaningful. For example, if we encode the word cat into [0,0,....,1,0,0], a lot of space will be wasted (in real word if we use sparse vector instead of dense vector to store the data, it will still be OK, but sparse vector have its own computational challenges.). And the distance between the word "cat" and say "dog", will as same as the distance between cat and say "keyboard".
Embedding uses dense vector to do the encoding, and the general idea is the distance between the dense vectors will have meanings. For example, the distance between "cat" and "dog", will be much smaller than the distance between "cat" and "keyboard".
Hashing is another interesting idea, an example can be found in sklearn documentation here. The idea is we use hash functions to produce a fixed number of features. This approach will apply a hash function to the features to determine their column index in data / design matrices directly. The result is increased speed and reduced memory usage, at the expense of inspectability; the hasher does not remember what the input features looked like and has no inverse_transform method. In addition, there will be collisions if we set number of the output features small. (for example, the this trick make not be able to differentiate the word "cat" and "keyboard" as both of them mapped into same column index.)
Answer: This Medium article I wrote might help as well: 4 ways to encode categorical features with high cardinality. It explores four encoding methods applied to a dataset with 26 categorical features with cardinalities up to 40k (includes code):
Target encoding

PROS: parameter free; no increase in feature space
CONS: risk of target leakage (target leakage means using some information from target to predict the target itself); when categories have few samples, the target encoder would replace them by values very close to the target which makes the model prone to overfitting the training set; does not accept new values in testing set

Count encoding

PROS: easy to understand and implement; parameter free; no increase in feature space
CONS: risk of information loss when collision happens; can be too simplistic (the only information we keep from the categorical features is their frequency); does not accept new values in testing set

Feature hashing

PROS: limited increase of feature space (as compared to one hot encoding); does not grow in size and accepts new values during inference as it does not maintain a dictionary of observed categories; captures interactions between features when feature hashing is applied on all categorical features combined to create a single hash
CONS: need to tune the parameter of hashing space dimension; risk of collision when the dimension of hashing space is not big enough

Embedding

PROS: limited increase of feature space (as compared to one hot encoding); accepts new values during inference; captures interactions between features and learns the similarities between categories
CONS: need to tune the parameter of embedding size; the embeddings and a logistic regression model cannot be trained synergically in one phase, since logistic regression do not train with backpropagation. Rather, embeddings has to be trained in an initial phase, and then used as static inputs to the decision forest model.


Solving $-\left(\frac{5}{x-1}\right)=\frac{1}{2}$

Question: I am not familiar with equations, here I am trying to find the value of $x$ in this equation so, what should I do?
$$-\bigg(\dfrac{5}{x-1}\bigg)=\dfrac{1}{2}$$
Comment: Hint: $x-1=-10$
Answer: Even though other answers are already posted, I just want to remind you that since you want to find $x$, your priority should be leaving it alone. Step by step, it is like this:
$$-\dfrac{5}{x-1}=\dfrac{1}{2}$$
$$-5 =\dfrac{x-1}{2}$$
$$-10=x-1$$
$$-9=x$$
Answer: $-\bigg(\dfrac{5}{x-1}\bigg)=\dfrac{1}{2}$
Multiply both sides by -$1$
$\bigg(\dfrac{5}{x-1}\bigg)=-\dfrac{1}{2}$
Cross multiply-
$x-1=-10$
$x=-10+1$
$x=-9$
there's your answer.
Try doing these on your own, these should be very easy for you.
Good luck.
Answer: Multiply both sides of the equation by $-2(x-1)$ to obtain a more trivial equation.
Answer: Though this is not the recommended way to go, you can solve it "by inspection".
For the two members to be equal, you need the denominator of the left fraction to be the double of $5$ with a negative sign. Hence $x-1=-10$, or $x=-9$.

A more orthodoxical way is by reducing the two fractions to the same denominator $2(x-1)$, noting that $x-1=0$ is not allowed. You get
$$-\frac{10}{2(x-1)}=\frac{x-1}{2(x-1)}.$$  and you are nearly done.
Answer: -(5/X-1) = 1/2
Taking reciprocal and changing signs , (X-1)/5 = -2
$X-1 = -10$ => $X = -9$


Creating Policy for SAML's IAM role

Question: I'm trying to create a policy for an IAM role for my federated users (authenticating through my SAML provider). I'm following Creating a Role for SAML 2.0 Federation (Console) - AWS Identity and Access Management:
<code>{
    "Version": "2012-10-17",
    "Statement": {
      "Effect": "Allow",
      "Action": "sts:AssumeRoleWithSAML",
      "Principal": {"Federated": "arn:aws:iam::ACCOUNT-ID-WITHOUT-HYPHENS:saml-provider/PROVIDER-NAME"},
      "Condition": {"StringEquals": {"SAML:aud": "https://signin.aws.amazon.com/saml"}}
    }
  }
</code>
But I get following error:
<code>This policy contains the following error: Has prohibited field Principal For more information about the IAM policy grammar, see AWS IAM Policies
</code>
I tried to Google it but no success. The answer on AWS Trust Policy Has prohibited field Principal - Stack Overflow wasn't helpful either. Can someone tell me how can I create policy and role for my SAML provider?
Comment: Can you describe exactly where you are putting this policy, or the exact steps you took? It appears that there are two policies required — a trust policy and a permissions policy.
Comment: Did you change "ACCOUNT-ID-WITHOUT-HYPHENS" to your account number, and "PROVIDER-NAME" to your SAML provider?
Comment: Problem solved. explained it in another post
Answer: Problem solved. The documentation is old and misleading. If you create a role for SAML provider via IAM Console, automatically it has trust relationship built in there. So, just permissions need to be added.
Answer: There is an error in the policy.
You are missing [] in the statement.
The correct Policy will be:
<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Federated": "<COPY & PASTE SAML ARN VALUE HERE>"
      },
      "Action": "sts:AssumeRoleWithSAML",
      "Condition": {
        "StringEquals": {
          "SAML:aud": "https://signin.aws.amazon.com/saml"
        }
      }
    }
  ]
}
</code>
Try this one

Creating Policy for SAML's IAM role


Garbage collection and cgo

Question: Is it possible to make the garbage collector in Go handle and release memory allocated through C code? I apologize, I haven't used C and cgo before so my examples may need some clarification.
Lets say you've got some C library that you'd like to use and this library allocates some memory that needs to be freed manually. What I'd like to do is something like this:
package stuff

/*
#include <stuff.h>
*/
import "C"

type Stuff C.Stuff

func NewStuff() *Stuff {
    stuff := Stuff(C.NewStuff()) // Allocate memory

    // define the release function for the runtime to call
    // when this object has no references to it (to release memory)
    // In this case it's stuff.Free()

    return stuff

}

func (s Stuff) Free() {
    C.Free(C.Stuff(s)) // Release memory
}

Is there any way for the garbage collector to call Stuff.Free() when there are no references to *Stuff in the Go runtime?
Am I making sense here?
Perhaps a more direct question is: Is it possible to make the runtime automatically handle the cleanup of C allocated memory by writing a function that the runtime calls when there are zero references to that object?
Answer: There exists the runtime.SetFinalizer function, but it cannot be used on any object allocated by C code.
However, you can create a Go object for each C object that needs to be freed automatically:
type Stuff struct {
    cStuff *C.Stuff
}

func NewStuff() *Stuff {
    s := &Stuff{C.NewStuff()}
    runtime.SetFinalizer(s, (*Stuff).Free)
    return s
}

func (s *Stuff) Free() {
    C.Free(s.cStuff)
}

Garbage collection and cgo