答:
a classic case of pointers and variables

essentially when you are declaring pointer as

```<code>int *twenties=0, *tens=0, *fives=0, *ones=0;
</code>```

you are essentially making these pointers to point to NULL memory which means no memory is allocated to those.

one way to solve this is by declaring these as variables and passing the address of these variables

```<code>int dollars, twenties=0, tens=0, fives=0, ones=0;
</code>```

and

```<code>pay_month(dollars, &twenties, &tens, &fives, &ones);
</code>```

Title: Why am i getting EXC_BAD_ACCESS (code=1, address=0x0)?

Body:
a classic case of pointers and variables

essentially when you are declaring pointer as

int *twenties=0, *tens=0, *fives=0, *ones=0;

you are essentially making these pointers to point to NULL memory which means no memory is allocated to those.

one way to solve this is by declaring these as variables and passing the address of these variables

int dollars, twenties=0, tens=0, fives=0, ones=0;

and

pay_month(dollars, &twenties, &tens, &fives, &ones);


来源: stackexchange

问:
How to retrieve the text inside the objects of array?
i have an array of this format:

```<code>points.push(
{text: '<span style="font-weight: bold;font-size:25px;">hi</span>'},
{text: '<span style="font-weight: bold;font-size:25px;">hello</span>'},
{text: '<span style="font-weight: bold;font-size:25px;">call</span>'},
{text: '<span style="font-weight: bold;font-size:25px;">crow</span>'});
</code>```

when i use alert(points[1]); i get [object object] obviously because there are some html code around it...

can anyone tell me how to retrieve the text inside this array.
i need the output as only "hi" or "hello" or "call" or "crow"

Thank you.

答: alert(points[1].text) will give you the text: 'hi' for example. You will have to extract the proper content after that.

ContentLicense: CC BY-SA 2.5

Body:
i have an array of this format:

points.push(
{text: 'hi'},
{text: 'hello'},
{text: 'call'},
{text: 'crow'});

when i use alert(points[1]); i get [object object] obviously because there are some html code around it...

can anyone tell me how to retrieve the text inside this array.
i need the output as only "hi" or "hello" or "call" or "crow"

Thank you.

Body: alert(points[1].text) will give you the text: '<span style="font-weight: bold;font-size:25px;">hi</span>' for example. You will have to extract the proper content after that.


问:
Need help improving my c++ and class creation 2
i wanna know where i can improve my program as well as i have run into a problem with my code.

this is my hero class and source, it is telling me i have hero h; calling a deleted function as well as how do i pass stats through this function? until i have this figured out i had // out the classes constructor.

```<code> class hero : public Stats {
    //protected:

public:

    void raceAndClass() {

        Stats S(10,10,10,10,10,10);
        race c_race(race::orc, S);
        //classes c_classes(classes::fighter, modStats, sneak, bluff, deplomacy, swim, mana, run);
        using namespace std;
        }
};

int main()
{
        hero H;
        H.raceAndClass();
        while (true);

}
</code>```

here is my next class stats

```<code>   class Stats {
    public:
        int //default stats
            Str = 10,
            Dex = 10,
            Con = 10,
            Int = 10,
            Wis = 10,
            Chr = 10;

    Stats(int STR, int DEX, int CON, int INT, int WIS, int CHR) :
        Str(STR), Dex(DEX), Con(CON), Int(INT), Wis(WIS), Chr(CHR) {
    }
};
</code>```

my race cpp and header

```<code>  #include"stats.h"

class race {
public:
    enum raceOpt { orc, elf, human };

    race(raceOpt c_raceOpt, Stats &stats);

    //race opt outcomes
    void ORC(Stats& stats) {
        stats.Str += 2;
        stats.Int -= 2;
        stats.Chr -= 2;
    }
    void ELF(Stats &stats) {
        //elf code and stat changes
    }

    void HUMAN(Stats &stats) {

}
    };

#include"race.h"

race::race(raceOpt c_raceOpt, Stats &stats) {
    switch (c_raceOpt) {
    case orc:
        ORC(stats);
        break;
    case human:
        //human code
        break;
    case elf:
        //elf code
        break;
    }
}
</code>```

and finally my classes cpp & header.(not currently being called)

```<code>#include"stats.h"

class classes {
public:
    enum classOpt { fighter, mage, soccerPlayer };

    classes(classOpt c_classOpt, double ModStats[_MAX_PATH], int& Sneak, int& Bluff, int& Deplomacy, int& Swim, int& Mana, int& Run);

    void Fighter(int& SWIM, int& RUN, int& BLUFF, double ModStats[_MAX_PATH]) {
        SWIM = static_cast<int>(SWIM + std::round(((ModStats[1] * 2.3))));
        RUN = static_cast<int>(RUN + (std::round(((ModStats[1] * 2)))));
        BLUFF = static_cast<int>(BLUFF + std::round(((ModStats[0] * 2.5))));

    }
    void Mage(int& MANA, int& DEPLOMACY, int& BLUFF, double ModStats[_MAX_PATH]) {
        //code to be added

    }
    void SoccerPlayer(int& RUN, int& SWIM, int& DEPLOMACY, int& SNEAK, double ModStats[_MAX_PATH]) {
        //code to be added

    }
};

#include"classes.h"

classes::classes(classOpt c_classOpt, double ModStats[_MAX_PATH], int& Sneak, int& Bluff, int& Deplomacy, int& Swim, int& Mana, int& Run) {
    switch (c_classOpt) {
    case fighter:
        Fighter(Swim, Run, Bluff, ModStats);
        break;
    case mage:
        Mage(Mana, Deplomacy, Bluff, ModStats);
        break;
    case soccerPlayer:
        SoccerPlayer(Run, Swim, Deplomacy, Sneak, ModStats);
        break;
    }

}
</code>```

答:
i redid my stats class and my hero class!!! i will also take my stats class and add more stats/skills to it as well as get my classes class refinded. thanks for the help!!!</p>

```<code>#pragma once
class Stats {
public:
    int //default stats
        Str = 10,
        Dex = 10,
        Con = 10,
        Int = 10,
        Wis = 10,
        Chr = 10;

    Stats(){}
};

//hero class vvvvv

class hero : public Stats {
private:
    Stats s;
public:

     hero() {

         race c_race(race::orc, s);
         std::cout << s.Str << std::endl;
         std::cout << s.Int << std::endl;
         std::cout << s.Chr << std::endl;
         std::cout << s.Wis << std::endl;
        //classes c_classes(classes::fighter, modStats, sneak, bluff, deplomacy, swim, mana, run);

        }
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i wanna know where i can improve my program as well as i have run into a problem with my code.

this is my hero class and source, it is telling me i have hero h; calling a deleted function as well as how do i pass stats through this function? until i have this figured out i had // out the classes constructor.

 class hero : public Stats {
    //protected:

public:

    void raceAndClass() {

        Stats S(10,10,10,10,10,10);
        race c_race(race::orc, S);
        //classes c_classes(classes::fighter, modStats, sneak, bluff, deplomacy, swim, mana, run);
        using namespace std;
        }
};

int main()
{
        hero H;
        H.raceAndClass();
        while (true);

}

here is my next class stats

   class Stats {
    public:
        int //default stats
            Str = 10,
            Dex = 10,
            Con = 10,
            Int = 10,
            Wis = 10,
            Chr = 10;

    Stats(int STR, int DEX, int CON, int INT, int WIS, int CHR) :
        Str(STR), Dex(DEX), Con(CON), Int(INT), Wis(WIS), Chr(CHR) {
    }
};

my race cpp and header

  #include"stats.h"

class race {
public:
    enum raceOpt { orc, elf, human };

    race(raceOpt c_raceOpt, Stats &stats);

    //race opt outcomes
    void ORC(Stats& stats) {
        stats.Str += 2;
        stats.Int -= 2;
        stats.Chr -= 2;
    }
    void ELF(Stats &stats) {
        //elf code and stat changes
    }

    void HUMAN(Stats &stats) {

}
    };

#include"race.h"

race::race(raceOpt c_raceOpt, Stats &stats) {
    switch (c_raceOpt) {
    case orc:
        ORC(stats);
        break;
    case human:
        //human code
        break;
    case elf:
        //elf code
        break;
    }
}

and finally my classes cpp & header.(not currently being called)

#include"stats.h"

class classes {
public:
    enum classOpt { fighter, mage, soccerPlayer };

    classes(classOpt c_classOpt, double ModStats[_MAX_PATH], int& Sneak, int& Bluff, int& Deplomacy, int& Swim, int& Mana, int& Run);

    void Fighter(int& SWIM, int& RUN, int& BLUFF, double ModStats[_MAX_PATH]) {
        SWIM = static_cast<int>(SWIM + std::round(((ModStats[1] * 2.3))));
        RUN = static_cast<int>(RUN + (std::round(((ModStats[1] * 2)))));
        BLUFF = static_cast<int>(BLUFF + std::round(((ModStats[0] * 2.5))));

    }
    void Mage(int& MANA, int& DEPLOMACY, int& BLUFF, double ModStats[_MAX_PATH]) {
        //code to be added

    }
    void SoccerPlayer(int& RUN, int& SWIM, int& DEPLOMACY, int& SNEAK, double ModStats[_MAX_PATH]) {
        //code to be added

    }
};

#include"classes.h"

classes::classes(classOpt c_classOpt, double ModStats[_MAX_PATH], int& Sneak, int& Bluff, int& Deplomacy, int& Swim, int& Mana, int& Run) {
    switch (c_classOpt) {
    case fighter:
        Fighter(Swim, Run, Bluff, ModStats);
        break;
    case mage:
        Mage(Mana, Deplomacy, Bluff, ModStats);
        break;
    case soccerPlayer:
        SoccerPlayer(Run, Swim, Deplomacy, Sneak, ModStats);
        break;
    }

}

Body:
i redid my stats class and my hero class!!! i will also take my stats class and add more stats/skills to it as well as get my classes class refinded. thanks for the help!!!

#pragma once
class Stats {
public:
    int //default stats
        Str = 10,
        Dex = 10,
        Con = 10,
        Int = 10,
        Wis = 10,
        Chr = 10;

    Stats(){}
};

//hero class vvvvv

class hero : public Stats {
private:
    Stats s;
public:

     hero() {

         race c_race(race::orc, s);
         std::cout << s.Str << std::endl;
         std::cout << s.Int << std::endl;
         std::cout << s.Chr << std::endl;
         std::cout << s.Wis << std::endl;
        //classes c_classes(classes::fighter, modStats, sneak, bluff, deplomacy, swim, mana, run);

        }
};


问:
pass ref class object(Uri^) as native pointer parameter(IUriRuntimeClass *)
I have following midl method in my code:

interface IMyClass : IInspectable
 {
     HRESULT Func1([in] Windows.Foundation.Uri *uri);
}

It generates following interface method:

IMyClass : public IInspectable
{
    public:virtual HRESULT STDMETHODCALLTYPE Func1(
        /* [in] */ __RPC__in_opt ABI::Windows::Foundation::IUriRuntimeClass *uri) = 0;
}

The interface is implemented in App side and its object is passed to my code where I can 'see' only interface.

I want to know what is the best way to call Func1 and pass Windows::Foundation::Uri object as parameter?

Simply passing ref class object does not not work, due to C2664 error

Windows::Foundation::Uri^ u = ref new Uri(...);
IMyClassObj->Func1(u); // error cannot convert argument 1 from Windows::Foundation::Uri ^' to 'ABI::Windows::Foundation::IUriRuntimeClass *

I could achive my goal with reintrepret_casting:

Windows::Foundation::Uri^ u = ref new Uri(...);
ABI::Windows::Foundation::IUriRuntimeClass* uu = reinterpret_cast<ABI::Windows::Foundation::IUriRuntimeClass*>(u);
MyClassObj->Func1(u); // this works fine

Is reinterpret_cast right approach in this situation? Or is there any other way of passing Uri^ object as IUriRuntimeClass* parameter?

答:
A slightly cleaner way to do this is to wrap it in a ComPtr as soon as possible so you get the right behaviour if any exceptions are thrown etc. (Your method might be simple today, but it could get more complex later on).

Something like this:

```<code>#include <wrl/client.h>
#include <windows.foundation.h>

// Dummy method that just prints out the URI to the debug console
HRESULT MyFunc(ABI::Windows::Foundation::IUriRuntimeClass* uri)
{
    HSTRING str{};
    HRESULT ret{ S_OK };
    if (SUCCEEDED(ret = uri->get_AbsoluteUri(&str)))
        OutputDebugString(WindowsGetStringRawBuffer(str, nullptr));

    WindowsDeleteString(str);
    return ret;
}

void Test()
{
    using namespace Microsoft::WRL;

    // Create the ref class
    auto uri = ref new Windows::Foundation::Uri(L"http://www.bing.com");

    // Wrap in a dummy IUnknown wrapper. In theory you could use
    // IInspectable or even IUriRuntimeClass but if you're going to
    // copy-paste the code elsewhere, IUnknown is the "safest" thing you
    // can reinterpret_cast<>() to.
    ComPtr<IUnknown> iUnknown{ reinterpret_cast<IUnknown*>(uri) };

    // Try to cast it to the IUriRuntimeClass, and call our method if
    // it succeeds
    ComPtr<ABI::Windows::Foundation::IUriRuntimeClass> iUri{};
    if (SUCCEEDED(iUnknown.As(&iUri)))
        MyFunc(iUri.Get());
}
</code>```

Body:
A slightly cleaner way to do this is to wrap it in a ComPtr as soon as possible so you get the right behaviour if any exceptions are thrown etc. (Your method might be simple today, but it could get more complex later on).

Something like this:

#include <wrl/client.h>
#include <windows.foundation.h>

// Dummy method that just prints out the URI to the debug console
HRESULT MyFunc(ABI::Windows::Foundation::IUriRuntimeClass* uri)
{
    HSTRING str{};
    HRESULT ret{ S_OK };
    if (SUCCEEDED(ret = uri->get_AbsoluteUri(&str)))
        OutputDebugString(WindowsGetStringRawBuffer(str, nullptr));

    WindowsDeleteString(str);
    return ret;
}

void Test()
{
    using namespace Microsoft::WRL;

    // Create the ref class
    auto uri = ref new Windows::Foundation::Uri(L"http://www.bing.com");

    // Wrap in a dummy IUnknown wrapper. In theory you could use
    // IInspectable or even IUriRuntimeClass but if you're going to
    // copy-paste the code elsewhere, IUnknown is the "safest" thing you
    // can reinterpret_cast<>() to.
    ComPtr<IUnknown> iUnknown{ reinterpret_cast<IUnknown*>(uri) };

    // Try to cast it to the IUriRuntimeClass, and call our method if
    // it succeeds
    ComPtr<ABI::Windows::Foundation::IUriRuntimeClass> iUri{};
    if (SUCCEEDED(iUnknown.As(&iUri)))
        MyFunc(iUri.Get());
}


问:
How to get a header from a html file
I am having difficulty in understanding what exactly I am suppose to do for my homework question.

The question states... Given a str, return the entire substring starting at the beginning of the str up to and including . Requirement:
The string contains .

```<code>The code is...
def get_header(s):
'''(str) -> str
Return the start of the given string up to and including</head>.'''
</code>```

Here is a small segment snippet of the html file example I am suppose to use for this code....

```<code> <html>
            <head>
                <style>
    body {
        background: black;
        text-align: center;
        color: white;
        }
</code>```

Is this question asking me to only read the first two html lines or do I have to find all headers throughout the html files?

Thank you, any help would be appreciated,

Ned

答:
using js:</p>

```<code>var x = document.getElementsByTagName("HEAD")[0];
var y = x.outerHTML
</code>```

Title: How to get a header from a html file

Body:
I am having difficulty in understanding what exactly I am suppose to do for my homework question.

The question states... Given a str, return the entire substring starting at the beginning of the str up to and including . Requirement:
The string contains .

The code is...
def get_header(s):
'''(str) -> str
Return the start of the given string up to and including.'''

Here is a small segment snippet of the html file example I am suppose to use for this code....

Body:
using js:

var x = document.getElementsByTagName("HEAD")[0];
var y = x.outerHTML


问:
Why are both `p()` and `(*p)()` valid?
Say for this simple code:

```<code>int foo(void);
int (*p)(void);
p = foo;
p = &foo;
int a = p();
int b = (*p)();
</code>```

In the above example, Line 3&4 are both valid, Line 5&6 are also both valid.

In fact if you try to play with variable pointers like that when you play with function pointers, your program will surely die. So why is it valid for function pointers?

答:
According to §6.5.2.2/1 of the C11 Standard, in a function call:

The expression that denotes the called function shall have type pointer to function returning void or returning a complete object type other than an array type.

Now, in most expressions a function designator is converted to a function pointer (§6.3.2.1/4):

A function designator is an expression that has function type. Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, a function designator with type ''function returning type'' is converted to an expression that has type ''pointer to function returning type''.

So, in a function call such as int a = p();, the function designator p is converted to a function pointer, which is needed in the expression before the postfix operator () for the function call.

But, according to §6.5.3.2/4 about the indirection operator:

If the operand points to a function, the result is a function designator

So, in a function call such as int b = (*p)();, the function designator p is converted to a function pointer, and the result of the indirection operator acting on this function pointer is a function designator, which itself is converted to the function pointer needed in the postfix expression for the function call.

By §6.5.2.2/1 above, foo is converted to a function pointer in the expression p = foo. But, in the expression p = &foo, the function designator is not converted to a function pointer. Here, §6.5.3.2/3 states that:

The unary & operator yields the address of its operand. If the operand has type ''type'', the result has type ''pointer to type''.... Otherwise, the result is a pointer to the object or function designated by its operand.

So the expression &foo evaluates to a pointer to the function designated by foo, as expected.

Title: Why are both `p()` and `(*p)()` valid?

Body:
Say for this simple code:

int foo(void);
int (*p)(void);
p = foo;
p = &foo;
int a = p();
int b = (*p)();

In the above example, Line 3&4 are both valid, Line 5&6 are also both valid.

In fact if you try to play with variable pointers like that when you play with function pointers, your program will surely die. So why is it valid for function pointers?


问:
Corret way to set up inline function
I want to define an inline function in c++. For example, in the header file of this function fun.h I had

```<code>#ifndef FUN_H
#define FUN_H

void fun(int);

#endif // FUN_H
</code>```

and in the source file fun.cpp I had

```<code>#include "fun.h"

inline void fun(int a){
    return ++a;
}
</code>```

I know this is one way to define an inline function but I did see plenty of people saying that the implementation of an inline function should directly be in the header file fun.h, which means the following pattern,

```<code>#ifndef FUN_H
#define FUN_H

inline void fun(int a){
    return ++a;
}

#endif // FUN_H
</code>```

However, I do not want to squeeze all the codes together so I coded like this,

```<code>#ifndef FUN_H
#define FUN_H

void fun(int);

inline void fun(int a){
    return ++a;
}
#endif // FUN_H
</code>```

Is this a correct style so that the function can be thought as an inline function?

Btw, someone told me that if I put the definition of an inline function in a source file, it may cause an “undefined reference to” problem when linking. I did encounter this problem once and the solution is to delete the "inline" keyword in the source file. However, there are still some functions that have their definitions in the source file with inline keywords. This functions did not trigger any linking errors so I am confused now about the right way to use the "inline" keyword.

Does anyone have some ideas on it?

答:
You can get an overview from their official documentation of inline function in c++,

When to use -

Function can be made as inline as per programmer need. Some useful recommendation are mentioned below-

Use inline function when performance is needed.

Use inline function over macros.

Prefer to use inline keyword outside the class with the function definition to hide implementation details.

Also it is worth mentioning from that same place,

Pros :-

...

By marking it as inline, you can put a function definition in a header file (i.e. it can be included in multiple compilation unit, without the linker complaining)

And

Cons :-

...

When used in a header, it makes your header file larger with information which users don’t care.

What I do is, as the function is quite small (as it should be), include it in the header file like this

```<code>#ifndef FUN_H
#define FUN_H

inline void fun(int a) { return ++a; }

#endif // FUN_H
</code>```

So you are not being overwhelmed by the function definitions and can read off the function without scrolling too much and also skipping the compilation problems as you have mentioned in your question.

Title: Corret way to set up inline function

Body:
I want to define an inline function in c++. For example, in the header file of this function fun.h I had

#ifndef FUN_H
#define FUN_H

void fun(int);

#endif // FUN_H

and in the source file fun.cpp I had

#include "fun.h"

inline void fun(int a){
    return ++a;
}

I know this is one way to define an inline function but I did see plenty of people saying that the implementation of an inline function should directly be in the header file fun.h, which means the following pattern,

#ifndef FUN_H
#define FUN_H

inline void fun(int a){
    return ++a;
}

#endif // FUN_H

However, I do not want to squeeze all the codes together so I coded like this,

#ifndef FUN_H
#define FUN_H

void fun(int);

inline void fun(int a){
    return ++a;
}
#endif // FUN_H

Is this a correct style so that the function can be thought as an inline function?

Btw, someone told me that if I put the definition of an inline function in a source file, it may cause an “undefined reference to” problem when linking. I did encounter this problem once and the solution is to delete the "inline" keyword in the source file. However, there are still some functions that have their definitions in the source file with inline keywords. This functions did not trigger any linking errors so I am confused now about the right way to use the "inline" keyword.

Does anyone have some ideas on it?

Body:
You can get an overview from their official documentation of inline function in c++,

When to use -

Function can be made as inline as per programmer need. Some useful recommendation are mentioned below-

Use inline function when performance is needed.

Use inline function over macros.

Prefer to use inline keyword outside the class with the function definition to hide implementation details.

Also it is worth mentioning from that same place,

Pros :-

...

By marking it as inline, you can put a function definition in a header file (i.e. it can be included in multiple compilation unit, without the linker complaining)

And

Cons :-

...

When used in a header, it makes your header file larger with information which users don’t care.

What I do is, as the function is quite small (as it should be), include it in the header file like this

#ifndef FUN_H
#define FUN_H

inline void fun(int a) { return ++a; }

#endif // FUN_H

So you are not being overwhelmed by the function definitions and can read off the function without scrolling too much and also skipping the compilation problems as you have mentioned in your question.


问:
Java: why class designed for inheritance should contain protected clone method?
I'm reading carefully Effective Java (by Joshua Bloch) and I found the following sentence on cloning:

If you design a class for inheritance, be aware that if you choose not to provide a well-behaved protected clone method, it will be impossible for subclasses to implement Cloneable.

I'm a little bit confused, because in my little test:

```<code>public class Cloning {

    public static void main(String[] args) throws CloneNotSupportedException {

        Woman woman1 = new Woman("Marie Curie-Sklodowska", 33, "Physics");
        Woman woman2 = (Woman) woman1.clone();
    }

    static abstract class Person {
        protected String name;
        protected int age;

        Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }

    static class Woman extends Person implements Cloneable {

        private String field;

        Woman(String name, int age, String field) {
            super(name, age);
            this.field = field;
        }

        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
}
</code>```

I'm not getting any error. I think, I do not understand the sentence correctly. Could someone please explain, what the author had in mind?

答:
If you design a class for inheritance, be aware that if you choose not to provide a well-behaved protected clone() method, it will be impossible for subclasses to implement Cloneable.

He's wrong. They can. Consider:

```<code>public class A
{
    private int fieldA;
}

public class B extends A implements Cloneable
{
    public B clone() throws CloneNotSupportedException
    {
        return (B)super.clone();
    }
}
</code>```

B.clone() will return a perfect copy of the instance of B it is invoked on, including A.fieldA. Refuted by counter-example: QED

[I'm aware that this clone() should not really be declared to throw CloneNotSupportedException but it makes the demonstration simpler.]

This all is very curious, because a couple of sentences earlier he has just said:

some programmers simply choose never to override the clone() method

and

classes designed for inheritance should not implement it [Cloneable]

What's even more curious is that the first sentence above is the final sentence in the entire section, and is completley unsupported by either argument or example, unless the entire section is intended to prove it, which it doesn't. The whole section is all so confused that it is difficult to make out exactly what is being claimed. Cloning isn't as difficult to understand or implement as he makes out. Nor is it important. I haven't used it in serious code in 20 years of Java, or so-called 'copy constructors' either.

Body:
I'm reading carefully Effective Java (by Joshua Bloch) and I found the following sentence on cloning:

If you design a class for inheritance, be aware that if you choose not to provide a well-behaved protected clone method, it will be impossible for subclasses to implement Cloneable.

I'm a little bit confused, because in my little test:

public class Cloning {

    public static void main(String[] args) throws CloneNotSupportedException {

        Woman woman1 = new Woman("Marie Curie-Sklodowska", 33, "Physics");
        Woman woman2 = (Woman) woman1.clone();
    }

    static abstract class Person {
        protected String name;
        protected int age;

        Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }

    static class Woman extends Person implements Cloneable {

        private String field;

        Woman(String name, int age, String field) {
            super(name, age);
            this.field = field;
        }

        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
}

I'm not getting any error. I think, I do not understand the sentence correctly. Could someone please explain, what the author had in mind?

Body:
If you design a class for inheritance, be aware that if you choose not to provide a well-behaved protected clone() method, it will be impossible for subclasses to implement Cloneable.

He's wrong. They can. Consider:

public class A
{
    private int fieldA;
}

public class B extends A implements Cloneable
{
    public B clone() throws CloneNotSupportedException
    {
        return (B)super.clone();
    }
}

B.clone() will return a perfect copy of the instance of B it is invoked on, including A.fieldA. Refuted by counter-example: QED

[I'm aware that this clone() should not really be declared to throw CloneNotSupportedException but it makes the demonstration simpler.]

This all is very curious, because a couple of sentences earlier he has just said:

some programmers simply choose never to override the clone() method

and

classes designed for inheritance should not implement it [Cloneable]

What's even more curious is that the first sentence above is the final sentence in the entire section, and is completley unsupported by either argument or example, unless the entire section is intended to prove it, which it doesn't. The whole section is all so confused that it is difficult to make out exactly what is being claimed. Cloning isn't as difficult to understand or implement as he makes out. Nor is it important. I haven't used it in serious code in 20 years of Java, or so-called 'copy constructors' either.


问:
C# listView, how do I add items to columns 2, 3 and 4 etc?
To add items to column 1 in my listView control (Winform) I'm using listView1.Items.Add, this works fine but how do I add items to columns 2 and 3 etc?

答:
There are several ways to do it, but here is one solution (for 4 columns).

```<code>string[] row1 = { "s1", "s2", "s3" };
listView1.Items.Add("Column1Text").SubItems.AddRange(row1);
</code>```

And a more verbose way is here:

```<code>ListViewItem item1 = new ListViewItem("Something");
item1.SubItems.Add("SubItem1a");
item1.SubItems.Add("SubItem1b");
item1.SubItems.Add("SubItem1c");

ListViewItem item2 = new ListViewItem("Something2");
item2.SubItems.Add("SubItem2a");
item2.SubItems.Add("SubItem2b");
item2.SubItems.Add("SubItem2c");

ListViewItem item3 = new ListViewItem("Something3");
item3.SubItems.Add("SubItem3a");
item3.SubItems.Add("SubItem3b");
item3.SubItems.Add("SubItem3c");

ListView1.Items.AddRange(new ListViewItem[] {item1,item2,item3});
</code>```

OwnerDisplayName: Steve

LastEditorDisplayName: buyutec

Body:
There are several ways to do it, but here is one solution (for 4 columns).

string[] row1 = { "s1", "s2", "s3" };
listView1.Items.Add("Column1Text").SubItems.AddRange(row1);

And a more verbose way is here:

ListViewItem item1 = new ListViewItem("Something");
item1.SubItems.Add("SubItem1a");
item1.SubItems.Add("SubItem1b");
item1.SubItems.Add("SubItem1c");

ListViewItem item2 = new ListViewItem("Something2");
item2.SubItems.Add("SubItem2a");
item2.SubItems.Add("SubItem2b");
item2.SubItems.Add("SubItem2c");

ListViewItem item3 = new ListViewItem("Something3");
item3.SubItems.Add("SubItem3a");
item3.SubItems.Add("SubItem3b");
item3.SubItems.Add("SubItem3c");

ListView1.Items.AddRange(new ListViewItem[] {item1,item2,item3});

OwnerDisplayName: James Atkinson

LastEditorDisplayName: James Atkinson


问:
Is this common behaviour of the iPad device?
I have developed an iPad application which runs good in simulator with both orientations.

When i rotate the simulator , the corresponding view gets loaded according to the orientation.

But the same application when running on real iPad device,  when i rotate the device fastly, the corresponding view is not getting loaded. it takes time to load the correct view according to the device orientation.

why this happening? is this common behaviour in the ipad device?

Please let me know your views.

答:
Does the view not load at all or just slowly?

Realize the iPad is nowhere near as powerful / fast as the Mac running your simulator.  Rotation is a relatively intensive task.  Also, depending on your memory footprint and if you have offscreen views that need to know about the rotation (to handle it appropriately), rotation often can trigger reloads of views that might have been unloaded previously by memory warnings, causing even further degradation in performance.

Finally, not loading at all could reflect upon issues in your orientation methods in your view controllers.


问:
Set progressbar indeterminate srcCompat
I make my own progressBar so i can tint the color in pre-lolipop and it worked well until i change the drawable from png into vector. I get long stacktrace error. As what i search on google, the error is because i use src instead of srcCompat. But i didn't find any way to use srcCompat in indeterminate drawable of progressBar. So please could you tell me how to use srcCompat to my indeterminate?

XML :

```<code><com.muadzbinjabal.muadzbinjabal.helper.view.TintProgressBar
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:indeterminateDrawable="@drawable/xml_progress_bar_circle"
    style="@style/Widget.AppCompat.ProgressBar"/>
</code>```

xml_progress_bar_circle :

```<code><rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/ic_progress_bar"
    android:pivotX="50%"
    android:pivotY="50%"/>
</code>```

ic_progress_bar :

```<code><vector android:height="24dp" android:viewportHeight="80.433334"
    android:viewportWidth="80.433334" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:fillAlpha="0.18" android:fillColor="#00000000"
        android:fillType="evenOdd"
        android:pathData="M75.21,40.22A34.99,34.99 0,0 1,53.61 72.55,34.99 34.99,0 0,1 15.47,64.96 34.99,34.99 0,0 1,7.89 26.83,34.99 34.99,0 0,1 40.22,5.23"
        android:strokeAlpha="0.99" android:strokeColor="#000000"
        android:strokeLineCap="round" android:strokeLineJoin="round" android:strokeWidth="8.37210464"/>
</vector>
</code>```

ERROR :

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.muadzbinjabal.muadzbinjabal, PID: 18996
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.muadzbinjabal.muadzbinjabal/com.muadzbinjabal.muadzbinjabal.ActivityRegister}: android.view.InflateException: Binary XML file line #0: Error inflating class com.muadzbinjabal.muadzbinjabal.helper.view.TintProgressBar
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2318)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
    at android.app.ActivityThread.access$800(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:149)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class com.muadzbinjabal.muadzbinjabal.helper.view.TintProgressBar
    at android.view.LayoutInflater.createView(LayoutInflater.java:620)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
    at com.muadzbinjabal.muadzbinjabal.BaseActivity_Network.onCreate(BaseActivity_Network.kt:37)
    at com.muadzbinjabal.muadzbinjabal.ActivityRegister.onCreate(ActivityRegister.kt:73)
    at android.app.Activity.performCreate(Activity.java:5411)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
    at android.app.ActivityThread.access$800(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:149)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Constructor.constructNative(Native Method)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at android.view.LayoutInflater.createView(LayoutInflater.java:594)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
    at com.muadzbinjabal.muadzbinjabal.BaseActivity_Network.onCreate(BaseActivity_Network.kt:37)
    at com.muadzbinjabal.muadzbinjabal.ActivityRegister.onCreate(ActivityRegister.kt:73)
    at android.app.Activity.performCreate(Activity.java:5411)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
    at android.app.ActivityThread.access$800(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:149)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/xml_progress_bar_circle.xml from drawable resource ID #0x7f070090
    at android.content.res.Resources.loadDrawable(Resources.java:2163)
    at android.content.res.Resources.loadDrawable(Resources.java:2082)
    at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
    at android.widget.ProgressBar.<init>(ProgressBar.java:294)
    at android.widget.ProgressBar.<init>(ProgressBar.java:246)
    at android.widget.ProgressBar.<init>(ProgressBar.java:242)
    at com.muadzbinjabal.muadzbinjabal.helper.view.TintProgressBar.<init>(TintProgressBar.kt:23)
    at java.lang.reflect.Constructor.constructNative(Native Method)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at android.view.LayoutInflater.createView(LayoutInflater.java:594)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
    at com.muadzbinjabal.muadzbinjabal.BaseActivity_Network.onCreate(BaseActivity_Network.kt:37)
    at com.muadzbinjabal.muadzbinjabal.ActivityRegister.onCreate(ActivityRegister.kt:73)
    at android.app.Activity.performCreate(Activity.java:5411)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
    at android.app.ActivityThread.access$800(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:149)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ic_progress_bar.xml from drawable resource ID #0x7f07007d
    at android.content.res.Resources.loadDrawable(Resources.java:2163)
    at android.content.res.Resources.loadDrawable(Resources.java:2082)
    at android.content.res.Resources.getDrawable(Resources.java:706)
    at android.graphics.drawable.RotateDrawable.inflate(RotateDrawable.java:247)
    at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:937)
    at android.graphics.drawable.Drawable.createFromXml(Drawable.java:877)
    at android.content.res.Resources.loadDrawable(Resources.java:2159)
    at android.content.res.Resources.loadDrawable(Resources.java:2082)
    at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
    at android.widget.ProgressBar.<init>(ProgressBar.java:294)
    at android.widget.ProgressBar.<init>(ProgressBar.java:246)
    at android.widget.ProgressBar.<init>(ProgressBar.java:242)
    at com.muadzbinjabal.muadzbinjabal.helper.view.TintProgressBar.<init>(TintProgressBar.kt:23)
    at java.lang.reflect.Constructor.constructNative(Native Method)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at android.view.LayoutInflater.createView(LayoutInflater.java:594)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
    at com.muadzbinjabal.muadzbinjabal.BaseActivity_Network.onCreate(BaseActivity_Network.kt:37)
    at com.muadzbinjabal.muadzbinjabal.ActivityRegister.onCreate(ActivityRegister.kt:73)
    at android.app.Activity.performCreate(Activity.java:5411)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
    at android.app.ActivityThread.access$800(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:149)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #0: invalid drawable t
</code>```

答:
To use the srcCompat you have to use it following

```<code>app:srcCompat="@drawable/ic_play"
</code>```

Add this to the top parent view.

```<code>xmlns:app="http://schemas.android.com/apk/res-auto"
</code>```

Title: Set progressbar indeterminate srcCompat

Body:
I make my own progressBar so i can tint the color in pre-lolipop and it worked well until i change the drawable from png into vector. I get long stacktrace error. As what i search on google, the error is because i use src instead of srcCompat. But i didn't find any way to use srcCompat in indeterminate drawable of progressBar. So please could you tell me how to use srcCompat to my indeterminate?

XML :

<com.muadzbinjabal.muadzbinjabal.helper.view.TintProgressBar
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:indeterminateDrawable="@drawable/xml_progress_bar_circle"
    style="@style/Widget.AppCompat.ProgressBar"/>

xml_progress_bar_circle :

<rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/ic_progress_bar"
    android:pivotX="50%"
    android:pivotY="50%"/>

ic_progress_bar :

<vector android:height="24dp" android:viewportHeight="80.433334"
    android:viewportWidth="80.433334" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:fillAlpha="0.18" android:fillColor="#00000000"
        android:fillType="evenOdd"
        android:pathData="M75.21,40.22A34.99,34.99 0,0 1,53.61 72.55,34.99 34.99,0 0,1 15.47,64.96 34.99,34.99 0,0 1,7.89 26.83,34.99 34.99,0 0,1 40.22,5.23"
        android:strokeAlpha="0.99" android:strokeColor="#000000"
        android:strokeLineCap="round" android:strokeLineJoin="round" android:strokeWidth="8.37210464"/>
</vector>

ERROR :

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.muadzbinjabal.muadzbinjabal, PID: 18996
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.muadzbinjabal.muadzbinjabal/com.muadzbinjabal.muadzbinjabal.ActivityRegister}: android.view.InflateException: Binary XML file line #0: Error inflating class com.muadzbinjabal.muadzbinjabal.helper.view.TintProgressBar
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2318)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
    at android.app.ActivityThread.access$800(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:149)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class com.muadzbinjabal.muadzbinjabal.helper.view.TintProgressBar
    at android.view.LayoutInflater.createView(LayoutInflater.java:620)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
    at com.muadzbinjabal.muadzbinjabal.BaseActivity_Network.onCreate(BaseActivity_Network.kt:37)
    at com.muadzbinjabal.muadzbinjabal.ActivityRegister.onCreate(ActivityRegister.kt:73)
    at android.app.Activity.performCreate(Activity.java:5411)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
    at android.app.ActivityThread.access$800(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:149)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Constructor.constructNative(Native Method)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at android.view.LayoutInflater.createView(LayoutInflater.java:594)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
    at com.muadzbinjabal.muadzbinjabal.BaseActivity_Network.onCreate(BaseActivity_Network.kt:37)
    at com.muadzbinjabal.muadzbinjabal.ActivityRegister.onCreate(ActivityRegister.kt:73)
    at android.app.Activity.performCreate(Activity.java:5411)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
    at android.app.ActivityThread.access$800(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:149)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/xml_progress_bar_circle.xml from drawable resource ID #0x7f070090
    at android.content.res.Resources.loadDrawable(Resources.java:2163)
    at android.content.res.Resources.loadDrawable(Resources.java:2082)
    at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
    at android.widget.ProgressBar.<init>(ProgressBar.java:294)
    at android.widget.ProgressBar.<init>(ProgressBar.java:246)
    at android.widget.ProgressBar.<init>(ProgressBar.java:242)
    at com.muadzbinjabal.muadzbinjabal.helper.view.TintProgressBar.<init>(TintProgressBar.kt:23)
    at java.lang.reflect.Constructor.constructNative(Native Method)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at android.view.LayoutInflater.createView(LayoutInflater.java:594)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
    at com.muadzbinjabal.muadzbinjabal.BaseActivity_Network.onCreate(BaseActivity_Network.kt:37)
    at com.muadzbinjabal.muadzbinjabal.ActivityRegister.onCreate(ActivityRegister.kt:73)
    at android.app.Activity.performCreate(Activity.java:5411)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
    at android.app.ActivityThread.access$800(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:149)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ic_progress_bar.xml from drawable resource ID #0x7f07007d
    at android.content.res.Resources.loadDrawable(Resources.java:2163)
    at android.content.res.Resources.loadDrawable(Resources.java:2082)
    at android.content.res.Resources.getDrawable(Resources.java:706)
    at android.graphics.drawable.RotateDrawable.inflate(RotateDrawable.java:247)
    at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:937)
    at android.graphics.drawable.Drawable.createFromXml(Drawable.java:877)
    at android.content.res.Resources.loadDrawable(Resources.java:2159)
    at android.content.res.Resources.loadDrawable(Resources.java:2082)
    at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
    at android.widget.ProgressBar.<init>(ProgressBar.java:294)
    at android.widget.ProgressBar.<init>(ProgressBar.java:246)
    at android.widget.ProgressBar.<init>(ProgressBar.java:242)
    at com.muadzbinjabal.muadzbinjabal.helper.view.TintProgressBar.<init>(TintProgressBar.kt:23)
    at java.lang.reflect.Constructor.constructNative(Native Method)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at android.view.LayoutInflater.createView(LayoutInflater.java:594)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
    at com.muadzbinjabal.muadzbinjabal.BaseActivity_Network.onCreate(BaseActivity_Network.kt:37)
    at com.muadzbinjabal.muadzbinjabal.ActivityRegister.onCreate(ActivityRegister.kt:73)
    at android.app.Activity.performCreate(Activity.java:5411)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
    at android.app.ActivityThread.access$800(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:149)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #0: invalid drawable t

Body:
To use the srcCompat you have to use it following

app:srcCompat="@drawable/ic_play"

Add this to the top parent view.

xmlns:app="http://schemas.android.com/apk/res-auto"


问:
VXG Media Player giving Unknown error in browser
I want to play RTSP link in my webpage. for that I am using VXG Media Player to play RTSP link video.

I am testing in Chrome browser

below is my code.

```<code><html>
<head>

<script src="~/vxgplayer-1.8.33/vxgplayer-1.8.33.js"></script>
<link href="~/vxgplayer-1.8.33/vxgplayer-1.8.33.min.css" rel="stylesheet" />

</head>
  <body>
  <div class="vxgplayer"
             id="vxg_media_player1"
             url="rtmp://5.101.139.34:1935/vod/Naam_Shahana.mp4"
             autostart controls avsync
             nmf-src="~/vxgplayer-1.8.33/pnacl/Release/media_player.nmf"
             nmf-path="media_player.nmf"></div>
  </body>
</html>
</code>```

I have taken reference from this url

I am getting error like below screenshot,

答:
Init your player

```<code><html>
<head>
  <script src="~/vxgplayer-1.8.33/vxgplayer-1.8.33.js"></script>
  <link href="~/vxgplayer-1.8.33/vxgplayer-1.8.33.min.css" rel="stylesheet" />

</head>
<body>
 <div class="vxgplayer"
         id="vxg_media_player1"
         url="rtmp://5.101.139.34:1935/vod/Naam_Shahana.mp4"
         autostart controls avsync
         nmf-src="~/vxgplayer-1.8.33/pnacl/Release/media_player.nmf"
         nmf-path="media_player.nmf"></div>
 <script>
   var player = vxgplayer('vxg_media_player1');
 </script>
</body>
</html>
</code>```

See more here https://github.com/VideoExpertsGroup/VXG.Chrome-RTSP-Player/blob/master/src/index.html

Body:
I want to play RTSP link in my webpage. for that I am using VXG Media Player to play RTSP link video.

I am testing in Chrome browser

below is my code.

<link href="~/vxgplayer-1.8.33/vxgplayer-1.8.33.min.css" rel="stylesheet" />

I have taken reference from this url

I am getting error like below screenshot,

Body:
Init your player

<html>
<head>
  <script src="~/vxgplayer-1.8.33/vxgplayer-1.8.33.js"></script>
  <link href="~/vxgplayer-1.8.33/vxgplayer-1.8.33.min.css" rel="stylesheet" />

</head>
<body>
 <div class="vxgplayer"
         id="vxg_media_player1"
         url="rtmp://5.101.139.34:1935/vod/Naam_Shahana.mp4"
         autostart controls avsync
         nmf-src="~/vxgplayer-1.8.33/pnacl/Release/media_player.nmf"
         nmf-path="media_player.nmf"></div>
 <script>
   var player = vxgplayer('vxg_media_player1');
 </script>
</body>
</html>

See more here https://github.com/VideoExpertsGroup/VXG.Chrome-RTSP-Player/blob/master/src/index.html


问:
ASP.NET Identity change password
I need ability to change password for user by admin. So, admin should not enter a current password of user, he should have ability to set a new password. I look at ChangePasswordAsync method, but this method requires to enter old password. So, this method is not appropriate for this task. Therefore I have made it by the following way:

```<code>    [HttpPost]
    public async Task<ActionResult> ChangePassword(ViewModels.Admin.ChangePasswordViewModel model)
    {
        var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var result = await userManager.RemovePasswordAsync(model.UserId);
        if (result.Succeeded)
        {
            result = await userManager.AddPasswordAsync(model.UserId, model.Password);
            if (result.Succeeded)
            {
                return RedirectToAction("UserList");
            }
            else
            {
                ModelState.AddModelError("", result.Errors.FirstOrDefault());
            }
        }
        else
        {
            ModelState.AddModelError("", result.Errors.FirstOrDefault());
        }
        return View(model);
    }
</code>```

it works, but theoretically we can receive error on AddPasswordAsync method. So, old password will be removed but new is not set. It's not good. Any way to do it in "one transaction"?
PS. I seen ResetPasswordAsync method with reset token, seems, it's more safe (because can't be unstable situation with user) but in any case, it does by 2 actions.

答:
```<code>public async Task<IActionResult> ChangePassword(ChangePwdViewModel usermodel)
        {
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            var user = await _userManager.FindByIdAsync(userId);
            var result = await _userManager.ChangePasswordAsync(user, usermodel.oldPassword, usermodel.newPassword);
            if (!result.Succeeded)
            {
                //throw exception......
            }
            return Ok();
        }

public class ChangePwdViewModel
    {
        [DataType(DataType.Password), Required(ErrorMessage ="Old Password Required")]
        public string oldPassword { get; set; }

        [DataType(DataType.Password), Required(ErrorMessage ="New Password Required")]
        public string newPassword { get; set; }
    }
</code>```

Note : here UserId i am retrieving  from Current logged User.

Title: ASP.NET Identity change password

Body:
I need ability to change password for user by admin. So, admin should not enter a current password of user, he should have ability to set a new password. I look at ChangePasswordAsync method, but this method requires to enter old password. So, this method is not appropriate for this task. Therefore I have made it by the following way:

    [HttpPost]
    public async Task<ActionResult> ChangePassword(ViewModels.Admin.ChangePasswordViewModel model)
    {
        var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var result = await userManager.RemovePasswordAsync(model.UserId);
        if (result.Succeeded)
        {
            result = await userManager.AddPasswordAsync(model.UserId, model.Password);
            if (result.Succeeded)
            {
                return RedirectToAction("UserList");
            }
            else
            {
                ModelState.AddModelError("", result.Errors.FirstOrDefault());
            }
        }
        else
        {
            ModelState.AddModelError("", result.Errors.FirstOrDefault());
        }
        return View(model);
    }

it works, but theoretically we can receive error on AddPasswordAsync method. So, old password will be removed but new is not set. It's not good. Any way to do it in "one transaction"?
PS. I seen ResetPasswordAsync method with reset token, seems, it's more safe (because can't be unstable situation with user) but in any case, it does by 2 actions.

Body:
public async Task<IActionResult> ChangePassword(ChangePwdViewModel usermodel)
        {
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            var user = await _userManager.FindByIdAsync(userId);
            var result = await _userManager.ChangePasswordAsync(user, usermodel.oldPassword, usermodel.newPassword);
            if (!result.Succeeded)
            {
                //throw exception......
            }
            return Ok();
        }

public class ChangePwdViewModel
    {
        [DataType(DataType.Password), Required(ErrorMessage ="Old Password Required")]
        public string oldPassword { get; set; }

        [DataType(DataType.Password), Required(ErrorMessage ="New Password Required")]
        public string newPassword { get; set; }
    }

Note : here UserId i am retrieving  from Current logged User.


问:
Why doesn't RecyclerView have onItemClickListener()?
I was exploring RecyclerView and I was surprised to see that RecyclerView does not have onItemClickListener().

I've two question.

Main Question

I want to know why Google removed onItemClickListener()?

Is there a performance issue or something else?

Secondary Question

I solved my problem by writing onClick in my RecyclerView.Adapter:

```<code>public static class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {

    public TextView txtViewTitle;
    public ImageView imgViewIcon;

    public ViewHolder(View itemLayoutView) {
        super(itemLayoutView);
        txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.item_title);
        imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon);
    }

    @Override
    public void onClick(View v) {

    }
}
</code>```

Is this ok / is there any better way?

答:
recyclerview animation has not been tested, the other is normal. I think it has been optimized to the maximum. Interface has other uses, you can temporarily ignore.

```<code>public abstract class BaseAdapterRV<VH extends BaseViewHolder> extends RecyclerView.Adapter<VH> implements AdapterInterface {
    public final String TAG = getClass().getSimpleName();

    protected final Activity mActivity;
    protected final LayoutInflater mInflater;
    protected ItemClickInterface<?, Integer> mListener;

    public BaseAdapterRV(Activity activity) {
        mActivity = activity;
        mInflater = LayoutInflater.from(mActivity);
    }

    @Override
    public final VH onCreateViewHolder(ViewGroup parent, int viewType) {
        return onCreateViewHolder(parent, viewType, mInflater);
    }

    @Override
    public final void onBindViewHolder(VH holder, int position) {
        holder.itemView.setTag(R.id.tag_view_click, position);
        //创建点击事件
        holder.itemView.setOnClickListener(mListener);
        holder.itemView.setOnLongClickListener(mListener);
        onBindVH(holder, position);
    }

    ///////////////////////////////////////////////////////////////////////////
    // 以下是增加的方法
    ///////////////////////////////////////////////////////////////////////////

    /**
     * 注意!涉及到notifyItemInserted刷新时立即获取position可能会不正确
     * 里面也有onItemLongClick
     */
    public void setOnItemClickListener(ItemClickInterface<?, Integer> listener) {
        mListener = listener;
        notifyDataSetChanged();
    }

    @NonNull
    protected abstract VH onCreateViewHolder(ViewGroup parent, int viewType, LayoutInflater inflater);

    protected abstract void onBindVH(VH holder, int position);

}
</code>```

This is Interface

```<code>/**
 * OnItemClickListener的接口
 * 见子类实现{@link OnItemClickListener}{@link OnItemItemClickListener}
 */
public interface ItemClickInterface<DATA1, DATA2> extends View.OnClickListener, View.OnLongClickListener {

    void onItemClick(DATA1 data1, DATA2 data2);

    boolean onItemLongClick(DATA1 data1, DATA2 data2);
}
</code>```

This is an abstract class

```<code>public abstract class OnItemClickListener<DATA> implements ItemClickInterface<View, DATA> {
    @Override
    public void onClick(View v) {
        onItemClick(v, (DATA) v.getTag(R.id.tag_view_click));
    }

    @Override
    public boolean onLongClick(View v) {
        return onItemLongClick(v, (DATA) v.getTag(R.id.tag_view_click));
    }

    @Override
    public boolean onItemLongClick(View view, DATA data) {
        return false;
    }
}
</code>```

You only need it

```<code>    mAdapter.setOnItemClickListener(new OnItemClickListener<Integer>() {
        @Override
        public void onItemClick(View view, Integer integer) {

        }

        @Override
        public boolean onItemLongClick(View view, Integer integer) {
            return true;
        }
    });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I was exploring RecyclerView and I was surprised to see that RecyclerView does not have onItemClickListener().

I've two question.

Main Question

I want to know why Google removed onItemClickListener()?

Is there a performance issue or something else?

Secondary Question

I solved my problem by writing onClick in my RecyclerView.Adapter:

public static class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {

    public TextView txtViewTitle;
    public ImageView imgViewIcon;

    public ViewHolder(View itemLayoutView) {
        super(itemLayoutView);
        txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.item_title);
        imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon);
    }

    @Override
    public void onClick(View v) {

    }
}

Is this ok / is there any better way?

Body:
recyclerview animation has not been tested, the other is normal. I think it has been optimized to the maximum. Interface has other uses, you can temporarily ignore.

public abstract class BaseAdapterRV<VH extends BaseViewHolder> extends RecyclerView.Adapter<VH> implements AdapterInterface {
    public final String TAG = getClass().getSimpleName();

    protected final Activity mActivity;
    protected final LayoutInflater mInflater;
    protected ItemClickInterface<?, Integer> mListener;

    public BaseAdapterRV(Activity activity) {
        mActivity = activity;
        mInflater = LayoutInflater.from(mActivity);
    }

    @Override
    public final VH onCreateViewHolder(ViewGroup parent, int viewType) {
        return onCreateViewHolder(parent, viewType, mInflater);
    }

    @Override
    public final void onBindViewHolder(VH holder, int position) {
        holder.itemView.setTag(R.id.tag_view_click, position);
        //创建点击事件
        holder.itemView.setOnClickListener(mListener);
        holder.itemView.setOnLongClickListener(mListener);
        onBindVH(holder, position);
    }

    ///////////////////////////////////////////////////////////////////////////
    // 以下是增加的方法
    ///////////////////////////////////////////////////////////////////////////

    /**
     * 注意!涉及到notifyItemInserted刷新时立即获取position可能会不正确
     * 里面也有onItemLongClick
     */
    public void setOnItemClickListener(ItemClickInterface<?, Integer> listener) {
        mListener = listener;
        notifyDataSetChanged();
    }

    @NonNull
    protected abstract VH onCreateViewHolder(ViewGroup parent, int viewType, LayoutInflater inflater);

    protected abstract void onBindVH(VH holder, int position);

}

This is Interface

/**
 * OnItemClickListener的接口
 * 见子类实现{@link OnItemClickListener}{@link OnItemItemClickListener}
 */
public interface ItemClickInterface<DATA1, DATA2> extends View.OnClickListener, View.OnLongClickListener {

    void onItemClick(DATA1 data1, DATA2 data2);

    boolean onItemLongClick(DATA1 data1, DATA2 data2);
}

This is an abstract class

public abstract class OnItemClickListener<DATA> implements ItemClickInterface<View, DATA> {
    @Override
    public void onClick(View v) {
        onItemClick(v, (DATA) v.getTag(R.id.tag_view_click));
    }

    @Override
    public boolean onLongClick(View v) {
        return onItemLongClick(v, (DATA) v.getTag(R.id.tag_view_click));
    }

    @Override
    public boolean onItemLongClick(View view, DATA data) {
        return false;
    }
}

You only need it

    mAdapter.setOnItemClickListener(new OnItemClickListener<Integer>() {
        @Override
        public void onItemClick(View view, Integer integer) {

        }

        @Override
        public boolean onItemLongClick(View view, Integer integer) {
            return true;
        }
    });


问:
Select distinct for one column
I have a compound primary key where the single parts are potentially random. They aren't in any particular order and one can be unique or they can be all the same.

I do not care which row I get. This is like "Just pick one from each group".

My table:

```<code>KeyPart1 KeyPart2 KeyPart3 colA colB colD
11       21       39                 d1
11       22       39                 d2
12       21       39                 d2
12       22       39                 d3
13       21       38                 d3
13       22       38                 d5

</code>```

Now what I want is to get for each entry in colD one row, I do not care which one.

```<code>KeyPart1 KeyPart2 KeyPart3 colA colB colD
11       21       39                 d1
12       21       39                 d2
12       22       39                 d3
13       22       38                 d5
</code>```

答:
Change 'order by' if necessary   </p>

```<code>with D as (
select distinct ColdD from yourtable
)
select Y.* from D
inner join lateral
(
   select * from yourtable X
   where X.ColdD =D.ColdD
   order by X.KeyPart1, X.KeyPart2, X.KeyPart3
   fetch first rows only

) Y on 1=1
</code>```

Title: Select distinct for one column

Body:
I have a compound primary key where the single parts are potentially random. They aren't in any particular order and one can be unique or they can be all the same.

I do not care which row I get. This is like "Just pick one from each group".

My table:

KeyPart1 KeyPart2 KeyPart3 colA colB colD
11       21       39                 d1
11       22       39                 d2
12       21       39                 d2
12       22       39                 d3
13       21       38                 d3
13       22       38                 d5

Now what I want is to get for each entry in colD one row, I do not care which one.

KeyPart1 KeyPart2 KeyPart3 colA colB colD
11       21       39                 d1
12       21       39                 d2
12       22       39                 d3
13       22       38                 d5

Body:
Change 'order by' if necessary

with D as (
select distinct ColdD from yourtable
)
select Y.* from D
inner join lateral
(
   select * from yourtable X
   where X.ColdD =D.ColdD
   order by X.KeyPart1, X.KeyPart2, X.KeyPart3
   fetch first rows only

) Y on 1=1


答:
the proper syntax would be points[1].text

It is not because there is html code, javascript isn't looking at the contents.  For each pushed element you are using a javascript object literal { property : "value" } meaning for each object you pushed.  You would have to reference the property you instantiated, by assigning it a value, in dot notation object.property. if you want to not use json, change your push statement like so.

```<code>points.push(
'<span style="font-weight: bold;font-size:25px;">hi</span>',
'<span style="font-weight: bold;font-size:25px;">hello</span>',
'<span style="font-weight: bold;font-size:25px;">call</span>',
'<span style="font-weight: bold;font-size:25px;">crow</span>');
</code>```

If you use this type of syntax, (without json {}) you will simply have an array of strings that you could referance like you originally intended.

Also, understand that it does not care what is contained in these string values, it treats them just like any other string.

Title: How to retrieve the text inside the objects of array?

Body:
i have an array of this format:

points.push(
{text: 'hi'},
{text: 'hello'},
{text: 'call'},
{text: 'crow'});

when i use alert(points[1]); i get [object object] obviously because there are some html code around it...

can anyone tell me how to retrieve the text inside this array.
i need the output as only "hi" or "hello" or "call" or "crow"

Thank you.

Body:
the proper syntax would be points[1].text

It is not because there is html code, javascript isn't looking at the contents.  For each pushed element you are using a javascript object literal { property : "value" } meaning for each object you pushed.  You would have to reference the property you instantiated, by assigning it a value, in dot notation object.property. if you want to not use json, change your push statement like so.

points.push(
'<span style="font-weight: bold;font-size:25px;">hi</span>',
'<span style="font-weight: bold;font-size:25px;">hello</span>',
'<span style="font-weight: bold;font-size:25px;">call</span>',
'<span style="font-weight: bold;font-size:25px;">crow</span>');

If you use this type of syntax, (without json {}) you will simply have an array of strings that you could referance like you originally intended.

Also, understand that it does not care what is contained in these string values, it treats them just like any other string.


问:
Wrap async await queries in try catch
I originally had try...catch in my getAllUsers method for querying but ended up removing it because as far as I could tell it wasn't doing anything. I know the async function returns a promise so it should be fine and actually based on how the code is structured I think it's required otherwise the try...catch in the query would swallow the error. Is there anything I'm missing with this structure and use of async/await, try...catch, and .then .catch?

```<code>let getAllUsers = async () => {
  let res = await models.users.findAll({
      attributes: [ 'firstName', 'lastName' ]
    });
    return res;
};

router.get(`${path}`, (req, res) => {
    queries.users.getAllUsers()
      .then(users => {
        res.status(200).json(users);
      })
      .catch(error => {
        res.status(500).send(error)
      });
});
</code>```

答:
The best way I have found to handle this is using middleware.

Here is the function:

```<code>// based upon this
// http://madole.xyz/error-handling-in-express-with-async-await-routes/
// https://github.com/madole/async-error-catcher

export default function asyncErrorCatcher(fn) {
    if (!(fn instanceof Function)) {
        throw new Error("Must supply a function");
    }

    return (request, response, next) => {
        const promise = fn(request, response, next);
        if (!promise.catch) {
             return;
        }
        promise.catch((error) => {
            console.log(error.message);
            response.sendStatus(500);
        });

    };
}
</code>```

Here is the usage:

```<code>router.get("/getSettings/", asyncErrorCatcher(async (request: Request, response: Response) => {
  const settings = await database.getSettings();
  response.json(settings);
}));
</code>```

Title: Wrap async await queries in try catch

Body:
I originally had try...catch in my getAllUsers method for querying but ended up removing it because as far as I could tell it wasn't doing anything. I know the async function returns a promise so it should be fine and actually based on how the code is structured I think it's required otherwise the try...catch in the query would swallow the error. Is there anything I'm missing with this structure and use of async/await, try...catch, and .then .catch?

let getAllUsers = async () => {
  let res = await models.users.findAll({
      attributes: [ 'firstName', 'lastName' ]
    });
    return res;
};

router.get(`${path}`, (req, res) => {
    queries.users.getAllUsers()
      .then(users => {
        res.status(200).json(users);
      })
      .catch(error => {
        res.status(500).send(error)
      });
});

Body:
The best way I have found to handle this is using middleware.

Here is the function:

// based upon this
// http://madole.xyz/error-handling-in-express-with-async-await-routes/
// https://github.com/madole/async-error-catcher

export default function asyncErrorCatcher(fn) {
    if (!(fn instanceof Function)) {
        throw new Error("Must supply a function");
    }

    return (request, response, next) => {
        const promise = fn(request, response, next);
        if (!promise.catch) {
             return;
        }
        promise.catch((error) => {
            console.log(error.message);
            response.sendStatus(500);
        });

    };
}

Here is the usage:

router.get("/getSettings/", asyncErrorCatcher(async (request: Request, response: Response) => {
  const settings = await database.getSettings();
  response.json(settings);
}));


问:
SQL statement to convert dd/mm/yy nvarchar(255) to Date format dd/mm/yyyy
I am struggling with a SQL statement to convert imported data that is in a format dd/mm/yy and of type nvarchar(255) into a date type 'dd/mm/yyyy' format.

The sample data is as follows:

Date:

```<code>'23/10/17'
'24/10/17'
'25/10/17'
'26/10/17'
'27/10/17'
</code>```

To Date Format:

```<code>'23/10/2017'
'24/10/2017'
'25/10/2017'
'26/10/2017'
'27/10/2017'
</code>```

I am using SQL Server 2008 R2

答:
Try using CONVERT.

```<code>SELECT convert(datetime, datecolumn, 103);
</code>```

Refer these links for more detail

http://www.sqlusa.com/bestpractices/datetimeconversion/

https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql

Hope this helps.

Body:
I am struggling with a SQL statement to convert imported data that is in a format dd/mm/yy and of type nvarchar(255) into a date type 'dd/mm/yyyy' format.

The sample data is as follows:

Date:

'23/10/17'
'24/10/17'
'25/10/17'
'26/10/17'
'27/10/17'

To Date Format:

'23/10/2017'
'24/10/2017'
'25/10/2017'
'26/10/2017'
'27/10/2017'

I am using SQL Server 2008 R2

Body:
Try using CONVERT.

SELECT convert(datetime, datecolumn, 103);

Refer these links for more detail

http://www.sqlusa.com/bestpractices/datetimeconversion/

https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql

Hope this helps.


问:
3d pose estimation in opencv
I have an object with some sensors on it with a known 3d location in a fixed orientation in relation to each other. Let's call this object the "detector".
I have a few of these sensors' detected locations in 3D world space.
Problem: how do I get an estimated pose (position and rotation) of the "detector" in 3D world space.

I tried looking into the npn problem, flann and orb matching and knn for the outliers, but it seems like they all expect a camera position of some sort. I have nothing to do with a camera and all I want is the pose of the "detector". considering that opencv is a "vision" library, do I even need opencv for this?

edit: Not all sensors might be detectec. Here indicated by the light-green dots.

答:
Sorry this is kinda old but never too late to do object tracking :)

OpenCV SolvePNP RANSAC should work for you. You don't need to supply an initial pose, just make empty Mats for rvec and tvec to hold your results.

Also because there is no camera just use the Identity for the camera distortion arguments.

The first time calling PNP with empty rvec and tvec make sure to set useExtrinsicGuess = false. Save your results if good, use them for next frame with useExtrinsicGuess = true so it can optimize the function more quickly.
https://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html#solvepnpransac

Title: 3d pose estimation in opencv


问:
PHP ecommerce API?
Is there such a thing as an open source PHP ecommerce API? That is, just the API (i.e., not a whole CMS etc.). I just want some sort of "library" I can invoke from my own code. All of the open source ecommerce solutions that I've run across (such as http://www.opencart.com/) include a whole UI, etc., which I don't want.

答:
The only one I think of is Shopify which has RESTFul Apis.

http://www.shopify.com/
http://api.shopify.com/

Title: PHP ecommerce API?


问:
Python end function after another function returns result
I may be approaching this all wrong but still this is where I'm at.  I have very large log files I'm trying to search, up to 30gb in some cases.  I'm writing a script to pull info and have been playing with multi process to speed it up a bit.  right now I'm testing running two functions at the same time to search from the top and bottom to get results, which seems to work.  I'm wondering if it's possible to stop one function one a result from the other.  Such as if the top function finds a result they both stop.  This way I can build it out as needed.</p>

```<code>from file_read_backwards import FileReadBackwards
from multiprocessing import Process
import sys

z = "log.log"

#!/usr/bin/env python
rocket = 0

def top():
    target = "test"
    with open(z) as src:
        found= None
        for line in src:
            if len(line) == 0: break #happens at end of file, then stop loop
            if target in line:
                found= line
                break
    print(found)

def bottom():
    target = "text"
    with FileReadBackwards(z) as src:
        found= None
        for line in src:
            if len(line) == 0: break #happens at end of file, then stop loop
            if target in line:
                found= line
                break
    print(found)

if __name__=='__main__':
     p1 = Process(target = top)
     p1.start()
     p2 = Process(target = bottom)
     p2.start()
</code>```

答:
This is essentially the same as Blurp's answer, but I shortened it and made it a bit to make it more general. As you can see top should be an infinite loop, but bottom stops top immediately. </p>

```<code>from multiprocessing import Process
valNotFound = True
def top():
    i=0
    while ValNotFound:
        i += 1

def bottom():
    ValNotFound = False

p1 = Process(target = top)
p2 = Process(target = bottom)
p1.start()
p2.start()
</code>```

Body:
I may be approaching this all wrong but still this is where I'm at.  I have very large log files I'm trying to search, up to 30gb in some cases.  I'm writing a script to pull info and have been playing with multi process to speed it up a bit.  right now I'm testing running two functions at the same time to search from the top and bottom to get results, which seems to work.  I'm wondering if it's possible to stop one function one a result from the other.  Such as if the top function finds a result they both stop.  This way I can build it out as needed.

from file_read_backwards import FileReadBackwards
from multiprocessing import Process
import sys

z = "log.log"

#!/usr/bin/env python
rocket = 0

def top():
    target = "test"
    with open(z) as src:
        found= None
        for line in src:
            if len(line) == 0: break #happens at end of file, then stop loop
            if target in line:
                found= line
                break
    print(found)

def bottom():
    target = "text"
    with FileReadBackwards(z) as src:
        found= None
        for line in src:
            if len(line) == 0: break #happens at end of file, then stop loop
            if target in line:
                found= line
                break
    print(found)

if __name__=='__main__':
     p1 = Process(target = top)
     p1.start()
     p2 = Process(target = bottom)
     p2.start()

Body:
This is essentially the same as Blurp's answer, but I shortened it and made it a bit to make it more general. As you can see top should be an infinite loop, but bottom stops top immediately.

from multiprocessing import Process
valNotFound = True
def top():
    i=0
    while ValNotFound:
        i += 1

def bottom():
    ValNotFound = False

p1 = Process(target = top)
p2 = Process(target = bottom)
p1.start()
p2.start()


问:
Cannot find function setFullYear in object - Google Scripts
Very new to scripting. This is my second script, I basically modified a Google Sample.

Error I'm getting:
TypeError: Cannot find function setFullYear in object . (line 22, file "Code").

Script does seems to complete, as emails get sent, but I'd like to know why I'm getting the error, and what can I do to correct it.

I'm assuming the script doesn't like the date format.

Problematic code:

var dateToSend = row[0];
 dateToSend = dateToSend.setFullYear(0000);

row[0] refers to a cell on a Google Sheet with a date in it.

Full script, if it helps:

```<code>var today = new Date()
today.setHours(0,0,0,0)
today = today.setFullYear(0000) // Set year as 0, so recurs every year

var EMAIL_SENT = "EMAIL_SENT";

function sendEmailsByDate() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var dataRange = sheet.getRange('A2:E')
  var data = dataRange.getValues();
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var dateToSend = row[0];
    dateToSend = dateToSend.setFullYear(0000); // This is the problematic line 22
    var emailAddress = row[1];
    var subject = row[2];
    var message = row[3];
    var emailSent = row[4];
    if ((emailSent != EMAIL_SENT) && (today == dateToSend)) {
      MailApp.sendEmail(emailAddress, subject, message);
      sheet.getRange(startRow + i, 5).setValue(EMAIL_SENT);
      SpreadsheetApp.flush();

    }
  }
}
</code>```

答:
You have to create a date object with the row[0] data so that you can access the setFullYear function on it. Like so:</p>

```<code>  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var dateToSend = new Date(row[0]);
</code>```

Body:
Very new to scripting. This is my second script, I basically modified a Google Sample.

Error I'm getting:
TypeError: Cannot find function setFullYear in object . (line 22, file "Code").

Script does seems to complete, as emails get sent, but I'd like to know why I'm getting the error, and what can I do to correct it.

I'm assuming the script doesn't like the date format.

Problematic code:

var dateToSend = row[0];
 dateToSend = dateToSend.setFullYear(0000);

row[0] refers to a cell on a Google Sheet with a date in it.

Full script, if it helps:

var today = new Date()
today.setHours(0,0,0,0)
today = today.setFullYear(0000) // Set year as 0, so recurs every year

var EMAIL_SENT = "EMAIL_SENT";

function sendEmailsByDate() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var dataRange = sheet.getRange('A2:E')
  var data = dataRange.getValues();
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var dateToSend = row[0];
    dateToSend = dateToSend.setFullYear(0000); // This is the problematic line 22
    var emailAddress = row[1];
    var subject = row[2];
    var message = row[3];
    var emailSent = row[4];
    if ((emailSent != EMAIL_SENT) && (today == dateToSend)) {
      MailApp.sendEmail(emailAddress, subject, message);
      sheet.getRange(startRow + i, 5).setValue(EMAIL_SENT);
      SpreadsheetApp.flush();

    }
  }
}

Body:
You have to create a date object with the row[0] data so that you can access the setFullYear function on it. Like so:

  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var dateToSend = new Date(row[0]);


问:
How to get everything before and up to a certain substring within a string?
How would I return a string up to a certain character?

```<code>def get_header(s):
    '''(str) -> str
    Return the start of the given string upto and including
    </head>.'''
    return (s.split('</head>')[0])
</code>```

this is what i did but, I don't know how i would get everything before the "  "<"/heads">"" and including it.

for example:

```<code>s ="hello python world </head> , i'm a beginner "
get_header(s)
</code>```

this would return

"hello python world "<"/head">"   #without the quotient marks around the <
```

答:
This would be a fairly easy thing to do with Python's re module which matches a "regular expression" (or regex) to a string.

Here's how to use it to do what you want:

```<code>import re

def get_header(s):
    """(str) -> str
    Return the start of the given string upto and including </head>.
    """
    matches = re.search(r".*</head>", s)
    return matches.group(0) if matches else None

s = "hello python world </head> , i'm a beginner "
print(get_header(s))  # -> hello python world </head>
</code>```

Body:
How would I return a string up to a certain character?

def get_header(s):
    '''(str) -> str
    Return the start of the given string upto and including
    .'''
    return (s.split('')[0])

this is what i did but, I don't know how i would get everything before the "  "<"/heads">"" and including it.

for example:

s ="hello python world  , i'm a beginner "
get_header(s)

this would return

"hello python world "<"/head">"   #without the quotient marks around the <

Body:
This would be a fairly easy thing to do with Python's re module which matches a "regular expression" (or regex) to a string.

Here's how to use it to do what you want:

import re

def get_header(s):
    """(str) -> str
    Return the start of the given string upto and including </head>.
    """
    matches = re.search(r".*</head>", s)
    return matches.group(0) if matches else None

s = "hello python world </head> , i'm a beginner "
print(get_header(s))  # -> hello python world </head>