Q:

Android List View Array Index Out Of Bounds Exception - No clues?

I have an app which loads a listview when opened, however I am getting an Array Index Out Of Bounds Exception, with no clues as to where the problem lies. It is trying to access index=-1 somewhere, but I have no idea where.
The app loads Homework information from a database, puts them into separate Homework objects in an ArrayList and loads it into the ListView from there. I really don't know where the exception is coming from, I have checked all my code. There is only 1 homework in the list, however the app refuses to open and force closes as soon as I try to open it. Here is the LogCat output
Thanks
LogCat output
01-11 16:38:43.644: E/AndroidRuntime(7267): FATAL EXCEPTION: main
01-11 16:38:43.644: E/AndroidRuntime(7267): java.lang.ArrayIndexOutOfBoundsException: length=29; index=-1
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.text.StaticLayout.calculateEllipsis(StaticLayout.java:738)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.text.StaticLayout.out(StaticLayout.java:702)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.text.StaticLayout.generate(StaticLayout.java:410)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.text.StaticLayout.<init>(StaticLayout.java:140)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.widget.TextView.makeSingleLayout(TextView.java:5888)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.widget.TextView.makeNewLayout(TextView.java:5745)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.widget.TextView.onMeasure(TextView.java:6102)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.View.measure(View.java:15513)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:645)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:425)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.View.measure(View.java:15513)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4827)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1052)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:590)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.View.measure(View.java:15513)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.widget.ListView.measureScrapChild(ListView.java:1183)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.widget.ListView.measureHeightOfChildren(ListView.java:1248)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.widget.ListView.onMeasure(ListView.java:1158)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.View.measure(View.java:15513)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4827)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.View.measure(View.java:15513)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4827)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.View.measure(View.java:15513)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.View.measure(View.java:15513)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4827)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.View.measure(View.java:15513)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.Choreographer.doCallbacks(Choreographer.java:562)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.Choreographer.doFrame(Choreographer.java:532)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.os.Handler.handleCallback(Handler.java:725)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.os.Looper.loop(Looper.java:137)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at android.app.ActivityThread.main(ActivityThread.java:5039)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at java.lang.reflect.Method.invokeNative(Native Method)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at java.lang.reflect.Method.invoke(Method.java:511)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-11 16:38:43.644: E/AndroidRuntime(7267):     at dalvik.system.NativeStart.main(Native Method)

Loading from DB
public ArrayList<HomeworkItem> getHomeworks() {
        String[] columns = new String[] { KEY_ROWID, KEY_TITLE, KEY_SUBJECT,
                KEY_DUE_DAY, KEY_DUE_MONTH, KEY_DUE_YEAR, KEY_NOTES,
                KEY_REMINDER_ONE, KEY_REMINDER_TWO };
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
                null, null);
        ArrayList<HomeworkItem> hwks = new ArrayList<HomeworkItem>();

        int id = c.getColumnIndex(KEY_ROWID);
        int iTitle = c.getColumnIndex(KEY_TITLE);
        int iSub = c.getColumnIndex(KEY_SUBJECT);
        int iDay = c.getColumnIndex(KEY_DUE_DAY);
        int iMonth = c.getColumnIndex(KEY_DUE_MONTH);
        int iYear = c.getColumnIndex(KEY_DUE_YEAR);
        int iNotes = c.getColumnIndex(KEY_NOTES);
        int iOne = c.getColumnIndex(KEY_REMINDER_ONE);
        int iTwo = c.getColumnIndex(KEY_REMINDER_TWO);

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            HomeworkItem h = new HomeworkItem();
            h.id = c.getInt(id);
            h.title = c.getString(iTitle);
            h.subject = c.getString(iSub);
            h.day = Integer.parseInt(c.getString(iDay));
            h.month = Integer.parseInt(c.getString(iMonth));
            h.year = Integer.parseInt(c.getString(iYear));
            h.notes = c.getString(iNotes);
            h.late = h.isLate();

            h.oneDayReminder = Boolean.parseBoolean(c.getString(iOne));
            h.twoDayReminder = Boolean.parseBoolean(c.getString(iTwo));
            hwks.add(h);
        }
        return hwks;
    }

ListView Adapter
public class MyAdapter extends BaseAdapter { // adapter for list

        public MyAdapter(Context c) {

        }

        public int getCount() {
            // TODO Auto-generated method stub
            Log.d("hwk", hwks.size()+" is the size");
            return hwks.size();
        }

        public Object getItem(int position) {
            // TODO Auto-generated method stub
            Log.d("hwk", position+" being accessed");
            return position;
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            Log.d("hwk", position+" being accessed");
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View v = convertView; // inflate the list
            TextView title, subject, dueDate, listLate;

            if (v == null) {
                LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.list, null);
                Log.d("hwk", "v inflated");
            }
            title = (TextView) v.findViewById(R.id.listTitle); // get the id's
                                                                // of fields
            subject = (TextView) v.findViewById(R.id.listSubject);
            dueDate = (TextView) v.findViewById(R.id.listDueDate);
            listLate = (TextView) v.findViewById(R.id.listLate);
            Log.d("hwk", "got views");

            title.setText(hwks.get(position).title);
            subject.setText(hwks.get(position).subject);
            String date = hwks.get(position).day + "/"
                    + (hwks.get(position).month + 1) + "/"
                    + hwks.get(position).year;
            dueDate.setText(date);
            Log.d("hwk", "some text set");

            if (hwks.get(position).late) { // set if they are late or not
                if (hwks.get(position).isToday()) {
                    listLate.setTextColor(Color.rgb(255, 165, 0));
                    listLate.setText("Due Today!");
                } else {
                    listLate.setTextColor(Color.RED);
                    listLate.setText("Late");
                }
            } else {
                listLate.setTextColor(Color.GREEN);
                listLate.setText("Ongoing");
            }
            Log.d("hwk", "returning v");
            return v;
        }

    }

EDIT: Also, the ListView works when I first add a Homework within the app, and it goes and refreshes the ListView and adds the Homework to it. I am totally reloading the main Activity when this happens, so it appears to be a problem opening it after the app has been closed once.
EDIT 2: I deleted the data from the app, added a new Homework and now I cannot recreate the problem.. What could have caused this?!
EDIT 3: PROBLEM DETECTED. It is to do with some of the text. I have worked out that when I set the 'title' to "Binomial Expansion" it recreated the error that I had before when the homework was also called "Binomial Expansion". Could it be to do with trying to put that String in the TextView and the text being too large?
I have extended the width of the TextView and it stopped the error. When I extended the text I got the issue again. It must be a problem with the text view overflowing. Are there any TextView properties I can set to stop this?

A:

This is caused by setting android:ellipsize="middle" (or start) on a TextView that does not have android:singleLine="true" on.
For example, the following crashes on this error:
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ellipsize="middle"
    android:maxLines="1"
    android:text="blahblahblahblahblahblahblahblahblahbla---go really long" />

But the following does not:
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ellipsize="middle"
    android:singleLine="true"
    android:text="blahblahblahblahblahblahblahblahblahbla---go really long" />

Reference: https://code.google.com/p/android/issues/detail?id=33868
Note: singleLine is a deprecated attribute but still works on Jelly Bean.


Q:

How to approach copying objects with smart pointers as class attributes?

From the boost library documentation I read this:

Conceptually, smart pointers are seen as owning the object pointed to,
  and thus responsible for deletion of the object when it is no longer
  needed.

I have a very simple problem: I want to use RAII for pointer attributes of a class that is Copyable and Assignable.
The copy and assignment operations should be deep: every object should have its own copy of the actual data. Also, RTTI needs to be available for the attributes (their type may also be determined at runtime).
Should I be searching for an implementation of a Copyable smart pointer (the data are small, so I don't need Copy on Write pointers), or do I delegate the copy operation to the copy constructors of my objects as shown in this answer?
Which smart pointer do I choose for simple RAII of a class that is copyable and assignable? (I'm thinking that the unique_ptr with delegated copy/assignment operations to the class copy constructor and assignment operator would make a proper choice, but I am not sure)
Here's a pseudocode for the problem using raw pointers, it's just a problem description, not a running C++ code:
// Operation interface
class ModelOperation
{
    public:
        virtual void operate = ();
};

// Implementation of an operation called Special
class SpecialModelOperation
:
    public ModelOperation
{
    private:
        // Private attributes are present here in a real implementation.

    public:

        // Implement operation
        void operate () {};
};

// All operations conform to ModelOperation interface
// These are possible operation names:
// class MoreSpecialOperation;
// class DifferentOperation;

// Concrete model with different operations
class MyModel
{
    private:
        ModelOperation* firstOperation_;
        ModelOperation* secondOperation_;

    public:

        MyModel()
            :
                firstOperation_(0),
                secondOperation_(0)
        {
            // Forgetting about run-time type definition from input files here.
            firstOperation_  = new MoreSpecialOperation();
            secondOperation_ = new DifferentOperation();
        }

        void operate()
        {
            firstOperation_->operate();
            secondOperation_->operate();
        }

        ~MyModel()
        {
            delete firstOperation_;
            firstOperation_ = 0;

            delete secondOperation_;
            secondOperation_ = 0;
        }
};

int main()
{

    MyModel modelOne;

    // Some internal scope
    {
        // I want modelTwo to have its own set of copied, not referenced
        // operations, and at the same time I need RAII to for the operations,
        // deleting them automatically as soon as it goes out of scope.
        // This saves me from writing destructors for different concrete models.
        MyModel modelTwo (modelOne);
    }

    return 0;
}

A:

If you accept some requirements on your types, this can be done without requiring implementing virtual clone functions for all types. The particular requirements are that the types have accessible copy constructors, which some would deem undesirable because of potential for accidental slicing. Proper use of friending may mitigate the drawbacks of that, though.
If such is acceptable one can go about this by erasing the derived types under an interface that provides copy functionality:
template <typename Base>
struct clonable {
    // virtual copy
    // this clone function will be generated via templates
    // no boilerplate is involved
    virtual std::unique_ptr<clonable<Base>> clone() const = 0;

    // expose the actual data
    virtual Base* get() = 0;
    virtual Base const* get() const = 0;

    // virtual destructor
    // note that this also obviates the need for a virtual destructor on Base
    // I would probably still make it virtual, though, just in case
    virtual ~clonable() = default;
};

This interface is implemented by a class templated on the most derived type, and thus knows how to make normal copies through the copy constructor.
template <typename Base, typename Derived>
struct clonable_holder : clonable<Base> {
    // I suppose other constructors could be provided
    // like a forwarding one for emplacing, but I am going for minimal here
    clonable_holder(Derived value)
    : storage(std::move(value)) {}

    // here we know the most derived type, so we can use the copy constructor
    // without risk of slicing
    std::unique_ptr<clonable<Base>> clone() const override {
        return std::unique_ptr<clonable<Base>>(new clonable_holder(storage));
    }

    Base* get() override { return &storage; }
    Base const* get() const override { return &storage; }

private:
    Derived storage;
};

This will generate virtual copy functions for us without extra boilerplate. Now we can build a smart pointer-like class on top of this (not quite a smart pointer because it does not give pointer semantics, but value semantics instead).
template <typename Base>
struct polymorphic_value {
    // this constructor captures the most derived type and erases it
    // this is a point where slicing may still occur
    // so making it explicit may be desirable
    // we could force constructions through a forwarding factory class for extra safety
    template <typename Derived>
    polymorphic_value(Derived value)
    : handle(new clonable_holder<Base, Derived>(std::move(value))) {
        static_assert(std::is_base_of<Base, Derived>::value,
            "value must be derived from Base");
    }

    // moving is free thanks to unique_ptr
    polymorphic_value(polymorphic_value&&) = default;
    polymorphic_value& operator=(polymorphic_value&&) = default;

    // copying uses our virtual interface
    polymorphic_value(polymorphic_value const& that)
    : handle(that.handle->clone()) {}
    polymorphic_value& operator=(polymorphic_value const& that) {
        handle = that.handle->clone();
        return *this;
    }

    // other useful constructors involve upcasting and so on

    // and then useful stuff for actually using the value
    Base* operator->() { return handle.get(); }
    Base const* operator->() const { return handle.get(); }
    // ...

private:
    std::unique_ptr<clonable<Base>> handle;
};

This is just a minimal interface, but it can easily be fleshed out from here to cover more usage scenarios.

A:

It's a bit late, but for future viewers: There's a ready-to-use implementation in my header-only library Aurora and its SmartPtr tutorial. With Aurora, it's trivial to implement deep-copy through smart pointers. The following code works for any copyable type T:
aurora::CopiedPtr<T> first(new T);
aurora::CopiedPtr<T> second = first; // deep copy

This makes it often unnecessary to implement The Big Three/Five if your classes have pointer members.


Q:

Vertical alignment of tikz circle in equation

I wish to insert a graphic in an equation, and have it horizontally centered.
For example, the circle in the following example should be in the center of the brackets, not sitting halfway above them.
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{equation}
  A + B \Big \langle \tikz \draw (0,0) circle (0.5cm); \Big \rangle
\end{equation}
\end{document}

How do I achieve this?
I'm aware of the hack here, but find this unsuitable. (It will be impractical for me to hack 50+ such diagrams by hand.)

A:

The standard way to center content in math is \vcenter which alignes a list of vertical material centered to the math axis (the invisible line the minus sign, the equal sign, fractions etc. are aligned):
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{equation}
  A + B \Big \langle \vcenter{\hbox{\tikz \draw (0,0) circle (0.5cm);}} \Big \rangle
\end{equation}
\end{document}

Output:

A:

It is still worth mentioning that baseline can help you in an efficient way: by defining a style vertical align that abbreviates the long baseline=... command.

\documentclass{article}
\usepackage{tikz}
\begin{document}
    \tikzset{
        vertical align/.style={
            baseline=-.5*(height("$+$")-depth("$+$"))
        }
    }
    \foreach\size in{\tiny,\footnotesize,\normalsize,\Large,\huge}{
        \size
        \begin{equation}
            A+B\Big\langle\tikz[vertical align]\draw circle(0.5);\Big\rangle^{
            A+B\Big\langle\tikz[vertical align]\draw circle(0.5);\Big\rangle^{
            A+B\Big\langle\tikz[vertical align]\draw circle(0.5);\Big\rangle}}
        \end{equation}
    }
    \end{document}

What can be done further is that you can apply style globally by saying
\tikzset{
    every picture/.style={vertical align}
}

For irrelevant pictures, you can cancel the effect by either grouping or saying [baseline=0pt] or just [baseline]. (Or you can define no vertical align/.style={baseline})

You can also encode the drawing of the circle in a .pic. For example
\tikzset{
    cir5/.pic={
        \draw circle(0.5);
    }
}

Together with the global setting of baseline, the code is now much simpler
    \begin{equation}
          A+B\Big\langle\tikz\pic{cir5};\Big\rangle
    \end{equation}

in contrast to
    \begin{equation}
        A+B\Big\langle\vcenter{\hbox{\tikz\draw circle(0.5);}}\Big\rangle
    \end{equation}

Of course one can do something like \def\vcentertikz#1{\vcenter{\hbox{\tikz{#1}}}}, just like one can do \def\tikzvcenterpic#1{\tikz[vcenter]{\pic{#1}}}. So as long as one does not need tricky baseline setting (such as baseline=(node.anchor)), both methods are interchangeable.

The following is the full code.
\documentclass{article}
\usepackage{tikz}
\begin{document}
    \tikzset{
        vertical align/.style={
            baseline=-.5*(height("$+$")-depth("$+$"))
        }
    }
    \foreach\size in{\tiny,\footnotesize,\normalsize,\Large,\huge}{
        \size
        \begin{equation}
            A+B\Big\langle\tikz[vertical align]\draw circle(0.5);\Big\rangle^{
            A+B\Big\langle\tikz[vertical align]\draw circle(0.5);\Big\rangle^{
            A+B\Big\langle\tikz[vertical align]\draw circle(0.5);\Big\rangle}}
        \end{equation}
    }

    \clearpage

    \tikzset{
        every picture/.style={vertical align}
    }
    \foreach\size in{\tiny,\footnotesize,\normalsize,\Large,\huge}{
        \size
        \begin{equation}
            A+B\Big\langle\tikz\draw circle(0.5);\Big\rangle^{
            A+B\Big\langle\tikz\draw circle(0.5);\Big\rangle^{
            A+B\Big\langle\tikz\draw circle(0.5);\Big\rangle}}
        \end{equation}
    }

    \clearpage

    \tikzset{
        cir5/.pic={
            \draw circle(0.5);
        }
    }
    \foreach\size in{\tiny,\footnotesize,\normalsize,\Large,\huge}{
        \size
        \begin{equation}
              A+B\Big\langle\tikz\pic{cir5};\Big\rangle
            ^{A+B\Big\langle\tikz\pic{cir5};\Big\rangle
            ^{A+B\Big\langle\tikz\pic{cir5};\Big\rangle}}
        \end{equation}
    }

    \clearpage

    \foreach\size in{\tiny,\footnotesize,\normalsize,\Large,\huge}{
        \size
        \begin{equation}
            A + B \Big \langle \vcenter{\hbox{\tikz \draw (0,0) circle (0.5cm);}} \Big \rangle^{
            A + B \Big \langle \vcenter{\hbox{\tikz \draw (0,0) circle (0.5cm);}} \Big \rangle^{
            A + B \Big \langle \vcenter{\hbox{\tikz \draw (0,0) circle (0.5cm);}} \Big \rangle}}
        \end{equation}
    }

\end{document}


Q:

How to see NaN values in Pandas with read_csv

I have a Data, and read this from txt File, but have a Problem.
import pandas as pd
df = pd.read_csv("df.txt", sep =";")
df.set_index(["Name", "Day"], inplace=True)

But i see not all indexes.
It looks like:

df.txt:

How can i see Peters day 2 and 3 (from image) with Nan values?

A:

reindex to the cartesian product of the level values:
import pandas as pd

df = df.reindex(pd.MultiIndex.from_product(df.index.levels))

#         Breakfest  Lunch  Dinner
#Anna  1        5.0   11.0     9.0
#      2        6.0    9.0    10.0
#      3        1.0   10.0     8.0
#      4        7.0   11.0    11.0
#Peter 1        6.0   12.0    10.0
#      2        NaN    NaN     NaN
#      3        NaN    NaN     NaN
#      4        4.0   10.0     9.0


Q:

Typescript array map with JSON.stringify produces error

In Typescript, this snippet:
[].map(JSON.stringify);

Is producing this error:

Argument of type '{ (value: any, replacer?: ((key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (value: any, replacer?: (string | number)[] | null | undefined, space?: string | ... 1 more ... | undefined): string; }' is not assignable to parameter of type '(value: never, index: number, array: never[]) => string'.
  Types of parameters 'replacer' and 'index' are incompatible.
    Type 'number' is not assignable to type '((key: string, value: any) => any) | undefined'.

Which I don't think it should.
To me this looks like a Typescript bug but before I file an issue in GitHub can you check if I'm doing something wrong?
Typescript version: 3.0.3

A:

The signature of JSON.stringify and the Array.mapare not compatible due to the second parameter:
interface JSON {
    /**
      * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
      * @param value A JavaScript value, usually an object or array, to be converted.
      * @param replacer A function that transforms the results.
      * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
      */
     stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string;
}

interface Array<U> {
    /**
      * Calls a defined callback function on each element of an array, and returns an array that contains the results.
      * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
      * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
      */
    map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
}

Here you can see that stringify does not match callbackfn because the second arguments do not match.
But you can absolutely do [].map(i => JSON.stringify(i))


Q:

Can my items be stolen if I leave them somewhere?

I haven't bought a house, but I have my own quarters as:

 the Archmage of Winterhold, after Savos Aren dies and I bring back the Staff of Magnus.

If I put some items in a chest by the bed, will they stay there permanently until I remove them, or could they be stolen by NPCs, disappear over time, etc.?
On a related note, I've noticed that items remain until I come back when dropped arbitrarily across landscape, buildings, and caves. Has anyone experienced a case where this is not true?

A:

Yes, they will be safe in those quarters.  I have all the unique artifact style weapons and armor I've acquired and am not using in that exact chest.  The earliest ones have been in there for at least 50 hours now.  The alchemical components and soul gems on the shelves in the room have restocked a few times, my collection of knick-knacks is fine.


Q:

Are the "What software do I use to make this video" questions off topic?

There seem to be a lot of "Here is a video , what software do I use to make an ad like this?" questions.
IMHO They're pretty pointless because yes, you can tell the asker that they can use After Effects, Nuke or Blender or whatever, but that's going to help them as much as telling someone that they should use oil paint if they want to paint like Botticelli.
Should questions like this be flagged:
https://video.stackexchange.com/questions/17110/what-softwares-and-techniques-can-be-used-to-make-videos-similar-to-byju-videos
https://video.stackexchange.com/questions/17115/waze-advertisement-video

A:

Personally, I'd be more inclined to close as duplicate.  The purpose of the question is answerable and the answer is still beneficial.  The asker has no clue how complicated it actually is, nor what techniques are used.  Letting them know what direction to look in as well as the difficulty of the task they are attempting to take on is useful information for them.
If they were asking how to do it, that would be too broad as it is far beyond the scope of what we can describe in an answer here, but asking what kind of software is used is fully answerable.  I see no harm in pointing them in the right direction and explaining the likely futility.
I do see a problem with taking on every single such question with the same basic answer as a different question.  We should certainly make an effort to close these as duplicates as much as possible.  Perhaps trying to write up a generalized case of some of these types of questions might be useful or trying to generalize the questions people ask if we don't already have a similar one we can direct them to.


Q:

How to make button like this in Android?

I am trying to implement button in android with following layout.How to make it??

i have already implemented button like this

i used following code to make
<TextView
              android:id="@+id/action_text_share"
                            style="@style/mediumTextSize"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="5dip"
                            android:gravity="center"
                            android:singleLine="false"
                            android:text="Share by Text"
                            android:padding="10dp"
                            android:layout_weight="1"
                             android:background="@drawable/white_broder_round_with_transparent_bg"
                            android:textColor="@color/blackColor" />

and have drawable like this
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/removeContactRedColor"/>
    <stroke android:width="2dip" android:color="@color/removeContactRedColor" />
    <corners
       android:radius="5dip"
        />
</shape>

A:

You can do like this in drawable, <item android:right="-2dp"> will remove stroke from the right end.
 <item android:right="-2dp">
    <shape>
        <corners android:radius="4dp"/>
        <solid android:color="@android:color/transparent" />
        <stroke
            android:width="1dp"
            android:color="@color/app_white" />
    </shape>
</item>


Q:

how to correctly make an iframe src equal whatever my variable equals?

I'm trying to make it so that whatever my variable, named "cover", equals in my html body, the iframe will use that as a source. I have it setup like this in my js file:
var cover = elem.attr('myFrame');

var cover = document.getElementById("myFrame");

$('.player .cover').attr('src','http://fakeurl.com/' + cover+'');

and then i have this in a part of the html body:

In the Moment of Inspiration

Inspiring Ideas into Motion

Peaceful Dawn

Photos and Memories

Soaring Spirit

The iframe shows the correct url (e.g. fakeurl.com) , but instead of adding what cover equals to the URL, it just enters in [object HTMLIFrameElement]
any ideas how to make it say (in example, http://fakeurl.com/fakeurl1.html).
this is a music playlist so im trying to make it so whenever a certain audio is plaing, the iframe will equal whatever cover= for that song

A:

Why are you using getElementById when you have jQuery?
var cover = $('#cover');

You're also declaring cover twice and I can't see an HTML element with the .player class, nor with a myFrame attribute. Your code essentially sets the string representation of the iframe reference as its own src attribute.
That aside, I think what you want to do is something like this:
$(function(){
    // When a playlist item is chosen
    $('#audioplayer li').click(function(){
        // Set the iframe src attribute to fakeurl.com
        // with the playlist item's cover attribute appended
        $('#myFrame').attr('src','http://fakeurl.com/'+$(this).attr('cover'));
    });
});

Check out this fiddle.
http://jsfiddle.net/3LGW8/


Q:

difference between tab ,space and blank in C

I came across the following code in Ritchie and kernighan C,for counting no. of words ..
#include<stdio.h>
#define IN 1
#define OUT 0
main()
{
    int c,n1,nw,nc,state;
    state = OUT;
    n1 =nw = nc = 0;
    while((c = getchar())!=EOF)
    {
        ++nc;
        if(c == '\n')
            ++n1;
        if(c == ' '||c == '\n' ||c == '\t')
            state = OUT;
        else if(state == OUT)
        {
            state = IN;
            ++nw;
        }
    }

    printf("%d %d %d\n",n1,nw,nc);
}

I guess here c == ' ' and c == '\t' are doing the same job.
Can someone explain me difference between tab, space, whitespace, blank, form feed and vertical tab?

A:

Spaces and tabs have different representations in ASCII. <space> is 0x20, while <tab> is 0x09. When the program checks the current character, both possibilities need to be tested.
Also worth noting is that the newline character they are using is '\n', which is "Line Feed", the conventional newline character for Unix/Linux/BSD. On Windows, the typical newline is represented by "\r\n" or CRLF ("Carriage Return" and "Line Feed").
I don't know that characters like "vertical tab" are used much. Many of those "control characters" go back to the days when they were used to give printers instructions on how to move the head.


Q:

How to create an image that is just shading and transparency?

In photoshop I created this image that is supposed to represent the folds of a curtain:

I, however, only want the shading aspect of this so that I can export that to a PNG and display it over any color on the Web.
So my question then is how do I get only the shading part of this image into a PNG?

A:

Open your Layers and Channels palettes;
Make your image a regular layer as opposed to a background layer. Easiest way is to double click the layer bar in the Layers palette;
In the Channels palette, make sure the RGB channels are visible, then click the leftmost icon on the bottom, 'Load channel as selection';
In the Layers palette, click the 'Add Layer Mask' icon (third from left, rectangle with a round hole in it);
With the Layer Mask still selected, choose Image > Adjustments > Invert, shortcut Control / Command + I;
Use Layer Styles to give the layer a black Color Overlay;
Create a coloured layer under your current layer to see the effect;
Tweak the effect using opacity, curves or other adjustments on both the actual layer and the mask;
Save as png-24. Don't forget to turn off your coloured background layer before you do.


Q:

Is there an API to query OData meta data

OData services expose their metadata:
http://www.odata.org/blog/queryable-odata-metadata
What's the best way to programmatically get the metadata. Of course, I could query using XDocument. Is there a better way?

A:

Currently there's no higher level API in .NET for consuming the $metadata response. XLinq is probably the best option.
You can use the site from the post to vote for such a feature in the future release: http://blogs.msdn.com/b/astoriateam/archive/2010/09/10/what-do-you-want-to-see-added-changed-in-wcf-data-services.aspx


Q:

WPF Best point to update a progress bar from BackgroundWorker

I have a task that takes a long time to execute. In order to inform the user of the progress, I have a progress bar that I update inside DoWork.
Can anybody tell me if this is the best way to update the progress bar? I have heard that there is a ReportProgress event handler but I am confused because I'm unsure of the purpose of ReportProgress.

A:

Since the Background worker works in a separate thread, you'll run into problems if you try to access UI objects.  Calling the ReportProgress method on the worker from inside the DoWork handler raises the ProgressChanged event.  That event should be handled in the UI thread so as to easily access the control.
        BackgroundWorker worker = new BackgroundWorker();
        worker.DoWork += DoWorkHandler;
        worker.WorkerReportsProgress = true;
        worker.ProgressChanged += (s, e) =>
            { myProgressBar.Value = e.ProgressPercentage; };

        worker.RunWorkerAsync();

...
    public void DoWorkHandler(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;

        while (working)
        {
            // Do Stuff

            worker.ReportProgress(progressPercentage);
        }
    }


Q:

How create a django model to filter by a foreign key field

I have two models which are connected by a foreign key.
Book
 isbn - this is a unique value

Order
 book_isbn - this should refer to Book's isbn above.

How to introduce Order model the isbn of the Book as a foreign key.
I want to query orders which have given isbn (i.e. filter Order objects where book_isbn = given_isbn ?

A:

You could do models like,
class Book(models.Model):
    isbn = models.CharField(unique=True, primary_key=True, max_length=5)
    #some fields....

class Order(models.Model):
    book = models.ForeignKey(Book, related_name='orders')
    #another fields..

Then you could do the queries like,
given_isbn = 'some_value'
items = Order.objects.filter(book=given_isbn)

Or for a given book instances,
orders = book.orders.all()

EDIT
Or you could remove primary_key=True from Book model isbn field and do
the queries like,
items = Order.objects.filter(book__isbn=given_isbn)

Then, Django provides an automatic incrementing primary key for each object instances.


Q:

Is there a way to find where all resources a PE executable uses?

In my case I'm trying to find the container that persists the configuration parameters, which may be registry, config files (.ini or proprietary) or anything else.
I've tried some resource grabbering tools that can extract resources like images/string out of the executable , but after go through them one by one I find the configuration file is not there.
Anyone has recommendation for this?

A:

There isn't going to be anything inside the image file if it's using the registry, .ini files, or .config files.
Your best bet is to use Process Monitor. It will show you every file and registry access a program uses. From there it may be possible to deduce which is the bit you're interested in.


Q:

Docvar indicator for corpus source when combining quanteda corpora

Is there any way to automatically create an indicator variable when combining quanteda corpora (using the plus operator) that can label which source corpus the document came from?  For instance, say you have two corpora, corpus1 and corpus2. You run the following:
corpus 3 <- corpus1 + corpus2
I'd like to find some way to create a new docvar that indicates which corpus each document in corpus3 comes from.  Any ideas?

A:

No automatic way at the moment, but the easiest method is to create a corpus identifier before adding the corpora.
library("quanteda")
# Loading required package: quanteda
# Package version: 1.3.4

c1 <- corpus(c(d11 = "C1 Doc one.", d12 = "C1 Doc two."))
c2 <- corpus(c(d21 = "C2 Doc one.", d22 = "C2 Doc two.", d23 = "C2 Doc 3"))

docvars(c1, "corpusid") <- 1
docvars(c2, "corpusid") <- 2

cc <- c1 + c2
summary(cc)
# Corpus consisting of 5 documents:
#
#     Text Types Tokens Sentences corpusid
# d11     4      4         1        1
# d12     4      4         1        1
# d21     4      4         1        2
# d22     4      4         1        2
# d23     3      3         1        2
#
# Source: Combination of corpuses c1 and c2
# Created: Sun Jul 29 09:37:28 2018
# Notes:


Q:

What's the Azure Table storage equivalent of the T-SQL delete table command?

I am developing an application that is logging test messages to Azure table storage. I want to clean up the table so that I can quickly see the most recent set of records. Querying in Azure Storage Explorer by specifying the Timestamp takes 30 seconds or so.
What's the fastest way to delete all records in a specific table in Table Storage?

A:

Delete the entire table.  You may have to wait a few minutes (depending on the size of the table being deleted) before you can recreate the table with the same name.


Q:

How to specify default header arguments in orgmode code blocks

I'm tying to set default header arguments to the code blocks within my org file, like this:
#+PROPERTY: header-args  :session *my_python_session*
#+PROPERTY: header-args  :results silent
#+PROPERTY: header-args  :tangle yes

My code blocks look like this:
#+BEGIN_SRC python
  import pandas as pd
#+END_SRC

However, when I call org-babel-tangle from this buffer, I get Tangled 0 code blocks from filename.org.  When I add :tangle yes to the end of the #+BEGIN_SRC line, the code block is exported when I call org-babel-tangle.
I would expect that I don't need to set :tangle yes on each code block.  What am I doing wrong?

A:

You should have every header argument in one line:
#+PROPERTY: header-args :session *my_python_session* :results silent :tangle yes

Having several #+PROPERTY lines is accepted, but not in the way you're trying to do it.
From the Org manual (7.1 Property syntax):

If you want to add to the value of an existing property, append a ‘+’
      to the property name.  The following results in the property ‘var’
      having the value “foo=1 bar=2”.
#+PROPERTY: var  foo=1
#+PROPERTY: var+ bar=2

So, since header-args is the property and :session, :results and :tangle are its values, it should be:
#+PROPERTY: header-args :session *my_python_session*
#+PROPERTY: header-args+ :results silent
#+PROPERTY: header-args+ :tangle yes

But it's easier to have just one line IMO.


Q:

UpdatePanel in webpart - title in browser tab disappears

I created a webpart with standard asp.net Update Panel. I noticed, that as soon as content of that UpdatePanel gets reloaded, title in browser tab disappears (or changes to http://servername, depending on a browser).
I don't understand that behavior. My question:

why does title disappear?
how can I avoid that? (programatically)

A:

I found this blog post:
http://softlanding.ca/blog/page-title-disappearing-after-ajax-postbacks, that explained, how to fix the problem (in short, placeholder in masterpage must be all single line).
Still, this seems a strange bug. Can someone explain, why this happens?


Q:

Launch screen is not working in iPad Device

in my project the Launch screen is not showing in Device(iPad Mini) but it showing in the simulator(iPad Retina,iPad Air,iPad 2), my deployment Target is 8.4 & my device also have 8.4 and i fixed the name LaunchImage.png(768*1024) & LaunchImage@2x.png(1536*2048) ,Device Orientation only for portrait & Device for ipad only help me

A:

1.You have to check iPad Version & if Your is iOS fix the Launch screen for iOS 6 or 7.
2.Check the Files are in correct .png Format or not.


Q:

How to install and run UNetbootin?

Strangely, but true, you cannot install from the the original site, or run it. So how to install and run UNetBootin?

A:

Install UNetbootin in Ubuntu
Using these few commands, downloading and running it will work.
sudo add-apt-repository ppa:gezakovacs/ppa
sudo apt-get update
sudo apt-get install unetbootin

Adding repository is necessary for updates and support for older versions of Ubuntu.

A:

Installing UNetbootin via PPA
sudo add-apt-repository ppa:gezakovacs/ppa
sudo apt-get update
sudo apt-get install unetbootin

Note:
In Ubuntu <18.04, we can directly install UNetbootin with single command
sudo apt-get install unetbootin

But UNetbootin is unavailable from the standard Ubuntu >= 18.04 repositories, due to requiring now-deprecated dependencies (e.g., gksu, kdesudo). The standard UNetbootin PPA, which explicitly supports Ubuntu >= 18.04, should be leveraged instead.

A:

As commented in your question by Web-E , you should just add the executable permission to the file downloaded from SourceForge, then you are able to run it (no installation needed, btw). I had the same problem and that comment gave me the solution, without the need to add the ppa.
If you don't want to use terminal, you can right-click the file unetbootin-linux-585, select "properties", go to "permissions" and then tick "allow execution of the file as a program" (or something like that, i don't have an english-language o.s.).
EDIT:
As suggested in the comment below, here's a little how-to about making a file executable:
To make the file executable via terminal (and we are here supposing you downloaded that file using a browser like Firefox or Opera), you only have to go to the folder where the file resides, right-click on the folder and select "Open terminal here". When you have the terminal shell, don't forget to run
ls -l

to make sure the file is really here, and to check permissions. You should see something like
-rw-r--r-- 1 name name 4478124 lug 11 15:28 unetbootin-linux-585

which means you have to add execution permissions on it. How you do it? Simply typing:
chmod +x unetbootin-linux-585

(don't forget to use Tab to autocomplete the long unetbootin name :P).
Now, checking again the file with ls -l should give the following result:
-rwxr-xr-x 1 name name 4478124 lug 11 15:28 unetbootin-linux-585

This means that the program became executable, so just type:
./unetbootin-linux-585

to run the application.
Hope everything is clear.


Q:

Install Xamarin on Visual Studio 2017

I have recently installed Visual Studio(VS) 2015 on my desktop on Windows operating system. I thought when I opened the VS 2015, I expected to see the Xamarin in it, but it does not. Then I installed the Xamarin again, and again and again, but still Xamarin does not show up in VS 2015.
I wonder what is wrong? what am I missing? By the way, I still have Visual Studio 2013 on my system.

A:

solution:
uninstall all the existing versions of visual studio ( 2010, 2012, 2013) except Visual Studio 2015 and then install Xamarin, and then you could able to see Xamarin on Visual Studio 2015.


Q:

Optimized method (for dataframes) to find time range overlaps with specified hour range

I'll preface this by saying I have a method that works, but I'm looking to optimize and learn some more Pythonic methods of working on DataFrames.
The premise is as follows: I have multiple "visits" by a user to a certain location. These ranges could be any datetime to any datetime, but occur in chronological order:
Jan 1, 15:00 to Jan 1, 18:35
Jan 3, 09:12 to Jan 5, 10:54
Jan 5, 11:00 to Jan 6, 19:48
etc.

Now, I have these arrival and departure times in a DataFrame, and I'm looking to determine the total amount of time that is spent by the user between the hours of 8pm - 8am every day.
My current method is to apply a custom function on each row:
def find_8am_8pm_hours(t1, t2):
    if t1 > t2:
        raise Exception('t1 must be before t2')
    total = dt.timedelta(minutes=0)
    while t1 < t2:
        t1 += dt.timedelta(minutes=1)
        if (t1.time() < dt.time(8, 0)) or (t1.time() > dt.time(20, 0)):
            total += dt.timedelta(minutes=1)
    return total

and apply this on the DataFrame with:
df['Time Spent 8am-8pm'] = df.apply(lambda row: find_8am_8pm_hours(row['Arrival Time'], row['Departure Time']), axis=1)

I originally wrote the function with granularity at seconds, but it actually took some time to run on even very small data sets (a few seconds run time for a data set with only ~20 rows). Once I changed the approximation to minutes, the small data sets ran very quickly, but I imagine that with large data sets the algorithm would take a long time.
I know the while loop is the main culprit, but I couldn't think of any method that was more elegant. I had also considered if/else statements to handle specific cases of how times overlapped, but to handle 24+hr ranges, there would be 20 or more different types of cases to handle.

A:

Let me help you sort out some logic in your problems, the implementation part should be simple, either in Python/Pandas, or another programming language.
See the following diagram, I divided the window into 6 zones by 8AM and 8PM on 1-2 consecutive days(depends on the adjusted arrival-time and departure-time which I will discuss below):
            +---day1--+---day2--+
            |   z1    |   z4    |
            +---------+---------+<-- 8AM (a8)
            |   z2    |   z5    |
(p8) 8PM -->+---------+---------+
            |   z3    |   z6    |
            +---------+---------+

First we calculate the delta_in_days between two timestamps t1 and t2,
each individual delta day will get you extra 12 hours into the final total.
Adding up the delta_in_days to the arrival-time, so that we can focus on a window which is within 1 day (24 hours) frame. Assume ts is the adjusted arrival-time and te is the departure-time, (Note: I originally defined them as start-time and end-time, thus named them ts and te) then

ts = t1 + delta_in_days
te = t2

Also set:

p8 the same day as ts but at 8PM
a8 the same day as te but at 8AM

Below list the possible cases with pseudo code:
Case-1:
ts and te in the same day - basically in day2 and p8 > a8
if both in the same zone: z4(te < a8) or z6(ts > p8):
    total = te - ts
else:
    total = max(0, te - p8) + max(0, a8 - ts)

Case-2:
ts, te in different days, if te in z6, then ts must be in z3. Remember, after the adjusted arrival-time, ts and te must be within the 24-hour window.
if te > p8 + 1day:
    total = (te - p8 - 1day) + (a8 - ts)

Case-3:
ts, te in different days, if ts in z1, then te must be in z4
if ts < a8 - 1day
    total = (a8 - 1day - ts) + (te - p8)

Case-4:
ts in [z2, z3] while te in [z4, z5]
total = min(a8, te) - max(p8, ts)

Code in Python:
import pandas as pd
from io import StringIO

str="""Jan 1, 15:00 to Jan 1, 18:35
Jan 3, 09:12 to Jan 5, 10:54
Jan 5, 21:00 to Jan 6, 23:48
Jan 5, 23:00 to Jan 6, 20:48
Jan 5, 03:00 to Jan 6, 02:48
Jan 5, 10:00 to Jan 6, 05:48
Jan 5, 21:00 to Jan 6, 10:48
"""

df = pd.read_table(StringIO(str)
     , sep='\s*to\s*'
     , engine='python'
     , names=['t1','t2']
)

for field in ['t1', 't2']:
    df[field] = pd.to_datetime(df[field], format="%b %d, %H:%M")

delta_1_day = pd.Timedelta('1 days')
# add 12 hours for each delta_1_day
ns_spent_in_1_day = int(delta_1_day.value*12/24)

# the total time is counted in nano seconds
def count_off_hour_in_ns(x):
    t1 = x['t1']
    t2 = x['t2']

    # number of days from t1 to t2
    delta_days = (t2 - t1).days
    if delta_days <= 0:
        return 0

    # add delta_days to start-time so ts and te in 1-day window
    # define the start-time(ts) and end-time(te) of the window
    ts = t1 + pd.Timedelta('{} days'.format(delta_days))
    te = t2

    # 8PM the same day as ts
    p8 = ts.replace(hour=20, minute=0, second=0)

    # 8AM the same day as te
    a8 = te.replace(hour=8, minute=0, second=0)

    # Case-1: te and ts on the same day
    if p8 > a8:
        if te < a8 or ts > p8:
            total = (te - ts).value
        else:
            total = max(0, (te - p8).value) + max(0, (a8 - ts).value)
    # Below ts and te all in different days
    # Case-2: te in z6
    elif te > p8 + delta_1_day:
        total = (te - p8 - delta_1_day + a8 - ts).value
    # Case-3: ts in z1
    elif ts < a8 - delta_1_day:
        total = (a8 - delta_1_day - ts + te - p8).value
    # Case-4: other cases
    else:
        total = (min(te, a8) - max(ts, p8)).value

    return total + delta_days * ns_spent_in_1_day

df['total'] = df.apply(count_off_hour_in_ns, axis=1)

print(df)

                   t1                  t2           total
0 1900-01-01 15:00:00 1900-01-01 18:35:00               0
1 1900-01-03 09:12:00 1900-01-05 10:54:00  86400000000000
2 1900-01-05 21:00:00 1900-01-06 23:48:00  53280000000000
3 1900-01-05 23:00:00 1900-01-06 20:48:00  35280000000000
4 1900-01-05 03:00:00 1900-01-06 02:48:00  42480000000000
5 1900-01-05 10:00:00 1900-01-06 05:48:00  35280000000000
6 1900-01-05 21:00:00 1900-01-06 10:48:00  39600000000000

Let me know if this works.


Q:

Should I Use Native Generic PHP or a Framework

I'm working with a team i just met.
I've been using the normal native generic php for coding up until now,
and built several webapps with it.
But a team member suggests we switch to using a framework for development.
I personally prefer going the normal way, using native generic PHP codes,
but he Suggests we use a framework.
I learnt Code Igniter has problem with loading images,
and this is one problem with some frameworks, they have some difficulties you just have to go with, unlike writing native PHP Codes.
I have a large archive of PHP Codes, that does the work of what some Framework does,
i can use this and implement it in the WebApp.
Is it better to go with a Framework or Go Native & Generic PHP.
Another thing is that, this is a web app for mobile devices, which me and the team are developing for a company, and there will be need for maintenance in the nearest future, if we are not available for the maintenance.
Our codes has to be very simple, not too ambiguous and self explanatory, and with comments too, for the future developer. Which is why i'm thinking we write out our own codes, and make it very Simple in the best possible way.

A:

This article gives an overview of some reasons that you might want to use a framework. To me it sounds like you've built up your own custom framework.
Points like less code for faster development and neat and tidy code/files are good points to consider when starting from scratch.
The Job oppertunities point is one to consider for yourself and your personal development.  It's also work considering the inverse of this which is your going to appear a more desirable place to work when/if you attempt to hire on more staff.  The staff you hire will also be productive faster if they can quickly recognise the patterns in the code.
Performance and security are always good things to think about as well.
It's also worth considering if your coworker is politely trying to say that they are finding the current code base difficult to work with and would like some more predictable structure.
In conclusion my opinion would be yes use a framework, it'll make things easier in the long run.

A:

Something to add on to @Klee points, on a team member's point of view it is much better that everyone is working on the same page with a known documented framework, which might not be the case with your own archive PHP codes.
Also you might want to start converting some of your archive codes to use-able modular libraries so you/your team can readily extend the framework if similar functions are not provided.

A:

A best solution for your question is to decide with your team members about this matter and which is best using a framework or Native generic programming .I suggest you to develop your own framework which contains all features your team want.
There are plenty of tutorials available i internet , see a tutsplus tutorial on php framework development :-
Php5 framework development


Q:

Opposing viewpoints are needed if you disagree with a closure

As I was doing my daily browsing today, I noticed that one of our questions had been reopened.  Normally, this would be a cause for celebration, for we have improved a question
to be acceptable to our standards.
Unfortunately, in this case, the question is still completely unacceptable.  It was closed, and on the brink of deletion.  I even waited until the question had gotten the closed text before casting my delete vote.  When the question was originally closed, a comment was left to inform the user of his options to get it reopened.
The resulting Meta was created, and I took responsibility for expressing my view on why the question was not acceptable.  I even spent a good chunk of time trying to help the user reword it into something we could keep.  Unfortunately, it was not to be.
I couldn't help but notice that there's no dissenting viewpoint on that Meta question.  None at all.  That doesn't strike me as good form. A question got closed, gets a Meta, an answer justifying the close and enough support to merit at least minor community consensus.  And yet, we have users casting votes against that consensus, without providing a viewpoint.
This isn't right.  If a Meta's been made, and you disagree with the actions taken, there needs to be a dissenting viewpoint on it before you go casting that reopen vote.  Tell us your reasons, and let the community judge its merits.  Once the dust settles, we can take action on whatever viewpoint the community deemed most worthy.  But casting a vote without providing your input just makes more work for those of us trying to keep the site neat and tidy.  You're actively working against site policy when you do that.
In the end, five more people are needed to close the question again, and now those votes will be nullified.  All it could have taken was a single dissenting point of view on the existing Meta.  Would your post have gotten downvoted?  I don't know; it would depend on how people agree with your points.  Who knows?  Making a case for a question you feel should be reopened can maybe garner enough support to ensure it does.  But that case needs to be made, first.
Yeah, Meta's a bit of a bloodbath sometimes.  Downvotes don't matter, though; no rep is lost, and all that will happen is a spirited exchange of ideas and opinions.  But we need those dissenting opinions.  Not only does it give us an idea of how parts of the community feel about things, but it's a hell of a lot more productive than requesting a meta and then being conspicuously absent once it DOES get made.  And it's also needed if you feel the site is moving in a direction you don't like.
Give us your input.  We might not agree with it, but we can certainly listen, at least.

So, in essence:

Closed question gets Meta, no dissenting viewpoint, no support for reopening, cast vote for reopen anyways = bad.
Closed question gets Meta, dissenting viewpoint, consensus does not agree with reopen, cast vote for reopen anyways = ehh.  Respect from me for providing your side, at least.
Closed question gets Meta, dissenting viewpoint, no support for reopening, no vote cast = good.

A:

In the end, it's not the Metas that count, it's the votes. Metas are optional and not really enforceable when it's a specific question rather than a matter of adopting a site-wide policy.
This is good. This is the site functioning as intended. We're not supposed to have a lengthy process of conversations and arguments to sort the site content into good questions, bad questions, valid and invalid questions. The entire point of the very existence of the Stack platform is to avoid lengthy discussions. Instead we vote: the sum of the votes, over an appropriately-long timescale, determines these thing for us independently of individual opinions.
We don't have to have a side-band consensus-determination social system of arguments, when we already have an automatic consensus-determination system coded right into the site. We shouldn't have a side-band system. Creating a side-band for deciding whether close votes should be cast or whether the votes are "valid" would completely undermine the value and function of the site.
It sucks when one's own opinion appears to have support, and then the votes say otherwise. Thems the breaks.
On the other hand, votes keep happening, and that's also part of the expected process. This question will probably simply get closed again. Eventually, equilibrium will be reached and it will stay either open or closed.
Meta is for discussion. That meta was for explaining the problems with the question, in an attempt to help the asker fix it. In the end we failed to fix the question. At least, in our opinion we failed to fix the question. Our opinion, no matter how well argued, does not earn us extra votes though, and it shouldn't. Now it's up to other citizens to take responsibility for judging that question. Our job is done.

Edit: As of 1 hour after this meta question was posted, the post had been reclosed. As of 15 hours after this meta question was posted, the question had been deleted. Other people can take care of the site too.
A lesson I brought here from my time editing and adminning on Wikipedia is relevant and useful here and now:
Don't Panic

It's easy to get caught up in an emotionally fired up argument over something that is so important that it must be fixed immediately. [...]
Remember, there are few things on [Arqade] that won't fix themselves, either because someone else sees it or because it's not actually a big deal.

We have lots of volunteers. If something is actually important, it will get taken care of.


Q:

Changing body background color with angularjs

I want to be able to change the background color of  depending on what the current path is.
I tried doing it by checking $location.path() whenever the path was changed and then using the ng-style directive to change the background color but this seems like a hack (and didn't work).
What would be a more decoupled way to achieve this?
Here's the code I wrote if anyone wants to see it.
app.controller('backgroundCtrl', ['$rootScope', '$scope', '$route', '$location', function($rootScope, $scope, $route, $location){
  $rootScope.$on('$routeChangeStart', function(){

    if ($location.path() == '/'){
      $scope.backgroundStyle = {background: '#ffffff'};
    } else {
      $scope.backgroundStyle = {background: '#000000'};
    }

  });
}]);

A:

To decouple such a dynamic change in style, data, content and etc., it is often practical to create another angular module that contains an interface(Custom Provider) that can give you access to these changes before and after the configuration level. Here is a plunker to provide a view of what I'll be discussing below.
For this answer, I have created a small module(route-data.js) with a provider, RouteData, which exposes
two function configurations:
applyConfig() - assigns settings to be accessed in the RouteData service.
hookToRootScope() - hooks the RouteData service in the $rootScope hence making it available to all child scopes to be created and the entire application.
The RouteData provider has a RouteData() service that provides access to methods which sets and gets RouteData settings that will be provided in the $routeProvider configuration.
(If you're not familiar with providers and services, read more about it here)
(If you're not familiar with the config() and run() methods, you can read more in here)
route-data.js
angular.module('RouteData', []).

provider('RouteData', function () {
  var settings = {};
  var hookToRootScope = false;

  this.applyConfig = function(newSettings) {
    settings = newSettings;
  };

  this.hookToRootScope = function(enableRootScopeHook) {
    hookToRootScope = enableRootScopeHook;
  };

  function RouteData() {

    this.set = function(index, value) {
      settings[index] = value;
    };

    this.get = function(index) {
      if(settings.hasOwnProperty(index)) {
        return settings[index];
      } else {
        console.log('RouteData: Attempt to access a propery that has not been set');
      }
    };

    this.isHookedToRootSope = function() {
      return hookToRootScope;
    };
  }

  this.$get = function() {
      return new RouteData();
  };
}).

run(['$location', '$rootScope', 'RouteData', function($location, $rootScope, RouteData) {
  if(RouteData.isHookedToRootSope()) {
    $rootScope.RouteData = RouteData;
  }

  $rootScope.$on('$routeChangeStart', function(event, current, previous) {
    var route = current.$$route;
    if(typeof(route) !== 'undefined' && typeof(route['RouteData']) !== 'undefined') {
      var data = route['RouteData'];
      for(var index in data)
        RouteData.set(index, data[index]);
    }
  });
}]);

The script below shows how to use the RouteData Module above via injecting the RouteDataProvider in the configuration level and apply default configurations such as the bodyStyle via RouteDataProvider.applyConfig(), you may also add more settings before the application is fully running. Hook it up in the $rootScope by setting RouteDataProvider.hookToRootScope() to true. Lastly, appending data, RouteData e.g.
RouteData: {
      bodyStyle: {
        'background-color': 'green'
      }
    }

to be sent in by the $routeProvider and processed by the run() method defined in the RouteData module which initializes the settings for the RouteData services to be accessed in the application.
script.js
angular.module('app', ['ngRoute', 'RouteData']).

config(['$routeProvider', 'RouteDataProvider', function($routeProvider, RouteDataProvider) {
  RouteDataProvider.applyConfig({
    bodyStyle: {
      'background-color': 'white'
    }
  });

  RouteDataProvider.hookToRootScope(true);

  $routeProvider.when('/landing', {
    RouteData: {
      bodyStyle: {
        'background-color': 'green'
      }
    },
    templateUrl: 'landing.html',
    controller: 'LandingController'
  }).when('/login', {
    RouteData: {
     bodyStyle: {
         'background-color': 'gray',
         padding: '10px',
         border: '5px solid black',
         'border-radius': '1px solid black'
     }
    },
    templateUrl: 'login.html',
    controller: 'LoginController'
  }).otherwise({
    redirectTo: '/landing'
  });

}]).

controller('LoginController', ['$scope', function($scope) {

}]).

controller('LandingController', ['$scope', function($scope) {

}]);

So the final piece of code to be added in your index page or any other page would be something like this.
A portion of index.html

    Landing |
    Login

A:

One way to style the body is to add ng-view as a body attribute, then use ng-class or ng-style (I did not use any other option to date).
For example:
<!doctype html>

    <title>My Site</title>

In this example, the login class is applied to the body only when loginBody is a true value in the current scope, set in a login controller.
This is much less flexible than the approach offered by @ryeballar. It may just be enough in some cases.


Q:

Can someone be compelled to prove they are complying with a contract? (If contract doesn't stipulate such proving)

I serve on an HOA board, and a fellow board-member believes we can compel someone to prove they're not violating a rule, and punish them if they are violating it OR IF THEY REFUSE TO PROVE they aren't.
The rule in this example is "no inoperable vehicle in the driveway".  We haven't seen the car move.  But we don't have 24x7 surveillance on that driveway either.  Even if it's not moving, that doesn't mean it's not capable of moving (inoperABLE).
Fellow board-member believes it's inoperable and wants to give 7 days to move it.
Our bylaws never stated a 7 days limit, nor do they have any language requiring homeowners to testify against themselves or provide evidence to their defense.
Fellow board-member's argument is that it's inherent to any contract that both parties have to prove they're in compliance.  I don't know where she got that, and she refuses to cite any sources.  The state is Kansas, USA if that is relevant.
I'm not looking for advice on the car.  I'm asking about the broader legal argument of having to defend one's self.  Is not the burden of proving the violation on the accuser?
I feel it is at the very least reckless to go accusing someone if we don't have any evidence of an actual violation.
I'd very much appreciate citation of sources in the answer that I can present at next board meeting to have a better informed discussion.

A:

Can someone be compelled to prove they are complying with a contract?

In this context, yes, since its apparent breach is evident. The other answer rightly explains the notion of preponderance of evidence, which pertains to the procedural aspect. Here, I will mainly address the substantive standpoint as per the situation you describe.
The HOA rule most likely is intended to serve one or more purposes, such as preserving the prestige of the neighborhood, and to avoid safety hazards. The prolonged presence of an abandoned vehicle --just like any piece of junk--- tends to contravene those purposes.
Regardless of the vehicle's true state, the effect of its apparent abandonment is visibly detrimental to the neighborhood, and it frustrates the ultimate purposes of the HOA rule: to preserve safety conditions in the neighborhood as well as the value of the properties.
Also, the presumption that an abandoned vehicle is inoperable seems reasonable. The most straight-forward way to disprove the board's allegations of inoperability is to actually move the vehicle at least once in a while. Accordingly, the owner's inexplicable reluctance to take that simple step reinforces the supported suspicion that the vehicle is indeed inoperable, and thus in breach of the HOA rule.


Q:

Can a service be started by normal user on Windows?

I have a service application created with Delphi, and managed to install it from another Delphi application using elevated privileges.
The service is set to log on as the Local System account (which is default when creating a service application in Delphi).
I have another Delphi application in which an ordinary user is supposed to be able to start or stop the above service.
My question is: Is this allowed by Windows? When I try to start the service using code in Delphi, it just fails with 'Code 5. Access is denied.' How can I prevent this error from occurring? I want to be able to have the normal user running the application (not in Administrator mode and thus not with elevated privileges) to start / stop the service. Is it possible and if so how? Below is my code:
function ServiceStart(sMachine, sService: string): boolean;
var
  schm, schs: SC_Handle;
  ss: TServiceStatus;
  psTemp: PChar;
  dwChkP: DWord; // check point
begin
  ss.dwCurrentState := 0;
  // connect to the service control manager
  schm := OpenSCManager(PChar(sMachine), nil, SC_MANAGER_CONNECT);
  // if successful...
  if (schm <> 0) then
  begin
    // open a handle to the specified service
    // we want to start the service and query service
    // status
    schs := OpenService(schm, PChar(sService), SERVICE_START  or SERVICE_QUERY_STATUS);
    // if successful...
    if (schs <> 0) then
    begin
      psTemp := nil;
      if (StartService(schs, 0, psTemp)) then
      begin
        // check status
        if (QueryServiceStatus(schs, ss)) then
        begin
          while (SERVICE_RUNNING <> ss.dwCurrentState) do
          begin
            // dwCheckPoint contains a value that the
            // service increments periodically to
            // report its progress during a
            // lengthy operation. Save current value
            dwChkP := ss.dwCheckPoint;
            // wait a bit before checking status again
            // dwWaitHint is the estimated amount of
            // time the calling program should wait
            // before calling QueryServiceStatus()
            // again. Idle events should be
            // handled here...
            Sleep(ss.dwWaitHint);
            if not QueryServiceStatus(schs, ss) then
            begin
              // couldn't check status break from the
              // loop
              break;
            end;

            if ss.dwCheckPoint < dwChkP then
            begin
              // QueryServiceStatus didn't increment
              // dwCheckPoint as it should have.
              // Avoid an infinite loop by breaking
              break;
            end;
          end;
        end;
      end
      else
      begin

        if MessageDlg('Start Service failed. Do you want remove it?',
          mtWarning, [mbYes, mbNo], 0) = mrYes then
        begin
          InstallUninstallService(1);
        end;

      end;

      // close service handle
      CloseServiceHandle(schs);
    end else RaiseLastOSError;
    // close service control manager handle
    CloseServiceHandle(schm);
  end;
  // Return TRUE if the service status is running
  Result := SERVICE_RUNNING = ss.dwCurrentState;
end;

A:

By default you need to have admin privileges to start, stop, install and delete services.
You will have to arrange for your service to expose its own Active property, distinct from what Windows terms as running. Arrange that it is running in Windows terms all the time, but inert when its Active property is false.
You'll have to implement a control mechanism for your user app. I've done this with named pipes but the are other IPC methods available.

A:

Services hava ACLs as other Windows objects. In a domain permissions to start/stop services may be assigned to users using group policies (under Computer Configuration -> Polices -> Windows Settings -> Security Settings -> System Services). AFAIK this node does not appear in gpedit.msc for a local system. sc.exe could be used to set a service security descriptor, but it requires some knowledge of SDDL (Security Descriptor Definition Language, this may help you). Don't know if a template is available to allow gpedit to handle that - it's a bit uncommon a standalone system for which the user has no admin account.


Q:

I need to intercept data before it is put into the model from the database and vice versa

The data stored in the database is HTML.  I cannot change this fact, but I want to hide it in my django admin site.
Before the database populates the model, I'd like to capture it and convert the html entities to unicode.  When the model is saved to the database I'd like to reverse the process.
I can do the actual conversion from HTML entity to unicode and the other way round, but I don't know Django well enough to accomplish this.
I've looked into a modelform for the admin, but this will not work for when the data is displayed in the list_display or other places on the site.
Where/how is the best way to hook into this?

A:

Look into making a custom field if you want it automatically to anything that calls/saves this field. Specifically, set your database-to-model conversion in to_python, and model-to-database conversion in get_prep_value.
If this is behavior specifically for one area of the admin, you could also set it all in the ModelAdmin. list_display can point to readonly fields which can do whatever it wants to the output.
Pure admin:
class ModelAdmin(admin.ModelAdmin):
    list_display = ('_myfield',)
    readonly_fields = ('_myfield', )
    form = MyModelForm # modelform with overriden save() and init
    # converting values to / from db.

    def _myfield(self, obj):
        return whatever_conversion_here(obj.myfield)


Q:

Equation for concentric circles?

I want an equation for concentric circles. In following image I am trying to draw concentric circles in Java but as you can see these are messed up.
This is because their (x,y) coordinates (i.e. positions) are measured from the upper-left corner, but because of having different heights and widths both circles no longer remain concentric. So I need to know how much I should increment x and y for smaller circle. Can anyone provide some equation?
Following are the methods I am using to draw circles in Java:
    g.setColor( Color.YELLOW );
    g.fillOval( 10, 10, 300, 300 ); // x,y, width,height

    g.setColor( Color.CYAN );
    g.fillOval( 10, 10 , 200, 200 ); // x,y, width,height

A:

As you can see in your picture, your two circles have different origins, but concentric circles must share the same origin.  Specifically, the first circle has an origin of $(160,160)$ ($10 + 150$ radius) while the second circle has an origin of $(110,110)$ ($10 + 100$ radius).  To equalize the two origins, simply add 50 to the $x$ and $y$ upper-left corner for the second circle:
g.setColor(Color.YELLOW);
g.fillOval(10, 10, 200, 200);

g.setColor(Color.CYAN);
g.fillOval(60, 60, 100, 100);

Here is another example with a generalized equation:
int origin = 160;
int diameter1 = 300;
int diameter2 = 200;
int diameter3 = 100;

g.setColor(Color.YELLOW);
g.fillOval((origin - (diameter1 / 2),
           (origin - (diameter1 / 2), diameter1, diameter1);

g.setColor(Color.CYAN);
g.fillOval((origin - (diameter2 / 2),
           (origin - (diameter2 / 2), diameter2, diameter2);

g.setColor(Color.MAGENTA);
g.fillOval((origin - (diameter3 / 2),
           (origin - (diameter3 / 2), diameter3, diameter3);


Q:

Detail of Gallifrey's Transduction Barrier

I recall a reference work that discusses the working of Gallifrey's Transduction Barrier as mentioned in The Invasion of Time. As I recall it, it's far more than a force field; it actually takes Gallifrey out of phase with the universe by several seconds, making approach and landing on the planet virtually impossible with out a time machine, more precisely a TARDIS with the information on how to cross the barrier.
It's mentioned / used in several audio adventures and novels during The Hiatus, but I've never been able to find an original (canon) citation for this, and I'm beginning to suspect it was merely a very plausible fan theory that gained support by the writers.
Ringing a bell for anyone?

A:

Like much Time Lord Tech, the Transduction Barrier(s) aren't really ever explained in cannon.  Dr Who isn't a very technobabbly show;  lost of tech "just works" or he'll "explain it later."
In the TV show, a transduction barrier is mentioned in The Invasion of Time and ...that's really it.
If you expand to accept the Webcasts as canon, then Shada mentions transduction barriers and some of their effects, and seems to pull from the Audio dramas as a "canon acceptable" source.
The Audio dramas provide a lot more background on the transduction barriers, including the concept that Gallifrey was kept "slightly out of phase" with the barriers, but in Dr Who's wibbly-wobbly "canon" universe, it's up to you to decide which bits are canon or not.
I would posit that the "Transduction Barrier" in the TV series is just a powerful planetary shield.  The Time Lord's propensity for naming things with grandiose language would keep them from calling it a "planetary shield" or "border fence."
The word "Transduction" is used in many contexts to simply mean the conversion of one thing into another. In medicine, it means the conversion of one type of chemical or electrical signal in a cell to another.  In Computer Science, it means converting one set of data directly into another via machine learning.  I would therefore further posit that the transduction barrier is simply a fancy way of saying "electromagnetic force field;"  it converts one kind of energy (electricity) into a (series?) of forcefield(s) which repel attackers, either as a pseudo-physical barrier, or simply a technological barrier (warp gravity and you can't achieve orbit or land.  Put up enough static, you don't want to depend on your transmat beams.)
Finally, I would mention that New Who pretty much replaced "transduction barriers" with "sky trenches."  Again, as above, no explanation is made on how a sky trench works, or how it can even be remotely trench-like, but these too appear to be a type of forcefield; until The Last Day, nothing had ever penetrated two layers of sky trenches.  I would posit that "sky trenches," unlike the "transduction barriers," could also defend against time travellers.  In Television Classic Who, there are very few species with Time Travel, with a heavy hint that the Time Lords were the only real people to perfect it, so they didn't really need special protections against time travel.  In the Last Great Time War, however, at a minimum Daleks had perfected time travel for themselves, in which case transduction barriers would be "old tech" to be replaced with "sky trenches."
Putting Gallifrey into a time bubble and shifting it out of phase with the universe as a protection sure does sound cool, doesn't it?  Kinda like stasis cubes...


Q:

Is there a way to tell eslint to block console but not console.error?

I want to use the rule no-console but I also want to log errors in my application.
Is there a way to ignore calls to console.error or ir there another way to log it on stderr?

A:

You can always write to process.stderr. But if you want to know if you really can write to the standard output streams, you need to check if Node.js is started in TTY mode, as shown in process.stdout documentation.


Q:

How To replace Space by '+' sign using javascript

I am trying to create a program in javascript which converts Hello how are you into hello how are you
After searching for it I found this code but it didn't work.

is you good
is you good

A:

"demo" is not an id that exists in your example. Also, I'm fairly certain you are trying to use php as javascript in there.
is you good


Q:

Has science fiction used the Many Worlds Interpretation (MWI) of Hugh Everett to address time travel?

The Many Worlds Interpretation (MWI) of quantum theory first proposed by Hugh Everett in 1957, says that everything that can happen, will, in its own separate universe.  (Note that this is not the multiverse, aka the megaverse theory.  Each universe of the multiverse, in the MWI, repeatedly branches at the quantum level and becomes many universes.)  Has any SF work explicitly used MWI to address time travel?
"Many-worlds implies that all possible alternate histories and futures are real, each representing an actual "world" (or "universe"). In lay terms, the hypothesis states there is a very large — perhaps infinite — number of universes, and everything that could possibly have happened in our past, but did not, has occurred in the past of some other universe or universes."  Wikipedia, https://en.wikipedia.org/wiki/Many-worlds_interpretation

A:

Here's an article by science fiction writer Gregory Benford where he talks about how Everett's interpretation specifically inspired the time travel mechanics of his 1980 novel Timescape:

Still, I wondered how tachyons—which Einstein's special theory of
  relativity clearly allowed—could fit into the world as we knew it. I
  essayed an approach in a novelette in Epoch, an anthology of the
  mid-1970s. Then over five years I wrote a novel, Timescape (published
  1980), exploring the simplest situation I could imagine—discovery of
  tachyons, and the first attempts to probe their properties and use.
  Rather than the convenient Wellsian traveler, I used scientists as I
  knew them, warts and all, doing what they would—trying to use the new
  discovery to communicate something they cared about.
But how to deal with the paradox? I had always rather liked another
  theory which resolved the multiple-outcome property of conventional
  quantum mechanics. This interpretation of quantum events supposes that
  when a given particle, say, passes through a hole in a wall, it can go
  in several directions. The wave-like property of matter says that the
  same experiment, repeated many times, will give a pattern of impacts
  on a far screen. The density of impacts corresponds to the probability
  that a single particle would follow that trajectory and make that
  impression. But a single particle's trajectory can't be predicted
  precisely—we can only get the probability distribution.
Enter a fresh view, due to Hugh Everett of Princeton in the 1950s.
  Everett said that all the possible outcomes predicted by the
  probability analysis of quantum mechanics are separately real. This
  means that every time a particle passes through a hole, the entire
  universe splits into many possible outcomes.
Envision separable worlds peeling off from every microscopic event. In
  our world, the particle smacks into the wall and that specific outcome
  defines our world forever more. Other worlds simultaneously appear,
  with a slightly different impact point. Every event generates great
  handfuls of other worlds—a cosmic plentitude of astronomical
  extravagance. I've often wondered whether Everett was influenced by
  such SF stories as Murray Leinster's "Sidewise in Time" (1934).
  Certainly he influenced later SF writers, including the Larry Niven of
  "All the Myriad Ways" (1963).
The Everett view was fun to think about, and logically defensible, but
  nobody really believed it. But I found it handy. (Writers are
  magpies.) I said in my novel that the Everett interpretation didn't
  really apply to every event. Instead, I reserved the Everett picture
  for only those events which produced a causal paradox. If a physicist
  sent a tachyon backward in time and it had no grandfather-killing
  effects, no problem. If it did, though, then the universe split into
  as many versions as it took to cover all the possibilities. So you
  could indeed send some grandfather-killing message (or anything else
  that made a paradox), and grandfather would die. But not in the
  universe you were doomed to inhabit. Instead, another universe would
  appear, unknown to you, in which dear old grandfather died, alas, and
  you never happened at all. No paradox, since the tachyon which killed
  gramps came from another universe, from another you.

Searching inside the book on amazon shows it doesn't directly reference Everett or the many-worlds interpretation, but if you search in the book for the word "quantum" it does feature a character thinking about the problem of what causes the wave function to collapse in quantum mechanics (p. 211), and coming up with the idea that the paradoxes associated with tachyons (which travel faster than light and can therefore be used to transmit information back in time, see the tachyonic antitelephone) could be solved if the wavefunction didn't collapse at all (p. 363):

Markham thought of a universe with one wave function, scattering into the new states of being as a paradox formed inside it like the kernel of an idea.—If the wave function did not collapse ... Worlds lay ahead of him, and worlds lay behind.

For an example of a story where time travel creates branching histories that does explicitly reference Everett, there is The Time Ships by Stephen Baxter (an officially-licensed sequel to H.G. Wells' The Time Machine, published in 1995), where there is the following dialogue between the narrator and two other characters (in a section viewable here):

“There is — will be — a new philosophy called the Many Worlds
  Interpretation of Quantum Mechanics, “Nebogipfel said, and the sound
  of his queer, liquid voice, delivering such a striking phrase, sent
  shivers along my spine. “There is another ten or twenty years to
  elapse before the crucial papers are published — I remember the name
  of Everett…”
“It’s like this,” Moses said. “Suppose you have a Particle which can
  be in just two places — here or there, we will say — with some chance
  associated with each place. All right? Now you take a look with your
  microscope, and find it here…”
“According to the Many Worlds idea,” Nebogipfel said, “History splits
  into two when you perform such an experiment. In the other History,
  there is another you — who has just found the object there, rather
  than here.”
“Another History?”
Moses said, “With all the reality and consistency of this one.”
He grinned. “There is another you there is an infinite number of
  ’you’s’ — propagating like rabbits at every moment!”
“What an appalling thought,” I said. “I thought two were more than
  enough. But look, Nebogipfel, couldn’t we tell if we were being split
  up in this way?”
“No,” he said, “because any such measurement, in either History, would
  have to come after the split. It would be impossible to measure the
  consequences of the split itself.”
“Would it be possible to detect if these other Histories were there? —
  or for me to travel there, to meet another of this sheaf of twin
  selves you say I have?”
“No,” Nebogipfel said. “Quite impossible. Unless—”
“Yes?”
“Unless some of the tenets of Quantum Mechanics prove to be false.”
Moses said, “You can see why these ideas could help us make sense of
  the paradoxes we have uncovered. If more than one History can indeed
  exist—”
“Then causality violations are easily dealt with,” Nebogipfel said.
  “Look: suppose you had returned through time with a gun, and shot
  Moses summarily.” Moses paled a little at this.
Nebogipfel went on: “So there we have a classic Causality Paradox in
  its simplest terms. If Moses is dead, he will not go on to build the
  Time Machine, and become you — and so he cannot travel back in time to
  do the murder. But if the murder does not take place, Moses lives on
  to build the machine, travels back — and kills his younger self. And
  then he cannot build the machine, and the murder cannot be committed,
  and—”
“Enough,” I said. “I think we understand.”
“It is a pathological failure of causality,” Nebogipfel said, “a loop
  without termination.
“But if the Many Worlds idea is right, there is no paradox. History
  splits in two: in one edition, Moses lives; in the second, he dies.
  You, as a Time Traveler, have simply crossed from one History into the
  other.”
“I see it,” I said in wonder. “And surely this Many Worlds phenomenon
  is precisely what we have witnessed, Nebogipfel and I — we have
  already watched the unfolding of more than one edition of History…” I
  felt enormously reassured by all this — for the first time, I saw that
  there might be a glimmer of logic about the blizzard of conflicting
  Histories which had hailed about my head since my second launch into
  time! Finding some sort of theoretical structure to explain things was
  as important to me as finding solid ground beneath his feet might be
  to a drowning man; though what practical application we might make of
  all this I could not yet imagine.

Also worth noting is that the idea of time travel paradoxes being solved by having multiple parallel histories actually predates Everett's theory. On p. 299 of his book Time Machines, Paul Nahin writes:

The first such tale in science fiction was probably the 1935 story "The Branches of Time" (Daniels), which also contained the observation that although alternate time tracks may allow for changing the past for the better (something that can't be done, for better or for worse, with just one time time track), in the end any such change may still be futile. As Daniels' time traveler puts it, sadly, "I did have an idea to ... go back to make past ages more liveable. Terrible things have happened in history, you know. But it isn't any use. Think, for instance, of the martyrs and the things they suffered. I could go back and save them those wrongs. And yet all the time ... they would still have known their unhappiness and their agony, because in this world-line those things have happened. At the end, it's all unchangeable; it merely unrolls before us."

And endnote to this section on p. 400 adds:

The editorial introduction to this pioneering tale is interesting; the opening line is "To say that this short story contains some revolutionary time-travel theories would be putting it exceedingly mild." The editor then goes on to tell us enthusiastically that "when the author ... submitted this story to us, his accompanying letter stated that in it he had settled the time-travel question once and for all. We must admit that a broad, unbelieving grin spread over our countenances when the author dared to make this assertion. BUT—the smile soon left our faces. ... [T]o our chagrin, Mr. Daniels had really propounded so many brand new ideas about time and time-travel, and such logical ones—that he has not left one loophole in his argument!" ... After Daniels the concept quickly became part of standard science fiction lore and could be used by writers with little explanation. For example, in the 1947 story "A Hitch in Time" (MacCreigh) the author did not have to say much about his "First Law of Chronistics," which determines the development of "the branches of Fan-Shaped time." It was sufficient for his readers to learn that should a time traveler to the past change anything, a parallel branch of time would be created on which the time traveler would be trapped. "The man who interfered with the space-time matrix, displacing even a comma in the great scroll of time, would be cut off from his origin forever."

"The Branches of Time" appeared in the August 1935 issue of Wonder Stories, which is available on archive.org here (the story starts on page 295), part of their pulp magazine archive. There are also alternate history stories that predate "The Branches of Time", such as Leinster's "Sideways in Time" from 1934 (on archive.org here, p. 10) which was mentioned by Oldcat in a comment (see this wikipedia article for more examples), but "The Branches of Time" may be the first in which new alternate histories are created directly by time travel, and only begin to diverge from our history at the moment the time traveler arrives in the past.


Q:

How to sort the two line character in R

How can I sort the variable (pair) which is two line label in the following order:
Pair<-c("CA.F - BK.F\n(P-value=0.00)", "CA.M - BK.M\n(P-value=0.00)",
 "EA.F - BK.F\n(P-value=0.41)", "EA.F - CA.F\n(P-value=0.00)",
 "EA.M - BK.M\n(P-value=0.32)", "EA.M - CA.M\n(P-value=0.33)",
 "SA.F - BK.F\n(P-value=0.08)", "SA.F - CA.F\n(P-value=0.00)",
 "SA.F - EA.F\n(P-value=0.99)", "SA.M - BK.M\n(P-value=0.95)",
 "SA.M - CA.M\n(P-value=0.01)", "SA.M - EA.M\n(P-value=0.94)")

lwr<-c(2,3,4,5,6,7,8,9,11,13,14,16)
upr<-c(5,6,7,8,10,12,14,14,13,14,15,15)
Final<-data.frame(Pair,lwr,upr)

I want to sort variable (pair) in this format and add it into the data set as a new variable:
c("SA.M - EA.M","SA.M - CA.M","EA.M - CA.M","SA.M - BK.M",
"EA.M - BK.M","CA.M - BK.M","SA.F - EA.F","SA.F - CA.F",
"EA.F - CA.F","SA.F - BK.F","EA.F - BK.F","CA.F - BK.F")

A:

I'll assume that you want to reorder Pair according to the labels in the second vector. If so, then you could do the following:
Data:
Pair<-c("CA.F - BK.F\n(P-value=0.00)", "CA.M - BK.M\n(P-value=0.00)",
"EA.F - BK.F\n(P-value=0.41)", "EA.F - CA.F\n(P-value=0.00)",
"EA.M - BK.M\n(P-value=0.32)", "EA.M - CA.M\n(P-value=0.33)",
"SA.F - BK.F\n(P-value=0.08)", "SA.F - CA.F\n(P-value=0.00)",
"SA.F - EA.F\n(P-value=0.99)", "SA.M - BK.M\n(P-value=0.95)",
"SA.M - CA.M\n(P-value=0.01)", "SA.M - EA.M\n(P-value=0.94)")

customOrder = c("SA.M - EA.M","SA.M - CA.M","EA.M - CA.M","SA.M - BK.M",
"EA.M - BK.M","CA.M - BK.M","SA.F - EA.F","SA.F - CA.F",
"EA.F - CA.F","SA.F - BK.F","EA.F - BK.F","CA.F - BK.F")

The vector customOrder is how you want to order Pair
Do:
ordered = sapply(customOrder, function(x){grep(x,Pair)})

Result:
lwr<-c(2,3,4,5,6,7,8,9,11,13,14,16)
upr<-c(5,6,7,8,10,12,14,14,13,14,15,15)
Final<-data.frame(Pair,lwr,upr)

Final[ordered,]

                          Pair lwr upr
12 SA.M - EA.M\n(P-value=0.94)  16  15
11 SA.M - CA.M\n(P-value=0.01)  14  15
6  EA.M - CA.M\n(P-value=0.33)   7  12
10 SA.M - BK.M\n(P-value=0.95)  13  14
5  EA.M - BK.M\n(P-value=0.32)   6  10
2  CA.M - BK.M\n(P-value=0.00)   3   6
9  SA.F - EA.F\n(P-value=0.99)  11  13
8  SA.F - CA.F\n(P-value=0.00)   9  14
4  EA.F - CA.F\n(P-value=0.00)   5   8
7  SA.F - BK.F\n(P-value=0.08)   8  14
3  EA.F - BK.F\n(P-value=0.41)   4   7
1  CA.F - BK.F\n(P-value=0.00)   2   5


Q:

Why is the HTML SCRIPT tag not subject to the same origin policy

I am asking this questions because we will develop an application that is supposed to share cross origin data via javascript. One possible solution seems JSONP as it uses SCRIPT tags pull data from other domains. However, I would like to avoid the situation that we implement our awesome code on the assumption that the SCRIPT tag is not subject to sop and at some point browsers prohibit this functionality.
Can anybody shed some light on what is the reason for the SCRIPT tag to allow cross domain requests?

A:

I suppose this draft titled "Principles of the Same-Origin Policy" explains (albeit briefly) what's pretty much in everyone's head:

In principle, user agents could treat every URL as a separate principal and isolate each document from every other URL unless the document explicitly indicated that it trusted that URL. Unfortunately, this design is cumbersome for developers because web applications often consist of a number of resource acting in concert.
As an approximation, user agents group URLs together into protection domains called origins. In particular, two URLs are part of the same origin (i.e., represent the same principal) if they have the same scheme, host, and port.

In short: it would be much harder to build the Web if everything was subject to SOP.


Q:

how to set control to occupy several grid cells?

I want a control to take 2 cells: column 3 and column 4 of the same row . how to do that? I've tried that but it doesn't work:
Grid.Column="4-5"

A:

Grid.Column="4"
Grid.ColumnSpan="2"


Q:

APIs/SDKs for 2.1 and 2.2 won't install - thinks Windows 7 is Linux?

Trying to install either SDKs for 2.1 or 2.2 in Eclipse, I get the same err msg:
Android SDK Manager Log:
File not found: C:\Program Files (x86)\Android\android-sdk\temp\android-2.2_r03-linux.zip (Access is denied)
My OS is 64-bit Windows 7.
So why it's even looking for linux file, I don't know.

A:

You can run the SDK Manager for Android independently from start menu - but run it "As Administrator" (mouse right-click on SDK Manager to have the selection to run "As Administrator").
This worked for me.


Q:

omouseover not working for images at my machine though it works for online images

This is working in my browser:
<!DOCTYPE html>

But this is not working:
<!DOCTYPE html>

Please answer as soon as possible and path to my images is totally correct!!

A:

If you want to use paths pointing to your local hard drive, you will need to use the file protocol like this:
file:///c:/Users/user/Desktop/WE/Pics/milk.png

However, it's best practice to use relative URLs instead, for instance:
Pics/milk.png

will find the file milk.png in the Pics folder, where the Pics folder is alongside your HTML file.


Q:

Trouble understanding this Equality of Complex number question.

I have this question here
$$(3-2j)(x+yj)=4+j^9$$
I know that $a + bj$ and $x + yj$ are equal when $a = x$ and $b = y$.
This question is confusing me because I have had three different answers but they are all wrong.
What feels like my closest attempt was:
$$(3-2j)(x+yj)=4+j^9.$$
$x + yj = (-3+2j)(4-j)$
$= -12 + 3j + 8j -2j^2$
$= -12 + 11j -2(-1)$
$= -12 + 11j + 2$
$= -10 + 11j \:\: \Rightarrow$
$x = -10$
$y = 11$
But the answer is supposed to be
$x = 10/13$
$y = 11/13$
I am just looking for some guidance on how to properly solve this and figure out where I went wrong.
Thank you!

A:

\begin{align*}(3-2i)(x+yi)=4+i^9&\Longleftrightarrow x+yi=\frac{4+i}{3-2i}\\&\Longleftrightarrow x+yi=\frac{(4+i)(3+2i)}{(3-2i)(3+2i)}\\&\Longleftrightarrow x+yi=\frac{10+11i}{13}=\frac{10}{13}+\frac{11}{13}i\\&\Longleftrightarrow x=\frac{10}{13}\text{ and }y=\frac{11}{13}\end{align*}