Does Pierre stay dead if I kill him?

Question: Throughout most levels, you may come across a guard named Pierre who is writing a message to his mother (or in one of them, a girl writing to a friend about how all this guy Pierre can talk about is fish and cheese). As a running gag, it's pretty effective. However, since Pierre is, after all, a guard, he is at odds with the thieving crew, and can become antagonistic to the crew if they catch his attention.
This leads to the logical conclusion that one may, if carrying a weapon, kill Pierre.
He appears in new levels thanks to the thieves' actions, which cause him to be fired from his current job, so it's possible he might disappear or be replaced if killed. Then again, guards seem to be able to revive their own through some magic grisly process I don't understand (or care to).
So, in the campaign, if you kill Pierre, does he show up in later levels to write more messages?
Comment: Wouldn't it be faster to check this yourself ? I am almost 100% sure that he would still appear because death is not permanents for the guards in Monaco.
Answer: Death is a temporary state in Monaco.
As you mentioned, guards can revive other guards, just as players can revive other players in multiplayer mode. Even in singleplayer mode, if all four characters die, "justice is served", which means they get arrested, not killed (there is no death penalty in Monaco, since its abolition in 1962, the year of the last exectution was 1847).

Does Pierre stay dead if I kill him?


(The number of) embeddings of an algebraic extension of $\mathbb{Q}$ into $\mathbb{C}$

Question: While reading a book (Neukirch) I came upon the claim that for an algebraic extension $K/\mathbb{Q}$ of degree $n$ there are $n$ embeddings of $K$ into $\mathbb{C}$. Why is it so, and in general how do such embeddings "look"?
Answer: Here's a short anwser. The Primitive element theorem tells you that $K/\mathbb{Q}$ is generated by a single element: $K = \mathbb{Q}(\alpha) = \mathbb{Q}[X]/(P)$ where $P$ is the minimal polynomial of $\alpha$.
Now like any irreductible polynomial over $\mathbb{Q}$, $P$ has $n = [K:\mathbb{Q}]$ distinct roots in $\mathbb{C}$ (because it is prime to its derivative $P'$). Let $\alpha_1,\ldots,\alpha_n$ be these roots. Then you get $n$ distinct embeddings $\sigma_i: K = \mathbb{Q}[X]/(P) \hookrightarrow \mathbb{C}$, $X \mapsto \alpha_i$. And obviously there can't be more since the image of $X$ has to be a root of $P$.
I should mention that all of this remains true for any finite extension $K/F$ that is separable (meaning that the minimal polynomials of elements $x\in K$ have distinct roots in $\bar{F}$.)
Comment: Just a note for myself and future readers, finite extensions of rationals are separable and that is why one can use PET
Answer: If $K/\mathbb{Q}$ is of degree $n$, then by the Primitive Element Theorem there exists $\alpha\in K$ such that $K=\mathbb{Q}(\alpha)$; the irreducible polynomial of $\alpha$ over $\mathbb{Q}$ has degree $[K:\mathbb{Q}]=n$. Thus, it is of the form
$$f(x) = x^n + a_{n-1}x^{n-1}+\cdots + a_1x + a_0, \qquad a_i\in\mathbb{Q}$$
and every element of $K$ can be written uniquely as
$$ \beta_0 + \beta_1\alpha + \beta_2\alpha^2+\cdots + \beta_{n-1}\alpha^{n-1}$$
for some $\beta_0,\ldots,\beta_{n-1}\in\mathbb{Q}$.
Let $\rho_1,\rho_2,\ldots,\rho_n$ be the $n$ distinct complex roots of $f(x)$ in $\mathbb{C}$ (distinct since irreducible polynomials over $\mathbb{Q}$ are always square free). Then for each $j$, you have an embedding $\iota_j\colon K\to\mathbb{C}$ obtained by mapping $\mathbb{Q}$ to itself, and $\alpha$ to $\rho_j$; i.e.,
$$\iota_j(\beta_0 + \beta_1\alpha + \beta_2\alpha^2+\cdots + \beta_{n-1}\alpha^{n-1}) = \beta_0 + \beta_1\rho_j + \beta_2\rho_j^2+\cdots + \beta_{n-1}\rho_j^{n-1}.$$
For example, the two embeddings of $\mathbb{Q}(\sqrt{2})$ into $\mathbb{C}$ are given by (i) sending $a+b\sqrt{2}$ to $a+b\sqrt{2}\in\mathbb{C}$; and (ii) sending $a+b\sqrt{2}$ to $a-b\sqrt{2}\in\mathbb{C}$; since the two roots of $x^2-2$ are $\sqrt{2}$ and $-\sqrt{2}$.
Since an embedding from $K$ to $\mathbb{C}$ is completely determined by what happens to $\alpha$, and the image of $\alpha$ must be a complex root of $f(x)$, the $n$ embeddings described above are all the embeddings of $K$ into $\mathbb{C}$.


Rails3 + Drag & Drop + multiple file upload

Question: I'm looking for the best practice of uploading multiple files with drag and drop function on a Rails (3.2.8) app.
I'm considering using the following libraries/gems:
Gems

carrierwave
paperclip

JavaScript

jQuery File Upload
Uploadify
Plupload
jQuery Multiple File Upload Plugin v1.48 (2012-07-19)
valums/file-uploader

What is the best/simplest combination?
Answer: If you want to upload directly to Amazon S3, you can use s3_direct_upload gem which uses jQuery File Upload. It's pretty simple to implement.


Complex polynomials vanishing at all real points

Question: Suppose $f \in \mathbb C[X_1,\ldots,X_n]$ is a complex polynomial in $n$ variables such that $f(P) = 0$ for all $P \in \mathbb R^n$. Is then necessarily $f = 0$?
This is certainly true for $n=1$ as a univariate polynomial that vanishes in infinitely many points is the zero polynomial. However, this argument does not immediately generalize to the case $n > 1$,  e.g. $f(X,Y) = X-Y$ has infinitely many zeroes but is not the zero polynomial.
Answer: Induct on $n$.  As you said, it's true for $n=1$.  For the induction step, write $f(X_1,\ldots, X_n) = \sum_{j=0}^d f_j(X_2,\ldots,X_n) X_1^j$ where $f_j(X_2,\ldots,X_n)$ is a polynomial.  If $x_1,\ldots,x_n$ are all real we have $\sum_{j=0}^d f_j(x_2,\ldots,x_n) x_1^j = 0$, which by the $n=1$ case implies $f_j(x_2,\ldots,x_n) = 0$.  Then use the induction hypothesis to get $f_j(X_2,\ldots,X_n) = 0$.


Argparse - How to Specify a Default Subcommand

Question: I am using the argparse package of Python 2.7 to write some option-parsing logic for a command-line tool. The tool should accept one of the following arguments:
"ON": Turn a function on.
"OFF": Turn a function off.
[No arguments provided]: Echo the current state of the function.
Looking at the argparse documentation led me to believe that I wanted two--possibly three--subcommands to be defined, since these three states are mutually exclusive and represent different conceptual activities.  This is my current attempt at the code:
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
parser.set_defaults(func=print_state) # I think this line is wrong.

parser_on = subparsers.add_parser('ON')
parser_on.set_defaults(func=set_state, newstate='ON')

parser_off = subparsers.add_parser('OFF')
parser_off.set_defaults(func=set_state, newstate='OFF')

args = parser.parse_args()

if(args.func == set_state):
    set_state(args.newstate)
elif(args.func == print_state):
    print_state()
else:
    args.func() # Catchall in case I add more functions later

I was under the impression that if I provided 0 arguments, the main parser would set func=print_state, and if I provided 1 argument, the main parser would use the appropriate subcommand's defaults and call func=set_state.  Instead, I get the following error with 0 arguments:
usage: cvsSecure.py [-h] {ON,OFF} ...
cvsSecure.py: error: too few arguments

And if I provide "OFF" or "ON", print_state gets called instead of set_state.  If I comment out the parser.set_defaults line, set_state is called correctly.
I'm a journeyman-level programmer, but a rank beginner to Python. Any suggestions about how I can get this working?
Edit: Another reason I was looking at subcommands was a potential fourth function that I am considering for the future:
"FORCE txtval": Set the function's state to txtval.
Answer: The defaults of the top-level parser override the defaults on the sub-parsers, so setting the default value of func on the sub-parsers is ignored, but the value of newstate from the sub-parser defaults is correct.
I don't think you want to use subcommands. Subcommands are used when the available options and positional arguments change depending on which subcommand is chosen. However, you have no other options or positional arguments.
The following code seems to do what you require:
import argparse

def print_state():
    print "Print state"

def set_state(s):
    print "Setting state to " + s

parser = argparse.ArgumentParser()
parser.add_argument('state', choices = ['ON', 'OFF'], nargs='?')

args = parser.parse_args()

if args.state is None:
    print_state()
elif args.state in ('ON', 'OFF'):
    set_state(args.state)

Note the optional parameters to parser.add_argument. The "choices" parameter specifies the allowable options, while setting "nargs" to "?" specifies that 1 argument should be consumed if available, otherwise none should be consumed.
Edit: If you want to add a FORCE command with an argument and have separate help text for the ON and OFF command then you do need to use subcommands. Unfortunately there doesn't seem to be a way of specifying a default subcommand. However, you can work around the problem by checking for an empty argument list and supplying your own. Here's some sample code illustrating what I mean:
import argparse
import sys

def print_state(ignored):
    print "Print state"

def set_state(s):
    print "Setting state to " + s

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
on = subparsers.add_parser('ON', help = 'On help here.')
on.set_defaults(func = set_state, newstate = 'ON')
off = subparsers.add_parser('OFF', help = 'Off help here.')
off.set_defaults(func = set_state, newstate = 'OFF')
prt = subparsers.add_parser('PRINT')
prt.set_defaults(func = print_state, newstate = 'N/A')
force = subparsers.add_parser('FORCE' , help = 'Force help here.')
force.add_argument('newstate', choices = [ 'ON', 'OFF' ])
force.set_defaults(func = set_state)

if (len(sys.argv) < 2):
    args = parser.parse_args(['PRINT'])
else:
    args = parser.parse_args(sys.argv[1:])

args.func(args.newstate)

Comment: No the above solution does not allow separate help text for 'ON' and 'OFF' and a 'FORCE' command with an argument won't work with the above solution. I'll add another answer with a workaround in a moment.
Comment: A couple questions. 1) Will I be able to provide separate help text for 'ON' and 'OFF' in the usage statement? 2) I'm considering adding a fourth option, which takes an additional argument: "FORCE txtval". Is this doable in the current solution?
Comment: Thanks, the if/else statement with `if (len(sys.argv) < 2):` did  the trick! However, it will ignore the rest of the arguments now. Let's say you wanto to run the script without command, resulting to 'PRINT'. But you want also provide the --newstate as well.
Answer: There are two problems with your approach.
First you probably already noticed that newstate is not some sub_value of the sub parser and needs to be addressed at the top level of args as args.newstate. That should explain that assigning a default to newstate twice will result in the first value being overwritten. Whether you call your programm with 'ON' or 'OFF' as a parameter, each time set_state() will be called with OFF. If you just want to be able to do python cvsSecure ON and
python cvsSecure OFF the following would work:
from __future__ import print_function

import sys
import argparse

def set_state(state):
    print("set_state", state)

def do_on(args):
    set_state('ON')

def do_off(args):
    set_state('OFF')

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()

parser_on = subparsers.add_parser('ON')
parser_on.set_defaults(func=do_on)
parser_on.add_argument('--fast', action='store_true')
parser_off = subparsers.add_parser('OFF')
parser_off.set_defaults(func=do_off)

args = parser.parse_args()
args.func(args)

The second problem is that argparse does handle subparsers as single value arguments, so you have to specify one before invoking parser.parse_args(). You can automate insertion of a lacking argument by adding a extra subparser 'PRINT' and automatically inserting
that using set_default_subparser added to argparse.ArgumentParser() (that code is part
of the package ruamel.std.argparse
from __future__ import print_function

import sys
import argparse

def set_default_subparser(self, name, args=None):
    """default subparser selection. Call after setup, just before parse_args()
    name: is the name of the subparser to call by default
    args: if set is the argument list handed to parse_args()

    , tested with 2.7, 3.2, 3.3, 3.4
    it works with 2.6 assuming argparse is installed
    """
    subparser_found = False
    for arg in sys.argv[1:]:
        if arg in ['-h', '--help']:  # global help if no subparser
            break
    else:
        for x in self._subparsers._actions:
            if not isinstance(x, argparse._SubParsersAction):
                continue
            for sp_name in x._name_parser_map.keys():
                if sp_name in sys.argv[1:]:
                    subparser_found = True
        if not subparser_found:
            # insert default in first position, this implies no
            # global options without a sub_parsers specified
            if args is None:
                sys.argv.insert(1, name)
            else:
                args.insert(0, name)

argparse.ArgumentParser.set_default_subparser = set_default_subparser

def print_state(args):
    print("print_state")

def set_state(state):
    print("set_state", state)

def do_on(args):
    set_state('ON')

def do_off(args):
    set_state('OFF')

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()

parser_print = subparsers.add_parser('PRINT', help='default action')
parser_print.set_defaults(func=print_state)
parser_on = subparsers.add_parser('ON')
parser_on.set_defaults(func=do_on)
parser_on.add_argument('--fast', action='store_true')
parser_off = subparsers.add_parser('OFF')
parser_off.set_defaults(func=do_off)

parser.set_default_subparser('PRINT')

args = parser.parse_args()
args.func(args)

You don't need to handle in args to do_on(), etc., but it comes in handy if you start specifying options to the different subparsers.


Most efficient way to add menu items to a tableViewCell

Question: I'm creating an food menu app in Xcode using Swift and I am trying to find the most appropriate way to code the food information for my prototype cell to display.  Each foodItem will have 3 attributes associated with it: the name of the food, a description of the food, and a price.  Would it be best to create a Food object from a class, add them all to an array, and iterate through the array using the indexPath? Do the exact same thing but with a struct (what I'm leaning towards), or even add the food items to a tuple and iterate over that? Each scene will be responsible for displaying around 20 foodItem cells.  There will be 5 scenes: Breakfast, Lunch, Dinner, Dessert, Beverages.
Comment: I don't know why you are saying "iterate". To display the data you don't iterate directly, you simply return the cell requested in `cellForRowAtIndexPath`. It isn't really a question of efficiciency either, but usability. All 3 methods will involve memory access and an array, so equivalent access overhead. If you don't need additional methods the a struct is ok although structure are passed by value so you need to factor that in. If you need to pass by reference or you need additional methods then a class is needed.
Comment: If you are not using CoreData and can use structs, then I would suggest that. Then your data is immutable and in a way safer to use. Safer in that it won't change on you in unexpected ways  at unexpected times due to Swift's value type semantics.
Answer: I think you could do outlets for the table view cell labels. These outlets have to be stored in a subclass of UITableViewCell.
Then you should make a class for the food with the properties you need.  Then implement UITableViewDataSource and UITableViewDelegate in your view controller. All the food items you could 'pack' into an array. Then in tableView_:cellForRowAtIndexPath: you can do:
let cell = tableView.dequeueReusableCellWithIdentifier("identifier", forIndexPath: indexPath) as YourCustomCell
    if cell == nil {
        cell = UITableViewCell(style: .Default, reuseIdentifier: "reuseIdentifier")
    }
cell.foodName = "noodles"
cell.foodPrice = "12,95$"


How to save Shift + PrintScr Screenshots to Desktop automatically?

Question: I frequently use Screenshot tools which automatically get invoked by keyboard shortcut Shift + PrintScr. I have changed that keyboard shortcut to Shift + F1 because F9 to Program keys of my 4-5 years old Kinesis advantage keyboard have a circuit trouble.
Anyway, now these screenshots gets automatically saved to my Home folder. I want to change that to automatically save to Desktop.
Automatically saving to Desktop give me opportunity to Trash useless screenshots on start-up at-least everyday.
Thanks..
Answer: If you are using gnome-sccreenshot, you can set the default 'save-to' directory with dconf or gsettings.
# gsettings set org.gnome.gnome-screenshot auto-save-directory "[path-to-directory]"

MyDesktopFolder=$(xdg-user-dir DESKTOP)
gsettings set org.gnome.gnome-screenshot auto-save-directory "$MyDesktopFolder"

Then restart gnome shell
Alt+F2 and type r then ↵.
Comment: I have done it using dconf editor org -> gnome -> gnome-screenshot -> auto-save-directory Current value '/home/neo/Desktop' but it still save screenshots in /home/neo.
Comment: did you restart gnome ?
Comment: No, can you please include that in your answer?
Comment: @GauravAgarwal : Edit done


How to use Jmock to produce mock Json request?

Question: In our code we get Json object from ActiveMQ and then decide action and other parameter for action and then return Json object to ActiveMQ. To unit test we have to mock Json object request.
Comment: What do you want to test? The json parsing or action decision?
Comment: We want to test action decision.
Answer: What about mock action instead?
<code>@Mock private Action action;

private ActionDispather subject = new ActionDispather(action);

@Test public void doAction1GivenSomeStateIsTrue() throws Throwable {
    final Message message = new Message();
    message.setState(true);
    //message (json object in your case) population is omitted

    context.checking(new Expectations() {
        {
             oneOf(action).doAction1();
        }
    });

    subject.on(message);
}

@Test public void doAction2GivenSomeStateIsFalse() throws Throwable {
    final Message message = new Message();
    message.setState(false);
    //message (json object in your case) population is omitted

    context.checking(new Expectations() {
        {
             oneOf(action).doAction2();
        }
    });

    subject.on(message);
}
</code>
The json parsing could be handled in Consumer, therefore the action decision test is json agnostic.
<code>public class Consumer {
    private ActionDispatcher dispatcher;

    public void on(ActiveMQMessage message) {
         Message m = convertFrom(message);
         dispatcher.on(m);
    }
}
</code>
Anyway, mock behavior not data.


Massive problem with unusable computer need help immediately

Question: Ubuntu 18.04
I was trying to go from a gnome flashback session to an xfce one to see if it might be better to run a resource intensive game. I logged out and logged into the xfce and all that has happened is a grey screen with a movable cursor, but nothing else.
I cannot logout. I cannot start the xfce from ctrl-alt-f3 tty3 session. I cannot get into a tty 1 session. I have followed several ideas on this site and a couple of others to no avail.
I can get into a basic gnome session with startx, but as soon as I try to do anything via terminal, I get the message that things like -pkill are not installed (one of the things I was trying), and I cannot install anything. When I logout from that 800x600 session, it goes right back to the tty3 screen.
How do I get into the login screen so I can choose another known working desktop? I really need help ASAP.
Thank you.
Comment: Have you restarted the Display Manager?

i.e., sudo systemctl restart lightdm

or sudo systemctl restart gdm
Comment: I was (somehow) able to get the xfce desktop to show, albeit quite broken. I think I had no network, which is why I could not install things. As for the pkill situation, once I was able to logout and log back into a gnome session properly, pkill is there along with everything else.

Must have been some weird glitch in the matrix.
Answer: I was able to get back to the xfce desktop after reinstalling the kernel headers. I know I did not touch anything like that, so weird. After the reinstall, I simply logged out of the tty session and got to the desktop. Not everything was working, but I was able to logout and get to the gdm screen. Logged into a known working gnome desktop and everything seems fine.
I would suggest that when using autoremove via terminal, pay close attention to what is being removed. I think this might be what happened.
Comment: In your question, you never mentioned autoremove.
Comment: @OrganicMarble - I did not mention it in my OP because I only thought about it after I got things back to normal.
Comment: Sometimes when installing different desktops, they do not play nice together.  Should try using a VM or even installing a separate dual boot to play around with installing extra desktops.
Comment: The autoremove is a repeat of the message that occurs when you `apt install|remove` packages (with install it's because they are listed as being removed because of clashes with newer packages).  This first warning is what you should taken notice of; the `autoremove` step was the last second chance. You shouldn't use add `apt -y install` unless you are sure about what's going to occur....  That "y" answer to the remove was your authorization to remove the packages...
Comment: @guiverc - you are absolutely correct.
Comment: @crip659 - good idea. Although I have never had an issue with switching desktops in the dozen or so years I've been using Linux. But a VM is something to think about.


Isn't $\bigcap_{i=1}^5 A_i=A_5$ where $A_i=\{x \mid x \in \mathbb{N},0 \le x \le \frac{1}{n}\}$

Question: If $A_i=\{x \mid x \in \mathbb{N},0 \le x \le \frac{1}{n}\}$ where $n \in \mathbb{N}$. which one is correct?(Note that $0 \notin \mathbb{N}$)

1.$\bigcup_{i=1}^n A_i=A_1$
2.$\bigcap_{i=1}^5 A_i=A_5$
3.$\bigcap_{i=1}^{\infty} A_i=\{0\}$
4.All three are correct.

It is easy to say that the first one is correct.Also the book gave the answer $1$.Also It is easy to say $3$ is wrong.But what about $2$ isn't it correct?I think it is correct because $\bigcap_{i=1}^5 A_i=\varnothing$ and also $A_5=\varnothing$.What's your idea?
Answer: I assume you mean $A_i=\{x\in\mathbb{N}: 0\leqslant x\leqslant\frac{1}{i}\}$, otherwise your definition makes no sence. If so, then $A_i=\{0\}$ for $i\geqslant 2$, and $A_1=\{0,1\}$. Using this, it follows easily that 1 is false for $n\neq 1$, while (2) and (3) are true. Interestingly, this is also true if we replace the $x\in\mathbb{N}$ by $x\in\mathbb{Q}$ or $x\in\mathbb{R}$.
EDIT: I didn't notice $0\notin\mathbb{N}$ for this question. In that case we find that $A_i=\emptyset$ for $i\geqslant 2$, and $A_1=\{1\}$. So only (2) is true.
EDIT 2: Now (1) has edited from $\bigcup_{i=1}^n A_i=A_i$ into $\bigcup_{i=1}^n A_i=A_1$, this is correct as well.
Comment: I told that zero isn't a natural number.
Comment: note that I am not who give downvote.
Comment: Fixed it now. Always very confusing when $0$ is left out.
Comment: Excuse me I wrote the first one wrong.Now I think both is correct.


Unexpected behavior of g++ -MG flag

Question: I have main.cpp file for which I want to generate dependency file main.d (to be included in Makefile).
I'm calling g++ -MM -MF src/main.d -MP -MT src/main.o src/main.cpp. It works fine unless I have some source generator. I found -MG flag for this, but it doesn't work as I expected it to work.
For example: main.cpp includes module/mod.h (#include "module/mod.h") and mod.h includes generator/gen.h (#include "generator/gen.h"), gen.h is generated. There is following structure:
-Makefile
-src
--main.cpp
--module
---mod.h
---generator
----gen.h

In Makefile I have a rule to generate src/module/generator/gen.h.
Generated by g++ dependencies for existing files are correct:
src/main.o: src/module/mod.h

But for non-existing file gen.h dependency is just generator/gen.h.
If I generate this file before generating dependencies it is correct src/module/generator/gen.h.
Is there any other option for g++ to correctly generate dependencies for non-existing files?
main.d generated when gen.h doesn't exist:
src/main.o: src/module/mod.h generator/gen.h

Correct main.d generated when gen.h exist:
src/main.o: src/module/mod.h src/module/generator/gen.h

Answer: As stated in man gcc

The dependency filename is taken directly from the "#include" directive without prepending path

actually there's no way for gcc to know the real path.
I'd recommend you to fix the include statement to keep include path in sync with make path, i.e. white in mod.h
#include <module/generator/gen.h>

put Makefile to src and add proper -I flag to gcc, e.g.
SRCDIR := $(shell pwd)
CXXFLAGS += -I$(SRCDIR)

it is a good practice to always start all non-local includes from some 'source root'
Comment: Why there is no way to know the real path? If in file from directory "a/b/c" is `#include "d/e.h"` file `e.h` is in `a/b/c/d/e` directory? So it is pretty easy to determine full path for `""` include.
Comment: thats becaus of -I (or -iquote) switches -- you can have 10 directories to be scanned for include file and unless file exists it's not possible to say for sure
Comment: I'd recommend you to try cmake. I dont like it but it solves this particular problem - you'll provide the name explicitly threre
Comment: OK, I always thought that -I is for <...> includes.
Comment: Just to clarify subtleties of <..> and ".." for history -- both <...> and "..." search paths are set with -I, while only "..." search path is set by rarely met -iquote. <..> include system include folders (like /usr/include) while ".." includes directory where including source file resides

Unexpected behavior of g++ -MG flag


Trouble Installing AMD r9 380 GPU Pro driver in Ubuntu 16.10

Question: I am trying to install the AMDGPU Pro driver in Ubuntu 16.10. When i try to start the install script i get /etc/os-release: line 3: OS: command not found. I have tried several ways to get the driver to install ,it just will not do it. Any thoughts?
Answer: At this time, AMDGPU-Pro drivers only support Ubuntu 16.04 64-bit (kernel Linux 4.4): http://support.amd.com/en-us/kb-articles/Pages/AMDGPU-PRO-Driver-for-Linux-Release-Notes.aspx
If you need this "hybrid" driver, you have to install Xenial instead of Yakkety


How to properly clear TextField on submit in SwiftUI?

Question: I want to log some text and clear the TextField after submitting without changing the value of the logged text. How I can achieve that?
Here's example of my code:
@State private var loggedText: String = ""
@State private var showLoggedText = false

var body: some View {

    VStack {

        if showLoggedText {
            Text(loggedText)
        }

            HStack {
                TextField(
                       "Add new set",
                       text: $loggedText
                   )
                .onSubmit {
                    showLoggedText = true
                    loggedText = ""
                }
            }
    }

Comment: You need to assign the value of loggedText to another property. On Submit you override the value with an empty string
Answer: Going off one of the comments. It seems as though that you need to assign loggedText to another variable like so:
@State private var loggedText: String = ""
@State private var showLoggedText = false

var body: some View {

    VStack {

        if showLoggedText {
            Text(loggedText)
        }

            HStack {
                TextField(
                       "Add new set",
                       text: $loggedText
                   )
                .onSubmit {
                    showLoggedText = true
                    newText = loggedText
                }
            }
    }

This will allow you to submit the text without it being cleared. The  loggedText = "" clears everything that you had. Keep in mind that this code won't "lock" whatever's in loggedText. If you change the field after submitting. The text will be updated again.


Find the Selector of a Class method

Question: I'm quite a newbie in Objective C, though I have some background in Java reflection.
Here, I have a classic class method findAll that find all the domain objects from the database. The class Univers directly inherits from DomainObject
@interface DomainObject : NSObject

  - (NSString *) execute : (NSString*) method  withJson:(NSString*)json;
  + (NSString*)findAll: (NSString*)json;

@end

@implementation DomainObject

  - (NSString *) execute: (NSString*) method  withJson:(NSString*)json{

      method = [NSString stringWithFormat:@"%@%@", method, @":"];
      //method is 'findAll:'
      NSString* result =  [ self performSelector:
          NSSelectorFromString(method) withObject:json];// Error here
      return result;
  }
@end

The code was working when findAll was NOT a class method (ie -findAll declaration), but now I have the error : NSInvalidArgumentException -[Univers findAll:]
It clearly seems that the runtime is looking for an instance method.
Any idea to find my class method ?
Answer: Instead of calling
NSString* result =  [self performSelector:NSSelectorFromString(method) withObject:json];

you need to call
NSString* result =  [[self class] performSelector:NSSelectorFromString(method) withObject:json];

for class methods.
After all it's the object instance's class that supposed to be calling the method, not the instance itself.
Short explanation: NSObject implements - (Class)class; (not to be mistaken with + (Class)class of similar effect, which NSObject implements, too!) which returns the Class object of your instance object. Keep in mind that in Objective-C in addition to plain instance objects, Classes are actual objects, too: objects of type Class, that is (vs. id, NSObject, …).
See the documentation for the -class method here.

Btw, you should probably wrap your method call into an conditional block to prevent exceptions caused by calls to missing methods.
SEL selector = NSSelectorFromString(method);
if ([[self class] respondsToSelector:selector]) {
    NSString* result =  [[self class] performSelector:selector withObject:json];
}

In general it's a common pattern in Objective-C to call an object's class method by receiving the class object via [object class].
Consider this case of a class called Foo implementing a convenience method for returning an autporeleased instance of itself (to be called via: Foo *newFoo = [Foo foo];):
While it would certainly be possible to implement said method like this (after all we know the object's class name, right?):
+ (id)foo {
    return [[[Foo alloc] init] autorelease];
}

the correct way is this:
+ (id)foo {
    return [[[self alloc] init] autorelease];
}

As the first one would cause problems with polymorphism in subclasses (Such as a subclass called FooBar, for which it should clearly be [FooBar alloc] …, not [Foo alloc] …. Luckily [[self class] alloc] solves this dynamically).
While this is clearly not the right place for a thorough explanation of this (rather offtopic one might say) it's certainly worth noting/warning about, imho.
Comment: I don't think good explanations to a beginner are offtopic :)
Comment: `return [[[[self class] alloc] init] autorelease];` should just be `return [[[self alloc] init] autorelease];`. `[self class]` is the exact same as `self` in a class mehtod
Comment: @user102008: You're absolutely right. I blame copy & paste. ;) Fixed.
Comment: You can also just write `self.class` instead of `[self class]`.

Find the Selector of a Class method


Can I specify multiple data targets for Twitter Bootstrap collapse?

Question: I'd like to target two divs for expand when clicking on a single trigger? Is that possible?
Answer: You can simply add all the ids separated by commas in data-target:
<button type="button" data-toggle="collapse" data-target="#demo,#demo1,#demo2">
  Hide them all
</button>

Comment: While this approach works very well, you will run into issues if a second button targets any of those ids.  Rather than the second button showing e.g. #demo, #demo3, it will hide #demo, and add #demo3 to the list shown.
Comment: Bootstrap3: The data-target attribute accepts a CSS selector to apply the collapse to (https://getbootstrap.com/javascript/#via-data-attributes-3)
Comment: I am using Bootstrap 4.1.2, the solution does not work, it only target the latter id, ignoring the first id.
Comment: I think class would be better than this solution.
Comment: This may not fully work.  Bootstrap.js is expecting just one id.  See bootstrap.js line 551 or so (depending on your version).  this.$trigger is set to whichever element has the element to show referenced in the data-target attribute.
Answer: Use the same class for both div's and set your data-target according this. Give your div's also the same parent (can also be a class) and set data-parent according this.
<button type="button" data-parent="#wrap" data-toggle="collapse" data-target=".demo">
    simple collapsible
</button>

        test1

        test1

Comment: exact copy/paste from the Bootstrap source code:

value: function _getTargetFromElement(element) {
          var selector = _Util['default'].getSelectorFromElement(element);
          return selector ? $(selector)[0] : null;
        }

so, your solution will not work at all.
Answer: From the Bootstrap 3 documentation:

The data-target attribute accepts a CSS selector to apply the collapse to.

Therefore you can use a comma-separated list of id's, class selector etc. for the data-target attribute value:
<button class="btn btn-primary"
        type="button"
        data-toggle="collapse"
        data-target="#target1,#target2,#target3"
        aria-expanded="false"
        aria-controls="target1,target2,target3">

You can see an extensive list of valid CSS selectors on the w3schools website.
Comment: @AndrewLam This should work for Bootstrap 4 as well. The [official documentation](https://getbootstrap.com/docs/4.1/components/collapse/#multiple-targets) states: A `` or `` can show and hide multiple elements by referencing them with a JQuery selector in its `href` or `data-target` attribute. Perhaps you could try specifying a class instead of multiple ids?
Comment: Do you have solution for Bootstrap 4?
Answer: If you want to hide one element and show another (like the bootstrap accordion but without a panel) you can add multiple targets but also add the class 'in' to have one element expanded on load!

This is section 1

Are you excited about toggling?

Boo!!

This is a new sentence

<button class="btn btn-block btn-primary" data-toggle="collapse" data-target="#section1,#section2">Toggle</button>

Live demo here
Answer: There is a solution in Bootstrap 4:
Bootstrap 4 documentation: Multiple targets
The least you need is:

data-toggle="collapse" data-target=".multi-collapse" for the toggle
button
class="collapse multi-collapse" for each element you need to
toggle

(While multiple ids in data-target indeed don't work).
Comment: This seems to be the only answer that works on this page. I tested it using classes in both JavaScript and as data targets.  I needed this as I was generating code in loops in VueJS and the ids (now classes) were bound to the indexes. Thanks.
Answer: The data-target answer did not work for me. However you can use JavaScript to do this.
Make your button call some JavaScript like:
$('.collapse-class').collapse('toggle')

See: https://getbootstrap.com/javascript/#via-javascript-3.
Answer: Bootstrap 4 uses document.querySelector instead of document.querySelectorAll. If this changes, then everything works.
Answer: In Bootstrap 4 using the same class for each respective div seemed to work over using id.

<button type="button" class="btn" data-toggle="collapse" data-target=".collapse-group">
                Reveal Items</button>

Visible Row div 1

hidden item

div 2

hidden item 2

Answer: I  faced the same problem but bootstrap won't let  data-toggle="tab" beside data-toggle="collapsed" so my problem was like this.
I have:

and this was switching tabs:
<button type="button" class="navbar-toggle collapsed nav-trigger style-mobile" data-toggle="collapse" data-target="#main-header-collapse" aria-expanded="false" data-changeclassnames='{ "html": "mobile-nav-activated overflow-hidden" }'>
</button>

But this one closes the modal because the switch tab button was in the modal.
To solve the problem I add id="popout"(to first button) and id="popoutTrigger" (to secend button).
And this script (jQuery):
$( "#popout" ).click(function() {
  $( "#popoutTrigger" ).trigger( "click" );
});

When the user clicked the switch button in the modal, after switching modal will close.
This a view of what I've done.

I hope my solution will help.
Answer: Not in bootstrap 3.0.3, I have checked all combinations....


how to check if a process in uninterruptable on Solaris

Question: which ps option on Solaris 11g gives information if a process is in uninterruptable sleep mode?
admin@starsut:/tmp$ ps -aef | grep java
UID   PID  PPID   C    STIME TTY         TIME CMD
oracle  1465  1462   0   Oct 13 ?          18:10 /oracle/product/11.2.0/db_1/jdk/bin/sparcv9/java -server -Xmx384M -XX:MaxPermSi
admin 15701 15680   0   Oct 19 ?        2403:01 /wls/bin/middleware/jdk160_29/bin/java -client -Xms1024m -Xmx2048m -XX:MaxPermS
admin 29778  1943   0 13:05:44 ?           0:15 /wls/bin/middleware/jdk160_29/bin/java -classpath /wls/bin/middleware/patch_wls
admin 28733  1943   0 12:51:49 ?           0:15 /wls/bin/middleware/jdk160_29/bin/java -classpath /wls/bin/middleware/patch_wls
admin 29122  1943   0 12:56:03 ?           0:15 /wls/bin/middleware/jdk160_29/bin/java -classpath /wls/bin/middleware/patch_wls
admin 13115 11818   0 16:10:39 pts/8       0:00 grep java

I can't find any option to indicate a process (is in "D" state).
Please advise if there's such a flag.
edit: deleted linux flag
Comment: Why is this flagged `linux` ?
Answer: There is no such process state 'D' in Solaris. Sources:

ps(1) man page (states: O, S, R, T, W, Z)
pflags and pflags.c (OpenSolaris) (ASLEEP seems closest to Linux's S, not D).
<sys/proc.h> and usr/src/uts/common/sys/proc.h (OpenSolaris again):
#define SSLEEP  1       /* awaiting an event */
#define SRUN    2       /* runnable */
#define SZOMB   3       /* process terminated but not waited for */
#define SSTOP   4       /* process stopped by debugger */
#define SIDL    5       /* intermediate state in process creation */
#define SONPROC 6       /* process is being run on a processor */
#define SWAIT   7       /* process is waiting to become runnable */


What is the impact or value of listing multiple repositories in .Options$repos, in R?

Question: I noticed that this answer to a question about .Rprofile settings mentions setting two repositories for CRAN.
Is there any benefit to doing so, such as the possibility of one site being down, then another is accessed?  It seems that the CRAN mirrors are identical or eventually mirrors, and uptime seems very good, so are there any other advantages?  (I realize OmegaHat and Bioconductor have their own repositories, so I'm focusing on CRAN.)
Is it fair to say that CRAN is for stable releases and R-Forge is a staging area?  If so, then it seems that including R-Forge as a repository is more suitable for instances of beta testing various packages.

Update 1: This post has some good links on comparing mirrors, especially determining if two or more mirrors are out of sync (i.e. outdated).  This is the direct link for information on the availability status of mirrors, though it doesn't reflect the status of packages on the mirrors.  Dirk's answer is useful for determining discrepancies in the packages offered.
Answer: A) I don't see any particular advantage to having multiple repositories. If you choose a reliable one and it is behind the times or temporarily out of service. it is pretty much trivial to access another. I generally use the CMU repository, but the Berkeley repo also seems reliable.
B) Agree that CRAN (or mirrors) is for stable releases and r-forge is a "staging area". If you need a more recent version or one that is not available, then r-forge is the first location to consult. The bioconductor repos may also be accessed.
It is a good idea to know how to access the CRAN package check page.
Comment: I only ever use the main CRAN mirror in Austria - it's just not worth the chance of getting an out of date package to me.
Comment: @hadley  That's very useful advice.  I don't specifically refer to the one in Austria, but my default repository appears to be the same - just "http://cran.r-project.org" (the IP addresses are the same for cran.at.r-project.org and cran.r-project.org).
Answer: If fault tolerance and flexibility is important, it can be useful to set local, internal, and remote repos.
<code>repos["CRAN"] <- c("file://opt/cran","https://cran.example.com","https://cran.r-project.org")
</code>


Oracle collect function creating internal type and privileges to PUBLIC

Question: I am using COLLECT function in my query, and it is creating internal system generated type even though it is CAST to an already existing SQL type collection
Something like this:
cast(collect(opentrades_id)as t_dds_number)

Now it is creating an internally created type like SYSTPZrEBTIYRDGYUI==
Also, the user is giving executing rights to PUBLIC.
I want to understand why it is creating a system generated type and giving execute privileges to PUBLIC?
Answer: That is just the way it works.
In order to cast TO something, we have to be casting FROM something, so we silently create that to cater for the need
SQL> create table t as select rownum x
  2  from dual connect by level <= 10;

Table created.

SQL>
SQL> select type_name from user_types;

no rows selected

SQL>
SQL> select cast(collect(x) as sys.odcinumberlist) from t;

CAST(COLLECT(X)ASSYS.ODCINUMBERLIST)
----------------------------------------------------------------
ODCINUMBERLIST(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

1 row selected.

SQL>
SQL> select type_name from user_types;

TYPE_NAME
----------------------------------------------------------------
ST000012SwVFQsQ4m5aVQ27Pg9mw=

1 row selected.

SQL>
SQL>
SQL> select text from user_source
  2  where name = 'ST000012SwVFQsQ4m5aVQ27Pg9mw=';

TEXT
----------------------------------------------------------------
TYPE         "ST000012SwVFQsQ4m5aVQ27Pg9mw=" AS TABLE OF NUMBER

Addenda - workaround to avoid type
SQL> select cast(multiset(select x from t) as sys.odcinumberlist) from dual;

CAST(MULTISET(SELECTXFROMT)ASSYS.ODCINUMBERLIST)
----------------------------------------------------------------------------
ODCINUMBERLIST(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

Comment: So what can we do in order to avoid the system generated types created?
Comment: Also why execute privilege is being given to PUBLIC for that type?
Comment: @MorienMoses as Connor said, that's the way it works. If you want to avoid that, raise an enhancement request with Oracle Support to ask for the internal implementation of the `collect` function to be changed.
Comment: @WilliamRobertson I understand it works that way but what is the reason behind giving execute privilege to PUBLIC. Are there any activities that needs to be performed that required execute privilege to PUBLIC. If yes I want to understand what it is.
Comment: @MorienMoses what would the alternative be? The database doesn't know who will be executing the query in the future. And why does it matter anyway?
Comment: I've made an addenda to workaround type creation if its really concerning you
Comment: The workaround will work when `collect` is meant to aggregate over all rows in its input rowset, but not in general. `collect` is an aggregate function (it works with `group by`); `multiset` is not.


Broken NVidia X driver

Question: Today I installed the daily updates and then a funny thing happened... I was playing Morrowind on Wine, and in the game I tried to navigate to the video settings menu to adjust the brightness. I had done this before many times with no problem. As soon as I clicked "video", the game silently crashed and returned me to my desktop. The funny part was that my second monitor, which normally remains "signaled" with a black screen, while playing Morrowind, was now showing signs of "no signal". A quick check in nvidia-settings showed that my second monitor stopped being detected. I thought... ok, no big deal, I'll just restart and everything will be OK... WRONG. Upon restarting, X would not start because the NVidia driver compiled for 3.5.0-18-generic went missing, as in, it was not shown in lsmod. The monitor that had disappeared also did not come back. So I thought, ok, I must have gotten a new kernel, maybe now I have to reinstall the driver. Sure enough, uname -r showed 3.5.0-19-generic, one tick newer. So I sudo apt-get remove --purge nvidia-current-updates and then sudo apt-get install --reinstall nvidia-current-updates. The files downloaded and the module compiled successfully with no warnings or errors.
At this point, the lightdm login screen works fine across both monitors, but after logging in, I only get my desktop background image. No Unity or desktop icons. The strange thing is, the X log has no errors. After a few restarts, I finally got the second monitor to come back online after physically removing my GPU and putting it back in.
I'm pretty puzzled about this whole thing, whence I ended up here. Any one have any clue what's going on? I just want my desktop back :/
Answer: I wanted to only leave a comment, but I don't seem to have the permissions, so I'm using the answering window instead.
I don't have a full answer, but I'm seeing similar symptoms on a new installation of 12.10. For now, all I can offer is a workaround: when you only see the desktop background, you can press CTRL+ALT+T, which opens up a terminal window. In there, you can install e.g. a very simple window manager, which you can use as a fallback from unity.
sudo apt-get install fluxbox

Then you can kill the gnome-session process, which will effectively kill your whole X session.
pkill gnome-session

You'll get back to the login screen. In the login window, click the ubuntu icon in the login window, and select fluxbox. This will at least allow you to move windows around and have an environment in which you can debug the original problem.
Sorry, but I can't help with the original problem right now.

Broken NVidia X driver


how to rename GAM inputs at each for loop in R

Question: I'm trying to run multiple GAMs (generalized additive models) in R and convert their output summaries to a single dataframe. The data I'm running the GAMs on is formatted as one dataframe including many variable columns and one effect column. So, I want to create a for loop that runs a gam for each predictor vs. effect combination, then adds summary data (the r-squared and p value) and the predictor variable name to a new dataframe. However, I can't figure out how to rename the predictor column name within the GAM at each loop iteration without it throwing an error.
Example input_data:
Effect     Predictor 1     Predictor 2   Predictor 3
1            1                 4            4
4            2                 7            1
6            14                7            6

I want to be able to call the predictor column header at each loop iteration, then paste that name into the gam:
for (i in 2:4){

gam_predictor <- colnames(input_data[,i])
gam_output <-gam(Effect~s(gam_predictor, k = 4), data = input_data, method="REML")

}

However, I get this error:
Error in model.frame.default(formula = Effect ~ 1 + gam_predictor, data = input_data,  :
variable lengths differ (found for 'gam_predictor')
How can I get around this? I think it has something to do with the ~ operator but I can't figure out what.
Thanks!
Answer: You can use reformulate to dynamically create your formula based on the column name stored in gam_predictor:
gam_predictor <- "foo"

reformulate(paste0("s(", gam_predictor, ", k = 4)"), "Effect")
#> Effect ~ s(foo, k = 4)

And here a full working reproducible example using some fake random example data:
Note: I also fixed an issue with your assignment of the column name and made gam_output a list.
library(mgcv)
#> Loading required package: nlme
#> This is mgcv 1.9-0. For overview type 'help("mgcv-package")'.

# Create example data
set.seed(2)

input_data <- gamSim(1, n = 400, dist = "normal", scale = 2)
#> Gu & Wahba 4 term additive model

names(input_data)[1] <- "Effect"

gam_output <- list()
for (i in 2:4) {
  gam_predictor <- names(input_data)[i]
  gam_output[[gam_predictor]] <- gam(
    reformulate(paste0("s(", gam_predictor, ", k = 4)"), "Effect"),
    data = input_data, method = "REML"
  )
}

gam_output
#> $x0
#>
#> Family: gaussian
#> Link function: identity
#>
#> Formula:
#> Effect ~ s(x0, k = 4)
#>
#> Estimated degrees of freedom:
#> 2.31  total = 3.31
#>
#> REML score: 1089.598
#>
#> $x1
#>
#> Family: gaussian
#> Link function: identity
#>
#> Formula:
#> Effect ~ s(x1, k = 4)
#>
#> Estimated degrees of freedom:
#> 2.15  total = 3.15
#>
#> REML score: 1061.844
#>
#> $x2
#>
#> Family: gaussian
#> Link function: identity
#>
#> Formula:
#> Effect ~ s(x2, k = 4)
#>
#> Estimated degrees of freedom:
#> 2.96  total = 3.96
#>
#> REML score: 999.68


Are Linear Complexes and Simple Graphs the same thing?

Question: I refer to the background of the notion of $Linear~complex$ by A. A. Zykov in the article entitled "General properties of Linear Complexes"
A $Linear~complex $ (or simplex complex) is a finite set $L$ for which the set $(L)^2$ of all pairs is split into non- intersection parts: $(L)^2=K+\bar{K,}$ with the following conditions:
(I) Two pairs, which differ only in the order of the elements, belongs to one and the same part.
(II) The pairs of equal elements belongs to $\bar{K}$.
The number $e(L)$ of elements of the complex $L$ is called its order.
The elements $A$ and $B$ of $L$ are called adjacent $(A\omega B)$, if the pair of them belongs to $K$, and not adjacent $(A\bar{\omega} B)$, if it belongs to $\bar{K}.$ The condition I expresses the symmetric property of the sign $\omega$, the condition II its anti- reflexiveness.
The complexes $L_1$ and $L_2$ are equal $(L_1=L_2$ if they consist of the same elements and if any two elements which are adjacent in $L_1$ are adjacent in $L_2$, and conversely.
The complementary complex to $L$ is that complex $\bar{L}$ which consists of the same elements but in which any two distinct elements which are adjacent in $L$ are not adjacent in $\bar{L}$, and conversely.
Now, I wonder as what are the points of difference between a $Linear~ complex $ and a $ simple~ graph$? Or are they both same?
Answer: Yes, linear complexes are the same things as graphs. (Simple graphs, if you must, though I think it's more common to say "graph" and "multigraph" than "simple graph" and "graph".) But Zykov is writing to us from an alien universe (namely, the year 1949) which does not yet have a well-developed notion of graphs.
These days, Zykov is considered to be one of the founders of graph theory as a discipline. By 1969, when he was writing a textbook on graph theory, he called it the Theory of Finite Graphs. But how was he supposed to know what to call a graph in 1949?


100 amp hot tub panel, only need 50 amp

Question: I've got a 100 amp subpanel that the previous owners used for a hot tub. The new hot tub we're getting only needs 50 amps. Can I reuse the existing wiring, breakers and subpanel for the new tub, or do I need to change the subpanel and the main breaker to 60 amps?
Image of the subpanel:
I've got a 100 amp subpanel that the previous owners used for a hot tub. The new hot tub we're getting only needs 50 amps. Can I reuse the existing wiring, breakers and subpanel for the new tub, or do I need to change the subpanel and the main breaker to 60 amps?

Image: https://i.stack.imgur.com/6IgVS.jpg
Comment: What gauge are the existing wires, and what's the diameter of the existing conduit?
Answer: How many Amps?
I think we have a bit of confusion here about 50 Amps vs. 100 Amps.
You appear to have a double-pole 50 Amp GFCI breaker. That means a few things:

It provides 240V at up to 50 Amps.
It can also provide 2 x 120V at up to 50 Amps.
It provides protection against ground faults, which is critical, and required by code, for hot tubs (and most other outdoor and/or water-related electrical connections).

It is not 100 Amps. If it were, the wires would be a lot thicker, among other differences.
The subpanel may actually be rated for much more. A small subpanel is typically rated for 60 Amps, but sometimes more. That allows for a 50 Amp double breaker for a hot tub (or an RV) as well as another circuit or two for other stuff - e.g., 120V lights, 120V convenience receptacles.
This subpanel appears (I am not an expert) to have incoming power on lugs (i.e., no master disconnect here - so to do any work on the subpanel you would turn it off at the matching breaker in the main panel) and 4 breaker spaces. Each breaker space can be a 120V breaker or 1/2 of a 240V double-breaker. You currently have a 50 Amp double-breaker and 2 empty spaces above it.
Neutral vs. Ground
Neutral and ground are supposed to be kept separate except in the main panel. It looks to me like all the grounds and neutrals are together in the lower left. I actually don't see the neutral coming from the main panel feed, but there are some hidden wires so it may be in there somewhere. The neutral gets extra confusing because for a GFCI it goes to the breaker (for monitoring) as well as to the neutral bar on the panel. But the grounds and neutrals should be on separate bars and the neutral bar not grounded to the case of the subpanel.
The good news is that if you indeed are missing a neutral, your wires are in conduit so you can add an appropriately sized white wire as neutral.
Comment: I don't see any neutrals in that box at all.  Looks like all hot and ground with the GFCI wired for line-to-line current.
Comment: There is a neutral from gfci to ground bar. Don't see neutral from either conduit.
Comment: Looks like they are using the ground back to the main panel as the neutral path for the GFCI.  Tisk, tisk, tisk...
Answer: I was cleaning my car's tires and I notice they say "130 MPH rating".  Oh no! I only drive 70 mph!  Do I need to get the tires changed? Where do I even buy 70 mph tires?
That's what you're talking about there.  You have a subpanel that is rated 100 amps maximum.  You are actually sending 50 amps through it.  That is allowable and safe, because 50 < 100.

The THHN wire is #6, because the installer was a dummy.  But you can take advantage of that.  #6 THHN is actually good for 65A.  Back at the main panel, this can be fed by a breaker as large as 70A (65A, rounding up to the next existing breaker size).
Inside this panel are several things.
First, there's a 50A GFCI breaker already in it.  That's designed to feed 50A to a hot tub.  And by wild coincidence, YOUR hot tub is 50A, and it needs a GFCI breaker!   So yeah. You can reuse this GFCI breaker. And since they're $100 normally nevermind COVID shortages, that's a good idea.
Second, there are 2 empty spaces in this subpanel. Each space has 15 amps to spare.  You can install 240V-only loads: continuous loads up to 12 amps, or non-continuous loads up to 15A. So for instance a well pump could go there.
Third, it really looks like the dummy who wired this chose to cut off strands of the wire to make them fit on the bars.  That neutral bar ought to be able to take #6 wire just fine. So clean that up.
Fourth, this panel doesn't have neutral brought from the main panel. Nothing here uses neutral except the GFCI (to power itself), and that is bootlegging neutral from ground.  That's not how I would've done it, but I'm not going to tell you it's unsafe.  If you want anything in this panel that uses neutral, you will need to pull a neutral wire from the main.  To make space in the conduit, change out that #8 ground (amateur!!!) to a bare #10 ground.   Also, remove the neutral-ground strap and install an accessory ground bar, so grounds are separate from neutrals.
Answer: The existing panel and breaker should be fine.
The panel is rated for up to 100A, the maximum current it is configured for based on wire size and matching breaker feeding the panel is 50A. You could use a 200A panel out there being fed by #8 thwn, and you could still only feed it with a 50A breaker due to wire size.
You need to separate the grounds and neutrals. it appears (though I can't be certain) that the bus you have is a neutral bus and should be isolated from ground. The panel cover should list a part number for a ground bus, some inspectors will insist that specific UL/CSA/ETL "Listed" part be used, but not always.
Also because of the warm ambient temperature in a hot tub the instructions may say to feed the tub from the disconnect with a specified minimum wire size that would normally be considered oversized. The instructions are part of the "Listing" and they must be followed.
Finally note if you have to change the wire to the tub from the disconnect install an insulated ground wire like before, the code doesn't allow bare grounds for hot tubs.
Comment: I may have judged wire size incorrectly, pretty sure it is at least #8 so 50A is good, but it is possible you could use a larger breaker as noted by Harper.
Answer: As long as the panel is not undersized, then you can use almost any size panel you want.
Can have a 200 amp panel that only has a 15 amp circuit in it.  The breaker size is what is important.
Wire gauge must be large enough for amps the breaker protects.  If the wire gauge is correct for a 50 amp breaker, you are good to go.
For a subpanel do think you need to separate ground and neutral wires coming in.  Wait for an expert to confirm.
Comment: Yes, I have 4 wires coming into the subpanel. Two hot (black wires), a neutral white, and a green ground. The panel then only has 3 wires leaving, 2 hot, and 1 ground. I'm checking to see if the hot tub will work with 3 wires or if I need to add a fourth neutral wire going out.
Comment: It is that neutral and ground should only be connected/bonded together at main panel only.  For sub panels they need to be separated, not bonded together.
Answer: So you have a 100 Amp sub panel but in it is a 50 Amp GFCI breaker so you should be OK. The only glitch would be if your new tub instructions stated that a 60 Amp breaker is needed. What size breaker in your main panel feeds this sub panel?
Comment: There are two 50 amp breakers connected together in the subpanel, and the main panel has two 50 amp breakers connected together. So, since I'll only be pulling 50amp of load from the hot tub, I should be fine.
Comment: @Anks329  It's a double pole GFCI breaker with handle ties. 120/240 volt, 50 Amp

100 amp hot tub panel, only need 50 amp


Weight function and orthogonalization

Question: If we have the weight function $w(x) = e^{-x}$, then what are the constant and linear polynomials $p_0(x)$, $p_1(x)$, that are orthogonal on $[0,\infty)$ w.r.t. $w(x)$?
And if $f(x) =\cos(x)$, what is the best linear approximation to $f(x)$ for the given weight?
Answer: I think you are interested in the Laguerre polynomials $L_n$, which form an orthonormal basis for the weighted space $L^2((0,\infty), e^{-x}\,dx)$. In particular, $L_0(x)=1$ and $L_1(x)=-x+1$.
To approximate $\cos x$, just compute its coefficients as
$$c_n=\int_0^\infty \cos x L_n(x) e^{-x}\,dx$$
For example, I get $1/2, 1/2, 1/4, 0, -1/8, -1/8$ for $n=0,\dots,5$. The corresponding sum
$$\sum_{n=0}^5 c_n L_n(x)= 1+\frac{1}8 x-\frac{7}{8}x^2+\frac{7}{24} x^3-\frac{1}{32} x^4+\frac{1}{960}x^5$$ gives this approximation:

This isn't picture-perfect but what can you expect from degree 5 polynomial. The weight $e^{-x}$ makes sure the approximation is okay at the beginning, but it does not care much about what happens when $x$ is large.

Weight function and orthogonalization


Can we call roslaunch or rosrun through a web page?

Question: I have a question that can we call or run files of our package inside ros through a webpage. In other word, can we perform rosrun or roslaunch from an html page?
Answer: One way to do what you want is to integrate a shell to a website. There are some projects dealing with such use cases. A greate solution is shellinabox. It is open source, easy to use and install. With the shell integrated to a website you are able to perform all shell commands you need to control ROS.
You can find a nice tutorial how to install and use shellinabox at Tecmint.


LiftMaster 1280R door won't close

Question: I have a somewhat ancient LiftMaster 1280R and the door does not close. The light blinks as if it were a safety sensor issue, but the lights on both sensors are solid. I've tried replacing the safety sensors, and the new sensors also light up solid, but the door still won't close.
I've confirmed it's not a wiring issue by wiring the sensors with short leads directly to the garage door opener and taped them so they were facing each other.
I can manually close the door without issue. If I hold my wall button down, the door will close (I believe this bypasses the safety sensor somehow). The above behavior resurfaces once I let go of the button regardless of the position of the door at the time. My other door opens and closes with a single press of the wall button.
Is there anything else I can try before replacing the whole garage door opener?
Comment: did you change the battery on remote and pair it again, by putting the garage door opener in pairing mode (blinking light)
Comment: Make darn sure the two "eyes" on each side are aligned correctly.  I have a door that sometimes does the same.  The lights on the eyes are good, but the door won't close unless I hold the button down.  Adjusting the eyes again makes it work properly.
Comment: @Huesmann The sensors are currently taped to each other so the sender and receiver are touching. No room for error there.
Comment: @Ruskes The behavior is the same with the wall button and remote, so it's not a remote issue. The remote is newly purchased and paired however (same day as the replacement eyes). I have two remotes in addition to the wall button and both removes are able to operate the other door perfectly. They can both open, but not close, the door in question.
Comment: Thank you for additional info, it is hard to diagnose from where I am. Typically if one of the sensor is blocked the garage opener light should flash. You can try disconnecting the light sensors.
Answer: In the end, I wasn't able to determine the problem. I replaced the entire garage door opener unit but used the existing safety sensors, and they function as expected. I assume that the problem was with a component on the main board of garage door opener.
The new opener is working perfectly.

LiftMaster 1280R door won't close


permutations and transpositions in even and odd cases

Question: Say we had some $\sigma = (1, 2)(2, 3)...(n-1 ,n)$ could someone explain why this formula doesn't hold for odd n?
For instance, $n = 2m+1$ $\sigma = (1,2)...(2m-2,2m-1)(2m, 2m+1)$, why does that not work?
Comment: Why don't you try to decompose an odd permutation with the formula first?
Comment: @nameless I've tried and have been unable too, for instance the cycle $(1,2,3,4) = (1,4)(1,3)(1,2)$ with is odd but $(1,4)(1,3)(1,3) = (1,2)(2,3)(3,4)(2,3)(1,2)(1,3)(1,2)$ so it seems as though it doesn't work... I don't know why?
Comment: Warz: $(1, 2, 3, 4) = (1, 2)(2, 3)(3, 4)$.
Answer: If $n = 2m+1$, then we have, for a cycle of length $n$, [note, we need to use $m = 0$ for $n = 1$]:
$$(1, 2)(2, 3) \ldots(2m - 2, 2m - 1)(2m, 2m + 1)$$
Note that the first transposition starts with an odd number, and the last transposition starts with an even number: this makes an even number of transpositions, which is correct, since a cycle of an odd length is even.  So the algorithm works fine for odd and even $n$.
A permutation $\sigma$ is deemed even or odd based on whether it can be expressed only as a product of an even number of transpositions or only as an odd number of transpositions, respectively.
It is not deemed even or odd based on the length(s) of its cycle(s).
Simple example: $n = 3$ (odd $n$)
$$\sigma = (1, 2, 3) = \underbrace{(1, 2)(2, 3)}_{\large 2\;\text{transpositions}}$$
$2$ is clearly even. Therefore, $\sigma$ is an even permutation.
Comment: Right to left, remember? $1\to 1, \;1\to 2.$ Next, from the right again: $2\to 3, \;3\to 3.$ Next, again from the right: $3\to 2,\; 2\to 1$. That gives us, in summary: $\;1 \to 2,\; 2\to 3,\;  3\to 1\;$ or $(1, 2, 3)$
Comment: say n = 7, then we get $\sigma = (1,2)(3,4)(5,6)(6,7)$ using the formula, but $ 5 \to 6$ and $7 \to 6$ $7 \not = 5$, how is this possible?
Comment: No, if $n = 7$, we have $(1, 2)(2, 3)(3, 4)(4, 5)(5, 6)(6, 7)$. You need to apply the transpositions from right to left to reconstruct a permutation.  Recall, order matters, in non-disjoint cycles of a permutation. Transpositions are usually not disjoint.
Comment: could you please explain why if we had $\sigma = (1,2)(2,3)$ why is this valid? It takes 2 to 1, and 2 to 3 - a permutation is supposed to be a bijective, how should I read this out?


How to iterate over a `groupBy` returned object in Python?

Question: I have the following data input as a single string:
data = ['historical_trades', '1.00', '30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f', '1925323', '343727655', '2019.11.14 21:24:01', '2019.11.14 21:24:01', '6', '0.01', '', '0.00000', '0.00000', '0.00000', '0.00000', '0.00', '0.00', '100000.00', '< >', 'historical_trades', '1.00', '30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f', '1925323', '344377716', '2019.11.27 21:07:22', '2019.12.06 17:14:03', '1', '0.20', 'GBPUSD', '1.29118', '1.31069', '0.00000', '0.00000', '0.00', '4.24', '-353.20', '<>', 'historical_trades', '1.00', '30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f', '1925323', '344377723', '2019.11.27 21:07:56', '2019.12.06 17:14:02', '1', '0.20', 'GBPUSD', '1.29117', '1.31070', '0.00000', '0.00000', '0.00', '4.24', '-353.57', '<>', 'historical_trades', '1.00', '30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f', '1925323', '344377724', '2019.11.27 21:08:00', '2019.12.02 18:38:14', '1', '0.20', 'GBPUSD', '1.29118', '1.29444', '0.00000', '0.00000', '0.00', '2.36', '-58.87', '<>', 'historical_trades', '1.00', '30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f', '1925323', '345200110', '2019.12.06 17:14:08', '2019.12.06 17:22:43', '0', '0.20', 'EURUSD', '1.10474', '1.10479', '0.00000', '0.00000', '0.00', '0.00', '0.91', '<>', 'historical_trades', '1.00', '30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f', '1925323', '345200125', '2019.12.06 17:14:21', '2019.12.06 17:22:45', '0', '4.00', 'EURUSD', '1.10483', '1.10479', '0.00000', '0.00000', '0.00', '0.00', '-14.48', '<>', '']

I use the Python itertool groupBy to extract the repeating strings/objects. I then want to push these extracted objects to the SQL database while each object represents one row.
            for key, group in groupby(data, key=lambda s: s != "historical_trades"):
                if key:

                    print(list(group))

                    # print output:

                    ['1.00', '30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f', '1925323', '343727655', '2019.11.14 21:24:01', '2019.11.14 21:24:01', '6', '0.01', '', '0.00000', '0.00000', '0.00000', '0.00000', '0.00', '0.00', '100000.00', '< >']
                    ['1.00', '30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f', '1925323', '344377716', '2019.11.27 21:07:22', '2019.12.06 17:14:03', '1', '0.20', 'GBPUSD', '1.29118', '1.31069', '0.00000', '0.00000', '0.00', '4.24', '-353.20', '<>']
                    ['1.00', '30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f', '1925323', '344377723', '2019.11.27 21:07:56', '2019.12.06 17:14:02', '1', '0.20', 'GBPUSD', '1.29117', '1.31070', '0.00000', '0.00000', '0.00', '4.24', '-353.57', '<>']
                    ['1.00', '30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f', '1925323', '344377724', '2019.11.27 21:08:00', '2019.12.02 18:38:14', '1', '0.20', 'GBPUSD', '1.29118', '1.29444', '0.00000', '0.00000', '0.00', '2.36', '-58.87', '<>']
                    ['1.00', '30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f', '1925323', '345200110', '2019.12.06 17:14:08', '2019.12.06 17:22:43', '0', '0.20', 'EURUSD', '1.10474', '1.10479', '0.00000', '0.00000', '0.00', '0.00', '0.91', '<>']
                    ['1.00', '30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f', '1925323', '345200125', '2019.12.06 17:14:21', '2019.12.06 17:22:45', '0', '4.00', 'EURUSD', '1.10483', '1.10479', '0.00000', '0.00000', '0.00', '0.00', '-14.48', '<>', '']

                    # Insert iteration logic here, to iterate returned (printed) object to execute the following statements.

                    [...]
                    [...]
                    s.th. like: "for every row in list(group):" ??

                    version = data[1]
                    DID = uuid.UUID(data[2])
                    accountNumber = int(data[3])
                    orderTicket = data[4]
                    orderOpenTime = data[5]
                    orderCloseTime = data[6]
                    orderType = float(data[7])
                    orderLots = float(data[8])
                    orderSymbol = data[9]
                    orderOpenPrice = float(data[10])
                    orderClosePrice = float(data[11])
                    orderStopLoss = float(data[12])
                    orderTakeProfit = float(data[13])
                    orderCommission = float(data[14])
                    orderSwap = float(data[15])
                    orderProfit = float(data[16])
                    orderComment = data[17]

                    # push the manipulated data to the PostgreSQL DB using `Trades` model
                    # If orderTicket exists, update values, if not create new entry

                    obj, created = Trades.objects.update_or_create(
                        orderTicket=orderTicket,
                        defaults={
                            'version': version,
                            'DID': DID,
                            'accountNumber': accountNumber,
                            'orderTicket': orderTicket,
                            'orderOpenTime': orderOpenTime,
                            'orderCloseTime': orderCloseTime,
                            'orderType': orderType,
                            'orderLots': orderLots,
                            'orderSymbol': orderSymbol,
                            'orderOpenPrice': orderOpenPrice,
                            'orderClosePrice': orderClosePrice,
                            'orderStopLoss': orderStopLoss,
                            'orderTakeProfit': orderTakeProfit,
                            'orderCommission': orderCommission,
                            'orderSwap': orderSwap,
                            'orderProfit': orderProfit,
                            'orderComment': orderComment
                        }
                    )

Now how can I access the groupby returned object and iterate over it to populate the database?
Working solution:
I tried to adapt @Tobi's solution into my code and it works properly now.
            for key, group in groupby(data, key=lambda s: s != "live_trades"):
                if key:

                    trades = list(group)
                    print(trades)

                    for data in trades:

                        version = trades[0]
                        print(version)
                        DID = uuid.UUID(trades[1])
                        accountNumber = int(trades[2])
                        print(accountNumber)
                        orderTicket = trades[3]
                        print(orderTicket)
                        orderOpenTime = trades[4]
                        orderCloseTime = trades[5]
                        orderType = float(trades[6])
                        orderLots = float(trades[7])
                        orderSymbol = trades[8]
                        orderOpenPrice = float(trades[9])
                        orderClosePrice = float(trades[10])
                        orderStopLoss = float(trades[11])
                        orderTakeProfit = float(trades[12])
                        orderCommission = float(trades[13])
                        orderSwap = float(trades[14])
                        orderProfit = float(trades[15])
                        orderComment = trades[16]
                        print(orderTicket)

                        # convert dateTime strings into Python comfort dateTime

                        orderOpenTime = datetime.strptime(orderOpenTime, '%Y.%m.%d %H:%M:%S')
                        orderCloseTime = datetime.strptime(orderCloseTime, '%Y.%m.%d %H:%M:%S')

                        # push the manipulated data to the PostgreSQL DB using `Trades` model
                        # If DID exists, update values, if not create new entry

                        obj, created = Trades.objects.update_or_create(
                            orderTicket=orderTicket,
                            defaults={
                                'version': version,
                                'DID': DID,
                                'accountNumber': accountNumber,
                                'orderTicket': orderTicket,
                                'orderOpenTime': orderOpenTime,
                                'orderCloseTime': orderCloseTime,
                                'orderType': orderType,
                                'orderLots': orderLots,
                                'orderSymbol': orderSymbol,
                                'orderOpenPrice': orderOpenPrice,
                                'orderClosePrice': orderClosePrice,
                                'orderStopLoss': orderStopLoss,
                                'orderTakeProfit': orderTakeProfit,
                                'orderCommission': orderCommission,
                                'orderSwap': orderSwap,
                                'orderProfit': orderProfit,
                                'orderComment': orderComment
                            }
                        )

Comment: You're only ever using the hard coded `data[1]`…!?
Answer: The following should work just fine:
for data in group:
    version = data[0]
    ...

Two things to note:

indexing starts with 0, so the first element in data is [0], the second is [1] and so on
not only the result from groupby, but also the indivisual groups within it are iterators, so once you consume them, e.g. with print(list(group)), they are exhausted (I guess that was the problem when you tried your loop)
>>> k, g = next(groupby([1,1,1,2,2,2]))
>>> list(g) # prints fine at first...
[1, 1, 1]
>>> list(g) # ... nothing happens in the loop afterwards?
[]

Instead, you could print the current group in your inner loop, or collect all the groups in a list, i.e. group = list(group)

Also, instead of storing all the fields in data in 17 different variables and then writing them back to a dictionary, you could use zip to combine them with the correct names and types directly from data. (Only works if you need all the fields from data, but this seems to be the case here.)
fields = ('version','DID','accountNumber','orderTicket','orderOpenTime',
        'orderCloseTime','orderType','orderLots','orderSymbol','orderOpenPrice',
        'orderClosePrice','orderStopLoss','orderTakeProfit','orderCommission',
        'orderSwap','orderProfit','orderComment')

types = (str,uuid.UUID,int,str,str,str,float,float,str,float,float,float,
        float,float,float,float,str)

defaults = {f: t(d) for f,t,d in zip(fields, types, data)}
#{'orderSwap': 0.0, 'orderCloseTime': '2019.12.06 17:22:45', 'orderComment': '<>',
# 'orderTakeProfit': 0.0, 'accountNumber': 1925323, 'DID': UUID('30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f'),
# 'orderType': 0.0, 'orderCommission': 0.0, 'orderLots': 4.0, 'orderOpenTime': '2019.12.06 17:14:21',
# 'orderSymbol': 'EURUSD', 'orderOpenPrice': 1.10483, 'version': '1.00', 'orderProfit': -14.48,
# 'orderStopLoss': 0.0, 'orderClosePrice': 1.10479, 'orderTicket': '345200125'}

Comment: Thank you very much for the superduper reply. However, I still didn't get it totally yet. So once the returned group is consumed (even with print) it is exhausted? So you suggest to store it in a variable before doing anything with it? I tried to implement your solution and it now returns me several string index out of range errors while looping, why? Also what kind of data structure/object is a group, 2-dimensional array?
Comment: The group is (in this case) kind-of a 2d array: It is an iterator of all the entries that are equal according to the `key` function, which in your case are lists themselves (the `data` rows)


House Party Protocol glitch?

Question: I finished the story and all, and done the bonus mission in Stark Tower named "House Party Protocol" got Stan Lee in Peril and True Believers, yet when I try to go in again for the Red Brick, it doesn't ask me if I want to do it in Free play mode or not, in which I cannot get the Red Brick. Any help on this? (I'm on the PC btw).
Answer: If you want to go back to these Deadpool mini-missions in Free Play to earn the stuff you can only get when you can switch freely, do not re-enter the door you used the first time.
Instead, open the map and select the icon for the mission like you would if you were fast traveling or setting a waypoint.  Once you select it, you'll be given the Free Play option, but only if you've already completed it once.
(As a side note, this is also a good way to figure out if you've cleared a mission or Deadpool mission - only ones you've played to completion at least once will bring up the Free Play option.  Ones you haven't played will just bring up the waypoint selection option.)
Comment: Just a tip that you can select any available Deadpool mission on the map, and then can use L-R to move between the other missions to select.
Comment: @agent86 Thanks for that tip mate! :D

House Party Protocol glitch?


Unable to load images/files pisa pdf Django python

Question: I had a problem before where it wouldn't show Chinese characters even when I specified @font-face to use a UTF-8 font. It turns out I cannot display images as well... so I seems like I am unable to get any of the files embeded into my pdf.
This is the code I use:
def render_to_pdf(template_src, context_dict):
    """Function to render html template into a pdf file"""
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = StringIO.StringIO()

    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")),
                                            dest=result,
                                            encoding='UTF-8',
                                            link_callback=fetch_resources)
    if not pdf.err:
        response = http.HttpResponse(result.getvalue(), mimetype='application/pdf')

        return response

    return HttpResponse('We had some errors
%s
' % escape(html))

def fetch_resources(uri, rel):
    import os.path
    from django.conf import settings
    path = os.path.join(
            settings.STATIC_ROOT,
            uri.replace(settings.STATIC_URL, ""))
    return path

html

and
    @font-face {
        font-family: "Wingdings";
        src: url("/static/fonts/wingdings.ttf");
    }

I looked at the other quests on SO but it was no help. There are also no exceptions happening in the two functions. Also in fetch_resources function the path returned was the correct full path to the file i.e. /home/<user>/project/static/images/bc_logo_bw_pdf.png and /home/<user>/project/static/fonts/wingdings.ttf and I am at a loss as to what is wrong.
UPDATE
Everytime I create a pdf, I get this message on the console
No handlers could be found for logger "ho.pisa"

could this be related?
UPDATE #2
The font works now I made a dumb mistake... The font I was using did not have the Chinese unicode. But I still cannot embed any images onto the pdf, be it jpeg, gif or png.
Comment: Are you sure your font really has Chinese characters? Fount could be unicode but still lacking some characters.
Comment: zentenk, I see that my code helps to you. Don't forget vote up my post on your previous answer ;) Also, let to you that: 1) this code works for me and is tested with images. 2) after wasting a lot of time with Pisa I have move my reports to [pod](http://appyframework.org/pod.html)
Comment: `logger` issue is unrelated (and harmless)
Comment: Thanks for the feedback. The fonts work now, but the image still does not work
Comment: I think you should once try with jpg image file.
Answer: I have finally solved the problem I was having... it turns out it doesn't work if I set the body's height with css... once I removed that line the image was loading perfectly...
Answer: For me (django 1.4, python 2.7 pisa==3.0.33), If I put the full path of image instead of relative, it works for me.
Try doing the same.
Answer: Everything looks better . Try once with JPG image file.  In my case PNG file was also not working.
<img src="/static/images/<name>.jpg" />

Answer: without width and height attribute image will not work. add width and height attribute.

this fix works for me.
Answer: I have the same problem here. Don't give up with XHTML2PDF Pisa.
Pisa use PIL for generate PDF and use lib zip decoder to inserting images.
You should check if your PIL already installed properly with zip decoder, fonts and several components
I have solve this problem by installing PIL with zip decoder.
http://obroll.com/install-python-pil-python-image-library-on-ubuntu-11-10-oneiric/
If you need more detail information, you can read my article here :
http://obroll.com/how-to-load-images-files-style-css-in-pdf-using-pisa-xhtml2pdf-on-django/


Does The Witness have a 3rd ending?

Question: So there is 1st ending when you

 complete whole upper part of the mountain.

2nd ending when you

 complete the gate-based enviromental puzzle

I would expect 3rd ending when you complete all obelisks, but once I've done it I haven't been able to find any trigger. Completing all 523 puzzles didn't help ether. Is there any 3rd ending? Are there any changes after completing all obelisks besides their color and fountains?
Answer: There is currently no known third ending.  See for example here.
Answer: There is a third "easter-egg"-style ending, right at the start, but it is unrelated to the other tasks.
From that guide:

At the beginning of the game, you appear in a long tube passage.
   Here, you'll learn the basics of the puzzle mechanics.
Complete the first line puzzle, then complete the second to reach a colorful garden.
To the right, you'll see a locked gate with a tall pillar of bright white light.
Line up the pillar of light with the bright white of the sun. Does it look familiar? That's right, you can complete an ambient
   light line puzzle using the pillar of light and the sun.
Press the sun and drag down. The screen will shake and rumble, and you might have to adjust your alignment until the puzzle works.
Once you're able to interact, the sun is your round start point. Drag downward until the gates open, allowing you to enter the island
   hotel.
Comment: Why do you call it the 3rd ending? What do you call the 2nd ending then?
Comment: Could you add a relevant quote or two from the link in case it ever disappears?
Comment: @Vemonus done .
Comment: @klm123 I didn't realise that was what you meant, because your description was so inspecific.

Does The Witness have a 3rd ending?


RubyMotion: Find each character entry in UITextField

Question: I am new to RubyMotion for iOS app, but I coded using Objective C.
My requirement is to get the delegate method which should be called for every char type in UITextField.
Objective C:  I used "shouldChangeCharactersInRange" for finding the user character entry.
Can you anyone suggest me how to implement this function in RubyMotion for tracking character type in UITextField
Thank you.
Regards.
Answer: First, when you create the text field, make sure you set the delegate to the same View Controller class it's in:
textField = UITextField.alloc.initWithFrame([[10,200],[300,40]])
textField.delegate = self

Then add this method to that class:
def textField(textField, shouldChangeCharactersInRange:range, replacementString:string)
  # return true or false based on whether you want to allow the replacement
  true
end

Answer: I like the BubbleWrap syntax:
textField.when(UIControlEventEditingChanged) do
  # something
end


React Redux this.props.getClasses is not a function

Question: I am trying to pass action with mapDispatchToProps to component,
when i am trying to use getClasses as this.props.getClasses().
I am getting Failed prop type: The prop getClasses is marked as required in HierarchySelect, but its value is undefined.
and on 'section' select component is crashing with TypeError: this.props.getClasses is not a function
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';

const { Fragment } = React;
export class HierarchySelect extends Component {
  constructor (props) {
    super(props);
    this.state = {
      sections: [],
      section: '--',
    };
  }

  handleChange (value, type, error) {
    switch (type) {
      case 'section':
        this.setState({
          section: value
        });
        this.props.getClasses({ type: '', data: '' });
        break;
      default:
    }
  }

  render () {
    return (
      <Fragment>
        <select id="lang" className="section" onChange={e => this.handleChange(e.target.value, 'section')} value={this.state.section}>
          {['--', ...this.state.sections].map(d => <option key={d} value={d}>{d}</option>)}
        </select>
      </Fragment>
    );
  }
}

HierarchySelect.propTypes = {
  deptHierarchy: PropTypes.object.isRequired,
  createHierarchy: PropTypes.func.isRequired,
  id: PropTypes.number.isRequired,
  getClasses: PropTypes.func.isRequired
};

export const mapStateToProps = (state, props) => ({
  user: state.getUser
});

export const mapDispatchToProps = dispatch => ({

  getClasses: (data) => {
    dispatch(data);
  }

});

export default connect(mapStateToProps, mapDispatchToProps)(HierarchySelect);

Comment: Are you passing the getClasses function as params from parent to child component ?
Comment: here the child component is HierarchySelect right ?
Comment: @Prabhu getClasses function should be passed from connect function as props.
Answer: In mapDispatchToProps you are not returning the dispatch in getClasses. You need to write it like
export const mapDispatchToProps = dispatch => ({
    getClasses: (data) => {
       return dispatch(data);
    }
});

or
export const mapDispatchToProps = dispatch => ({
  getClasses: (data) => dispatch(data);
});

Also you need to import the connected component which is the default export in your case
import HierarchySelect  from './hierarchy-dropdowns';

Comment: i have tried this also. hierarchy-dropdowns.jsx:42 Uncaught TypeError: this.props.getClasses is not a function

export const mapDispatchToProps = dispatch => ({
  getClasses: data => dispatch(data)
});
Comment: how are you importing HierarchySelect
Comment: import { HierarchySelect } from './hierarchy-dropdowns';

file name is hierarchy-dropdowns
Comment: you need to import the connected component  which is the default export `import  HierarchySelect  from './hierarchy-dropdowns';`
Comment: Great thanks it worked, I just had to make eslint understand i am doing right.
import HierarchySelect from './hierarchy-dropdowns'; // eslint-disable-line import/no-named-as-default
Any other way that does not require to change eslint config.
Comment: Glad to have helped
Answer: handleChange is not binded to component this instance.So, you getting props as undefined.
Define handleChange with
Arrow function which do lexical this binding.
handleChange = (value, type, error) =>{
            this.props.getClasses();
        }
      }

OR
In constructor do this binding with bind:
constructor(){

   this.handleChange = this.handleChange.bind(this);
}

Comment: it is binded, just that the binding is done inline `onChange={e => this.handleChange(e.target.value, 'section')}`


Problems with inheritance using SQLModel

Question: I want the role attribute from AppUser populated. When I declare it in AppUser class, it works as expected, joining the userrole table. But if I declare it in BaseUser class, it's not populating the field, ignoring the join. My question is, how can I make this inheritance model work? With the code below, you can view the sql query. I'm working with python 3.10.12 and SQLModel 0.0.12

from sqlmodel import Field, SQLModel,Column
from sqlalchemy import create_engine
from sqlalchemy.orm import relationship
from sqlalchemy.pool import StaticPool
from typing import Optional
from sqlalchemy import BigInteger
from sqlmodel import Field, Relationship, SQLModel, Column
from sqlmodel import Session, select

class Base(SQLModel, table = False):
    id:Optional[int] = Field(sa_column=Column(BigInteger(), default=None, primary_key=True))

class UserRole(Base, table = True):
    name:str

class BaseUser(Base, table = False):
    username:str
    role_id:int = Field(default=None, foreign_key="userrole.id")
    role:UserRole = Relationship(sa_relationship=relationship("UserRole", lazy="joined"))

class AppUser(BaseUser, table = True):
    email:str

    # Uncomment to make join work
    #role:UserRole = Relationship(sa_relationship=relationship("UserRole", lazy="joined"))

engine = create_engine(
        'sqlite:///demo2.db',
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
        echo=True
)
SQLModel.metadata.create_all(engine)

with Session(engine) as session:
        statement = select(AppUser)
        results = session.exec(statement)
        items = results.all()

Answer: According to the documentation of SQLModel, only models with table=True may include relationship attributes.
It seems like it doesn't work even if your child class has table=True.
If you need to include this field to output model, just create new model and add this field without relationship:
class BaseUser(Base, table = False):
    username:str
    role_id:int = Field(default=None, foreign_key="userrole.id")

class AppUser(BaseUser, table = True):
    email:str
    role:UserRole = Relationship(sa_relationship=relationship("UserRole", lazy="joined"))

class UserOut(BaseUser):
    role:UserRole

https://sqlmodel.tiangolo.com/tutorial/fastapi/relationships/#data-models-without-relationship-attributes


how to search for particular groups user belongs to

Question: I have file test.txt which contains details of id command ( eg: id sudi )
uid=23351(sudi) gid=5000(bns) groups=5000(bns),16382(damepgrp),15657(edl_prd_rcrr_sup),15650(edl_prd_rcrr_user),15712(edl_prd_yarn_int_cb),15721(edl_prd_yarn_int_rsk),15632(edl_prod_rcam_admin),16110(edlp_bc5m_sup)

uid=23458(achung1) gid=5000(bns) groups=5000(bns),15757(edl_prd_ice_analyst),15483(edl_prd_ice_user),15650(edl_prd_rcrr_user),15712(edl_prd_yarn_int_cb),15721(edl_prd_yarn_int_rsk)

uid=19831(afabia) gid=5000(bns) groups=5000(bns),15774(edl_prd_c360da_users),15714(edl_prd_yarn_int_ana),15712(edl_prd_yarn_int_cb),15606(edl_prod_c360_users),16179(edl_prod_c360rt_users),15621(edl_prod_dspm_dev),16076(edlp_bc4g_ca_ez_usr),16052(edlp_bc4g_ca_usr),16053(edlp_c360_da_usr),15105(hdpcmo),15104(hdpnanalytics),15279(hdpnaug),15144(rscmo),15280(rsnaug),16171(edl_prod_c360rt_susr)

how to print only id and yarn groups as output. I have tried it with grep and sed but no luck
eg:
 sudi: edl_prd_yarn_int_ana, edl_prd_yarn_int_cb
 achung1: edl_prd_yarn_int_cb, edl_prd_yarn_int_rsk
 afabia: edl_prd_yarn_int_cb, edl_prd_yarn_int_ana

Comment: Will the yarn info always be wrapped in double asterisks?
Comment: no i have just highlighted for the question purpose output of id command is as follows: uid=23351(abotha) gid=5000(bns) groups=5000(bns),16382(damepgrp),15657(edl_prd_rcrr_sup),15650(edl_prd_rcrr_user),15712(edl_prd_yarn_int_cb),15721(edl_prd_yarn_int_rsk),15632(edl_prod_rcam_admin),16110(edlp_bc5m_sup)
Answer: grep -oP "uid=\d+\(\K\w+(?=\))|\w+yarn\w+" file | awk '$0~/yarn/{if(!first){a=a" "$1; first=1}else{a=a" ,"$0}} $0!~/yarn/{print a; a=$0":"; first=0} END{print a}'
Output:
sudi: edl_prd_yarn_int_cb,edl_prd_yarn_int_rsk
achung1: edl_prd_yarn_int_cb,edl_prd_yarn_int_rsk
afabia: edl_prd_yarn_int_ana,edl_prd_yarn_int_cb

Comment: Yeah, that`s the one, what if i have 3 or more strings for yarn
Comment: If each user has 3 strings for yarn then change the paste command to `paste - - - -`. BUT this will not work if users have different number of yarn strings for eg. if user1 has 3 yarn strings and user2 has 4 yarn strings. This will fail in that case. Do you want a generic solution ?
Comment: i have users with 2 , 3, 4 yarn strings eg: uid=23391(xxxx) gid=5000(bns) groups=5000(bns),15714(edl_prd_yarn_int_ana),15712(edl_prd_yarn_int_cb),15718(edl_prd_yarn_int_gbm),16110(edlp_bc5m_sup),15829(edlp_cbt_tsz_ro),15143(rsnanalytics),15152(rsnanalyticssec) this user has 3 yarn strings..so i need a generic one wherein irrespective of number of yarn strings it should work
Comment: Check the updated solution. From next time make sure to put all necessary information in your question and show your efforts also. SO is not a code factory.
Answer: Using
gawk :
$ awk -v RS='[()]' -v OFS=, '/yarn/{s=s?s OFS $1:$1}END{print "sudi: " s}' infile
sudi: edl_prd_yarn_int_ana,edl_prd_yarn_int_cb

awk :
$ awk -F'[()]' -v OFS=, '{for(i=1; i<=NF; i++)if($i~/yarn/)s=s?s OFS $i:$i}END{print "sudi: " s}' infile

Input:
$ cat infile
uid=21015(sudi) gid=5000(bns) groups=5000(bns),15714(edl_prd_yarn_int_ana),15712(edl_prd_yarn_int_cb),16083(edlp_bc4g_sup),16186(edlp_bc55_ah_da_usr1),16183(edlp_bc55_ah_da_usr2),16134(edlp_bc55_sup),16045(edlp_ds_na_usrgrp),15970(edlp_dsci_usr),15861(edlp_dsna_app),15956(edlp_pricinggtb_susr),15105(hdpcmo),15108(hdpcoe),15104(hdpnanalytics),15144(rscmo),15143(rsnanalytics),15152(rsnanalyticssec),15159(s2hdp19grp)


How to copy Xbox info from USB?

Question: I have a USB that I formatted to use with my Xbox. It worked fine, used it for ages, no issue.
Now though, I have not used it on my Xbox for quite a while, so I was wondering if I might be capable of copying the data from the USB, onto my PC for temporary storage, then format the USB once more and use that as per normal?
(I do realize I can simply copy the data off the USB onto my Xbox, but that is a last resort at this point - Xbox is packed up etc.)
Answer: I believe there is a hidden folder that the 360 makes on external storage devices. The path under Windows is (drive letter):\Xbox360\ and should contain a number of Data000* files
Note: This is the format for the Xbox 360. I am unsure if the same method is used for the Xbox One.
If you copy this folder off, you should be able to use your flashdrive normally, however other problems may arise from reformatting. Please also note: this is not an official method, as the only properly supported method is to copy your save files with the 360 itself.

How to copy Xbox info from USB?


Problems installing Ubuntu 12.04 alongside Windows XP

Question: I have been trying to install Ubuntu for the last few days, but somehow it doesn't work. During the installation I keep getting this message:
<code>BusyBox v1.18.5 (ubuntu 1:1.18.5-1ubuntu 4.1) built-in shell (ash)
Enter 'help' for list of built-in commands.

(initramfs)
</code>
Comment: Downvote: Not enough information to be able to help. Anyway check: http://askubuntu.com/questions/162075/my-computer-boots-to-a-black-screen-what-options-do-i-have-to-fix-it/162078#162078
Comment: Dito: Please edit your question to add information about the hardware you are running on. Give more details about what happens when you try to install.
Answer: This means the graphical system could not be booted. Maybe the graphics card is not supported. We need more details to help you. What is your hardware and what did you do so far?
You can edit your question to add more specifics.