Object Oriented Approach for a simple game

Question:
I am working on building a simplified version of this game. The problem states that you can have a computer that is smart or stupid but i have decided that to exclude that feature for now and decided to only go with a computer that picks a random amount of objects. I posted a question earlier and worked on it. (https://softwareengineering.stackexchange.com/questions/244680/object-oriented-design-of-a-small-java-game/244683#244683)
So initially i only had designed one class. But now i have designed 3 classes as stated by the problem. I have a pile class , a player class and a game class (also my main class).
I have so far coded the Pile and Player class. I started coding the Game class aswell however i am stuck now as i dont know how to make the game class interact with the Player and Pile class. I basically determine who's turn it is first and then rotate turns till the pile of objects is complete and declare a winner...I don't know how to make the different classes interact with each other . SO i would highly appreciate if someone can guide me further and help me finish this simple game.
I sincerely apologize if i have asked a bad question. This is my first such program i am doing in java dealing with multiple classes so it is a little confusing. I do not want anyone write code but even mentioning or telling me i should make so and so methods etc will be great !
HERE IS THE CODE I HAVE SO FAR.
PILE CLASS
package Nim;

import java.util.Random;

public class Pile {

    private int initialSize;

    public Pile() {

    }

    Random rand = new Random();

    public void setPile() {

        initialSize = (rand.nextInt(100 - 10) + 10);
    }

    public void reducePile(int x) {

        initialSize = initialSize - x;

    }

    public int getPile() {

        return initialSize;
    }

    public boolean hasStick() {

        if (initialSize > 0) {

            return true;
        }

        else {
            return false;
        }
    }

}

PLAYER CLASS
package Nim;

import java.util.Scanner;
import java.util.Random;

public class Player {

    public static final int HUMAN = 0;
    public static final int COMPUTER = 1;
    private int type;

    public Player(int theType) {

        type = theType;

    }

    Scanner in = new Scanner(System.in);

    // n is number of marbles left in the pile

    public int makeMove(int n) {

        int max = n / 2;
        int grab;

        if (type == HUMAN) {

            System.out.println("There are " + n
                    + " marbles in total. However you can only"
                    + "grab no more than " + max + " marbles");
            System.out.println("Please Enter the number of marbles to grab: ");
            grab = in.nextInt();

            while (grab > max || grab < 0) {

                System.out.println("You have entered a illelgal value. Please enter a legal value: ");
                grab = in.nextInt();

            }

            return grab;

        }

        else {
            Random rand = new Random();

            grab = (rand.nextInt(n / 2 - 1) + 1);

            System.out.println("Computer has grabbed: " + grab + " marbles");

            return grab;

        }
    }

    public void updateTurn(int n) {

        type = n;

    }

}

GAME CLASS (in progress)
package Nim;

import java.util.Scanner;
import java.util.Random;

public class Game {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        Random rand = new Random();

        System.out.println(welcome());

        Pile marbles = new Pile();
        Player human = new Player(Player.HUMAN);
        Player computer = new Player(Player.COMPUTER);
        marbles.setPile();

        System.out.println("There are total: " + marbles.getPile()
                + " marbles in the Pile.");
        System.out.println("Time for a toin coss to see who goes first!");

        System.out.println("Please Select heads(0) or Tails(1): ");
        int choice = in.nextInt();

        int tossResult = rand.nextInt(2);

        boolean playerTurn = false;
        boolean computerTurn = false;

        if (choice == tossResult) {
            System.out.println("You have won the Coin Toss! You will go first!");

            human.updateTurn(0);
            playerTurn = true;

        }

        else {
            System.out.println("Computer has won the coin toss! Computer will go first");

            computer.updateTurn(1);
            computerTurn = true;
        }

        while (marbles.getPile() > 0 && marbles.hasStick()) {

            while (playerTurn) {

                int removeMarbles = human.makeMove(marbles.getPile());

                marbles.reducePile(removeMarbles);
                computerTurn = true;
                playerTurn = false;
            }

            while (computerTurn) {
                int removeMarbles = computer.makeMove(marbles.getPile());
                marbles.reducePile(removeMarbles);

                playerTurn = true;
                computerTurn = false;

            }

        }

    }

    private static String welcome() {

        return "Welcome to the Game of Nim";

    }

}

Comment: Nice formatting! Also, I'm composing an answer now, people who come here for genuine help are the people that deserve an answer :)
Comment: Why are you double-spacing your code?
Comment: I would suggest for one make sure your code is formatted properly. Don't double space it, and make all your indentation and line breaks are consistant.
Comment: I always appreciate comments from you highly reputed developers it will help me become a better developer my self :)
Comment: Sorry i have a bad habbit. I am still in process of learning what we call " good coding practices " so i apologize for any such errors.
@JonathonReinhart i would highly appreciate it if you can make suggestions as i can see your quite experienced developer.
Comment: Thank you for suggestion @AnubianNoob is there some tool you use to that or do you do it manually?
Comment: If you use an IDE like Netbeans or Eclipse (Netbeans is a lot easier to use out of the box) there's an autoformat option. Alt-Shift-F by default in Netbeans. Also, this is a good question but because of the format difficult to answer...
Comment: Thanks i will try to fix this. and if possible @AnubianNoob if you can attempt to help me it would be great. i am just looking for help with thinking process as i really want to start thinking like a object oriented programer and get comfortable with making programs with multiple classes that interact with each other.
Comment: This is really not a good place to use OOP, but I can help you... Right now I'm kinda busy, but I'll try...
Comment: Sure help me at your convince @AnubianNoob
Comment: Code is formatted, got rid of spaces as suggested.
Answer: So I'm going to take a step back and look at your class diagram.
You have three classes: Pile, Player, and Game. Pile can represent the pile at the center. Game can be the class with the main method that manages everything. And Player? Well, since you're having one Player class for all three (or two) possible states (Human, Dumb, and Smart) it should be pretty easy to implement.
Let's start with Game. It need to contain two instances of Player (human and computer), and an instance of Pile. It also needs to have a loop that goes until the game is over. So let's start to come up with a basic implementation:
Starting with Pile:
private int size;

public Pile(int newSize) {
    size = newSize;
}

public boolean takeMarbles(int amount) {
    size -= amount;
    if (size < 1)
        return false;
    return true;
}

The constructor is pretty self explanatory. The takeMarbles method is returning false if the player lost, and true if they're still in the game.
Now on to Player:
public static final int HUMAN = 0;
public static final int COMPUTER = 1;

private int type;

public Player(int type) {
    this.type = type;
}

Those two static fields may seem a little out of place, but it will come together in a second. On to the Game class:
Pile pile = new Pile(size);
Player human = new Player(Player.HUMAN);
Player computer = new Player(Player.COMPUTER);

Now we have a pile with a certain size, and two players that differ by type. This is how we're using the classes.
Now we need to get the main game loop working. Basically, just add an update() method to Player that depends on it's type (ie prompts for input if player, randomly decides if computer). The update method should return the amount of marbles to take. Then create a loop in the main method in Game. The loop will call update of the player and the computer repeatedly until someone loses (takeMarbles returns false). Then it will break out of the loop and print the output.
This is the basic idea, good luck and feel free to ask more questions!
Comment: @user2733436 Feel free, glad I could help! Nice to see people who don't post "give me code pls" questions and are genuinely interested and motivated :)
Comment: Hey, Thanks for the clarification i am trying to absorb your answer and finish coding mine. So from what i see my pile and player class seem to have right approach and i will now have to work on creating a update method in game class that alternates turns between two players and takes their input until pile is empty. I might have a question or two so i will ask you when i get stuck . thanks again
Comment: Hey, i just had question regarding the update method to the player class. So in my case i start off with a coin toss and say the computer wins the coin toss i would have to use the update method to set the type as computer right?
Comment: Yeah, well you have the two Player objects, right? You have to do them in order... You can put them in an array based on the order, or just have a if statement in the loop. You don't need a whole 'nother method.
Comment: Hi, i have the players alternating turns but i seem to have a problem when the object is less than n it throws an exception. i am probably 95% close to finish line. is it possible for me to show u what code i got so far? so you can guide me me
Comment: Hi, i just posted the updated code in my question. Thanks so much for taking your time.
Comment: @user2733436 You need to add the exception as well. Or email me.
Comment: hey buddy, did u get a chance to look at the error? :)


Let $G$ be a group of order $2^tk$, then prove that elements of odd order form a subgroup

Question: Actually, this question already has multiple answers on this website: using Burnside's theorem and one with induction and $p$-Sylow groups. I'm asking this question here, however, because the exercise below appears in my group theory syllabus in the third chapter, with only the following topics covered: definition of groups, many examples, subgroups, direct product, homomorphisms, generators, order, index. Thus I don't understand the two answers I found on this site and I'm looking for a more elementary approach using the topics included in the first three chapters of my syllabus.
So I'm asked the following.

Let $G$ be a finite group of order $2^tk$, $\ t,k\in\mathbb{Z}$, $k$ odd and suppose that $G$ has an element of order $2^t$. Prove that the elements of $G$ of odd order form a subgroup of order $k$ and index $2^t$ in $G$.

Everything I tried so far led me nowhere and it does not contribute anything to show this here. I hope anyone can be give me a hint or (partial) proof to get me going!
Comment: Let me just remark immediately (as the answerer for the other methods) that I have no idea off the top of my head how one might do this with nothing more than the given tools. Has the exercise been marked in some way as challenging?
Comment: No, but none of the exercises are marked as challenging and there are some that are really difficult or require quite difficult theorems. By the way I state the topics included in my post but this also includes many related theorems. I would also appreciate another approach then the two in the other answers, because it might be helpful for me to understand this result.
Answer: Here's a sketch of a proof, using only very basic notions.
Consider an element $g$ of order $2^t$. The image of $g$ in the regular representation must consist of  $2^t$-cycles, so $k$ of them. Since $k$ is odd and $2^t$ is even, this is an odd permutation. So the elements of $G$ that correspond to even permutations in the regular representation form a subgroup $H$ of index $2$. Note that all elements of odd order of $G$ are contained in $H$.
Note that $g^2\in H$ has order $2^{t-1}$, while $|H|=k2^{t-1}$. So $H$ also satisfies the hypothesis. Simply repeat the procedure and you get a chain of subgroups, each of index $2$ in the previous one, until, you get a subgroup $N$ of index $2^t$ in $G$ and thus of order $k$, which contains all the elements of odd order in $G$. (Since $k$ is odd, by Lagrange $N$ consists of exactly the elements of odd order.)
(EDIT: I've made a small edit to remove the use of characteristic subgroups.)
Comment: @Stephen Sure, but they had already seen the answer in the link which is practically the same as this one, so clearly some part of it was not familiar.
Comment: I was assuming that the mention of Sylow subgroups (and even Hall subgroups) in those answers was throwing them off. Things like Cayley's Theorem are usually seen much earlier than Sylow (which is often not even included in a first class in group theory) and, in any case, it is actually very easy to show what is needed here from scratch (as Stephen said). But I also agree with both of you, these answers are essentially all the same, I just tried to avoid more advanced terminology.
Comment: Speaking of assuming, why do you assume that the OP has not studied these? All we've been given is a list of words, something like titles of sections, and it's hard to know exactly what that means. In most basic group theory classes, Cayley's Theorem is treated very early. In fact, I just had a look, and in the first two books I checked, it is handled in the chapter on homomorphisms, which the OP said they have seen. Similarly with the parity of a permutation.  So who knows? Why don't we wait for the OP to tell us if they are satisfied with these answers, and clarify some parts if necessary?
Comment: I did my best to write the most elementary answer I know. As Stephen, I doubt if there exists a significantly easier one. Would it have been better if nobody wrote anything except "it is impossible to write a proof using only the list of words you gave us"?
Comment: Nice answer (+1). My opinion is that this is both an elementary solution, and the best possible solution.
Comment: Also, I agree with verret that writing this answer is better than do nothing. Essentially (as far as I can judge) this answer seems the same as the one by induction I linked to in the question, but this one seems like a 'translation' to more elementary terminology so I can understand this. So thanks for this, also to Tobias who wrote the answer I linked to.

By the way I also looked quickly this morning to the other answer that is deleted now but I wasn't able to follow that one.
Comment: @VáclavMordvinov: the second part is easier. If $H$ has index $2$, then any element not in $H$ must have even order. (Its powers will alternate between $H$ and the other coset, so only even powers will be $H$.)
Comment: @VáclavMordvinov For the first part, the regular representation gives you a homomorphism from $G$ to $Sym(G)$. To make the notation easier, let me identify $G$ with its image in $Sym(G)$. (It turns out that the homomorphism is injective, so this is an embedding, but that doesn't even matter.) Let $H=G \cap Alt(G)$. Since $|Sym(G):Alt(G)|=2$, we have $|G:H|\leq 2$. (see my answer for https://math.stackexchange.com/questions/2649635/centralizer-sizes-in-groups-and-subgroups/2649673#2649673 for example) Since we have an odd permutation, $H<G$, so in fact $|G:H|=2$.
Comment: It seems like the OP has not yet seen group actions.
Comment: Why do both answers *assume* that a relatively advanced result (relative to what the OP himself said he's studied so far) as Cayley's Theorem is "basic"? Not only that: both answers make relatively deep use of the structure of element in symmetric groups, whic **also** hasn't yet been studied by the OP... I think Tobias' comment below the question still applies: how can this exercise be solved with so few stuff  as the OP says he's studied?
Comment: @verret I don't assume anything: he himself wrote that **explicitly** in his post, as you can easily read. That's happened to most of us now and then...And about books: Rotman's book takes it in page 52, in the obvious chapter of permutation groups and etc...even after proving the simplicity of $\;A_n,\,n\ge5\;$ . Dummit&Foote: in the chapter of actions of groups, after seeing permutations, series (Hölder and stuff), etc.  Hungerford: after actions, permutations and etc.
Comment: @verret About your second comment above: nobody said it would be better to write that...and, as far as I can read, nobody did. I, as Tobias said, also don't know a proof that uses only the elements the OP wrote has studied so far. Perhaps somebody does. The answers here don't show that, imo. They use stuff more advanced than what the OP stated he's studied so far. That's all.
Comment: Indeed, like DonAntonio assumes, I'm also in doubt whether this result can be proven using the topics I named. And indeed group actions and Cayley's theorem appear later in my syllabus. Like verret says, an answerer cannot know exactly what is treated in my course and what is not and thus have to make assumptions on this.
Comment: By the way when you say

"So the elements of $G$ that correspond to even permutations in the regular representation form a subgroup $H$ of index $2$. Note that all elements of odd order of $G$ are contained in $H$.",

this is where Cayley's theorem and group actions are used, implicitly, right? If not, could you elaborate on this a bit further because I get it intuitively but I wouldn't know how to make this rigorous.

Like DonAntonio says, I'm also in doubt whether an easier solution is possible. This morning I asked my teacher but she also couldn't think of an elementary solution.
Comment: It makes way more sense now and I see that we have proved a lot of stuff we mention already in the exercises of our syllabus. I understand now, although it is a quite difficult exercise at this stage. Thanks for the help! :)


Does $\partial_{\varepsilon_k} f(x^k)$ approximate $ \partial f (\bar{x})$ for $ x^k \to \bar{x} $ and $\varepsilon_{k} \to 0 $?

Question: Suppose that $f: \mathbb{R}^n \to \mathbb{R}$ is convex and globally Lipschitz continuous.
Let $(x^k) \subset \mathbb{R}^n$ be a sequence such that $ x^k \to \bar{x} $ for some $\bar{x} \in \mathbb{R}^n$.
Assume $(\varepsilon_k) \subset \mathbb{R}_{+}$ a sequence of positive scalars such that $\varepsilon_{k} \to 0 \, .$

Does the following hold:
$$ \operatorname{dist} \left( \, \partial_{\varepsilon_k} f(x^k) \, , \, \partial f (\bar{x}) \, \right):= \sup_{g \in \partial_{\varepsilon_k} f(x^k)} \, \, \inf_{h \in  \partial f (\bar{x})} \, \| g - h \|_2  \to 0 $$
where

$\partial_{\varepsilon_k} f(\cdot)$ denotes the $\varepsilon_k$-subdifferential of $f$
$\partial f(\cdot)$ denotes the regular convex subdifferential of $f$
$\| \cdot \|$ denotes the Euclidean distance.

The following is all from Convex Analysis and Minimization Algorithms II and might be of use:
Definition 1.1.1 Given $x \in \mathbb{R}^n$ the vector $s \in \mathbb{R}^{n}$ is called an $\varepsilon$ -subgradient of $f$ at $x$ when the following property holds:
$$
f(y) \geqslant f(x)+\langle s, y-x\rangle-\varepsilon \quad \text { for all } y \in \mathbb{R}^{n}
$$
It follows immediately from the definition that

$\partial_{\varepsilon} f(x) \subset \partial_{\varepsilon^{\prime}} f(x)$ whenever $\varepsilon \leqslant \varepsilon^{\prime}$
$\partial f(x)=\partial_{0} f(x)=\cap\left\{\partial_{\varepsilon} f(x): \varepsilon>0\right\}\left[=\lim _{\varepsilon \downarrow 0} \partial_{\varepsilon} f(x)\right] $

Theorem 1.1.4 For $\varepsilon \geqslant 0, \partial_{\varepsilon} f(x)$ is a closed convex set, which is nonempty and bounded.
Proposition 4.1.1 Let $\left\{\left(\varepsilon_{k}, x_{k}, s_{k}\right)\right\}$ be a sequence converging to $(\varepsilon, x, s),$ with $s_{k} \in$ $\partial_{\varepsilon_{k}} f\left(x_{k}\right)$ for all $k .$ Then $s \in \partial_{\varepsilon} f(x)$.
Proposition 4.1.2 Let $\delta>0$ and $L$ be such that $f$ is Lipschitzian with constant $L$ on some ball $B(x, \delta),$ where $x \in \mathbb{R}^n$. Then, for all $\delta^{\prime}<\delta$
$$
\|s\| \leqslant L+\frac{\varepsilon}{\delta-\delta^{\prime}}
$$
whenever $s \in \partial_{\varepsilon} f(y),$ with $y \in B\left(x, \delta^{\prime}\right)$.
As a result, the multifunction $\partial_{\varepsilon} f$ is outer semi-continuous, just as is the exact subdifferential.
Theorem 4.1.3 Let $f: \mathbb{R}^{n} \rightarrow \mathbb{R}$ be a convex Lipschitzian function on $\mathbb{R}^{n} .$ Then there exists $K>0$ such that, for all $x, x^{\prime}$ in $\mathbb{R}^{n}$ and $\varepsilon, \varepsilon^{\prime}$ positive:
$$
\Delta_{H}\left(\partial_{\varepsilon} f(x), \partial_{\varepsilon^{\prime}} f\left(x^{\prime}\right)\right) \leqslant \frac{K}{\min \left\{\varepsilon, \varepsilon^{\prime}\right\}}\left(\left\|x-x^{\prime}\right\|+\left|\varepsilon-\varepsilon^{\prime}\right|\right)
$$
This result  implies the inner semi-continuity of $(x, \varepsilon) \longmapsto \partial_{\varepsilon} f(x)$ for a Lipschitz-continuous $f$.
In particular, for fixed $\varepsilon>0$
$$\partial_{\varepsilon} f(y) \subset \partial_{\varepsilon} f(x)+\|y-x\| B(0, \frac{K}{\varepsilon}) \quad \text{for all } x \text{ and } y \, .$$
Corollary 4.1.5 Let $f: \mathbb{R}^{n} \rightarrow \mathbb{R}$ be convex. For any $\delta \geqslant 0,$ there is $K_{\delta}>0$ such that
$$\Delta_{H}\left(\partial_{\varepsilon} f(x), \partial_{\varepsilon} f\left(x^{\prime}\right)\right) \leqslant \frac{K_{\delta}}{\varepsilon}\left\|x-x^{\prime}\right\| \quad \text{ for all } x \text{ and } x^{\prime} \in B(0, \delta) \, .$$
Theorem 4.2.1  Let be given $f: \mathbb{R}^n \to \mathbb{R}$, $x \in \mathbb{R}^n$ and $\varepsilon \geqslant 0 .$ For any $\eta>0$ and $s \in \partial_{\varepsilon} f(x),$ there exist $x_{\eta} \in B(x, \eta)$ and
$s_{\eta} \in \partial f\left(x_{\eta}\right)$ such that $\left\|s_{\eta}-s\right\| \leqslant \varepsilon / \eta$.
This result can be written in a set formulation:
$$
\partial_{\varepsilon} f(x) \subset \bigcap_{\eta>0} \bigcup_{\|y-x\| \leqslant \eta}\left\{\partial f(y)+B(0, \frac{\varepsilon}{\eta})\right\} .
$$

The following one is not from the above mentioned source but easy to prove:
Theorem Assume $f: \mathbb{R}^n \to \mathbb{R}$ is convex and let $x \in \mathbb{R}^n$. Then for every $\varepsilon > 0$ there is a $\delta > 0$ such that
$$
\bigcup_{y \in B_{\delta}(x)} \partial f(y) \subset \partial_{\varepsilon} f(x) \,.
$$
Answer: The Clarke subdifferential is upper semi-continuous. By definition, for each $\epsilon>0$ and $k$ big enough we must have that $\partial f(x^k) \subset \partial f(x) +  B(0, \epsilon).$ Hence, for such $k$ big enough,
$$\sup_{g_k \in\partial f(x^k)} \inf_{g \in\partial f(x)} \| g_k - g \| \leq \epsilon. $$ Consequently,
$$\lim \sup_{g_k \in\partial f(x^k)} \inf_{g \in\partial f(x)} \| g_k - g \| = 0$$
Comment: Many thanks for your reply. However, my question is concerning the $\varepsilon$-subdifferential.
Comment: If you don't mind and maybe have some time, would you have a look at this other question I have:

https://math.stackexchange.com/questions/4219167/upper-semicontinuity-of-clarke-subdifferential

Even a literature recommendation would help. Many thanks.
Answer: Your Theorem 4.2.1 and the upper semicontinuity of Clarke differential is enough to answer the question.
We want to prove that $$\lim \sup_{g \in \partial_{\varepsilon_k} f(x^k)} \, \, \inf_{h \in  \partial f (\bar{x})} \, \| g - h \|_2 = 0. \tag{*}$$ The main idea is to note that, since $$\partial_{\epsilon} f (x) \subset \cup_{\|y-x\| \leq \sqrt{\epsilon}}\  \partial f (y) + B\left(0,\sqrt{\epsilon}\right),$$ each $g \in \partial_{\varepsilon_k} f(x^k)$ is an approximation of some Clarke differential close to $x$.
Aiming to prove (*), let $\epsilon>0$ be given, there exists $\delta>0$ such that for all $x' \in B(\bar{x},\delta)$ implies that
$$\partial f(x') \subset \partial f(\bar{x})+B\left(0,\dfrac{\epsilon}{2}\right)  \tag{1} $$ due to upper semicontinuity of Clarke differential. Choosing $k_0$ such that for each $k \geq k_0$ it's true that $$\sqrt{\epsilon_k}<\dfrac{\min\{\delta,\epsilon\}}{2} \tag{2}$$ and
$$\|x^{k} - \bar{x}\| < \dfrac{\delta}{2}, \tag{3}$$ given $g \in \partial_{\epsilon_k} f(x^{k}) $, by the Theorem 4.2.1, there exist $y^{k}$ such that $$\|y^{k} - x^{k}\| \leq \sqrt{\epsilon_k}$$ and $$g \in \partial f (y^{k}) + B\left(0,\dfrac{\epsilon_k}{\sqrt{\epsilon_k}}\right) = \partial f (y^{k})+ B\left(0,\sqrt{\epsilon_k}\right).\tag{4}$$ Since $\|y^{k} - x^{k}\| < \dfrac{\delta}{2}$ and $\|x^{k} - \bar{x}\| < \dfrac{\delta}{2}$ by (2) and (3), we have $$\|y^{k} - \bar{x}\| \leq \|y^{k} - x^{k}\|+\|x^{k} - \bar{x}\|<\delta$$ which means, by (1), $$
\partial_{\epsilon_k} f(y^{k}) \subset \partial f(\bar{x})+B\left(0,\dfrac{\epsilon}{2}\right).$$ Consequently, by (4),
\begin{align}
g \in \partial f (y^{k})+ B\left(0,\sqrt{\epsilon_k}\right) \subset & \partial f(\bar{x})+B\left(0,\dfrac{\epsilon}{2}\right) + B\left(0,\sqrt{\epsilon_k}\right) \\
\subset & \partial f(\bar{x})+B\left(0,\dfrac{\epsilon}{2}\right) + B\left(0,\dfrac{\epsilon}{2}\right) \\
\subset & \partial f(\bar{x})+B\left(0,\epsilon \right).\end{align} Finally,
$$\inf_{h \in \partial f(\bar{x})} \|g - h\|<\epsilon $$ for all $g\in \partial_{\epsilon_k} f (x^{k})$ which means $$\sup_{g\in \partial_{\epsilon_k} f(x^{k})} \inf_{h \in \partial f(\bar{x})} \|g - h\| \leq \epsilon.$$
Comment: Many, many thanks for your great effort! I will go through it and try to follow it step by step. When I understand everything I will mark it as answered. Again, thank you very much. =)
Comment: I did not have the time yet to follow every single step but I think this is exactly what I was looking for!
Comment: Take your time. You will find that it's correct. I have checked the proof of  **Theorem 4.2.1** on the aforementioned book and everything is fine.


AS3 pixel perfect drawing?

Question: When I'm use:
var shape:Shape = new new Shape();
shape.graphics.lineStyle(2,0);
shape.graphics.lineTo(10,10);
addChild(shape);

I get the black line I want, but I also get grey pixels floating around next to them. Is there a way to turn off whatever smoothing/anti-aliasing is adding the fuzzy pixels?
Comment: First off your posted code is broken var shape:Shape = new new Shape(); you can't have "new new" secondly you are drawing a vector image and the lines should be crisp and sharp. I ran your sample code in CS4 flash and it looked fine to me. So please post the actual code that is giving you the issue.
Answer: Yes, it is possible to draw pixel-perfect shapes, even with anti-aliasing on.  Pixel-hinting is a must.  The other half of the equation is to actually issue the drawing commands with whole-pixel coordinates.
For example, you can draw a pixel-perfectly-symmetrical rounded-rectangle with 4px radius curves with the following code.  Pay careful attention to what the code is doing, particularly how the offsets relate to the border thickness.
First, keep in mind that when you're drawing filled shapes, the rasterization occurs up to, but no including the right/lower edges of the outline.  So to draw a 4x4 pixel filled square, you can just call drawRect(0,0,4,4).  That covers pixels 0,1,2,3,4 (5 pixels), but since it doesn't rasterize the right and lower edges, it ends up being 4 pixels.  On the other hand, if you're drawing just the outline (without filling it), then you need to call drawRect(0,0,3,3), which will cover pixels 0,1,2,3, which is 4 pixels.  So you actually need slightly different dimensions for the fill vs the outline to get pixel-perfect sizes.
Suppose you wanted to draw a button that's 50px wide, 20px tall, with a 4px radius on its rounded edges, which are 2px thick.  In order to ensure that exactly 50x20 pixels are covered, and the outside edge of the 2px thick line buts up against the edge pixels without overflowing, you have to issue the drawing command exactly like this.  You must use pixel hinting, and you must offset the rectangle by 1px inward on all sides (not half a pixel, but exactly 1).  That places the center of the line exactly between pixels 0 and 1, such that it ends up drawing the 2px wide line through pixels 0 and 1.
Here is an example method that you can use:
public class GraphicsUtils
{
    public static function drawFilledRoundRect( g:Graphics, x:Number, y:Number, width:Number, height:Number, ellipseWidth:Number = 0, ellipseHeight:Number = 0, fillcolor:Number = 0xFFFFFF, fillalpha:Number = 1, thickness:Number = 0, color:Number = 0, alpha:Number = 1, pixelHinting:Boolean = false, scaleMode:String = "normal", caps:String = null, joints:String = null, miterLimit:Number = 3 )
    {
        if (!isNaN( fillcolor))
        {
            g.beginFill( fillcolor, fillalpha );
            g.drawRoundRect( x, y, width, height, ellipseWidth, ellipseHeight );
            g.endFill();
        }
        if (!isNaN(color))
        {
            g.lineStyle( thickness, color, alpha, pixelHinting, scaleMode, caps, joints, miterLimit );
            g.drawRoundRect( x, y, width, height, ellipseWidth, ellipseHeight );
        }
    }
}

Which you'd want to call like this:
var x:Number = 0;
var y:Number = 0;
var width:Number = 50;
var height:Number = 20;
var pixelHinting:Boolean = true;
var cornerRadius:Number = 4;
var fillColor:Number = 0xffffff; //white
var fillAlpha:Number = 1;
var borderColor:Number = 0x000000; //black
var borderAlpha:Number = 1;
var borderThickness:Number = 2;
GraphicsUtils.drawFilledRoundRect( graphics, x + (borderThickness / 2), y + (borderThickness / 2), width - borderThickness, height - borderThickness, cornerRadius * 2, cornerRadius * 2, fillColor, fillAlpha, borderThickness, borderColor, borderAlpha, pixelHinting );

That will produce a pixel-perfectly-symmetrical 2px thick filled rounded rectangle that covers exactly a 50x20 pixel region.
Its very important to notice that using a borderThickness of zero is somewhat non-sensical, and will result in an rectangle oversized by 1 pixel, because it's still drawing a one-pixel wide line, but it's failing to subtract the width (since its zero), hence you'll get an oversized rectangle.
In summary, use the algorithm above, where you add half the border thickness to the x and y coordinates, and subtract the whole border thickness from the width and height, and always use a minimum thickness of 1.  That will always result in a rectangle with a border that occupies and does not overflow a pixel region equivalent to the given width and height.
If you want to see it in action, just copy and paste the following code block into a new AS3 Flash Project on the main timeline and run it, as is, since it includes everything necessary to run:
import flash.display.StageScaleMode;
import flash.display.StageAlign;
import flash.events.Event;
import flash.utils.getTimer;
import flash.display.Sprite;
import flash.display.Graphics;

stage.scaleMode = flash.display.StageScaleMode.NO_SCALE;
stage.align = flash.display.StageAlign.TOP_LEFT;
stage.frameRate = 60;
draw();

function draw():void
{
    var x:Number = 10;
    var y:Number = 10;
    var width:Number = 50;
    var height:Number = 20;
    var pixelHinting:Boolean = true;
    var cornerRadius:Number = 4;
    var fillColor:Number = 0xffffff; //white
    var fillAlpha:Number = 1;
    var borderColor:Number = 0x000000; //black
    var borderAlpha:Number = 1;
    var borderThickness:Number = 2;

    var base:Number = 1.6;
    var squares:int = 10;
    var rows = 4;
    var thicknessSteps:Number = 16;
    var thicknessFactor:Number = 4;

    var offset:Number;
    var maxBlockSize:Number = int(Math.pow( base, squares ));
    var globalOffset:Number = maxBlockSize; //leave room on left for animation
    var totalSize:Number = powerFactorial( base, squares );
    var colors:Array = new Array();
    for (i = 1; i <= squares; i++)
        colors.push( Math.random() * Math.pow( 2, 24 ) );

    for (var j:int = 0; j < thicknessSteps; j++)
    {
        var cycle:Number = int(j / rows);
        var subCycle:Number = j % rows;
        offset = cycle * totalSize;
        y = subCycle * maxBlockSize;
        borderThickness = (j + 1) * thicknessFactor;
        for (var i:int = 0; i < squares; i++)
        {
            cornerRadius = Math.max( 8, borderThickness );
            borderColor = colors[i];
            x = globalOffset + offset + powerFactorial( base, i ); //int(Math.pow( base, i - 1 ));
            width = int(Math.pow( base, i + 1 ));
            height = width;
            if (borderThickness * 2 > width) //don't draw if border is larger than area
                continue;
            drawFilledRoundRect( graphics, x + (borderThickness / 2), y + (borderThickness / 2), width - borderThickness, height - borderThickness, cornerRadius * 2, cornerRadius * 2, fillColor, fillAlpha, borderThickness, borderColor, borderAlpha, pixelHinting );
        }
    }

    var start:uint = flash.utils.getTimer();
    var duration:uint = 5000;
    var sprite:Sprite = new Sprite();
    addChild( sprite );
    var gs:Graphics = sprite.graphics;
    addEventListener( flash.events.Event.ENTER_FRAME,
    function ( e:Event ):void
    {
        var t:uint = (getTimer() - start) % duration;
        if (t > (duration / 2))
            borderThickness = ((duration-t) / (duration/2))  * thicknessSteps * thicknessFactor;
        else
            borderThickness = (t / (duration/2)) * thicknessSteps * thicknessFactor;
        //borderThickness = int(borderThickness);
        cornerRadius = Math.max( 8, borderThickness );
        borderColor = colors[squares - 1];
        x = 0;
        y = 0;
        width = int(Math.pow( base, squares ));
        height = width;
        if (borderThickness * 2 > width) //don't draw if border is larger than area
            return;
        gs.clear();
        drawFilledRoundRect( gs, x + (borderThickness / 2), y + (borderThickness / 2), width - borderThickness, height - borderThickness, cornerRadius * 2, cornerRadius * 2, fillColor, fillAlpha, borderThickness, borderColor, borderAlpha, pixelHinting );
    }, false, 0, true );
}

function powerFactorial( base:Number, i:int ):Number
{
    var result:Number = 0;
    for (var c:int = 0; c < i; c++)
    {
        result += int(Math.pow( base, c + 1 ));
    }
    return result;
}

function drawFilledRoundRect( g:Graphics, x:Number, y:Number, width:Number, height:Number, ellipseWidth:Number = 0, ellipseHeight:Number = 0, fillcolor:Number = 0xFFFFFF, fillalpha:Number = 1, thickness:Number = 0, color:Number = 0, alpha:Number = 1, pixelHinting:Boolean = false, scaleMode:String = "normal", caps:String = null, joints:String = null, miterLimit:Number = 3 )
{
    if (!isNaN( fillcolor))
    {
        g.beginFill( fillcolor, fillalpha );
        g.drawRoundRect( x, y, width, height, ellipseWidth, ellipseHeight );
        g.endFill();
    }
    if (!isNaN(color))
    {
        g.lineStyle( thickness, color, alpha, pixelHinting, scaleMode, caps, joints, miterLimit );
        g.drawRoundRect( x, y, width, height, ellipseWidth, ellipseHeight );
    }
}

Comment: I accepted this answer without actually testing it myself, but I dimly remember convincing myself that something like this was actually the solution, and chose a different path rather than implement this. I'm glad this is here.
Answer: Try turning on pixelHinting:
shape.graphics.lineStyle(2, 0, 1, true);
More about pixelHinting here.
Comment: Pixel hinting doesn't turn off antialiasing. It is still antialiased but lines are snapped to whole pixels where possible, so there is sometimes a reduction in the amount of blurry pixels. If you run your code and then run OP's code, there is no visual difference.
Answer: You can't turn off antialiasing completely. If you want a sharp, pixelated line then unfortunately you have to draw pixel by pixel, using a Bitmap and setPixel()

AS3 pixel perfect drawing?


LNK2028 LNK2019 errors on unmanaged function call in managed function

Question: I have an absurdly simple managed (CLI Interop) function calling an unmanaged function:
void ManagedZigBeeTransport::StartDiscovery(void)
{
    std::list<sDeviceEndPoint> devices = zbTransport->startDiscovery();
}

where zbTransport is an unmanged object. I have several other examples of methods in this unmanaged object that that are called in similar managed wrappers without a problem and they all work. However, they do not have a return value. This one does.
It gives me the dreaded
CppBridgeTransports.obj : error LNK2028: unresolved token (0A00033B) "public: class std::list<struct _sDeviceEndPoint,class std::allocator<struct _sDeviceEndPoint> > __thiscall ZBTransport::startDiscovery(void)" (?startDiscovery@ZBTransport@@$$FQAE?AV?$list@U_sDeviceEndPoint@@V?$allocator@U_sDeviceEndPoint@@@std@@@std@@XZ) referenced in function "public: void __clrcall CppBridge::ManagedZigBeeTransport::StartDiscovery(void)" (?StartDiscovery@ManagedZigBeeTransport@CppBridge@@$$FQ$AAMXXZ)

followed by
CppBridgeTransports.obj : error LNK2019: unresolved external symbol "public: class std::list<struct _sDeviceEndPoint,class std::allocator<struct _sDeviceEndPoint> > __thiscall ZBTransport::startDiscovery(void)" (?startDiscovery@ZBTransport@@$$FQAE?AV?$list@U_sDeviceEndPoint@@V?$allocator@U_sDeviceEndPoint@@@std@@@std@@XZ) referenced in function "public: void __clrcall CppBridge::ManagedZigBeeTransport::StartDiscovery(void)" (?StartDiscovery@ManagedZigBeeTransport@CppBridge@@$$FQ$AAMXXZ)

I have not been able to apply any of the information I have seen in these threads that have functioned (some pretty simple like adding the std::list<> header file ).
The unmanaged sDeviceEndPoint structure is also defined in a header file. The idea was to obtain this unmanaged std::list<> and use it to load a managed ArrayList(). But I can't even get by this simple step. I don't know what is causing the problem, the std::list or the sDeviceEndPoint struct. The latter is successfully used in other parts of this unmanaged to managed bridge.
Any ideas?
Is it due to name mangling conventions from the return value that I do not understand?
Answer: I am embarrassed as hell! I tested a series of simple functions between managed and unmanaged code, from returning a simple int to a struct, to a vector of structs and to a list of structs. Even passed these fields in as a parameter.
They all worked.
What did I do wrong???
Idiot that I was I forgot I had not yet implemented the original stupid function. All my tests, were, of course, implemented! So my original discovery function was declared but had no implementation.  AARRGG! All day I have spent on this.
(I would have never guessed that was the reason for the error message.)
Maybe this will save someone else who gets the same sets of messages for the same reason.


Run a select query from multiple tables with similar names like t103042020, t102042020, t101042020 etc.?

Question: How to run a select query from multiple tables with similar names like t103042020, t102042020, t101042020, etc.?
I have some tables
t103042020, t102042020, t101042020, t112042019, t111042019, t110042019. I want to merge the contents of these tables without using Union or Union all.
I have an example that I was using:
select * from t103042020
Union
select * from t102042020
Union
select * from t101042020
Union
select * from t112042019
Union
select * from t111042019
Union
select * from t110042019

I want to run the query without using Union or Union all, probably using a regular expression to read through similar table names with a name like '%T1%'. Is there a way of doing it except union or union all?
Comment: Dynamic SQL is the only real way you can handle that, but make sure you use `quotename` to avoid an injection hole.
Comment: @DaleK Can you give more detail?
Comment: is this a one off thing ?
Comment: Google is your friend
Answer: Try this:
DECLARE @DynamicTSQL NVARCHAR(MAX);

SELECT @DynamicTSQL = STUFF
(
    (
        SELECT ' UNION SELECT * FROM ' + QUOTENAME(SCHEMA_NAME([schema_id])) + '.' + QUOTENAME([name])
        FROM [sys].[tables]
        WHERE [name] LIKE 't10%'
            OR [name] LIKE 't111%'
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')
    ,1
    ,7
    ,''
);

EXEC sp_executesql @DynamicTSQL;


Can't change custom keyboard layout in Ubuntu 22.04

Question: I had a keyboard layout file in 18.04 (/usr/share/X11/xkb/symbols/us), where I defined additional characters.
e.g.
...
    key <AD03> {        [         e,    E,      Greek_epsilon,  Greek_EPSILON]  };
...

This worked fine there. After switching to 22.04, this stopped working. To not change the whole file with an older version only the basic entry was edited.
xkb_symbols "basic" {

    name[Group1]= "English (US)";

When I pick the keyboard and check the layout, it appears correctly. (under the layout selection on the top bar)
keyboard layout shows the epsilon character
However, in the applications, I am not able to use the character. AltGr + E does not print any character. In some applications it even triggers some shortcuts. I tried also CTRL + SHIFT + E. Still no success.
(I did relogin/rebooted to test the functionality.)
Comment: Have you defined AltGr as the "Alternate Characters Key"?
Comment: Please feel free to submit an answer yourself. It's fine to answer your own question. ;)
Comment: Thanks it did it. Can you submit it as an answer so that I can accept it? It is done under settings apparently. I have missed it completely.
Answer: Here is Gunnar's comment, which worked out for me.
Under Settings/Keyboard there is a field for "Alternate Characters Key", which can be set to "Right Alt" (nothing political here, just the right "Alt" key on the keyboard).
Setting for alternate key


Norm of a symmetric matrix equals spectral radius

Question: How do I prove that the norm of a matrix equals the absolutely largest eigenvalue of the matrix? This is the precise question:

Let $A$ be a symmetric $n \times n$ matrix. Consider $A$ as an operator in $\mathbb{R}^n$ given by $x \mapsto Ax$. Prove that $\|A\| = \max_j |\lambda_j|$, where $\lambda_j$ are the eigenvalues of $A$.

I've read the relevant sections in my literature over and over but can't find any clue on how to begin. A solution is suggested here but the notion of diagonal operator is not in my literature so it doesn't tell me very much. So, any other hints on how to solve the question? Thanks.
Comment: It is missing here completely in the discussion (but also in the task) that it is about the 2-norm. For other induced matrix norms (lub-norms) the situation is different.
Answer: The norm of a matrix is defined as
\begin{equation}
\|A\| = \sup_{\|u\| = 1} \|Au\|
\end{equation}
Taking the singular value decomposition of the matrix $A$, we have
\begin{equation}
A = VD W^T
\end{equation}
where $V$ and $W$ are orthonormal and $D$ is a diagonal matrix. Since $V$ and $W$ are orthonormal, we have $\|V\| = 1$ and $\|W\| = 1$. Then $\|Av\| = \|D v\|$ for any vector $v$. Then we can maximize the norm of $Av$ by maximizing the norm of $Dv$.
By the definition of singular value decomposition, $D$ will have the singular values of $A$ on its main diagonal and will have zeros everywhere else. Let $\lambda_1, \ldots, \lambda_n$ denote these diagonal entries so that
\begin{equation}
D = \left(\begin{array}{cccc}
              \lambda_1 & 0 & \ldots & 0 \\
              0 & \lambda_2 & \ldots & 0 \\
              \vdots &  & \ddots & \vdots \\
             0 & 0 & \ldots & \lambda_n
          \end{array}\right)
\end{equation}
Taking some $v = (v_1, v_2, \ldots, v_n)^T$, the product $Dv$ takes the form
\begin{equation}
Dv = \left(\begin{array}{c}
                  \lambda_1v_1 \\
                    \vdots \\
                  \lambda_nv_n
\end{array}\right)
\end{equation}
Maximizing the norm of this is the same as maximizing the norm squared. Then we are trying to maximize the sum
\begin{equation}
S = \sum_{i=1}^{n} \lambda_i^2v_i^2
\end{equation}
under the constraint that $v$ is a unit vector (i.e., $\sum_i v_i^2 = 1$). The maximum is attained by finding the largest $\lambda_i^2$ and setting its corresponding $v_i$ to $1$ and then setting each other $v_j$ to $0$. Then the maximum of $S$ (which is the norm squared) is the square of the absolutely largest eigenvalue of $A$. Taking the square root, we get the absolutely largest eigenvalue of $A$.
Comment: @TedShifrin is it not up to me who asked the question to determine what is overkill? I asked for more details, the answer is not overkill, it's precisely what I needed.
Comment: @ErikVesterlund If you consider $S$ just as a weighted sum (putting aside for now that these are eigenvalues of $A$ we're dealing with), then intuitively it makes sense that to maximize the weighted sum, we'd assign all of the weight to the largest element in the sum. Considering the case of a $2 \times 2$ matrix, we'd just have $\lambda_1$ and $\lambda_2$ so that $S = \lambda_1^2v_1^2 + \lambda_2^2v_2^2$. Here, if $\lambda_1 > \lambda_2$, we'd maximize $S$ by setting $v_1 = 1$ and $v_2 = 0$ (and vice-versa if $\lambda_2 > \lambda_1$). The case of higher dimensions is similar. Does this help?
Comment: The fact that $\|W\| = 1$ and does not imply that $\|Wv\| = \|v\|$ for any vector $v$. It follows from $W$ being unitary.
Comment: @yoknapatawpha I understand your argument completely, thank you. However, I'm not able to convince myself that your choice of $x \in R^n$ yields the greatest $||Dx|||$?
Comment: @ErikVesterlund: My apologies for stepping on your toes.
Answer: But the key point is exactly that your matrix is diagonalizable more specially that  you can find an orthonormal basis of eigenvector $e_i$ for which you have $A e_i=\lambda_i e_i$.
Then your write for $x=\sum x_ie_i$ and you have $Ax=\sum x_i\lambda_i e_i$ so that $\|Ax\|^2=\sum\lambda_i^2x_i^2$ now by definition of the norm of matrix it gives you $$\frac{\|Ax\|}{\|x\|}\leq|\lambda_{i_0}|$$ therefore $\|A\|\leq|\lambda_{i_0}|$ where $\lambda_{i_0}$ is the greatest eigenvalue . Finally the identity $\|Ae_{i_0}\|=\|\lambda_{i_0}e_i\|$ gives you the inequality $\|A\|\geq|\lambda_{i_0}|$.
Comment: just because  $(e_i)$ is an orthonormal basis, the whole question relies on the euclidean structure : the norm in $\mathbb{R}^n$ is the one defined by  $\|x\|^2:==\sum x_i^2$. The fact that $e_i$ is orthonormal reads $=\delta_{ij}$ which means $1$ if $i=j$ and $0$ otherwise. Now compute $\|x\|^2==\sum x_ix_j=\sum x_i^2$
Comment: So $x_i$ is not the elements of $x$ but its decomposition in the orthonormal basis $(e_i)$?
Comment: How do you get that $||Ax||^2 = \sum \lambda_i^2 x_i^2$? At least in my book the matrix norm is not defined, not previous to the exercise anyway so, what is it?
Comment: Is it correct to draw the conclusion, that when we can find an eigenbasis, then the largest singular value always equals the largest eigenvalue?
Answer: I don't have enough reputation to comment. But I'd like to fix a mistake in @yoknapatawpha's answer. The overall idea is correct.
Take the singular value decomposition of $A$ as $$A=VDW^T$$ and then we are looking for $$\max_{||u||=1}||Au||=\max_{||u||=1}||VDW^Tu||.$$
Here V and W are both orthogonal matrices.
Because V is orthogonal, we have
$$||VDW^Tu||=||DW^Tu||.$$
Now denote $$x=W^Tu,$$ because W is orthogonal, we have $$||x||=||W^Tu||=||u||=1$$ and also there is an one-to-one mapping between $x$ and $u$. Thus the problem is equivalent to
$$\max_{||x||=1} ||Dx||$$
and the rest of the answer follows @yoknapatawpha's.
However, generally it's not right to say $\|Av\| = \|D v\|$ is true for any $v$. For example when
$$V=\left[\begin{matrix}1& 0\\0 & 1\end{matrix}\right], D=\left[\begin{matrix}2& 0\\0 & 1\end{matrix}\right], W=\left[\begin{matrix}0& 1\\1 & 0\end{matrix}\right], v=\left[\begin{matrix}1\\0\end{matrix}\right]$$
in this case you can check that $||Av||=1$ but $||Dv||=2$.
Answer: Hints:
1)

$$ A x = \lambda x \implies ||Ax|| = ||\lambda x||.$$

2)

$$ ||A x||\leq ||A||\, ||x|| $$

3) Check the definition of the norm and conclude.
Comment: Unfortunately this only allows one to show that $\|A\|\geq\lambda_{i_0}$ and you the need the argument below to conclude in the other way.
Comment: Where are you using the symmetry hypothesis?
Comment: @TedShifrin: As you see it is a hint just to give the OP a start. Thanks for the comment. I appreciate it.


Logging warnings in Django: filter not returning anything

Question: I am trying to setup Django logging to log deprecation warnings. I normally wouldn't have a formatter like this or output it to console, that is just to test and show it is not working.
Here is my code:
def is_deprecated(record):
    if record.exc_info:
        exc_type, exc_value = record.exc_info[:2]
        print(exc_value)
        if isinstance(exc_value, DeprecationWarning) or isinstance(exc_value, PendingDeprecationWarning):
            return True
    return False

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'stuff': {
            'format': 'This works!'
        }
    },
    'filters': {
      'is_deprecated': {
          '()': 'django.utils.log.CallbackFilter',
          'callback': is_deprecated,
      },
    },
    'handlers': {
        'console': {
            'filters': ['is_deprecated'],
            'class': 'logging.StreamHandler',
            'formatter': 'stuff',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': 'INFO',
        },
    },
}

It should output "This works!" when it hits a deprecation warning however it won't. I am running python with these alerts on

python -Wd

So I can see the regular Django alert but I can't get the logger to detect them.
Answer: Apparently, the you use the -Wd argument it displays the warning but is not treated as an exception (Django log only handles exceptions) you can change this behavior using warnings.simplefilter('error') in some initial part (like the settings.py, init.py, manage.py, etc.) or use the python -W error command
reference: https://docs.python.org/2/library/warnings.html#the-warnings-filter
Comment: On top of this, simplefilter will raise the equivalent exception. If you do not want this you can follow this solution to handle the warnings with Django's logging silently

https://stackoverflow.com/questions/40752766/how-to-log-python-warnings-in-a-django-log-file


"Multiple serializers are not supported" configuration error in NServiceBus 4.0.4 during unit testing

Question: I am trying to unit test message handlers for NServiceBus 4.0.4. The bus is configured to use JSON serializer in the application using the Configure.Serialization.Json(); method call.
Whenever I call the Test.Initialize() method from the unit tests assembly I get the following exception: System.Configuration.ConfigurationErrorsException : Multiple serializers are not supported. Please make sure to only enable one
I tried calling Configure.Serialization.Json() and Serializers.SetDefault<JsonSerialization>() before calling the Test.Initialize() method without any success.
Does anyone know what am I doing wrong? All examples I see on the internet do not mention any Configure calls.
Comment: I think you found a bug, please report it to us, https://github.com/Particular/NServiceBus/issues/new
Answer: This issue has been reported previously here and looks like it will be fixed in the next NServiceBus build (both 4.0.5 and 4.1.0)
A workaround is to explicitly disable the xml serializer when enabling the json one.
Configure.Serialization.Json();
Feature.Disable<XmlSerialization>(); // hack to make NSB unit tests work


Exactly how does Suleiman's special work?

Question: Playing Ottoman for the first time and I seem to have far less than 50% conversion of naval barbarians via barbary corsairs. The description merely says there is a 50% conversion rate however and doesn't specify what triggers this so I suspect I'm doing something wrong/
Comment: Similar question asked here: http://forums.2kgames.com/showthread.php?91131-Ottoman-Special-Ability&highlight=Ottoman
Comment: I have no idea how it works. I already have captured 14 barbarian naval units, and still no achievement... :-(
Comment: Okay - now I have 20 barb units. No achievement. Grrr... Anyone?
Answer: When you get near a barbarian naval unit with your own unit the special ability works. If you are lucky then the barbarian naval unit is converted. If not nothing changes you can attack.
Comment: from experiments this seems correct, also if it didnt work going away and coming back to it doesn't seem to trigger it for a second shot


Minecraft /playsound for raid horn?

Question: I tried /playsound ominous_horn_blares and it did not work. How can I play the raid horn sound? in minecraft with /playsound?
Answer: You will want to use /playsound minecraft:event.raid.horn hostile @a ~ ~ ~ 1. The 1 at the end is the volume, so if you can't hear it, turn it up. Personally, I could hear it at volume 100, and pretty well at 1000.
For more information on the command, here is the /playsound wiki.
For more information on sounds, here are all of the Java Edition sounds.
Edit:
For bedrock users, the /playsound wiki applies too, but as described in the site, the syntax is a little different. I don't have BE, so I can't test it, but I think the command should be /playsound raid.horn @a ~ ~ ~ 1 1 1. The first 1 is the volume, the next is the pitch, and the last is the minimum volume.
The full list of bedrock sounds can be found here. Make sure to click [show] on the page to expand the list.
Comment: Yeah for obscure things it's easier that way, but when you look at the amount of sound files there are, having them grouped by source, so for example `minecraft:entity.skeleton.something`, it's easier to manage overall.
Comment: @Julian Plus, Minecraft is really nice in that the wikis are kept pretty well maintained, especially for things like commands, nbt, and such, so it's pretty easy to find things like sounds once you figure out how it works. Granted, figuring that out in the first place is really hard, so there's ups and downs.
Comment: @RetryVx Sorry for the *very* late response, but I just edited it to provide information for BE.
Comment: I hate all this event.raid or this.that mumbo jumbo. I wish is was just playsound minecraft:horn or something
Comment: I'm playing on bedrock and I tried out the command with no luck is there a way I could do this on bedrock.

Minecraft /playsound for raid horn?


POWER BI Creating visual using two dates from the same table

Question: I have a table of bugs that I want to create a line graph visual on:
<code>| Id | Created Date | Closed Date |
|----|--------------|-------------|
| 1  | 01/01/2020   | 01/02/2020  |
| 2  | 01/01/2020   | 01/03/2020  |
| 3  | 02/01/2020   |             |
</code>
I want to create a line chart visual that shows per day how many bugs were created and how many were closed cumulatively (running total) using two lines.
Is it possible to create this from the one table (using two y-axis)? Do I need another table for the dates and what is the best way to create the relationship?
Answer: This would be a great use case for a simple measure.
<code>Running Total MEASURE =
CALCULATE (
    COUNT(  'Table'[ID] ),
    FILTER (
        ALL ( 'Table' ),
        'Table'[Created Date] <= MAX (  'Table'[Created Date] )
    )
)
</code>
In the above DAX expression, simply plugin your created date and the bug ID where appropriate. Basically, it is counting the instance of each ID that occurs on or before every created date.
Let me know if this helps
Comment: Hi, thank you for the reply. Would you suggest creating a measure also for the Closed Date? Also if I then had another column of "category" would I still be able to slice against this column if using measures?
Comment: Yes, I would create another measure, but this time replace "Created Date" with "Closed Date" to show the cumulative amount of cases closed as the DAX I provided into shows the cumulative amount of cases opened. Yes, this measure can be filtered by any column that is in your table or a table that has a relationship with your table.


How do I let a variable reference a global variable while keeping the value of the global variable unchanged?

Question: So I have this code here:
from random import randint

name = input("u");

def ou():
     global allo
     randomlist = "1", "2", "3", "4"

     array = list(randomlist);
     allo = array

allo = ou();

def wagon():
     som = allo

     for x in range (0, 4):
          som[x] = "1"

if name == "u":
     wagon();
     print(som)
     print(allo)

the output of som and allo are (the last line) ['1', '1', '1', '1']. What should I do to let som reference the value of allo while allowing allo to preserve its original value(1, 2, 3, 4) so sum prints out ['1', '1', '1', '1'] and allo prints out ['1', '2', '3', '4'] at the end? Plus, I need to keep allo as global.
Comment: Try `som = allo[:]` but there are better ways to implement this.
Comment: use global allo before som = allo
Comment: https://www.programiz.com/python-programming/methods/list/copy this might help
Comment: Study list.copy() and do at least an hour of learning on scopes.
Comment: God, I didn't know about list.copy()! Thank you for telling me this. I was trying for a solid day to learn on scopes but It didn't go as well as I've expected... Y'all are angels.
Answer: Here's a version of your code with minimal changes that will allow it to do what you want it to do.  In addition to the two suggestions noted in the comments, I had to change the call to au() to not set allo, since the au() function doesn't return anything.
from random import randint

name = input("u")

def ou():
    global allo
    randomlist = "1", "2", "3", "4"
    array = list(randomlist)
    allo = array

ou()

def wagon():
    global som
    som = allo[:]
    for x in range(0, 4):
        som[x] = "1"

if name == "u":
    wagon()
    print(som)
    print(allo)

Here's another version that does things the way I'd suggest you do them while keeping allo global and using allo to initialize som, even though you turn around and redefined som completely.  If allo was longer than 4 entries, then you'd get a different result if you didn't start with a copy of allo, so I left that in.
name = input("u")

def ou():
    return ["1", "2", "3", "4"]

allo = ou()

def wagon(allo):
    som = allo[:]
    for x in range(0, 4):
        som[x] = "1"
    return som

if name == "u":
    som = wagon(allo)
    print(som)
    print(allo)

Note here that except for keeping your one constraint of ending up with a global allo, I got rid of all uses of globals that rely on them being global inside functions, and rather pass values in and out of the functions so that they do not rely on if the variables being used are global.  This is a much better way to go, and is what is generally done.  Relying on functions to change global variables is harder to read and prone to errors.
NOTE: I see the comments about list.copy.  You could use som = list.copy(allo) instead of som = allo[:].  I always use the former "slice" notation.  I can't think of an advantage to the latter approach, but maybe there is one for larger lists.
Comment: Thank you, Steve. I've learned a lot from your feedback. The second example looks way finer.


SQLite's test code to production code ratio

Question: SQLite claim to have 679 times more test code than production one.
http://www.sqlite.org/testing.html
Does anyone knows how it is possible? Do they generate any test code automatically? What are the major parts of these "45678.3 KSLOC" of test code?
Comment: Just for comparison, 45 MLOC is about the same size as Windows XP. Of course as I argue below, it's easier to write a line of test code (and it survive to the present day) than to write a line of production code and it survive to the present day. Arguably the "test code" for XP includes all the lines of code in Office 95, 98 and 2000 :-)
Answer: "Does anyone knows how it is possible?"
"It is possible" to have 679 times as much test code because a single feature can be used in many different ways.  Consider just a single function that takes two parameters.  I can generate alot of test code for that one function that tests boundary conditions and many other combinations of conditions.  When you consider setup/teardown of the tests, there is additional code there.  Depending on their testing framework this overhead may significantly add to the amount of code in testing.
What it really boils down to is the fact the a piece of software can be used in so many different ways, which means that you have many different scenarios to test for.  This is the beauty of elegant software, in that a simple program can be applied to numerous scenarios, but that is the same thing that makes verifying and testing software so challenging.
Answer: It's presumably possible if the developers spent 679 times as much time writing test code as they spent writing production code.  Just think:  if they'd opted instead for 339 times as much test code, they could have had two entire database engines, each still with a ludicrous amount of test coverage.
I once watched a fellow developer trying to placate a furious customer about slipped deadlines by informing them that he had written 5 times as much test code as production code.  The customer was not placated, if you can imagine.  At least I don't think 5X coverage is extreme anymore.
Comment: There are probably more people writing test code than production code. For instance the article describes their policy on regression tests - you don't have to understand the SQLite code at all to write a regression test for a bug you just found and reported (although someone has to fit it into the test harness). Even so 45 MLOC sounds like an incredible amount to me: even if it's all in repositories and hence "not auto-generated", a lot of it might have been machine-generated in the first place, if only by emacs macros...
Comment: I suspect that a lot of the tests (especially in TH3) were contributed by mobile phone makers. They have a bit of a vested interest in *very* thorough testing of the database engine they ship...
Comment: Also, you remove and replace old code from the product, but unless you've removed a feature there's no point ever removing test cases. So 679:1 LOC doesn't translate to anything like 679:1 time. You can easily spend a day *reducing* the number of LOC in the product and consider it time well spent, but it's rarely worth bothering to do that with test cases.
Comment: @Steve: you make a good point, if SQLite lets end-users write test code and then submit it for incorporation in the larger body of tests. I agree that a lot of it might have been auto-generated, and a lot of it might also consist of long lists of property assignments and so forth. A great example of how worthless LOC is as a measurement.
Answer: It uses Tcl to power the test framework so it's much easier to write tests than it is to write the implementation. This encourages thorough testing, which is what you want in a database, yes? Moreover, a fair fraction of those tests are proprietary, aimed at testing in embedded environments; I imagine some corporate user (or users) paid for that sort of thing. It's also quite possible that the same feature is tested multiple times.
Answer: Looking at section 3.1 (OOM):

OOM testing is accomplished by
  simulating OOM errors. SQLite allows
  an application to substitute an
  alternative malloc() implementation
  using the
  sqlite3_config(SQLITE_CONFIG_MALLOC,...)
  interface. The TCL and TH3 test
  harnesses are both capable of
  inserting a modified version of
  malloc() that can be rigged to fail
  after a certain number of allocations.
  These instrumented mallocs can be set
  to fail only once and then start
  working again, or to continue failing
  after the first failure. OOM tests are
  done in a loop. On the first iteration
  of the loop, the instrumented malloc
  is rigged to fail on the first
  allocation. Then some SQLite operation
  is carried out and checks are done to
  make sure SQLite handled the OOM error
  correctly. Then the time-to-failure
  counter on the instrumented malloc is
  increased by one and the test is
  repeated. The loop continues until the
  entire operation runs to completion
  without ever encountering a simulated
  OOM failure. Tests like this are run
  twice, once with the instrumented
  malloc set to fail only once, and
  again with the instrumented malloc set
  to fail continuously after the first
  failure.

Note that section 7 explicitly states 100% core coverage as determined by gcov. I agree with Donal Fellows that the test framework is largely responsible for the test coverage beyond what a call graph would suggest. Its a much different thing to see malloc() entered nn times and write a test for it than it is to write dozens of tests geared to simulate environments where malloc() is likely to fail.
Yes, the resulting coverage is an artifact of diligence, however so is the selection of a test framework that enables that kind of diligence.
Finally, reiterating the obvious, malloc() takes only a single void pointer. This suggests that the tests written around it are by deliberate design, not automatically generated.


Javascript Trim First Character if Its a Zero

Question: I am getting passed numbers like 01,02,03,04 and up. And I would like to remove the prefixed 0 from them if it exists. But I need it to leave numbers like 10, 20, 30 as they are.
My latest attempt of which I think is overkill as is.. is:
newValue = 01;
tester(newValue);
newValue = 10;
tester(newValue);
function tester(newValue)
{
    finalValue = newValue;
    var arr = newValue.split('0');
    if(arr.length > 1)
    {
        if(arr[0] == 0)
        {
            finalValue = '';
            $.each(arr, function(v)
                   {
                        finalValue +=v;
                   });
        }
    }
//return finalValue;
    console.log(finalValue);
}

Im not sold on this method, I've just tried a number of ways and its all be no go.
Comment: pls refer here: http://stackoverflow.com/questions/646628/javascript-startswith hope it helps..
Comment: If you're dealing with numbers, not strings (which your code example seems to show), then there is no difference between `01` and `1`.  They are the same number.  Try `alert(01)` and see what you get.
Comment: @jfriend00 watch it, 08 and 09 are illegal octal numbers
Comment: @mplungjan - the point here is that the OP appears to be using numbers, not strings and isn't using `parseInt()` so the question is nonsense as posted.  Besides `alert(09)` still shows `9`.  As is, the question should be closed.
Comment: @jfriend00 we don't close questions for being confused. That is not a valid reason for closing.
Comment: @RobinGreen - the question makes no sense.  There is no leading zero on a numeric value (like in the OP's code)!  Thus, there can be no answer that removes it.  Look at the OP's line of code to illustrate `newValue = 01;`.  That's a numeric value.
Comment: @jfriend00 that is an excessively pedantic definition of "number", which is incorrect in many business contexts. I am talking about business domain concepts, not programming concepts.
Comment: @RobinGreen - Look at the OP's line of code: `newValue = 01;`.  That's a numeric value, plain and simple.  It has no leading zero once the JS parser has turned it into live JS.  Thus, there is no leading zero to remove from `newValue`.  There's nothing pedantic about it.  That's the OP's code.  And, the OP has had 13 hours of chances to change the question into one about removing leading zeroes from a string, but has not done so.
Comment: If you are suggesting that the question is actually asking about a non-problem, then as I said before, that is simply confusion on the part of the asker, which is not a valid reason to close in and of itself. Many legitimate SO questions arise from a confused understanding of something or other!
Comment: @RobinGreen - the reason I selected for voting to close is "Unclear what you're asking" which is a valid, listed reason for closing a question and in 13 hours the OP has not made it clear.  It is not clear whether they are confused about leading zeroes on numbers (what their code shows) or actually meant to ask about leading zeroes on strings (where a leading zero would actually occur).  If you can show me how it is "clear" what the OP is actually asking, I'd like you to do so.
Answer: Any number loses all leading 0 when it is used in any calculation
Live Demo
function num(n) { return +n }

Faster and shorter than parseInt(str,10)
Note that 08 and 09 are considered illegal octal numbers if the leading 0 is not removed.
Answer: parseInt(val, 10) will remove leading zeros.
Comment: Regex not necessary at all
Comment: Some more information about parseInt(string, radix). (You may want to check the part about the second parameter "radix") https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt


How many terms of the geometric sequence $2, 8, 32, 128,\dots $are required to give a sum of $174,762$?

Question:
How many terms of the geometric sequence $2, 8, 32, 128,\dots $are required to give a sum of $174,762$?

My attempt
$a = 2$ (the first term)
$r = 4$ (the common ratio)
$S_n = 174,762$ (sum to $n$ terms)
Using the formula
$$S_n=a\bigg(\frac{r^n-1}{r-1}\bigg)$$
Therefore
\begin{align*}
S_n&=2\bigg(\frac{4^n-1}{4-1}\bigg)\\[5pt]
S_n&=174,762\\[5pt]
  4^n-1&= \frac{174,762\cdot3}{2} \\[5pt]
  4^n &= 262,144 \\[5pt]
n &= \log_4(262,144) \\[5pt]
n & =\frac{\ln(262,144)}{\ln(4)}\\[5pt]
n &= \frac{12.476...}{1.386...} \\[5pt]
n & = 9
\end{align*}
There 9 terms are required. Is there a better way go about this? Is this process succinct?
Comment: For some reason you had $4_n$ where I would expect $4^n.$
Comment: Another way to find this (with software assistance) is to convert the number to binary:  $ \ 174762_{10} \ = \ 101010101010101010_2 \ \  . $  The numbers in the geometric sequence occupy the odd-powers-of-2 positions and there are nine  $ \ 1$'s , so nine terms are required. (I offer this only as a comment, since I don't think it merits being an "answer".)
Answer: Once you reach
$$
4^n = 262,144
$$
I would proceed with arithmetic, not logarithms. You know
$$
4^5 = 2^{10} = 1,024
$$
so
$$
4^{10} = 2^{20} \approx 1,000,000
$$
is nearly four times too big. So   $4^9 = 262,144$ and you need $9$ terms.
Comment: A variation of this that a computer-science person might use is that $ \ 2^{20} \ $ is a "Meg" ( $ \ 1M \ $ ) , so $ \ 2^{17} \ $ (one-eighth of a Meg) would be the highest power of $ \ 2 \ $ smaller than $ \ 174762 \ . $  So we count the odd-positive-integer exponents up to $ \ 17 \ \  . $
Answer: That is correct and it is a reasonable way to solve the problem. Of course you may add up the terms until you get to the answer due to fast growth of the terms.


A step in computing the cohomology ring of $\mathbb{C}P^n$

Question: On page 250 of Hatcher's Algebraic Topology, he uses a certain corollary to compute the cohomology ring of $\mathbb{C}P^n$. The relevant section is below for convenience:

I understand the proof except for his statement that once can deduce $H^{2i}(\mathbb{C}P^n)$ is generated by $\alpha^i$ for all $i<n$. The base case follows trivially from the induced isomorphism between $H^2(\mathbb{C}P^1)$ and $H^2(\mathbb{C}P^2)$. I tried working everything out after that, but in the end I arrive at $H^{2i} (\mathbb{C}P^n)$ is generated by $\alpha^i$ for all $i<n-1$, not $n$, as Hatcher says. I really don't see how one could use the fact that $H^2(\mathbb{C}P^2)$ is generated by $\alpha$ to show that $H^4(\mathbb{C}P^3)$ is generated by $\alpha^2$. How does one see this?
Answer: To take the example at the end of your question, the fact that $H^4(\mathbb CP^3)$ is generated by $\alpha^2$ is deduced from the fact (part of the induction hypothesis) that $H^4(\mathbb CP^2)$ is generated by $\alpha^2$.  That's why Hatcher first recalls that the inclusion of $\mathbb CP^2$ in $\mathbb CP^3$ induces an isomorphism of cohomology up to dimension $4$, so that the full result for $\mathbb CP^2$ (including $H^4$) is available when proving the result for $\mathbb CP^3$.  (Analogous comments apply for general $n$ in place of $3$.)
Comment: Thank you, I was being an idiot.


WiFi doesn't work with Compaq CQ58 (RALINK RT5390R)

Question: After going around all the forums looking for answers and help, having tested all I read on my circa-2012 Compaq CQ58 (with no success), I'm here to ask you help.
For days I installed versions and versions of Ubuntu and Lubuntu trying to make WiFi work well, but it doesn't. Currently I have installed Lubuntu 18.04 LTS (system requirements) and it doesn't work here either.
I will briefly explain the problem: when I turn on my PC the WiFi connects and for a minute the pages loads and everything goes very quickly but after a minute (or even less) despite the connection there is and despite I have Internet on my phone; on the computer it does not work anymore. The pages do not load and the WiFi tends to disconnect and change networks without being able to establish a connection, no longer allowing me to browse.
I thought it was a drivers problem and then I looked for the drivers for my WiFi module (Ralink RT5390R 802.11bgn PCIe), but I did not found them loadable for Linux... I found only for Windows and with all the codes that I found I had no results, often i've gotPL code errors and other problems.
Can you help me? I don't know what to do. If you need details let me know ...
i'm adding some outputs:
02:00.0 Network controller [0280]: Ralink corp. RT5390R 802.11bgn PCIe Wireless Network Adapter [1814:539b]
    Subsystem: Hewlett-Packard Company RT5390R 802.11bgn PCIe Wireless Network Adapter [103c:18ed]
    Kernel driver in use: rt2800pci
    Kernel modules: rt2800pci
03:00.0 Unassigned class [ff00]: Realtek Semiconductor Co., Ltd. RTS5229 PCI Express Card Reader [10ec:5229] (rev 01)
0: phy0: Wireless LAN
    Soft blocked: no
    Hard blocked: no

Linux leo-PC 5.3.0-51-generic #44~18.04.2-Ubuntu SMP Thu Apr 23 14:27:18 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

I've tried to set a static ip address but no changes.
Comment: Why are you using capslock?
Comment: Please [edit] your question and add output of `lspci -knn | grep Net -A3; rfkill list` terminal command.
Comment: 02:00.0 Network controller [0280]: Ralink corp. RT5390R 802.11bgn PCIe Wireless Network Adapter [1814:539b]
 Subsystem: Hewlett-Packard Company RT5390R 802.11bgn PCIe Wireless Network Adapter [103c:18ed]
 Kernel driver in use: rt2800pci
 Kernel modules: rt2800pci
03:00.0 Unassigned class [ff00]: Realtek Semiconductor Co., Ltd. RTS5229 PCI Express Card Reader [10ec:5229] (rev 01)
0: phy0: Wireless LAN
 Soft blocked: no
 Hard blocked: no
Comment: What is the kernel version? `uname -a`?
Comment: This looks to me as a hardrware issue. This is a very old device natively supported by Linux.
Comment: Try setting a static local IP address through network manager and also set the IP for your Ubuntu device in your router settings as well. This (bypassing dhcp and setting a static IP) will often solve the problem of an unresponsive network.
Comment: Linux leo-PC 5.3.0-51-generic #44~18.04.2-Ubuntu SMP Thu Apr 23 14:27:18 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
Comment: i've tried setting a static ip address but no changes
Answer: Maybe you can find your solution here:
After installing Ubuntu 20.04 the wifi card Ralink RT3090 does not see any wifi networks

Seems the kernel module for this WiFi chipset is available but not
loaded in Ubuntu 20.04. Load it and set it to load on boot using these
commands:
echo "options rt2800pci  nohwcrypt=1" | sudo tee /etc/modprobe.d/rt2800pci.conf
sudo modprobe -rfv rt2800pci
sudo modprobe -v rt2800pci

I have an ASUS X45C (Ralink corp. RT5390) running Ubuntu 20.04  and  seems it worked for me.
Answer: I've maybe the same problem. I have:
02:00.0 Network controller: Ralink corp. RT5390 [802.11 b/g/n 1T1R G-band PCI Express Single Chip]
    Subsystem: Hewlett-Packard Company Pavilion DM1Z-3000 PCIe wireless card
    Flags: bus master, fast devsel, latency 0, IRQ 17
    Memory at d0100000 (32-bit, non-prefetchable) [size=64K]
    Capabilities: [40] Power Management version 3
    Capabilities: [50] MSI: Enable- Count=1/32 Maskable- 64bit+
    Capabilities: [70] Express Endpoint, MSI 00
    Capabilities: [100] Advanced Error Reporting
    Capabilities: [140] Device Serial Number 00-00-9e-c4-b7-f9-55-ec
    Kernel driver in use: rt2800pci
    Kernel modules: rt2800pci

With linux-image-5.3.0-51-generic it don't work. It disconnect all the time.
With linux-image-5.3.0-28-generic it works fine.
Also works with all ubuntu kernels I've tested back to ubuntu 11.04 kernels.
Get this in syslog:
May 12 22:49:41 pluttis wpa_supplicant[1004]: wlan0: CTRL-EVENT-SIGNAL-CHANGE above=0 signal=-83 noise=9999 txrate=6500
May 12 22:49:45 pluttis wpa_supplicant[1004]: wlan0: SME: Trying to authenticate with 38:43:7d:60:f1:4e (SSID='JACn2G' freq=2412 MHz)
May 12 22:49:45 pluttis kernel: [  167.140512] wlan0: disconnect from AP 38:d5:47:1f:04:e0 for new auth to 38:43:7d:60:f1:4e
May 12 22:49:45 pluttis kernel: [  167.265794] wlan0: authenticate with 38:43:7d:60:f1:4e
May 12 22:49:45 pluttis kernel: [  167.268995] wlan0: send auth to 38:43:7d:60:f1:4e (try 1/3)
May 12 22:49:45 pluttis wpa_supplicant[1004]: wlan0: CTRL-EVENT-REGDOM-CHANGE init=CORE type=WORLD
May 12 22:49:45 pluttis NetworkManager[953]: <info>  [1589316585.2040] device (wlan0): supplicant interface state: completed -> authenticating
May 12 22:49:45 pluttis kernel: [  167.973741] wlan0: send auth to 38:43:7d:60:f1:4e (try 2/3)
May 12 22:49:46 pluttis kernel: [  168.956007] wlan0: send auth to 38:43:7d:60:f1:4e (try 3/3)
May 12 22:49:47 pluttis kernel: [  169.356777] wlan0: authentication with 38:43:7d:60:f1:4e timed out
May 12 22:49:47 pluttis NetworkManager[953]: <info>  [1589316587.3694] device (wlan0): supplicant interface state: authenticating -> disconnected
May 12 22:49:47 pluttis NetworkManager[953]: <info>  [1589316587.4700] device (wlan0): supplicant interface state: disconnected -> scanning
May 12 22:49:47 pluttis wpa_supplicant[1004]: wlan0: SME: Trying to authenticate with 38:d5:47:1f:04:e0 (SSID='JACn2G' freq=2462 MHz)
May 12 22:49:47 pluttis kernel: [  169.601817] wlan0: authenticate with 38:d5:47:1f:04:e0
May 12 22:49:47 pluttis kernel: [  169.724194] wlan0: send auth to 38:d5:47:1f:04:e0 (try 1/3)
May 12 22:49:47 pluttis NetworkManager[953]: <info>  [1589316587.6547] device (wlan0): supplicant interface state: scanning -> authenticating
May 12 22:49:48 pluttis kernel: [  170.981842] wlan0: send auth to 38:d5:47:1f:04:e0 (try 2/3)
May 12 22:49:49 pluttis kernel: [  171.783215] wlan0: send auth to 38:d5:47:1f:04:e0 (try 3/3)
May 12 22:49:50 pluttis kernel: [  172.965891] wlan0: authentication with 38:d5:47:1f:04:e0 timed out

Answer: I looked up your current kernel driver, and found this driver information page for it, which seems to list your device as being supported.
It recommends using the following command for updates (if you haven't tried it already).

# apt-get update && apt-get install firmware-ralink

The page for your rt2800pci kernel driver also said you should, "Configure your wireless interface as appropriate," using How to use a WiFi interface as a guide.
Based upon your devices issues, I would recommend taking a look at the connman package discussed in the how-to. It looks like connman can be used to automatically reconnect dropped connections for you.
Comment: i've tried the command but it says that is not possible to find the firmware railink
Comment: From the link, it's not clear how to adapt this to ubuntu 18.04 and whether it should work on it at all.


How to execute a generic SQL Command in C#?

Question: I am trying to write a Method that simply accepts a string which is an SQL Command and runs it against the pre-defined Database/Server ... This is what I have so far:
public class TSqlConnector : IDbConnector
{
    private readonly string _connectionString;

    public TSqlConnector(string conn)
    {
        _connectionString = conn;
    }
    public IEnumerable<object[]> ExecuteCommand(string query)
    {
        var res = new List<object[]>();
        try
        {
            using (SqlConnection sql = new SqlConnection(_connectionString))
            {
                sql.Open();
                SqlCommand cmd = new SqlCommand(query, sql);
                var reader = cmd.ExecuteReader();
                DataTable tbl = new DataTable();
                while (reader.Read())
                {
                    var dr = tbl.NewRow();
                    dr.ItemArray = new object[reader.FieldCount];
                    reader.GetValues(dr.ItemArray);
                    res.Add(dr.ItemArray);
                }

            }

            return res;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
            throw;
        }
    }
}

This code, however, gives me an error saying that

Input array is longer than the number of columns in this table.

I googled the error message, apparently I first have to define the DataTable's columns, using tbl.Add("ColumnName", typeof(type));
This however, completely undermines what I was trying to do - writing a generic version. All I wanted was some kind of construct which contains the information I would get from the SqlServer if I typed the same command into SSMS, I don't really care what hoops I have to jump through to read the data in C#; Using an object-Array for each row, having to manually cast each object into a string, int or whatever is perfectly acceptable, even a CSV-like string would be just fine
The only thing I don't want to do is add a definition for the table or a fixed amount of row. Each method that uses ExecuteCommand() will have to know what type of object-array is returned and that's fine but adding some complex data structure containing types and column names in addition to the SQL Commands seems like overkill.
Is there some easier way to achieve this?
Comment: If you ask me I would not do this. There are much better options like [dapper](https://github.com/StackExchange/Dapper) or [PetaPoco](https://github.com/CollaboratingPlatypus/PetaPoco)
Comment: Look into using a data adapter instead of a data reader.
Comment: You could use Entity Framework for example.
Btw. what output do you expect when `type` is something the database isn't supporting? E.g. an enum. `tbl.Add("ColumnName", typeof(MyColor));`
Comment: or even drop table or worse...  offering such can be very dangerous depending on how / where you expose this "feature"...
Comment: You're not taking this query from the user, I hope.
Comment: It is better practice to `yield return` when your method returns an Enumerable.
Comment: See the answer to this for automatically loading the datatable : https://stackoverflow.com/questions/18961938/populate-data-table-from-data-reader
Comment: @Crowcoder Using `yield return` is not really recommended for this scenario because of dangers leaving your connection open. In this scenario returning a list is probably better.
Comment: @Crowcoder You have a reference for that claim?
Comment: @KennethK. I don't have a reference handy at the moment, but I think one place you can find it is in one of Bill Wagner's Effective C# editions. One benefit is that you allow the caller to end an iteration without having to materialize the entire collection.
Comment: @FilipCordas there is no danger of open connections if the reader is inside a `using` (instead of the connection) with CommandBehavior.CloseConnection.
Comment: @Crowcoder using will only work if you iterate all the items. If you are doing skip, take, first. I am not saying it shouldn't be done but there is nothing wrong with using lists in this case if you are afraid of problems with yield.
Comment: @FilipCordas it is not true that `using` only works if you iterate all items. Good software is largely about good API etiquette and when I get an Enumerable I expect that it will yield return items. It is designed that way very intentionally so your code can be more efficient dealing with large collections or streams which is what a DataReader really exposes.
Answer: What you have is an IDataReader from your cmd.ExecuteReader();
To load the results into a DataTable, you can use the Load method as follows:
var reader = cmd.ExecuteReader();
DataTable tbl = new DataTable();
tbl.Load(reader);
// now tbl contains the corresponding columns and rows from your sql command.

// Then you can return the ItemArrays from each row;

return tbl.Rows.Cast<DataRow>().Select(row => row.ItemArray);

Comment: Sweet! I figured there had to be an easier way but could for the life of me not figure it out! Thank you!
Answer: I've used code like this to input a generic SQL query and return the results as a datatable. Of course, you'll have to parse out the results how you need them.
private DataTable QueryToTable(string sql, string cs)
{

    var ds = new DataSet();

    using (var adapter = new SqlDataAdapter(sql, cs))
    {
        adapter.Fill(ds);
    }

    return ds.Tables(0);
}


What size wire do I need for a 100amp underground 300 ft run?

Question: I want to put in a 100amp subpanel in my garage.  The run will be underground and 300ft long.
I have a Siemens panel with breakers rated at 60/75 deg C.
What is the proper wire size I need?  I was originally thinking I needed to put the wire in conduit, but is there a better way to go with a direct burial wire?
Comment: Only if you care about power quality.  300' of #3 uncoated copper @ 100 amperes, will have a voltage drop of 14.7 volts.  So if the panel is fully loaded (drawing 100 amperes), and you have 240 volts at the service equipment panel, you'll end up with 225.3 volts at the panel. And that's at the panel. You'll loose even more along the branch circuits. If the panel is only drawing 50% of the max (50 amperes), you'll only loose 7.35 volts. This is why load calculations are important, they allow you to figure out what wiring is required.
Comment: [This answer](http://diy.stackexchange.com/a/29077/33) might be helpful.
Comment: Yes, I read that post.  That is for 60 ft run, does the 300 ft in my case make a difference?
Comment: Without knowing more about the equipment that will be connected to the panel, it's difficult to give an accurate answer.
Comment: I used this [link](http://www.woodmagazine.com/woodworking-tips/techniques/outfitting-woodworking-shop/critical-questions-about-workshop-wiring/?page=4) to figure out the capacity of the panel.  Is this what you mean about load calculation?  The highest single amp draw i have is a welder 240v / 30 amps.  Simultaneous high draw tools is 23 amps (table saw + shop vac).  Continuous draw amps is 15 (lights).  The equation in the link gives me 76 amps and I bumped it up to 100.
Comment: If this is a simple one man shop, it's not likely you'll be welding while you cut things on the table saw.  The lights will always (or usually) be on while you're working, so you'll have to figure for that. However, for the most part, you won't be drawing anywhere near the 100 ampere capacity.  Which means you'll probably never have a problem using #3 conductors. If you often have helpers, and you'll be using the welder and table saw simultaneously. You might want to bump up the wire size, to reduce the voltage drop across the long wire run.
Comment: NEC **recommends** (but does not require) a maximum of 5% voltage drop from service to consumer. So you'll probably want to try and design the system to reduce voltage drop as much as possible.
Comment: ok, so you are saying the minimum I can use is #3 copper.  I'm confused by this because on table 310.15 [from this answer](http://diy.stackexchange.com/questions/29057/what-wire-gauge-do-i-need-for-a-100-amp-subpanel-at-the-end-of-a-60-wire-run/29077#29077) I have to use the temp rating of the conducter which is 60C for copper which says #3 is 85 amp max.
Comment: Ryan, don't forget, you CANNOT simply add up 240V and 120V amperages. This is a completely ambiguous number.
Comment: @Ryan you said the terminals are 60/75, so you can use the 75 column.
Comment: thank you for your help.  For the voltage drop, I used [southwest's calculator](http://www.southwire.com/support/voltage-drop-calculator.htm) which told me I need a 1awg copper line.
Answer: Old question, but it deserves a proper answer...
TL;DR Aluminum 1 AWG or possibly 1/0 if you expect consistent high usage, in 1-1/2" rigid metal conduit (6" burial depth) or 1-1/2" PVC schedule 40 (18" burial depth).
Panel size is listed as 100A. Based on comments of a load calculation of 76A, that would be correct. I am dubious about that (I expect it to be much lower), but let's assume it is correct for the moment, and use that as the value for voltage drop calculations. In addition, welder and at least some of the other key tools are 240V rather than 120V, so I'll use 240V for voltage drop calculations.
Note that you can (and generally should) use a 100A or larger panel as a subpanel, even if the feed is much smaller. For example, if you use a 90A feed breaker and 2 AWG aluminum wire, you can feed a 100A (or 200A!) panel. Larger capacity (current) panels are also larger capacity (spaces) panels, and you can always upgrade the feed wire and breaker if you use large enough conduit.
Minimum wire sizes (wires, not cables, 75 C rated) are 3 AWG copper and 1 AWG aluminum. For any significant distance, aluminum is almost always the better choice due to cost.
The Southwire Voltage Drop Calculator gives 4.46% for 3 AWG copper, 300', 240V, 76A and 4.61% for 1 AWG aluminum. Bumping up one size to 2 AWG copper gives 3.46% and to 1/0 aluminum gives 3.96%.
One thing that has changed quite a bit in the 9 years since this question was originally posted is electric vehicle supply equipment or EVSE, used to charge electric vehicles. If this garage is used as a garage and not just as a workshop then adding 20A - 30A @ 240V for electric charging is a common and reasonable thing to do. That could take a workshop garage from a much smaller real-world load - perhaps 40A - up to 60A - 70A or possibly more. Which in my opinion turns the 76A number from a way too high value to something quite reasonable.
Definitely go with conduit. Buried cable, which must be properly burial rated - you can't throw ordinary Romex in a trench - has to be 24" underground. PVC conduit only needs 18" and rigid metal conduit needs only 6", except under driveways. For a short distance this makes rigid metal conduit a very good deal as you can dig the trench easily by hand. For a 300' installation it may not matter so much because it will pay to rent equipment to get the job done in a day. But I would definitely trust PVC conduit in the long term much more than buried cable.
Conduit size will vary. A quick calculation on Southwire's site shows that 1-1/2" PVC 40 or Rigid Metal Conduit will do fine. You may be able to use a slightly smaller size, but a larger size will allow for 1/0 so if you start with 1 AWG and later need to upgrade you can do that.
Answer: So for anyone finding this page, none of the answers are incorrect or be qualified electrician. please for any electric services needed find and ask a qualified electrician.
Basically the breaker size protects the wire, So the breaker should not be higher amperage than the wire rating, however can over size the wire to meet voltage drop requirements. load calculations are for what minimum size panel/service needed but not the actual service rating if the breaker from the service side is a 100amp breaker feeding this then wire rated for 100 amp, etc. Most ampacity charts are up to 100 feet and go up one size of additional 100 feet. So, if using a 100amp breaker at the service side, then need to minimally size the wire accordingly and there are different rating for non burial, burial and in conduit  Aluminum sizes will be larger than copper. For that service would use URD Aluminum 4 conductor cable (need 2 hot, neutral and should have separate ground to shop, grounds isolated from neutrals in shop panel. for 300 feet for 100 amp rated service I would use Aluminum direct burial 1/0-1/0-1/0-1/0, the forth can be as low as #4 for the ground (but also in conduit, even if in conduit must still be rated underground wire and required by code also) Also note the size wire the breaker can handle, cannot cut strands to make fit, no no no, so check the breaker specs first. So if not really needing full 100 amp load, can go down smaller wires sizes, but use smaller breaker to meet the maximum amperage rating for that wire. so for example could use a popular 2-2-2-4 URD Aluminum direct burial wire, but would only use a 60 amp breaker for that distance, 80 amp if needed but could experience some voltage drop at high load, bad for running motors any length of time. Copper would allow smaller wire size, bigger wire still fit into breaker but is way more expensive. best to google look at a few wire size charts better contact an actual qualified electrician.


How do CUDA threads know which piece of data they should work on?

Question: As far as I understand, CUDA kernels are executed in parallel by many threads on the GPU.
Each thread executes the same kernel code. I.e., the kernel code is not copied.
Each thread operates on a different piece of data. I.e., before starting to work on data, the threads already know which data they should work on.
My question is, How do threads know which piece of data they should operate on?
Comment: There are special variables/registers `threadIdx` and `blockIdx` that allow the programmer to calculate an unique index for each thread that can then be used to access memory. I.e. there is no magic, the programmer needs to "tell" the threads what data to work on.
Comment: Yes, if you don't use these indices every thread or every block will really just do the same operation on the same data which would be a waste.
Comment: See [CUDA C++ Programming Guide - Programming Model - Thread Hierarchy](https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#thread-hierarchy)
Answer:
My question is, How do threads know which piece of data they should operate on?

They don't.
It is your job as the programmer to devise a scheme to divide whatever data-parallel task you have amongst the threads you choose to launch to execute that task in parallel. As you must now be aware, the CUDA execution model provide a simple, logical numbering system for threads within a block, and blocks within a grid, from which you can construct a scheme to assist you in assigning unique parallel work tasks to individual threads or groups of threads.
NVIDIA also provide additional levels of abstraction to program groups of threads to operate cooperatively, and various domain specific libraries which can implement parallel algorithm primitives and linear algebra operations at different levels of granularity within a running kernel.
Comment: @user366312: if you find that a comment is inappropriate, then best to flag it for moderation and then ignore it. Please don't make the situation worse by posting a comment that is even *more* inappropriate and here, verging on racism.
Comment: @user366312: then best of luck on your journeys


CSS Simple Thing doesn't seem to work

Question: I have the following CSS code:
.special {
    height: 20px;
    width: 125px;
    border-bottom: 0px #69D2E7;
    border-radius: 10px 10px 0px 0px;
    background-color: #69D2E7;
    text-align: center;
    color: #FFFFFF;
    font-family:"Arial Narrow",Arial,Helvetica,sans-serif;
    font-size:10px;
    font-weight:normal;
    letter-spacing:1px;
    opacity: 0.5;
    transition-property: opacity;
    transition-duration: 500ms;
    text-transform: uppercase;
    right: 0px;
    position: fixed;
    bottom: 0px;
    z-index: 6969;
}

.special:hover {
    tranisition: opacity 500ms, border-bottom 500ms;
    opacity: 1.5;
    border-bottom: 200px #69D2E7;
}

I'm trying to make it so when hovered, it gets bigger (border-bottom height increases), and opacity changes. Opacity does, with the element I have, but the height doesn't increase. What am I doing wrong ?
http://jsfiddle.net/7U3xn/
Here's an example to see how it works.
Answer: You need to add a border-style. For instance, you can use solid:
UPDATED EXAMPLE HERE
.special:hover {
    transition: opacity 500ms, border-bottom 500ms;
    opacity: 1.5;
    border-bottom: 200px solid #69D2E7;
}

Also, fix the typo as MarcB points out. It should be transition not tranisition.
Answer: tranisition: opacity 500ms, border-bottom 500ms;
   ^^---typo

Syntax errors in CSS blocks kill the rest of the css directives BELOW the error. If you'd bothered looking at your browser's developer console (e.g. shift-ctrl-J) in Firefox, you'd have seen the CSS error...

CSS Simple Thing doesn't seem to work


Filter Nested Array with Same Item That Contain Higest Value

Question: How can i filter this array base on same 'a', and max 'value' in 'a'
   data = [
             {a: 1, value: 12}, {a: 11, value: 39}, {a: 11, value: 150},
             {a: 2, value: 15}, {a: 22, value: 83}, {a: 222, value: 12},
             {a: 3, value: 55}, {a: 33, value: 9}, {a: 33, value: 1}
           ]

to become
data = [
         {a: 1, value: 12}, {a: 11, value: 150},
         {a: 2, value: 15}, {a: 22, value: 83}, {a: 222, value: 12},
         {a: 3, value: 55}, {a: 33, value: 9},
       ]

i have planty of nasted object array, i cant filter it, same id with diferent value i just want to show the higest on it
Answer: You could store the index of the result set in a hash table and check if the actual value is greater, then take the actual object as result.

var data = [{ a: 1, value: 12 }, { a: 11, value: 39 }, { a: 11, value: 150 }, { a: 2, value: 15 }, { a: 22, value: 83 }, { a: 222, value: 12 }, { a: 3, value: 55 }, { a: 33, value: 9 }, { a: 33, value: 1 }],
    hash = Object.create(null),
    result = [];

data.forEach(function (o) {
    if (!(o.a in hash)) {
        hash[o.a] = result.push(o) - 1;
        return;
    }
    if (result[hash[o.a]].value < o.value) {
        result[hash[o.a]] = o;
    }
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }