问:
Get Values from child nodes from XML | Python
I have the following XML.

I am using ElementTree library to scrape the values.

```<code><?xml version="1.0" encoding="UTF-8"?>

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
 <url>
  <loc> Test1</loc>
  </url>
 <url>
  <loc>Test 2</loc>
 </url>
 <url>
  <loc>Test 3</loc>
 </url>
</urlset>
</code>```

I need to get the values out of 'loc tag'.

Desired Output:

```<code>Test 1
Test 2
Test 3
</code>```

Tried Code:

```<code>tree = ET.parse('sitemap.xml')
root = tree.getroot()
for atype in root.findall('url'):
 rank = atype.find('loc').text
print (rank)
</code>```

Any suggestions on where am I wrong ?

答:
Your XML has a default namespace (http://www.sitemaps.org/schemas/sitemap/0.9) so you either have to address all your tags as:

```<code>tree = ET.parse('sitemap.xml')
root = tree.getroot()
for atype in root.findall('{http://www.sitemaps.org/schemas/sitemap/0.9}url'):
    rank = atype.find('{http://www.sitemaps.org/schemas/sitemap/0.9}loc').text
    print(rank)
</code>```

Or to define a namespace map:

```<code>nsmap = {"ns": "http://www.sitemaps.org/schemas/sitemap/0.9"}

tree = ET.parse('sitemap.xml')
root = tree.getroot()
for atype in root.findall('ns:url', nsmap):
    rank = atype.find('ns:loc', nsmap).text
    print(rank)
</code>```

Body:
I have the following XML.

I am using ElementTree library to scrape the values.

<?xml version="1.0" encoding="UTF-8"?>

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
 <url>
  <loc> Test1</loc>
  </url>
 <url>
  <loc>Test 2</loc>
 </url>
 <url>
  <loc>Test 3</loc>
 </url>
</urlset>

I need to get the values out of 'loc tag'.

Desired Output:

Test 1
Test 2
Test 3

Tried Code:

tree = ET.parse('sitemap.xml')
root = tree.getroot()
for atype in root.findall('url'):
 rank = atype.find('loc').text
print (rank)

Any suggestions on where am I wrong ?

Body:
Your XML has a default namespace (http://www.sitemaps.org/schemas/sitemap/0.9) so you either have to address all your tags as:

tree = ET.parse('sitemap.xml')
root = tree.getroot()
for atype in root.findall('{http://www.sitemaps.org/schemas/sitemap/0.9}url'):
    rank = atype.find('{http://www.sitemaps.org/schemas/sitemap/0.9}loc').text
    print(rank)

Or to define a namespace map:

nsmap = {"ns": "http://www.sitemaps.org/schemas/sitemap/0.9"}

tree = ET.parse('sitemap.xml')
root = tree.getroot()
for atype in root.findall('ns:url', nsmap):
    rank = atype.find('ns:loc', nsmap).text
    print(rank)


来源: stackexchange

问:
how to install vendor package from laravel package
So i'am in Laravel 5.4 and i've my custom package packages/dev/mypackage.

And i want to install soundasleep/html2text into my package, so i add this to my packages/dev/mypackage/composer.json :

```<code>{
  "require": {
    "soundasleep/html2text": "~0.5"
  }
}
</code>```

then composer update , but when i tried to call Html2Text\Html2Text i got always class Html2Text\Html2Text not found.

So please if someone has any idea i'll be very appreciative.

答: first use Html2Text\Html2Text then call html2text

ContentLicense: CC BY-SA 3.0

Body:
So i'am in Laravel 5.4 and i've my custom package packages/dev/mypackage.

And i want to install soundasleep/html2text into my package, so i add this to my packages/dev/mypackage/composer.json :

{
  "require": {
    "soundasleep/html2text": "~0.5"
  }
}

then composer update , but when i tried to call Html2Text\Html2Text i got always class Html2Text\Html2Text not found.

So please if someone has any idea i'll be very appreciative.


问:
Handle breadcrumbs in mvc dotnetcore
I'm working on a website (MVC dotnetcore) that has many pages and flows as well. A user can approach a single page from many different ways. I'm getting stuck when user wants to move back and I don't have any track of its last URL. And I'm getting confused that how to handle this situation?

Should I use a global variable to keep track of last URL??

but in this case, I've to do a repeatable code on each screen, or may be for each get/ post call.

OR

Should I use kind of breadcrumbs structure?

Like if user move Admin from Index, there would be something like this

```<code>Index >> Admin
</code>```

And for further

```<code>Index >> Admin >> ManageUsers
</code>```

And these would be links to their related pages.
But I dont know how to handle this in mvc dotnetcore? Any Idea??

Which approach is good to follow? Any kind of help will be appreciated.

答:
I suggest You to Use breadcumb. Its a bootstrap component you can manage it on front end. In Site map you have to do some extra work. As compare to sitemap, breadcumb  is simple , take little effort and you can customise it also
breadcomb
please visit the above link it will be help full to you

Title: Handle breadcrumbs in mvc dotnetcore

Body:
I'm working on a website (MVC dotnetcore) that has many pages and flows as well. A user can approach a single page from many different ways. I'm getting stuck when user wants to move back and I don't have any track of its last URL. And I'm getting confused that how to handle this situation?

Should I use a global variable to keep track of last URL??

but in this case, I've to do a repeatable code on each screen, or may be for each get/ post call.

OR

Should I use kind of breadcrumbs structure?

Like if user move Admin from Index, there would be something like this

Index >> Admin

And for further

Index >> Admin >> ManageUsers

And these would be links to their related pages.
But I dont know how to handle this in mvc dotnetcore? Any Idea??

Which approach is good to follow? Any kind of help will be appreciated.


问:
In Coq, How to construct an element of 'sig' type
With a simple inductive definition of a type A:

```<code>Inductive A: Set := mkA : nat-> A.

(*get ID of A*)
Function getId (a: A) : nat := match a with mkA n => n end.
</code>```

And a subtype definition:

```<code>(* filter that test ID of *A* is 0 *)
Function filter (a: A) : bool := if (beq_nat (getId a) 0) then true else false.

(* cast bool to Prop *)
Definition IstrueB (b : bool) : Prop := if b then True else False.

(* subtype of *A* that only interests those who pass the filter *)
Definition subsetA : Set := {a : A | IstrueB (filter a) }.
</code>```

I try this code to cast element of A to subsetA when filter passes, but failed to convenience Coq that it is a valid construction for an element of 'sig' type:

```<code>Definition cast (a: A) : option subsetA :=
match (filter a) with
 | true => Some (exist _ a (IstrueB (filter a)))
 | false => None
end.
</code>```

Error:

```<code>In environment
a : A
The term "IstrueB (filter a)" has type "Prop"
while it is expected to have type "?P a"
(unable to find a well-typed instantiation for "?P": cannot ensure that
"A -> Type" is a subtype of "?X114@{__:=a} -> Prop").
</code>```

So, Coq expects an actual proof of type (IstrueB (filter a)), but what I provide there is type Prop.

Could you shed some lights on how to provide such type? thank you.

答:
First of all, there is the standard is_true wrapper. You can use it explicitly like so:

```<code>Definition subsetA : Set := {a : A | is_true (filter a) }.
</code>```

or implicitly using the coercion mechanism:

```<code>Coercion is_true : bool >-> Sortclass.
Definition subsetA : Set := { a : A | filter a }.
</code>```

Next, non-dependent pattern-mathching on filter a doesn't propagate filter a = true into the true branch. You have at least three options:

Use tactics to build your cast function:

```<code>Definition cast (a: A) : option subsetA.
  destruct (filter a) eqn:prf.
  - exact (Some (exist _ a prf)).
  - exact None.
Defined.
</code>```

Use dependent pattern-matching explicitly (search for "convoy pattern" on Stackoverflow or in CDPT):

```<code>Definition cast' (a: A) : option subsetA :=
  match (filter a) as fa return (filter a = fa -> option subsetA) with
  | true => fun prf => Some (exist _ a prf)
  | false => fun _ => None
  end eq_refl.
</code>```

Use the Program facilities:

```<code>Require Import Coq.Program.Program.

Program Definition cast'' (a: A) : option subsetA :=
  match filter a with
  | true => Some (exist _ a _)
  | false => None
  end.
</code>```

Body:
With a simple inductive definition of a type A:

Inductive A: Set := mkA : nat-> A.

(*get ID of A*)
Function getId (a: A) : nat := match a with mkA n => n end.

And a subtype definition:

(* filter that test ID of *A* is 0 *)
Function filter (a: A) : bool := if (beq_nat (getId a) 0) then true else false.

(* cast bool to Prop *)
Definition IstrueB (b : bool) : Prop := if b then True else False.

(* subtype of *A* that only interests those who pass the filter *)
Definition subsetA : Set := {a : A | IstrueB (filter a) }.

I try this code to cast element of A to subsetA when filter passes, but failed to convenience Coq that it is a valid construction for an element of 'sig' type:

Definition cast (a: A) : option subsetA :=
match (filter a) with
 | true => Some (exist _ a (IstrueB (filter a)))
 | false => None
end.

Error:

In environment
a : A
The term "IstrueB (filter a)" has type "Prop"
while it is expected to have type "?P a"
(unable to find a well-typed instantiation for "?P": cannot ensure that
"A -> Type" is a subtype of "?X114@{__:=a} -> Prop").

So, Coq expects an actual proof of type (IstrueB (filter a)), but what I provide there is type Prop.

Could you shed some lights on how to provide such type? thank you.

Body:
First of all, there is the standard is_true wrapper. You can use it explicitly like so:

Definition subsetA : Set := {a : A | is_true (filter a) }.

or implicitly using the coercion mechanism:

Coercion is_true : bool >-> Sortclass.
Definition subsetA : Set := { a : A | filter a }.

Next, non-dependent pattern-mathching on filter a doesn't propagate filter a = true into the true branch. You have at least three options:

Use tactics to build your cast function:

Definition cast (a: A) : option subsetA.
  destruct (filter a) eqn:prf.
  - exact (Some (exist _ a prf)).
  - exact None.
Defined.

Use dependent pattern-matching explicitly (search for "convoy pattern" on Stackoverflow or in CDPT):

Definition cast' (a: A) : option subsetA :=
  match (filter a) as fa return (filter a = fa -> option subsetA) with
  | true => fun prf => Some (exist _ a prf)
  | false => fun _ => None
  end eq_refl.

Use the Program facilities:

Require Import Coq.Program.Program.

Program Definition cast'' (a: A) : option subsetA :=
  match filter a with
  | true => Some (exist _ a _)
  | false => None
  end.


问:
mprotect() Invalid argument in C
I want to allocate 4096 Bytes with posix_memalign in the array "page", and then protect it with PROT_NONE via mprotect().
The allocation seems to work, but protect() returns 1 instead of 0. The given error code is "Invalid argument".

I think it's only a small mistake, I am not able to detect. Thanks in advance for any help or suggestions.

```<code>uint8_t *page;
size_t page_size = 4096;
size_t alignment = 8;

int main(int argc, char* argv[]) {
    if (posix_memalign((void **) &page, alignment, page_size) != 0) perror("Allocation failed!");
    if (mprotect(page, page_size, PROT_NONE) != 0) perror("mprotect() failed!");
}
</code>```

答:
Try the way in the code below ... and read better the man-pages:

man -S3 posix_memalign

man -S2 mprotect

```<code>#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/mman.h>
#include <stdint.h>
#include <inttypes.h>
#include <unistd.h>

uint8_t *page=NULL;
size_t page_size;
size_t alignment = 8;

int main(int argc, char* argv[]) {
    int blen;

    // page_size=getpagesize();
    page_size = sysconf(_SC_PAGE_SIZE);

    blen=page_size * 2;

    if (posix_memalign((void **) &page, page_size, blen) != 0)
        perror("Allocation failed!");

    if (mprotect(page, page_size, PROT_READ | PROT_WRITE) != 0)
        perror("mprotect() failed!");
}
</code>```

Title: mprotect() Invalid argument in C

Body:
I want to allocate 4096 Bytes with posix_memalign in the array "page", and then protect it with PROT_NONE via mprotect().
The allocation seems to work, but protect() returns 1 instead of 0. The given error code is "Invalid argument".

I think it's only a small mistake, I am not able to detect. Thanks in advance for any help or suggestions.

uint8_t *page;
size_t page_size = 4096;
size_t alignment = 8;

int main(int argc, char* argv[]) {
    if (posix_memalign((void **) &page, alignment, page_size) != 0) perror("Allocation failed!");
    if (mprotect(page, page_size, PROT_NONE) != 0) perror("mprotect() failed!");
}

Body:
Try the way in the code below ... and read better the man-pages:

man -S3 posix_memalign

man -S2 mprotect

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/mman.h>
#include <stdint.h>
#include <inttypes.h>
#include <unistd.h>

uint8_t *page=NULL;
size_t page_size;
size_t alignment = 8;

int main(int argc, char* argv[]) {
    int blen;

    // page_size=getpagesize();
    page_size = sysconf(_SC_PAGE_SIZE);

    blen=page_size * 2;

    if (posix_memalign((void **) &page, page_size, blen) != 0)
        perror("Allocation failed!");

    if (mprotect(page, page_size, PROT_READ | PROT_WRITE) != 0)
        perror("mprotect() failed!");
}


问:
Add CALayer to UILabel text
Is there a way to add extra CAShapeLayer( a small box) to uilalbel text. I want it to be placed exactly after the last character of label.

Thank you!
some what like this. an extra layer near to the end of label

答:
If you don't want to go into complexity , try unicode characters & append it in your string with some space if required. You can check in Interface builder. Select label. Go into Edit -> Emoji & Symbols & select dot .Check in attached screenshot.

EDIT

Find position of last character in UILabel text & add CAShapeLayer as subview.It should work.

OR

You can simplify your solution by having 1 UIView with label & CAShapeLayer as subviews.Set origin of layer with label width .

Title: Add CALayer to UILabel text


问:
Equivalent of Java's getBytes in JavaScript for different encodings
I have a function in Java that I need to convert to JavaScript and that contains this line:

```<code>byte[] bytes = ttText.getBytes(Charset.forName("Cp1250"));
</code>```

ttText is String. I need to do the same. I need to get the bytes of a string encoded in Cp1250 (windows-1250), modify those bytes and then convert it back to string. Is there a way how to do it in JavaScript?

I discovered for example TextEncoder and TextDecoder but the support for different encodings than UTF-8 was dropped some time ago.

答:
Try this.
https://mths.be/windows-1250

This looks promising. It provides support for both encoding and decoding.
All you need to do is add the library and use the methods.
var encodedData = windows1250.encode(text);

Body:
I have a function in Java that I need to convert to JavaScript and that contains this line:

byte[] bytes = ttText.getBytes(Charset.forName("Cp1250"));

ttText is String. I need to do the same. I need to get the bytes of a string encoded in Cp1250 (windows-1250), modify those bytes and then convert it back to string. Is there a way how to do it in JavaScript?

I discovered for example TextEncoder and TextDecoder but the support for different encodings than UTF-8 was dropped some time ago.


问:
android cardview showing border around card
Android cardview is showing unnecessary border around the card. I have tried different things but I am not able to remove it.
It happens when I give the card a custom background color.
When I remove the cardBackgroundColor, and when default is used. Then unnecessary border is not visible.

I have to use shadow and tranparent color code.

Here is my layout CardView

```<code>         <RelativeLayout
            android:id="@+id/rlUserNamePassword"
            android:layout_width="match_parent"
            android:background="@android:color/transparent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/margin"
                android:background="@android:color/transparent"
                app:cardBackgroundColor="@color/form_card_bg_color"
                app:cardElevation="@dimen/margin"
                app:contentPadding="@dimen/margin_large"
                app:cardPreventCornerOverlap="false"
                app:cardUseCompatPadding="true" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center_vertical"
                        android:orientation="horizontal">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/user" />

                        <android.support.design.widget.TextInputLayout
                            android:id="@+id/tilName"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">

                            <com.yaashvi.placeandpeople.customviews.CustomEditText
                                android:id="@+id/etEmail"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:hint="@string/username"
                                android:singleLine="true"
                                android:maxLines="1"/>

                        </android.support.design.widget.TextInputLayout>

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="@dimen/margin_large"
                        android:gravity="center_vertical"
                        android:orientation="horizontal">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/password" />

                        <android.support.design.widget.TextInputLayout
                            android:id="@+id/tilPassword"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">

                            <com.yaashvi.placeandpeople.customviews.CustomEditText
                                android:id="@+id/etPassword"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:hint="@string/password"
                                android:singleLine="true"
                                android:maxLines="1"
                                android:inputType="textPassword"/>
                        </android.support.design.widget.TextInputLayout>

                    </LinearLayout>
                </LinearLayout>

            </android.support.v7.widget.CardView >

            <LinearLayout
                android:id="@+id/llGo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:orientation="vertical"
                android:elevation="@dimen/margin_large"
                >

                <include layout="@layout/go_button" />

            </LinearLayout>

        </RelativeLayout>
</code>```

And the view created is this

See the extra border on left, right and top of cardview and inside the card shadow.

答:
i check it again and i got that result what you want.<android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimay >

Body:
Android cardview is showing unnecessary border around the card. I have tried different things but I am not able to remove it.
It happens when I give the card a custom background color.
When I remove the cardBackgroundColor, and when default is used. Then unnecessary border is not visible.

I have to use shadow and tranparent color code.

Here is my layout CardView

         <RelativeLayout
            android:id="@+id/rlUserNamePassword"
            android:layout_width="match_parent"
            android:background="@android:color/transparent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/margin"
                android:background="@android:color/transparent"
                app:cardBackgroundColor="@color/form_card_bg_color"
                app:cardElevation="@dimen/margin"
                app:contentPadding="@dimen/margin_large"
                app:cardPreventCornerOverlap="false"
                app:cardUseCompatPadding="true" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center_vertical"
                        android:orientation="horizontal">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/user" />

                        <android.support.design.widget.TextInputLayout
                            android:id="@+id/tilName"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">

                            <com.yaashvi.placeandpeople.customviews.CustomEditText
                                android:id="@+id/etEmail"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:hint="@string/username"
                                android:singleLine="true"
                                android:maxLines="1"/>

                        </android.support.design.widget.TextInputLayout>

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="@dimen/margin_large"
                        android:gravity="center_vertical"
                        android:orientation="horizontal">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/password" />

                        <android.support.design.widget.TextInputLayout
                            android:id="@+id/tilPassword"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">

                            <com.yaashvi.placeandpeople.customviews.CustomEditText
                                android:id="@+id/etPassword"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:hint="@string/password"
                                android:singleLine="true"
                                android:maxLines="1"
                                android:inputType="textPassword"/>
                        </android.support.design.widget.TextInputLayout>

                    </LinearLayout>
                </LinearLayout>

            </android.support.v7.widget.CardView >

            <LinearLayout
                android:id="@+id/llGo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:orientation="vertical"
                android:elevation="@dimen/margin_large"
                >

                <include layout="@layout/go_button" />

            </LinearLayout>

        </RelativeLayout>

And the view created is this

See the extra border on left, right and top of cardview and inside the card shadow.


问:
How to cross-reference types in parameters
I'm trying to cross-reference types in their generic parameters.
In java, I have this:

```<code>public interface Group<C extends Child> {
  List<C> getChildren();
}

public interface Child<G extends Group> {
  G getParent();
}

class MyGroup implements Group<MyChild> {
  @Override
  public List<MyChild> getChildren() {
    return null;
  }
}

class MyChild implements Child<MyGroup> {
  @Override
  public MyGroup getParent() {
    return null;
  }
}
</code>```

Using AndroidStudio's "Convert to Kotlin" function results in:

```<code>interface Group<C : Child<*>> {
  val children: List<C>
}

interface Child<G : Group<*>> {
  val parent: G
}

internal inner class MyGroup : Group<MyChild> {
  override val children: List<MyChild>?
    get() = null
}

internal inner class MyChild : Child<MyGroup> {
  override val parent: MyGroup?
    get() = null
}
</code>```

Which throws: Finite Bound Restriction violated.

Is there any way I can write such code in kotlin?

答:
I don't like that way. because it will introduce another generic parameter. instead you can introduce a middle role Node interface to describe the relationship, for example:

```<code>interface Node<out T>;

interface Group<out C : Node<*>> : Node<C> {
    val children: List<C>
}

interface Child<out G : Group<*>> : Node<G> {
    val parent: G;
}

class MyGroup : Group<MyChild> {
    override val children: List<MyChild>
        get() = TODO("not implemented")
}

class MyChild : Child<MyGroup> {
    override val parent: MyGroup
        get() = TODO("not implemented")
}
</code>```

the middle role just like as kotlin.Function:

```<code>public interface Function<out R>
</code>```

Note: the out variance is optional.

Body:
I'm trying to cross-reference types in their generic parameters.
In java, I have this:

public interface Group<C extends Child> {
  List<C> getChildren();
}

public interface Child<G extends Group> {
  G getParent();
}

class MyGroup implements Group<MyChild> {
  @Override
  public List<MyChild> getChildren() {
    return null;
  }
}

class MyChild implements Child<MyGroup> {
  @Override
  public MyGroup getParent() {
    return null;
  }
}

Using AndroidStudio's "Convert to Kotlin" function results in:

interface Group<C : Child<*>> {
  val children: List<C>
}

interface Child<G : Group<*>> {
  val parent: G
}

internal inner class MyGroup : Group<MyChild> {
  override val children: List<MyChild>?
    get() = null
}

internal inner class MyChild : Child<MyGroup> {
  override val parent: MyGroup?
    get() = null
}

Which throws: Finite Bound Restriction violated.

Is there any way I can write such code in kotlin?

Body:
I don't like that way. because it will introduce another generic parameter. instead you can introduce a middle role Node interface to describe the relationship, for example:

interface Node<out T>;

interface Group<out C : Node<*>> : Node<C> {
    val children: List<C>
}

interface Child<out G : Group<*>> : Node<G> {
    val parent: G;
}

class MyGroup : Group<MyChild> {
    override val children: List<MyChild>
        get() = TODO("not implemented")
}

class MyChild : Child<MyGroup> {
    override val parent: MyGroup
        get() = TODO("not implemented")
}

the middle role just like as kotlin.Function:

public interface Function<out R>

Note: the out variance is optional.


问:
Getting error while importing rest-assured packages

I am using maven project, in which I already created the dependency for rest-assured. When I am trying to import rest-assured package, I am unable to do. I am getting an error.

答:
Created wrong maven dependency
Was trying to import io.restassured while developed jayway restassured dependencies</p>


问:
Specific example: Is it possible to aviod the use of a global variable?
I have the following program and the variable(dictionary) in question is player_info that stores player information (name and goals). In order to solve the error that results currently, I simply need to make player_info a global variable, but I was wondering if stackoverflow experts could suggest or discuss the possibility of alternate ways of solving this problem WITHOUT the use of global variables.

Code

```<code>#FOOTBALL COACH app

#The program allows a user to enter a number of players (their names and goals scored) and then search for a player, returning their average goals for the three matches

import sys
def main():
 mainmenu()

def mainmenu():

  print("=====WELCOME to the MAIN MENU=============")
  print("""
  1..........Add New Players & Goals
  2..........Search by Players
  3..........Quit

  =========================================
  """)

  choice=int(input("Enter choice:"))
  if choice==1:
    addplayers()
  elif choice==2:
    searchplayer(player_info)
  elif choice==3:
    sys.exit()
  else:
    print("You must make a valid choice - 1, 2 or 3")

def addplayers():

  player_info= {} #create a dictionary that stores the player name: player goals

  num_players = int(input("Please enter number of players you wish to enter:"))
  print ("You are entering %s players" %num_players)
  player_data = ['Match 1 goals : ', 'Match 2 goals : ', 'Match 3 goals : ']
  for i in range(0,num_players):
      player_name = input("Enter Player Name :")
      player_info[player_name] = {}
      for entry in player_data:
          player_info[player_name][entry] = int(input(entry)) #storing the marks entered as integers to perform arithmetic operations later on.

  mainmenu()

def searchplayer():
   print("===============SEARCH by player: Calculate average goals==================")
   name = input("Player name : ")
   if name in player_info.keys():
     #print student_info
      print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
   else:
      print("Please enter a valid player name:")

main()
</code>```

As mentioned, I am aware that re-writing this in the addplayer() sub would fix the problem:

```<code>global player_info
player_info = {} #create a dictionary that stores the player name: player goals
</code>```

...I am looking for ways to solve the problem WITHOUT the use of global variables.

Update:

One answer below using return player_info is what I would like to go with, but it doesn't quite work yet. Also, I need to return to the main menu each time a player is added, not quite sure how to do this, without a mainmenu call each time. Any suggestions? https://repl.it/JRl5/1

答:
Firstly, it is always possible to avoid using global variables. Secondly, global variables are possibly a misnomer in Python; global stores the variable in the local globals, which is typically the local module. That avoids a large part of the problem languages like C have with globals, in that they collide; Python has a namespace per module. For a simple script, where there is only one context, that might be fine.

Another namespace you might use is that of a particular object, using a class. This might look like:

```<code>class Game:
    def mainmenu(self,...):
        self.addplayers()
    def addplayers(self):
        self.player_info = {}
</code>```

With that sort of code, whoever instantiates Game can make multiple instances, each passed as self when used. This is in large part syntactic sugar for a similar form of mutable state passing:

```<code>def mainmenu():
    state={}
    addplayers(state)
def addplayers(state):
    state['player_info'] = {}
</code>```

For some forms of programming, immutable state is far preferable (in particular, multithreading where data is shared, or to keep a log where you can undo steps). That's done similarly but you make a new state for each call:

```<code>def mainmenu():
    state = {}
    state = addplayers(state)
def addplayers(oldstate):
    newstate = oldstate.copy()
    newstate['player_info'] = {}
    return newstate
</code>```

Python isn't designed for this and doesn't really have a mode to keep you from inadvertently modifying mutable types. Some types can be converted to similar types that are immutable, like frozenset or tuple.

One of the weirder hacks we can do is calling a Python function with a different set of globals than it normally has. This can be abused to take your existing functions, global statements and all, and have them use a different variable:

```<code>fakeglobals = mainmenu.__globals__.copy()
exec(addplayers.__code__, fakeglobals)
</code>```

Your original code has calls back and forth between functions, though, and each of those will reset their globals per that __globals__ attribute.

Your code also implements a loop using tail recursion. This is not optimized in Python and will run out of stack space eventually. In languages where tail recursion is optimized, you can pass along state as arguments continously and need not return it.

Body:
I have the following program and the variable(dictionary) in question is player_info that stores player information (name and goals). In order to solve the error that results currently, I simply need to make player_info a global variable, but I was wondering if stackoverflow experts could suggest or discuss the possibility of alternate ways of solving this problem WITHOUT the use of global variables.

Code

#FOOTBALL COACH app

#The program allows a user to enter a number of players (their names and goals scored) and then search for a player, returning their average goals for the three matches

import sys
def main():
 mainmenu()

def mainmenu():

  print("=====WELCOME to the MAIN MENU=============")
  print("""
  1..........Add New Players & Goals
  2..........Search by Players
  3..........Quit

  =========================================
  """)

  choice=int(input("Enter choice:"))
  if choice==1:
    addplayers()
  elif choice==2:
    searchplayer(player_info)
  elif choice==3:
    sys.exit()
  else:
    print("You must make a valid choice - 1, 2 or 3")

def addplayers():

  player_info= {} #create a dictionary that stores the player name: player goals

  num_players = int(input("Please enter number of players you wish to enter:"))
  print ("You are entering %s players" %num_players)
  player_data = ['Match 1 goals : ', 'Match 2 goals : ', 'Match 3 goals : ']
  for i in range(0,num_players):
      player_name = input("Enter Player Name :")
      player_info[player_name] = {}
      for entry in player_data:
          player_info[player_name][entry] = int(input(entry)) #storing the marks entered as integers to perform arithmetic operations later on.

  mainmenu()

def searchplayer():
   print("===============SEARCH by player: Calculate average goals==================")
   name = input("Player name : ")
   if name in player_info.keys():
     #print student_info
      print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
   else:
      print("Please enter a valid player name:")

main()

As mentioned, I am aware that re-writing this in the addplayer() sub would fix the problem:

global player_info
player_info = {} #create a dictionary that stores the player name: player goals

...I am looking for ways to solve the problem WITHOUT the use of global variables.

Update:

One answer below using return player_info is what I would like to go with, but it doesn't quite work yet. Also, I need to return to the main menu each time a player is added, not quite sure how to do this, without a mainmenu call each time. Any suggestions? https://repl.it/JRl5/1

Body:
Firstly, it is always possible to avoid using global variables. Secondly, global variables are possibly a misnomer in Python; global stores the variable in the local globals, which is typically the local module. That avoids a large part of the problem languages like C have with globals, in that they collide; Python has a namespace per module. For a simple script, where there is only one context, that might be fine.

Another namespace you might use is that of a particular object, using a class. This might look like:

class Game:
    def mainmenu(self,...):
        self.addplayers()
    def addplayers(self):
        self.player_info = {}

With that sort of code, whoever instantiates Game can make multiple instances, each passed as self when used. This is in large part syntactic sugar for a similar form of mutable state passing:

def mainmenu():
    state={}
    addplayers(state)
def addplayers(state):
    state['player_info'] = {}

For some forms of programming, immutable state is far preferable (in particular, multithreading where data is shared, or to keep a log where you can undo steps). That's done similarly but you make a new state for each call:

def mainmenu():
    state = {}
    state = addplayers(state)
def addplayers(oldstate):
    newstate = oldstate.copy()
    newstate['player_info'] = {}
    return newstate

Python isn't designed for this and doesn't really have a mode to keep you from inadvertently modifying mutable types. Some types can be converted to similar types that are immutable, like frozenset or tuple.

One of the weirder hacks we can do is calling a Python function with a different set of globals than it normally has. This can be abused to take your existing functions, global statements and all, and have them use a different variable:

fakeglobals = mainmenu.__globals__.copy()
exec(addplayers.__code__, fakeglobals)

Your original code has calls back and forth between functions, though, and each of those will reset their globals per that __globals__ attribute.

Your code also implements a loop using tail recursion. This is not optimized in Python and will run out of stack space eventually. In languages where tail recursion is optimized, you can pass along state as arguments continously and need not return it.


问:
How to replace the UUID with random numbers using Friendly_id gem in rails?
Using Rails 4 and FriendlyId Gem version 5.Im new to Friendly id gem. Here I wanna replace my Url like profile-name-{4 (or) 5 length random numbers} instead of profile-name-Long-UUID . Thanks</p>

答:
```<code>Class Profile < ActiveRecord::Base
   extend FriendlyId
   friendly_id :slug_candidates, use: :slugged
   def slug_candidates
      [self.name, "%s %s" % [self.name, SecureRandom.hex(3)]]
   end
end
</code>```

Please click here for more reference

Body:
Class Profile < ActiveRecord::Base
   extend FriendlyId
   friendly_id :slug_candidates, use: :slugged
   def slug_candidates
      [self.name, "%s %s" % [self.name, SecureRandom.hex(3)]]
   end
end

Please click here for more reference


问:
Mapbox GL JS: zoom to filtered polygon?
I am using Mapbox GL JS to display a polygon layer. I would to allow the user to choose a name from a dropdown, and then highlight and zoom to the matching polygon.

I already know how to highlight the matching polygon using map.setFilter, but I don't know how to zoom to the bounds of the matching polygon. This is my current code:

```<code>map.addLayer({
    'id': 'polygon_hover',
    'source': 'mysource',
    'source-layer': 'mylayer',
    'type': 'fill',
    'paint': {
        'fill-color': 'red',
        "fill-opacity": 0.6
    },
    "filter": ["==", 'CUSTNAME', ""]
});
// Get details from dropdown
custname.on("change", function(e) {
    // get details of name from select event
    map.setFilter('polygon_hover', ["==", 'CUSTNAME', name]);
    // Get bounds of filtered polygon somehow?
    // var bounds = ??;
    // map.fitBounds(bounds);
});
</code>```

I have examined the Mapbox example of zooming to bounds, but it assumes that you already know what the bounds are.

Is there any way it's possible to get the bounds of the polygon matching a map filter in Mapbox?

答:
I've the following code to fitBounds to Polygon center coords:

```<code>var coordinates = f.geometry.coordinates[0];
var bounds = coordinates.reduce(function (bounds, coord) {
    return bounds.extend(coord);
}, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));

map.fitBounds(bounds, {
    padding: 20
});
</code>```

Where f is one Feature.

Title: Mapbox GL JS: zoom to filtered polygon?

Body:
I am using Mapbox GL JS to display a polygon layer. I would to allow the user to choose a name from a dropdown, and then highlight and zoom to the matching polygon.

I already know how to highlight the matching polygon using map.setFilter, but I don't know how to zoom to the bounds of the matching polygon. This is my current code:

map.addLayer({
    'id': 'polygon_hover',
    'source': 'mysource',
    'source-layer': 'mylayer',
    'type': 'fill',
    'paint': {
        'fill-color': 'red',
        "fill-opacity": 0.6
    },
    "filter": ["==", 'CUSTNAME', ""]
});
// Get details from dropdown
custname.on("change", function(e) {
    // get details of name from select event
    map.setFilter('polygon_hover', ["==", 'CUSTNAME', name]);
    // Get bounds of filtered polygon somehow?
    // var bounds = ??;
    // map.fitBounds(bounds);
});

I have examined the Mapbox example of zooming to bounds, but it assumes that you already know what the bounds are.

Is there any way it's possible to get the bounds of the polygon matching a map filter in Mapbox?

Body:
I've the following code to fitBounds to Polygon center coords:

var coordinates = f.geometry.coordinates[0];
var bounds = coordinates.reduce(function (bounds, coord) {
    return bounds.extend(coord);
}, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));

map.fitBounds(bounds, {
    padding: 20
});

Where f is one Feature.


问:
Long term caching with webpack chunkhash and cache control
I am using webpack to bundle all of my files. Inside webpack I use chunkhash,  Md5Hash and manifest to produce unique chunkhash for each of my files that get download by browser. It would look like this.

```<code>styles.3840duiel348fdjh385idfki.css
bundle.488503289dfksdlkor93lfui.js
vendor.sdkkfuuewkf892377rfkjdle.js
image.dkkdiiue9984ujjkfld003kfpp.png
</code>```

This means that browser can cache them and if the hash is not changed it will use the cached version.At the same time I can for example just change styles and only that hash will be changed so when I deploy the app browser will download only the new styles.

The problem is that on my server i use this:

```<code>Cache-Control: public max-age=31536000
</code>```

This represents aggressive caching and the browser will use cached version for one year unless URL, file name is changed. When I for example change styles my hash is changed and browser should request the new styles from server. That is according to this article(pattern 1) and a few more that I found https://jakearchibald.com/2016/caching-best-practices/

My problem is that when I update something, example styles, hash for styles is changed and I deploy that. The browser will not request new styles unles I hit reload while on my page. It will server the cached files. How can I fix this?

I can use Cache-Control: no-cache but that is not a solution because than browser has to check with server every time if he can use cached version. That is 4 http requests that are not needed every time someone visits the page.

答:
I did it like this. I use different webpack config for my client and server bundle. For my client bundle that has bundle.js, vendor.js, styles.css... I use chunkhash and Cache-Control: public max-age=31536000 as described in my question. For my server bundle that serves html(ejs) I use Cache-Control: no-cache. This works good because browser will contact server on every reload but that will be only one http request. If nothing is changed browser uses the cached version of all the assets since chunkhash in html didn't changed.

If for example I update styles and chunkhash is changed browser will see that when in contacts the server on reload and only new styles will be downloaded.

Body:
I am using webpack to bundle all of my files. Inside webpack I use chunkhash,  Md5Hash and manifest to produce unique chunkhash for each of my files that get download by browser. It would look like this.

styles.3840duiel348fdjh385idfki.css
bundle.488503289dfksdlkor93lfui.js
vendor.sdkkfuuewkf892377rfkjdle.js
image.dkkdiiue9984ujjkfld003kfpp.png

This means that browser can cache them and if the hash is not changed it will use the cached version.At the same time I can for example just change styles and only that hash will be changed so when I deploy the app browser will download only the new styles.

The problem is that on my server i use this:

Cache-Control: public max-age=31536000

This represents aggressive caching and the browser will use cached version for one year unless URL, file name is changed. When I for example change styles my hash is changed and browser should request the new styles from server. That is according to this article(pattern 1) and a few more that I found https://jakearchibald.com/2016/caching-best-practices/

My problem is that when I update something, example styles, hash for styles is changed and I deploy that. The browser will not request new styles unles I hit reload while on my page. It will server the cached files. How can I fix this?

I can use Cache-Control: no-cache but that is not a solution because than browser has to check with server every time if he can use cached version. That is 4 http requests that are not needed every time someone visits the page.


问:
Apply changes from Live Property Explorer in WPF
I am new to WPF.

I am debugging a simple program and playing around with the the Live Visual Tree and Live Property Explorer to make changes on the fly.

My simple question is, Can I apply those changes straight into my XAML code or to I have to keep 2 versions of Visual Studio open? One for Debugging and one for editing?

答:
Can I apply those changes straight into my XAML code or to I have to keep 2 versions of Visual Studio open?

No and Yes. Visual Studio won't update the XAML for you. You will have to do this manually yourself.

You may want to suggest this as a new Visual Studio feature on uservoice.com.


问:
App Freezes when Network connection is slow,Because a POST API Call happens on APP launch. Below is my Connection Manager code,Objective-C, iOS
//Below is the code i have used to perform simple httpPOST. But app hangs on App launch on splash screen and crashes . i am doing an API Call on applaunch in Appdelegate</p>

```<code>- (NSDictionary *)postUserRegWithUrl:(NSString *)urlString andParams:(NSString *)paramString{
NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                                                                                NULL,
                                                                                (CFStringRef)paramString,
                                                                                NULL,
                                                                                (CFStringRef)@"+",
                                                                                kCFStringEncodingUTF8 ));
NSDictionary *responseDictionary;
NSError *err;

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kBaseProdURL,urlString]]];

NSData *data = [encodedString dataUsingEncoding:NSUTF8StringEncoding];
[request setTimeoutInterval:60.0];
 [request setHTTPMethod:@"POST"];
[request setHTTPBody:data];
NSLog(@"the data Details is =%@", request);
NSURLResponse *response;

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];

NSLog(@"got response==%@", resSrt);

if(resSrt.length)
{

    responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&err];

    NSLog(@"Response dictionary formed is =%@", responseDictionary);
} else {

    NSLog(@"failed to connect");

        [self showAlertViewTitle:@"Please try later" withMessage:@"Something went wrong"];

}
return responseDictionary;
</code>```

<p>} </p>

答: You shouldn't execute your network calls synchronously, especially on main thread. Either use sendAsynchronousRequest or just use any good networking library, like AFNetworking, which do this out of the box.

Body:
//Below is the code i have used to perform simple httpPOST. But app hangs on App launch on splash screen and crashes . i am doing an API Call on applaunch in Appdelegate

- (NSDictionary *)postUserRegWithUrl:(NSString *)urlString andParams:(NSString *)paramString{
NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                                                                                NULL,
                                                                                (CFStringRef)paramString,
                                                                                NULL,
                                                                                (CFStringRef)@"+",
                                                                                kCFStringEncodingUTF8 ));
NSDictionary *responseDictionary;
NSError *err;

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kBaseProdURL,urlString]]];

NSData *data = [encodedString dataUsingEncoding:NSUTF8StringEncoding];
[request setTimeoutInterval:60.0];
 [request setHTTPMethod:@"POST"];
[request setHTTPBody:data];
NSLog(@"the data Details is =%@", request);
NSURLResponse *response;

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];

NSLog(@"got response==%@", resSrt);

if(resSrt.length)
{

    responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&err];

    NSLog(@"Response dictionary formed is =%@", responseDictionary);
} else {

    NSLog(@"failed to connect");

        [self showAlertViewTitle:@"Please try later" withMessage:@"Something went wrong"];

}
return responseDictionary;

}


问:
How to style hint for EditText with inputType set to textPassword in Android
Style of text for hint changes when I set inputType=textPassword in my EditText. Please see this image:

Both EditTexts have same XML but the upper has inputType set to textPassword.

How do I make them look the same?

答:
Set Edittext Typeface default programmatically</p>

```<code>password.setTypeface(Typeface.DEFAULT);
</code>```

Body:
Set Edittext Typeface default programmatically

password.setTypeface(Typeface.DEFAULT);


问:
FBML tab control replacement?
Facebook is deprecating FBML and recommending JavaScript SDK (on Graph API) with Social Plugins to implement features inside an iFrame app.

If FBML goes away so does its controls including the tabs FBML.  Excerpt:

fb:tabs

  Advanced Topics › Legacy FBML › fb:tabs

  Renders a group of standard
  Facebook navigation tabs. Must contain
  at least one fb:tab-item.

Is there a Facebook replacement for the tabs UI control, or is it now left up to the developer to find their own tab control for use in iFrame apps?

Another potential avenue is XFBML - I think if Facebook is deprecating FBML then they might be deprecating XFBML by inference, but I cannot find a definitive statement about this. FBML might refer to the type of app, or it might refer to the tags because FBML tags can be used inside an iFrame (i.e. usedoutside of an official FBML application).  I would choose to use XFBML in an iFrame app if it's not being deprecated with standard FBML.

答: Apparently you have to find your own tab ui technology (same for other specialized controls offered by FBML).  It's best left up to the programming technology used in your iFrame pages. e.g. PHP, ASP.NET, jQuery, etc. </p>

ContentLicense: CC BY-SA 2.5

Title: FBML tab control replacement?


问:
How can I connect two Android device by socket without server
I am trying to develop an android application that can exchange data on peer to peer connection with other devices without server. So please suggest how can I do this. Thank you in advance.</p>

答:
If you're looking for such P2P over a local network, there are two parts to it:

Discovering peers

Communicating with peers

Among Android APIs, you can either use Network Service Discovery APIs for this or Wifi P2P Service Discovery APIs.

There's a wrapper library which which uses these internally and has comparatively better documentation - Salut, which can also be used.

I also created a library for P2P - Near, which uses sockets directly. The problem I was facing with Android APIs was that discovery wasn't happening with certainty every time and the underlying issue was unknown.

If you're looking for P2P across the internet, socket IO is a prevalent solution. Even Near should be able to facilitate the transfers if you provide the IP addresses and they're not behind NAT firewalls.


问:
Gson parse map object without key
can someone explain me, how I can parse JSON

```<code>{
"5": {
    "NumPossibleAchievements": "2",
    "PossibleScore": "15",
    "NumAchieved": 0,
    "ScoreAchieved": 0,
    "NumAchievedHardcore": 0,
    "ScoreAchievedHardcore": 0
},
"1838": {
    "NumPossibleAchievements": "48",
    "PossibleScore": "400",
    "NumAchieved": "48",
    "ScoreAchieved": "400",
    "NumAchievedHardcore": "48",
    "ScoreAchievedHardcore": "400"
},
"7634": {
    "NumPossibleAchievements": 0,
    "PossibleScore": 0,
    "NumAchieved": 0,
    "ScoreAchieved": 0,
    "NumAchievedHardcore": 0,
    "ScoreAchievedHardcore": 0
}
}
</code>```

Now I've class that I want use for response

```<code>public class UserProgress {

private Map<String, Progress> userProgress;

public Map<String, Progress> getUserProgress() {
    return userProgress;
}
}
</code>```

Also class that represent inner object in this map

```<code>public class Progress {

@SerializedName("NumPossibleAchievements")
private String numPossibleAchievements;
@SerializedName("PossibleScore")
private String possibleScore;
@SerializedName("NumAchieved")
private int numAchieved;
@SerializedName("ScoreAchieved")
private int scoreAchieved;
@SerializedName("NumAchievedHardcore")
private int numAchievedHardcore;
@SerializedName("ScoreAchievedHardcore")
private int scoreAchievedHardcore;

.....
</code>```

And custom deserializer that should parse this type JSON to normal object. This deserializer I added to retrofit converter.

```<code>public class UserProgressDeserializer implements JsonDeserializer<UserProgress> {

@Override
public UserProgress deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    final JsonObject jsonObject = json.getAsJsonObject();
    final Map<String, Progress> parameters = readParametersMap(jsonObject);
    final UserProgress result = new UserProgress();

    if (parameters != null) result.setUserProgress(parameters);
    return result;
}

@Nullable
private Map<String, Progress> readParametersMap(@NonNull final JsonObject jsonObject) {
    final JsonElement paramsElement = jsonObject.getAsJsonObject();
    if (paramsElement == null) return null;

    final JsonObject parametersObject = paramsElement.getAsJsonObject();
    final Map<String, Progress> parameters = new HashMap<>();
    for (Map.Entry<String, JsonElement> entry : parametersObject.entrySet()) {
        String key = entry.getKey();
        Progress value = new Gson().fromJson(entry.getValue().getAsString(), Progress.class);
        parameters.put(key, value);
    }
    return parameters;
}
}
</code>```

And my request

```<code>@GET("API_GetUserProgress.php")
Flowable<UserProgress> getUserProgress(@Query("u") @NonNull String userName,
                                                     @Query("i") String gamesCSV);
</code>```

Request work, in raw body I see that JSON, but object contains empty map. I tested with breakpoints, but it never goes into deserializer. Now my idea is create custom function that will parse JSON string from response raw body, but this will be spike.

Thanks for any help

答:
UPD:
Seems like GSON accepts Map for objects out of the box and cast those objects to LinkedTreeMap. So, all we needed was to change request return type.

```<code>Flowable<Map<String, Progress>> getUserProgress(@Query("u") @NonNull String userName,
                                                @Query("i") String gamesCSV);
</code>```

REDUNDANT

I had no success with custom deserializer, so I implemented new function that accepts JSON string from raw response, maps result to list of required objects. And now it looks like

```<code>Flowable<ResponseBody> flowable = USERS_API.getUserProgress(userName, gameIDsCSV);
    return manageRequestWithMapper(flowable, responseBody -> {
        String body = responseBody.string();
        JSONObject yourJSON = new JSONObject(body);
        Iterator<String> keysIterator = yourJSON.keys();
        List<Progress> tempList = new ArrayList<>();
        while (keysIterator.hasNext()) {
            String key = keysIterator.next();
            JSONObject actualObj = (JSONObject) yourJSON.get(key);
            tempList.add((new Gson()).fromJson(actualObj.toString(), Progress.class));
        }
        return tempList;
    });
</code>```

Title: Gson parse map object without key

Body:
can someone explain me, how I can parse JSON

{
"5": {
    "NumPossibleAchievements": "2",
    "PossibleScore": "15",
    "NumAchieved": 0,
    "ScoreAchieved": 0,
    "NumAchievedHardcore": 0,
    "ScoreAchievedHardcore": 0
},
"1838": {
    "NumPossibleAchievements": "48",
    "PossibleScore": "400",
    "NumAchieved": "48",
    "ScoreAchieved": "400",
    "NumAchievedHardcore": "48",
    "ScoreAchievedHardcore": "400"
},
"7634": {
    "NumPossibleAchievements": 0,
    "PossibleScore": 0,
    "NumAchieved": 0,
    "ScoreAchieved": 0,
    "NumAchievedHardcore": 0,
    "ScoreAchievedHardcore": 0
}
}

Now I've class that I want use for response

public class UserProgress {

private Map<String, Progress> userProgress;

public Map<String, Progress> getUserProgress() {
    return userProgress;
}
}

Also class that represent inner object in this map

public class Progress {

@SerializedName("NumPossibleAchievements")
private String numPossibleAchievements;
@SerializedName("PossibleScore")
private String possibleScore;
@SerializedName("NumAchieved")
private int numAchieved;
@SerializedName("ScoreAchieved")
private int scoreAchieved;
@SerializedName("NumAchievedHardcore")
private int numAchievedHardcore;
@SerializedName("ScoreAchievedHardcore")
private int scoreAchievedHardcore;

.....

And custom deserializer that should parse this type JSON to normal object. This deserializer I added to retrofit converter.

public class UserProgressDeserializer implements JsonDeserializer<UserProgress> {

@Override
public UserProgress deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    final JsonObject jsonObject = json.getAsJsonObject();
    final Map<String, Progress> parameters = readParametersMap(jsonObject);
    final UserProgress result = new UserProgress();

    if (parameters != null) result.setUserProgress(parameters);
    return result;
}

@Nullable
private Map<String, Progress> readParametersMap(@NonNull final JsonObject jsonObject) {
    final JsonElement paramsElement = jsonObject.getAsJsonObject();
    if (paramsElement == null) return null;

    final JsonObject parametersObject = paramsElement.getAsJsonObject();
    final Map<String, Progress> parameters = new HashMap<>();
    for (Map.Entry<String, JsonElement> entry : parametersObject.entrySet()) {
        String key = entry.getKey();
        Progress value = new Gson().fromJson(entry.getValue().getAsString(), Progress.class);
        parameters.put(key, value);
    }
    return parameters;
}
}

And my request

@GET("API_GetUserProgress.php")
Flowable<UserProgress> getUserProgress(@Query("u") @NonNull String userName,
                                                     @Query("i") String gamesCSV);

Request work, in raw body I see that JSON, but object contains empty map. I tested with breakpoints, but it never goes into deserializer. Now my idea is create custom function that will parse JSON string from response raw body, but this will be spike.

Thanks for any help

Body:
UPD:
Seems like GSON accepts Map for objects out of the box and cast those objects to LinkedTreeMap. So, all we needed was to change request return type.

Flowable<Map<String, Progress>> getUserProgress(@Query("u") @NonNull String userName,
                                                @Query("i") String gamesCSV);

REDUNDANT

I had no success with custom deserializer, so I implemented new function that accepts JSON string from raw response, maps result to list of required objects. And now it looks like

Flowable<ResponseBody> flowable = USERS_API.getUserProgress(userName, gameIDsCSV);
    return manageRequestWithMapper(flowable, responseBody -> {
        String body = responseBody.string();
        JSONObject yourJSON = new JSONObject(body);
        Iterator<String> keysIterator = yourJSON.keys();
        List<Progress> tempList = new ArrayList<>();
        while (keysIterator.hasNext()) {
            String key = keysIterator.next();
            JSONObject actualObj = (JSONObject) yourJSON.get(key);
            tempList.add((new Gson()).fromJson(actualObj.toString(), Progress.class));
        }
        return tempList;
    });


问:
I am updating this in view file by clicking it and want to show in view file without refreshing it
```<code>$scope.pause = function(userid){

    var id = $scope.userid;
    var status = 3;

    getClients.status(id,status).then(function(response)
    {
        console.log('Response',response);
        $scope.clients = response.data;
        console.log('Data',$scope.clients);

        $scope.cancel();
    });

};
</code>```

I am updating this  in view file by clicking it and want to show in view file without refreshing it.

答:
Solution,

HTML

```<code><div ng-controller="controllerName" ng-int="getData()">

</div>
</code>```

JS

```<code>    app.controller("name",fucntion(){

    $scope.getData = function(){
      //api call to get data from database
       $scope.data = resultData;
    }

    $scope.yourEditFunction = function(){
    //make API call to update data in database
    $scope.getData();
   }

    })
</code>```

But ideally if you assign your get API result to an $scope variable and later in edit function update it then there is no need to refresh page angular will update the data for you.

Body:
$scope.pause = function(userid){

    var id = $scope.userid;
    var status = 3;

    getClients.status(id,status).then(function(response)
    {
        console.log('Response',response);
        $scope.clients = response.data;
        console.log('Data',$scope.clients);

        $scope.cancel();
    });

};

I am updating this  in view file by clicking it and want to show in view file without refreshing it.

Body:
Solution,

HTML

<div ng-controller="controllerName" ng-int="getData()">

</div>

JS

    app.controller("name",fucntion(){

    $scope.getData = function(){
      //api call to get data from database
       $scope.data = resultData;
    }

    $scope.yourEditFunction = function(){
    //make API call to update data in database
    $scope.getData();
   }

    })

But ideally if you assign your get API result to an $scope variable and later in edit function update it then there is no need to refresh page angular will update the data for you.


问:
Range Selection in Matlab
I defined a matrix 6 by 6 and want to make a change in values in some ranges.

```<code>c = floor(rand(6,6) * 100)
</code>```

the result:

```<code>22    26    10     2     9     3
38    82    90    42    59     6
58    98    87    31    47    31
25    73    81    16    69    53
29    34    26    17    69    65
61    58    59    42    63    40
</code>```

then I run:

```<code>c(c(1:3,:)<17) = 0

22     0     0     2     9     3
38    82    90    42    59     6
58    98    87    31    47    31
25     0     0    16    69    53
29    34     0    17    69    65
61    58    59    42    63    40
</code>```

I want to make elements in rows between 1 and 3 which are less than 17 zero, but the result seems wrong to me! any idea?

答:
This does not work because you are getting linear indices from your condition and the size of the submatrix is different from that of the original one.
You can first get the subscripts and then change your original matrix:

```<code>c = floor(rand(6,6) * 100)
c =

28    60    24    48    20    99
 0    78    34    80    38    70
49    11    54    37    66     8
98    57     6    51    75     4
73    87    41     9    17    49
31    68    23    90    51    44

[a,b]=find(c(1:3,:)<17);
c(sub2ind(size(c),a,b))=0
c =

28    60    24    48    20    99
 0    78    34    80    38    70
49     0    54    37    66     0
98    57     6    51    75     4
73    87    41     9    17    49
31    68    23    90    51    44
</code>```

please note that if you dont start from the first row or the first column, you should consider the difference:

```<code>[a,b]=find(c(3:6,2:5)<17);
c(sub2ind(size(c),a+2,b+1))=0
</code>```

Another solution is to create a mask matrix of indicies to use for the substitution. This would also work in the general case of not starting from the first row or column:

```<code>idx = zeros(size(c));
idx(1:3,:) = c(1:3,:)<17;
c(idx==1) = 0
</code>```

Title: Range Selection in Matlab

Body:
I defined a matrix 6 by 6 and want to make a change in values in some ranges.

c = floor(rand(6,6) * 100)

the result:

22    26    10     2     9     3
38    82    90    42    59     6
58    98    87    31    47    31
25    73    81    16    69    53
29    34    26    17    69    65
61    58    59    42    63    40

then I run:

c(c(1:3,:)<17) = 0

22     0     0     2     9     3
38    82    90    42    59     6
58    98    87    31    47    31
25     0     0    16    69    53
29    34     0    17    69    65
61    58    59    42    63    40

I want to make elements in rows between 1 and 3 which are less than 17 zero, but the result seems wrong to me! any idea?

Body:
This does not work because you are getting linear indices from your condition and the size of the submatrix is different from that of the original one.
You can first get the subscripts and then change your original matrix:

c = floor(rand(6,6) * 100)
c =

28    60    24    48    20    99
 0    78    34    80    38    70
49    11    54    37    66     8
98    57     6    51    75     4
73    87    41     9    17    49
31    68    23    90    51    44

[a,b]=find(c(1:3,:)<17);
c(sub2ind(size(c),a,b))=0
c =

28    60    24    48    20    99
 0    78    34    80    38    70
49     0    54    37    66     0
98    57     6    51    75     4
73    87    41     9    17    49
31    68    23    90    51    44

please note that if you dont start from the first row or the first column, you should consider the difference:

[a,b]=find(c(3:6,2:5)<17);
c(sub2ind(size(c),a+2,b+1))=0

Another solution is to create a mask matrix of indicies to use for the substitution. This would also work in the general case of not starting from the first row or column:

idx = zeros(size(c));
idx(1:3,:) = c(1:3,:)<17;
c(idx==1) = 0


答:
The problem is text  setTypeface.

Tip: By default, when you set an EditText element to use the
  "textPassword" input type, the font family is set to monospace, so you
  should change its font family to "sans-serif" so that both text fields
  use a matching font style.

For more details please refer this link,
Try

Title: How to style hint for EditText with inputType set to textPassword in Android

Body:
Style of text for hint changes when I set inputType=textPassword in my EditText. Please see this image:

Both EditTexts have same XML but the upper has inputType set to textPassword.

How do I make them look the same?


问:
drupal------how to output it
this is the code in my module file. if i only want to print the second or the third value or another value., how should i do?

```<code>function alterlink_address(){   //page callback function
$sql = db_query("SELECT field_link_url FROM {content_type_address}");
while ($q = db_fetch_object($sql)){

return $q->field_link_url.'<br>';
</code>```

}
    }

答:
I'm no drupal expert and there will surely be a more economic way, but this will still work:

```<code>function alterlink_address(){   //page callback function
   $sql = db_query("SELECT field_link_url FROM {content_type_address}");
   while ($q = db_fetch_object($sql)){
      $results[] = $q->field_link_url.'<br>';
   }
   return $results[0]."<br />";
}
</code>```

Where the 0 in square brackets is the number (starting from 0) of the result you want to return.

A couple of notes:

a correct indentation can save lives;

getting a plethora of results from the database and displaying just a few of them is a nice method to awaken Cthulhu. I suggest you take a look at the drupal docs to get directly just the results you need.

Title: drupal------how to output it

Body:
this is the code in my module file. if i only want to print the second or the third value or another value., how should i do?

function alterlink_address(){   //page callback function
$sql = db_query("SELECT field_link_url FROM {content_type_address}");
while ($q = db_fetch_object($sql)){

return $q->field_link_url.'
';

}
    }

Body:
I'm no drupal expert and there will surely be a more economic way, but this will still work:

function alterlink_address(){   //page callback function
   $sql = db_query("SELECT field_link_url FROM {content_type_address}");
   while ($q = db_fetch_object($sql)){
      $results[] = $q->field_link_url.'<br>';
   }
   return $results[0]."<br />";
}

Where the 0 in square brackets is the number (starting from 0) of the result you want to return.

A couple of notes:

a correct indentation can save lives;

getting a plethora of results from the database and displaying just a few of them is a nice method to awaken Cthulhu. I suggest you take a look at the drupal docs to get directly just the results you need.


问:
Ascending order with three integers for C++
```<code>#include <iostream>

using namespace std;

int main()
{
    int a;
    int b;
    int c;

    cout << "Please input three integers:" << endl;
    cout << ">> ";
    cin >> a >> b >> c;
    cout << endl;

    if (((a == a) && (b > a)) && (c >= a))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << a << " " << c << " " << b;
    }
    else if (((a == a) && (b >= a)) && (c >= a))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << a << " " << b << " " << c;
    }
    else if (((a > b) && (b == b)) && (c >= b))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << b << " " << c << " " << a;
    }
    else if (((a >= b) && (b == b)) && (c < b))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << c << " " << a << " " << b;
    }
    else if (((a > c) && (b >= c)) && (c == c))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << c << " " << b << " " << a;
    }
    else if (((a >= c) && (b <= c)) && (c == c))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << b << " " << c << " " << a;
    }

    return 0;
}
</code>```

<p>For this assignment, I used 1, 2, and 3 for entering the integer.
My question is why these input (1, 2, 3) and (2, 1, 3) and (3, 2, 1)
don't ascended properl?   </p>

答:
You have the right number of cases (6 possible orderings) but the conditions are wrong. I will only go through the first one...

```<code>if (((a == a) && (b > a)) && (c >= a)) {
        cout << a << " " << c << " " << b;
}
</code>```

An input that would pass the condition is a=1,b=2, c=3, but 1 3 2 is not the correct order. To be certain that a c b is ascending, you need

```<code>if (( c >= a) && (b >= c))
</code>```

(You dont need a third one here, because by transitivity, if c>=a and b>=c then also b>=a holds.

Body:
#include <iostream>

using namespace std;

int main()
{
    int a;
    int b;
    int c;

    cout << "Please input three integers:" << endl;
    cout << ">> ";
    cin >> a >> b >> c;
    cout << endl;

    if (((a == a) && (b > a)) && (c >= a))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << a << " " << c << " " <= a)) && (c >= a))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << a << " " << b << " " << c;
    }
    else if (((a > b) && (b == b)) && (c >= b))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << b << " " << c << " " <= b) && (b == b)) && (c < b))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << c << " " << a << " " < c) && (b >= c)) && (c == c))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << c << " " << b << " " <= c) && (b <= c)) && (c == c))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << b << " " << c << " " << a;
    }

    return 0;
}

For this assignment, I used 1, 2, and 3 for entering the integer.
My question is why these input (1, 2, 3) and (2, 1, 3) and (3, 2, 1)
don't ascended properl?

Body:
You have the right number of cases (6 possible orderings) but the conditions are wrong. I will only go through the first one...

if (((a == a) && (b > a)) && (c >= a)) {
        cout << a << " " << c << " " << b;
}

An input that would pass the condition is a=1,b=2, c=3, but 1 3 2 is not the correct order. To be certain that a c b is ascending, you need

if (( c >= a) && (b >= c))

(You dont need a third one here, because by transitivity, if c>=a and b>=c then also b>=a holds.


问:
dependent dynamic dropdown in php
Here I have two dependent drop downs.
    First drop down is displaying all accounts(name and id).

```<code><select name="account" id="account" class="input-name">
<?php
$query = "SELECT id,name FROM account";
$results = mysqli_query(con, $query);
while($account = $results ->fetch_assoc()){
?>
<option value="<?php echo $account["id"]; ?>"><?php echo $account["name].'-'.$account["id"];?</option>
<?php } ?>
</select>
</code>```

In second drop down I need to display selected account users.

```<code> <select name="extension" id="extension" class="input-name">
    <?php
    $query = "SELECT ext FROM user WHERE account=100"; //Query for users for selected account.

    $results = mysqli_query($con, $query);
    while($user= $results ->fetch_assoc()){
    ?>
<option value="<?php echo $user["ext"]; ?>"><?php echo $users["ext"];?></option>
<?php } ?>
</select>
</code>```

How can I filter users according to select company. Need help.

答:
You may reload page after first value was selected and load page with second param. for example </p>

```<code><select onchange="window.location.href='some url with some value?select_value=' + this.value">...options...</select>"
</code>```

<p>Or if you do not want to reload page you can use AJAX. send request with ajax to server and replace options in second select.
with jquery </p>

```<code>$('select.first-select').change(function(){
    var value = $(this).val();
    $.get('get-account', { val: value }, function(){ ...replace options... })
})
</code>```

Title: dependent dynamic dropdown in php

Body:
Here I have two dependent drop downs.
    First drop down is displaying all accounts(name and id).

<select name="account" id="account" class="input-name">
<?php
$query = "SELECT id,name FROM account";
$results = mysqli_query(con, $query);
while($account = $results ->fetch_assoc()){
?>
<option value="<?php echo $account["id"]; ?>"><?php echo $account["name].'-'.$account["id"];?</option>
<?php } ?>
</select>

In second drop down I need to display selected account users.

 <select name="extension" id="extension" class="input-name">
    <?php
    $query = "SELECT ext FROM user WHERE account=100"; //Query for users for selected account.

    $results = mysqli_query($con, $query);
    while($user= $results ->fetch_assoc()){
    ?>
<option value="<?php echo $user["ext"]; ?>"><?php echo $users["ext"];?></option>
<?php } ?>
</select>

How can I filter users according to select company. Need help.

Body:
You may reload page after first value was selected and load page with second param. for example

<select onchange="window.location.href='some url with some value?select_value=' + this.value">...options...</select>"

Or if you do not want to reload page you can use AJAX. send request with ajax to server and replace options in second select.
with jquery

$('select.first-select').change(function(){
    var value = $(this).val();
    $.get('get-account', { val: value }, function(){ ...replace options... })
})


问:
Tensorflow LinearClassifier() always guesses negative class
I'm currently implementing a logistic regressor using tensorflow according to their 'wide' tutorial: https://www.tensorflow.org/tutorials/wide

My code pretty much matches the tutorial, however, when I run predict() on the model, it guesses the negative class every time, which is about 77% of the data.  How can I get my model to venture some positive guesses? I am not regularizing so variance should be at a max. The documentation boasted 84 percent accuracy and I am using exactly the same dataset.  What could be going wrong? Here is the training code:

```<code>def train_logistic_model(training_path, response, predictors, num_labels):

    # Get csv
    df_train = pd.read_csv(training_path, header=0)

    # Sanitize column names
    unsanitized_column_names = df_train.columns.values
    column_names = []
    for col in unsanitized_column_names:
        column_names.append(re.sub('[^A-Za-z0-9]+', '', col))

    # Update dataframe with sanitized column names
    df_train = pd.read_csv(training_path, names=column_names, skiprows=1)

    # Slice off %10 of training data to test with
    df_test = df_train.loc[(len(df_train.index) * .9):]
    df_train = df_train.loc[:(len(df_train.index) * .9)]

    response_name = column_names[response]

    LABEL_COLUMN = "label"
    df_train[LABEL_COLUMN] = (df_train[response_name].apply(lambda x: ">50K" in x)).astype(int)
    df_test[LABEL_COLUMN] = (df_test[response_name].apply(lambda x: ">50K" in x)).astype(int)

    del df_train[response_name]
    del df_test[response_name]

    # remove NaN elements
    df_train = df_train.dropna(how='any', axis=0)
    df_test = df_test.dropna(how='any', axis=0)

    CATEGORICAL_COLUMNS = []
    CONTINUOUS_COLUMNS = []
    for key, value in predictors.items():
        if value == 'Categorical':
            CATEGORICAL_COLUMNS.append(column_names[key])
        elif value == 'Continuous':
            CONTINUOUS_COLUMNS.append(column_names[key])

    # Input bulder function
    def input_fn(df):
        continuous_cols = {k: tf.constant(df[k].values) for k in CONTINUOUS_COLUMNS}

        categorical_cols = {
            k: tf.SparseTensor(
                indices=[[i, 0] for i in range(df[k].size)],
                values=df[k].values,
                dense_shape=[df[k].size, 1]) for k in CATEGORICAL_COLUMNS
            }

        # Merges the two dictionaries into one.
        feature_cols = {**continuous_cols, **categorical_cols}

        label = tf.constant(df[LABEL_COLUMN].values)

        return feature_cols, label

    def train_input_fn():
        return input_fn(df_train)

    def eval_input_fn_test():
        return input_fn(df_test)

    cat_tensors = []
    for col in CATEGORICAL_COLUMNS:
        cat_tensors.append(tf.contrib.layers.sparse_column_with_hash_bucket(
            column_name=col, hash_bucket_size=100))

    cont_tensors = []
    for cont in CONTINUOUS_COLUMNS:
        cont_tensors.append(tf.contrib.layers.real_valued_column(cont))

    feature_columns = cat_tensors + cont_tensors

    model_dir = tempfile.mkdtemp()

    logistic_model = tf.contrib.learn.LinearClassifier(feature_columns=feature_columns, n_classes=num_labels, model_dir=model_dir)

    logistic_model.fit(input_fn=train_input_fn, steps=200)

    # Test the model on reserve data
    eval_result_test = logistic_model.evaluate(input_fn=eval_input_fn_test, steps=1)

    # Test the model on training data
    eval_result_train = logistic_model.evaluate(input_fn=eval_input_fn_train, steps=1)

    for key in sorted(eval_result_train):
        print("%s: %s" % (key, eval_result_train[key]))

    return eval_result_test, model_dir
</code>```

答: I guess, you need to add cross_columns to make our linear model works better.</p>

Body:
I'm currently implementing a logistic regressor using tensorflow according to their 'wide' tutorial: https://www.tensorflow.org/tutorials/wide

My code pretty much matches the tutorial, however, when I run predict() on the model, it guesses the negative class every time, which is about 77% of the data.  How can I get my model to venture some positive guesses? I am not regularizing so variance should be at a max. The documentation boasted 84 percent accuracy and I am using exactly the same dataset.  What could be going wrong? Here is the training code:

def train_logistic_model(training_path, response, predictors, num_labels):

    # Get csv
    df_train = pd.read_csv(training_path, header=0)

    # Sanitize column names
    unsanitized_column_names = df_train.columns.values
    column_names = []
    for col in unsanitized_column_names:
        column_names.append(re.sub('[^A-Za-z0-9]+', '', col))

    # Update dataframe with sanitized column names
    df_train = pd.read_csv(training_path, names=column_names, skiprows=1)

    # Slice off %10 of training data to test with
    df_test = df_train.loc[(len(df_train.index) * .9):]
    df_train = df_train.loc[:(len(df_train.index) * .9)]

    response_name = column_names[response]

    LABEL_COLUMN = "label"
    df_train[LABEL_COLUMN] = (df_train[response_name].apply(lambda x: ">50K" in x)).astype(int)
    df_test[LABEL_COLUMN] = (df_test[response_name].apply(lambda x: ">50K" in x)).astype(int)

    del df_train[response_name]
    del df_test[response_name]

    # remove NaN elements
    df_train = df_train.dropna(how='any', axis=0)
    df_test = df_test.dropna(how='any', axis=0)

    CATEGORICAL_COLUMNS = []
    CONTINUOUS_COLUMNS = []
    for key, value in predictors.items():
        if value == 'Categorical':
            CATEGORICAL_COLUMNS.append(column_names[key])
        elif value == 'Continuous':
            CONTINUOUS_COLUMNS.append(column_names[key])

    # Input bulder function
    def input_fn(df):
        continuous_cols = {k: tf.constant(df[k].values) for k in CONTINUOUS_COLUMNS}

        categorical_cols = {
            k: tf.SparseTensor(
                indices=[[i, 0] for i in range(df[k].size)],
                values=df[k].values,
                dense_shape=[df[k].size, 1]) for k in CATEGORICAL_COLUMNS
            }

        # Merges the two dictionaries into one.
        feature_cols = {**continuous_cols, **categorical_cols}

        label = tf.constant(df[LABEL_COLUMN].values)

        return feature_cols, label

    def train_input_fn():
        return input_fn(df_train)

    def eval_input_fn_test():
        return input_fn(df_test)

    cat_tensors = []
    for col in CATEGORICAL_COLUMNS:
        cat_tensors.append(tf.contrib.layers.sparse_column_with_hash_bucket(
            column_name=col, hash_bucket_size=100))

    cont_tensors = []
    for cont in CONTINUOUS_COLUMNS:
        cont_tensors.append(tf.contrib.layers.real_valued_column(cont))

    feature_columns = cat_tensors + cont_tensors

    model_dir = tempfile.mkdtemp()

    logistic_model = tf.contrib.learn.LinearClassifier(feature_columns=feature_columns, n_classes=num_labels, model_dir=model_dir)

    logistic_model.fit(input_fn=train_input_fn, steps=200)

    # Test the model on reserve data
    eval_result_test = logistic_model.evaluate(input_fn=eval_input_fn_test, steps=1)

    # Test the model on training data
    eval_result_train = logistic_model.evaluate(input_fn=eval_input_fn_train, steps=1)

    for key in sorted(eval_result_train):
        print("%s: %s" % (key, eval_result_train[key]))

    return eval_result_test, model_dir


问:
-event- can only appear on the left hand side of += or -=
I have an event in a loop. I am trying to prevent the same method being added to an event more than once. I've implemented the add and remove accessors.

However, I get an error stating that:

ItemsProcessed can only appear on the left hand side of += or -=

When I try to call them, even within the same class.

```<code>ItemsProcessed(this, new EventArgs()); // Produces error

public event EventHandler ItemsProcessed
{
    add
    {
        ItemsProcessed -= value;
        ItemsProcessed += value;
    }
    remove
    {
        ItemsProcessed -= value;
    }
}
</code>```

答:
What error? I guess its stack overflow error, because you are calling add and remove on yourserlf (same event). Also you cannot raise event ACCESSOR.

Valid way to do this is to create backing private event, that will be added and removed to from public accessor, and you should raise this private event.

Dang, minute late.

Body:
I have an event in a loop. I am trying to prevent the same method being added to an event more than once. I've implemented the add and remove accessors.

However, I get an error stating that:

ItemsProcessed can only appear on the left hand side of += or -=

When I try to call them, even within the same class.

ItemsProcessed(this, new EventArgs()); // Produces error

public event EventHandler ItemsProcessed
{
    add
    {
        ItemsProcessed -= value;
        ItemsProcessed += value;
    }
    remove
    {
        ItemsProcessed -= value;
    }
}


问:
How do i put my 1000+ line console data in a txt file?
i tried the following code but it gets stuck on String lineFromInput = in.readLine(); line and without this line , the txt file is empty.

the code i used is :

```<code>    try
    {
        File file = new File("out.txt"); //Your file
        FileOutputStream fos = new FileOutputStream(file);
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String lineFromInput = in.readLine();
        PrintStream ps = new PrintStream(fos);
        System.setOut(ps);
        ps.println(lineFromInput);
        //  System.out.println("This goes to out.txt");
    }
    catch(IOException e)
    {
    System.out.println("Error during reading/writing");
    }
</code>```

答:
As Andreas said, it waits for a Standard Input to write to file.
You should really use log4j for this purpose.

See how to make log4j to write to the console as well for more details.

Body:
i tried the following code but it gets stuck on String lineFromInput = in.readLine(); line and without this line , the txt file is empty.

the code i used is :

    try
    {
        File file = new File("out.txt"); //Your file
        FileOutputStream fos = new FileOutputStream(file);
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String lineFromInput = in.readLine();
        PrintStream ps = new PrintStream(fos);
        System.setOut(ps);
        ps.println(lineFromInput);
        //  System.out.println("This goes to out.txt");
    }
    catch(IOException e)
    {
    System.out.println("Error during reading/writing");
    }


问:
How to import a module in Python which is already imported in another file?
In my gui.py module I have:

```<code>from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
        ...
</code>```

How do I correctly import everything from that module in my main.py without from gui import * Should I again use in my from PyQt5 import QtCore ... or from gui import QtCore ...?

答:
In general, you shouldn't import stuff from a module which itself has only imported it:

```<code># gui.py
from PyQt5 import QtCore, QtGui, QtWidgets

def some_function():
    pass
</code>```

you should then do:

```<code># main.py
from PyQt5 import QtCore, QtGui, QtWidgets
from gui import some_function
</code>```

The only exception are __init__.py files that aggregate modules from its submodules for convenience reasons:

```<code># some_module/__init__.py
from .submodule import some_function
from .other_submodule import some_other_function
</code>```

and then

```<code># main.py
from .some_module import some_function, some_other_function
</code>```

Since the're not modules that are provided by gui you should just import them directly from PyQt5.

Body:
In my gui.py module I have:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
        ...

How do I correctly import everything from that module in my main.py without from gui import * Should I again use in my from PyQt5 import QtCore ... or from gui import QtCore ...?

Body:
In general, you shouldn't import stuff from a module which itself has only imported it:

# gui.py
from PyQt5 import QtCore, QtGui, QtWidgets

def some_function():
    pass

you should then do:

# main.py
from PyQt5 import QtCore, QtGui, QtWidgets
from gui import some_function

The only exception are __init__.py files that aggregate modules from its submodules for convenience reasons:

# some_module/__init__.py
from .submodule import some_function
from .other_submodule import some_other_function

and then

# main.py
from .some_module import some_function, some_other_function

Since the're not modules that are provided by gui you should just import them directly from PyQt5.


问:
Wordpress & Woocommerce Product SKU on Single Product
Hi i have a woo commerce website and i'm trying to get the Product SKU displaying on the single product page,

i have different SKU for Variable Products.

答:
Add this code in function.php file .</p>

```<code>add_action( 'woocommerce_single_product_summary', 'wdm_show_sku', 5 );
function wdm_show_sku(){
global $product;
echo $product->get_sku();
}
</code>```

Body:
Add this code in function.php file .

add_action( 'woocommerce_single_product_summary', 'wdm_show_sku', 5 );
function wdm_show_sku(){
global $product;
echo $product->get_sku();
}


问:
ActiveRecord where and order on via-table
I have three database table:

product (id, name)

product_has_adv (product,advantage,sort,important)

advantage (id, text)

In ProductModel I defined this:

```<code>public function getAdvantages()
    {
        return $this->hasMany(AdvantageModel::className(), ['id' => 'advantage'])
            ->viaTable('product_has_advantage', ['product' => 'id']);
    }
</code>```

I get the advantages without any problems.

But now I need to add a where product_has_advantage.important = 1 clausel and also sort the advantages by the sort-columen in the product_has_advantage-table.

How and where I have to realize it?

答:
For who comes here after a while and don't like above solutions, I got it working by joining back to the via table after the filter via table.

Example for above code:

```<code>public function getAdvantages()
{
    return $this->hasMany(AdvantageModel::className(), ['id' => 'advantage'])
        ->viaTable('product_has_advantage', ['product' => 'id'])
        ->innerJoin('product_has_advantage','XXX')
        ->orderBy('product_has_advantage.YYY'=> SORT_ASC);
}
</code>```

Take care about changing XXX with the right join path and YYY with the right sort column.

Body:
I have three database table:

product (id, name)

product_has_adv (product,advantage,sort,important)

advantage (id, text)

In ProductModel I defined this:

public function getAdvantages()
    {
        return $this->hasMany(AdvantageModel::className(), ['id' => 'advantage'])
            ->viaTable('product_has_advantage', ['product' => 'id']);
    }

I get the advantages without any problems.

But now I need to add a where product_has_advantage.important = 1 clausel and also sort the advantages by the sort-columen in the product_has_advantage-table.

How and where I have to realize it?

Body:
For who comes here after a while and don't like above solutions, I got it working by joining back to the via table after the filter via table.

Example for above code:

public function getAdvantages()
{
    return $this->hasMany(AdvantageModel::className(), ['id' => 'advantage'])
        ->viaTable('product_has_advantage', ['product' => 'id'])
        ->innerJoin('product_has_advantage','XXX')
        ->orderBy('product_has_advantage.YYY'=> SORT_ASC);
}

Take care about changing XXX with the right join path and YYY with the right sort column.


答: You can do it by using Jquery ajax request. Write an onchange method on first dropdown. On change take the id of selected account and pass it to your query for selecting users.Return all the users and display it to your users dropdown.</p>

Title: dependent dynamic dropdown in php


问:
Make ImageView display black portions of image as different color
How can I replace the black color with transparent color (or some other color) in an ImageView?

I load image from web using Picasso:

```<code>Picasso.with(getContext()).load("www.abc.com/a.png").into(myImageView);
</code>```

Currently it looks like this:

The image itself contains the black background, which I want to remove. I tried using myImageView.setColorFilter(Color.BLACK); but it doesn't seem to work.

答:
You can try this.</p>

```<code>Picasso.with(this).load("Your URL").into(new Target() {
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from)
        {
           bitmap.eraseColor(Color.argb(AAA,RRR,GGG,BBB));
           OR
           bitmap.eraseColor(getResources().getColor(R.color.myColor));
           imageView.setBackground(new BitmapDrawable(bitmap));
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {

        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {

        }
    });
</code>```

Body:
How can I replace the black color with transparent color (or some other color) in an ImageView?

I load image from web using Picasso:

Picasso.with(getContext()).load("www.abc.com/a.png").into(myImageView);

Currently it looks like this:

The image itself contains the black background, which I want to remove. I tried using myImageView.setColorFilter(Color.BLACK); but it doesn't seem to work.

Body:
You can try this.

Picasso.with(this).load("Your URL").into(new Target() {
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from)
        {
           bitmap.eraseColor(Color.argb(AAA,RRR,GGG,BBB));
           OR
           bitmap.eraseColor(getResources().getColor(R.color.myColor));
           imageView.setBackground(new BitmapDrawable(bitmap));
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {

        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {

        }
    });