text:
Q: Class members that are objects - Pointers or not? C++ If I create a class MyClass and it has some private member say MyOtherClass, is it better to make MyOtherClass a pointer or not?  What does it mean also to have it as not a pointer in terms of where it is stored in memory? Will the object be created when the class is created?
I noticed that the examples in QT usually declare class members as pointers when they are classes.

A: The common wisdom in C++ is to avoid the use of (bare) pointers as much as possible. Especially bare pointers that point to dynamically allocated memory.
The reason is because pointers make it more difficult to write robust classes, especially when you also have to consider the possibility of exceptions being thrown.

A: I follow the following rule: if the member object lives and dies with the encapsulating object, do not use pointers. You will need a pointer if the member object has to outlive the encapsulating object for some reason. Depends on the task at hand.
Usually you use a pointer if the member object is given to you and not created by you. Then you usually don't have to destroy it either.

A: This question could be deliberated endlessly, but the basics are:
If MyOtherClass is not a pointer:

*

*The creation and destruction of MyOtherClass is automatic, which can reduce bugs.

*The memory used by MyOtherClass is local to the MyClassInstance, which could improve performance.

If MyOtherClass is a pointer:

*

*The creation and destruction of MyOtherClass is your responsibility

*MyOtherClass may be NULL, which could have meaning in your context and could save memory

*Two instances of MyClass could share the same MyOtherClass

A: Some advantages of pointer member:

*

*The child (MyOtherClass) object can have different lifetime than its parent (MyClass).

*The object can possibly be shared between several MyClass (or other) objects.

*When compiling the header file for MyClass, the compiler doesn't necessarily have to know the definition of MyOtherClass. You don't have to include its header, thus decreasing compile times.

*Makes MyClass size smaller. This can be important for performance if your code does a lot of copying of MyClass objects. You can just copy the MyOtherClass pointer and implement some kind of reference counting system.

Advantages of having the member as an object:

*

*You don't have to explicitely write code to create and destroy the object. It's easier and and less error-prone.

*Makes memory management more efficient because only one block of memory needs to be allocated instead of two.

*Implementing assignment operators, copy/move constructors etc is much simpler.

*More intuitive

A:
If I create a class MyClass and it has some private member say MyOtherClass, is it better to make MyOtherClass a pointer or not?

you should generally declare it as a value in your class. it will be local, there will be less chance for errors, fewer allocations -- ultimately fewer things that could go wrong, and the compiler can always know it is there at a specified offset so... it helps optimization and binary reduction at a few levels. there will be a few cases where you know you'll have to deal with pointer (i.e. polymorphic, shared, requires reallocation), it is typically best to use a pointer only when necessary - especially when it is private/encapsulated.

What does it mean also to have it as not a pointer in terms of where it is stored in memory?

its address will be close to (or equal to) this -- gcc (for example) has some advanced options to dump class data (sizes, vtables, offsets)

Will the object be created when the class is created?

yes - the size of MyClass will grow by sizeof(MyOtherClass), or more if the compiler realigns it (e.g. to its natural alignment)

A: Where is your member stored in memory?
Take a look at this example:
struct Foo { int m; };
struct A {
  Foo foo;
};
struct B {
  Foo *foo;
  B() : foo(new Foo()) { } // ctor: allocate Foo on heap
  ~B() { delete foo; } // dtor: Don't forget this!
};

void bar() {
  A a_stack; // a_stack is on stack
             // a_stack.foo is on stack too
  A* a_heap = new A(); // a_heap is on stack (it's a pointer)
                       // *a_heap (the pointee) is on heap
                       // a_heap->foo is on heap
  B b_stack; // b_stack is on stack
             // b_stack.foo is on stack
             // *b_stack.foo is on heap
  B* b_heap = new B(); // b_heap is on stack
                       // *b_heap is on heap
                       // b_heap->foo is on heap
                       // *(b_heap->foo is on heap
  delete a_heap;
  delete b_heap;
  // B::~B() will delete b_heap->foo!
}

We define two classes A and B. A stores a public member foo of type Foo. B has a member foo of type pointer to Foo.
What's the situation for A:

*

*If you create a variable a_stack of type A on the stack, then the object (obviously) and its members are on the stack too.

*If you create a pointer to A like a_heap in the above example, just the pointer variable is on the stack; everything else (the object and it's members) are on the heap.

What does the situation look like in case of B:

*

*you create B on the stack: then both the object and its member foo are on the stack, but the object that foo points to (the pointee) is on the heap. In short: b_stack.foo (the pointer) is on the stack, but *b_stack.foo the (pointee) is on the heap.

*you create a pointer to B named b_heap: b_heap (the pointer) is on the stack, *b_heap (the pointee) is on the heap, as well as the member b_heap->foo and *b_heap->foo.

Will the object be automagically created?

*

*In case of A: Yes, foo will automatically be created by calling the implicit default constructor of Foo. This will create an integer but will not intitialize it (it will have a random number)!

*In case of B: If you omit our ctor and dtor then foo (the pointer) will also be created and initialized with a random number which means that it will point to a random location on the heap. But note, that the pointer exists! Note also, that the implicit default constructor won't allocate something for foo for you, you have to do this explicitly. That's why you usually need an explicit constructor and a accompanying destructor to allocate and delete the pointee of your member pointer. Don't forget about copy semantics: what happens to the pointee if your copy the object (via copy construction or assignment)?

What's the point of all of this?
There are several use cases of using a pointer to a member:

*

*To point to an object you don't own. Let's say your class needs access to a huge data structure that is very costly to copy. Then you could just save a pointer to this data structure. Be aware that in this case creation and deletion of the data structure is out of the scope of your class. Someone other has to take care.

*Increasing compilation time, since in your header file the pointee does not have to be defined.

*A bit more advanced; When your class has a pointer to another class that stores all private members, the "Pimpl idiom": http://c2.com/cgi/wiki?PimplIdiom, take also a look at Sutter, H. (2000): Exceptional C++, p. 99--119

*And some others, look at the other answers

Advice
Take extra care if your members are pointers and you own them. You have to write proper constructors, destructors and think about copy constructors and assignment operators. What happens to the pointee if you copy the object? Usually you will have to copy construct the pointee as well!

A: In C++, pointers are objects in their own right. They're not really tied to whatever they point to, and there's no special interaction between a pointer and its pointee (is that a word?)
If you create a pointer, you create a pointer and nothing else. You don't create the object that it might or might not point to. And when a pointer goes out of scope, the pointed-to object is unaffected. A pointer doesn't in any way affect the lifetime of whatever it points to.
So in general, you should not use pointers by default. If your class contains another object, that other object shouldn't be a pointer.
However, if your class knows about another object, then a pointer might be a good way to represent it (since multiple instances of your class can then point to the same instance, without taking ownership of it, and without controlling its lifetime)

A: If you make the MyOtherClass object as member of your MyClass:
size of MyClass = size of MyClass + size of MyOtherClass
If you make the MyOtherClass object as pointer member of your MyClass:
size of MyClass = size of MyClass + size of any pointer on your system
You might want to keep MyOtherClass as a pointer member because it gives you the flexibility to point it to any other class that is derived from it. Basically helps you implement dynamice polymorphism.

A: It depends... :-)
If you use pointers to say a class A, you have to create the object of type A e.g. in the constructor of your class
 m_pA = new A();

Moreover, don't forget to destroy the object in the destructor or you have a memory leak:
delete m_pA;
m_pA = NULL;

Instead, having an object of type A aggregated in your class is easier, you can't forget to destroy it, because this is done automatically at the end of lifetime of your object.
On the other hand, having a pointer has the following advantages:

*

*If your object is allocated on the
stack and type A uses a lot of memory
this won't be allocated from the
stack but from the heap.

*You can construct your A object later (e.g. in a method Create) or destroy it earlier (in method Close)

A: An advantage of the parent class maintaining the relation to a member object as a (std::auto_ptr) pointer to the member object is that you can forward declare the object rather than having to include the object's header file.
This decouples the classes at build time allowing to modify the member object's header class without causing all the clients of your parent class to be recompiled as well even though they probably do not access the member object's functions.
When you use an auto_ptr, you only need to take care of construction, which you could typically do in the initializer list. Destruction along with the parent object is guaranteed by the auto_ptr.

A: The simple thing to do is to declare your members as objects. This way, you do not have to care about copy construction, destruction and assignment. This is all taken care of automatically.
However, there are still some cases when you want pointers. After all, managed languages (like C# or Java) actually hold member objects by pointers.
The most obvious case is when the object to be kept is polymorphic. In Qt, as you pointed out, most objects belong to a huge hierarchy of polymorphic classes, and holding them by pointers is mandatory since you don't know at advance what size will the member object have.
Please beware of some common pitfalls in this case, especially when you deal with generic classes. Exception safety is a big concern:
struct Foo
{
    Foo()
    {
        bar_ = new Bar();
        baz_ = new Baz(); // If this line throw, bar_ is never reclaimed
                          // See copy constructor for a workaround
    }

    Foo(Foo const& x)
    {
        bar_ = x.bar_.clone();
        try { baz_ = x.baz_.clone(); }
        catch (...) { delete bar_; throw; }
    }

    // Copy and swap idiom is perfect for this.
    // It yields exception safe operator= if the copy constructor
    // is exception safe.
    void swap(Foo& x) throw()
    { std::swap(bar_, x.bar_); std::swap(baz_, x.baz_); }

    Foo& operator=(Foo x) { x.swap(*this); return *this; }

private:
    Bar* bar_;
    Baz* baz_;
};

As you see, it is quite cumbersome to have exception safe constructors in the presence of pointers. You should look at RAII and smart pointers (there are plenty of resources here and somewhere else on the web).


text:
Q: Wait-Notify получилась однопоточность Первый поток определяет количество пробелов в файле; если количество пробелов четное, второй поток делает первые буквы всех слов в файле заглавными, если нечетные - последние буквы. С применением wait и notify.
Почему получилась однопоточность?
public class Dispatcher {

    public static void main(String[] args) {
        FileChanger[] fileChanger = {
                new FileChanger(new File("text.txt")),
                new FileChanger(new File("text2.txt")),
                new FileChanger(new File("text3.txt"))
        };

        new CountSpaces(fileChanger).start();
        new ChangeText(fileChanger).start();
    }
}

class CountSpaces extends Thread{
    FileChanger[] fileChanger;

    public CountSpaces(FileChanger[] fileHandlers) {
        this.fileChanger = fileHandlers;
    }

    @Override
    public void run() {
        for (FileChanger fileChanger : fileChanger) {
            fileChanger.countSpace();
        }
    }
}

class ChangeText extends Thread {
    FileChanger[] fileChanger;

    public ChangeText(FileChanger[] fileHandlers) {
        this.fileChanger = fileHandlers;
    }

    @Override
    public void run() {
        for (FileChanger fileChanger : fileChanger) {
            try {
                fileChanger.changeLetters();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class FileChanger {
    boolean valueSet = true;
    int count;
    File file;

    public FileChanger(File file) {
        this.file = file;
    }

    synchronized void countSpace() {
        while (!valueSet) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try (Scanner sc = new Scanner(file)) {
            while (sc.hasNext()) {
                count++;
                sc.next();
            }
            valueSet = false;
            notify();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    synchronized void changeLetters() throws InterruptedException {
        while (valueSet) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try (Scanner sc = new Scanner(file);
             PrintWriter printWriter = new PrintWriter(file + "result")) {

            if ((count - 1) % 2 == 0) {
                while (sc.hasNext()) {
                    String word = sc.next();

                    printWriter.print(word.substring(0, 1).toUpperCase()
                    + word.substring(1) + " ");
                }
            } else {
                while (sc.hasNext()) {
                    String word = sc.next();
                    printWriter.print(word.substring(0, word.length() - 1)
                    + word.substring(word.length() - 1).toUpperCase() + " ");
                }
            }
            valueSet = false;
            notify();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

A: Проблема не обнаружена.
Добавив логирование в методы FileChanger::countSpace, FileChanger::changeLetters и запустив программу, получил такой вывод:
Thread-0:: countSpace text.txt: started
Thread-0:: countSpace text.txt: scanning started
Thread-0:: countSpace text.txt: done, count = 11
Thread-0:: countSpace text2.txt: started
Thread-0:: countSpace text2.txt: scanning started
Thread-1:: changeLetters text.txt: started
Thread-0:: countSpace text2.txt: done, count = 4
Thread-0:: countSpace text3.txt: started
Thread-0:: countSpace text3.txt: scanning started
Thread-1:: changeLetters scanning text.txt: and printing
Thread-0:: countSpace text3.txt: done, count = 7
Thread-1:: changeLetters in text.txt done
Thread-1:: changeLetters text2.txt: started
Thread-1:: changeLetters scanning text2.txt: and printing
Thread-1:: changeLetters in text2.txt done
Thread-1:: changeLetters text3.txt: started
Thread-1:: changeLetters scanning text3.txt: and printing
Thread-1:: changeLetters in text3.txt done

Process finished with exit code 0

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP: Is Static better than Non-Static? I got really confused with static and non-static functions and class properties when I was trying to run my website.
Can someone explain whether it is better to have the whole website written using Static functions rather than using the non-static methods?
I can't find much of this on google.

A: There is a school of thought according to which statics are harmful and should be avoided, because they create binds between classes which are too rigid. E.g. if you have classes A and B which call each other's methods, and then subclass AA and BB from them, and expect AA to invoke the code of BB, that will work nicely if they only know about each other as instances, but it will fail for static calls which will still point to A/B.
At any rate, PHP's implementation of statics is quite bad. There is no late static binding before 5.3 (meaning that an object can't call its own static methods, making static functions farily useless in an OOP architecture), static functions cannot be called non-statically in strict mode, calling functions the wrong way will result in very weird errors, classes share their static variables with their parents... when uncertain, you should go with non-static IMHO.

A: This really depends on how your application is designed. If the function can and will be called and without instantiating the class, then declare it as static. Otherwise, don't. In almost all cases you would be using a combination of the two, since using only static functions wouldn't make sense (you might as well write procedural code).

A: It doesn't make sense writing OO code and using only static variables and methods. It would be same as writing procedural code. you can't benefit from all the functionality OOP gives only using static code.
I'm not saying that you mustn't use static methods or properties, but using them a lot is an indicator of a bad OO design.

A: If your method needs access to data in "this->", then you have to make it a non-static method. Then the object needs to be instantiated (via "new").
If all your method uses is data contained in function parameters, then consider making your method static. Or create a separate class with static methods only.


text:
Q: What are ordered hashes in Ruby used for? I recently started learning Ruby and hashes. At first I learned that hashes are unordered which makes sense, but now I found out that hashes are ordered with later versions of Ruby. I don't really understand why or the concept behind this.
Could I get some insight as to what the ordered hashes are for? Possible use cases would be nice too for regular hash vs. ordered hash.

A: Some people like to rely on ordering of a Hash, because the ordered-hash remembers the insertion order of the key/value pairs. This allows the programmer to use a hash somewhat like a queue with random access to the values associated with the keys. This would be useful if they intend to change values on the fly and then iterate over the queue's key/value pairs to retrieve them in the insertion order again.
Also, rather than have to supply indexes into the queue, like they would if they were using an Array-based queue, they can supply a symbolic name.
Instead of:
queue[0]

they can use:
queue[:fred]

That's the only use-case I can see for ordered hashes; It'd be really easy to duplicate the functionality with a queue of keys that preserved the insertion order.

A: Looking back at some of the previous posts by Matz, he was pretty vague as to why it was implemented. Check out https://www.ruby-forum.com/topic/166075
He basically states that it was implemented to fit some edge cases but he didn't seem to elaborate on it more than that. He also stated that there was no impact on performance, just a negligible increase in memory consumption.

A: Imagine git commits, handled by ruby git wrapper. They are likely instance of a Hash, with sha as keys. While the sorting by Date makes them easily iteratable in a human-friendly manner.


text:
Q: Control may reach end non-void function The attached code is returning an error:
Control may reach end non-void function

Code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row == 0) {
        FirstCustomCell *fCustomCell = [tableView dequeueReusableCellWithIdentifier:@"firstCustomCell" forIndexPath:indexPath];

        if (fCustomCell == nil) {

            fCustomCell = [[FirstCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"firstCustomCell"];
        }

        return fCustomCell;

    }

    else if (indexPath.row == 1) {
        SecondCustomCell *sCustomCell = [tableView dequeueReusableCellWithIdentifier:@"secondCustomCell" forIndexPath:indexPath];

        if (sCustomCell == nil) {

            sCustomCell = [[SecondCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SecondCustomCell"];
        }

        return sCustomCell;

    }
} //<-- Control may reach non-void function (I precise that's the end of the cellForRowAtIndexPath method)

I know that the problem is specially at the "return" but how do I eliminate the error?

A: You account for the cases where indexPath.row == 0 and where indexPath.row == 1 but the compiler is saying: What should I return if the row isn't 0 or 1?
You probably want a return nil; at the end of your method.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        FirstCustomCell *fCustomCell = [tableView dequeueReusableCellWithIdentifier:@"firstCustomCell" forIndexPath:indexPath];
        if (fCustomCell == nil)
        {
            fCustomCell = [[FirstCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"firstCustomCell"];
        }
        return fCustomCell;
    }
    else if (indexPath.row == 1)
    {
        SecondCustomCell *sCustomCell = [tableView dequeueReusableCellWithIdentifier:@"secondCustomCell" forIndexPath:indexPath];
        if (sCustomCell == nil)
        {
            sCustomCell = [[SecondCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"secondCustomCell"];
        }
        return sCustomCell;
    }
    return nil; //<--Add this line
}

Or perhaps an "else" case:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        FirstCustomCell *fCustomCell = [tableView dequeueReusableCellWithIdentifier:@"firstCustomCell" forIndexPath:indexPath];
        if (fCustomCell == nil)
        {
            fCustomCell = [[FirstCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"firstCustomCell"];
        }
        return fCustomCell;
    }
    else if (indexPath.row == 1)
    {
        SecondCustomCell *sCustomCell = [tableView dequeueReusableCellWithIdentifier:@"secondCustomCell" forIndexPath:indexPath];
        if (sCustomCell == nil)
        {
            sCustomCell = [[SecondCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"secondCustomCell"];
        }
        return sCustomCell;
    }
    else //<--Add this clause
    {
        OtherCustomCell *oCustomCell = [tableView dequeueReusableCellWithIdentifier:@"otherCustomCell" forIndexPath:indexPath];
        if (oCustomCell == nil)
        {
            oCustomCell = [[OtherCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"otherCustomCell"];
        }
        return sCustomCell;
    }
}

Note: You also have a typo in your reuse identifiers:
"secondCustomCell" is not the same as "SecondCustomCell"

A: Add a return nil; line.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row == 0) {
        FirstCustomCell *fCustomCell = [tableView dequeueReusableCellWithIdentifier:@"firstCustomCell" forIndexPath:indexPath];

        if (fCustomCell == nil) {

            fCustomCell = [[FirstCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"firstCustomCell"];
        }

        return fCustomCell;

    }

    else if (indexPath.row == 1) {
        SecondCustomCell *sCustomCell = [tableView dequeueReusableCellWithIdentifier:@"secondCustomCell" forIndexPath:indexPath];

        if (sCustomCell == nil) {

            sCustomCell = [[SecondCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SecondCustomCell"];
        }

        return sCustomCell;

    }
    return nil;
     }

I might add that you need to make sure that you fCustomCell and your sCustomCell are not (!=) nil.
if (!fCustomCell) {
    fCustomCell = [UITableViewCell alloc] initWithStyle:/*aStyle*/ reuseIdentifier:/*identifier*/];
}

The identifier can be a static NSString defined at the beginning of the method like so: static NSString *identifier = @"cell";
Look at some tutorials.


text:
Q: Connect GIMP with PHP or Python is there any way to connect GIMP with python or PHP and use its libraries? It seems that all i can find on the web is pygimp which is not supported anymore.
ps. i do my development on mac and i use linux as a production server

A: You can write GIMP plugins in Python (see, for example James Hestenridge's clothify, then call the plug-in from the command-line with a command of the form
gimp -i -b '(python-fu-bw-film RUN-NONINTERACTIVE "/path/to/filename.jpg" 0 1 FALSE FALSE FALSE FALSE FALSE FALSE)' -b '(gimp-quit 0)'

It's not exactly pretty, but it's possible. Here is another example.

A: Probably not directly, but I'll bet you can access some functions via 'exec()' on the command line.  What are you trying to do?  Can the GD or ImageMagic tools help?

A: One important thing regarding running gimp python plugin in batch mode.
Option -i means no interface. But in gimp documentation there is another option with same explanation --no-interface. User could though that they have same effect.
But when you try to run batch script on remote linux machine, with option -i you will get 'no display'. With option --no-interface, batch script will run without error. My colleague discovered that this is undocumented gimp 2.6.11 feature.
Regards, Karlo.


text:
Q: Which is the best redirection method used in html and javascript? I have seen location.href, window.open, window.location, etc for redirection.

*

*I want to know which is the best method and works on every device.

*One more thing if I have using setTimer and loads the script after loads the page elements which is the best method?

Please treat answer for both 1 and 2 question separately and thanks in advance.

A: window.location.href = 'URL';

is the standard implementation for changing the current window's location.
document.location is a (deprecated but still present) read-only string property, replaced by document.url.
window.location also affects to the frame,
the best form i found is:
parent.window.location.href

And the worse is:
parent.document.URL

I did a massive browser test, and some rare IE with several plugins get undefined with the second form.


text:
Q: mysqli insert to database not working I'm trying to insert data into my MySQL table, but not working!
My code:
if(isset($_POST['btn44'])){
        $fname=$_POST['fname'];
        $lname=$_POST['lname'];
        $mysqli->query("INSERT INTO `mss_user` (`fname`,`lname`) VALUES ('$fname','$lname')");
}

The connection is fine, returns no errors.

A: try this
 echo "INSERT INTO `mss_user` (`fname`,`lname`) VALUES ('$fname','$lname')";
 $mysqli->query("INSERT INTO `mss_user` (`fname`,`lname`) VALUES ('$fname','$lname')");

then you can read real query and copy this string and paste in mysql client or phpmyadmin page.

A: First of all, does your connect the Database ?
Second thing, if you check the result with bamtoggi suggestion, and if there is nothing in the place of $fname and $lname, you should try to extract data value from string like this :
   $mysqli->query("INSERT INTO `mss_user` (`fname`,`lname`) VALUES (' "+$fname+" ',' "+$lname+" ');");

Let us know.


text:
Q: Algebraic closure of Puiseaux field $K((T))$ equals $\bigcup_{n \ge 1} K((T^{1/n}))$ I want to show that the algebraic closure $L:= \overline{K((T))}$ of Puiseaux field $K((T))$ for $K$ alg. closed of char $K=0$ equals the union $\bigcup_{n \ge 1} K((T^{1/n}))$.
The closure clearly contains the union. For the other direction we have to chow that every finite alg extension of $K((T))$ is contained in $K((T^{1/n}))$ for certain $n$.
We asking which different types of finite extensions for local fields can occure? There are tamely ramified, wildly ramified and unramified extensions.
Since $K$ is already algebraically closed the "fundamental formula" (what is it's true name?) $[M:K((T))]=e f$ tells that no non trivial unramified extension could exist.  Also, wildly extensions no exist as the characteritic of residue field $K$ is $0$. That is we only have have to deal with finite tamely ramified extensions.
Questions: What do we know about such finite tamely ramified extensions? The residue field not changes. How can I conclude that each such extension is contained in a $K((T^{1/n}))$ for appropriate $n$? Any result (I actually not know) from theory of local field?
Addendum: I noticed that this question Algebraic closure of $k((t))$ dealed with same problem. The answer is beautiful but attacked the problem from another viewpoint. Can the claim be proved only with methods from class field theory?
an outlook: although I haven't finished the proof yet, it is known to to true for $K$ alg closed of char $0$. Can the claim be generalized under weaker assumptions? Ie if we assume char $K>0$ or $K$ is not more closed?
My guess is not since we obtain in any or these two cases a new class of non traivial finite extensions: the unramified or the wildly ramified which we before excluded. But that's just my conjecture. Are some concrete conterexamples known?

A: $F=K((t))$ with $K$ algebraically closed of characteristic $0$.
For a finite extension $E/F$, with corresponding complete DVR $O_F=K[[t]]\subset O_E$ and uniformizers $\pi_F=t,\pi_E$ and residue field $O_F/(\pi_F)=O_E/(\pi_E)=K$.
The completeness says that $$O_E=\sum_{n\ge 0} \pi_E^n K=\sum_{n= 0}^{[E:F]-1} \pi_E^n O_F$$
ie. $\pi_F = u \pi_E^{[E:F]}$ where $u\in O_F^\times$.
Let $a\in K^\times$ such that $au \in 1+\pi_F O_F$.
Then $(au)^{1/[E:F]}=\sum_{k\ge 0} {[E:F]\choose k} (au-1)^k \in O_F$ and $a^{1/[E:F]}\in O_F$ which means that $u^{1/[E:F]}\in O_F$ ie. $\pi_F^{1/[E:F]} \in O_F$.
But $\pi_F^{1/[E:F]} $ is also an uniformizer so that $$O_E=\sum_{n\ge 0} (\pi_F^{1/[E:F]})^n K=\sum_{n= 0}^{[E:F]-1} (\pi_F^{1/[E:F]})^n O_F$$ and

$E = F(\pi_F^{1/[E:F]})$

Whence $$\overline{F}=\bigcup_{[E:F]<\infty} E=\bigcup_{[E:F]<\infty}F(\pi_F^{1/[E:F]})=\bigcup_m K((t))(t^{1/m})$$

A: Because $K$ is algebraically closed of characteristic $0$, every finite extension of $K((t))$ is a tamely totally ramified extension: tamely ramified because the residue field $K$ of $K((t))$ has characteristic is $0$, and totally ramified because the residue field $K$ of $K((t))$ has no proper finite extensions.
A totally ramified extension of a complete discretely valued field $F$ is generated by a root of an Eisenstein polynomial, and a tamely totally ramified extension is  generated by a root of an Eisenstein polynomial of binomial type $x^n - c$ where $c$ is a uniformizer of $F$, but typically we can't force $c$ to be a particular uniformizer. A standard example of this issue is the cyclotomic extension $\mathbf Q_p(\zeta_p)$ of $\mathbf Q_p$: this is tamely totally ramified of degree $p-1$, so $\mathbf Q_p(\zeta_p)$ equals $\mathbf Q_p(\sqrt[p-1]{up})$ for some $u \in \mathbf Z_p^\times$. It turns out we can use $u = -1$: $\mathbf Q_p(\zeta_p)$ is $\mathbf Q_p(\sqrt[p-1]{-p})$ but it is not $\mathbf Q_p(\sqrt[p-1]{p})$ when $p > 2$.
When the residue field of $F$ is algebraically closed of characteristic $0$ then we can control the constant term of that binomial Eisenstein polynomial: it can be any uniformizer of $F$.
Theorem. Let $F$ be a complete discretely valued field with uniformizer $\pi$ and $n$ be a positive integer.
(1) Every tamely totally ramified extension of $F$  with degree $n$ has the form $F(\sqrt[n]{u\pi})$ for some $u \in \mathcal O_F^\times$ and some $n$th root of $u\pi$.
(2) If the residue field of $F$ is algebraically closed of characteristic $0$ then the only extension of $F$ with degree $n$ is $F(\sqrt[n]{\pi})$, where this field is independent of the choice of $n$th root of $\pi$.
Proof.
(1) Let $E/F$ be totally ramified of degree $n$ and $\Pi$ be a uniformizer of $E$. Then $\pi$ and $\Pi^n$ have the same valuation in $E$, so $\Pi^n = v\pi$ for some unit $v \in \mathcal O_E^\times$. A totally ramified extension of $F$ is generated by any of its uniformizers, so $E = F(\Pi)$. (Warning. Since $\Pi^n = v\pi$, we could write $E = F(\sqrt[n]{v\pi})$, but this is not what the theorem is about because $v$ here is a unit up in $E$, not down in $F$, so $v\pi$ is not a uniformizer in $F$. The fact that we didn't even use the tameness property also shows the poor quality of such an argument.)
Since the residue field degree is $1$, $v \equiv u \bmod \Pi$ for some $u \in \mathcal O_F^\times$, so $v = uw$ where $w \equiv 1 \bmod \Pi$. The polynomial $g(x) = x^n - w$ in $\mathcal O_E[x]$ has a root $\varepsilon$ in $\mathcal O_E^\times$ by Hensel's lemma ($|g(1)|_E < 1$ and $|g'(1)|_E = |n|_E = 1$; that $|n|_E = 1$ is where we use the tameness condition). Thus $v = uw = u\varepsilon^n$, so $\Pi^n = v\pi = u\varepsilon^n\pi$, so  $(\Pi/\varepsilon)^n = u\pi$. Since $\Pi/\varepsilon$ is a uniformizer of $E$, $E = F(\Pi/\varepsilon) = F(\sqrt[n]{u\pi})$.
(2)  First we develop some background about extensions of $F$ by $n$th roots. Since the residue field of $F$ is algebraically closed of characteristic $0$, $F$ has characteristic $0$. The polynomial $x^n - 1$ has $n$ distinct roots in the residue field of $F$, so $x^n - 1$ has $n$ distinct roots in $F$ by Hensel's lemma. Therefore for $a \in F^\times$, the field $F(\sqrt[n]{a})$ is a Galois extension of $F$ (a Kummer extension) and it is independent of the choice of $n$th root of $a$: there is only one of these fields in an algebraic closure of $F$, unlike the three extensions of $\mathbf Q$ by a cube root of $2$ in an algebraic closure of $\mathbf Q$.
Now let's look at an extension field $E$ of $F$ with degree $n$. Since $F$ is complete with respect to a discrete valuation and its residue field is perfect, we have $n = e(E/F)f(E/F)$, and $f(E/F) = 1$ since the residue field is algebraically closed: every finite extension of $F$ is totally ramified. And since $n \not= 0$ in the residue field of $F$, every finite extension $E$ of $F$ is tamely totally ramified. Therefore if we pick a uniformizer $\pi$ of $F$, (1) tells us $E = F(\sqrt[n]{u\pi})$ for some unit $u \in \mathcal O_F^\times$ and some $n$th root of $u\pi$, although the previous paragraph tells us $E$ is the same for all choices of $n$th root of $u\pi$.
In the residue field of $F$, $u$ is congruent to an $n$th power (since the residue field is algebraically closed of characteristic $0$), so $u$ is an $n$th power in $\mathcal O_F^\times$ by Hensel's lemma.  Therefore $E = F(\sqrt[n]{u\pi}) = F(\sqrt[n]{\pi})$. QED
Corollary. If $F$ is a complete discretely valued field whose residue field is algebraically closed of characteristic $0$, and $\pi$ is a uniformizer of $F$, then the algebraic closure of $F$ is $\bigcup_{n \geq 1} F(\sqrt[n]{\pi})$.
Proof. The algebraic closure of $F$ is a union of finite extensions of $F$, and the only extension of $F$ of a degree $n$ is $F(\sqrt[n]{\pi})$ (which is independent of the choice of $n$th root of $\pi$. QED
When $K$ is an algebraically closed field of characteristic $0$, the field $K((T))$ has residue field $K$ and it is complete with respect to the $T$-adic valuation, with uniformizer $T$. So if you apply the corollary to the field $K((T))$ with $\pi = T$, then the corollary says the algebraic closure of $K((T))$ is $\bigcup_{n \geq 1} K((T))(\sqrt[n]{T})$. We have $K((\sqrt[n]{T})) = K((T))(\sqrt[n]{T})$: for a power $\sqrt[n]{T}^j$, write $j = kn + r$ where $0 \leq r \leq n$, so $\sqrt[n]{T}^j = T^k\sqrt[n]{T}^r$ and that lets you rewrite a Laurent series in $\sqrt[n]{T}$ as a $K((T))$-linear combination of $1$, $\sqrt[n]{T}, \ldots, \sqrt[n]{T}^{n-1}$. Therefore the algebraic closure of $K((T))$ is $\bigcup_{n \geq 1} K((\sqrt[n]{T}))$.


text:
Q: check the platform of the installed mingw, 32bit or 64 bit I am programming in c++. I have installed mingw. I installed it from the standard installer from mingw website. I am confused between mingw32, mingw, mingw64. What are the differences and how can I check my version. Also when my programs are build, how would I know whether the executables created are 32 bit or 64 bit?

A: As indicated in the comments to the currently accepted answer gcc --version will not give the target information but rather the version of gcc itself.
Instead gcc -v will print verbose information about the environment of the compiler. Among it you will find either the 64 bit (as shown by "x86_64")
Target: x86_64-w64-mingw32

or the 32 bit (as shown by "i686")
Target: i686-w64-mingw32

A: mingw and mingw32 are for creating executables for 32-bit windows systems.  mingw64 is for creating 64-bit executables. Note: this doesn't have to do with what version you are running when you do the build, but what the target system is for the executable you are creating (the system on which you will be running the newly created executable).
Regarding MinGW and MinGW32, here's a snippet from The MinGW Wiki

"The project's name changed from mingw32 to MinGW is to prevent the
  implication that MinGW will only works on 32 bit systems (as 64 and
  higher bit machines become more common, MinGW will evolve to work with
  them)."

To find out what version you have, go the the associated bin directory and do:
gcc --version

I'd recommend checking out minGW-w64, from here: http://mingw-w64.sourceforge.net/ That projects goal is to "deliver runtime, headers, and libs for developing 64 bit (x64), as well as 32 bit (x86), windows applications using gcc-4.6 or newer versions."


text:
Q: Complex POJO validation with PlayFramework Is there an elegant way to validate a POJO parameter with another parameter from the same POJO with PlayFramework ? I'm searching a solution which keep the Play error mechanism.
Exemple :
@Entity
public class Page extends Model {

    @Required
    @Min(0)
    public Integer minWidth;

    @Required
    @Min(0)
    public Integer maxWidth;
}

I need to check that minWidth < maxWidth.

A: You need to write a custom validator and use the @CheckWith annotation.
You could also write a custom annotation (docs on the same page as above), but it's more complicated.


text:
Q: Group By : Remove groups(rows) based on condition I have a dataframe df :-

ID
Date
Event

3
04-09-2013
Success

3
27-09-2013
Success

3
14-10-2013
Success

3
15-10-2013
Email

3
18-10-2013
Form

3
19-10-2013
Click

If the first event for every group of ID is Success or followed by Consecutive Success(note
strictly start with and /or followed by consecutive Success )then I want to drop the ID from the dataframe(Drop all the rows for that ID from the df)
Also if the case where the group is this way :-

ID
Date
Event

4
04-09-2013
Success

4
27-09-2013
Success

4
14-10-2013
Email

4
15-10-2013
Email

4
18-10-2013
Success

4
18-10-2013
Success

4
18-10-2013
Click

Expected output to be (i.e a.)remove rows if the first event/consecutive events are Success and also b.)drop the events(rows) after the last/latest success within each group(taken one example of Event click but if there are more events those are to be dropped as well):

ID
Date
Event

4
14-10-2013
Email

4
15-10-2013
Email

4
18-10-2013
Success

4
18-10-2013
Success

b.) is valid for every group irrespective of how the Event starts( for example ) :-

ID
Date
Event

5
14-10-2013
Email

5
15-10-2013
Click

5
18-10-2013
Success

5
18-10-2013
Email

Expected :-

ID
Date
Event

5
14-10-2013
Email

5
15-10-2013
Click

5
18-10-2013
Success

How can this be achieved?

A: Use:
#remove values after last Success per groups + not remove only non Success groups
df = df.iloc[::-1]
m = df['Event'].eq('Success')
df  = df[~m.groupby(df['ID']).transform('all') | m.groupby(df['ID']).cummax()].iloc[::-1]

#remove first conscutive Success per groups
m1 = df['Event'].ne(df.groupby(df['ID'])['Event'].shift()).groupby(df['ID']).cumsum().ne(1)
#alternative solution
#m1 = df['Event'].mask(df['Event'].eq('Success')).groupby(df['ID']).ffill().notna()
m2 = df['Event'].ne('Success')

df = df[m1 | m2]
print (df)
    ID        Date    Event
8    4  14-10-2013    Email
9    4  15-10-2013    Email
10   4  18-10-2013  Success
11   4  18-10-2013  Success
13   5  14-10-2013    Email
14   5  15-10-2013    Click
15   5  18-10-2013  Success


text:
Q: Run supervisor in virtual environment I installed supervisor and gunicorn in my virtual environment (venv).
I am using this tutorial: https://realpython.com/blog/python/kickstarting-flask-on-ubuntu-setup-and-deployment/
I'm confused as to where I should be creating the config file for supervisor as the default etc/supervisor won't apply to me.
The supervisorctl file is in the directory:
/home/giri/venv/py2.7/lib/python2.7/site-packages/supervisor
I noticed this line in the supervisorctl file:
Options:
-c/--configuration -- configuration file path (default /etc/supervisord.conf)

Do I need to manually set this flag each time I run the supervisorctl script or is there another way?
Thanks

A: As found in the docs (http://supervisord.org/configuration.html):

The Supervisor configuration file is conventionally named
  supervisord.conf. It is used by both supervisord and supervisorctl. If
  either application is started without the -c option (the option which
  is used to tell the application the configuration filename
  explicitly), the application will look for a file named
  supervisord.conf within the following locations, in the specified
  order. It will use the first file it finds.

*

*$CWD/supervisord.conf

*$CWD/etc/supervisord.conf

*/etc/supervisord.conf

So put the supervisor.conf in your current working directory and you're fine.


text:
Q: Mozilla FF browser.tabs.create() doesn't work I have a problem with my own extension for mozilla firefox. I want to open a new tab after click event on a document. I wrote this:
  (() => {
    document.addEventListener('click', () => {
      console.log('click');
      browser.tabs.create({});
    });
  })();

What is wrong with my code? Console prints'click' so event works. Also in manifest.json I have this permission (and only this one):
"permissions": [
    "tabs"
  ]

I will be very gratefull for an answear :)

A: The "browser.tabs" API only works in a background script. You are using it in a content script. Most APIs in WebExtensions only work in a background script.
From MDN:

JavaScript APIs for WebExtensions can be used inside the extension's
  background scripts and in any other documents bundled with the
  extension, including browser action or page action popups, sidebars,
  options pages, or new tab pages. A few of these APIs can also be
  accessed by an extension's content scripts (see the list in the
  content script guide).

Please read more about WebExtensions: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API
The answer to this question contains more info: TypeError: browser is undefined (Web Extension Messaging)


text:
Q: Recursion Error with Surface_polygon I'm having a recursion error that I think is very basic but I'm not seeing the problem, although I think it's in the stopping condition.
Basically, I have a list of lists, where each list is a floor with around 30 points. I'm doing a recursion that goes to each floor and makes a surface polygon in each and then i make an extrusion with each surface_polygon in another function.
Down below is the code and the error message, he makes me the 75 floors I want to make but once the list of floors is empty he errors.
    def pisos_generico(list_lists):
        if list_lists == []:
            pass
        else:
            return surface_polygon (list_lists[0]) + pisos_generico(list_lists[1:])

    def pisos (list_lists):
        return extrusion(pisos_generico (list_lists)

This is the error code:
 Traceback (most recent call last):
      File "D:\Universidade\3o Ano\PCA\Projeto\First Try Base Planta 2.py", line
    547, in <module>
        pisos (xy(0,0), 1.41, 0.02, 75)
      File "D:\Universidade\3o Ano\PCA\Projeto\First Try Base Planta 2.py", line
    529, in pisos
        return extrusion(pisos_generico (piso_pisos_rodados (lista, n_andares, p, a, a_torcao)), vz(0.3))
      File "D:\Universidade\3o Ano\PCA\Projeto\First Try Base Planta 2.py", line 503, in pisos_generico
        return surface_polygon (list_lists[0]) + pisos_generico(list_lists[1:])
      File "D:\Universidade\3o Ano\PCA\Projeto\First Try Base Planta 2.py", line 503, in pisos_generico
        return surface_polygon (list_lists[0]) + pisos_generico(list_lists[1:])
      File "D:\Universidade\3o Ano\PCA\Projeto\First Try Base Planta 2.py", line 503, in pisos_generico
        return surface_polygon (list_lists[0]) + pisos_generico(list_lists[1:])
       [Previous line repeated 72 more times]
TypeError: unsupported operand type(s) for +: 'surface_polygon' and 'NoneType'

Updated version:
def pisos (p, a, a_torcao, n_andares):
     return pisos_generico (lista_listas)

def pisos_generico(list_lists):
    if list_lists == []:
        []
    else:
        return [extrusion(surface_polygon (list_lists[0]), vz(0.3))] + pisos_generico(list_lists[1:])

And the new Error message, pretty much like the old one:
Traceback (most recent call last):
  File "D:\Universidade\3o Ano\PCA\Projeto\First Try Base Planta 2.py", line
548, in <module>
    pisos (xy(0,0), 1.41, 0.02, 75)
  File "D:\Universidade\3o Ano\PCA\Projeto\First Try Base Planta 2.py", line
530, in pisos
    return pisos_generico (lista_listas)
  File "D:\Universidade\3o Ano\PCA\Projeto\First Try Base Planta 2.py", line
503, in pisos_generico
    return [extrusion(surface_polygon (list_lists[0]), vz(0.3))] +
pisos_generico(list_lists[1:])
  File "D:\Universidade\3o Ano\PCA\Projeto\First Try Base Planta 2.py", line
503, in pisos_generico
    return [extrusion(surface_polygon (list_lists[0]), vz(0.3))] +
pisos_generico(list_lists[1:])
  File "D:\Universidade\3o Ano\PCA\Projeto\First Try Base Planta 2.py", line
503, in pisos_generico
    return [extrusion(surface_polygon (list_lists[0]), vz(0.3))] +
pisos_generico(list_lists[1:])
  [Previous line repeated 72 more times]
TypeError: can only concatenate list (not "NoneType") to list

Thank you so much for the help

A: Function implicitly return None if you return noting. This happens on
def pisos_generico(list_lists):
    if list_lists == []:
        pass
    else:
        return surface_polygon (list_lists[0]) + pisos_generico(list_lists[1:])
        #                                                        ^^^^^^^^^^^^
        #                                                     empty => returns None

   # exactly here on list_lists == [] is None returned

You probably need something like:
def pisos_generico(list_lists):
    if list_lists == []:                          # you can delete the ``... == []: pass``
        pass                                      # part and make the next one
    elif len(list_lists) == 1:                    # a normal if instead of elif
        return surface_polygon (list_lists[0])    # just make sure you do not call it with
    else:                                         # an empty list to start with
        return surface_polygon (list_lists[0]) + pisos_generico(list_lists[1:])


text:
Q: How to make calculator in asp.net using javascript? Howdy!
I want to make calculator in asp.net. without involving html and ajax, I want to use java script with asp. Any guide??

A: You can get started here for JavaScript.  You really don't need ASP for a simple calculator although it wouldn't hurt anything to create an ASP project for this I suppose.  Just keep in mind, that in this case, shoehorning ASP into this project is definitely not necessary and probably a bit of overkill.
If you are interested in jQuery at all, there is a much better tutorial for a jQuery calculator here.

A: You obviously need HTML if you want to do this in a browser, otherwise you won't have any input controls. A really simple calculator can be easily made in a few lines of JavaScript (you don't even need jQuery). Something like:

<input type="text" id="data" />
<input type="button" value="Calculate" onclick="calculate()" />

Just type your equation in the text box (eg. 2 + 4 / 10) and click the button!

A:

var cnt = 0;

function addcount(x) {
    var y = document.getElementById("text1").value;
    var l = y.length;
    var last = y.charAt(l - 1);
    if (last != x) {
        cnt = 0;
    }
    cnt = parseInt(cnt) + parseInt(1);
    if (cnt <= 1) {
        document.getElementById("text1").value += x;
    }
    else {
        document.getElementById("text1").innerHTML = '';
    }
}

function event1(m) {
    document.getElementById("text1").value += m;
    var z = document.getElementById("text1").value;
    document.getElementById("text3").value = eval(z);
    document.getElementById("text1").value = eval(z);
}

function event2() {

    var x = document.getElementById("text1").value;

    document.getElementById("text1").value = eval(x);
}

function event3() {
    document.getElementById("text1").value = "";
    document.getElementById("text3").value = "";
}

function event4() {
    var x = document.getElementById("text1").value;
    var sillyString = x.slice(0, -1);
    document.getElementById("text1").value = sillyString;
}
.curve{
    border-radius: 13px;
}
.col{
    background-color: #00acc1;
}
.col1{
    background-color: #e8f5e9;
}
.col2{
    background-color: #1C2331;
}

#text1{

}
#text3{

}

    <title>Calculator</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

Calculator

            <input type="text" id="text1" class="curve col1" style="text-align:right;width:100%;"/>

            <input type="text" id="text3"  class="curve col1" style="text-align:right;width:100%;"/>

            <button type="button" value="/" onClick="addcount(this.value)" class="curve btn-primary" style="padding:8px 14px;">/</button>
            <button type="button" value="." onClick="addcount(this.value)" class="curve btn-primary" style="padding:8px 14px;">.</button>
            <button type="button" value="*" onClick="addcount(this.value)" class="curve btn-primary"style="padding:8px 14px;">*</button>
            <button type="button" value="-" onClick="addcount(this.value)" class="curve btn-primary"style="padding:8px 14px;">-</button>
            <button type="button" value="" onClick="event3(this.value)"  class="curve btn-primary"style="padding:6px 18px;">C</button>

            <button type="button" value="7" onClick="event1(this.value)" class="curve btn-primary" style="padding:7px 12px;">7</button>
            <button type="button" value="8" onClick="event1(this.value)"  class="curve btn-primary"style="padding:7px 12px;">8</button>
            <button type="button" value="9" onClick="event1(9)" class="curve btn-primary" style="padding:7px 12px;">9</button>
            <button type="button" id="ad"value="+" class="curve btn-primary" style="height:70px;padding:8px 13px;" onClick="addcount(this.value)">+</button>
            <button type="button" value="" onClick="event4(this.value)" class="curve btn-primary" style="padding:6px 10px;">DEL</button>

            <button type="button" value="4" onClick="event1(4)" class="curve btn-primary" style="padding:7px 12px;">4</button>
            <button type="button" value="5" onClick="event1(5)" class="curve btn-primary" style="padding:7px 12px;">5</button>
            <button type="button" value="6" onClick="event1(6)" class="curve btn-primary" style="padding:7px 12px;">6</button>

            <button type="button" value="1" onclick="event1(1)" class="curve btn-primary" style="padding:7px 12px;">1</button>
            <button type="button" value="2" onClick="event1(2)" class="curve btn-primary" style="padding:7px 12px;">2</button>
            <button type="button" value="3" onClick="event1(3)" class="curve btn-primary" style="padding:7px 12px;">3</button>
            <button type="button" class="curve btn-primary" style="height:70px;padding:8px 13px;" onClick="event2()">=</button>

            <button type="button" class="curve btn-primary" onclick="event1(0)" style="padding:7px 12px;">0</button>


text:
Q: Puppeteer - Search for element by div class - Return all div classes for Element I have a site I need to scrape, to find a list of classes on a div, by searching for a particular div class.
For instance, if we have the code:
//HTML on site

Main Stuff

Other Stuff

Footer Stuff
'

I need to search for "special class" as a div class, and return the list of classes for that div, so I would want to return:
class1 class2 specialclass
I'm using a Wikibooks site as an example and running this code:
//Puppeteer Code
const puppeteer = require('puppeteer')
const devices = require('puppeteer/DeviceDescriptors');

const browser = await puppeteer.launch();

const page = await browser.newPage();
await page.goto('https://www.wikibooks.org/');

const myclassname = await page.evaluate(() =>
document.querySelector('.lang1').innerText);

console.log(myclassname);

It searches for the div with a class of lang1, the default language div near the top of the screen, and returns me the text of the object, but I don't know what to change innerText to in order to get the class names of the object, so it will return central-featured-lang lang1, all of the classes of that object.

A: use
.getAttribute("class");

for example
var x = document.getElementsByTagName("H1")[0].getAttribute("class");

A: Consider the following element from the webpage you specified:

...

You can use className or getAttribute('class') to obtain the content of the class attribute of an element:
const myclassname = await page.evaluate(() => document.querySelector('.lang1' ).className);

console.log(myclassname); // Returns "central-featured-lang lang1"

Or, you can return an iterable array of the classes of an element using classList:
const myclassnamearray = await page.evaluate(() => [...document.querySelector('.lang1').classList]);

console.log(myclassnamearray[0]); // Returns "central-featured-lang"
console.log(myclassnamearray[1]); // Returns "lang1"


text:
Q: Is UFW working? Still seeing many sshd entries to log file I recently enabled the firewall on my Elementary OS system, using ufw.
Here is my sudo ufw status verbose:
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip

Then I only allow ports for ssh (22), printing (cups port), and my media server.
The problem is I am still seeing many sshd log entries in journalctl such as this:
Aug 30 12:07:08 elementaryos sshd[8225]: Invalid user yale from 125.43.68.83 port 63475
Aug 30 12:07:08 elementaryos sshd[8225]: Received disconnect from 125.43.68.83 port 63475:11: Bye Bye [preauth]
Aug 30 12:07:08 elementaryos sshd[8225]: Disconnected from invalid user yale 125.43.68.83 port 63475 [preauth]
Aug 30 12:11:31 elementaryos sshd[8327]: Invalid user rx from 49.234.116.13 port 53310
Aug 30 12:11:31 elementaryos sshd[8327]: Received disconnect from 49.234.116.13 port 53310:11: Bye Bye [preauth]
Aug 30 12:11:31 elementaryos sshd[8327]: Disconnected from invalid user rx 49.234.116.13 port 53310 [preauth]
Aug 30 12:24:42 elementaryos sshd[8627]: Invalid user sftp_user from 142.44.211.229 port 39952
Aug 30 12:24:43 elementaryos sshd[8627]: Received disconnect from 142.44.211.229 port 39952:11: Bye Bye [preauth]
Aug 30 12:24:43 elementaryos sshd[8627]: Disconnected from invalid user sftp_user 142.44.211.229 port 39952 [preauth]
Aug 30 12:31:56 elementaryos sshd[8789]: Invalid user chris from 128.199.154.237 port 42658
Aug 30 12:31:56 elementaryos sshd[8789]: Received disconnect from 128.199.154.237 port 42658:11: Bye Bye [preauth]
Aug 30 12:31:56 elementaryos sshd[8789]: Disconnected from invalid user chris 128.199.154.237 port 42658 [preauth]
Aug 30 12:40:44 elementaryos sshd[9270]: Invalid user admin from 139.59.14.210 port 51780
Aug 30 12:40:45 elementaryos sshd[9270]: Connection closed by invalid user admin 139.59.14.210 port 51780 [preauth]
Aug 30 12:43:31 elementaryos sshd[9630]: Invalid user test from 139.59.14.210 port 43548
Aug 30 12:43:31 elementaryos sshd[9630]: Connection closed by invalid user test 139.59.14.210 port 43548 [preauth]
Aug 30 12:46:10 elementaryos sshd[9690]: Connection closed by authenticating user root 139.59.14.210 port 35310 [preauth]
Aug 30 12:55:33 elementaryos sshd[11834]: Received disconnect from 186.225.255.116 port 20373:11: Bye Bye [preauth]
Aug 30 12:55:33 elementaryos sshd[11834]: Disconnected from authenticating user root 186.225.255.116 port 20373 [preauth]

These requests should be blocked by my firewall. What is the explanation for all these sshd log entries?


text:
Q: using something like group_concat on clickhouse I'm trying to get a result of

types
name

fruit
banana, apple, guaba, strawberry

from a table with database like
table: fruits

types
name

fruit
banana

fruit
apple

fruit
guaba

fruit
strawberry

I know with MySQL I can use group_concat to get the result I want by using
SELECT group_concat(name), types FROM fruits

I have done my research and people recommend me to use groupArray in clickhouse to obtain similar result but this is not what I want. Because when I use
SELECT groupArray(name), types FROM fruits GROUP BY types

it gives me result of

types
name

fruit
apple, banana, banana, strawberry,strawberry,strawberry, guaba,guaba,guaba,guaba

the order of groupArray is mixed up and I can't seem to find an answer to fix the order :(
is there any way in clickhouse where we can get array of results in order? and why are there duplicated results?
I can't use groupUniqArray because sometimes my result should be
banana, apple, guaba, strawberry, strawberry (if strawberry is there twice in DB)
how do I keep the duplicated data without having it multiplied in order???

*

*I have data of input_time and key so my table is something like

types
name
input_time
key

fruit
banana
01:01
01

fruit
apple
01:02
01

fruit
guaba
01:03
02

fruit
strawberry
01:04
03

fruit
strawberry
01:05
04

and forgetting about 'types', I want to get result of grouped names in DB saved order (input_time order) group by key. How should I change my query??
I've tried
SELECT groupArray(name), key FROM fruits GROUP BY key ORDER BY input_time
but it does not give me the result I want..

A: use order by in sub-query. The order in the array is the same as the order of rows at a previous stage of query pipeline
select types, arrayCompact(groupArray(name))  names, length(names) len from(
   select types, name from fruit order by types, input_time)
group by types

┌─types─┬─names───────────────────────────────────┬─len─┐
│ fruit │ ['banana','apple','guaba','strawberry'] │   4 │
└───────┴─────────────────────────────────────────┴─────┘

https://clickhouse.com/docs/en/sql-reference/functions/array-functions/#arraycompact
Removes consecutive duplicate elements from an array. The order of result values is determined by the order in the source array.


text:
Q: How to check if ANY php parameter exists in url I am making a forum that accesses threads based off the category in the URL using the GET method. I want to redirect to an error page if no parameters exist in the url, but I want this to be a generic piece of code that can be used around my whole site.
For example:
The url would normally contain the category id:
localhost/myforum/threads.php?categoryid=1

I want it so that when the url is:
localhost/myforum/threads.php

it is to redirect to an error page, and that this piece of code is usable all around the website

A: The most reliable way is to check if the URL contains a question mark:
if (false !== strpos($_SERVER['REQUEST_URI'], '?')) {
    // There is a query string (including cases when it's empty)
}

A: Try:
$gets = parse_url($url));
if($gets['query'] == "")
{
    echo "No GET variables";
}

A: Just:
if (empty(array_diff($_GET, ['']))) {
    header("Location: /path/to/error.php");
}

EDIT: Updated to remove empty values

A: You can use is_set to check if the parameter exists like this,
isset($_GET)


text:
Q: 2 arrays into 1, with lambda exp distinct I've got 2 object arrays that Im getting from the DB, some overlap, so I have to make a distinct func.
I tried to make a lambda expression , but I still got an overlapped objects.
this is my code:
ArtObject[] pinui = new ArtObject[root.Count - 1];
ArtObject[] c1=     new ArtObject[root2.Count - 1];

pinui = getArticlesArray(root2, pinui);
c1= getArticlesArray(root, c1);

art = new ArtObject[c1.Count()+pinui.Count()];

pinui.CopyTo(art, 0);
c1.CopyTo(art, pinui.Count());

art = art.Distinct().OrderByDescending(a => a.dateTosort).ToArray();

I guess something wrong with my last line, art = art.Distinct().OrderByDescending(a => a.dateTosort).ToArray(); .. I wonder what and how can I get only the distinct objects..?

A: Distinct will use Equals and GetHashCode to determine equal values. I suspect you haven't overridden these methods to indicate how you want equality to be checked.
Also note that your last part would be simpler as:
ArtObject[] art = pinui.Union(c1).OrderByDescending(a => a.dateTosort).ToArray();

a.Union(b) is equivalent to a.Concat(b).Distinct().
An alternative to overriding GetHashCode and Equals is to specify an IEqualityComparer<Person> to either Union or Distinct.
MoreLINQ makes this easier with a DistinctBy method:
var query = collection.DistinctBy(x => x.Description);

(There's no equivalent for Union yet, but we could easliy add one.)

A: Your code looks fine, although it could be shortened (no need to use CopyTo):
 var art = pinui.Union(c1).OrderByDescending(a => a.dateTosort).ToArray();

Union already removes duplicates like Distinct.
The reason why the objects are not detected as duplicates is probably because they are distinct. For example, by default,
 var obj1 = new ArtObject("Picasso");
 var obj2 = new ArtObject("Picasso");

are two distinct objects.
You can, however, provide a custom equality comparer to Distinct or Union, the linked MSDN page contains a nice example.

A: If you do distinct on one of fields, you can use GroupBy then get First:
pinui.Concat(c1).GroupBy(a => a.Description, (key, g) => g.First())
    .OrderByDescending(a => a.dateTosort).ToArray();


text:
Q: Sever returning 400 when body passed with GET I have an Express GET route to fetch all users. Whenever a req.body is present, the server is always responding with 400.
Obviously, I have body-parser and this behaviour is only experienced in the production k8s environment (working fine in localhost)
Is there any limitation to send req.body to GET routes? Express documentation doesn't say so

A: You need to set the content type --header "Content-Type: application/json"  in the GET request and it should work.
 curl --header "Content-Type: application/json"   --request GET  --data '{"username":"xyz","password":"xyz"}' https://example.com/posttest

and here is the nodejs snippet
app.get('/posttest', function(req, res){
  console.log("posttest call received")
  res.send(req.body);
});


text:
Q: Symfony Validate TimeType So I am using TimeType fields in my FormType and was wondering how the validation might work there.
To be more precise, I have two TimeTypes and I want to check that the second one is after the first one.
I've used the Validation constraint GreaterThan, which correctly validates my field. However I have 2 problems which come in my mind:

*

*should I also use LessThan on the first field?

*the validation message outputs that my field has to be greather than "01.01.1970 05:00" which is not the error message I expect (date should be removed) how do I achieve this? Also translations should work for that.

Thanks
No solution yet - anyone knows a fix?


text:
Q: Using find in Solaris 10 to search a single directory but not its subdirectories I'm trying to use find on Solaris 10 to list the contents of one directory, excluding subdirectories from the search. I tried a command based on the solution suggested by sdaau:
find /tmp -type d ! -perm -u+rx -prune -o -type f -name dsm\*

Unfortunately, in addition to returning the desired results, this still results in errors like these:
find: cannot read dir /tmp/hsperfdata_oracle4: Permission denied
find: cannot read dir /tmp/hsperfdata_jsweb: Permission denied

There are a couple of directories in /tmp to which the user executing find has neither read nor traverse (execute) authorization.
-bash-3.2$ ls -ld /tmp/hsp*
drwxr-x---   2 jsweb    other        117 Jan  5 13:00 /tmp/hsperfdata_jsweb
drwxr-x---   2 oracle4  dba4         117 Nov  5 19:51 /tmp/hsperfdata_oracle4
drwxr-xr-x   2 root     root         117 Jan 22 08:58 /tmp/hsperfdata_root

I need to find a way to eliminate these errors so that find does not end with a non-zero return code. What am I overlooking?

A: You can just discard those errors and ignore the exit status:
find /tmp -name dsm\* -type f 2> /dev/null || :

If you still want to keep find's stderr, to still be able to see errors other than failure to enter or list directories because of access permission restriction, you could try and use a syntax that detects those permission issues, but that's going to be tricky.
The directories you don't have access to depend on permission and ownership (user and group). You'd need something like:
export "PATH=$(getconf PATH):$PATH"
u=$(id -u) g=$(id -G | sed 's/ / -o -group /g'); IFS=" "
find /tmp -type d ! \( \
    -user "$u" -perm -u=rx -o \
    ! -user "$u" \( -group $g \) -perm -g=rx -o \
    ! -user "$u" ! \( -group $g \) -perm -o=rx \
  \) -prune -o -type f -name dsm\* -print

Having said that, in my tests, on Solaris 11, find will still complain about directories it can't read even if you've pruned them, and on Solaris 10, I can't even get it to do any action, let alone -prune on them.
So Solaris find seems to be beyond hope on that front. You could use perl's File::Find module instead.
Also note that the approach above only takes simple Unix permissions into consideration, not ACLs or other security restrictions.

A: In your examples, ! -perm -u+rx doesn't evaluate as true - owners still have those rights. You're supposed to use ! -perm -o+rx. So:
find /tmp -type d ! -perm -o+rx -prune -o -type f -name dsm\*

A: Not sure what you're trying to accomplish, but since you don't want sub-directories, why not just run a ls and pipe it to grep?  With maybe an awk or sort to meet your needs?

A: find /tmp -type d ! -perm -775 -prune -o -type f -name dsm\*


text:
Q: Physically measure the covariant and contravariant components of a vector? I'm just wondering if there is a way to physically measure the covariant and contravariant components of a vector without prior knowledge of the metric.
Suppose I have a speedometer of some sort to measure the speed relative to me, of some faraway slowly moving and non interacting dust cloud in some area with dark matter. Said speedometer would give me measurements of the vector field in contravariant form (or covariant, doesn't matter).
However as one can't yet observe anything about dark matter save it's gravitational effects, I am unable to write out the energy momentum tensor to derive the metric.
Simply by knowing the covariant and contravariant components of the vector field of the cloud, I could probably derive the metric and thus solve for the EM tensor and therefore derive the matter distribution and movements of said dark matter (I think?).
But from the measurements of my speedometer, I would only get covariant components of the vector field. Since I do not have knowledge of the metric itself, and as far as I am concerned the coordinates I am using may as well be Cartesian,or at least Minkowskian since it 'looks' flat, without the knowledge of the matter and momentum distribution of dark matter, how do I find the covariant components and therefore be able to derive a metric?
I'm sure there is a way to do so, else how do astronomers calculate the masses of black holes or the amount and distribution of the missing mass that is dark matter?

A: As a consequence of the equivalence principle, the metric is not observable at a point in general relativity. Only scalars formed from its second and higher derivatives are observable at a point. This means that there is no meaningful sense in which we could measure, or need to measure, both a contravariant vector and its covariant version. If we could measure them both, then we would be able to infer the metric from them.
There is not really any notion of finding an unknown metric in general relativity, although we often say it that was as shorthand for something that is mutually understood. What we're really finding is a metric over some region of space, up to an equivalence class based on an arbitrary smooth change of coordinates. The metric at one point doesn't need to be found. We can make it anything we like, as long as it has the correct signature.
The question seems to be written as if the Einstein field equations need to be expressed in a form where the stress-energy tensor is in covariant form. You can freely raise and lower indices on both sides of the EFE.


text:
Q: Angle to Mecca from current location with iPhone compass I have a question about the Qibla direction, I am building an iPhone application which will show both North direction and Qibla direction, I am showing the north direction with the help of CLLocationManager and updating it with CLHeading as newHeading.magneticHeading, And i am showing the Qibla direction with the following code
double A = MECCA_LONGITUDE - lon;
double b = 90.0 - lat;
double c = 90.0 - MECCA_LATITUDE;
NSLog(@"tan -1( sin(%f) / ( sin(%f) * cot(%f) - cos(%f) * cos(%f)))", A, b, c, b, A);
double qibAngle =  atan(sin(A) /( sin(b) * (1 / tan(c)) - cos(b) * cos(A) ));
NSLog(@"qib Angle- %f",qibAngle);
qibla.transform = CGAffineTransformMakeRotation(qibAngle * M_PI /180);

So, here i am getting the angle, but it does not update the angle when i rotate the device, Can anyone help me out, i know that i need to do some thing with heading , but i don't know what to do?

A: I'm probably going to lose points on this answer because I know absolutely nothing about ios, but, I believe atan returns a value in radians, and CGAffineTransformMakeRotation takes it's argument in radians as well , so the conversion qibAngle * M_PI /180 is not needed.
You might also want to re-title your post, since most people have no idea what Qibla is and wouldn't realize that it's about math and iOS.  I only looked because I've heard calculating the right direction to Mecca is kind of a neat math problem.

A: I assume the code you posted computes the angle between geographical north and the direction towards Mecca for the current location. All you need to do now is take into account the user's heading.
For example, suppose the user is located so Mecca is directly due West, and the user is facing directly due East. Since tan returns +/-90 degrees, the qibla angle would have to be -90  degrees. Now the adjustment should be obvious: you need to subtract 90 degrees from the qibla angle respective to geographical north (-90) to arrive at (-180) degrees, which is how much user needs to turn in order to face Mecca.
Simply put, you need to "undo" the user's deviation, and you do this by subtracting from the qibla angle the the user's heading, which is relative to geographical north.
With the maths out of the way, now you need to observe heading changes and recompute the qibla angle when the heading changes. Lastly, make sure to use the trueHeading property.


text:
Q: Why are Branch Target Buffers needed for non register jump instructions? For a MIPS 5 stage pipeline, the branch target is known by the decode stage because it can be easily extracted if the branch offset it is in the instruction and also you read the registers in the decode stage.
So then for an out of order pipeline, you obviously run into a problem with with instructions like 'jr', which might use a register that hasn't been calculated yet. For uses like this, there is clear use for a branch target buffer.
But for an instruction like 'beq', I see the necessity for a branch predictor, but not for the branch target because you already know the branch offset and of course you know the current program counter so you can easily come up with the branch destination.
Are register jumps the only instructions that use the branch target buffer or am I missing something?

A: The fetch stage needs prediction to know what block to fetch next.  Instruction cache has some latency but can be pipelined.  DRAM has even more latency, but can still have multiple outstanding requests (depending on the memory controller or outer levels of cache).  So the fetch stage needs block addresses multiple cycles ahead of the blocks that are currently arriving from memory/cache.
Decode doesn't happen until after fetch, so that's an extra stall cycle if you waited until decode to detect the existence of unconditional direct branches.
See What branch misprediction does the Branch Target Buffer detect? for more about this from an x86 perspective (where decode is expensive and takes multiple stages, so this is even more critical).
Also note that high-performance CPUs decode multiple instructions in parallel, and often have a queue between fetch and decode to absorb fetch bubbles.  If the fetch stage predicts there's a taken branch (conditional or unconditional, doesn't matter), it can queue up instructions from the branch target instead of instructions after the branch.

See also Slow jmp-instruction for an x86 benchmark of a giant sequence of jump to next-instruction.  (i.e. relative offset = 0).  It slows down when the sequence is long enough not to fit in the BTB.


text:
Q: How to align objects to centre of page? I have tried aligning the objects in my webpage with the following CSS but the objects were not positioned at the centre. What should I do?
left:50%;
margin-left:-25%;

A: Can you try this please? It works fine
Works on : Internet Explorer - Google Chrome - Safari - Mozilla

Hello my text is in the middle :-)

A: The objects parent element (their container) must be set to position:relative
The objects themselves should be set to position:absolute, left:50%, margin-left negative value in pixels which is half the value of the object.
Alternatively you could also try simply setting the parent element to have text-align:center and give the objects themselves "margin:0 auto;"


text:
Q: Trying to load only certain entities into a table view I have a data model with entity Customer. The Customer has attributes like name, address...etc. One of these attributes is a call back date. I want to load into the table only the Customers with call back date of today.  below is the code I have to check to see if the dates are equal and then to create the cell. The problem is when the dates are not equal and it skips the creation of the cell. How do I skip that specific customer and move to the next one?
if(date==date2 && month==month2 && year==year2)
    {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }

        NSString *string = [NSString stringWithFormat:@"%@ %@", cust.firstName, cust.lastName];
        cell.textLabel.text = string;
        return cell;
    }
return nil;

}

A: I'd take a different route altogether.
Rather than not showing anything in the cell, simply don't provided data for there to even be a cell. You mention that you're using models so I assume you're using core data?
If so, then change your predicate when you fetch your models to ignore all objects that don't meet your criteria. Then you can just show every object in your table as you know that there aren't any you don't want.
Alternatively, fetch everything (if perhaps you're not using core data) then apply a predicate to the array of data you're using and filter it out that way.


text:
Q: Help in CSS for lightning component to override standard CSS Im trying from a long time to remove the Cancel button at the bottom for modal , but when I do it, it is also removing Done button. I would like to retain the Done. Can you please let me know what wrong I am doing. Here is the code and screen shot. FileuploadPopUp.cmp , Quick action on Account with FileuploadPopUp.cmp in quickAction
<aura:component description="FileUploadPopUp" implements="force:hasRecordId,force:lightningQuickAction" >
    <aura:attribute name="next" type="boolean" default="false" />
    <aura:attribute name="current" type="boolean" default="true" />
    <aura:html tag="style">
        .slds-modal__container {
        min-width: 60vw;
        }
        .ui-widget{
            margin:0px !important;
        }
        .slds-modal__content {
             min-height: 5vw !important;
        }
    </aura:html>
    <aura:if isTrue="{!v.current}">
        <lightning:button label="Next" title="Next" onclick="{!c.NextHs }" />
    </aura:if>
    <aura:if isTrue="{!v.next}">
    <c:FileUploadStandardPopUp />
    </aura:if>
</aura:component>

({
    NextHs : function(component, event, helper) {
        component.set('v.next',true);
        component.set('v.current',false);
    }
})

FileUploadStandardPopUp.cmp

<aura:component >
    <aura:attribute name="POEID" type="string" default="0016g00000C5RPVAA3"/>
    <lightning:fileUpload  label="Upload Files"
                          name="fileUploader"
                          multiple="false"
                          recordId="{!v.POEID}"
                          onuploadfinished="{!c.handleUploadFinished}" />
</aura:component>

({
    handleUploadFinished : function(component, event, helper) {

    }
})

I tried in the above style block , but it remove both cancel and done buttons.
.uiButton--brand{
        display:none;
        }

A: Why not target some other class which is not common in both for example in your aura:html tag you can put this
<aura:html tag="style">
.cuf-publisherCancelButton{
        display:none;
        }
 </aura:html>

A: You should implement lightningQuickActionWithoutHeader to hide the cancel button
Example:
<aura:component description="FileUploadPopUp" implements="force:lightningQuickActionWithoutHeader, force:hasRecordId">

Modal Header

</aura:component>


text:
Q: Google form script not working I can't seem to get a form-triggered script to run right. To be precise, it runs, and I can do some things, but I can't access the form data that is supposed to be sent to the event handler function.
I've got a very simple script triggered by a Google Sheet form:
function OnFormSubmit(e)
{
  try {
    var timeStamp = e.namedValues["Timestamp"][0];
    MailApp.sendEmail(emailAddress, "SCRIPT ENTRY", timeStamp);
  } catch (x) {
    var message = x.toString() + "\n[" + Utilities.jsonStringify(e) + "]\n"
    MailApp.sendEmail(emailAddress, "SCRIPT ERROR", message);
    }
}

I've also got a very simple form with just one item. I've got the trigger set up. The form runs and adds a line to the spreadsheet. I get email, so the script is triggering. However I get the SCRIPT ERROR email. The message is:
TypeError: Cannot read property "Timestamp" from undefined.
[{"response":"FormResponse","authMode":"FULL"}]

The "Timestamp" does indeed exist in the Form Response sheet (as I believe it always will; Timestamp is an automatic entry).
It seems that OnFormSubmit() is not being passed the parameter I think it's supposed to get passed. But all the examples I see work like this.
Any help?

A: It seems that you are using a script in a form (as can be seen from the value in object e) and not from within a spreadsheet.
You should be using the forResponse class documented here, you'll see that methods are completely different, I'm not going to reproduce the doc here but for example the time stamp comes using getTimestamp().


text:
Q: Paypal Preapproval Start Date timezone? I'm setting up an application using Paypal Adaptive Payments.
I'm currently implementing the call to the Preapproval, and the specification says the StartDate can not be before today.
With that in mind... under which timezone are they validating this against?
The API SDK has this in the example:
$currDate = getdate();
$startDate = $currDate['year'].'-'.$currDate['mon'].'-'.$currDate['mday'];
$startDate = strtotime($startDate);
$startDate = date('Y-m-d', mktime(0,0,0,date('m',$startDate),date('d',$startDate),date('Y',$startDate)));
$endDate = add_date($startDate, 1);

However that date can be different based on the timezone of the server sending the request.
Anyone have any ideas on how to ensure no issues will occur?
Edit w/ Bounty:
As of December 15th, we have now run into this as an error. We are using UTC time, and once it turns a new day in UTC, payments start getting failures.
I am using the above code in the following place:
$preapprovalRequest->startingDate = $startDate;
$preapprovalRequest->endingDate = $endDate;

What do I need to make this work?
Edit 2:
Yes timezone is setup as UTC, we did this intentionally so that all time information in our database is stored without timezone.
Essentially I'm trying to figure out how to specify that the date I'm sending to Paypal is in UTC, not whatever timezone they happen to be in.
Edit 3:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_APPreapproval
There is the API, and it says the following

The startingDate and endingDate can be in eiter Zulu or GMT offset
  formats. as in the following respective examples:
  2010-09-10Z
  2010-09-10T17:24:03.874-07:00

Essentially I need the above code, to output something like that specifying I'm using UTC...

A: The api documentation says it uses GMT or Zulu time over the wire, and expects it to have a final 'Z' to indicate this (consistent with ISO 8601).

Additional Notes About the PreApproval API Operation

*

*Preapproval constraints are additive; thus, for example, if you specify a preapproval that allows payments only on Fridays and on the 13th day of the month, the preapproval would be valid only on Friday the 13th of months within the specified time period.

*The startingDate and endingDate can be in eiter Zulu or GMT offset formats. as in the following respective examples:

2010-09-10Z [NOTE: THIS IS ZULU]
2010-09-10T17:24:03.874-07:00 [NOTE: THIS IS GMT OFFSET]

The safest thing to use is probably this:
$startingDate = gmdate('Y-m-d\Z', $startingDateTimestamp);

However, you must make absolutely sure that your own server's time zone (and time!) is set correctly.  You may also need to set timezone separately in your PHP application using date_default_timezone_set().
Finally, there's another wrinkle--I do not know what SDK you are using. Possibly it tries to be clever and changes the date you pass in to something else. In that case you need to find out what date translation it does and what date it expects. (E.g., perhaps it expects a date in the system-local time, and it changes it to a UTC time.)  Assuming it doesn't alter what you supply, however, you should be able to use the code above.

A: PHP time functions are based on system time (http://us.php.net/manual/en/intro.datetime.php). Are you sure your system is setup to use UTC time? You can check with the following:
mpurcell@service1 ~/projects/config $ -> date
Thu Dec 15 23:29:09 UTC 2011

Notice the UTC in the response. If your system is setup to some other timezone, then that may be your problem, if you need to set your timezone to UTC, try:
$ rm -f /etc/localtime
$ ln -s /usr/share/zoneinfo/UTC /etc/localtime

Also be sure that your system time is corrected using Network Time Protocol:
$ ntpdate -b pool.ntp.org

-- Edit --
Based on your edits, looks like they are expecting the time in either Zulu (append Z) or GMT with offset (more complex), try this:
$preapprovalRequest->startingDate = $startDate . 'Z';
$preapprovalRequest->endingDate = $endDate . 'Z';


text:
Q: If S is a bounded set, then inf(S) and sup(s) belong to the closure of S My proof:
Since $\bar S = S\cup bdy(S)$ $\Rightarrow S\subset \bar{S}$
and since S is bounded
$\Rightarrow inf(S)$ and $sup(S)$ exist
Then is it safe to assume that since inf(S) and sup(S) exists, then inf(S) and sup(s) is already a subset of $\bar S$?

A: It isn't entirely safe. It's better to mention that $\inf(S)$, $\sup{S}$ are limit points of $S$, i.e. there exist sequences $S\supset(x_n)\longrightarrow\inf(S)$ and $S\supset(y_n)\longrightarrow\sup(S)$, and that the closure contains all limit points, which follows easily from any possible definition.
But it is not true in general that $\inf(S)$, $\sup(S)$ belong to $S$! Note e.g. $S=(0, 1)$.

A: The definition of $\sup(S)$ is the real number $M$ such that $x \leq M$ for all $x \in S$, and such that if $M'$ also satisfies this inequality, then $M' \geq M$.
So let $M = \sup(S)$, and for all $n \in \mathbb{N}$, let $\delta_n = \frac{1}{n}$.
Now, for each $n$, let $a_n \in S$ be such that $\left| M - a_n \right| < \delta_n$. This exists by the definition of $\sup$, for if we could not find such an $a_n$, then we would have that $x \leq M - \delta_n$ for all $x \in S$, contradicting that $M$ is the $\sup$.
Now, by construction, we have $a_n \in S$ for all $n$ and $a_n \rightarrow M$ as $n \rightarrow \infty$. So by definition of closure, $M \in \bar{S}$.
The proof for $\inf$ is similar.


text:
Q: Android Emulator Display Strangely [Virtualbox] I don't know what's the category of this problem.
But i only encountered this in several apps that runs under my emulator of Android 4.1.1 under VirtualBox.

Any clue, what should I do to resolve this problem?


text:
Q: subscribing two observables i.e. observable inside another observable HTTP I am new to angular. I am trying to post and get data at a time. I am using map and subscribing the observable while the outer observable is subscribed in component.

add(data) {
  return this.postModel(`pathHere`, data)
  .pipe(map((resp) => {
    if(resp.models){
      return this.getRoomById(resp.models.id).subscribe();
    }
  }));
    }

A: I guess you need to use flatMap instead of map as

add(data) {
  return this.postModel(`pathHere`, data)
  .pipe(flatMap((resp) => {
    if(resp.models){
      return this.getRoomById(resp.models.id);
    }
  }));
    }

A: add(data) {
    return this.postModel(`pathHere`, data)
        .pipe(
            switchMap((resp) => {
                if (resp.models) {
                    return this.getRoomById(resp.models.id);
                }
                  return of(resp.models);
            })
        );
}

You can use switchMap to emit another Observable.
As you used if statement for checking resp.models, you have to handle the case when resp.models is not truthy.


text:
Q: how to redirect to sub directory in htaccess without direct access to it I already asked this question but no answers.
I develop new forum So I put some files like index, login, signup and etc... in sub directory called webroot and i want to redirect all requests to webroot without direct access to it for example:
localhost/myforum [root project files] should access with no problems but
localhost/myforum/webroot redirect to 404
myforum/.htaccess
DirectoryIndex index.php

# No directory listings
IndexIgnore *

<IfModule mod_rewrite.c>
    RewriteEngine on

   # Uncomment the following line if your webserver's URL is not directly related to physical file paths.
   # Also uncomment it if you are on 1&1 hosting
   #RewriteBase /

    # Comment the following line if you have not a .well-known directory in the root folder.
    RewriteRule ^(\.well-known/.*)$ $1 [L]

    RewriteRule    ^$    webroot/    [L]
    RewriteRule    (.*) webroot/$1    [L]
</IfModule>

myforum/webroot/.htaccess
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

A: Have myforum/webroot/.htaccess as this code:
<IfModule mod_rewrite.c>
    RewriteEngine On

    # return 404 if accessed directly
    RewriteCond %{THE_REQUEST} /webroot/ [NC]
    RewriteRule ^ - [L,R=404]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>


text:
Q: Persisting data on the page on refresh I want to keep the data of the target ordered list before page refresh and then prepend it using jquery on document ready.
Here is my code

// if an refresh event is fired
window.onbeforeunload = function(event){
  //store the messages into sessionStorage
  sessionStorage.setItem('ol', jQuery('#messages'));
  return undefined;
};
$(document).ready(function(){
  if (sessionStorage.getItem('ol')) {
  // Restore the contents of the ol (message contents)
    var ol = sessionStorage.getItem('ol');
    jQuery('#messages').html(ol);
  }
});

      <form id="message-form" action="">
        <input type="text" name="message" placeholder="Message" autofocus autocomplete="off"/>
        <button>Send</button>
      </form>
      <button id="send-location"> Send location</button>

But the code is not working as expected after refreshing the result is
enter image description here
Although before refreshing it was
enter image description here

A: You need to use localStorage As data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
For sessionStorage, changes are only available per window (or tab in browsers like Chrome and Firefox). Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted.
More details on this link https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

A: Thanks @charlietfl     Here is what works for me

// if an refresh event is fired
window.onbeforeunload = function(event){
  //store the messages into sessionStorage
  sessionStorage.setItem('ol', jQuery('#messages').html());
  return undefined;
};
$(document).ready(function(){
  if (sessionStorage.getItem('ol')) {
  // Restore the contents of the ol (message contents)
    var ol = sessionStorage.getItem('ol');
    jQuery('#messages').html(ol);
  }
});


text:
Q: Files aren't showing up in windows bash I just set up bash for windows with the new windows update. After setting up a username and password and trying to navigate through my directories I find that there is nothing there. Does anyone know why this happened and how to fix it?

A: What do you mean by nothing is there? Do "cd /" and try "ls" here to see if there are files here. Your other drives are mounted in '/mnt/". In case nothing works, reinstall WSL. Run the following  in an elevated command prompt.
lxrun /uninstall /full
lxrun /install

And properly answer the questions.

A: By default, it puts you in your home directory.  There is nothing in it.
Type ls / to see if there are folders in the root.  I would bet there are.


text:
Q: Fill pandas DataFrame nans with index value I have a DataFrame which contains nan values. I would like to fill those nans with the index value. The actual use case is filling the nans with a string template containing the index value which you can answer as a bonus.
Given:
In [31]: df
Out[31]:
          0         1         2         3
0       NaN  0.069419       NaN       NaN
1  2.439000  1.943944  0.279904  0.755746
2  0.013795  1.189474  0.834894  2.202108
3  0.520385       NaN       NaN  1.451822
4  0.153863  0.957394       NaN  0.052726
5  1.274204       NaN       NaN  0.169636
6       NaN  1.031703       NaN  0.267850
7  0.419157       NaN       NaN  0.409045
8       NaN  1.526764  0.947936  0.442226
9       NaN       NaN       NaN  0.458331

and
In [35]: tmp
Out[35]: 'i=%(idx)s'

Output should be something like the following:
          0         1         2         3
0       i=0  0.069419       i=0       i=0
1  2.439000  1.943944  0.279904  0.755746
2  0.013795  1.189474  0.834894  2.202108
3  0.520385       i=3       i=3  1.451822
4  0.153863  0.957394       i=4  0.052726
5  1.274204       i=5       i=5  0.169636
6       i=6  1.031703       i=6  0.267850
7  0.419157       i=7       i=7  0.409045
8       i=8  1.526764  0.947936  0.442226
9       i=9       i=9       i=9  0.458331

Just trying to fill the nans with the index.
Tried
In [32]: df.fillna(df.index)

ValueError: invalid fill value with a <class 'pandas.core.index.Int64Index'>

Tried
In [33]: df.replace(np.nan, df.index)

TypeError: Invalid "to_replace" type: 'float'

Tried
In [41]: df.fillna(df.index.values)

ValueError: invalid fill value with a <type 'numpy.ndarray'>

Tried
In [53]: df1 = df.astype(object)

and repeating the above, received same errors.
Using pandas==0.17.1

A: Similar to @maxymoo solution using where but with pd.Series instead of lambda:
s = pd.Series(['i={}'.format(i) for i in df.index])

In [49]: df.where(df.notnull(), s, axis=0)
Out[49]:
          0         1         2         3
0       i=0  0.069419       i=0       i=0
1     2.439   1.94394  0.279904  0.755746
2  0.013795   1.18947  0.834894   2.20211
3  0.520385       i=3       i=3   1.45182
4  0.153863  0.957394       i=4  0.052726
5    1.2742       i=5       i=5  0.169636
6       i=6    1.0317       i=6   0.26785
7  0.419157       i=7       i=7  0.409045
8       i=8   1.52676  0.947936  0.442226
9       i=9       i=9       i=9  0.458331

Timing:
def f1():
    nan_strings = ["i={}".format(i) for i in df.index]
    df.apply(lambda c: c.where(c.notnull(), nan_strings))

def f2():
    s = pd.Series(['i={}s'.format(i) for i in df.index])
    df.where(df.notnull(), s, axis=0)

In [51]: %timeit f1()
100 loops, best of 3: 5.17 ms per loop

In [52]: %timeit f2()
1000 loops, best of 3: 1.34 ms per loop

A: You can use where to do your substitution (it's kind of like assignment with a  reversed mask), but you'll need to apply it column-by-column, I can't think of how to do it all at once:
In [1]: nan_strings = ["i={}".format(i) for i in df.index]

In [2]: df.apply(lambda c: c.where(c.notnull(), nan_strings))
Out[2]:
          0         1         2         3
0       i=0  0.069419       i=0       i=0
1     2.439   1.94394  0.279904  0.755746
2  0.013795   1.18947  0.834894   2.20211
3  0.520385       i=3       i=3   1.45182
4  0.153863  0.957394       i=4  0.052726
5    1.2742       i=5       i=5  0.169636
6       i=6    1.0317       i=6   0.26785
7  0.419157       i=7       i=7  0.409045
8       i=8   1.52676  0.947936  0.442226
9       i=9       i=9       i=9  0.458331

A: Ok, so what you are doing is going to cause problems. Firstly, your columns appear to be all float64. 'i=%(idx)s' is a string. So you will either have to convert all columns to object or you will have to fill float values for nan. That said, why don't you try this, and let me know if you get your answer:
df.fillna(df.index.values, inplace=True)

Since you say bonus, let's try to convert the columns to object type first:
fill_val = ['i={}'.format(i) for i in df.index.values]
df.astype('object', inplace=True)
df.fillna(fill_val, inplace=True)