What do I need to use one winch motor independently on several different cables (for overhead storage)?

Question: I'm almost-nearly-started on installing a bunch of motorized ceiling-storage platforms in my garage.  I was researching which winch/hoist to buy when I realized that I'd rather not buy one electric winch motor per platform.
Is there a gearbox of some sort where I could hook up a single motor to a half-dozen (or so) reels, and select which reel gets rotated?  I would hook each reel up to one ceiling-storage platform.  Each reel would have to have a brake of its own, so when it's not engaged, it doesn't rotate.  (The stuff on the ceiling needs to stay on the ceiling when the motor isn't hooked up to it.)
Edit: I don't have access to a machine shop.  I'm trying to figure out if it's cheaper to go for the gearbox, or just one winch per platform (at around $75 each).  I'll build the platform and set up the pulleys myself.  I figure that each platform + stuff will weigh around 200 pounds, and the current plan will have enough pulleys to have a 4:1 lift ratio.  (I'm going to use a single cable that goes back and forth to the ceiling several times, for stability.)
Comment: How much weight are you lifting?  How much money are you willing to spend? Do you have access to a machine shop, to fabricate parts?
Comment: Looking at the rear wheel of a 10 speed bike, may provide some inspiration.
Answer: I have two of these Racor Heavy Lifts in my garage now.  I also had one in my old house.  They now have a rod that you can connect to a drill to raise and lower the platforms.  At $127 they are very affordable and work quite well.  I store my lawnmower on it in the winter and the snowblower on it in the summer along with some other items that are not used very often like my wheelbarrow.
Comment: Official [Racor](http://www.racorinc.com/Default.aspx) site.
Answer: At 4:1, 200 lbs should not be difficult to lift by hand.  Save yourself the $75 and just buy a rope cleat to secure the lift cable.
Comment: +1 Simple is always a good solution.  Though even at 4:1, it's more work than pushing a button.
Answer: The first thing that comes to mind for me, would be to attach multiple gears to a long axle driven by a motor. Since you don't want to drive all the winches at once, you'd have to devise a way for the axle to spin independently of each gear. So the first pieces you'd need are gears with collars, that would fit just over the axle.

Putting a hole in the collar, would give you a way to engage the axle and make the gear spin with it. So you'd need some type of "pin" to fit in the hole, and connect to the axle. The idea here is that when the "pin" is not engaged, the axle would spin while the gear slips and stays stationary. Engaging the "pin", would cause axle and gear to spin together.

The next thing you'd need is some type of spacers, to prevent the gears from sliding along the length of the axle.  This will allow you to have multiple gears along the axle, while keeping them each in place and engaged with the gear on the reels.
For each cable you want to control, you'll need a winch with a gear like this.

Just remove the handle, and have the gear on the axle engage the gear on the winch. These type of winches should already have a locking mechanism, that prevents the cable from coming unwound. So once you raise the load, you shouldn't have to worry about it falling.
You should be able to add as many gears as you need to the axle, so you can control each winch independently.

Keep in mind this is just a basic idea; there are surely design flaws that would need to be worked out, but it might be enough to spark your creativity.


How does a "power set" work on proper classes?

Question: I am trying to understand what the notion of "power set" means when we consider a class $A$ that is not a set (a proper class), where the definition of the "power set" of $A$ is:

$\mathcal{P}(A) = \{x: x \subseteq A\}$

I have a theorem that states:

If $A$ is a set then $x \in \mathcal{P}(A) \iff x \subseteq A$.

So, unless this theorem was intentionally written in a confusing way, this seems to indicate that one of these implications breaks for $A$ being a proper class. But that also seems to contradict the definition. So... what's going on here?
Another piece of information I have is that $\mathcal{P(U)} = \mathcal{U}$ where $\mathcal{U}$ is the universe in which we are working (and $\mathcal{U}$ is not a set).
So what exactly does it mean to take the power set of a proper class?
Comment: It's important to note that if you're working in a theory like ZF, and $A$ is a proper class, $\exists x(x=A)$ is false. So you can't even apply an instance of the power set axiom to $A$ to start with. In ZF, proper classes are a figure of speech, and not actually things in the theory.
Answer: If you're working in a theory that doesn't allow proper classes to be elements (as I suspect you are), the best we can do is to construct the class of subsets of $A$. This class will be a proper class, so we should probably call it the power class of $A$. Your theorem will then apply for sets $x$.
Note also that $\mathcal{P}(\mathcal{U})$ is the class of subsets of $\mathcal{U}$, i.e. $\mathcal{U}$ itself as required. If this seems at odd with Cantor's theorem, note the latter's proof constructs something that would be a proper class and hence no element of $\mathcal{U}$, so the theorem doesn't work for proper classes' power classes.
You might want to modify these ideas to interpret the union of a proper class, $\bigcup A$.
Comment: @dandar In your example the power set axiom implies $\mathcal{C}$ is a set, as is $\mathcal{P}(\mathcal{C})$. However, $\{y|\exists Y\in\mathcal{C}(y\in Y)\}$ is an in general different set, $\bigcup\mathcal{C}$ by the union axiom. In particular, if $\mathcal{C}\subseteq\mathcal{P}(X)$ then $\bigcup\mathcal{C}\subseteq X$.
Comment: @dandar The easiest approach is that if $X$ is a set so are $\mathcal{P}(X)$ (that's an axiom), as is $\mathcal{P}(\mathcal{P}(X))$ (same axiom), whence so is $\mathcal{C}$.
Comment: A bit late to the game here. So if $\mathcal{C}$ is a class of subsets of an underlying set $X$, i.e. $Y\in\mathcal{C}$ implies $Y\subseteq X$, is it correct to define the set of all subsets of $\mathcal{C}$, denoted as $\mathcal{P}(\mathcal{C})$, as $\mathcal{P}(\mathcal{C})=\{y:y\in Y \text{ for some }Y\in\mathcal{C}\}$. If so $\mathcal{P}(\mathcal{C})$ is a set and not a class (as required), and furthermore $\mathcal{P}(\mathcal{C})=\bigcup\mathcal{C}$. Also how does this defintion (of a set) differ from the class of all subsets of $\mathcal{C}$?
Comment: +1 for informative answer and (if I could give it) +1 for speed of response. So a set $A$ is *by definition* a set if and only if there exists a set $\mathcal{P}(A)$ which is defined in the power set axiom? Now I learnt in basic set theory that if $A=\{a,b,c\}$ that $\mathcal{P}(A)=\{\emptyset,\{a\},\{b\},\{c\},\{a,b\},\{b,c\},\{a,c\},A\}$ is a *class*.
Comment: But you are saying because, say, $\{a,c\}\in \mathcal{P}(A)$ implies and is implied by $\{a,c\}=\{\{a\},\{a,c\}\}\in\mathcal{P}(\mathcal{P}(A))$, and this holds for all elements of $\mathcal{P}(A)$, that $\mathcal{P}(A)$ satisfies the power set axiom and so is a set? So applying this logic to $\mathcal{C}$ and $\mathcal{P}(\mathcal{C})$ we arrive at your claim that $\mathcal{C}$ and $\mathcal{P}(\mathcal{C})$ are in fact both sets?
Comment: I now see what you mean by $\bigcup\mathcal{C}:=\{y:\exists Y\in\mathcal{C},y\in Y\}\not=\mathcal{P}(\mathcal{C})$ in general. For instance $X=\{a,b,c\}$ and $\mathcal{C}=\{a,\{b,c\}\}\subset X$ give $\mathcal{P}(\mathcal{C})=\{\emptyset,\{a\},\{b,c\},\{\{a\},\{b,c\}\},\mathcal{C}\}=\{\emptyset,\{a\},\{b,c\},X,\mathcal{C}\}$ and $\bigcup\mathcal{C}=\{a\}\cup\{b,c\}=X$. Thus $\mathcal{P}(\mathcal{C})\not=\bigcup\mathcal{C}$.
Comment: Furthermore, as you state, since $\mathcal{P}(X)=\{\emptyset,\{a\},\{b\},\{c\},\{a,b\},\{b,c\},\{a,c\},X\}$ then $\mathcal{C}\subset\mathcal{P}(X)$ and $\bigcup\mathcal{C}\subseteq X$. Previous to this new knowledge, where necessary I always thought of a class as a set whose elements are sets - I never realised you could formally prove it is a set. So....what classes are *not* sets (proper classes?). This possibility of proper classes then prevents Russell's paradox? I realise I am into dangerously philsophical things here (for me anyway)!
Comment: @dandar You have a few misconceptions. Sets are classes that are elements of some class; it's classes that are more general. A set's power set is a set.
Comment: It is not surprising I have misconceptions about this concept. Thank you for your patience. So a class $\mathcal{C}$ is not a set - i.e. there exists no power set $\mathcal{P}(\mathcal{C})$ of this class by which to prove $\mathcal{C}$ is a set?
Comment: @dandar In the example you gave, $\mathcal{C}\subseteq\mathcal{P}(X)$ so $\mathcal{C}$ is a set.
Comment: Thank you for the clarification. So $\mathcal{P}(X)$ being viewed as a class, and $\mathcal{C}\subseteq \mathcal{P}(X)$ means, by definition (power set axiom) that $\mathcal{C}$ is a set? In exactly the same way, $\mathcal{P}(\mathcal{P}(X))$ being viewed as a class (i.e the class of subsets of the class $\mathcal{P}(X)$) and $\mathcal{P}(X)\subseteq\mathcal{P}(\mathcal{P}(X))$ means by definition that $\mathcal{P}(X)$ is also a set? Thus $\mathcal{P}(X)$ is both a class and a set?
Comment: Many thanks I think this is slowly sinking in. I will go and study some of these axioms and reflect on this.


Reading .csv file into C LinkedList

Question: I have the following struct:
struct NODE {
    char username[50];
    char password[50];
    char usertype[50];
    struct NODE *next;
} *head=NULL;

I would like to read from a .csv file, say database.csv of the form username, password, usertype, tokenize each line into tokens using strtok and put each token inside the right field. For instance, my file looks like this:
johnnydepp, pirate123, user
tonystark, iron456, sysop
I keep reading on C LinkedList, but I cannot figure it out. Any help would be greatly appreciate, or any good references on how to implement a LinkedList in C.
My main problem is putting element in the each of the node. I know how to use strtok to tokenize a line in a file. This is what I have done so far:
void createList() {
    FILE *data;
    data = fileopen("password.csv", "r");
    char parsedLine[50];
    while (fgets(parsedLine, 50, data) != NULL) {
    char *ptr = strtok(parsedLine, ", ");
        node *temp;
        temp = (node*)malloc(sizeof(node));
    // I am stuck here //
}

Thanks!
EDIT
Will this work?
extern void createList() {

FILE *data;
data = fileopen("password.csv", "r");
char parsedLine[50];
while (fgets(parsedLine, 50, data) != NULL) {
    struct NODE *node = malloc(sizeof(struct NODE));
    char *getUser = strtok(parsedLine, ", ");
    strcpy(node->username, getUser);
    char *getPass = strtok(NULL, ", ");
    strcpy(node->password, getPass);
    char *getType = strtok(NULL, ", ");
    strcpy(node->usertype, getType);
    node->next = head;
    head = node;
}
fclose(data);

}

Comment: What is it you have trouble with? The linked list? Reading/parsing the CSV file? Can you be more specific, and if possible show us the code you tried (but please read http://sscce.org/ before posting all your code).
Comment: You'll need to allocate the new node once in the loop; then you'll need to call `strtok()` three times (and `strcpy()` too) to split the input line and copy the values found into the new node. When you're sure the data is valid, you hook the new node into the list as in Joachim's answer. If there's a problem, you must decide what to do about it — abandon ship, release the new node and try again with the next line, or ... I'm not a big fan of `strtok()` for a number of reasons. It works OK in limited contexts like this, but you must be very careful with it. Don't use it in a library function.
Answer: It's actually very simple... You have a NODE structure, which contains a next pointer, and a variable head which points to the head (first node) of the list. The head pointer starts out as NULL meaning the list is empty.
To add a node you create a node, then set the newly created nodes next pointer to point to the current head of the list, and set the head to point to the new node:
/* Allocate new node */
struct NODE *node = malloc(sizeof(struct NODE));

/* Link to the current head */
node->next = head;

/* Make the new node the head of the list */
head = node;

After doing this once, you have a list containing one node. After doing it twice you have a two-node list. Etc.
Comment: Now that I have this clear in my head, may I ask if my synthax for `strtok` is correct? How do I store the content of my `.csv` file inside the field of a node? Perhaps I should make a `add(struct NODE *p)` function to loop through my file and keep adding nodes to my list?
Comment: @iHubble I recommend putting all list-handling in separate functions. The `strtok` call is good to get the first sub-string, use a loop with `strtok(NULL, ", ")` to get the remaining values. After you have done the `strtok` use `strcpy` to copy to the correct fields: `strcpy(node->username, ptr);` etc.
Comment: I need to use an `add` method to add any node to my `LinkedList`. Such function uses a pointer to a node, as I wrote above. How could I read from my `.csv` file and use this `add` function at the same time?

Reading .csv file into C LinkedList


Commutative rings such that all non-units are zero divisors

Question: The construction of the total ring of fractions shows that any commutative ring (with 1) can be put inside a ring whose non-units are zero divisors.
Examples of these rings are the products of fields.
Are there other examples? Do these rings have a standard name?
Comment: Any finite commutative (unital) ring.
Comment: Such rings are discussed in [this MO thread](https://mathoverflow.net/questions/42647/rings-in-which-every-non-unit-is-a-zero-divisor)  (link is from this  [old comment](https://math.stackexchange.com/questions/98154/zero-divisors-and-units-for-the-ring-mathbbz-n-mathbbz-with-integer-n/98168#comment231219_98168))
Comment: Similarly, any algebra of finite dimension over some field.
Comment: Aha, I forgot they can be non-reduced...
Comment: [Related](https://math.stackexchange.com/q/573563/29335) but a different question.
Comment: Also [related](https://math.stackexchange.com/a/95248/242)
Answer: Following Lam's Lectures on modules and rings these would be called commutative classical rings because they are equal to their localizations at their set of regular elements. (See section 11 in the book.)
That is, all the regular elements are already units: therefore something which isn't a unit has to be nonregular, i.e. a zero divisor.
The broadest, easily described subclass, I think, is that of strongly $\pi$-regular rings, which are rings that satisfy the DCC on all chains of the form $xR\supseteq x^2R\supseteq x^3R\supseteq\cdots$ for every $x\in R$.
That includes all one-sided artinian rings and all von Neumann regular rings, covering all examples given in the comments and in the original post.
Suppose, though, that you fabricate strongly $\pi$-regular rings $R_i$ such that there exists $x_i\in R_i$ satisfying $x_i^iR\neq x_i^{i+1}R$.  Then in $R=\prod_{i=1}^\infty R_i$, it is easy to see that nonunits are zero divisors, but $R$ is not strongly $\pi$-regular, because the element $x=(x_1, x_2,\ldots)$ spoils things.  So at least we can say rings with your condition are a strictly bigger class than the strongly $\pi$-regular rings.
Comment: @OP Beware that Lam's terminology "commutative classical ring" is rarely used by others, so most readers will likely have no idea what it means.
Comment: To give a helpful version of the preceding comment: in the past, authors in articles have also called these types of (commutative) rings "quasi-regular" or "O-rings".  (The author had these in mind but did not mention it for some odd reason.)


how to create my own 'cout' and 'cerr' class

Question: How do I create my own class that behaves exactly like: std::cout & std::cerr.
I am writing a mini operating system and this is a requirement, having these as modules there.
The code will look like:
myNewCoutClass myCout; // create cout behavioral class
myNewCerrClass myCerr; // create cerr behavioral class

myCout << someString << endl; // prints the string
myCerr << someString << endl; // prints the string as error

Comment: The `new` is not necessary. In fact, your example won't work until you dereference `myCout` and `myCErr`, which are pointers. Avoid the pointers.
Comment: _"failed to find anywhere answers for that, i will appreciate simple answers."_ That smells a bit contradictorily, not? Your question seems way too broad. You may start out with studying the implementation of `std::cin` and `std::cout`.
Comment: @Tango_Chaser: "Print it to the screen" is exceptionally vague. How is your "screen" implemented? What is it?
Comment: @Tango_Chaser: Um, then use `std::cout`.
Comment: what i found was mostly overriding of the "<<" operators in classes i use, which is not useful for me.
Comment: @Tango_Chaser: It may be. We can't say, because we have no idea how you want these classes to work, beyond having an ostream interface
Comment: @Lightness Races: I want the classes to behave as the simplest cout functions possible. to receive a string and pint it to the screen.
Comment: @Lightness Races: the user will be able to see on the screen the string that the new class received. In a 'regular' print and in error output.
Comment: @Tango_Chaser: You didn't answer my question. Explain how the functionality required differs from `std::cout`.
Comment: @Lightness Races: it does not. it behaves exactly the same.
Comment: @Lightness Races: yes.. well i can't. i need to create my own class to do the same thing.
Comment: @Tango_Chaser: Sorry but that makes very little sense. One concept you need to understand is that `std::cout` and `std::cerr` are instantiations of `std::ostream`; they're not classes. They're instances, pre-defined to use _stdout_ and _stderr_ as their data sinks. You can trivially make your own instantiations that do the same thing, but they will be _identical_, just the same objects, with different names. Utterly pointless. You could reinvent `std::ostream` too if you really want to give yourself more work, but then you're back to "what I found was mostly overriding of the << operator".
Comment: @Lightness Races in Orbit: what you just told me makes sense and helped me understand the problem better. it is EXACTLY what i'm trying to do.
Comment: @Tango_Chaser: If you're making a "mini-OS", there'll be far more value in reimplementing _stdout_ itself if anything. But we don't have any details on the scope of your OS.
Answer: First things first, don't do this unless you know very well what you're doing, and are willing to take all of the risks involved.  It's just an example of how one could bind another stream to stdout, in effect creating a second cout, as a thought experiment.  That said, here we go.

If you want to create another stream for stdout, you have to take a good look at your compiler's deep, dark innards, and find out how it defines cout, cerr, and/or clog.  This will be in a compiler-dependent location, and most likely not where you expect; for example, on older versions of Visual Studio, you would have to look at a few of the files in the crt\src folder:
// Visual Studio 2010 implementation of std::cout.
// Irrelevant parts omitted.

// cout.cpp
__PURE_APPDOMAIN_GLOBAL static filebuf fout(_cpp_stdout);
#if defined(_M_CEE_PURE)
__PURE_APPDOMAIN_GLOBAL extern ostream cout(&fout);
#else
__PURE_APPDOMAIN_GLOBAL extern _CRTDATA2 ostream cout(&fout);
#endif

struct _Init_cout
    {
    __CLR_OR_THIS_CALL _Init_cout()
        {
        _Ptr_cout = &cout;
        if (_Ptr_cin != 0)
            _Ptr_cin->tie(_Ptr_cout);
        if (_Ptr_cerr != 0)
            _Ptr_cerr->tie(_Ptr_cout);
        if (_Ptr_clog != 0)
            _Ptr_clog->tie(_Ptr_cout);
        }
    };
__PURE_APPDOMAIN_GLOBAL static _Init_cout init_cout;

// stdio.h
#define _INTERNAL_BUFSIZ 4096
// ...
#define _IOB_ENTRIES 20
// ...
#ifndef _STDSTREAM_DEFINED
#define stdin (&__iob_func()[0])
#define stdout (&__iob_func()[1])
#define stderr (&__iob_func()[2])
#define _STDSTREAM_DEFINED
#endif  /* _STDSTREAM_DEFINED */

// _file.c
char _bufin[_INTERNAL_BUFSIZ];

FILE _iob[_IOB_ENTRIES] = {
    /* _ptr, _cnt, _base,  _flag, _file, _charbuf, _bufsiz */
    /* stdin (_iob[0]) */
    { _bufin, 0, _bufin, _IOREAD | _IOYOURBUF, 0, 0, _INTERNAL_BUFSIZ },
    /* stdout (_iob[1]) */
    { NULL, 0, NULL, _IOWRT, 1, 0, 0 },
    /* stderr (_iob[3]) */
    { NULL, 0, NULL, _IOWRT, 2, 0, 0 },
};
_CRTIMP FILE * __cdecl __iob_func(void)
{
    return _iob;
}

// `__PURE_APPDOMAIN_GLOBAL` is an internal macro that can generally be ignored.
// `_CRTIMP` is an internal macro that can generally be ignored.
// `_CRTDATA2` is an internal macro that can generally be ignored.
// `__CLR_OR_THIS_CALL` is a calling convention macro that expands to either
//   `__clrcall` or `__thiscall`.

From this, we can derive our own stream for stdout, although it'll be compiler-dependent.
// Visual Studio 2010 user-created char16_t cout.
// Note that in VStudio 2010, char16_t is actually a typedef for unsigned short.
#include <iostream>
#include <fstream>
#include <string>
#include <codecvt>

#define _cpp_stdout (&(__iob_func())[1])
typedef std::basic_filebuf<char16_t, std::char_traits<char16_t>> filebuf_c16;
typedef std::basic_ostream<char16_t, std::char_traits<char16_t>> ostream_c16;

int main() {
    filebuf_c16 f16out(_cpp_stdout);
    ostream_c16 c16out(&f16out);
    // It really should be tied to the other stdin/stdout/stderr streams,
    //   but this is a simple program where it won't be a problem.

    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> converter;

    std::string u8tmp = "Hello from char16_t!";
    std::u16string u16str = converter.from_bytes(u8tmp);

    c16out << u16str << std::endl;
}

And the results...
Hello from char16_t!

If you wanted to tie a second standard ostream (a.k.a. a basic_ostream<char, char_traits<char>>) to stdout, you could use something similar.  Note that as fout is static, you would need to make your own filebuf.  Also note that this is just asking for trouble, but that's beside the point; just be careful of data races, or anything of the sort.

Note that while you can do this, unless you know very well what you're doing, are willing to take responsibility for anything that goes wrong, and are willing to spend enough time delving into your compiler's library and/or code to find out how exactly it implements stdout and the default strings, you very well shouldn't do it.
Also note that your code will be tightly coupled to the compiler, and there's a very high probability that future versions of the same compiler may break it.  For example, to my knowledge, this code won't compile with Visual Studio 2015 because of changes to the CRT (specifically, I believe it's because of changes to FILE, but I didn't look into it).
Answer: These objects are std::ostreams. You can create your own std::ostream. Precisely how that'll work depends entirely on the data sink, which you haven't specified, but an std::ostringstream will be enough to get you started on testing the code that uses it.
However, if you literally wish to reinvent std::cout, don't. Its data sink is the magic file handle stdout, which you can't recreate as it's provided by the OS. You could create a std::ostream that steals that buffer from std::cout but what's the point?
Comment: @Tango_Chaser: _"yet it all goes to std::cout at the end"_ No it doesn't. Perhaps spend more than four minutes looking into it, yeah?
Comment: std::ostringstream helps me use functions on stream, yet it all goes to std::cout at the end.  how do i implement my own cout?
Comment: i will deepen my understanding on that subject, thank you.


Vulkan: failed with VK_ERROR_INITIALIZATION_FAILED

Question: I've been running Overwatch using Lutris on my MSI Laptop (see link for specs). However, recently I've been encountering problems. When I try to run Overwatch, a get this error message:
No compatible graphics hardware
0xE0070160

It used to all work fine. I ran the command vulkaninfo and the following error message showed up:
/build/vulkan-tools-_xrZWD/vulkan-tools-220.127.116.11+dfsg1/vulkaninfo/vulkaninfo.c:630: failed with VK_ERROR_INITIALIZATION_FAILED

So there seems to be something wrong with vulkan, which I suspect might be the cause of the Overwatch problem.
However, this all used to work fine. The only thing I can think of that might have caused issues is me installing i3wm, but I'm really not sure.
I've reinstalled vulkan several times, as well as Lutris and my Nvidia drivers. No luck.
I'm using Ubuntu 18.04.3. I installed Overwatch by following this tutorial. According to this my graphics card should support vulkan.
Any ideas?
(Might want to add that I'm really new to linux.)
Answer: What worked for me was the following from terminal:

Install mesa-vulkan-drivers and vulkan-tools
sudo apt update
sudo apt upgrade`
sudo apt install mesa-vulkan-drivers vulkan-tools`

Edit /etc/default/grub using
sudoedit /etc/default/grub

and append
amdgpu.si_support=1 radeon.si_support=0 amdgpu.cik_support=1 radeon.cik_support=0

to GRUB_CMDLINE_LINUX_DEFAULT.
Example: Change
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

to
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash amdgpu.si_support=1 radeon.si_support=0 amdgpu.cik_support=1 radeon.cik_support=0"

Save the edit

Update GRUB and restart the system.
sudo update-grub2
shutdown -r now

Comment: Correction!  It worked at first, then stopped working (don't ask me why).  I played around with the options and this ended up working.
`GRUB_CMDLINE_LINUX_DEFAULT="quiet splash amdgpu.si_support=1 radeon.si_support=0 amdgpu.cik_support=1 radeon.cik_support=1"`

I changed radeon.si_support to 1.
Comment: This worked for me thanks!  Minus appending "amdgpu.si_support=1 radeon.si_support=0 amdgpu.cik_support=1 radeon.cik_support=0" to /etc/default/grub.  That threw an error for me,


Numbers & escape characters for regex replacement in Notepad++

Question: I'm trying to match a pattern using RegEx in notepad++, but not having much luck. I'm able to match part but not all of it.
I need to search for this line:
    <size value="Large" pax="13074"/>

And replace it with this:
    <size value="Very_large" pax="41450"  cargo="Largest" cargovolume="3227"/>

Essentially I need to find all patterns matching pax="n"/> and replace them with pax="n" cargo="Largest" cargovolume="0"/> while retaining the initial value of n.
So, ideas anyone?
Comment: Do you need to replace them with the same `n`?
Comment: Yes, the n value should be retained.
Answer: Press Ctrl + F, move to tab Replace, in Find what do: pax="(\d+)" and in Replace with put this: pax="\1" cargo="Largest" cargovolume="0"
Remember to mark regex. That should retain the number and replace the content.
UPDATE: Hint about saving text for replacement.
Whenever you use regex to do text replacement, wrap the content you want to save in parenthesis and then you can access them using \i where i is the order of appearance of the parenthesis starting at 1.
Hope it helps!
Comment: Actually I noticed I left this behind `/>` in the _Replace with_. That's not necessary because it will duplicate in the answer, you can press Ctrl+Z and remove it :)


How do you get inside the hidden chambers on fy_buzzkill?

Question: How do you get inside the hidden chamber(s), behind the escalators, on fy_buzzkill I'm playing version 1.6.
Edit: I noticed a couple of players were able to crawl inside the escalator, camp and shoot anyone who lurked in that area from inside.
Normally, the escalator throws you in the air when you step, walk or run on it. However, a player asked me to crouch+move onto the escalator; when I did I went straight through the escalator. There isn't any ammo or easter egg there but it is a very, very good place to camp.
Now, next day I tried to repeat the trick over and over again (multiplayer and local) but failed. I need "steps to reproduce the behavior".
Here is screenshot in overview mode:

Move around here and there so that some of the wall and other textures disappear which reveals the space for camping:
Comment: It's most likey not a secret room, most people mame things hollow to simplify the map building process.
Answer: As @Nitrous Oxide said above.  It is not a "Secret Room" per say -  It is a secret glitch that players exploit to get kills from un-expecting victims. Its a cowards paradise.
If you crouch and walk at the correct angle into the corner of the "treadmill" you can essentially "slip" into the underside of the ramp where you can see through the ramp, clear as day, and fire through it to attack enemies.  I haven't played on this map in a long time but if I remember correctly people are unable to shoot through the ramp to hit you while in there.  I hope this helps out!  Happy Camping!


Extract comments from R source files, keep function in which they occurs

Question: I would like to extract comments (matching to patterns) from my R source script keeping the functions in which they occurs.
The goal is to write documentation comments inside function body code using classic markdown checkboxes - [ ] or - [x] and extract those comments for further processing as list of character vectors - which I can easily write to new .md file.
Reproducible example and expected output below.

# preview the 'data'
script_body = c('# some init comment - not matching pattern','g = function(){','# - [x] comment_g1','# - [ ] comment_g2','1','}','f = function(){','# - [ ] comment_f1','# another non match to pattern','g()+1','}')
cat(script_body, sep = "\n")
# # some init comment - not matching pattern
# g = function(){
#     # - [x] comment_g1
#     # - [ ] comment_g2
#     1
# }
# f = function(){
#     # - [ ] comment_f1
#     # another non match to pattern
#     g()+1
# }

# populate R souce file
writeLines(script_body, "test.R")

# test it
source("test.R")
f()
# [1] 2

# expected output
r = magic_function_get_comments("test.R", starts.with = c(" - [x] "," - [ ] "))
# r = list("g" = c(" - [x] comment_g1"," - [ ] comment_g2"), "f" = " - [ ] comment_f1")
str(r)
# List of 2
#  $ g: chr [1:2] " - [x] comment_g1" " - [ ] comment_g2"
#  $ f: chr " - [ ] comment_f1"

Answer: Here's a stripped-down, unevaluated variant of what hrbmstr has done:
get_comments = function (filename) {
    is_assign = function (expr)
        as.character(expr) %in% c('<-', '<<-', '=', 'assign')

    is_function = function (expr)
        is.call(expr) && is_assign(expr[[1]]) && is.call(expr[[3]]) && expr[[3]][[1]] == quote(`function`)

    source = parse(filename, keep.source = TRUE)
    functions = Filter(is_function, source)
    fun_names = as.character(lapply(functions, `[[`, 2))
    setNames(lapply(attr(functions, 'srcref'), grep,
                    pattern = '^\\s*#', value = TRUE), fun_names)
}

This comes with a caveat: since we don't evaluate the source, we may miss function definitions (for instance, we wouldn't find f = local(function (x) x)). The above function uses a simple heuristic to find function definitions (it looks at all simple assignments of a function expression to a variable).
This can only be fixed using eval (or source), which comes with its own caveats — for instance, it's a security risk to execute files from an unknown source.
Comment: Thanks both. I've made a wrapper for easier use on package development. Described on blog [here](http://jangorecki.github.io/blog/2015-09-18/Function-body-documentation.html)
Comment: jangorecki - you shld prbly accept this as the answer so i can delete mine (Konrad's is a much better solution)
Comment: @hrbrmstr Respectfully disagree.
Comment: @hrbrmstr I will accept this one but don't delete yours, it answers the question, it is good, it teach people, I see it valuable too!
Comment: _"it's a security risk…"_ given what `data.table` did with tracking code in their CRAN package vignettes, (`source`, `library`, etc al) is a security risk in general IMO.
Comment: @hrbrmstr Ouch, didn't know about this. Sounds horrible.
Comment: Also live example: [logR source code description](https://github.com/jangorecki/logR/blob/804b6177e70043c92c83dc8840de391d9a107b76/inst/doc/doc.md). It seems to be nice to fill the gap between the source code and project functional requirements. If anybody is able to boost the code by matching number on whitespaces to produce nested lists in markdown feel free to contribute :)
Answer: It's unlikely anyone is going to write the grep / stringr::str_match part for you (this isn't a grunt code-writing service). But, the idiom for iterating over parsed function source might be useful enough to a broader audience to warrant inclusion.
CAVEAT This source()s the .R file, meaning it evaluates it.
#' Extract whole comment lines from an R source file
#'
#' \code{source()} an R source file into a temporary environment then
#' iterate over the source of \code{function}s in that environment and
#' \code{grep} out the whole line comments which can then be further
#' processed.
#'
#' @param source_file path name to source file that \code{source()} will accept
extract_comments <- function(source_file) {

  tmp_env <- new.env(parent=sys.frame())
  source(source_file, tmp_env, echo=FALSE, print.eval=FALSE, verbose=FALSE, keep.source=TRUE)
  funs <- Filter(is.function, sapply(ls(tmp_env), get, tmp_env))

  lapply(funs, function(f) {
    # get function source
    function_source <- capture.output(f)
    # only get whole line comment lines
    comments <- grep("^[[:blank:]]*#", function_source, value=TRUE)
    # INCANT YOUR GREP/REGEX MAGIC HERE
    # instead of just returning the comments
    # since this isn't a free code-writing service
    comments
  })

}

str(extract_comments("test.R"))
## List of 2
##  $ f: chr [1:2] "# - [ ] comment_f1" "# another non match to pattern"
##  $ g: chr [1:2] "# - [x] comment_g1" "# - [ ] comment_g2"

Comment: "I do this since source() preserves comments whereas parse does not." — Nah, that's not true, they behave the same. In fact, `source` uses `parse` internally.
Comment: My attempt at brevity was probably unwarranted (I know it keeps it but getting to the comments via parse is a pain). I'll re-phrase.
Comment: Evaluation is not a problem so your solution is perfect, I will work on regex myself - agree with your comment on that. Thanks!
Comment: @hrbrmstr I don't find expressions more complex to deal with than evaluated functions (see my answer) but the answer is otherwise good. One huge caveat: your `source` is non-locally, so it will dump stuff into the global namespace. Make it evaluate in an empty environment instead. [Also, `source` has a bug under Windows](http://stackoverflow.com/q/24454559/1968) in that it cannot deal with UTF-8. The only workaround I know is to use `eval(parse(…))` instead of `source(…)`.
Comment: gd point. commentary removed and environment pollution localized. thx


OpenGL method number value

Question: I have seen OpenGL codes written like this:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(1,1,1,1,1,-1);
glMatrixMode(GL_MODELVIEW);

and I have seen OpenGL codes written like this:
glEnable(2896);
glDisable(3042);

Notice the number values in the glEnable() and glDisable() methods.
My real question is: Does anyone have a link to a website that has a list of every method or which number value corresponds to whichever mode you are putting in the code? Like, what does glEnable(2896); actually mean?
Comment: Whoever wrote the code using those magic numbers needs to be shot. At the very least, use base-16 values so that you can look up the enum by value.
Comment: @AndonM.Coleman: Shooting that guy is far to benign IMHO. I'm open for suggestions for harder punishments.
Comment: @datenwolf: The Human Rendering Pipeline?
Answer: The enum names and values live in gl.xml, off of the main spec registry page.
Given your example of glEnable(2896):

2896 in hex is 0x0B50

Searching gl.xml for that value lands you on
<enum value="0x0B50" name="GL_LIGHTING"/>

Which you can see corresponds to GL_LIGHTING
Answer: The numbers are the numeric values for OpenGL tokens as defined by the OpenGL specification. You can find the specifications for the various OpenGL versions at http://www.opengl.org/registry/
The definitions for the tokens is written down in a form usable by a C or C++ compiler in the GL/gl.h header file.
However it's strongly discouraged to use the numeric values, since in code they're just magic numbers.

Like, what does glEnable(2896); actually mean?

Just search the GL/gl.h for the token which is defined to this value. They're usually written in hexadecimal so you have to convert that decimal representation first. Like this (using a *nix style shell):
dw ~ % grep $(printf '%X' 2896) /usr/include/GL/gl.h
#define GL_LIGHTING                             0x0B50

OpenGL method number value


Variable Redux State Structure

Question: Situation:
I have a tabbed react-redux application, and I'm trying to figure out how I should best structure the state (redux store/slices). Each "tab" has a resourceRef which looks something like "app://new-tab" or "app://user/1234567890" - and the component that renders when a tab is selected is determined by its resourceRef (e.g. an "app://new-tab" resourceRef will render a <NewTab> component, an "app://user/1234567890" resourceRef will render a <UserDisplay> component, etc.).
Currently I have tabsSlice which handles the tabs (adding, removing, updating tab state, etc.). The tabSlice's state looks like the following:
initialState: {
    tabs: [],
    activeTabUid: null
}

// Where tabs look like:
// {
//   title: (String),
//   resourceRef: (String - e.g. "app://new-tab"),
//   uid: (String - unique tab identifier),
//   componentState: (Object - serializable state object)
// }

// And updating a tab's componentState works like so:
reducers: {
    updateTabState: (state, action) => {
        const {updateIndex, tabState} = action.payload;
        state.tabs[updateIndex].componentState = tabState;
    }
}

The problem is that I have componentState persisted in each tab object of the tabsSlice reducer. My current solution is to manage the state at the parent page component level (e.g. <NewTab>) - pulling tab state via useSelector(selectTabState(tabUid)), and then creating a bunch of state-updating functions to pass down to the child components. This doesn't feel very Redux-y, and I would like to have all of my pages be managed by Redux slices - i.e. have a slice for <NewTab>, <UserDisplay>, and all of my other possible page components. The problem is, I can't see how to achieve this, since these page states are managed within an array in another slice.
Question:
How do I structure this application state such that I can use slices for everything (e.g. a slice inside of a slice)? Is it even possible? If it's not possible, is my current solution a reasonable one?
My understanding of Redux application state structuring is novice at the moment, and so any advice or links to helpful resources would be appreciated.

Clarifying Note: It's perfectly reasonable to expect multiple tabs of the same page-type in this application. There might be many UserDisplay tabs open, for example - each one with its own separate state, displaying a separate user.
Answer: I was able to resolve this architectural challenge by removing page state from the parent tab slice and creating reducer slices for each page-type that I want in my system. Each page slice has a collection of pages of that type, and the actions required for updating any single page.
The following considerations were made:

The individual page states (child state) could not be kept within the tabs state (parent state) - it makes some sense to do this, as each page state is always tied to a tab. But there were found to be no good ways to manage complex and variable child component state within a parent slice. If the child pages were not variable, managing it from within the parent would not have been an issue.

There may be multiple instance of each page present in the tabs at a given time. This means that a simple slice, meant to handle a single instance of a page would not work - the page slices had to be designed to accommodate any number of pages of their type.

An example page slice of this nature might look like:
const initialPageState = {...};

export const slice = createSlice({
  name: <SliceName>,
  initialState: { instances: {} }, // Where a key/value entry looks like {[uid]: state}
  reducers: {
    addPage: (state, action) => {
      const {uid} = action.payload;
      state.instances[uid] = initialPageState;
    },
    removePage: (state, action) => {
      const {uid} = action.payload;
      delete state.instances[uid];
    },

    // Example instance-specific reducer
    setPageValue: (state, action) => {
      const {uid, val} = action.payload;
      state.instances[uid].val = val;
    }
  }
});

export const selectInstance = (uid) => (state) => state.<SliceName>.instances[uid];

All references to a tab's componentState have been stripped. This did require some additional legwork, creating the connection between tabSlice tabs and individual pages within a pageSlice. This connection was done through the tab uid. And of course there's a bit of code in the background to coordinate between tabs and pages - but hopefully this answer summarizes an effective solution to the type of problem I encountered.
Sometimes if nesting reducers cannot be done with idiomatic and clean Redux code, that reduction should instead be done within separate slices and any necessary state linking can be managed through effective state/action management.

Variable Redux State Structure


php and mysql problems with updating two tables, and inserting into two tables with one button

Question: Here is some of my code for my checkout page. I am new to php, this is my first semester, and I am still struggling. This page collects orders added to the cart and displays and totals the orders perfectly. Here is my problem.
Sometimes there will be OrderIn products and there can be none or more than one of these, and there can also be OrderOut products, or none. complicated, I know. I may be trying to do too much. When I press the pay this invoice button, I want to collect the Order ID's, no matter how many or what kind, (out or in) and set the order ID Paid to yes, and insert the OrderId's into the appropriate invoice, invoice_in or invoice_out, and set shipped to NO.
Is this possible, it is changing the OrderId_in, first product only to yes, and now I am getting a MySQL error of "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '75.18', 'No')' at line 2". I could use some direction here please.

<form action='checkout.php' method='post'>

Purchases this invoice:

<?php
echo "

Order ID:
Product Name:
Quantity:
Price:

";

if (isset($_GET['user_id'])) {
    $user_id = $_GET['user_id'];
} elseif (isset($_POST['user_id']))  {
    $user_id = $_POST['user_id'];
}

$display="SELECT *
    FROM order_instate JOIN in_Product ON
    order_instate.ip_id = in_product.ip_id
    WHERE user_id = '$user_id'; " ;

$displayResult = @mysqli_query($dbhandle, $display)
            or die(mysqli_error($dbhandle));

$priceIn = 0;
while($row = mysqli_fetch_array($displayResult, MYSQLI_ASSOC)) {
    if($row['orderIn_paid'] == "No") {
echo "

<input type='hidden' name='ip_id' value='" . $row['ip_id'] . "' />
" . $row['orderIn_id'] . " &nbsp&nbsp
" . $row['ip_name'] . " &nbsp&nbsp
" . $row['orderIn_quantity'] . " &nbsp&nbsp
$" . $row['orderIn_total'] . " &nbsp&nbsp

";

 $priceIn += $row['orderIn_total'];
 $orderIn_id = $row['orderIn_id'];
 $_SESSION['orderIn'] = $orderIn_id;
    }
 }

 if (isset($_GET['user_id'])) {
    $user_id = $_GET['user_id'];
} elseif (isset($_POST['user_id']))  {
    $user_id = $_POST['user_id'];
}

$display2="SELECT *
    FROM order_outstate JOIN op_Product ON
    order_outstate.op_id = op_product.op_id
    WHERE user_id = '$user_id'; " ;

$displayResult2 = @mysqli_query($dbhandle, $display2)
            or die(mysqli_error($dbhandle));

 $priceOut = 0;
while($row2 = mysqli_fetch_array($displayResult2, MYSQLI_ASSOC)) {
    if($row2['orderOut_paid'] == "No") {
echo "

<input type='hidden' name='op_id' value='" . $row2['op_id'] . "' />
" . $row2['orderOut_id'] . " &nbsp&nbsp
" . $row2['op_name'] . " &nbsp&nbsp
" . $row2['orderOut_quantity'] . " &nbsp&nbsp
$" . $row2['orderOut_total'] . " &nbsp&nbsp

";

 $priceOut += $row2['orderOut_total'];
 $orderOut_id = $row['orderOut_id'];
 $_SESSION['orderOut'] = $orderOut_id;

    }
 }
echo "
";

$subtotal = 0;
$tax = 0;
$gtotal = 0;
$subtotal = number_format($priceIn + $priceOut, 2);
$tax = number_format($subtotal * .074, 2);
$gtotal = number_format($subtotal + $tax, 2);

?>

Total Amount of Purchase(s): <?php echo "$" . " $subtotal " ?>

Tax this invoice (7.4%): <?php echo "$" . " $tax " ?>

Grand Total of Invoice: <?php echo "$" . " $gtotal " ?>

<input type="submit" name="submit" value="Pay This Invoice" style="width: 162px; height:   37px" >
<input type="button" name="print" value="Print This Invoice" style="width:162px; height: 37px" onclick="window.print()">

</form>

<?php

if($_SERVER['METHOD'] == 'POST') {

    if(isset($_SESSION['orderIn'])) {
        $orderIn_id = $_SESSION['orderIn'];
        $orderIn_paid = "Yes";

    $changeVal="UPDATE order_instate
                 SET orderIn_paid = '$orderIn_paid'
                 WHERE orderIn_id = '$orderIn_id'; " ;

    $changeCheck=mysqli_query($dbhandle, $changeVal)
                        or die(mysqli_error($dbhandle));
     }

    if(isset($_SESSION['orderOut'])) {
        $orderOut_id = $_SESSION['orderOut'];
        $orderOut_paid = "Yes";

    $changeVal2="UPDATE order_outstate
                 SET  orderOut_paid = '$orderOut_paid'
                 WHERE orderOut_id = '$orderOut_id'; " ;

    $changeCheck2=mysqli_query($dbhandle, $changeVal2)
                        or die(mysqli_error($dbhandle));
    }

    $invoiceIn_total = 0;
    $invoiceIn_total = $gtotal;
    $invoiceIn_shipped = "No";

    $add ="INSERT INTO invoice_in(user_id, orderIn_id, invoiceIn_total, invoiceIn_shipped)
                VALUES ('$user_id', '$orderIn_id '$invoiceIn_total', '$invoiceIn_shipped')";

    $addCheck=mysqli_query($dbhandle, $add)
                        or die(mysqli_error($dbhandle));

    $invoiceOut_total = 0;
    $invoiceOut_total = $gtotal;
    $invoiceOut_shipped = "No";

    $add2 ="INSERT INTO invoice_out(user_id, orderOut_id, invoiceOut_total, invoiceOut_shipped)
                VALUES ('$user_id', '$orderOut_total '$invoiceOut_total', '$invoiceOut_shipped')";

    $addCheck2=mysqli_query($dbhandle, $add2)
                        or die(mysqli_error($dbhandle));

    header("location: userOrders.php");
}

?>

Answer: There are a few things wrong with your code.
There's
VALUES ('$user_id', '$orderIn_id  '$invoiceIn_total',
                                ^^

is missing a quote and a comma
do
VALUES ('$user_id', '$orderIn_id',  '$invoiceIn_total',

same thing for
VALUES ('$user_id', '$orderOut_total  '$invoiceOut_total',
                                    ^^

do
VALUES ('$user_id', '$orderOut_total', '$invoiceOut_total',

which are where the SQL errors come from.
$orderOut_total is undefined in your posted code.
Plus, from a comment you made:
"Fred, I found why my OrderOut_id was not getting populated, I found a syntax error, I was creating and defining the variable without using the correct $row2 to grab it. It now works for both OrderIn and OrderOut, although I have not tested for multiple orders. But I am getting it working, thanks to you Fred, that worked in finding my exact syntax error."

Which came to be the final solution to the problem.

I must note that your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.

Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

Sidenote: Error reporting should only be done in staging, and never production.
Comment: @Fred-ii- I'm marking this up because watching the discussion this was more than an answer this was a Save, :) Good work sir!
Comment: @user3447733 You're very much welcome, glad to see the matter was resolved, *cheers*


Chat prefixes in Minecraft without plugins?

Question: I'm trying to make chat prefixes (like so):
Steve (Administrator): Hello

That is in the chat.
In this, Steve is the username and Administrator is the rank.
I want to do this without plugins or mods, just commands. Is this possible?
Comment: Possible duplicate of [How do you give people prefixes for their usernames?](https://gaming.stackexchange.com/questions/212309/how-do-you-give-people-prefixes-for-their-usernames)
Answer: By default, this is impossible, unless you would use a NBT editor, such NBTexplorer.
This technique uses teams, so you will need to create a team. /scoreboard teams (for options press tab)
If you want to look at the file/path on NBT Explorer (it's probably compatable with other programs):

saves\custom world name here\scoreboard.dat\teams\X entries\Prefix

now edit Prefix. This is what you want
If you want color codes, visit the wiki:
Formatting Codes
For example,
§f[§e§lOWNER§f]
Would be <Owner> (when Owner is bold yellow, the rest is plain white)
Comment: would this be possible on Minecraft Realms?
Comment: I do not know as I do not own a realm anynore, but as long as you upload the world then most likely yes. You can do this do an existing world by downloading it and than editing.
Comment: :D no problem. If you want to do this on a great scale, I would suggest a bukkit server, as their are much easier ways to do this such as the PEX plugin. But considering that your on a realm, this wont be nessecary.
Answer: You can't change the user's name.
The chat is always formatted like as <pseudo> : message (excluding CommandBlocks say or tellraw option)
In order to change it, you NEED to change the program. Even for typing the § character (for formating text), you need a third-party program or changing a .class file.


redux-form Migration to v6 throwing error in getValues.js

Question: I'm attempting to use v6 of redux-form but running into some pretty undescriptive errors. The setup is straight forward, the reducer verbatim from the site:
import { combineReducers } from 'redux'
import { reducer as formReducer } from 'redux-form';

export default combineReducers({
  form: formReducer,
});

Then, I create a straight forward component without any fields (I get the exact same error when I have fields too).
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';

class LoginForm extends Component {
  render() {
    const { handleSubmit, pristine, reset, submitting } = this.props;

    return (

        Form

    );
  }
}

export default reduxForm({
  form: 'login' // a unique name for this form
})(LoginForm);

When I navigate to my component, I get this error:
Uncaught TypeError: Cannot read property 'reduce' of undefined

The error is pointing to redux-form's getValues.js, and specifically this area of the code:
var getValues = function getValues(fields, state) {
  return fields.reduce(function (accumulator, field) {
    getValue(field, state, accumulator);
    return accumulator;
  }, {});
};

One idea came from the very bottom of redux-form's v6 migration page about upgrading react-hot-loader, so I upgraded to 3.X but that didn't work.
Answer: You are using v6 syntax but the version in your node_modules/redux-form is v5. That getValues function no longer exists in v6.
rm -rf node_modules/redux-form
npm install --save redux-form

Comment: Awesome, thank you. I had to run npm i -S redux-form@6 to make sure I was getting the latest and greatest, otherwise this is the answer!


How can I implement Android Dialog box?

Question: How to implement the Dialog Box in my android project?
Comment: what problems do you have? Can you be more specify with it?
Answer: Are you looking for simple AlertDialog or Dialogbox?
Example AlertDialog :
<code>         AlertDialog.Builder alertDialog = new AlertDialog.Builder(Borc.this);
                // Setting Dialog Title
                alertDialog.setTitle("Eraser");
                // Setting Dialog Message
                alertDialog.setMessage("Are you sure?");
                // Setting Icon to Dialog
                alertDialog.setIcon(R.drawable.remove);
                // Setting Positive "Yes" Button
                alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dataBase.borclar.delete(String.valueOf(tableHelper.getSelectedRowId()));
                    }
                });
                // Setting Negative "NO" Button
                alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                // Showing Alert Message
                alertDialog.show();
</code>
Answer: Use this code where ever you want to show dialog..
<code>AlertDialog.Builder builder =new AlertDialog.Builder(Dialogs.this);
builder.setIcon(R.drawable.save1);
builder.setTitle("Save Your Work");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

 @Override
 public void onClick(DialogInterface dialog, int which) {
                // do something.......
  }
 });
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

 @Override
 public void onClick(DialogInterface dialog, int which) {
                // do something.......
  }
 });
AlertDialog alert = builder.create();
alert.show();
</code>
Comment: you can download the image to add to dialog..
Comment: public void onClick(View v) {
            DB.open();
            Cursor c = DB.getContact("1");
            if(c.moveToFirst()){
                do {
                    Display(c);
                } while (c.moveToNext());
            }
            DB.close();
            String checkPass = pass.getText().toString();
            if(checkPass.equals(getpass)){
                startActivity(new Intent(Welcome.this,Main.class));
            }else{
                Toast.makeText(getBaseContext(), "Wrong PassWord", Toast.LENGTH_LONG).show();
            }
        }
Answer: I think the best way to start with android dialogs is reading the docs: Android Dialog Documentation. They describe the various types of dialogs and how you can implement them in your app.
If you have a specific problem please show us your code and ask a correct question.

How can I implement Android Dialog box?


How to send some custom tokens with MetaMask API?

Question: It seems the example code on the MetaMask documentation page, sends ETH only. How should I customize the sample code to send some custom tokens?
const transactionParameters = {
  nonce: '0x00', // ignored by MetaMask
  gasPrice: '0x09184e72a000', // customizable by user during MetaMask confirmation.
  gas: '0x2710', // customizable by user during MetaMask confirmation.
  to: '0x0000000000000000000000000000000000000000', // Required except during contract publications.
  from: ethereum.selectedAddress, // must match user's active address.
  value: '0x00', // Only required to send ether to the recipient from the initiating external account.
  data:
    '0x7f7465737432000000000000000000000000000000000000000000000000000000600057', // Optional, but used for defining smart contract creation and interaction.
  chainId: '0x3', // Used to prevent transaction reuse across blockchains. Auto-filled by MetaMask.
};

// txHash is a hex string
// As with any RPC call, it may throw an error
const txHash = await ethereum.request({
  method: 'eth_sendTransaction',
  params: [transactionParameters],
});

Answer: A transaction sending an ERC-20 token needs to have the token contract as the recipient (the to field), and the data field containing encoded instructions to execute its transfer() function along with address of the token receiver and amount.
const transactionParameters = {
    from: accounts[0],
    to: tokenContractAddress,
    data: getDataFieldValue(tokenRecipientAddress, tokenAmount),
};
await ethereum.request({
    method: 'eth_sendTransaction',
    params: [transactionParameters],
});

You can use for example the web3js library (docs) to encode the data field value. The transfer() function is standardized - so assuming the token contract follows the standard, it's going to be the same for any token contract.
function getDataFieldValue(tokenRecipientAddress, tokenAmount) {
    const web3 = new Web3();
    const TRANSFER_FUNCTION_ABI = {"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"};
    return web3.eth.abi.encodeFunctionCall(TRANSFER_FUNCTION_ABI, [
        tokenRecipientAddress,
        tokenAmount
    ]);
}

Answer: For a cleaner version of Petr's solution using the encodeABI function.
await window.ethereum
    .request({
      method: "eth_sendTransaction",
      params: [
        {
          from: accounts[0],
          to: TOKEN_CONTRACT_ADDRESS,
          data: tokenContract.methods
            .transfer(receiverAddress, amount)
            .encodeABI(),
        },
      ],
    })
    .then((result) =>  console.log(result))
    .catch((error) => console.error(error));


Unable to change display resolution Ubuntu 18.04 on Xenserver VM

Question: I'm using Dell T410 server with Free version of Xenserver 7.4, i installed Ubuntu 18.04 VM all went well but i'm unable to adjust the resolution
from ubuntu settings, showing just 800X600, see attached image taken from VNC Viewer but look the same if i use XenCentre or Xen Orchestra console. i also installed Windows 10 vm and using Microsoft RDP App installed on my iMac to access and it working ok i can change any resolution from both the VM or the RDP App settings and have sound. but on the Ubuntu i think it picks up the Dell driver\HW with no option to change the resolution, as you see from the screen shot even the setting page doesn't fit the screen. in general i would like to do the same as windows VM, RDP with Microsoft if possible as preferred. I did manage to use VNC Viewer but resolution was the same. i did install the XS Guest tools on both the Windows and Ubuntu vms but didn't help with the resolution on ubuntu. i also researched online but only found outdated solution from 2016 XS V6.5 and Ubuntu 16.04 but no solution helped.
I use this setup as a home lab to learn about  servers, linux CLI and VMs, so i wish to have a similar environment as a desktop.
my questions are :

how do i fix the resolution, do i need to install a XS or Ubuntu driver?
what you normally using in production and home lab environment to access the VM, RDP Client?
what RDP you recommend to get for best compatibility and environment as a desktop?

Thank you for your help
Yariv
Ubuntu settings showing on VNC
Comment: I'm not sure if it helps, but I can imagine, that this could work.
https://askubuntu.com/questions/1031143/unable-to-change-display-resolution-ubuntu-18-04-on-xenserver-vm
Answer: 1.Shutdown your VM.
2.From the command line, find the UUID of your VM:
xe  vm-list  name-label='Name of your VM'
3.Taking the UUID value, run the following command:
xe  vm-param-remove  uuid=UUID  param-name=platform  param-key=vga
4.You can always switch back to the default driver with the following command:
xe  vm-param-set  uuid=UUID  platform:vga=std


Why are ground wires sometimes not insulated?

Question: I recently replaced a single AC dimmer light switch that was one of two light switches in a larger box.  The ground wire leading to the switch was raw copper without any insulation.
After replacing the switch, and turning on the circuit breaker, the breaker sparked and tripped.  I'm thinking one of two things explain why:

The new FEIT switch was defective (which would be my 4th defective switch from the big carton of FEIT switches I bought).
The naked ground wire touched the contacts of the other switch in the box.

I turned off the breaker, put it a completely different switch, and did my best to get that naked ground wire as far away as possible from the other switch.  Then I flipped the breaker on (shielding my eyes, and standing away from the breaker box), and everything worked.
So my question: Why are ground wires sometimes installed without any insulation?  The cost of insulated wire is almost identical to that of non-insulated wire, so I tend to think cost is not the primary driver of this decision.
Comment: I learned to wrap switches and outlets in electrical tape to help avoid a bare ground wire touching a live screw terminal in an electrical box.  That doesn't answer your question but it can help avoiding this issue in the future.
Comment: Think so it is easier to cause short anywhere(or kill rats) on cable path and trip breaker/fuse. Insulated ground will only have certain short sections for short to happen.  Might want your two cents back.
Comment: @MacGuffin Great tip! Here is a question I just posted requesting further details: https://diy.stackexchange.com/questions/219053/techniques-to-wrap-the-innards-of-electrical-switches-and-outlets-with-electrica
Answer: Cost, mostly
Whether your grounding conductors are bare, insulated, or not even a wire to begin with depends on what wiring method you are working with.  NM, because it's made in large quantities, uses a bare grounding wire to save cost (likewise with UF and most SE cables, as those pennies add up at industrial scales).  On the other hand, if your house is wired using armored cable (AC), there are no ground wires, because the metal cable armor serves as the ground with the aid of a thin "bonding strip" to prevent "choking" of fault currents caused by stray inductive interactions.  That lack of grounding wires is also a notable feature of many installs done in metal conduit, as the conduit itself then becomes the grounding conductor.
Furthermore, some wiring methods aren't uniform in how they handle this; it's legal (and occasionally required) to run a separate equipment grounding conductor in metal conduit, and in most (albeit not all!) cases, equipment grounding conductors inside conduits can be either bare or insulated.  Likewise, metal-clad cable usually uses an insulated grounding conductor, but can sometimes be found with a bare grounding conductor, or in configurations where the armor is the grounding means.
Comment: It also saves the ele from having to strip 12" of it so that they can curl the box screw and then have enough length for the device / branch pig tails.  I was thinking it might also be a bit of a safety thing - if you drive a nail into NM and hit the hot or neutral through the insulation you have good chances of the nail hitting the ground and it tripping out the breaker.
Answer: You're supposed to resolve that with technique
First, if you're working in a metal box, there shouldn't be any ground wires flying around in a switch box. Code requires that you take the cable grounds to the metal box itself FIRST -- either via separate ground screws for each, or pigtail them to one ground screw.  Switches can pick up ground via their mounting screws, so the next thing you do is push all the ground wires into the very back of the box, and never touch them again.
You should be installing grounds first anyway because it smooths troubleshooting. (some people install them last, and wind up with a puzzling problem when the circuit stops working when the grounds are connected. The problem wouldn't have been puzzling if they'd done grounds first).
Now, if it's a plastic box, then first, trim all your backstabs * and back-wires so they have no exposed shank of bare wire.  (I cued up this video so you can see the exposed shank of copper on a neutral wire.  That's terrible! The switch has a strip gage for a reason!)  And that's a code requirement/violation by the way: 110.3(B) and 110.12.
Then second, run down all the screws you aren't using so they aren't sticking out.  Finally, wrap the switch in electrical tape so all the screw heads are covered.
Now you know about Feit Electric, stop buying their stuff LOL. Also on the "expect junk" list are Utilitech, Lights of America and Commercial Electric.  These are all UL-listed so they're safe, but UL doesn't test for reliability.  Try brands like Leviton, Lutron, Legrand, GE, Eaton, etc.  And in the "surprisingly good" category: IKEA.  Crud sold mostly online/mail-order should be avoided at all costs; they're using a Customs loophole to sell stuff that isn't even UL-Listed and will burn your house down. Amazon is actually the worst of this.

* Backstabs, where you jab the wire in and it grabs, are bad news anyway - they're Code legal and judged safe by UL, but vast experience is that they are highly unreliable, and create frustrating "half my circuit went dead" problems.  They are certainly uninspectable, which makes finding such a fault even harder.  Also when using backstabs you're not using screws, and the tendency is to leave the screws in the factory-supplied position: sticking all the way out like Ross Perot's ears.  That makes the screws more likely to snag a ground wire or metal-box side. **
** And don't get me wrong. Metal boxes are vastly superior at every job we need boxes to do.  Their metalness and risk of hitting Ross Perot ears isn't a failing; run down the screws and they're fine.  Actually metalness is a virtue, as they're far more likely to "clear" (trip) faults like a loose hot wire. And of course they are vastly superior at containing overheats and resisting burn-through.  Their handling of grounds is also superior.
Comment: "first, trim all your backstabs"... I think you meant, "first, **don't use backstabs**". The consensus almost everywhere seems to be that backstabs are nasty, failure-prone shortcuts.
Comment: @Matthew Yeah, I was thinking of back-*wires* like in the video, but you're right, I should cover the general badness of back-*stabs*.
Comment: Ah, yes... I hadn't watched the video, but I see now those aren't the much-derided backstabs... they *look* similar but they're still screw-down, which is much better.
Comment: Oh man, that Feit video... not only is the conductor exposed, the dimmer is screwed to the box with drywall screws. The sharp tip risks penetrating a cable behind it.


How to unambiguously identify a Model as a lowercase string in Django

Question: I want to pass a model name as an URL parameter, so I can use it to access a specified model class in my view. For example:

/app_label/model_name

and in views.py:
from django.db.models.loading import get_model
model = get_model(app_label, model_name)

The problem is - I want my url to be case-insensitive. Therefore, I cannot just use the code above, because one of the models can look like these below:

MyModel, MySuperModel, MyAwesomeSuperModel

Is there any way to identify a Model unambiguously as a lowercase string?
I thought about using table_name however it would mean looping over every model in the project each time a request is processed. Not very efficient.
Comment: If you want the url to be case-insensitive, then you should not use model class names which differ only by case in their names, and so there would not be any ambiguity.
Comment: If you don't have too many models you could create a dictionary mapping model canonical names to the models themselves... There may be a DRYer way to do it out there, but this would be quick and easy.
Comment: I want to create a generic solution (a reusable app), so I do not control how many models are out there or what are their names
Answer: I am afraid you will have to iterate over app's models list but you can cache it:
from django.core.exceptions import ImproperlyConfigured
from django.db.models import get_app, get_models

APPS_MODELS = {}

def get_model(app_name, model_name):

    app_models = APPS_MODELS.get(app_name)
    if app_models:
        return app_models.get(model_name)

    try:
        app = get_app(app_name)
    except ImproperlyConfigured: # no such app
        return None

    APPS_MODELS[app_name] = dict((model._meta.model_name, model)
                                     for model in get_models(app))

    return APPS_MODELS[app_name].get(model_name)

Answer: your_model_object.__class__.__name__.lower()

gives you the lower case name of model name if it can help you


Difference between "Riki's Sange and Yasha" and "Sange and Yasha" cosmetics

Question: On the Dota 2 market, I see the cosmetic items "Sange and Yasha" and "Riki's Sange and Yasha". What is the difference between these two items?
Answer: Cosmetically there is no difference. The difference is in the name and when they were available or given out.


On the size of a certain topology defined by an inclusion function.

Question: I found this problem in chapter 7 of biglist. This is supposed to be an easy problem, but I have no idea how to approach it. The problem goes as follows:

Let $(X, \mathcal{T})$ be a topological space and let $A \subseteq X$. Let $i: A \to X$ be the inclusion function defined by $i(x) = x$. Show that the topology $A$ inherits from $X$ is the coarsest topology on $A$ such that $i$ is continuous.

Specifically, I want to know, the precise definition of a topology being coarse and how to start proving that some topology is coarser than others. I know about topologies refining each other. Is that what I am supposed to prove here? Any help is appreciated.
EDIT: (An attempt at a proof)
Let's first show that $i$ is continuous. Let $U$ be an open set in $X$. Then, $i^{-1}(U) = U \cap A$. Since $U$ is open in $X$ and $A \subseteq X$, the intersection of $U$ and $A$ is open in $X$. Therefore, $i^{-1}(U)$ is open in $A$, which shows that $i$ is continuous. Now we need to show that no strictly finer topology on $A$ makes $i$ continuous. Or in other words, we want to show if $\mathcal{T}_c$ is a topology on $A$ that makes $i$ continuous, then $\mathcal{T}_c \subseteq \mathcal{T}$, where $\mathcal{T}$ is the topology on $A$ inherited from $X$. Let $U \in \mathcal{T}_c$. Since, $i$ is continuous, $i^{-1}(U)$ must be open in $A$. But $i^{-1}(U) = U \cap A$. So, $U \cap A$ is open in $X$ with respect to the topology inherited from $X$. So, $U \cap A \in \mathcal{T}$. Thus $\mathcal{T}_c \subseteq \mathcal{T}$.
Feel free to comment :)
Comment: Topology $\mathcal{T}_1$ is *coarser* than topology $\mathcal{T}_2$ if $\mathcal{T}_1 \subseteq \mathcal{T}_2$.
Comment: As a follow up to @K.Jiang 's comment, you want to show that no strictly finer topology on $A$ allows $i$ to be continuous.
Comment: I thought the other way. No Strictly coarser topology on $A$ allows $i$ to be continuous
Comment: @K.Jiang Thanks
Comment: Let $\mathcal{T}_A :=\{U \cap A \ | \ U \in \mathcal{T}\}$ be the induced topology on $A$. Let $U \in \mathcal{T}$ be open. Show $i^{-1}(U) = U \cap A$, so $i : (A, \mathcal{T}_A) \rightarrow (X, \mathcal{T})$ is continuous. If $\mathcal{T}_0\subsetneq \mathcal{T}_A$, show that $i$ is not continuous.
Comment: @User203940 Thanks for the help... can you comment on my solution?
Comment: @K.Jiang Can you comment on my solution
Comment: Your proof looks good to me.
Answer: Let $\mathcal{T}_s$ denote the (subspace) topology that $A \subseteq X$ inherits from $X$. Let $\mathcal{T}_A$ be any topology on $A$ with respect to which the function $i : A \mapsto X$, defined by $i (a) = a$, is continuous.
Let $V \in \mathcal{T}_s$ be arbitrary. By definition, there exists $U \in \mathcal{T}$ such that $V = A \cap U$. We note that $i^{-1} (U) = A \cap i^{-1} (U) = i^{-1} (A \cap U) = A \cap U = V$ is contained in $\mathcal{T}_A$ since $i$ is continuous with respect to the topology $(A, \mathcal{T}_A)$. Thus, $\mathcal{T}_s \subseteq \mathcal{T}_A$. Since $\mathcal{T}_A$ was arbitrary, $\mathcal{T}_s$ is the coarsest topology on $A$ with respect to which $i$ is continuous. In other words, $\mathcal{T}_s$ is contained in every topology with respect to which $i$ is continuous.
Comment: Can you please check my solution?


Pdf reader for iOS with scrollView

Question: I use CGContextDrawPDFPage for drawing my pdf. I have a scrollView and 2 arrays with low and high resolution images. When user scrolling on scrollView load low resolution images, after method scrollViewDidEndDecelerating it load high resolution image for this page.
I use removeFromSuperView for low resolution image and add high but my scroll is blinking.
How can I delete low image without blinking?
Answer: I think if you are worried about performance on scrolling , I will suggest using titled layer rendering. Apple ZoominPdfViewer should be the best example.
Comment: I use it, but in example it high resolution image at all. But my problem is that if i didn't delete low resolution image and add high resolution image when zooming i can see at some borders low resolution image. So i need to remove it and add high but, when i make it my scroll is blinking
Comment: Sorry, I really cant understand what you are trying to say.
Comment: I have 2 methods, onу for load low resolution images, second for load high resolution images. when user scrolling on `didscroll` i use first method. when he stop i use secoтd so the problem is that i need to delete low from superView and add hidh resolution image on scrollView, but wneh i make this my scrollView is blinking
Comment: In what order you are doing this. you should add then remove.

Pdf reader for iOS with scrollView


How to set ArrayList values from database MySQL with IDE (Android Studio)?

Question: I want to put data from a MySQL database table into Android Studio.
For modifying script from tutorial.
In tutorial ArrayList value is:
HomeCollection.date_collection_arr = new ArrayList<HomeCollection>();
HomeCollection.date_collection_arr.add(new HomeCollection("2018-07-08" ,"Title1","Subject1","Description1"));
HomeCollection.date_collection_arr.add(new HomeCollection("2018-07-09" ,"Title2","Subject2","Description2"));
HomeCollection.date_collection_arr.add(new HomeCollection("2018-07-10" ,"Title3","Subject3","Description3"));

My Question:
How to modify data Array, in example with all data in MySql table
having below columns?

| id | date | title | subject | description |

Any help will be greatly appreciated
Comment: First of All what's your database SQLite or MySQL?
Answer: //you can do like this.
get the value from arraylist into string array then split the array and then send the string to database.given below code
 String[] value = HomeCollection.date_collection_arr.get(0).split(",");
 String date=value[0];
 String title=value[1];
 String description=value[2];

//if your array list value contain space use below code
 String[] valuetrim= HomeCollection.date_collection_arr.get(0).split("\\s*,\\s*");
 String valuetrim=value[0];
 String valuetrim=value[1];
 String valuetrim=value[2];

Answer: Thanx for your clue, but I still not understand,
I try to get array list, from this way n success to views data at list (bellow array scrip),
maybe someone can give me more specific, how to implement/combine value data i have got from this way (below) to array at my question (i want to impemented sample script from this link https://www.developerbrothers.com/highlight-events-custom-calendar-android-studio-developerbrothers-com/) but i want data values get from MySql, Thanks
private void showOrder(){
        JSONObject jsonObject = null;
        ArrayList> list = new ArrayList>();
        try {
            jsonObject = new JSONObject(JSON_STRING);
            JSONArray result = jsonObject.getJSONArray(konfigurasi.TAG_JSON_ARRAY);
        for(int i = 0; i<result.length(); i++){
            JSONObject jo = result.getJSONObject(i);

            String idplace = jo.getString(konfigurasi.TAG_PLACE);
            String titl = jo.getString(konfigurasi.TAG_TITLE);
            String subj = jo.getString(konfigurasi.TAG_SUBJECT);
            String desc= jo.getString(konfigurasi.TAG_DESCRIPTION);
            String dateo = jo.getString(konfigurasi.TAG_DATEORDER);

            HashMap<String,String> orders = new HashMap<>();

            orders.put(konfigurasi.TAG_PLACE,idplace);
            orders.put(konfigurasi.TAG_TITLE,titl);
            orders.put(konfigurasi.TAG_SUBJECT,subj);
            orders.put(konfigurasi.TAG_DESCRIPTION,desc);

            orders.put(konfigurasi.TAG_DATEORDER,dateo);
            list.add(orders);
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

    ListAdapter adapter = new SimpleAdapter(
            DateEventActivity.this, list, R.layout.list_item,
            new String[]{konfigurasi.TAG_PLACE,konfigurasi.TAG_TITLE,konfigurasi.TAG_SUBJECT,konfigurasi.TAG_DESCRIPTION,konfigurasi.TAG_DATEORDER},
            new int[]{R.id.idplace, R.id.titl, R.id.subj, R.id.desc, R.id.dateo});

    listView.setAdapter(adapter);
}

private void getJSON(){
    class GetJSON extends AsyncTask<Void,Void,String> {

        ProgressDialog loading;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(DateEventActivity.this,"Mengambil Data","Mohon Tunggu...",false,false);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            loading.dismiss();
            JSON_STRING = s;
            showOrder();
        }

        @Override
        protected String doInBackground(Void... params) {
            RequestHandler rh = new RequestHandler();
            String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
            return s;
        }
    }
    GetJSON gj = new GetJSON();
    gj.execute();
}


Youtube live streams in Android Webview are jittery

Question: I am having a lot of trouble trying to play some youtube videos inside an Android Webview. I search everywhere but cannot find a solution that works.
I am using the following code:
WebView mWebView = (WebView) findViewById(R.id.webView1);
//Setup Webview
WebChromeClient client= new WebChromeClient();
mWebView.setWebChromeClient(client);

mWebView.getSettings().setPluginsEnabled(true);
mWebView.getSettings().setSupportZoom(false);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setRenderPriority(RenderPriority.HIGH);
mWebView.getSettings().setAllowFileAccess(true);

mWebView.loadDataWithBaseURL("www.youtube.com", "\n", "text/html", "UTF-8", "");

The problem seems to be only with certain streams like this one: http://www.youtube.com/watch?v=JEkbk-xDmZE
The sound is great but the video is very slow, like 1 frame per second. unwatchable.
But if I use this stream: http://www.youtube.com/watch?v=GDFIYKmNw9Q
It works perfectly fine.
What is the difference between these live streams and how do I get the first one to play properly?
Also I should mention that sometimes the first one DOES play just fine. I am not able to figure out why it sometimes plays and other times doesn't. I've tried creating a new project with pretty much just a Webview and a Factory Reset device to eliminate any settings that may be effecting this but I still get the problem.
Comment: did you find working solution for your problem?
Answer: I've struggled with YouTube in general, trying to get it to work on android. Why certain videos lag is beyond me, but it might be different quality settings and limited bandwidth thus its buffering.
Hopefully one of the options below might help if it's not a buffering issue.
Currently, with WebView you use either use an IFrame or the YouTube API. Otherwise you can use the GData API to get the RSTP link to the video for use in a VideoView. Finally you can use an Intent to launch the YouTube app.
In the future there is a new API for Android for YouTube. But it has not been released. Theme again neither has Fragment support for Google Maps that was announced in Dec 2011. - http://www.youtube.com/watch?v=3WFsx-u-q3Y
Pros/Cons below (Examples are all making the WebView fill 100% of screen height and width)
WebView - IFrame - Limited configuration available. Runs in the WebView and works on nearly all platforms. Don't get me wrong, sometimes different options do not work, and you get a grey background when you try to play the video. Use the following site to create the IFrame code and try different options until it works for you - https://developers.google.com/youtube/youtube_player_demo (Do note several of the allowed configuration options do not work, such as hide controls has no effect). As mentioned there are lots of different options so trial and error is involved. Whilst several don't work, some look quite different. Looking at your question, i've never used the html5=1 option before, or set youtube.com as the base url.
webView = new WebView(this);
webView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
webView.getSettings().setPluginState(PluginState.ON);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.getSettings().setJavaScriptEnabled(true);

// Prevent scrolling of the webview
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setHorizontalScrollBarEnabled(false);
webView.setVerticalScrollBarEnabled(false);
webView.setWebChromeClient(new WebChromeClient()); //Blank webview to prevent null pointer plugin issues
webView.setWebViewClient(new WebViewClient()
{
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url)
    {
        view.loadUrl(url);
        return true;
    }
});

String data = ""+
""+
""+
""+
"" +
""+
"";

webView.loadData(data, "text/html", "utf-8");

WebView - YouTube API - Much better, but requires flash. Therefore "Nexus 7" and any future devices released with JellyBean (4.1 and above) will not work. As the WebView on those devices uses a cut down version of Chrome rather than a cut down version of WebBrowser. Therefore as I found out yesterday, going forward this can't be used on our apps.
webView = new WebView(this);
webView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
webView.getSettings().setPluginState(PluginState.ON);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.getSettings().setJavaScriptEnabled(true);

// Prevent scrolling of the webview
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setHorizontalScrollBarEnabled(false);
webView.setVerticalScrollBarEnabled(false);
webView.setWebChromeClient(new WebChromeClient()); //Blank webview to prevent null pointer plugin issues
webView.setWebViewClient(new WebViewClient()
{
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url)
    {
        view.loadUrl(url);
        return true;
    }
});

String data = "<!DOCTYPE HTML>" + "" + ""
+ "

"
+ "" + "" + "";

webView.loadData(data, "text/html", "utf-8");

VideoView - YouTube Data API - Can get access to information and importantly links to the video streams for use in a VideoView. The draw back is the free API is limited to low quaility 3GP videos not the MP4 (high quality/HD) streams. - https://developers.google.com/youtube/getting_started#data_api
Intent - Launch YouTube - Open the YouTube app with the video you want to play. Drawback is that another app is opened, thus not embedded into your app, and that some devices don't have YouTube installed.
if (AppChecker.isAppInstalled("com.google.android.youtube", this) == true)
{
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + uri));
    startActivity(intent);
}
else
{
    //Show youtube not installed
}

//Code to check if YouTube is installed.

public class AppChecker
{
    public static boolean isAppInstalled(String uri, Activity activity)
    {
        PackageManager pm = activity.getApplicationContext().getPackageManager();
        boolean app_installed = false;
        try
        {
            pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
            app_installed = true;
        }
        catch (PackageManager.NameNotFoundException e)
        {
            app_installed = false;
        }
        return app_installed;
    }
}

Comment: On the Nexus 7, We were getting a gray screen with a white image of a broken movie reel. `webView.setWebChromeClient(new WebChromeClient());` fixed the problem. thanks
Comment: @edwin, I haven't found any other ways yet. Preference has been more towards to launch the youtube application if installed, as it will handle many of the issues (i.e. playing a video, playing in background even if your app is closed, + more). One day Google will launch the YouTube control for android.
Comment: I'm sure I tried that but it never helped. Ill have to give it ago when next back on the Android client. Cheers
Comment: Also, instead of `youtube.com/v/` we are using `youtbue.com/embed/` since that will use HTML5 instead of flash.
Comment: @JonWillis i tried your code but it doesn't help me . did you find any other solution for this?


Substitution Cipher - issues modifying strings

Question: The following code is broken when trying to run due to an issue replacing the character on line 33. Am I replacing the character in the string incorrectly?
The code is designed to encrypt lowercase characters in the *cat string. Each character in code2 is 'mapped' to a character in the same position in code1. The lowercase chars in *cat are replaced with their substituted char from code2.
//Ben Adamson
//v1.0
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>

void code(char *s);

int main()
{
    char *cat = "The cat sat";

    code(cat);

    _getch();
    return 0;
}

void code(char *s)
{
    char code1[] = "abcdefghijklmnopqrstuvwxyz";
    char code2[] = "bpduhijkaltxwmrzfoysvngeqc";
    char *letter;
    unsigned int i, letterpos;

    for(i=0; i<strlen(s); i++)
    {
        if(isalpha(s[i]) && islower(s[i]))
        {
            letter = strchr(code1, s[i]);
            letterpos = (int)(letter - code1);
            s[i] = code2[letterpos];
        }
    }
    printf("New string is %s", s);
}

Answer: char *cat = "The cat sat";

Her cat is read only.
s[i] = code2[letterpos];

You need to allocate memory if you need to write to it.
char *cat =  malloc(100);

Better way to do it is:
char *cat = strdup("The cat sat");

Comment: I would recommend using `char *cat = strdup("The cat sat");`
Comment: @KlasLindbäck Yeah in order to fix his issue allocating memory will fix it.
Comment: Thanks Gopi & Klas - I took your suggestions into account and the code works, after using Klas' line replacement. One note - the compiler complained that strdup is deprecated so I used _strdup instead.
Comment: @BenAdamson [¡SO al rescate!](http://stackoverflow.com/questions/7582394/strdup-or-strdup), just use `strdup`.


Django template for loop

Question: I have a template where I get certain variables back.
One variable is instance.category which outputs: "words words words" which are values split by spaced.
When I use the code below I get letter by letter back and not the words.
{% for icon in instance.category  %}

{{ icon }}

{% endfor %}

Output

w

o

r

d

w

....

I need:

word

word

word

The Django plugin code
from cmsplugin_filer_image.cms_plugins import FilerImagePlugin
from cms.plugin_pool import plugin_pool
from django.utils.translation import ugettext_lazy as _
from models import Item

class PortfolioItemPlugin(FilerImagePlugin):
    model = Item
    name = "Portfolio item"
    render_template = "portfolio/item.html"
    fieldsets = (
        (None, {
            'fields': ('title', 'category',)
        }),
        (None, {
            'fields': (('image', 'image_url',), 'alt_text',)
        }),
        (_('Image resizing options'), {
            'fields': (
                'use_original_image',
                ('width', 'height', 'crop', 'upscale'),
                'use_autoscale',
            )
        }),
        (_('More'), {
            'classes': ('collapse',),
            'fields': (('free_link', 'page_link', 'file_link', 'original_link', 'target_blank'),)
        }),
    )

plugin_pool.register_plugin(PortfolioItemPlugin)

Any help is appreciated!
Comment: can you show us the view to have a look at category ?
Comment: We overridden the FilerImage plugin to add an extra field for a portfolio item. Does this help you (updated)?
Answer: If your separator is always " " and category is a string, you don't actually need a custom template filter. You could simply call split with no parameters:
{% for icon in instance.category.split %}

{{ icon }}

{% endfor %}

Answer: You are passing a string instance.category into the template and then iterating over its chars.
Instead, pass a list to the template: instance.category.split() which will split your words words words string into the list ['words', 'words', 'words']:
>>> s = "words words words"
>>> s.split()
['words', 'words', 'words']

Or, you can define a custom filter that will split a string into the list:
from django import template
register = template.Library()

@register.filter
def split(s, splitter=" "):
    return s.split(splitter)

Then, use it in the template this way:
{% for icon in instance.category|split %}

{{ icon }}

{% endfor %}

Comment: @NielsenRamon as Augusto Men correctly pointed out: you don't need a custom filter in case you are always splitting by space. Btw, I've updated the answer - should work in your case too.
Comment: I am using the custom filter but I get this error: 'for' statements should use the format 'for x in y': for icon in instance.category|split:" " any ideas?
Comment: I fixed it with the comment above from @Augusto Men, Thanks anyway, upvoted.
Comment: I've removed the useless `{% with  %}` to be more concise.
Comment: @MaximeLorant yeah, it was originally without the `with`, then I've tried to fix the OP's problem that way.
Answer: I know this is a late answer, but it might help someone (it was the problem I had).
If you have a point in the form: (x, y). then you need:
{% for x, y in points %}
    There is a point at {{ x }},{{ y }}
{% endfor %}

And for key-value pairs:
{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}

source: here (check the for section)

Django template for loop


Trouble loading numpy array where they show pickle data error in python

Question: I can successfully save & load small arrays using Numpy. Now I am saving the below array using np.save('array.npy')
[0, 100, 0, 5, 10, 15, 20, 25, 30, 25, 20, 15, 10, 5, 0]

when I try to load using np.load('array.npy'), it shows the below error:
    raise ValueError("Cannot load file containing pickled data "
ValueError: Cannot load file containing pickled data when allow_pickle=False

If I try to solve it by adding allow_pickle=True then it shows the below error:
    raise IOError(
OSError: Failed to interpret file 'array.npy' as a pickle

Its really a difficult situation. Please advise! :(
The code I am referring to is below:
def recv():
    import socket
    import time
    import numpy as np

    TCP_IP = "0.0.0.0"
    BUFFER_SIZE = 20  # Normally 1024, but we want fast response

    # receiving CAN frame payload
    TCP_PORT = 5003
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.bind((TCP_IP,TCP_PORT))
    s.listen(1)
    conn,addr = s.accept()
    while 1:
        data1 = conn.recv(BUFFER_SIZE)
        if not data1: break
        datalist = list(data1)
        print("CAN payload: %s" % datalist)
        conn.send(data1)  # echo
    conn.close()
    time.sleep(2)
    # ------------------------------------------------------------
    # assembling CAN frame
    from can import Message
    can_msg = Message(is_extended_id=bool(datalist[0]),arbitration_id=datalist[1],data=datalist[2:])

    # printing all received payloads
    print("CAN frame: ",can_msg)
    print("Vehicle speed: ",datalist[2:])

    # Saving all received payloads
    np.save('array.npy',datalist[2:])  # save

def EPS_process():
    # EPS process for Right turn, high speed
    import numpy as np

    print("Starting EPS process")
    speed_array = np.load('array.npy')  # load

Comment: Please post the non-working code. When running your example, it works fine, even without `allow_pickle=True`
Comment: it is a socket server. I have edited to add the code here
Answer: Okay, I want to share what resolves the situation. So basically @hpaulj was suggesting that for multiple processes the read might start before the save is finished. So I added a 3-sec delay before speed_array = np.load('array.npy')
This gives enough time for the NumPy array to save before I can read again. Otherwise, it will read the previously saved array and hence the pickle error.
Answer: That array shouldn't give you any problems:
In [1]: arr = np.array([0, 100, 0, 5, 10, 15, 20, 25, 30, 25, 20, 15, 10, 5, 0])
In [2]: arr
Out[2]:
array([  0, 100,   0,   5,  10,  15,  20,  25,  30,  25,  20,  15,  10,
         5,   0])
In [3]: np.save('test.npy',arr)
In [4]: np.load('test.npy')
Out[4]:
array([  0, 100,   0,   5,  10,  15,  20,  25,  30,  25,  20,  15,  10,
         5,   0])

Comment: That potentially makes a big difference.  You have to, in some sense, verify that the file that's being read is the same as the one that's saved.  For example with multiple processes the read might start before the save is finished.
Comment: It is a socket server. I have edited to add the code here. Please check
Comment: actually, I am calling these def functions separately at separate times, so it should get ample time to save.
Comment: You were right. I added 3 sec time delay, now it is working fine :D


Why would my new GTX 460 not outperform my old 8800 GT?

Question: I just purchased an Asus ENGTX460 DirectCU TOP/2DI/1GD5 to replace my Asus EN8800GT TOP/G/HTDP/512M.
For reference, here is a comparison chart of the approximate cards on Tom's Hardware.
I ran the Crysis GPU benchmark with results of:

8800GT = approximately 32FPS
GTX460 = approximately 32FPS - no increase in performance.

The Crysis settings for both tests were exactly the same for each test. And the test were run 3 times on each card.
Any ideas why the results would be nearly identical? Would this be a case where my older system is limiting any further FPS increase regardless of the video card I use?
My current system specs:

Motherboard: Asus A8N SLI Premium
Processor: AMD Athlon 64 X2 Dual Core 4400+
Memory: 4 gigs Corsair DDR-400 (XMS-3200C2)
HDD: Western Digital VelociRaptor WD3000HLFS 300GB 10000 RPM 16MB Cache
OS: Win XP x86
All drivers are up to date. System is kept extremely clean and updated.

Thanks for any input/insight you can provide.
Comment: What do [other benchmarks](http://www.futuremark.com/benchmarks/3dmark06/introduction/) say?  Crysis is rather poorly optimized, and not really representative of your performance in other games - more than anything, Crysis needs a *much* faster CPU than most games to get decent performance. [See also](http://gaming.stackexchange.com/questions/9397/graphics-card-processor-or-ram/9411#9411)
Comment: @BlueRaja - Agreed that Crysis may not be the best benchmark, but it is the game I've used in the past to benchmark when upgrading GPU's. For example, when I upgraded from a GeForce 7 series card to the 8800GT card, the FPS increased by about 35%. This latest upgrade was shocking to me as there was absolutely no FPS increase.
Answer: You most certainly have a performance bottleneck in your CPU. The X2 4400+ is over 5 years old now which, along with your older motherboard (which only supports PCIe 1.0, the 460 is designed for PCIe 2.0), is severely limiting any gains from your brand new video card.
This next part is a little hazy as I've heard conflicting arguments, so hopefully someone who understands this better will chime in. It seems you're using a 32-bit OS when you have over 4GB of RAM. x86 (or 32-bit) can't properly utilize memory over 3GB so this may also be limiting your performance.
Comment: An article to help with the hazy details: http://www.dansdata.com/askdan00015.htm
Comment: Very good point/catch about the PCI differences. I've been leaning toward the CPU and will run a few tests this afternoon. Regarding the RAM; you can shove 4GB in a x86 system. The OS will only recognize around 3.5 and the OS will further reduce the amount of RAM by how much your GPU is contributing.
Comment: This is exactly your problem. Your old components are bottlenecking the speeds you'd be able to get out of your video card. I know, because I tried to do the same thing that you're doing (ie - just upgrade the video card and forget the rest). You can only get away with that for a few years at most, but sooner or later you'll end up with bottlenecks from inferior components.
Answer: First of all, make sure you have the latest drivers, DirectX version etc. These can have a huge impact on performance.
But the most likely reason you do not experience any performance increase is that your graphics card isn't the bottleneck here. As games are a real-time challenge to your system, the weakest link will slow down the whole process.
So, are you CPU-bound, memory-bound, IO (disk) bound, or what? You can find more information by just checking how your system behaves. Open your task manager and choose to view page faults for the benchmark - a very high count hints that you do not have enough physical memory. Check out the CPU utilization - if it's constantly at 100% it's a sign it may not be fast enough for this game, regardless of how quickly the GPU can complete its own tasks.
These are just examples - you can find more information online about how to find the offending bottleneck.
Comment: All drivers are updated. I keep my system quite clean and updated. Do you have any links to narrowing down the offending bottleneck?
Comment: @Metro personally, no; but as this sounds very relevant to superuser.com, [I've just asked it there](http://superuser.com/questions/209438/).