问:
How to assign SQLiteOpenHelper in Custom Adapter?
I have searched an answer to this question quite long, but haven't found yet.
I'm doing project with SQLiteDatabase. Everything works fine, except assigning SQLiteOpenHelper to my CustomAdapter. I'm about two months in Android studio and all that Java thing, so I'm just searching almost everything on the internet. Here are fragments of my project.

SQLiteOpenHelper:

public class ActivitiesDataBase extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "database.db";
    public static final String ACTIVITIES_COLUMN_ID = "id";
    public static final String ACTIVITIES_TABLE_NAME = "create_activity";
    public static final String ACTIVITIES_COLUMN_NAME = "activity";
    public static final String ACTIVITIES_COLUMN_NUMBER = "number";
    public static final String ACTIVITIES_COLUMN_DESCRIPTION = "description";

    //Created command to create items
    public void addactivity(String activity, String description, String number){

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv =new ContentValues();
        cv.put(ACTIVITIES_COLUMN_NAME, activity);
        cv.put(ACTIVITIES_COLUMN_NUMBER, number);
        cv.put(ACTIVITIES_COLUMN_DESCRIPTION, description);

        db.insert(ACTIVITIES_TABLE_NAME, null, cv);
        db.close();
    }

    //Constructor
        public ActivitiesDataBase(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE create_activity" +
                "(id INTEGER PRIMARY KEY, " +
                "activity TEXT, " +
                "number TEXT, " +
                "description TEXT)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS create_activity");

    }
}```
</div>
</div>
</p>

<p><strong>Small part of ActivityMain:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>public class MainActivity extends AppCompatActivity implements DrawerLocker {

//Assigning SQLiteOpenHelper, no errors, result is fine.
    final ActivitiesDataBase db = new ActivitiesDataBase(this);

    private SQLiteDatabase sql;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//Here I call command addactivity and it works fine, because I
//assigned SQLiteOpenHelper well.
    db.addactivity(activitysubject, activitydesc, activitynum);

    }
}</code>```

And here is my Custom Adapter:

public class CustomAdapter extends ArrayAdapter {

    private List sarasas = new ArrayList();

    public CustomAdapter(Context context, int resource) {
        super(context, resource);
    }

    @Override
    public void add(Object object) {
        super.add(object);
        sarasas.add(object);
    }

    @Override
    public int getCount() {
        return this.sarasas.size();
    }

    @Override
    public Object getItem(int position) {
        return this.sarasas.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

        final Duomenys pavadinimas;

        if (v == null){
            LayoutInflater inflater = (LayoutInflater) this.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            v = inflater.inflate(R.layout.listview_layout, parent, false);

            pavadinimas = new Duomenys();
//I have missed some unnecessary text here, hope it doesn't change
//contex a lot

//So, crap starts here. Don't mind that pavadinimas after dots.
//Basically it's written here similarly to MainActivity, but it
//shows errors because assigning is different :(

//           (SQLiteOpenHelper assigning is below)
pavadinimas.plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pavadinimas.db.addactivity(name, description, number);
                }
            });

            v.setTag(pavadinimas);
        }else {
            pavadinimas = (Duomenys) v.getTag();
        }

        DataActivity perdavimas = (DataActivity) this.getItem(position);
        pavadinimas.txt1.setText(perdavimas.getNamee());

        return v;

    }

    static class Duomenys{

        SQLiteDatabase sql;

        //Here i don't know how to assign my SQLiteOpenHelper,
        // so actually, I NEED HELP HERE
        ActivitiesDataBase db;

    }
}```
</div>
</div>
</p>

<p>So, I really would like to know, how to assign (if possible) SQLiteOpenHelper in Custom Adapter. Any help is apreciated.</p>

<blockquote>
  <p>So, this is my edited version. Everything is fine with static class Duomenys, but there is some underlines in that part:</p>
</blockquote>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

//Here it underlines mContext and i really don't know from where to get it
        final Duomenys pavadinimas = new Duomenys(mContext);

        if (v == null){
            LayoutInflater inflater = (LayoutInflater) this.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            v = inflater.inflate(R.layout.listview_layout, parent, false);

//Then it underlines () after Duomenys
            pavadinimas = new Duomenys();
pavadinimas.plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

pavadinimas.db.assactivity(name, description, number);

                }
            });

           v.setTag(pavadinimas);
        }else {

//And it underlines pavadinimas, saying
//"Cannot assign a value to final variable 'pavadinimas'  "
            pavadinimas = (Duomenys) v.getTag();
        }</code>```

答:
add constructor to Duomenys class

```<code>static class Duomenys{

        SQLiteDatabase sql;

        //Here i don't know how to assign my SQLiteOpenHelper,
        // so actually, I NEED HELP HERE
        ActivitiesDataBase db;
        public Duomenys(Context context){
            this.db = new ActivitiesDataBase(context);
        }

    }
</code>```

then when creating Duomenys object pass context final Duomenys pavadinimas = new Duomenys(mContext)

Body:
I have searched an answer to this question quite long, but haven't found yet.
I'm doing project with SQLiteDatabase. Everything works fine, except assigning SQLiteOpenHelper to my CustomAdapter. I'm about two months in Android studio and all that Java thing, so I'm just searching almost everything on the internet. Here are fragments of my project.

SQLiteOpenHelper:

public class ActivitiesDataBase extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "database.db";
    public static final String ACTIVITIES_COLUMN_ID = "id";
    public static final String ACTIVITIES_TABLE_NAME = "create_activity";
    public static final String ACTIVITIES_COLUMN_NAME = "activity";
    public static final String ACTIVITIES_COLUMN_NUMBER = "number";
    public static final String ACTIVITIES_COLUMN_DESCRIPTION = "description";

    //Created command to create items
    public void addactivity(String activity, String description, String number){

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv =new ContentValues();
        cv.put(ACTIVITIES_COLUMN_NAME, activity);
        cv.put(ACTIVITIES_COLUMN_NUMBER, number);
        cv.put(ACTIVITIES_COLUMN_DESCRIPTION, description);

        db.insert(ACTIVITIES_TABLE_NAME, null, cv);
        db.close();
    }

    //Constructor
        public ActivitiesDataBase(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE create_activity" +
                "(id INTEGER PRIMARY KEY, " +
                "activity TEXT, " +
                "number TEXT, " +
                "description TEXT)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS create_activity");

    }
}

Small part of ActivityMain:

public class MainActivity extends AppCompatActivity implements DrawerLocker {

//Assigning SQLiteOpenHelper, no errors, result is fine.
    final ActivitiesDataBase db = new ActivitiesDataBase(this);

    private SQLiteDatabase sql;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//Here I call command addactivity and it works fine, because I
//assigned SQLiteOpenHelper well.
    db.addactivity(activitysubject, activitydesc, activitynum);

    }
}

And here is my Custom Adapter:

public class CustomAdapter extends ArrayAdapter {

    private List sarasas = new ArrayList();

    public CustomAdapter(Context context, int resource) {
        super(context, resource);
    }

    @Override
    public void add(Object object) {
        super.add(object);
        sarasas.add(object);
    }

    @Override
    public int getCount() {
        return this.sarasas.size();
    }

    @Override
    public Object getItem(int position) {
        return this.sarasas.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

        final Duomenys pavadinimas;

        if (v == null){
            LayoutInflater inflater = (LayoutInflater) this.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            v = inflater.inflate(R.layout.listview_layout, parent, false);

            pavadinimas = new Duomenys();
//I have missed some unnecessary text here, hope it doesn't change
//contex a lot

//So, crap starts here. Don't mind that pavadinimas after dots.
//Basically it's written here similarly to MainActivity, but it
//shows errors because assigning is different :(

//           (SQLiteOpenHelper assigning is below)
pavadinimas.plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pavadinimas.db.addactivity(name, description, number);
                }
            });

            v.setTag(pavadinimas);
        }else {
            pavadinimas = (Duomenys) v.getTag();
        }

        DataActivity perdavimas = (DataActivity) this.getItem(position);
        pavadinimas.txt1.setText(perdavimas.getNamee());

        return v;

    }

    static class Duomenys{

        SQLiteDatabase sql;

        //Here i don't know how to assign my SQLiteOpenHelper,
        // so actually, I NEED HELP HERE
        ActivitiesDataBase db;

    }
}

So, I really would like to know, how to assign (if possible) SQLiteOpenHelper in Custom Adapter. Any help is apreciated.

So, this is my edited version. Everything is fine with static class Duomenys, but there is some underlines in that part:

 @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

//Here it underlines mContext and i really don't know from where to get it
        final Duomenys pavadinimas = new Duomenys(mContext);

        if (v == null){
            LayoutInflater inflater = (LayoutInflater) this.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            v = inflater.inflate(R.layout.listview_layout, parent, false);

//Then it underlines () after Duomenys
            pavadinimas = new Duomenys();
pavadinimas.plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

pavadinimas.db.assactivity(name, description, number);

                }
            });

           v.setTag(pavadinimas);
        }else {

//And it underlines pavadinimas, saying
//"Cannot assign a value to final variable 'pavadinimas'  "
            pavadinimas = (Duomenys) v.getTag();
        }

Body:
add constructor to Duomenys class

static class Duomenys{

        SQLiteDatabase sql;

        //Here i don't know how to assign my SQLiteOpenHelper,
        // so actually, I NEED HELP HERE
        ActivitiesDataBase db;
        public Duomenys(Context context){
            this.db = new ActivitiesDataBase(context);
        }

    }

then when creating Duomenys object pass context final Duomenys pavadinimas = new Duomenys(mContext)


来源: stackexchange

问:
Python class information from variable
In the following code:

```<code>class species:
    def __init__(self, continent):
        self.continent=continent

giraffe = species("africa")

animal = "giraffe"
</code>```

EDIT: animal is a string

can i retrieve "africa" from var "animal"?

答:
Yes. Both animal and giraffe are references to the same underlying object. Very much like "Jala015" and "Jala Smith" and "mom" (or dad?) might all be references to the same person.

Similarly, if you change the continent of the object via one of the references, that change will be visible through the other reference, since they both point to the same place.

Update

Now you say that animal is not a reference to an object, but a string. There are a couple of ways to do that, all of them somewhat complex.

First, if giraffe is a global (as shown in your code, it is) then it will be in the globals() dictionary. You can do this:

```<code>giraffe = species('Africa')
animal = "giraffe"

continent = globals()[animal].continent
</code>```

If giraffe is not global, but rather a local variable in a function, that won't work. You might be able to get it with locals() but even that is iffy. In that case, and in general, you should probably put this stuff in your own dictionary for lookups:

```<code>Zoo = {}  # empty dictionary

giraffe = species('Africa')

Zoo['giraffe'] = giraffe

animal = "giraffe"

continent = Zoo[animal].continent
</code>```

You can make this simpler by storing the species name in the Animal class, thus:

```<code>class Animal:
    def __init__(self, name, where):
        self.name = name
        self.continent = where
</code>```

Then you could put your objects into a deque, dict, list, set, tuple, or whatever other thing you like, and still match them by brute force:

```<code>Zoo = [ Animal('giraffe', 'Africa'), Animal('zebra', 'Africa'), Animal('Cheeto-Stained Ferret-Wearing Shitgibbon', 'North America') ]

pet = None

for animal in Zoo:
    if animal.name == 'giraffe':
        pet = animal
        break
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python class information from variable

Body:
In the following code:

class species:
    def __init__(self, continent):
        self.continent=continent

giraffe = species("africa")

animal = "giraffe"

EDIT: animal is a string

can i retrieve "africa" from var "animal"?

Body:
Yes. Both animal and giraffe are references to the same underlying object. Very much like "Jala015" and "Jala Smith" and "mom" (or dad?) might all be references to the same person.

Similarly, if you change the continent of the object via one of the references, that change will be visible through the other reference, since they both point to the same place.

Update

Now you say that animal is not a reference to an object, but a string. There are a couple of ways to do that, all of them somewhat complex.

First, if giraffe is a global (as shown in your code, it is) then it will be in the globals() dictionary. You can do this:

giraffe = species('Africa')
animal = "giraffe"

continent = globals()[animal].continent

If giraffe is not global, but rather a local variable in a function, that won't work. You might be able to get it with locals() but even that is iffy. In that case, and in general, you should probably put this stuff in your own dictionary for lookups:

Zoo = {}  # empty dictionary

giraffe = species('Africa')

Zoo['giraffe'] = giraffe

animal = "giraffe"

continent = Zoo[animal].continent

You can make this simpler by storing the species name in the Animal class, thus:

class Animal:
    def __init__(self, name, where):
        self.name = name
        self.continent = where

Then you could put your objects into a deque, dict, list, set, tuple, or whatever other thing you like, and still match them by brute force:

Zoo = [ Animal('giraffe', 'Africa'), Animal('zebra', 'Africa'), Animal('Cheeto-Stained Ferret-Wearing Shitgibbon', 'North America') ]

pet = None

for animal in Zoo:
    if animal.name == 'giraffe':
        pet = animal
        break


问:
How to simplify this regex to avoid recursion?
Regex:

```<code>(?|`(?>[^`\\]|\\.|``)*`|'(?>[^'\\]|\\.|'')*'|"(?>[^"\\]|\\.|"")*"|(\?{1,2})|(:{1,2})([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*))
</code>```

Example input:

```<code>INSERT INTO xyz WHERE
a=?
and b="what?"
and ??="cheese"
and `col?`='OK'
and ::col='another'
and last!=:least
</code>```

https://regex101.com/r/HnTVXx/6

It should match ?, ??, :xyz and ::xyz but not if they are inside of a backquoted-string, double-quoted string, or single-quoted string.

When I try running this in PHP with a very large input I get PREG_RECURSION_LIMIT_ERROR from preg_last_error().

How can I simplify this regex pattern so that it doesn't do so much recursion?

Here's some test code that shows the error in PHP using Niet's optimized regex: https://3v4l.org/GdtmP Error code 6 is PREG_JIT_STACKLIMIT_ERROR. The other one I've seen is 3=PREG_RECURSION_LIMIT_ERROR

答:
Same idea to skip quoted parts (the (*SKIP)(*F) combo), but also 2 techniques to reduce the regex engine work:

the first character discrimination

the unrolled pattern

These 2 techniques have something in common: limiting the cost of alternations.

The first character discrimination is useful when your pattern starts with an alternation. The problem with an alternation at the beginning is that each branch should be tested so that a position where the pattern fails is identified. Since most of the time, there are many failing positions in a string, discarding them quickly constitutes a significant improvement.

For instance, something like: "...|'...|`...|:... can also be written like this:

```<code>(?=["'`:])(?:"...|'...|`...|:...)
</code>```

or

```<code>["'`:](?:(?<=")...|(?<=')...|(?<=`)...|(?<=:)...)
</code>```

This way, each position that doesn't start with one of these characters ["'`:] is immediately rejected with the first token without to test each branch.

The unrolled pattern consists to rewrite something like: " (?:[^"\\]|\\.)* " into:

```<code>" [^"\\]* (?: \\. [^"\\]* )* "
</code>```

Note that this design eliminates the alternation and reduces the number of steps drastically:
basic
unrolled

Using these 2 techniques, your pattern can be written like this:

```<code>~
[`'"?:]
(?:
    (?<=`) [^`\\]*+ (?s:\\.[^`\\]*|``[^`\\]*)*+ ` (*SKIP) (*F)
  |
    (?<=') [^'\\]*+ (?s:\\.[^'\\]*|''[^'\\]*)*+ ' (*SKIP) (*F)
  |
    (?<=") [^"\\]*+ (?s:\\.[^"\\]*|""[^"\\]*)*+ " (*SKIP) (*F)
  |
    (?<=\?) \??
  |
    (?<=:) :? ([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)
)
~x
</code>```

demo

Other way: instead of using an alternation (improved or not) at the beginning, you can build a pattern that matches all the string with contiguous results. The general design is:

```<code>\G (all I don't want) (*SKIP) \K (what I am looking for)
</code>```

\G is an anchor that matches either the position after the previous result or the start of the string. Starting a pattern with it ensures that all the matches are contiguous. In this situation (at the beginning of the pattern and in factor to the whole pattern), you can also replace it with the A modifier.

That gives:

```<code>~
[^`'"?:]*
(?:
    ` [^`\\]*+ (?s:\\.[^`\\]*|``[^`\\]*)*+ ` [^`'"?:]*
  |
    ' [^'\\]*+ (?s:\\.[^'\\]*|''[^'\\]*)*+ ' [^`'"?:]*
  |
    " [^"\\]*+ (?s:\\.[^"\\]*|""[^"\\]*)*+ " [^`'"?:]*
)*
\K  # only the part of the match after this position is returned
(*SKIP) # if the next subpattern fails, the contiguity is broken at this position
(?:
    \?{1,2}
  |
    :{1,2} ([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)
)
~Ax
</code>```

demo

Body:
Regex:

(?|`(?>[^`\\]|\\.|``)*`|'(?>[^'\\]|\\.|'')*'|"(?>[^"\\]|\\.|"")*"|(\?{1,2})|(:{1,2})([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*))

Example input:

INSERT INTO xyz WHERE
a=?
and b="what?"
and ??="cheese"
and `col?`='OK'
and ::col='another'
and last!=:least

https://regex101.com/r/HnTVXx/6

It should match ?, ??, :xyz and ::xyz but not if they are inside of a backquoted-string, double-quoted string, or single-quoted string.

When I try running this in PHP with a very large input I get PREG_RECURSION_LIMIT_ERROR from preg_last_error().

How can I simplify this regex pattern so that it doesn't do so much recursion?

Here's some test code that shows the error in PHP using Niet's optimized regex: https://3v4l.org/GdtmP Error code 6 is PREG_JIT_STACKLIMIT_ERROR. The other one I've seen is 3=PREG_RECURSION_LIMIT_ERROR

Body:
Same idea to skip quoted parts (the (*SKIP)(*F) combo), but also 2 techniques to reduce the regex engine work:

the first character discrimination

the unrolled pattern

These 2 techniques have something in common: limiting the cost of alternations.

The first character discrimination is useful when your pattern starts with an alternation. The problem with an alternation at the beginning is that each branch should be tested so that a position where the pattern fails is identified. Since most of the time, there are many failing positions in a string, discarding them quickly constitutes a significant improvement.

For instance, something like: "...|'...|`...|:... can also be written like this:

(?=["'`:])(?:"...|'...|`...|:...)

or

["'`:](?:(?<=")...|(?<=')...|(?<=`)...|(?<=:)...)

This way, each position that doesn't start with one of these characters ["'`:] is immediately rejected with the first token without to test each branch.

The unrolled pattern consists to rewrite something like: " (?:[^"\\]|\\.)* " into:

" [^"\\]* (?: \\. [^"\\]* )* "

Note that this design eliminates the alternation and reduces the number of steps drastically:
basic
unrolled

Using these 2 techniques, your pattern can be written like this:

~
[`'"?:]
(?:
    (?<=`) [^`\\]*+ (?s:\\.[^`\\]*|``[^`\\]*)*+ ` (*SKIP) (*F)
  |
    (?<=') [^'\\]*+ (?s:\\.[^'\\]*|''[^'\\]*)*+ ' (*SKIP) (*F)
  |
    (?<=") [^"\\]*+ (?s:\\.[^"\\]*|""[^"\\]*)*+ " (*SKIP) (*F)
  |
    (?<=\?) \??
  |
    (?<=:) :? ([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)
)
~x

demo

Other way: instead of using an alternation (improved or not) at the beginning, you can build a pattern that matches all the string with contiguous results. The general design is:

\G (all I don't want) (*SKIP) \K (what I am looking for)

\G is an anchor that matches either the position after the previous result or the start of the string. Starting a pattern with it ensures that all the matches are contiguous. In this situation (at the beginning of the pattern and in factor to the whole pattern), you can also replace it with the A modifier.

That gives:

~
[^`'"?:]*
(?:
    ` [^`\\]*+ (?s:\\.[^`\\]*|``[^`\\]*)*+ ` [^`'"?:]*
  |
    ' [^'\\]*+ (?s:\\.[^'\\]*|''[^'\\]*)*+ ' [^`'"?:]*
  |
    " [^"\\]*+ (?s:\\.[^"\\]*|""[^"\\]*)*+ " [^`'"?:]*
)*
\K  # only the part of the match after this position is returned
(*SKIP) # if the next subpattern fails, the contiguity is broken at this position
(?:
    \?{1,2}
  |
    :{1,2} ([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)
)
~Ax

demo


问:
What is the easiest way to test/debug Symbian applications on the phone?
I am currently experimenting with programming for my Nokia 5800 XpressMusic (running Symbian 9.4). Setting up the development environment (Carbide C++) was already a huge pain, but now that I am actually able to build something the pain doesn't stop! It seems there is an incredible overhead involved when you actually want to test an application on the phone. But I really hope somebody more experienced than me knows some easy way to do it.

If I understood right every application has to be signed. I can sign applications myself, so this is not a problem and it seems to work fairly well. But then it seems not all capabilities are available if I do this, and the one I need is amongst them. So now I have the option to buy a publisher ID to get a developer certificate (current cost: 200$ - no thanks) or I have to upload the application every time to symbiansigned! Every time I change the code and want to test on the phone I have to upload the thing using a stupid web form!

But now I was excited to find that you can do some remote debugging stuff with a thing called TRK (maybe this spares me the signing?). I hoped that I could use this to connect Carbide and my phone. But this doesn't quite work. My phone doesn't show the application required for this connection although it installed properly. I had a look at the supported Symbian version number and it seems to be 9.2, so not mine :( Stuck again?

And the emulator is no option because it doesn't support sensors and cameras :(

So what am I doing wrong (and sure there must be something)? Is the only way to test my app on the phone to actually upload it every time, wait for it to getting signed, download it again, install it and test - just to see it didn't work and that I have to repeat this process over and over again?? PLEASE no...

答: follow the instructions here http://www.forum.nokia.com/Distribute/Packaging_and_signing.xhtml to get yourself a free certificate for 5 testing devices, then you can use this certificate to sign your applications directly without using open sign.</p>

ContentLicense: CC BY-SA 2.5


问:
Adapt css style from a website to a Django crispy form checkbox
I am using bootstrap, I have a Django crispy form with a checkbox in it, the html looks like this:

```<code>    <div class="form-group">
        <div class="checkbox" id="div_id_include">
            <label class="" for="id_include"><input class="checkboxinput" id="id_include" name="include" type="checkbox"> Include some data.</label>
        </div>
    </div>
</code>```

I am having trouble adapting the following css classes to this rendered html, the checkbox is completely opaque and is not visible when the following css is applied:

CSS

```<code>.checkbox-wrapper {
position: relative;
}

td .checkbox-wrapper, th .checkbox-wrapper {
    margin: 0 0 0 6px;
}

.checkbox, input[type=checkbox].checkbox, .checkbox-styled {
    display: block;
    position: relative;
    height: 16px;
    width: 16px;
    border: 1px solid #d3dbe2;
    background-color: #ffffff;
    margin: 0;
    box-sizing: border-box;
    vertical-align: middle;
}

.checkbox, input[type=checkbox].checkbox {
    z-index: 2;
    opacity: 0
}

.checkbox-styled {
    border-radius: 3px;
    z-index: 1
}

.checkbox-styled:after {
    content: "";
    display: block;
    height: 10px;
    width: 10px;
    position: absolute;
    top: 50%;
    left: 50%;
    background-color: transparent;
    background-position: center center;
    background-size: cover;
    background-repeat: no-repeat;
    -webkit-transform: translate(-50%, -50%) scale(0);
    -ms-transform: translate(-50%, -50%) scale(0);
    transform: translate(-50%, -50%) scale(0);
    -webkit-transition: -webkit-transform 0.15s ease-in-out;
    transition: transform 0.15s ease-in-out;
    z-index: 2
}

.checkbox:active ~ .checkbox-styled, .checkbox:focus ~ .checkbox-styled {
    border-color: #479ccf
}

.checkbox:checked ~ .checkbox-styled:after {
    -webkit-transform: translate(-50%, -50%) scale(1);
    -ms-transform: translate(-50%, -50%) scale(1);
    transform: translate(-50%, -50%) scale(1)
}

.checkbox:indeterminate ~ .checkbox-styled:after {
    -webkit-transform: translate(-50%, -50%) scale(1);
    -ms-transform: translate(-50%, -50%) scale(1);
    transform: translate(-50%, -50%) scale(1)
    }

.checkbox-styled:after {
    background-image: url(data:image/svg+xml;charset=US-        ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20enable-background%3D%22new%200%200%2024%2024%22%3E%3Cstyle%20type%3D%22text%2Fcss%22%3Ecircle%2Cellipse%2Cline%2Cpath%2Cpolygon%2Cpolyline%2Crect%2Ctext%7Bfill%3A%23479ccf%20%21important%3B%20%7D%3C%2Fstyle%3E%3Cpath%20d%3D%22M23.6%205L22%203.4c-.5-.4-1.2-.4-1.7%200L8.5%2015l-4.8-4.7c-.5-.4-1.2-.4-1.7%200L.3%2011.9c-.5.4-.5%201.2%200%201.6l7.3%207.1c.5.4%201.2.4%201.7%200l14.3-14c.5-.4.5-1.1%200-1.6z%22%2F%3E%3C%2Fsvg%3E)
}

.checkbox:indeterminate ~ .checkbox-styled:after {
    background-image: url(data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2012%2012%22%20enable-background%3D%22new%200%200%2012%2012%22%3E%3Cstyle%20type%3D%22text%2Fcss%22%3Ecircle%2Cellipse%2Cline%2Cpath%2Cpolygon%2Cpolyline%2Crect%2Ctext%7Bfill%3A%23479ccf%20%21important%3B%20%7D%3C%2Fstyle%3E%3Cpath%20d%3D%22M6%200%22%2F%3E%3Cpath%20d%3D%22M.8%207C.3%207%200%206.7%200%206.2v-.4c0-.5.3-.8.8-.8h10.5c.4%200%20.7.3.7.8v.5c0%20.4-.3.7-.8.7H.8z%22%2F%3E%3C%2Fsvg%3E)
}
</code>```

The style is from here: Shopify embedded app css (where you can also see examples of the checkbox).

If have this working when I don't use Crispy forms but I output the html directly (within a table row):

```<code><td>
    <div class="checkbox-wrapper"><input class="checkbox" type="checkbox" id="id" name="" value="id"><span class="checkbox-styled"></span></div>
</td>
</code>```

答:
Well, there was no lazy way to do this. I solved this by ensuring that I followed the html layout provided by the embedded app css that I referenced in my post, and then customzing my crispy forms field template for checkboxes to ensure that it rendered html with the correct layout:</p>

```<code><div class="input-wrapper inline">
  <div class="checkbox-wrapper"><input class="checkbox" type="checkbox" id="check1" name="check1" value=""><span class="checkbox-styled"></span></div>
  <label for="check1">Check 1</label>
</div>
</code>```

Body:
I am using bootstrap, I have a Django crispy form with a checkbox in it, the html looks like this:

            <input class="checkboxinput" id="id_include" name="include" type="checkbox"> Include some data.

I am having trouble adapting the following css classes to this rendered html, the checkbox is completely opaque and is not visible when the following css is applied:

CSS

.checkbox-wrapper {
position: relative;
}

td .checkbox-wrapper, th .checkbox-wrapper {
    margin: 0 0 0 6px;
}

.checkbox, input[type=checkbox].checkbox, .checkbox-styled {
    display: block;
    position: relative;
    height: 16px;
    width: 16px;
    border: 1px solid #d3dbe2;
    background-color: #ffffff;
    margin: 0;
    box-sizing: border-box;
    vertical-align: middle;
}

.checkbox, input[type=checkbox].checkbox {
    z-index: 2;
    opacity: 0
}

.checkbox-styled {
    border-radius: 3px;
    z-index: 1
}

.checkbox-styled:after {
    content: "";
    display: block;
    height: 10px;
    width: 10px;
    position: absolute;
    top: 50%;
    left: 50%;
    background-color: transparent;
    background-position: center center;
    background-size: cover;
    background-repeat: no-repeat;
    -webkit-transform: translate(-50%, -50%) scale(0);
    -ms-transform: translate(-50%, -50%) scale(0);
    transform: translate(-50%, -50%) scale(0);
    -webkit-transition: -webkit-transform 0.15s ease-in-out;
    transition: transform 0.15s ease-in-out;
    z-index: 2
}

.checkbox:active ~ .checkbox-styled, .checkbox:focus ~ .checkbox-styled {
    border-color: #479ccf
}

.checkbox:checked ~ .checkbox-styled:after {
    -webkit-transform: translate(-50%, -50%) scale(1);
    -ms-transform: translate(-50%, -50%) scale(1);
    transform: translate(-50%, -50%) scale(1)
}

.checkbox:indeterminate ~ .checkbox-styled:after {
    -webkit-transform: translate(-50%, -50%) scale(1);
    -ms-transform: translate(-50%, -50%) scale(1);
    transform: translate(-50%, -50%) scale(1)
    }

.checkbox-styled:after {
    background-image: url(data:image/svg+xml;charset=US-        ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20enable-background%3D%22new%200%200%2024%2024%22%3E%3Cstyle%20type%3D%22text%2Fcss%22%3Ecircle%2Cellipse%2Cline%2Cpath%2Cpolygon%2Cpolyline%2Crect%2Ctext%7Bfill%3A%23479ccf%20%21important%3B%20%7D%3C%2Fstyle%3E%3Cpath%20d%3D%22M23.6%205L22%203.4c-.5-.4-1.2-.4-1.7%200L8.5%2015l-4.8-4.7c-.5-.4-1.2-.4-1.7%200L.3%2011.9c-.5.4-.5%201.2%200%201.6l7.3%207.1c.5.4%201.2.4%201.7%200l14.3-14c.5-.4.5-1.1%200-1.6z%22%2F%3E%3C%2Fsvg%3E)
}

.checkbox:indeterminate ~ .checkbox-styled:after {
    background-image: url(data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2012%2012%22%20enable-background%3D%22new%200%200%2012%2012%22%3E%3Cstyle%20type%3D%22text%2Fcss%22%3Ecircle%2Cellipse%2Cline%2Cpath%2Cpolygon%2Cpolyline%2Crect%2Ctext%7Bfill%3A%23479ccf%20%21important%3B%20%7D%3C%2Fstyle%3E%3Cpath%20d%3D%22M6%200%22%2F%3E%3Cpath%20d%3D%22M.8%207C.3%207%200%206.7%200%206.2v-.4c0-.5.3-.8.8-.8h10.5c.4%200%20.7.3.7.8v.5c0%20.4-.3.7-.8.7H.8z%22%2F%3E%3C%2Fsvg%3E)
}

The style is from here: Shopify embedded app css (where you can also see examples of the checkbox).

If have this working when I don't use Crispy forms but I output the html directly (within a table row):

<input class="checkbox" type="checkbox" id="id" name="" value="id">

Body:
Well, there was no lazy way to do this. I solved this by ensuring that I followed the html layout provided by the embedded app css that I referenced in my post, and then customzing my crispy forms field template for checkboxes to ensure that it rendered html with the correct layout:

<div class="input-wrapper inline">
  <div class="checkbox-wrapper"><input class="checkbox" type="checkbox" id="check1" name="check1" value=""><span class="checkbox-styled"></span></div>
  <label for="check1">Check 1</label>
</div>


问:
I Cannot Locate World Wide Web Publishing Service in Services on Windows 10
Please bear with me, I'm not 100% tech savvy - yet. When I try to run XAMPP (in order to experiment with local WordPress), everything runs except Apache. All the current data on the issue points me to stop the "World Wide Web Publishing Service" from "Services" in Windows 10.

However, I have found that the World Wide Web Publishing Service is missing from services, I have looked in both the Standard and Extended list, and it simply isn't there, neither is the variant "W3SVC."

I have also tried an entire search of my pc for both phrases and I came up empty. Please assist, I'm stuck and I have no idea where to go from here.

答:
go to start -> programs and features -> turn Windows features on or off and enable:
i. Internet Information Services
ii. Internet Information Services Hostable Web Core.

Refresh Services

Done!


问:
Get azure b2c custom claims in angular application
I have custom claim say email . I use hello js to login from a angular app.

```<code>var authResponse = hello(helloNetwork.adB2CSignInSignUp).getAuthResponse();
</code>```

The above code gives me the token but i am not getting the email claim that i have added.

How can I get the custom claim that i have configured .

答:
In order to get custom claims, you need to edit the policy and select "Email address" under the Application Claims blade. (See image in link below)

Please verify that is enabled for the policy that you are calling. If you have it enabled and it still doing that, can you please send a screenshot of the portal and a resulting token (that does not have the email address claim).

Screenshot of azure portal

Body:
I have custom claim say email . I use hello js to login from a angular app.

var authResponse = hello(helloNetwork.adB2CSignInSignUp).getAuthResponse();

The above code gives me the token but i am not getting the email claim that i have added.

How can I get the custom claim that i have configured .


问:
Cant connect to a SQL datasource in Visual Studio using Web Forms
I am attempting to populate a drop down list, and I think I am doing it the right way. I am using Web Forms on Visual Studio.I have my drop down list, and my databases set up correctly in the server explorer on Visual Studio 2015. Once I try and create a Sql data source (I'm using MySQl by the way) I get this error.
my error and I've watched videos on how to do this and I'm pretty sure I'm following the right instructions but don't know how to fix this error. Thank you for the help!</p>

答: Check for connection string in web.config. I think its empty.</p>


问:
Fabric.js: Problems with stroke color and width svg files on canvas
I'm using in my project fabricJS and I have problem to change stroke color and  width. I have some SVG files on my page and after clicking user can add this SVG to canvas and modify its properties. With fill it works perfectly but with stroke I can't do the same. This is code for fill and it is working good:

```<code>function setImageColor(element)
{
    var activeObject = canvas.getActiveObject(),
    color = "#"+element.value;

    console.log(color)
    console.log(activeObject)
    activeObject.set({fill : color});
    canvas.renderAll();
}

jscolor.addEventListener('change', function()
{
    setImageColor(this);
});
</code>```

Here is code for loading SVG elements on canvas:

```<code>shapes.forEach(function(e)
{
    e.addEventListener("click", function()
    {
        var src = e.src;
        fabric.loadSVGFromURL( src, function(objects, options)
        {
            var obj = fabric.util.groupSVGElements(objects, options);
            canvas.add(obj).renderAll();
            obj.scaleToHeight(127)
                .scaleToWidth(90)
                .center()
                .setCoords();
            canvas.setActiveObject(obj).renderAll();
        });
    });
});
</code>```

and here is code for the stroke and it is not working:

```<code>function setStrokeColor(element)
{
    color = "#"+element.value;
    var obj = canvas.getActiveObject();
    console.log(color)
    console.log(activeObject)
    activeObject.set({stroke : color, strokeWidth: 5});
    canvas.renderAll();
}

var stroke = document.getElementById("stroke");
console.log(stroke)

stroke.addEventListener('change', function()
{
    setStrokeColor(this);
});
</code>```

答:
This should do it (thanks for the SVG Path export):

Here's the FabricJS code:

```<code>fabric.loadSVGFromString('<svg id="Warstwa_1" data-name="Warstwa 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 70 70"><defs><style>.cls-1{fill:none;stroke:#000;stroke-miterlimit:10;}</style></defs><title>generator ikon</title><path class="cls-1" d="M60,35A25,25,0,1,1,35,10,25,25,0,0,1,60,35Z"/></svg>', function(objects, options) {
  var shape = fabric.util.groupSVGElements(objects, options);
  shape.set({
    left: 50,
    top: 50,
    scaleX: 3,
    scaleY: 3
  });
  if (shape.paths) {
    for (var i = 0; i < shape.paths.length; i++) {
      shape.paths[i].set({
        fill: 'red',
        stroke: 'green',
        strokeWidth: 5
      });
    }
  }
  object = shape;
  canvas.add(shape);
  canvas.renderAll();
});
var switchColors = true;
document.getElementsByTagName("button")[0].addEventListener('click', function() {
  if (object.paths) {
    for (var i = 0; i < object.paths.length; i++) {
      object.paths[i].set({
        fill: (switchColors ? 'green' : 'red'),
        stroke: (switchColors ? 'red' : 'green'),
        strokeWidth: (switchColors ? 10 : 5)
      });
    }
  }
  switchColors = !switchColors;
  canvas.renderAll();
});
</code>```

Here's the all important JSFiddle, https://jsfiddle.net/rekrah/wg2qxc8e/.

Let me know if you have anymore questions.  I hope it helps!

Body:
I'm using in my project fabricJS and I have problem to change stroke color and  width. I have some SVG files on my page and after clicking user can add this SVG to canvas and modify its properties. With fill it works perfectly but with stroke I can't do the same. This is code for fill and it is working good:

function setImageColor(element)
{
    var activeObject = canvas.getActiveObject(),
    color = "#"+element.value;

    console.log(color)
    console.log(activeObject)
    activeObject.set({fill : color});
    canvas.renderAll();
}

jscolor.addEventListener('change', function()
{
    setImageColor(this);
});

Here is code for loading SVG elements on canvas:

shapes.forEach(function(e)
{
    e.addEventListener("click", function()
    {
        var src = e.src;
        fabric.loadSVGFromURL( src, function(objects, options)
        {
            var obj = fabric.util.groupSVGElements(objects, options);
            canvas.add(obj).renderAll();
            obj.scaleToHeight(127)
                .scaleToWidth(90)
                .center()
                .setCoords();
            canvas.setActiveObject(obj).renderAll();
        });
    });
});

and here is code for the stroke and it is not working:

function setStrokeColor(element)
{
    color = "#"+element.value;
    var obj = canvas.getActiveObject();
    console.log(color)
    console.log(activeObject)
    activeObject.set({stroke : color, strokeWidth: 5});
    canvas.renderAll();
}

var stroke = document.getElementById("stroke");
console.log(stroke)

stroke.addEventListener('change', function()
{
    setStrokeColor(this);
});

Body:
This should do it (thanks for the SVG Path export):

Here's the FabricJS code:

fabric.loadSVGFromString('<svg id="Warstwa_1" data-name="Warstwa 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 70 70"><defs><style>.cls-1{fill:none;stroke:#000;stroke-miterlimit:10;}</style></defs><title>generator ikon</title><path class="cls-1" d="M60,35A25,25,0,1,1,35,10,25,25,0,0,1,60,35Z"/></svg>', function(objects, options) {
  var shape = fabric.util.groupSVGElements(objects, options);
  shape.set({
    left: 50,
    top: 50,
    scaleX: 3,
    scaleY: 3
  });
  if (shape.paths) {
    for (var i = 0; i < shape.paths.length; i++) {
      shape.paths[i].set({
        fill: 'red',
        stroke: 'green',
        strokeWidth: 5
      });
    }
  }
  object = shape;
  canvas.add(shape);
  canvas.renderAll();
});
var switchColors = true;
document.getElementsByTagName("button")[0].addEventListener('click', function() {
  if (object.paths) {
    for (var i = 0; i < object.paths.length; i++) {
      object.paths[i].set({
        fill: (switchColors ? 'green' : 'red'),
        stroke: (switchColors ? 'red' : 'green'),
        strokeWidth: (switchColors ? 10 : 5)
      });
    }
  }
  switchColors = !switchColors;
  canvas.renderAll();
});

Here's the all important JSFiddle, https://jsfiddle.net/rekrah/wg2qxc8e/.

Let me know if you have anymore questions.  I hope it helps!


问:
How to make a reverse string using a for loop?
I need to have my code output the String in reverse order. For example, the output should have "code" return as "edoc". This is what I have done so far.</p>

```<code>public String reverseString(String str) {
 String res = "";

for (int i = 0; i <= str.length()-1; i++) {
   res = res + str.charAt(i);
 }
  return res;
}
</code>```

答:
The main issue with your way of doing it is your taking the n'th character from str and appending it to make it the n'th character of res.

You could fix it like this:

```<code>public String reverseString(String str) {
   String res = "";

   for (int i = str.length() - 1; i >= 0; i--) {
       res = res + str.charAt(i);
   }
   return res;
}
</code>```

Body:
I need to have my code output the String in reverse order. For example, the output should have "code" return as "edoc". This is what I have done so far.

public String reverseString(String str) {
 String res = "";

for (int i = 0; i <= str.length()-1; i++) {
   res = res + str.charAt(i);
 }
  return res;
}

Body:
The main issue with your way of doing it is your taking the n'th character from str and appending it to make it the n'th character of res.

You could fix it like this:

public String reverseString(String str) {
   String res = "";

   for (int i = str.length() - 1; i >= 0; i--) {
       res = res + str.charAt(i);
   }
   return res;
}


问:
Programatically select a marker with jQuery Store Locator Plugin
I'm trying to programatically select a marker on a map with the jQuery Store Locator Plugin.

I have a jQuery click event that should trigger a marker selection.

```<code>// Init
$('#bh-sl-map-container').storeLocator({ //settings })

$('.select-head-office').click(function() {
  // Here I'd like to select a specific marker,
  // Ideally, select a marker from a unique category. Ex: Head office
});
</code>```

The plugin has the method changeSelectedMarker(), not sure if I could use it to solve my problem.

答:
I finally figured a solution. It's a little hackish but it works well.

First, I realized I could use the list of locations to get the markers IDs, and associate them with the location category.

```<code><li data-markerid="{{markerid}}" data-marker-category="{{category}}">
</code>```

Then, with jQuery, I select get the markerId for the location with the category 'head-office'. (Ideally, a unique category)

```<code>$('*[data-marker-category='head-office']').data('markerid');
</code>```

I created a custom method to pan to the selected marker.

```<code>selectMarker: function(markerId) {
 var _this = this;
 var map = _this.map;
 var infowindow = _this.infowindow;
 var storeStart = _this.storeStart;
 var page = _this.page;
 var selectedMarker = markers[markerId];

 map.panTo(selectedMarker.getPosition());
 if (_this.settings.bounceMarker === true) {
  selectedMarker.setAnimation(google.maps.Animation.BOUNCE);
  setTimeout(function () {
    selectedMarker.setAnimation(null);
  }, 1200);
 }
}
</code>```

Finally, I call my method with the markerid variable I got earlier.

```<code>storeLocator = $map_container.data('plugin_storeLocator');
storeLocator.selectMarker(activeMarkerID);
</code>```

Body:
I'm trying to programatically select a marker on a map with the jQuery Store Locator Plugin.

I have a jQuery click event that should trigger a marker selection.

// Init
$('#bh-sl-map-container').storeLocator({ //settings })

$('.select-head-office').click(function() {
  // Here I'd like to select a specific marker,
  // Ideally, select a marker from a unique category. Ex: Head office
});

The plugin has the method changeSelectedMarker(), not sure if I could use it to solve my problem.

Body:
I finally figured a solution. It's a little hackish but it works well.

First, I realized I could use the list of locations to get the markers IDs, and associate them with the location category.

<li data-markerid="{{markerid}}" data-marker-category="{{category}}">

Then, with jQuery, I select get the markerId for the location with the category 'head-office'. (Ideally, a unique category)

$('*[data-marker-category='head-office']').data('markerid');

I created a custom method to pan to the selected marker.

selectMarker: function(markerId) {
 var _this = this;
 var map = _this.map;
 var infowindow = _this.infowindow;
 var storeStart = _this.storeStart;
 var page = _this.page;
 var selectedMarker = markers[markerId];

 map.panTo(selectedMarker.getPosition());
 if (_this.settings.bounceMarker === true) {
  selectedMarker.setAnimation(google.maps.Animation.BOUNCE);
  setTimeout(function () {
    selectedMarker.setAnimation(null);
  }, 1200);
 }
}

Finally, I call my method with the markerid variable I got earlier.

storeLocator = $map_container.data('plugin_storeLocator');
storeLocator.selectMarker(activeMarkerID);


问:
PHP: Getting MYSQLI_CLIENT_COMPRESS to work
I can connect to my database with mysqli.  But when I add the MYSQL_CLIENT_COMPRESS flag it does not connect.

I'm using PHP 7.0.10, MySQL 5.7.14, and a WAMP installation on Windows 8.1.

I've been using:

```<code>$db=mysqli_connect($sHost, $sUsername, $sPassword, $sDatabase, MYSQLI_CLIENT_COMPRESS);
</code>```

I get the following connection error

Debugging errno: 2002

  Debugging error: No connection could be made
  because the target machine actively refused it.

答:
This works:

```<code>$db = mysqli_init();
$db->real_connect($sHost, $sUsername, $sPassword, $sDatabase, 0, '',  MYSQLI_CLIENT_COMPRESS);
</code>```

This also works:

```<code>global $db;
$db=new mysqli($sHost, $sUsername, $sPassword, $sDatabase, 0, '', MYSQLI_CLIENT_COMPRESS);
</code>```

Body:
I can connect to my database with mysqli.  But when I add the MYSQL_CLIENT_COMPRESS flag it does not connect.

I'm using PHP 7.0.10, MySQL 5.7.14, and a WAMP installation on Windows 8.1.

I've been using:

$db=mysqli_connect($sHost, $sUsername, $sPassword, $sDatabase, MYSQLI_CLIENT_COMPRESS);

I get the following connection error

Debugging errno: 2002

  Debugging error: No connection could be made
  because the target machine actively refused it.

Body:
This works:

$db = mysqli_init();
$db->real_connect($sHost, $sUsername, $sPassword, $sDatabase, 0, '',  MYSQLI_CLIENT_COMPRESS);

This also works:

global $db;
$db=new mysqli($sHost, $sUsername, $sPassword, $sDatabase, 0, '', MYSQLI_CLIENT_COMPRESS);


问:
Swift 3 unwind segue from view controller C to A also executes code of view controller B
ViewController A has the function:

@IBAction fund backToViewControllerA (segue: UIStoryboardSegue) {}

ViewController C: via storyboard a unwind segue was created (view controller to exit, with an identifier and action)

When going from A to B to C and then pressing the button in C to start the unwind, the ViewController C unwinds to A. So far so good...

Problem: in the meantime, during the unwind, also the viewDidAppear() of B is executed.

Question: how do I prevent the code of ViewController B to be executed?

答:
You are doing something wrong. I just created this example project to show that it is not the case.

https://github.com/Sethmr/TestUnwindSegue

Download it and see that viewDidAppear() in view controller B never gets called.


问:
jquery css selector to match elements with id contains specific text after the last dot
I need to write css selector for jquery that matches elements with id that contains some text after the last dot.
Something that resembles  $(div[id*='cow']) - but stronger because I need it to match only if the text is after last dot.
So take everything after the last dot and see if the text contains my string.
For example text to look for - cow

```<code><div id ='my.very.first.cow'></div> // get it
<div id = 'my.very.first.cowandcat'></div> //get it
<div id = 'my.very.firstcow.andcat'></div> //DON'T get it - not after the last dot
</code>```

答:
im not shure if i understand your problem but try this if helps.

$("div").each(function(){
 var item = $(this);
  var arr = item.attr("id").split('.');
  console.log(arr)
  n = arr[arr.length-1].indexOf("cow");
  if(n!=-1)
  {
   alert(item.attr("id"));
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id ='my.very.first.cow'></div> // get it
<div id = 'my.very.first.cowandcat'></div> //get it
<div id = 'my.very.firstcow.andcat'></div> //DON'T get it - not after the last dot</code>```

Body:
I need to write css selector for jquery that matches elements with id that contains some text after the last dot.
Something that resembles  $(div[id*='cow']) - but stronger because I need it to match only if the text is after last dot.
So take everything after the last dot and see if the text contains my string.
For example text to look for - cow

 // get it

 //get it

 //DON'T get it - not after the last dot

Body:
im not shure if i understand your problem but try this if helps.

$("div").each(function(){
 var item = $(this);
  var arr = item.attr("id").split('.');
  console.log(arr)
  n = arr[arr.length-1].indexOf("cow");
  if(n!=-1)
  {
   alert(item.attr("id"));
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id ='my.very.first.cow'></div> // get it
<div id = 'my.very.first.cowandcat'></div> //get it
<div id = 'my.very.firstcow.andcat'></div> //DON'T get it - not after the last dot


问:
Yii2 - Updating single field of another model from update form
Longtime passive user of StackExchange and I am at a loss here. It's probably super simple, but I'm stuck. I've used gii-enhanced to build the models and CRUD.

I have two models: ordenes and facturas.

When I'm updating a facturas model I can link it to an already
existing ordenes model.

A facturas model can be linked to an ordenes model.

Ordenes has an amount field and so does facturas.

What I currently have: I can link a facturas model to an already existing ordenes model. One facturas model can have only one ordenes model, while an ordenes model can have more than one facturas model linked to it.

What I'd like to achieve is that when I link a facturas model to an ordenes model the amount from the facturas model is subtracted from the amount of the ordenes model and the new value saved to the ordenes table. So, if I already have a ordenes model with an amount of, say $200000, and link to it a facturas model with an amount of $150000, the updated ordenes model should have an amount of $50000.

The relevant code in facturasController:

```<code>public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
            return $this->redirect(['view', 'id' => $model->idfacturas]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }
</code>```

The relevant field in the view:

```<code><?= $form->field($model, 'ordenes_idordenes')->widget(\kartik\widgets\Select2::classname(), [
        'data' => \yii\helpers\ArrayHelper::map(\frontend\models\Ordenes::find()->orderBy('idordenes')->asArray()->all(), 'idordenes', 'numero'),
        'options' => ['placeholder' => Yii::t('app', 'Vincular Orden de Compra')],
        'pluginOptions' => [
            'allowClear' => true
        ],
    ]); ?>
</code>```

The relevant parts of the facturas Model:

```<code>    /**
     * @return \yii\db\ActiveQuery
     */
    public function getOrdenesIdordenes()
    {
        return $this->hasOne(\frontend\models\Ordenes::className(), ['idordenes' => 'ordenes_idordenes'])->inverseOf('facturas');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProveedoresIdproveedores()
    {
        return $this->hasOne(\frontend\models\Proveedores::className(), ['idproveedores' => 'proveedores_idproveedores'])->inverseOf('facturas');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    /*public function getUserIduser()
    {
        return $this->hasOne(\frontend\models\User::className(), ['id' => 'user_iduser'])->inverseOf('facturas');
    }*/
    public function getUserIduser()
    {
        return $this->hasOne(\backend\models\User::className(), ['id' => 'user_iduser'])->inverseOf('facturas');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getOrdenes()
    {
        return $this->hasMany(\frontend\models\Ordenes::className(), ['facturas_idfacturas' => 'idfacturas'])->inverseOf('facturasIdfacturas');
    }

     /**
    * @return \yii\db\ActiveQuery
    */
   public function getEstadosContab()
   {
       return $this->hasOne(\frontend\models\EstadosContab::className(), ['idcontab' => 'estados_contab'])->inverseOf('facturas');
   }

/**
     * @inheritdoc
     * @return array mixed
     */
    public function behaviors()
    {
        return [
            'blameable' => [
                'class' => BlameableBehavior::className(),
                'createdByAttribute' => 'user_crea',
                'updatedByAttribute' => 'user_modif',
            ],
            'uuid' => [
                'class' => UUIDBehavior::className(),
                'column' => 'idfacturas',
            ],
        ];
    }

    /**
     * @inheritdoc
     * @return \frontend\models\FacturasQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \frontend\models\FacturasQuery(get_called_class());
    }
}
</code>```

And the relevant parts of the Ordenes Model:

```<code> /**
     * @return \yii\db\ActiveQuery
     */
    public function getFacturas()
    {
        return $this->hasMany(\frontend\models\Facturas::className(), ['ordenes_idordenes' => 'idordenes'])->inverseOf('ordenesIdordenes');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getNotas()
    {
        return $this->hasMany(\frontend\models\Notas::className(), ['ordenes_idordenes' => 'idordenes'])->inverseOf('ordenesIdordenes');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getEstado()
    {
        return $this->hasOne(\frontend\models\Estados::className(), ['idestados' => 'estado_id'])->inverseOf('ordenes');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getNotasIdnotas()
    {
        return $this->hasOne(\frontend\models\Notas::className(), ['idnotas' => 'notas_idnotas'])->inverseOf('ordenes');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getFacturasIdfacturas()
    {
        return $this->hasOne(\frontend\models\Facturas::className(), ['idfacturas' => 'facturas_idfacturas'])->inverseOf('ordenes');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProveedoresIdproveedores()
    {
        return $this->hasOne(\frontend\models\Proveedores::className(), ['idproveedores' => 'proveedores_idproveedores'])->inverseOf('ordenes');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTipocompra()
    {
        return $this->hasOne(\frontend\models\TipoCompra::className(), ['category_id' => 'tipocompra_id'])->inverseOf('ordenes');
    }

/**
     * @inheritdoc
     * @return array mixed
     */
    public function behaviors()
    {
        return [
            'blameable' => [
                'class' => BlameableBehavior::className(),
                'createdByAttribute' => 'created_by',
                'updatedByAttribute' => 'updated_by',
            ],
            'uuid' => [
                'class' => UUIDBehavior::className(),
                'column' => 'idordenes',
            ],
        ];
    }

    /**
     * @inheritdoc
     * @return \frontend\models\OrdenesQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \frontend\models\OrdenesQuery(get_called_class());
    }
}
</code>```

答:
This is just a suggestion

you should populate model Facturas retriving the facturas related  to this orders  and then assign properly the value you need  to the facturas model

```<code>use common\models\Facturas;

public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->loadAll(Yii::$app->request->post()){
           $modelFacturas = Facturas::find()
             ->(['your_id_fatcuras' => $model->your_id_facturas ])->one();
           $modelFacturas->you_field_to_change =  $model->value1 - $modelFacturas->value2;
           $model->save();
           $modelFacturas->save();

           return $this->redirect(['view', 'id' => $model->idfacturas]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }
</code>```

based  on your last comment this could be a more precise answer  to your question

Assuming you Orders Model is name Orders
and in Facturas you have a field named  fk_orders where you pass the value selectd by user in the view and that can link  the  related  order

Then in Facturas Controller you can

```<code>use common\models\Orders;

public function actionUpdate($id)
    {
        $model = $this->findModel($id); // retrive the Factursa model

        if ($model->loadAll(Yii::$app->request->post()){
           $modelOrders = Orders::find()
             ->(['id_orders' => $model->fk_orders ])->one();
           $modelOrders->amount  =  $modelOrders->amount - $model->value_to_subtract;
           $model->save();
           $modelOrders->save();

           return $this->redirect(['view', 'id' => $model->idfacturas]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }
</code>```

Body:
Longtime passive user of StackExchange and I am at a loss here. It's probably super simple, but I'm stuck. I've used gii-enhanced to build the models and CRUD.

I have two models: ordenes and facturas.

When I'm updating a facturas model I can link it to an already
existing ordenes model.

A facturas model can be linked to an ordenes model.

Ordenes has an amount field and so does facturas.

What I currently have: I can link a facturas model to an already existing ordenes model. One facturas model can have only one ordenes model, while an ordenes model can have more than one facturas model linked to it.

What I'd like to achieve is that when I link a facturas model to an ordenes model the amount from the facturas model is subtracted from the amount of the ordenes model and the new value saved to the ordenes table. So, if I already have a ordenes model with an amount of, say $200000, and link to it a facturas model with an amount of $150000, the updated ordenes model should have an amount of $50000.

The relevant code in facturasController:

public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
            return $this->redirect(['view', 'id' => $model->idfacturas]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

The relevant field in the view:

<?= $form->field($model, 'ordenes_idordenes')->widget(\kartik\widgets\Select2::classname(), [
        'data' => \yii\helpers\ArrayHelper::map(\frontend\models\Ordenes::find()->orderBy('idordenes')->asArray()->all(), 'idordenes', 'numero'),
        'options' => ['placeholder' => Yii::t('app', 'Vincular Orden de Compra')],
        'pluginOptions' => [
            'allowClear' => true
        ],
    ]); ?>

The relevant parts of the facturas Model:

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getOrdenesIdordenes()
    {
        return $this->hasOne(\frontend\models\Ordenes::className(), ['idordenes' => 'ordenes_idordenes'])->inverseOf('facturas');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProveedoresIdproveedores()
    {
        return $this->hasOne(\frontend\models\Proveedores::className(), ['idproveedores' => 'proveedores_idproveedores'])->inverseOf('facturas');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    /*public function getUserIduser()
    {
        return $this->hasOne(\frontend\models\User::className(), ['id' => 'user_iduser'])->inverseOf('facturas');
    }*/
    public function getUserIduser()
    {
        return $this->hasOne(\backend\models\User::className(), ['id' => 'user_iduser'])->inverseOf('facturas');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getOrdenes()
    {
        return $this->hasMany(\frontend\models\Ordenes::className(), ['facturas_idfacturas' => 'idfacturas'])->inverseOf('facturasIdfacturas');
    }

     /**
    * @return \yii\db\ActiveQuery
    */
   public function getEstadosContab()
   {
       return $this->hasOne(\frontend\models\EstadosContab::className(), ['idcontab' => 'estados_contab'])->inverseOf('facturas');
   }

/**
     * @inheritdoc
     * @return array mixed
     */
    public function behaviors()
    {
        return [
            'blameable' => [
                'class' => BlameableBehavior::className(),
                'createdByAttribute' => 'user_crea',
                'updatedByAttribute' => 'user_modif',
            ],
            'uuid' => [
                'class' => UUIDBehavior::className(),
                'column' => 'idfacturas',
            ],
        ];
    }

    /**
     * @inheritdoc
     * @return \frontend\models\FacturasQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \frontend\models\FacturasQuery(get_called_class());
    }
}

And the relevant parts of the Ordenes Model:

 /**
     * @return \yii\db\ActiveQuery
     */
    public function getFacturas()
    {
        return $this->hasMany(\frontend\models\Facturas::className(), ['ordenes_idordenes' => 'idordenes'])->inverseOf('ordenesIdordenes');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getNotas()
    {
        return $this->hasMany(\frontend\models\Notas::className(), ['ordenes_idordenes' => 'idordenes'])->inverseOf('ordenesIdordenes');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getEstado()
    {
        return $this->hasOne(\frontend\models\Estados::className(), ['idestados' => 'estado_id'])->inverseOf('ordenes');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getNotasIdnotas()
    {
        return $this->hasOne(\frontend\models\Notas::className(), ['idnotas' => 'notas_idnotas'])->inverseOf('ordenes');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getFacturasIdfacturas()
    {
        return $this->hasOne(\frontend\models\Facturas::className(), ['idfacturas' => 'facturas_idfacturas'])->inverseOf('ordenes');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProveedoresIdproveedores()
    {
        return $this->hasOne(\frontend\models\Proveedores::className(), ['idproveedores' => 'proveedores_idproveedores'])->inverseOf('ordenes');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTipocompra()
    {
        return $this->hasOne(\frontend\models\TipoCompra::className(), ['category_id' => 'tipocompra_id'])->inverseOf('ordenes');
    }

/**
     * @inheritdoc
     * @return array mixed
     */
    public function behaviors()
    {
        return [
            'blameable' => [
                'class' => BlameableBehavior::className(),
                'createdByAttribute' => 'created_by',
                'updatedByAttribute' => 'updated_by',
            ],
            'uuid' => [
                'class' => UUIDBehavior::className(),
                'column' => 'idordenes',
            ],
        ];
    }

    /**
     * @inheritdoc
     * @return \frontend\models\OrdenesQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \frontend\models\OrdenesQuery(get_called_class());
    }
}

Body:
This is just a suggestion

you should populate model Facturas retriving the facturas related  to this orders  and then assign properly the value you need  to the facturas model

use common\models\Facturas;

public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->loadAll(Yii::$app->request->post()){
           $modelFacturas = Facturas::find()
             ->(['your_id_fatcuras' => $model->your_id_facturas ])->one();
           $modelFacturas->you_field_to_change =  $model->value1 - $modelFacturas->value2;
           $model->save();
           $modelFacturas->save();

           return $this->redirect(['view', 'id' => $model->idfacturas]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

based  on your last comment this could be a more precise answer  to your question

Assuming you Orders Model is name Orders
and in Facturas you have a field named  fk_orders where you pass the value selectd by user in the view and that can link  the  related  order

Then in Facturas Controller you can

use common\models\Orders;

public function actionUpdate($id)
    {
        $model = $this->findModel($id); // retrive the Factursa model

        if ($model->loadAll(Yii::$app->request->post()){
           $modelOrders = Orders::find()
             ->(['id_orders' => $model->fk_orders ])->one();
           $modelOrders->amount  =  $modelOrders->amount - $model->value_to_subtract;
           $model->save();
           $modelOrders->save();

           return $this->redirect(['view', 'id' => $model->idfacturas]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }


问:
Python sparse matrix remove duplicate indices except one?
I am computing the cosine similarity between matrix of vectors, and I get the result in a sparse matrix like this:

(0, 26)   0.359171459261

(0, 25)   0.121145761751

(0, 24)  0.316922015914

(0, 23)  0.157622038039

(0, 22)  0.636466644041

(0, 21)  0.136216495731

(0, 20)  0.243164535496

(0, 19)  0.348272617805

(0, 18)  0.636466644041

(0, 17)  1.0

But there are duplicates for example:

(0, 24) 0.316922015914 and (24, 0) 0.316922015914

What I want to do is to remove them by indice and be (if I have (0,24) then I don't need (24, 0) because it is the same) left with only one of this and remove the second, for all vectors in the matrix.
Currently I have the following code to create the matrix:

```<code>vectorized_words = sparse.csr_matrix(vectorize_words(nostopwords,glove_dict))
cos_similiarity = cosine_similarity(vectorized_words,dense_output=False)
</code>```

So to summarize I don't want to remove all duplicates, I want to be left with only one of them using the pythonic way.

Thank you in advance !

答:
I think it is easiest to get the upper-triangle of a coo format matrix:

First make a small symmetric matrix:

```<code>In [876]: A = sparse.random(5,5,.3,'csr')
In [877]: A = A+A.T
In [878]: A
Out[878]:
<5x5 sparse matrix of type '<class 'numpy.float64'>'
    with 11 stored elements in Compressed Sparse Row format>
In [879]: A.A
Out[879]:
array([[ 0.        ,  0.        ,  0.81388978,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.73944395,  0.20736975,  0.98968617],
       [ 0.81388978,  0.73944395,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.20736975,  0.        ,  0.05581152,  0.04448881],
       [ 0.        ,  0.98968617,  0.        ,  0.04448881,  0.        ]])
</code>```

Convert to coo, and set the lower-triangle data values to 0

```<code>In [880]: Ao = A.tocoo()
In [881]: mask = (Ao.row>Ao.col)
In [882]: mask
Out[882]:
array([False, False, False, False,  True,  True,  True, False, False,
        True,  True], dtype=bool)
In [883]: Ao.data[mask]=0
</code>```

Convert back to 0, and use eliminate_zeros to prune the matrix.

```<code>In [890]: A1 = Ao.tocsr()
In [891]: A1
Out[891]:
<5x5 sparse matrix of type '<class 'numpy.float64'>'
    with 11 stored elements in Compressed Sparse Row format>
In [892]: A1.eliminate_zeros()
In [893]: A1
Out[893]:
<5x5 sparse matrix of type '<class 'numpy.float64'>'
    with 6 stored elements in Compressed Sparse Row format>
In [894]: A1.A
Out[894]:
array([[ 0.        ,  0.        ,  0.81388978,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.73944395,  0.20736975,  0.98968617],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.05581152,  0.04448881],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ]])
</code>```

Both the coo and csr formats have a in-place eliminate_zeros method.

```<code>def eliminate_zeros(self):
    """Remove zero entries from the matrix

    This is an *in place* operation
    """
    mask = self.data != 0
    self.data = self.data[mask]
    self.row = self.row[mask]
    self.col = self.col[mask]
</code>```

Instead of using Ao.data[mask]=0 you could this code as a model for eliminating just the lower_triangle values.

Body:
I am computing the cosine similarity between matrix of vectors, and I get the result in a sparse matrix like this:

(0, 26)   0.359171459261

(0, 25)   0.121145761751

(0, 24)  0.316922015914

(0, 23)  0.157622038039

(0, 22)  0.636466644041

(0, 21)  0.136216495731

(0, 20)  0.243164535496

(0, 19)  0.348272617805

(0, 18)  0.636466644041

(0, 17)  1.0

But there are duplicates for example:

(0, 24) 0.316922015914 and (24, 0) 0.316922015914

What I want to do is to remove them by indice and be (if I have (0,24) then I don't need (24, 0) because it is the same) left with only one of this and remove the second, for all vectors in the matrix.
Currently I have the following code to create the matrix:

vectorized_words = sparse.csr_matrix(vectorize_words(nostopwords,glove_dict))
cos_similiarity = cosine_similarity(vectorized_words,dense_output=False)

So to summarize I don't want to remove all duplicates, I want to be left with only one of them using the pythonic way.

Thank you in advance !

Body:
I think it is easiest to get the upper-triangle of a coo format matrix:

First make a small symmetric matrix:

In [876]: A = sparse.random(5,5,.3,'csr')
In [877]: A = A+A.T
In [878]: A
Out[878]:
<5x5 sparse matrix of type '<class 'numpy.float64'>'
    with 11 stored elements in Compressed Sparse Row format>
In [879]: A.A
Out[879]:
array([[ 0.        ,  0.        ,  0.81388978,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.73944395,  0.20736975,  0.98968617],
       [ 0.81388978,  0.73944395,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.20736975,  0.        ,  0.05581152,  0.04448881],
       [ 0.        ,  0.98968617,  0.        ,  0.04448881,  0.        ]])

Convert to coo, and set the lower-triangle data values to 0

In [880]: Ao = A.tocoo()
In [881]: mask = (Ao.row>Ao.col)
In [882]: mask
Out[882]:
array([False, False, False, False,  True,  True,  True, False, False,
        True,  True], dtype=bool)
In [883]: Ao.data[mask]=0

Convert back to 0, and use eliminate_zeros to prune the matrix.

In [890]: A1 = Ao.tocsr()
In [891]: A1
Out[891]:
<5x5 sparse matrix of type '<class 'numpy.float64'>'
    with 11 stored elements in Compressed Sparse Row format>
In [892]: A1.eliminate_zeros()
In [893]: A1
Out[893]:
<5x5 sparse matrix of type '<class 'numpy.float64'>'
    with 6 stored elements in Compressed Sparse Row format>
In [894]: A1.A
Out[894]:
array([[ 0.        ,  0.        ,  0.81388978,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.73944395,  0.20736975,  0.98968617],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.05581152,  0.04448881],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ]])

Both the coo and csr formats have a in-place eliminate_zeros method.

def eliminate_zeros(self):
    """Remove zero entries from the matrix

    This is an *in place* operation
    """
    mask = self.data != 0
    self.data = self.data[mask]
    self.row = self.row[mask]
    self.col = self.col[mask]

Instead of using Ao.data[mask]=0 you could this code as a model for eliminating just the lower_triangle values.


问:
How to use SFINAE for enum without specifying the enum?
Using answer from
Substitution failure is not an error (SFINAE) for enum I tried to write a code that would get enum value from a class, and if this enum value is not found it would have a fallback value.
As I'm beginner with templates, after couple of hours I gave up and found a "solution" using macros :(

Is there a way to do the same thing without macros and without copying the code for every possible enum value?

This is what I came up with:

```<code>struct foo
{
    enum FooFields
    {
        enumFoo,
        enumHehe
    };
};

struct bar
{
    enum BarFields
    {
        enumHehe = 2
    };
};

#define GETENUM_DEF(testedEnum) \
template<class T> \
struct get_ ## testedEnum{\
  typedef char yes;\
  typedef yes (&no)[2];\
\
  template<int>\
  struct test2;\
\
  template<class U>\
  static int test(test2<U::testedEnum>*){return U::testedEnum;};\
  template<class U>\
  static int test(...){return -1;};\
\
  static int value(){return test<T>(0);}\
};

GETENUM_DEF(enumFoo)
GETENUM_DEF(enumHehe)

int main() {

    std::cout<<get_enumFoo<foo>::value()<<std::endl; //returns 0;
    std::cout<<get_enumFoo<bar>::value()<<std::endl; //returns -1;

    std::cout<<get_enumHehe<foo>::value()<<std::endl; //returns 1;
    std::cout<<get_enumHehe<bar>::value()<<std::endl; //returns 2;

    return 0;
}
</code>```

答:
C++ requires that you define a get_someField for every field you want to get, but you'd have to do that with or without macros.

Playing with SFINAE is part of what is known as template meta-programming. What you are doing is effectively detecting whether the expression T::enumFoo is valid, and returning that value if it is, else -1.

To detect whether expression is valid, we can do something like this:

```<code>#include <type_traits>

// You need void_t to avoid a warning about the lhs of the comma operator
// having no effect. C++ 17 has std::void_t
template<class...> using void_t = void;

template<class T, class = void>
struct get_enumFoo
{
    static constexpr int value = -1;
};

template<class T>
struct get_enumFoo<T, void_t<decltype(T::enumFoo)>>
{
    static constexpr int value = T::enumFoo;
};

template<class T, class = void>
struct get_enumHehe
{
    static constexpr int value = -1;
};

template<class T>
struct get_enumHehe<T, void_t<decltype(T::enumHehe)>>
{
    static constexpr int value = T::enumHehe;
};
</code>```

Using it (your example):

```<code>#include <iostream>

int main() {
    std::cout << get_enumFoo<foo>::value << std::endl; //returns 0;
    std::cout << get_enumFoo<bar>::value << std::endl; //returns -1;

    std::cout << get_enumHehe<foo>::value << std::endl; //returns 1;
    std::cout << get_enumHehe<bar>::value << std::endl; //returns 2;
}
</code>```

It works as follows:

We define a case for SFINAE to fall back on in the case that the expression T::enumFoo is invalid:

```<code>template<class T, class = void>
struct get_enumFoo
{
    static constexpr int value = -1;
};
</code>```

We then define the case that sees if T::enumFoo is valid:

```<code>template<class T>
struct get_enumFoo<T, void_t<decltype(T::enumFoo)>>
{
    static constexpr int value = T::enumFoo;
};
</code>```

If T::enumFoo is invalid, then the decltype(T::enumFoo) is an invalid expression, so SFINAE kicks in and we fall back to our previous case.

If T::enumFoo is valid, then decltype(T::enumFoo) is some type, but void_t<decltype(T::enumFoo)> is void. So we are specializing get_enumFoo<T, void> to have the field value = T::enumFoo.

Try it online

To further reduce the boilerplate behind adding new get_field traits, you could define a base class:

```<code>namespace detail {
    struct get_foo_defaultValue
    {
        static constexpr int value = -1;
    };
}
</code>```

Then the base case would be

```<code>template<class T, class = void>
struct get_enumFoo
    : detail::get_foo_defaultValue
{};
</code>```

Body:
Using answer from
Substitution failure is not an error (SFINAE) for enum I tried to write a code that would get enum value from a class, and if this enum value is not found it would have a fallback value.
As I'm beginner with templates, after couple of hours I gave up and found a "solution" using macros :(

Is there a way to do the same thing without macros and without copying the code for every possible enum value?

This is what I came up with:

struct foo
{
    enum FooFields
    {
        enumFoo,
        enumHehe
    };
};

struct bar
{
    enum BarFields
    {
        enumHehe = 2
    };
};

#define GETENUM_DEF(testedEnum) \
template<class T> \
struct get_ ## testedEnum{\
  typedef char yes;\
  typedef yes (&no)[2];\
\
  template<int>\
  struct test2;\
\
  template<class U>\
  static int test(test2*){return U::testedEnum;};\
  template<class U>\
  static int test(...){return -1;};\
\
  static int value(){return test<T>(0);}\
};

GETENUM_DEF(enumFoo)
GETENUM_DEF(enumHehe)

int main() {

    std::cout<<get_enumFoo<foo>::value()<<std::endl; //returns 0;
    std::cout<<get_enumFoo<bar>::value()<<std::endl; //returns -1;

    std::cout<<get_enumHehe<foo>::value()<<std::endl; //returns 1;
    std::cout<<get_enumHehe<bar>::value()<<std::endl; //returns 2;

    return 0;
}

Body:
C++ requires that you define a get_someField for every field you want to get, but you'd have to do that with or without macros.

Playing with SFINAE is part of what is known as template meta-programming. What you are doing is effectively detecting whether the expression T::enumFoo is valid, and returning that value if it is, else -1.

To detect whether expression is valid, we can do something like this:

#include <type_traits>

// You need void_t to avoid a warning about the lhs of the comma operator
// having no effect. C++ 17 has std::void_t
template<class...> using void_t = void;

template<class T, class = void>
struct get_enumFoo
{
    static constexpr int value = -1;
};

template<class T>
struct get_enumFoo<T, void_t<decltype(T::enumFoo)>>
{
    static constexpr int value = T::enumFoo;
};

template<class T, class = void>
struct get_enumHehe
{
    static constexpr int value = -1;
};

template<class T>
struct get_enumHehe<T, void_t<decltype(T::enumHehe)>>
{
    static constexpr int value = T::enumHehe;
};

Using it (your example):

#include <iostream>

int main() {
    std::cout << get_enumFoo<foo>::value << std::endl; //returns 0;
    std::cout << get_enumFoo<bar>::value << std::endl; //returns -1;

    std::cout << get_enumHehe<foo>::value << std::endl; //returns 1;
    std::cout << get_enumHehe<bar>::value << std::endl; //returns 2;
}

It works as follows:

We define a case for SFINAE to fall back on in the case that the expression T::enumFoo is invalid:

template<class T, class = void>
struct get_enumFoo
{
    static constexpr int value = -1;
};

We then define the case that sees if T::enumFoo is valid:

template<class T>
struct get_enumFoo<T, void_t<decltype(T::enumFoo)>>
{
    static constexpr int value = T::enumFoo;
};

If T::enumFoo is invalid, then the decltype(T::enumFoo) is an invalid expression, so SFINAE kicks in and we fall back to our previous case.

If T::enumFoo is valid, then decltype(T::enumFoo) is some type, but void_t<decltype(T::enumFoo)> is void. So we are specializing get_enumFoo<T, void> to have the field value = T::enumFoo.

Try it online

To further reduce the boilerplate behind adding new get_field traits, you could define a base class:

namespace detail {
    struct get_foo_defaultValue
    {
        static constexpr int value = -1;
    };
}

Then the base case would be

template<class T, class = void>
struct get_enumFoo
    : detail::get_foo_defaultValue
{};


问:
Android Best Pratice to reuse code and layout
I've been reading about the include tag on xml, fragments to use on layout for smartphone and tablets but I'm getting more confused than getting a solution to my problem.

My App has 4 screens.

1 - You login and it download info from a json

2,3,4 - From login, Activity 2 load (A list with custom adapter), where you can click one of 2 images to jump to 3rd and 4th activity.

I need now to create the activity 1, 2, and 3 again with different JSONs being parsed, with 1 and 2 having the same layout of the existent ones and 3 with a different layout.

The code I need for them to work is(or can be) the same (Download Task with AsyncTask, button click listeners, etc) I already have for those activities.

I think it's not a goot pratice to copy basically the same getView method, for example, and paste on a new class, right? The buttons wouldn't work on the second range of screens for example.

So, what approach should I take that isn't copy and paste code and change things manually?

Sorry for the newbie question.

If needed I can provide code.

PS 1: I've already did tests with include on xml and copy code but that doesnt look professional

PS 2: Is fragments only for different screens like tablet or I could make something with it?

答:
That's several questions, so here's several answers, including to some un-asked questions:

To the greatest extent possible, strive to remove as much code as possible from your Activities, Fragments, etc. If it doesn't have anything to do with the Android lifecycle or actually putting something on the screen (e.g. parsing JSON), put it in a "plain old java" class. Also, this way, you can share the functionality among Activities.

IMHO, you should never use an AsyncTask, for any reason. They're used with an Activity or Fragment, but don't respect the Fragment or Activity lifecycle, so are often the cause of crashes that can be difficult to diagnose. Use something synchronized with the lifecycle, like a Loader. Or go the RxJava route, where Subscribers can be canceled at the appropriate point in the Activity/Fragment lifecycle.

Fragments can be good for code re-use, but they have a slightly different lifecycle from Activities, so they can be difficult to work with, so use them sparingly and be careful. If you're doing it just to re-use a bit of UI (but not behavior), a layout "include" is probably better. For behavior, a custom View class can be a good alternative to a Fragment.

Don't do HTTP / REST access yourself, using primitives like HTTPUrlConnection. There are a lot of corner cases that are going to get you into trouble. Use one of the several really good open-source libraries that are built for this purpose. I highly recommend Retrofit.


问:
How to get Display Name Attribute using PropertyDescriptor C# ASP.NET MVC 4
I am using property descriptor to generically iterate over the properties and print their attribute names as table header. It works fine printing the property name, but not for the [Display(Name = "Test")]

Class:

```<code>public class Transaction
{
    [Display(Name = "Test")]
    public string DELETE { get; set; }
    public string PARTNO { get; set; } //Part Number
</code>```

Markup:

```<code>    @foreach (System.ComponentModel.PropertyDescriptor descriptor in System.ComponentModel.TypeDescriptor.GetProperties(Model[0]))
    {
       <th onclick="tableColumnSort(this)" class="tableSortHeaderBtnStyle">@descriptor.DisplayName;</th>
    }
</code>```

Just prints the "DELETE" name rather than "Test".  The descriptor has a Name, and DisplayName option and both are set to "DELETE"

What am I doing wrong?

答:
You have to use [DisplayName("Test")] instead of [Display(Name = "Test")], please check this:

```<code>public class Transaction
{
    //[Display(Name = "Test")]
    [DisplayName("Test")]
    public string DELETE { get; set; }
    public string PARTNO { get; set; } //Part Number
}
</code>```

You can check this in DotNetFiddle.

Body:
I am using property descriptor to generically iterate over the properties and print their attribute names as table header. It works fine printing the property name, but not for the [Display(Name = "Test")]

Class:

public class Transaction
{
    [Display(Name = "Test")]
    public string DELETE { get; set; }
    public string PARTNO { get; set; } //Part Number

Markup:

    @foreach (System.ComponentModel.PropertyDescriptor descriptor in System.ComponentModel.TypeDescriptor.GetProperties(Model[0]))
    {
       @descriptor.DisplayName;
    }

Just prints the "DELETE" name rather than "Test".  The descriptor has a Name, and DisplayName option and both are set to "DELETE"

What am I doing wrong?

Body:
You have to use [DisplayName("Test")] instead of [Display(Name = "Test")], please check this:

public class Transaction
{
    //[Display(Name = "Test")]
    [DisplayName("Test")]
    public string DELETE { get; set; }
    public string PARTNO { get; set; } //Part Number
}

You can check this in DotNetFiddle.


问:
Syntax error near unexpected token newline message after executing a shell script
I use shell in PUTTY to execute a remote script from Git:

```<code>curl -s https://github.com/dotnet/cli/blob/rel/1.0.0/scripts/obtain/uninstall/dotnet-uninstall-debian-packages.sh >dotnet-uninstall-debian-packages.sh
./dotnet-uninstall-debian-packages.sh
</code>```

But suddenly received a syntax error:

Syntax error near unexpected token newline

<!DOCTYPE html>

答:
Fix URL in your curl command:</p>

```<code>https://raw.githubusercontent.com/dotnet/cli/rel/1.0.0/scripts/obtain/uninstall/dotnet-uninstall-debian-packages.sh
</code>```

Body:
I use shell in PUTTY to execute a remote script from Git:

curl -s https://github.com/dotnet/cli/blob/rel/1.0.0/scripts/obtain/uninstall/dotnet-uninstall-debian-packages.sh >dotnet-uninstall-debian-packages.sh
./dotnet-uninstall-debian-packages.sh

But suddenly received a syntax error:

Syntax error near unexpected token newline

<!DOCTYPE html>

Body:
Fix URL in your curl command:

https://raw.githubusercontent.com/dotnet/cli/rel/1.0.0/scripts/obtain/uninstall/dotnet-uninstall-debian-packages.sh


问:
Reading settings.ini correctly
For example I have a settings.ini file of my program which includes:

```<code>theme=white
SaveDirectory=C:\Screenshots
</code>```

I read it like that:

```<code>with open("settings.ini", "r") as settings:
    setting = settings.readlines()
    theme = setting[0]
    theme = theme[len("theme="):].strip()
    bg = theme
    print(theme)
    SaveDirectory = setting[1]
    SaveDirectory = SaveDirectory[len("SaveDirectory="):].strip()
    print(SaveDirectory)
    settings.close()
</code>```

But I know that is bad and risky when my .ini gets longer. I need a function which reads lines with starts of them. Like: function("theme="). Is there something like that for python3?

答: Python 3 has a configparser module which does exactly what you want, though you'll need to add a [section] header to the top of your file first so that it conforms to the supported file structure.

Title: Reading settings.ini correctly

Body:
For example I have a settings.ini file of my program which includes:

theme=white
SaveDirectory=C:\Screenshots

I read it like that:

with open("settings.ini", "r") as settings:
    setting = settings.readlines()
    theme = setting[0]
    theme = theme[len("theme="):].strip()
    bg = theme
    print(theme)
    SaveDirectory = setting[1]
    SaveDirectory = SaveDirectory[len("SaveDirectory="):].strip()
    print(SaveDirectory)
    settings.close()

But I know that is bad and risky when my .ini gets longer. I need a function which reads lines with starts of them. Like: function("theme="). Is there something like that for python3?


问:
Excel VBA - Bitcoin
I'm trying to run this macro on Microsoft Excel, but every time I do, I get a

Run-time error '5'

What am I doing wrong?
This is my first time doing something like this.

What's suppose to happen is that everytime I run the Keyboard Shortcut, it's suppose to get the data from the blockchain website.

It's essentially just code that says..

1 USD is worth this many BTC

```<code>Sub USD_to_BTC()
'
' USD_to_BTC Macro
' Get the price of 1 btc if purchased by 1 USD
'
' Keyboard Shortcut: Ctrl+Shift+B
'
    With ActiveSheet.QueryTables.Add(Connection:= _
        "URL;https://blockchain.info/tobtc?currency=USD&value=1", Destination:=Range( _
        "$D$8"))
        .CommandType = 0
        .Name = "tobtc?currency=USD&value=1_1"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .WebSelectionType = xlAllTables
        .WebFormatting = xlWebFormattingNone
        .WebPreFormattedTextToColumns = True
        .WebConsecutiveDelimitersAsOne = True
        .WebSingleBlockTextImport = False
        .WebDisableDateRecognition = False
        .WebDisableRedirections = False
        .Refresh BackgroundQuery:=False
    End With
End Sub
</code>```

答:
Remove (or comment out) .CommandType = 0 line.

As this MSDN Post explains,

You can set the CommandType property only if the value of the QueryType property for the query table or PivotTable cache is xlOLEDBQuery.

Title: Excel VBA - Bitcoin

Body:
I'm trying to run this macro on Microsoft Excel, but every time I do, I get a

Run-time error '5'

What am I doing wrong?
This is my first time doing something like this.

What's suppose to happen is that everytime I run the Keyboard Shortcut, it's suppose to get the data from the blockchain website.

It's essentially just code that says..

1 USD is worth this many BTC

Sub USD_to_BTC()
'
' USD_to_BTC Macro
' Get the price of 1 btc if purchased by 1 USD
'
' Keyboard Shortcut: Ctrl+Shift+B
'
    With ActiveSheet.QueryTables.Add(Connection:= _
        "URL;https://blockchain.info/tobtc?currency=USD&value=1", Destination:=Range( _
        "$D$8"))
        .CommandType = 0
        .Name = "tobtc?currency=USD&value=1_1"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .WebSelectionType = xlAllTables
        .WebFormatting = xlWebFormattingNone
        .WebPreFormattedTextToColumns = True
        .WebConsecutiveDelimitersAsOne = True
        .WebSingleBlockTextImport = False
        .WebDisableDateRecognition = False
        .WebDisableRedirections = False
        .Refresh BackgroundQuery:=False
    End With
End Sub


问:
Angular2 Form Validation UI with Material Design
Following the example from Angular's official documentation, I have come across a road block with .css when using <input mdInput ..../> from Angular Material.

Given .css from the tutorial:

```<code>.ng-valid[required], .ng-valid.required {
  border-left: 5px solid #42A948; /* green */
}

.ng-invalid:not(form) {
  border-left: 5px solid #a94442; /* red */
}
</code>```

I get the following design in my output:

How do I fix the CSS from "bleed through" the text input?

答:
The Material Input Component has a dividerColor attribute, which is more straightforward than customizing the CSS.

Documentation

Divider Color

The divider (line under the input content) color can be changed by
  using the dividerColor attribute of md-input-container. A value of
  primary is the default and will correspond to the theme primary color.
  Alternatively, accent or warn can be specified to use the theme's
  accent or warn color.

Example

```<code><md-input-container [dividerColor]="passwordError ? 'warn' : 'primary'">
    <input mdInput formControlName="password" type="password" placeholder="Password" autocomplete="off" required>
</md-input-container>
</code>```

Body:
Following the example from Angular's official documentation, I have come across a road block with .css when using <input mdInput ..../> from Angular Material.

Given .css from the tutorial:

.ng-valid[required], .ng-valid.required {
  border-left: 5px solid #42A948; /* green */
}

.ng-invalid:not(form) {
  border-left: 5px solid #a94442; /* red */
}

I get the following design in my output:

How do I fix the CSS from "bleed through" the text input?

Body:
The Material Input Component has a dividerColor attribute, which is more straightforward than customizing the CSS.

Documentation

Divider Color

The divider (line under the input content) color can be changed by
  using the dividerColor attribute of md-input-container. A value of
  primary is the default and will correspond to the theme primary color.
  Alternatively, accent or warn can be specified to use the theme's
  accent or warn color.

Example

<md-input-container [dividerColor]="passwordError ? 'warn' : 'primary'">
    <input mdInput formControlName="password" type="password" placeholder="Password" autocomplete="off" required>
</md-input-container>