问:
Spring @JsonIgnore Serialization not working as expected
I have two Java classes: Usuario and Entrada.

Usuario:

```<code>@Entity
@Table(name="usuario")
@NamedQuery(name="Usuario.findAll", query="SELECT u FROM Usuario u")
public class Usuario implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int idusuario;

    private String apellido1;

    private String apellido2;

    private String email;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="fecha_alta")
    private Date fechaAlta;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="fecha_baja")
    private Date fechaBaja;

    @Column(name="is_admin")
    private boolean isAdmin;

    private String nombre;

    private String password;

    //bi-directional many-to-one association to CompraEntrada
    @OneToMany(mappedBy="usuarioBean")
    @JsonIgnore
    private List<CompraEntrada> compraEntradas;

    //bi-directional many-to-one association to Entrada
    @OneToMany(mappedBy="usuarioBean")
    private List<Entrada> entradas;

    //bi-directional many-to-one association to Evento
    @OneToMany(mappedBy="usuario")
    @JsonIgnore
    private List<Evento> eventos;

    //bi-directional many-to-one association to Mensaje
    @OneToMany(mappedBy="emisor")
    @JsonIgnore
    private List<Mensaje> mensajesEmitidos;

    //bi-directional many-to-one association to Mensaje
    @OneToMany(mappedBy="receptor")
    @JsonIgnore
    private List<Mensaje> mensajesRecibidos;
</code>```

Entrada:

```<code>@Entity
@Table(name="entrada")
@NamedQuery(name="Entrada.findAll", query="SELECT e FROM Entrada e")
public class Entrada implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int identrada;

    //bi-directional many-to-one association to Evento
    @ManyToOne
    @JoinColumn(name="evento")
    private Evento eventoBean;

    //bi-directional many-to-one association to Usuario
    @ManyToOne
    @JoinColumn(name="usuario")
    @JsonIgnore
    private Usuario usuarioBean;
</code>```

I have also the class Evento:

```<code>@Entity
@Table(name="evento")
@NamedQuery(name="Evento.findAll", query="SELECT e FROM Evento e")
public class Evento implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int idevento;

    private String categoria;

    private String descripcion;

    @Column(name="entradas_disponibles")
    private int entradasDisponibles;

    @Column(name="entradas_venta")
    private int entradasVenta;

    private int estado;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="fecha_hora")
    private Date fechaHora;

    private String imagen;

    private String localizacion;

    @Column(name="precio_entrada")
    private double precioEntrada;

    private String titulo;

    //bi-directional many-to-one association to CompraEntrada
    @OneToMany(mappedBy="eventoBean")
    private List<CompraEntrada> compraEntradas;

    //bi-directional many-to-one association to Entrada
    @OneToMany(mappedBy="eventoBean")
    private List<Entrada> entradas;

    //bi-directional many-to-one association to Usuario
    @ManyToOne
    @JoinColumn(name="creador")
    private Usuario usuario;
</code>```

I'm using Spring Data but I have a recursive serialization problem.
When I "print" an object of type Usuario, it should serialize all the information of Usuario. The point here is that, Entrada (List in Usuario) has an attribute of type Usuario.

I don't want to serialize the Usuario of Entrada. I'm just looking to serialize each one of the items in List of Usuario.

I've tried to add @JsonIgnore in the attribute of type Usuario in Entrada, but I still have the same problem.

The log shows:

```<code>2017-12-04 18:57:46.980[0;39m [31mERROR[0;39m [35m3389[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.a.c.c.C.[.[.[/].[dispatcherServlet]   [0;39m [2m:[0;39m Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: Infinite recursion (StackOverflowError) (through reference chain: es.softcorp.domains.Entrada["eventoBean"]->es.softcorp.domains.Evento["entradas"]->org.hibernate.collection.internal.PersistentBag[0]->es.softcorp.domains.Entrada["eventoBean"]->es.softcorp.domains.Evento["entradas"]->org.hibernate.collection.internal.PersistentBag[0]->es.softcorp.domains.Entrada["eventoBean"]->es.softcorp.domains.Evento["entradas"]-
</code>```

and so on

答:
I have solved this, from what I can remember for @JsonIgnore to work you have to disable auto field detection for that class or if you wish for all classes.

There is two ways you can solve the recursion issue.

Json annotations to tell ObjectMapper about the bi-directional relation.

@JsonIgnore, @JsonView the field thats causing the recursion/loop.

For a sample project I did disabled auto field detection for all classes like this and used @JsonProperty and @JsonIgnore in classes I wanted to serialise. If auto detect is disabled you have to manually mark the fields.

```<code>/**
 * Disable auto field detection for JSON message converter.
 * @return
 */
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    ObjectMapper objectMapper = new ObjectMapper();

    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    objectMapper.setVisibility(
            objectMapper
            .getVisibilityChecker()
            .with(Visibility.NONE)
    );

    jsonConverter.setObjectMapper(objectMapper);
    return jsonConverter;
}
</code>```

There is also @JsonView annotation which work similar to @JsonIgnore and can be used to select which fields will get serialised, here is the link for further reading https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring

The correct way to solve your issue is to tell the ObjectMapper about the recursive/bi-directional relation as explained on this page http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion

In summary you use @JsonManagedReference on the child ( non owning side) and use @JsonBackReference on parent (owning side of relation).

Body:
I have two Java classes: Usuario and Entrada.

Usuario:

@Entity
@Table(name="usuario")
@NamedQuery(name="Usuario.findAll", query="SELECT u FROM Usuario u")
public class Usuario implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int idusuario;

    private String apellido1;

    private String apellido2;

    private String email;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="fecha_alta")
    private Date fechaAlta;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="fecha_baja")
    private Date fechaBaja;

    @Column(name="is_admin")
    private boolean isAdmin;

    private String nombre;

    private String password;

    //bi-directional many-to-one association to CompraEntrada
    @OneToMany(mappedBy="usuarioBean")
    @JsonIgnore
    private List<CompraEntrada> compraEntradas;

    //bi-directional many-to-one association to Entrada
    @OneToMany(mappedBy="usuarioBean")
    private List<Entrada> entradas;

    //bi-directional many-to-one association to Evento
    @OneToMany(mappedBy="usuario")
    @JsonIgnore
    private List<Evento> eventos;

    //bi-directional many-to-one association to Mensaje
    @OneToMany(mappedBy="emisor")
    @JsonIgnore
    private List<Mensaje> mensajesEmitidos;

    //bi-directional many-to-one association to Mensaje
    @OneToMany(mappedBy="receptor")
    @JsonIgnore
    private List<Mensaje> mensajesRecibidos;

Entrada:

@Entity
@Table(name="entrada")
@NamedQuery(name="Entrada.findAll", query="SELECT e FROM Entrada e")
public class Entrada implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int identrada;

    //bi-directional many-to-one association to Evento
    @ManyToOne
    @JoinColumn(name="evento")
    private Evento eventoBean;

    //bi-directional many-to-one association to Usuario
    @ManyToOne
    @JoinColumn(name="usuario")
    @JsonIgnore
    private Usuario usuarioBean;

I have also the class Evento:

@Entity
@Table(name="evento")
@NamedQuery(name="Evento.findAll", query="SELECT e FROM Evento e")
public class Evento implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int idevento;

    private String categoria;

    private String descripcion;

    @Column(name="entradas_disponibles")
    private int entradasDisponibles;

    @Column(name="entradas_venta")
    private int entradasVenta;

    private int estado;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="fecha_hora")
    private Date fechaHora;

    private String imagen;

    private String localizacion;

    @Column(name="precio_entrada")
    private double precioEntrada;

    private String titulo;

    //bi-directional many-to-one association to CompraEntrada
    @OneToMany(mappedBy="eventoBean")
    private List<CompraEntrada> compraEntradas;

    //bi-directional many-to-one association to Entrada
    @OneToMany(mappedBy="eventoBean")
    private List<Entrada> entradas;

    //bi-directional many-to-one association to Usuario
    @ManyToOne
    @JoinColumn(name="creador")
    private Usuario usuario;

I'm using Spring Data but I have a recursive serialization problem.
When I "print" an object of type Usuario, it should serialize all the information of Usuario. The point here is that, Entrada (List in Usuario) has an attribute of type Usuario.

I don't want to serialize the Usuario of Entrada. I'm just looking to serialize each one of the items in List of Usuario.

I've tried to add @JsonIgnore in the attribute of type Usuario in Entrada, but I still have the same problem.

The log shows:

2017-12-04 18:57:46.980[0;39m [31mERROR[0;39m [35m3389[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.a.c.c.C.[.[.[/].[dispatcherServlet]   [0;39m [2m:[0;39m Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: Infinite recursion (StackOverflowError) (through reference chain: es.softcorp.domains.Entrada["eventoBean"]->es.softcorp.domains.Evento["entradas"]->org.hibernate.collection.internal.PersistentBag[0]->es.softcorp.domains.Entrada["eventoBean"]->es.softcorp.domains.Evento["entradas"]->org.hibernate.collection.internal.PersistentBag[0]->es.softcorp.domains.Entrada["eventoBean"]->es.softcorp.domains.Evento["entradas"]-

and so on

Body:
I have solved this, from what I can remember for @JsonIgnore to work you have to disable auto field detection for that class or if you wish for all classes.

There is two ways you can solve the recursion issue.

Json annotations to tell ObjectMapper about the bi-directional relation.

@JsonIgnore, @JsonView the field thats causing the recursion/loop.

For a sample project I did disabled auto field detection for all classes like this and used @JsonProperty and @JsonIgnore in classes I wanted to serialise. If auto detect is disabled you have to manually mark the fields.

/**
 * Disable auto field detection for JSON message converter.
 * @return
 */
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    ObjectMapper objectMapper = new ObjectMapper();

    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    objectMapper.setVisibility(
            objectMapper
            .getVisibilityChecker()
            .with(Visibility.NONE)
    );

    jsonConverter.setObjectMapper(objectMapper);
    return jsonConverter;
}

There is also @JsonView annotation which work similar to @JsonIgnore and can be used to select which fields will get serialised, here is the link for further reading https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring

The correct way to solve your issue is to tell the ObjectMapper about the recursive/bi-directional relation as explained on this page http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion

In summary you use @JsonManagedReference on the child ( non owning side) and use @JsonBackReference on parent (owning side of relation).


来源: stackexchange

问:
Count number of mutual friends in Firebase
I'm trying to pull the number of mutual friends that I have with any given userID. I first pulled all my friends from Firebase and then I pulled the userID's friends. I'm just not sure how to count the number of mutual friends from there. Please let me know if I'm going about it the wrong way.

```<code>func fetchMutualFriends(myID: String, userID: String) {

    let myID = Auth.auth().currentUser!.uid

    let postRef = self.databaseRef.child("friends").child(myID)

    postRef.observe(.value, with: { (snapshot) in
        for childSnapshot in snapshot.children {
              print(childSnapshot)

        }
    })
    let postRef1 = self.databaseRef.child("friends").child(friendID)

    postRef1.observe(.value, with: { (snapshot) in
        for childSnapshot in snapshot.children {
            print(childSnapshot)

        }
    })
}
</code>```

Firebase structure

```<code>root/
|___ friends/
|      |___ myID
|              |___ friendID1
|      |___ friendID1
|              |___ myID
</code>```

答:
Since the actual struture is not clear, let's assume a standard structure like this

```<code>  "users"
    "user_0"
      "friends"
        "user_1" : true,
        "user_2" : true,
        "user_3" : true
    "user_1"
      "friends"
        "user_0" : true,
        "user_2" : true
    "user_2"
      "friends"
        "user_0" : true,
        "user_1" : true,
        "user_3" : true
    "user_3"
      "friends"
        "user_0" : true,
        "user_2" : true
</code>```

As you can see, user 0 is friends with user_1, user_2 and user_3, and likewise in their nodes those users are friends with user_0.

If we want to keep this structure then finding the intersection of two users mutual friends is pretty easy.

Suppose we want to find which friends user_0 and user_2 have in common. Looking at the structure we find it's

```<code>user_1
user_3
</code>```

How do we do that in code?

```<code>let user1FriendsRef = self.ref.child("users").child("user_0").child("friends")
let user2FriendsRef = self.ref.child("users").child("user_2").child("friends")

user1FriendsRef.observeSingleEvent(of: .value, with: { user1Snapshot in
    let user1FriendsArray = user1Snapshot.children.map { ($0 as! DataSnapshot).key }
    let user1FriendsSet = Set(user1FriendsArray)

    user2FriendsRef.observeSingleEvent(of: .value, with: { user2Snapshot in
        let user2FriendsArray = user2Snapshot.children.map { ($0 as! DataSnapshot).key }
        let user2FriendsSet = Set(user2FriendsArray)

        let mutualFriends = user1FriendsSet.intersection(user2FriendsSet).sorted()
        print(mutualFriends)
        print(mutualFriends.count)
    })
})
</code>```

Here's how that code works: We start with a reference to the two users friends lists we want to compare

Using observeSingleEvent, the first users friends list is read and the keys  (user_1, user_2 etc) are stored in an array. That is done my mapping (iterating over) each key: value pair to capture the key. That array is converted to a Set var.

We do the same thing for the second user - noting it's important we do that within the first closure so we are guaranteed the results from the first user are complete. Those results are mapped to an array and the made into a Set.

Then, the magic of leveraging the intersection function of a Set and then print the mutual friends (sorted)

```<code>["user_1", "user_3"]
2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to pull the number of mutual friends that I have with any given userID. I first pulled all my friends from Firebase and then I pulled the userID's friends. I'm just not sure how to count the number of mutual friends from there. Please let me know if I'm going about it the wrong way.

func fetchMutualFriends(myID: String, userID: String) {

    let myID = Auth.auth().currentUser!.uid

    let postRef = self.databaseRef.child("friends").child(myID)

    postRef.observe(.value, with: { (snapshot) in
        for childSnapshot in snapshot.children {
              print(childSnapshot)

        }
    })
    let postRef1 = self.databaseRef.child("friends").child(friendID)

    postRef1.observe(.value, with: { (snapshot) in
        for childSnapshot in snapshot.children {
            print(childSnapshot)

        }
    })
}

Firebase structure

root/
|___ friends/
|      |___ myID
|              |___ friendID1
|      |___ friendID1
|              |___ myID

Body:
Since the actual struture is not clear, let's assume a standard structure like this

  "users"
    "user_0"
      "friends"
        "user_1" : true,
        "user_2" : true,
        "user_3" : true
    "user_1"
      "friends"
        "user_0" : true,
        "user_2" : true
    "user_2"
      "friends"
        "user_0" : true,
        "user_1" : true,
        "user_3" : true
    "user_3"
      "friends"
        "user_0" : true,
        "user_2" : true

As you can see, user 0 is friends with user_1, user_2 and user_3, and likewise in their nodes those users are friends with user_0.

If we want to keep this structure then finding the intersection of two users mutual friends is pretty easy.

Suppose we want to find which friends user_0 and user_2 have in common. Looking at the structure we find it's

user_1
user_3

How do we do that in code?

let user1FriendsRef = self.ref.child("users").child("user_0").child("friends")
let user2FriendsRef = self.ref.child("users").child("user_2").child("friends")

user1FriendsRef.observeSingleEvent(of: .value, with: { user1Snapshot in
    let user1FriendsArray = user1Snapshot.children.map { ($0 as! DataSnapshot).key }
    let user1FriendsSet = Set(user1FriendsArray)

    user2FriendsRef.observeSingleEvent(of: .value, with: { user2Snapshot in
        let user2FriendsArray = user2Snapshot.children.map { ($0 as! DataSnapshot).key }
        let user2FriendsSet = Set(user2FriendsArray)

        let mutualFriends = user1FriendsSet.intersection(user2FriendsSet).sorted()
        print(mutualFriends)
        print(mutualFriends.count)
    })
})

Here's how that code works: We start with a reference to the two users friends lists we want to compare

Using observeSingleEvent, the first users friends list is read and the keys  (user_1, user_2 etc) are stored in an array. That is done my mapping (iterating over) each key: value pair to capture the key. That array is converted to a Set var.

We do the same thing for the second user - noting it's important we do that within the first closure so we are guaranteed the results from the first user are complete. Those results are mapped to an array and the made into a Set.

Then, the magic of leveraging the intersection function of a Set and then print the mutual friends (sorted)

["user_1", "user_3"]
2


问:
TSQL turning these multiple CASE queries into one query
I have the following CASE queries that return 1 if they find anything, and 0 otherwise. I would like to turn these into a single query that returns 1 if any of them are true, or 0 otherwise. How can I acomplish this?</p>

```<code>SELECT CASE WHEN count(PLACE.CODE) > 0 THEN 1 ELSE 0 END
FROM PLACE
WHERE STYLE = 'RED'
AND RULES = 'NO'

SELECT CASE WHEN count(GARDEN.AREA) > 0 THEN 1 ELSE 0 END
FROM GARDEN
WHERE PLACE = 'GROUND'
AND MAZE = '1'

SELECT CASE WHEN count(place_area.AVAILABLE_AREA) > 0 THEN 1 ELSE 0 END
FROM PLACE_AREA as place_area
INNER JOIN USED_PLACE as used_place
    ON used_place.COLOR = 'RED'
    AND used_place.MAKE = 'INDUSTRY'
WHERE place_area.CODE = 'FLOOR'
AND place_area.DANCE = '0'
</code>```

答:
If I understand you correctly, you can union all the result and calculate the sum, if sum > 0 then there was at least one 1

```<code>Select Case When Sum(x.col) > 0 THEN 1 ELSE 0 END from
(
SELECT CASE WHEN count(PLACE.CODE) > 0 THEN 1 ELSE 0 END as col
FROM PLACE
WHERE STYLE = 'RED'
AND RULES = 'NO'

Union All

SELECT CASE WHEN count(GARDEN.AREA) > 0 THEN 1 ELSE 0 END as col
FROM GARDEN
WHERE PLACE = 'GROUND'
AND MAZE = '1'

Union All

SELECT CASE WHEN count(place_area.AVAILABLE_AREA) > 0 THEN 1 ELSE 0 END as col
FROM PLACE_AREA as place_area
INNER JOIN USED_PLACE as used_place
    ON used_place.COLOR = 'RED'
    AND used_place.MAKE = 'INDUSTRY'
WHERE place_area.CODE = 'FLOOR'
AND place_area.DANCE = '0'
) x
</code>```

Body:
I have the following CASE queries that return 1 if they find anything, and 0 otherwise. I would like to turn these into a single query that returns 1 if any of them are true, or 0 otherwise. How can I acomplish this?

SELECT CASE WHEN count(PLACE.CODE) > 0 THEN 1 ELSE 0 END
FROM PLACE
WHERE STYLE = 'RED'
AND RULES = 'NO'

SELECT CASE WHEN count(GARDEN.AREA) > 0 THEN 1 ELSE 0 END
FROM GARDEN
WHERE PLACE = 'GROUND'
AND MAZE = '1'

SELECT CASE WHEN count(place_area.AVAILABLE_AREA) > 0 THEN 1 ELSE 0 END
FROM PLACE_AREA as place_area
INNER JOIN USED_PLACE as used_place
    ON used_place.COLOR = 'RED'
    AND used_place.MAKE = 'INDUSTRY'
WHERE place_area.CODE = 'FLOOR'
AND place_area.DANCE = '0'

Body:
If I understand you correctly, you can union all the result and calculate the sum, if sum > 0 then there was at least one 1

Select Case When Sum(x.col) > 0 THEN 1 ELSE 0 END from
(
SELECT CASE WHEN count(PLACE.CODE) > 0 THEN 1 ELSE 0 END as col
FROM PLACE
WHERE STYLE = 'RED'
AND RULES = 'NO'

Union All

SELECT CASE WHEN count(GARDEN.AREA) > 0 THEN 1 ELSE 0 END as col
FROM GARDEN
WHERE PLACE = 'GROUND'
AND MAZE = '1'

Union All

SELECT CASE WHEN count(place_area.AVAILABLE_AREA) > 0 THEN 1 ELSE 0 END as col
FROM PLACE_AREA as place_area
INNER JOIN USED_PLACE as used_place
    ON used_place.COLOR = 'RED'
    AND used_place.MAKE = 'INDUSTRY'
WHERE place_area.CODE = 'FLOOR'
AND place_area.DANCE = '0'
) x


问:
Dynamic labels in matplotlib stacked area chart
I'm working with a stacked area plot created by pandas. The screenshots shows one such typical plot (labels are deliberatly not shown):

The relevant code producing this plot is

```<code>fig, axes = plt.subplots(nrows=2, ncols=1)
coredata = nonzero.loc[:, nonzero.columns != 'Busy'].plot.area(figsize=(9, 8), ax=axes[0], colormap='jet')
</code>```

where nonzero is a larger dataframe. The issue is that there are too many columns leading to a crowded legend. Instead of moving the legend out of the picture I'd like to use matplotlib's events to tell me which element of the chart I'm hovering over.

```<code>def on_move(event):
    if event.inaxes == coredata:
        # help please

fig.canvas.mpl_connect("motion_notify_event", on_move)
</code>```

The event fires exactly as desired but I have trouble extracting the area I'm hovering over (respectively its label). coredata.artists is empty, coredata.lines is a matplotlib.lines.Line2D element (supposedly too low level). How can I access the current area under the cursor in order to display its label?

Edit: following is a minimal example:

from pandas import DataFrame, Series
from matplotlib import pyplot as plt

# mock data
d = {'one' : Series([1., 2., 3.], index=['a', 'b', 'c']),
     'two' : Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd']),
     'three': Series([0.5, 0.2, 0.3, 0.1], index=['a', 'b', 'c', 'd']),
     'four': Series([3., 2., 1., 0.3], index=['a', 'b', 'c', 'd']),
}
df = DataFrame(d)

fig, axes = plt.subplots()
chart = df.plot.area(ax=axes)

# create and initially hide annotation
annot = axes.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"))
annot.set_visible(False)
def on_move(event):
    if event.inaxes == chart:
        pass # help plz: how do I best check I currently hover over one, two, three or four?
        print(event.xdata, event.ydata)
fig.canvas.mpl_connect("motion_notify_event", on_move)

plt.show()
```

答:
Just as when hovering a scatter, see e.g. here or here you need to check if any of the collections contains the mouseevent. To this end you would look over the collections of interest, do the check and if successful may add an identifier to a list.

```<code>which = []
for i,c in enumerate(axes.collections):
    if c.contains(event)[0]:
        which.append(i)
</code>```

You may then use this list to draw a new legend with only the collections identified in that list. Since redrawing the canvas is expensive and may slow down the application one would try to do it as seldom as possible. While moving the mouse, the exact same result would be expected a lot of times, so we may store it and only create a new legend in case it needs to be changed.

```<code>from pandas import DataFrame, Series
from matplotlib import pyplot as plt

# mock data
d = {'one' : Series([1., 2., 3.], index=['a', 'b', 'c']),
     'two' : Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd']),
     'three': Series([0.5, 0.2, 0.3, 0.1], index=['a', 'b', 'c', 'd']),
     'four': Series([3., 2., 1., 0.3], index=['a', 'b', 'c', 'd']),
}
df = DataFrame(d)

fig, axes = plt.subplots()
df.plot.area(ax=axes, legend=False)

# create and initially hide annotation
annot = axes.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"))
annot.set_visible(False)

last = [None]
def on_move(event):
    if event.inaxes == axes:
        which = []
        for i,c in enumerate(axes.collections):
            if c.contains(event)[0]:
                which.append(i)
        if which != last[0]:
            last[0] = which
            axes.legend([axes.collections[i] for i in which],
                        [df.columns[i] for i in which])
            fig.canvas.draw_idle()

fig.canvas.mpl_connect("motion_notify_event", on_move)

plt.show()
</code>```

Body:
I'm working with a stacked area plot created by pandas. The screenshots shows one such typical plot (labels are deliberatly not shown):

The relevant code producing this plot is

fig, axes = plt.subplots(nrows=2, ncols=1)
coredata = nonzero.loc[:, nonzero.columns != 'Busy'].plot.area(figsize=(9, 8), ax=axes[0], colormap='jet')

where nonzero is a larger dataframe. The issue is that there are too many columns leading to a crowded legend. Instead of moving the legend out of the picture I'd like to use matplotlib's events to tell me which element of the chart I'm hovering over.

def on_move(event):
    if event.inaxes == coredata:
        # help please

fig.canvas.mpl_connect("motion_notify_event", on_move)

The event fires exactly as desired but I have trouble extracting the area I'm hovering over (respectively its label). coredata.artists is empty, coredata.lines is a matplotlib.lines.Line2D element (supposedly too low level). How can I access the current area under the cursor in order to display its label?

Edit: following is a minimal example:

from pandas import DataFrame, Series
from matplotlib import pyplot as plt

# mock data
d = {'one' : Series([1., 2., 3.], index=['a', 'b', 'c']),
     'two' : Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd']),
     'three': Series([0.5, 0.2, 0.3, 0.1], index=['a', 'b', 'c', 'd']),
     'four': Series([3., 2., 1., 0.3], index=['a', 'b', 'c', 'd']),
}
df = DataFrame(d)

fig, axes = plt.subplots()
chart = df.plot.area(ax=axes)

# create and initially hide annotation
annot = axes.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"))
annot.set_visible(False)
def on_move(event):
    if event.inaxes == chart:
        pass # help plz: how do I best check I currently hover over one, two, three or four?
        print(event.xdata, event.ydata)
fig.canvas.mpl_connect("motion_notify_event", on_move)

plt.show()

Body:
Just as when hovering a scatter, see e.g. here or here you need to check if any of the collections contains the mouseevent. To this end you would look over the collections of interest, do the check and if successful may add an identifier to a list.

which = []
for i,c in enumerate(axes.collections):
    if c.contains(event)[0]:
        which.append(i)

You may then use this list to draw a new legend with only the collections identified in that list. Since redrawing the canvas is expensive and may slow down the application one would try to do it as seldom as possible. While moving the mouse, the exact same result would be expected a lot of times, so we may store it and only create a new legend in case it needs to be changed.

from pandas import DataFrame, Series
from matplotlib import pyplot as plt

# mock data
d = {'one' : Series([1., 2., 3.], index=['a', 'b', 'c']),
     'two' : Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd']),
     'three': Series([0.5, 0.2, 0.3, 0.1], index=['a', 'b', 'c', 'd']),
     'four': Series([3., 2., 1., 0.3], index=['a', 'b', 'c', 'd']),
}
df = DataFrame(d)

fig, axes = plt.subplots()
df.plot.area(ax=axes, legend=False)

# create and initially hide annotation
annot = axes.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"))
annot.set_visible(False)

last = [None]
def on_move(event):
    if event.inaxes == axes:
        which = []
        for i,c in enumerate(axes.collections):
            if c.contains(event)[0]:
                which.append(i)
        if which != last[0]:
            last[0] = which
            axes.legend([axes.collections[i] for i in which],
                        [df.columns[i] for i in which])
            fig.canvas.draw_idle()

fig.canvas.mpl_connect("motion_notify_event", on_move)

plt.show()


问:
How to save attachments from Outlook Email Items into the server folder using AJAX jquery
How to save attachments from an email to a server folder using AJAX jquery

I have develop Outlook Add-in using Node and Jquery.

'use strict';

(function () {
    // The initialize function must be run each time a new page is loaded
    Office.initialize = function (reason) {
        $(document).ready(function () {
            // After the DOM is loaded, app-specific code can run.
            var sender_email = Office.context.mailbox.item.from.emailAddress; // Email Address
            var sender_name = Office.context.mailbox.item.from.displayName; // Get Display Name
            var subject = Office.context.mailbox.item.subject; // Get Subject

            // Get Attachment from Outlooks Email.
            var _Item = Office.context.mailbox.item;
                    if (_Item.attachments.length > 0) {
                      for (var i = 0 ; i < _Item.attachments.length ; i++) {
                        var _att = _Item.attachments[i];
                        console.log(i + ". Name: ");
                        console.log(_att.name);
                        console.log(" ID: " + _att.id);
                        console.log(" contentType: " + _att.contentType);
                        console.log(" size: " + _att.size);
                        console.log(" attachmentType: " + _att.attachmentType);
                        console.log(" isInline: " + _att.isInline);
                      }
                    }

            // Do something with outputString

            // I need Outlook Email Attachment upload attachment on Specific server using Ajax Jquery
            var url = 'URL';
            $.ajax({
                url: url,
                type: "POST",
                data: {'attachment': attachment},
                dataType: "JSON",
                success: function (response) {
                    if (response.success == 1) {
                        console.log("Upload");
                    } else {
                        console.log("Error in Uploading attachment");
                    }
                }
            });
        }
    }
}
```

<p>Console Log:</p>

<pre class="lang-none prettyprint-override"><code>Name: Blank PDF Document.pdf
ID: AQMkADAwATM3ZmYAZS0wZTI1LTdlZQAxLTAwAi0wMAoARgAAA/y1A2YhzU1Bk05UvY0yWPQHAMN19wxC7xpPgbGB+hr4/lcAAAIBDAAAAMN19wxC7xpPgbGB+hr4/lcAAAADoVHPAAAAARIAEAC1Pk4zZiVsSKgpipMFf0rW
contentType: application/pdf
size: 4785
attachmentType: file
isInline: false
</code>```

答:
The attachment object itself does not have the attachment content in it. It just contains metadata bout the attachment. You can use the ID given for attachments and make a REST query to get contents of the attachment and download it to your server.

You can refer the documentation here: https://learn.microsoft.com/en-us/outlook/add-ins/get-attachments-of-an-outlook-item

Body:
How to save attachments from an email to a server folder using AJAX jquery

I have develop Outlook Add-in using Node and Jquery.

'use strict';

(function () {
    // The initialize function must be run each time a new page is loaded
    Office.initialize = function (reason) {
        $(document).ready(function () {
            // After the DOM is loaded, app-specific code can run.
            var sender_email = Office.context.mailbox.item.from.emailAddress; // Email Address
            var sender_name = Office.context.mailbox.item.from.displayName; // Get Display Name
            var subject = Office.context.mailbox.item.subject; // Get Subject

            // Get Attachment from Outlooks Email.
            var _Item = Office.context.mailbox.item;
                    if (_Item.attachments.length > 0) {
                      for (var i = 0 ; i < _Item.attachments.length ; i++) {
                        var _att = _Item.attachments[i];
                        console.log(i + ". Name: ");
                        console.log(_att.name);
                        console.log(" ID: " + _att.id);
                        console.log(" contentType: " + _att.contentType);
                        console.log(" size: " + _att.size);
                        console.log(" attachmentType: " + _att.attachmentType);
                        console.log(" isInline: " + _att.isInline);
                      }
                    }

            // Do something with outputString

            // I need Outlook Email Attachment upload attachment on Specific server using Ajax Jquery
            var url = 'URL';
            $.ajax({
                url: url,
                type: "POST",
                data: {'attachment': attachment},
                dataType: "JSON",
                success: function (response) {
                    if (response.success == 1) {
                        console.log("Upload");
                    } else {
                        console.log("Error in Uploading attachment");
                    }
                }
            });
        }
    }
}

Console Log:

Name: Blank PDF Document.pdf
ID: AQMkADAwATM3ZmYAZS0wZTI1LTdlZQAxLTAwAi0wMAoARgAAA/y1A2YhzU1Bk05UvY0yWPQHAMN19wxC7xpPgbGB+hr4/lcAAAIBDAAAAMN19wxC7xpPgbGB+hr4/lcAAAADoVHPAAAAARIAEAC1Pk4zZiVsSKgpipMFf0rW
contentType: application/pdf
size: 4785
attachmentType: file
isInline: false


问:
Getting general location of user with google maps
I'm trying to get a general location of the user, reasons irrelevant, but I can't use the API to get their location. I've tried to parse the data associated with the IP, but if I have the $.getJson() outside of the initMap() function, the variables aren't changed and if inside initMap(), initMap() isn't recognised as a function.

tl:dr - how do I call the $.getJSON from inside the initMap() function?

Here's What I've tried:

```<code><div id="map" style="width: 100%; height: 100%;; "></div>
        <!-- G-Maps box-sizing: border-box; -->

        <script>
            var usrLat = 0;
            var usrLon = 0;

            function initMap() {
                var map = new google.maps.Map(document.getElementById('map'), {
                    zoom: 6,

                    $.getJSON("https://freegeoip.net/json/", function (data) {
                                        usrLat = parseFloat(data.latitude);
                                        usrLon = parseFloat(data.longitude);
                                        console.log(usrLon + ", " + usrLat);
                                        });

                    center: {lat: usrLat, lng: usrLon},
                    mapTypeControl: true,
                    scrollwheel: false,
                    navigationControl: false,
                    mapTypeControl: false,
                    scaleControl: false,
                    draggable: false,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    disableDefaultUI: true,
                    mapTypeControlOptions: {
                    style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
                    mapTypeIds: ['roadmap', 'terrain']
                    }
                });
            }
        </script>
</code>```

答:
Your issue is the position of your call (inside the data structure), plus the semicolon on the end of the call.

Try this instead

```<code>    <div id="map" style="width: 100%; height: 100%;; "></div>
    <!-- G-Maps box-sizing: border-box; -->

    <script>
        var usrLat = 0;
        var usrLon = 0;

        function initMap() {

            $.getJSON("https://freegeoip.net/json/", function (data) {
                                    usrLat = parseFloat(data.latitude);
                                    usrLon = parseFloat(data.longitude);
                                    console.log(usrLon + ", " + usrLat);
                                    });
            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 6,
                center: {lat: usrLat, lng: usrLon},
                mapTypeControl: true,
                scrollwheel: false,
                navigationControl: false,
                mapTypeControl: false,
                scaleControl: false,
                draggable: false,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                disableDefaultUI: true,
                mapTypeControlOptions: {
                style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
                mapTypeIds: ['roadmap', 'terrain']
                }
            });
        }

    </script>
</code>```

Body:
Your issue is the position of your call (inside the data structure), plus the semicolon on the end of the call.

Try this instead

    <div id="map" style="width: 100%; height: 100%;; "></div>
    <!-- G-Maps box-sizing: border-box; -->

    <script>
        var usrLat = 0;
        var usrLon = 0;

        function initMap() {

            $.getJSON("https://freegeoip.net/json/", function (data) {
                                    usrLat = parseFloat(data.latitude);
                                    usrLon = parseFloat(data.longitude);
                                    console.log(usrLon + ", " + usrLat);
                                    });
            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 6,
                center: {lat: usrLat, lng: usrLon},
                mapTypeControl: true,
                scrollwheel: false,
                navigationControl: false,
                mapTypeControl: false,
                scaleControl: false,
                draggable: false,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                disableDefaultUI: true,
                mapTypeControlOptions: {
                style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
                mapTypeIds: ['roadmap', 'terrain']
                }
            });
        }

    </script>


问:
XML Parsing of Multiline tags
I am using XML Parsing in one of my apps. I have not done this before but I observed something weird (or may be now) today. I am trying to locate a business on in my app and their googlemaps link is obviously big

http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=1001+Fannin+Street,+Houston,+TX&aq=0&sll=37.0625,-95.677068&sspn=36.999937,73.476563&ie=UTF8&hq=&hnear=1001+Fannin+St,+Houston,+Harris,+Texas+77002&z=16.

Every time I load using this link the app crashes. However if I change the link to something like :

http://maps.google.com/?saddr=0000+FM+0000+RD+Houston+TX+77000

the app loads perfectly and works perfect.

I know this is not a problem in my app as I am using this just for reference to something else and not loading the addr in google maps app (as this works with the big link). So I am concluding that there is something wrong in the way I am writing it in my XML.

Please do not direct me to any tools and stuff that shorten the link etc. as I dont want to get in to that. I am sure that I am messing up somewhere in my basics so if some1 tells me what are the basics behind this.

Thank you,

ContentLicense: CC BY-SA 2.5

Title: XML Parsing of Multiline tags

Body:
Well if the top link is in XML and hasn't had its ampersands escaped you'll not have well formed XML.

& should be escaped as &amp;


问:
How to pass custom data to HandleChallengeAsync
I have a Web API with a custom authenication scheme that reads auth tokens. Authentication can fail (401) for a number of reasons (token missing, invalid, expired), so I'd like to be able to indicate the failure reason in the HTTP response. E.g., 401 Token has expired.

Tokens are parsed and validated in AuthenticationHandler<T>.HandleAuthenticateAsync. How do I pass the failure reason from that method to HandleChallengeAsync?

```<code>protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
  AuthenticateResult result = null;
  var tokenResult = this.ParseToken(this.Request, out var token);

  if (tokenResult == TokenResult.Normal)
  {
    result = AuthenticateResult.Success(this.ticketFactory.CreateAuthenticationTicket(token));
  }
  else
  {
    result = AuthenticateResult.Fail("Bad token");
    // FIXME: Figure out how to populate the Properties property
    //result.Properties.Items.Add(nameof(TokenResult), tokenResult.ToString());
  }

  return Task.FromResult(result);
}
</code>```

AuthenticationProperties.Items looks like a good place to store this type of custom data. But I can't figure out how to create an AuthenticationProperties object inside of HandleAuthenticateAsync and attach it to an AuthenticateResult object. Is there a way?

答:
The authentication handler is transient-scoped, as you can see here in the source code: https://github.com/dotnet/aspnetcore/blob/4dd2a883a4b22cf3df5944b1224355a94158f516/src/Security/Authentication/Core/src/AuthenticationBuilder.cs#L48

Every request will get their own instance of the handler, so you can set the failure reason as an instance field.

Body:
I have a Web API with a custom authenication scheme that reads auth tokens. Authentication can fail (401) for a number of reasons (token missing, invalid, expired), so I'd like to be able to indicate the failure reason in the HTTP response. E.g., 401 Token has expired.

Tokens are parsed and validated in AuthenticationHandler<T>.HandleAuthenticateAsync. How do I pass the failure reason from that method to HandleChallengeAsync?

protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
  AuthenticateResult result = null;
  var tokenResult = this.ParseToken(this.Request, out var token);

  if (tokenResult == TokenResult.Normal)
  {
    result = AuthenticateResult.Success(this.ticketFactory.CreateAuthenticationTicket(token));
  }
  else
  {
    result = AuthenticateResult.Fail("Bad token");
    // FIXME: Figure out how to populate the Properties property
    //result.Properties.Items.Add(nameof(TokenResult), tokenResult.ToString());
  }

  return Task.FromResult(result);
}

AuthenticationProperties.Items looks like a good place to store this type of custom data. But I can't figure out how to create an AuthenticationProperties object inside of HandleAuthenticateAsync and attach it to an AuthenticateResult object. Is there a way?

ContentLicense: CC BY-SA 4.0


问:
How to limited EditText for start characters just english alphabet in Android
In my application I want use EditText and I want start characters just English alphabet.

My mean is, First of characters has just English alphabet (a to z).

I write below codes :

```<code>registerUsernameEdtTxt.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    if (charSequence.toString().length() < 2) {
            registerUsernameEdtTxt.setFilters(new InputFilter[]{new InputFilter() {
                public CharSequence filter(CharSequence src, int start,
                                           int end, Spanned dst, int dstart, int dend) {
                    if (src.toString().matches("[a-zA-Z ]+")) {
                        registerUsernameInptLay.setErrorEnabled(false);
                        return src;
                    }
                    registerUsernameInptLay.setError(context.getResources().getString(R.string.insertJustEnglish));
                    return "";
                }
            }});
        }
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
});
</code>```

But not work me! How can I it?

Please help me

答:
Try this:

```<code>EditText et = findViewById(R.id.text_field);

// This part is to keep the existing filters of the EditText.
InputFilter[] filters = et.getFilters();
InputFilter[] newFilters = Arrays.copyOf(filters, filters.length + 1);

InputFilter firstFilter = new InputFilter() {
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        if (source != null && source.length() > 0 && dstart == 0){
            if (!source.toString().matches("^[A-Za-z].*"))
                return "";
        }

        return null;
    }
};

// Add the filter to the array of filters
newFilters[newFilters.length - 1] = firstFilter;

et.setFilters(newFilters);
</code>```

Can be simplified like this (if the previous InputFilter are not required)

```<code>EditText et = findViewById(R.id.text_field);
InputFilter firstFilter = new InputFilter() {
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        if (source != null && source.length() > 0 && dstart == 0){
            if (!source.toString().matches("^[A-Za-z].*"))
                return "";
        }

        return null;
    }
};
et.setFilters(new InputFilter[]{firstFilter});
</code>```

EDIT

If you want to keep the rest of the string (for example if the user pastes the text):

```<code>@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    if (source != null && source.length() > 0 && dstart == 0) {
        String s = source.toString();
        if (!s.matches("^[A-Za-z].*")) {
            Toast.makeText(getApplicationContext(), "This is a Toast", Toast.LENGTH_SHORT).show();
            return s.substring(1, s.length());
        }
    }

    return null;
}
</code>```

EDIT 2

The above versions don't work on deletion or when a text is pasted with more than a forbidden char at the beginning (e.g. '88sdfs') as only the first one was removed and the rest kept.
This new version should cover all these cases.

I'd suggest to create a separated class for the InputFilter.

```<code>InputFilter firstFilter = new InputFilter() {

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        if (dstart != 0) { // The modified part is not beginning of the text
            return null; // Nothing need to be changed
        }
        if (source.length() > 0) { // text is added
            return onTextAdded(source.toString());
        } else { // text is removed
            return onTextRemoved(dest, dend);
        }
    }

    private CharSequence onTextRemoved(Spanned dest, int dend) {
        // check what the string will look like after the text being removed
        String substring = dest.toString().substring(dend, dest.length());
        // if there is still a string and it's not valid
        if (substring.length() > 0 && !isValid(substring)) {
            displayError();
            // return the deleted part for the string to not change
            return dest.subSequence(0, dend);
        }
        return null;
    }

    private String onTextAdded(String s) {
        if (isValid(s)) {
            return null;
        } else {
            String substring;
            // We want to keep a part of the added string (it can be a paste).
            // so we remove all the first characters as long as the string doesn't match
            // the requirements
            for (int i = 1; i < s.length(); i++) {
                substring = s.substring(i, s.length());
                if (isValid(substring))
                    break;
            }
            displayError();
            return substring;
        }
    }

    private boolean isValid(String s) {
        return s.matches("^[A-Za-z].*");
    }

    private void displayError() {
        Toast.makeText(getApplicationContext(), "This is a Toast", Toast.LENGTH_SHORT).show();
    }
};

et.setFilters(new InputFilter[]{firstFilter});
</code>```

Body:
In my application I want use EditText and I want start characters just English alphabet.

My mean is, First of characters has just English alphabet (a to z).

I write below codes :

registerUsernameEdtTxt.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    if (charSequence.toString().length() < 2) {
            registerUsernameEdtTxt.setFilters(new InputFilter[]{new InputFilter() {
                public CharSequence filter(CharSequence src, int start,
                                           int end, Spanned dst, int dstart, int dend) {
                    if (src.toString().matches("[a-zA-Z ]+")) {
                        registerUsernameInptLay.setErrorEnabled(false);
                        return src;
                    }
                    registerUsernameInptLay.setError(context.getResources().getString(R.string.insertJustEnglish));
                    return "";
                }
            }});
        }
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
});

But not work me! How can I it?

Please help me

Body:
Try this:

EditText et = findViewById(R.id.text_field);

// This part is to keep the existing filters of the EditText.
InputFilter[] filters = et.getFilters();
InputFilter[] newFilters = Arrays.copyOf(filters, filters.length + 1);

InputFilter firstFilter = new InputFilter() {
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        if (source != null && source.length() > 0 && dstart == 0){
            if (!source.toString().matches("^[A-Za-z].*"))
                return "";
        }

        return null;
    }
};

// Add the filter to the array of filters
newFilters[newFilters.length - 1] = firstFilter;

et.setFilters(newFilters);

Can be simplified like this (if the previous InputFilter are not required)

EditText et = findViewById(R.id.text_field);
InputFilter firstFilter = new InputFilter() {
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        if (source != null && source.length() > 0 && dstart == 0){
            if (!source.toString().matches("^[A-Za-z].*"))
                return "";
        }

        return null;
    }
};
et.setFilters(new InputFilter[]{firstFilter});

EDIT

If you want to keep the rest of the string (for example if the user pastes the text):

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    if (source != null && source.length() > 0 && dstart == 0) {
        String s = source.toString();
        if (!s.matches("^[A-Za-z].*")) {
            Toast.makeText(getApplicationContext(), "This is a Toast", Toast.LENGTH_SHORT).show();
            return s.substring(1, s.length());
        }
    }

    return null;
}

EDIT 2

The above versions don't work on deletion or when a text is pasted with more than a forbidden char at the beginning (e.g. '88sdfs') as only the first one was removed and the rest kept.
This new version should cover all these cases.

I'd suggest to create a separated class for the InputFilter.

InputFilter firstFilter = new InputFilter() {

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        if (dstart != 0) { // The modified part is not beginning of the text
            return null; // Nothing need to be changed
        }
        if (source.length() > 0) { // text is added
            return onTextAdded(source.toString());
        } else { // text is removed
            return onTextRemoved(dest, dend);
        }
    }

    private CharSequence onTextRemoved(Spanned dest, int dend) {
        // check what the string will look like after the text being removed
        String substring = dest.toString().substring(dend, dest.length());
        // if there is still a string and it's not valid
        if (substring.length() > 0 && !isValid(substring)) {
            displayError();
            // return the deleted part for the string to not change
            return dest.subSequence(0, dend);
        }
        return null;
    }

    private String onTextAdded(String s) {
        if (isValid(s)) {
            return null;
        } else {
            String substring;
            // We want to keep a part of the added string (it can be a paste).
            // so we remove all the first characters as long as the string doesn't match
            // the requirements
            for (int i = 1; i < s.length(); i++) {
                substring = s.substring(i, s.length());
                if (isValid(substring))
                    break;
            }
            displayError();
            return substring;
        }
    }

    private boolean isValid(String s) {
        return s.matches("^[A-Za-z].*");
    }

    private void displayError() {
        Toast.makeText(getApplicationContext(), "This is a Toast", Toast.LENGTH_SHORT).show();
    }
};

et.setFilters(new InputFilter[]{firstFilter});


问:
Ruby on Rails: How to link two input fields and an object together when submitting form

Hi there. I was wondering how I could link 2 input fields together with an object when submitting a form.

At present I have a food menu that contains many food items. For each item in the menu, I wish to have two input fields linked to it. A check-box to select the item and a number field to enter the quantity of the item required.

When I click submit I would like to be able to access the selected items in the controller to which they were sent to and then be able to display each item in a designated view.

I was able to send the quantity of only a single item through. However, when I entered quantities for many food items, the resulting hash in the params was empty.

Is there any way I could send the item(s) selected + quantities entered as a key-value pair in the params when I click submit.

Edit(1):-

I am currently able to send the food items as a key-value pair but I would like to only send those where the checkbox is ticked.

Selecting food items and entering quantities

Resulting parameters:
{"1"=>{"quantity"=>"2"}, "2"=>{"quantity"=>""}, "3"=>{"quantity"=>"1"}, "4"=>{"quantity"=>""}, "5"=>{"quantity"=>""}, "6"=>{"quantity"=>""}, "7"=>{"quantity"=>""}, "8"=>{"quantity"=>""}, "9"=>{"quantity"=>""}, "10"=>{"quantity"=>""}, "11"=>{"quantity"=>""}, "12"=>{"quantity"=>""}}

Code:

```<code><h2><u>Appetizers: -</u></h2>
<form action="/order/create" method="post">

    <input type="hidden" value="<%= form_authenticity_token %>" name="authenticity_token">

    <% @food.where(course: 'appetizer').each do |appetizer| %>
        <ul>
            <li>
                <%= appetizer.name %> - <%= number_to_currency(appetizer.price, :unit => "£") %>
                <input type="checkbox">
            </li>
                 <label for="<%= appetizer.id %>_quantity">Qty:</label>
                 <input type="text"
                        name="<%= appetizer.id %>[quantity]"
                        size="2"
                        id="<%= appetizer.id %>_quantity">
        </ul>
    <% end %>

    <input type="submit" value="Submit">
</form>
<br>

<%= link_to 'Back', menu_path %>
</code>```

答:
You can get quick answers, if you include a code snippet. Coming to your question -
Have you used the array notation for the input element names?

```<code><input type="text" name="textbox[]" />
</code>```

Using this you can get two arrays - one array for checkbooks and other for text boxes..  this should be equivalent of having a  map.

See this
Post which talks about similar problem.

Body:
Hi there. I was wondering how I could link 2 input fields together with an object when submitting a form.

At present I have a food menu that contains many food items. For each item in the menu, I wish to have two input fields linked to it. A check-box to select the item and a number field to enter the quantity of the item required.

When I click submit I would like to be able to access the selected items in the controller to which they were sent to and then be able to display each item in a designated view.

I was able to send the quantity of only a single item through. However, when I entered quantities for many food items, the resulting hash in the params was empty.

Is there any way I could send the item(s) selected + quantities entered as a key-value pair in the params when I click submit.

Edit(1):-

I am currently able to send the food items as a key-value pair but I would like to only send those where the checkbox is ticked.

Selecting food items and entering quantities

Resulting parameters:
{"1"=>{"quantity"=>"2"}, "2"=>{"quantity"=>""}, "3"=>{"quantity"=>"1"}, "4"=>{"quantity"=>""}, "5"=>{"quantity"=>""}, "6"=>{"quantity"=>""}, "7"=>{"quantity"=>""}, "8"=>{"quantity"=>""}, "9"=>{"quantity"=>""}, "10"=>{"quantity"=>""}, "11"=>{"quantity"=>""}, "12"=>{"quantity"=>""}}

Code:

Appetizers: -

<form action="/order/create" method="post">

    <input type="hidden" value="<%= form_authenticity_token %>" name="authenticity_token">

    <% @food.where(course: 'appetizer').each do |appetizer| %>

                <%= appetizer.name %> - <%= number_to_currency(appetizer.price, :unit => "£") %>
                <input type="checkbox">

                 <label for="<%= appetizer.id %>_quantity">Qty:
                 <input type="text"
                        name="<%= appetizer.id %>[quantity]"
                        size="2"
                        id="<%= appetizer.id %>_quantity">

    <% end %>

    <input type="submit" value="Submit">
</form>

<%= link_to 'Back', menu_path %>

Body:
You can get quick answers, if you include a code snippet. Coming to your question -
Have you used the array notation for the input element names?

<input type="text" name="textbox[]" />

Using this you can get two arrays - one array for checkbooks and other for text boxes..  this should be equivalent of having a  map.

See this
Post which talks about similar problem.


问:
How to for loop meta_query array value WordPress?

I have the following code
</p>

```<code>                $today = date('d');
                $tomorrow = date('d', strtotime('+ 1 day'));
                $thedayaftertomorrow = date('d', strtotime('+ 2 day'));
                $current_month = date('m');
                $next_month = date('m', strtotime('+ 1 month'));
                $args = array (
                  'posts_per_page' => 4,  // number of posts
                  'post_type'      => 'employees', // your custom post type
                  'meta_key'       => 'birthday',  // your custom date field name
                  'orderby'        => 'meta_value_num',
                  'order'          => 'ASC',
                  'meta_query' => array(
                    'relation' => 'OR',
                    array(
                      'key'      => 'birthday',
                      'compare'  => 'REGEXP',
                      'value'    => '[0-9]{4}' . $current_month . $today,
                    ),
                    array(
                      'key'      => 'birthday',
                      'compare'  => 'REGEXP',
                      'value'    => '[0-9]{4}' . $current_month . $tomorrow,
                    ),
                    array(
                      'key'      => 'birthday',
                      'compare'  => 'REGEXP',
                      'value'    => '[0-9]{4}' . $current_month . $thedayaftertomorrow,
                    ),
                    array(
                      'key'      => 'birthday',
                      'compare'  => 'REGEXP',
                      'value'    => '[0-9]{4}' . $next_month . '[0-9]{2}',
                    ),
                  )
                );
</code>```

<p>
I want to use for loop to add next 30 days to the array value, instead of repeating the values, cureently I'm using $today, $tomorrow and $thedayaftertomorrow to add new days.
</p>

答:
try this:</p>

```<code>$date = new DateTime('now');
for ($i=0; $i<30; $i++){
$date->modify('+1 day');
$args["meta_query"][] =  array(
                      'key'      => 'birthday',
                      'compare'  => 'REGEXP',
                      'value'    => '[0-9]{4}' . $date->format('dm'),
                    );
}
</code>```

Body:
I have the following code

                $today = date('d');
                $tomorrow = date('d', strtotime('+ 1 day'));
                $thedayaftertomorrow = date('d', strtotime('+ 2 day'));
                $current_month = date('m');
                $next_month = date('m', strtotime('+ 1 month'));
                $args = array (
                  'posts_per_page' => 4,  // number of posts
                  'post_type'      => 'employees', // your custom post type
                  'meta_key'       => 'birthday',  // your custom date field name
                  'orderby'        => 'meta_value_num',
                  'order'          => 'ASC',
                  'meta_query' => array(
                    'relation' => 'OR',
                    array(
                      'key'      => 'birthday',
                      'compare'  => 'REGEXP',
                      'value'    => '[0-9]{4}' . $current_month . $today,
                    ),
                    array(
                      'key'      => 'birthday',
                      'compare'  => 'REGEXP',
                      'value'    => '[0-9]{4}' . $current_month . $tomorrow,
                    ),
                    array(
                      'key'      => 'birthday',
                      'compare'  => 'REGEXP',
                      'value'    => '[0-9]{4}' . $current_month . $thedayaftertomorrow,
                    ),
                    array(
                      'key'      => 'birthday',
                      'compare'  => 'REGEXP',
                      'value'    => '[0-9]{4}' . $next_month . '[0-9]{2}',
                    ),
                  )
                );

I want to use for loop to add next 30 days to the array value, instead of repeating the values, cureently I'm using $today, $tomorrow and $thedayaftertomorrow to add new days.

Body:
try this:

$date = new DateTime('now');
for ($i=0; $i<30; $i++){
$date->modify('+1 day');
$args["meta_query"][] =  array(
                      'key'      => 'birthday',
                      'compare'  => 'REGEXP',
                      'value'    => '[0-9]{4}' . $date->format('dm'),
                    );
}


问:
A C++ iterator adapter which wraps and hides an inner iterator and converts the iterated type
Having toyed with this I suspect it isn't remotely possible, but I thought I'd ask the experts. I have the following C++ code:

```
class IInterface
{
    virtual void SomeMethod() = 0;
};

class Object
{
    IInterface* GetInterface() { ... }
};

class Container
{
private:
    struct Item
    {
        Object* pObject;
        [... other members ...]
    };
    std::list<Item> m_items;
};
```

I want to add these methods to Container:

```
    MagicIterator<IInterface*> Begin();
    MagicIterator<IInterface*> End();
```

In order that callers can write:

```
Container c = [...]
for (MagicIterator<IInterface*> i = c.Begin(); i != c.End(); i++)
{
    IInterface* pItf = *i;
    [...]
}
```

So essentially I want to provide a class which appears to be iterating over some collection (which the caller of Begin() and End() is not allowed to see) of IInterface pointers, but which is actually iterating over a collection of pointers to other objects (private to the Container class) which can be converted into IInterface pointers.

A few key points:

MagicIterator is to be defined outside Container.

Container::Item must remain private.

MagicIterator has to iterate over IInterface pointers, despite the fact that Container holds a std::list<Container::Item>. Container::Item contains an Object*, and Object can be used to fetch IInterface*.

MagicIterator has to be reusable with several classes which resemble Container, but might internally have different list implementations holding different objects (std::vector<SomeOtherItem>, mylist<YetAnotherItem>) and with IInterface* obtained in a different manner each time.

MagicIterator should not contain container-specific code, though it may delegate to classes which do, provided such delegation is not hard coded to to particular containers inside MagicIterator (so is somehow resolved automatically by the compiler, for example).

The solution must compile under Visual C++ without use of other libraries (such as boost) which would require a license agreement from their authors.

Also, iteration may not allocate any heap memory (so no new() or malloc() at any stage), and no memcpy().

Thanks for your time, even if you're just reading; this one's really been bugging me!

Update: Whilst I've had some very interesting answers, none have met all the above requirements yet. Notably the tricky areas are i) decoupling MagicIterator from Container somehow (default template arguments don't cut it), and ii) avoiding heap allocation; but I'm really after a solution which covers all of the above bullets.

答:
I've now found a solution which is fitter for my original purpose. I still don't like it though :)

The solution involves MagicIterator being templated on IInterface* and being constructed with both a void* to an iterator, the byte size of said iterator, and a table of pointers to functions which perform standard iteration functions on said void* such as increment, decrement, dereference, etc. MagicIterator assumes that it is safe to memcpy the given iterator into an internal buffer, and implements its own members by passing its own buffer as a void* to the supplied functions as if it were the original iterator.

Container then has to implement static iteration functions which cast back a supplied void* to a std::list::iterator. Container::begin() and Container::end() simply construct a std::list::iterator, pass a pointer to it into a MagicIterator along with a table of its iteration functions, and return the MagicIterator.

It's somewhat disgusting, and breaks my original rule regarding "no memcpy()", and makes assumptions about the internals of the iterators in question. But it avoids heap allocation, keeps Collection's internals (including Item) private, renders MagicIterator entirely independent of the collection in question and of IInterface*, and in theory allows MagicIterators to work with any collection (provided its iterators can be safely memcopy()'d).

OwnerDisplayName: El Zorko

Body:
Having toyed with this I suspect it isn't remotely possible, but I thought I'd ask the experts. I have the following C++ code:

class IInterface
{
    virtual void SomeMethod() = 0;
};

class Object
{
    IInterface* GetInterface() { ... }
};

class Container
{
private:
    struct Item
    {
        Object* pObject;
        [... other members ...]
    };
    std::list<Item> m_items;
};

I want to add these methods to Container:

    MagicIterator<IInterface*> Begin();
    MagicIterator<IInterface*> End();

In order that callers can write:

Container c = [...]
for (MagicIterator<IInterface*> i = c.Begin(); i != c.End(); i++)
{
    IInterface* pItf = *i;
    [...]
}

So essentially I want to provide a class which appears to be iterating over some collection (which the caller of Begin() and End() is not allowed to see) of IInterface pointers, but which is actually iterating over a collection of pointers to other objects (private to the Container class) which can be converted into IInterface pointers.

A few key points:

MagicIterator is to be defined outside Container.

Container::Item must remain private.

MagicIterator has to iterate over IInterface pointers, despite the fact that Container holds a std::list<Container::Item>. Container::Item contains an Object*, and Object can be used to fetch IInterface*.

MagicIterator has to be reusable with several classes which resemble Container, but might internally have different list implementations holding different objects (std::vector<SomeOtherItem>, mylist<YetAnotherItem>) and with IInterface* obtained in a different manner each time.

MagicIterator should not contain container-specific code, though it may delegate to classes which do, provided such delegation is not hard coded to to particular containers inside MagicIterator (so is somehow resolved automatically by the compiler, for example).

The solution must compile under Visual C++ without use of other libraries (such as boost) which would require a license agreement from their authors.

Also, iteration may not allocate any heap memory (so no new() or malloc() at any stage), and no memcpy().

Thanks for your time, even if you're just reading; this one's really been bugging me!

Update: Whilst I've had some very interesting answers, none have met all the above requirements yet. Notably the tricky areas are i) decoupling MagicIterator from Container somehow (default template arguments don't cut it), and ii) avoiding heap allocation; but I'm really after a solution which covers all of the above bullets.

LastEditorDisplayName: El Zorko


问:
log4j alignment
By checking IntelliJ IDEA's log output, I noticed the alignment was very nice (due amongst other to the fact that class names are right aligned and trimmed).

How do you do this using log4J?  Do you need a special appender?

```<code>2011-01-08 00:48:53,938 [   2537]   INFO - ellij.vfs.persistent.FSRecords - Marking VFS as corrupted
2011-01-08 00:48:53,987 [   2586]   INFO - api.vfs.impl.local.FileWatcher - Native file watcher is operational.
2011-01-08 00:48:54,034 [   2633]   INFO - s.impl.stores.FileBasedStorage - Document was not loaded for $APP_CONFIG$/other.xml file is null
2011-01-08 00:48:54,035 [   2634]   INFO - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/other.xml
2011-01-08 00:48:54,046 [   2645]   INFO - s.impl.stores.FileBasedStorage - Document was not loaded for $APP_CONFIG$/project.default.xml file is null
2011-01-08 00:48:54,047 [   2646]   INFO - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/project.default.xml
2011-01-08 00:48:54,051 [   2650]   INFO - s.impl.stores.FileBasedStorage - Document was not loaded for $APP_CONFIG$/options.xml file is null
2011-01-08 00:48:54,051 [   2650]   INFO - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/options.xml
2011-01-08 00:48:54,295 [   2894]   INFO - s.impl.stores.FileBasedStorage - Document was not loaded for $APP_CONFIG$/filetypes.xml file is null
2011-01-08 00:48:54,295 [   2894]   INFO - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/filetypes.xml
2011-01-08 00:48:54,342 [   2941]   INFO - .history.utils.LocalHistoryLog - local history version mismatch (was: 0, expected: 5), rebuilding...
2011-01-08 00:48:54,342 [   2941]   INFO - .history.utils.LocalHistoryLog - FS has been rebuild, rebuilding local history...
</code>```

答:
You can do this with PatternLayout. For example, you might define the logger category as:

```<code>%20.20c
</code>```

This would cause the field to always be exactly 20 characters wide, left-padding with spaces if the value is less than 20 characters, and truncating it if greater than 20.

The PatternLayout for the logs in your question might be something like:

```<code>%d [%7.7r] %6.6p - %c{30} - %m%n
</code>```

Title: log4j alignment

Body:
By checking IntelliJ IDEA's log output, I noticed the alignment was very nice (due amongst other to the fact that class names are right aligned and trimmed).

How do you do this using log4J?  Do you need a special appender?

2011-01-08 00:48:53,938 [   2537]   INFO - ellij.vfs.persistent.FSRecords - Marking VFS as corrupted
2011-01-08 00:48:53,987 [   2586]   INFO - api.vfs.impl.local.FileWatcher - Native file watcher is operational.
2011-01-08 00:48:54,034 [   2633]   INFO - s.impl.stores.FileBasedStorage - Document was not loaded for $APP_CONFIG$/other.xml file is null
2011-01-08 00:48:54,035 [   2634]   INFO - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/other.xml
2011-01-08 00:48:54,046 [   2645]   INFO - s.impl.stores.FileBasedStorage - Document was not loaded for $APP_CONFIG$/project.default.xml file is null
2011-01-08 00:48:54,047 [   2646]   INFO - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/project.default.xml
2011-01-08 00:48:54,051 [   2650]   INFO - s.impl.stores.FileBasedStorage - Document was not loaded for $APP_CONFIG$/options.xml file is null
2011-01-08 00:48:54,051 [   2650]   INFO - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/options.xml
2011-01-08 00:48:54,295 [   2894]   INFO - s.impl.stores.FileBasedStorage - Document was not loaded for $APP_CONFIG$/filetypes.xml file is null
2011-01-08 00:48:54,295 [   2894]   INFO - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/filetypes.xml
2011-01-08 00:48:54,342 [   2941]   INFO - .history.utils.LocalHistoryLog - local history version mismatch (was: 0, expected: 5), rebuilding...
2011-01-08 00:48:54,342 [   2941]   INFO - .history.utils.LocalHistoryLog - FS has been rebuild, rebuilding local history...

Body:
You can do this with PatternLayout. For example, you might define the logger category as:

%20.20c

This would cause the field to always be exactly 20 characters wide, left-padding with spaces if the value is less than 20 characters, and truncating it if greater than 20.

The PatternLayout for the logs in your question might be something like:

%d [%7.7r] %6.6p - %c{30} - %m%n


问:
Cutting a python output with awk/sed/bash
I am attempting to print on separate line or extract all of the following entries:

```<code>['zzb', 'zzc', 'zzd', 'zze', 'zzf', 'zzg', 'zzh', 'zzi', 'zzj', 'zzk', 'zzl', 'zzm', 'zzn', 'zzo', 'zzp', 'zzq', 'zzr', 'zzs', 'zzt', 'zzu', 'zzv', 'zzw', 'zzx', 'zzy', 'zzz']
</code>```

The same are generated with a python script. I am attempting to pipe all results to a for bash cycle such as:

```<code>for i in $(python pythonscript.py); do something $i; done
</code>```

My knowledge on linux commands is sort of basic and I only end up with things such as:

```<code>python pythonscript.py | awk -F"'|'" '{print $2}'
</code>```

but since the entries are printed in a single string, this only gives me a single result.

Maybe my python script is incorrect, I would basically like to have a permutation of all 3 letter possible combinations generated from the - A, B, C, D, E, F, G, H, I, L, M, N, O, P, R, S, T alphabet characters that I could later pipe to a for cycle such as:

```<code>asd
bcd
ghl
llc
bbo
</code>```

However, I do not have the required knowledge and ended up using:

```<code>from itertools import product
from string import ascii_lowercase
keywords = [''.join(i) for i in product(ascii_lowercase, repeat = 3)]
print(keywords)
</code>```

from a different question here on stackoverflow.

Any help on the matter will be greatly appreciated.

答:
Don't parse the output with Bash.
Change the Python script to print in the format you like.

For example:

```<code>from itertools import product
from string import ascii_lowercase
for t in product(ascii_lowercase, repeat = 3):
    print(''.join(t))
</code>```

Body:
I am attempting to print on separate line or extract all of the following entries:

['zzb', 'zzc', 'zzd', 'zze', 'zzf', 'zzg', 'zzh', 'zzi', 'zzj', 'zzk', 'zzl', 'zzm', 'zzn', 'zzo', 'zzp', 'zzq', 'zzr', 'zzs', 'zzt', 'zzu', 'zzv', 'zzw', 'zzx', 'zzy', 'zzz']

The same are generated with a python script. I am attempting to pipe all results to a for bash cycle such as:

for i in $(python pythonscript.py); do something $i; done

My knowledge on linux commands is sort of basic and I only end up with things such as:

python pythonscript.py | awk -F"'|'" '{print $2}'

but since the entries are printed in a single string, this only gives me a single result.

Maybe my python script is incorrect, I would basically like to have a permutation of all 3 letter possible combinations generated from the - A, B, C, D, E, F, G, H, I, L, M, N, O, P, R, S, T alphabet characters that I could later pipe to a for cycle such as:

asd
bcd
ghl
llc
bbo

However, I do not have the required knowledge and ended up using:

from itertools import product
from string import ascii_lowercase
keywords = [''.join(i) for i in product(ascii_lowercase, repeat = 3)]
print(keywords)

from a different question here on stackoverflow.

Any help on the matter will be greatly appreciated.

Body:
Don't parse the output with Bash.
Change the Python script to print in the format you like.

For example:

from itertools import product
from string import ascii_lowercase
for t in product(ascii_lowercase, repeat = 3):
    print(''.join(t))


问:
Microsoft Access SQL Comma Delimited Values
I have a dataset with a primary key called authors and a field called books.

The table looks something like this:

```<code>Authors (primary key)     Books
John                      Fathom,Mouseover,Keycard
Kyle                      Teachers,Carl,Phone
</code>```

I know this violates 1NF, and I'm attempting to create a new table (one to many relationship) with the primary key (authors) occurring more than once for each book. ie

```<code>Authors                   Books
John                      Fathom
John                      Mouseover
John                      Keycard
Kyle                      Teachers
Kyle                      Carl
Kyle                      Phone
</code>```

I need to use SQL in microsoft access, and I think it involves the split function, but I'm at a loss for how to perform this query.

Any insight would be greatly appreciated!

Thank you very much

答:
Well, since the code is rather difficult to implement, and you only have 2, I guess I can share an implemented solution:

(replace MyTable with your tablename, and find and replace all field names with the correct one):

```<code>SELECT * Into NewTable FROM (
SELECT Author, IIf(InStr(1, [Books], ',') = -1, [Books], Left([Books], InStr(1, [Books], ',') - 1)) As Book
FROM MyTable
WHERE IIf(InStr(1, [Books], ',') = -1, [Books], Left([Books], InStr(1, [Books], ',') - 1)) <> ""
UNION ALL
SELECT Author, IIf( InStr(1,[Books],',')> 0, IIf(InStr(InStr(1,[Books],',') + Len(','), [Books] , ',') < 1, Mid([Books], InStr(1,[Books],',') + Len(',')), Mid([Books], InStr(1,[Books],',') + Len(','), InStr(InStr(1,[Books],',') + Len(','), [Books] , ',') - InStr(1,[Books],',') - Len(','))), "")  As Book
FROM MyTable
WHERE IIf( InStr(1,[Books],',')> 0, IIf(InStr(InStr(1,[Books],',') + Len(','), [Books] , ',') < 1, Mid([Books], InStr(1,[Books],',') + Len(',')), Mid([Books], InStr(1,[Books],',') + Len(','), InStr(InStr(1,[Books],',') + Len(','), [Books] , ',') - InStr(1,[Books],',') - Len(','))), "")  <> ""
UNION ALL
SELECT Author, IIf( InStr(InStr(1,[Books],',') + Len(','), [Books],',')> 0, IIf(InStr(InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(','), [Books] , ',') < 1, Mid([Books], InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(',')), Mid([Books], InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(','), InStr(InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(','), [Books] , ',') - InStr(InStr(1,[Books],',') + Len(','), [Books],',') - Len(','))), "")  As Book
FROM MyTable
WHERE IIf( InStr(InStr(1,[Books],',') + Len(','), [Books],',')> 0, IIf(InStr(InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(','), [Books] , ',') < 1, Mid([Books], InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(',')), Mid([Books], InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(','), InStr(InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(','), [Books] , ',') - InStr(InStr(1,[Books],',') + Len(','), [Books],',') - Len(','))), "") <> ""
)
</code>```

Body:
I have a dataset with a primary key called authors and a field called books.

The table looks something like this:

Authors (primary key)     Books
John                      Fathom,Mouseover,Keycard
Kyle                      Teachers,Carl,Phone

I know this violates 1NF, and I'm attempting to create a new table (one to many relationship) with the primary key (authors) occurring more than once for each book. ie

Authors                   Books
John                      Fathom
John                      Mouseover
John                      Keycard
Kyle                      Teachers
Kyle                      Carl
Kyle                      Phone

I need to use SQL in microsoft access, and I think it involves the split function, but I'm at a loss for how to perform this query.

Any insight would be greatly appreciated!

Thank you very much

Body:
Well, since the code is rather difficult to implement, and you only have 2, I guess I can share an implemented solution:

(replace MyTable with your tablename, and find and replace all field names with the correct one):

SELECT * Into NewTable FROM (
SELECT Author, IIf(InStr(1, [Books], ',') = -1, [Books], Left([Books], InStr(1, [Books], ',') - 1)) As Book
FROM MyTable
WHERE IIf(InStr(1, [Books], ',') = -1, [Books], Left([Books], InStr(1, [Books], ',') - 1)) <> ""
UNION ALL
SELECT Author, IIf( InStr(1,[Books],',')> 0, IIf(InStr(InStr(1,[Books],',') + Len(','), [Books] , ',') < 1, Mid([Books], InStr(1,[Books],',') + Len(',')), Mid([Books], InStr(1,[Books],',') + Len(','), InStr(InStr(1,[Books],',') + Len(','), [Books] , ',') - InStr(1,[Books],',') - Len(','))), "")  As Book
FROM MyTable
WHERE IIf( InStr(1,[Books],',')> 0, IIf(InStr(InStr(1,[Books],',') + Len(','), [Books] , ',') < 1, Mid([Books], InStr(1,[Books],',') + Len(',')), Mid([Books], InStr(1,[Books],',') + Len(','), InStr(InStr(1,[Books],',') + Len(','), [Books] , ',') - InStr(1,[Books],',') - Len(','))), "")  <> ""
UNION ALL
SELECT Author, IIf( InStr(InStr(1,[Books],',') + Len(','), [Books],',')> 0, IIf(InStr(InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(','), [Books] , ',') < 1, Mid([Books], InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(',')), Mid([Books], InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(','), InStr(InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(','), [Books] , ',') - InStr(InStr(1,[Books],',') + Len(','), [Books],',') - Len(','))), "")  As Book
FROM MyTable
WHERE IIf( InStr(InStr(1,[Books],',') + Len(','), [Books],',')> 0, IIf(InStr(InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(','), [Books] , ',') < 1, Mid([Books], InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(',')), Mid([Books], InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(','), InStr(InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(','), [Books] , ',') - InStr(InStr(1,[Books],',') + Len(','), [Books],',') - Len(','))), "") <> ""
)


问:
Keras does not use GPU on Pycharm having python 3.5 and Tensorflow 1.4

from tensorflow.python.client
import device_lib
def get_available_gpus():
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type == 'GPU']
xx= get_available_gpus()
print('The GPU device is: ', xx)
print('Tensorflow: ', tf.__version__)`
```

<p>This gives me the following output.</p>

<pre class="lang-py prettyprint-override"><code>Using TensorFlow backend.
2017-12-04 18:13:37.479189: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA
The GPU device is:  []
Tensorflow:  1.4.0
</code>```

I am using Pycharm community edition with python 3.5.
Can anybody help in fixing how one can enforce to use GPU. Although while reading the documentation, I have found that Keras use GPU automatically. So what is the problem in my case that it does not use GPU?
I also tried to uninstall Tensorflow, as suggested in some questions but still it does not use it. Need guidance.

答:
I solved it with the answer given by Keras with TensorFlow backend not using GPU </p>

<p>You need to uninstall both tensorflow and tensorflow-gpu. And than reinstall tensorflow-gpu.
If both are installed than Keras will use only CPU version. </p>

Body:
from tensorflow.python.client
import device_lib
def get_available_gpus():
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type == 'GPU']
xx= get_available_gpus()
print('The GPU device is: ', xx)
print('Tensorflow: ', tf.__version__)`

This gives me the following output.

Using TensorFlow backend.
2017-12-04 18:13:37.479189: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA
The GPU device is:  []
Tensorflow:  1.4.0

I am using Pycharm community edition with python 3.5.
Can anybody help in fixing how one can enforce to use GPU. Although while reading the documentation, I have found that Keras use GPU automatically. So what is the problem in my case that it does not use GPU?
I also tried to uninstall Tensorflow, as suggested in some questions but still it does not use it. Need guidance.

Body:
I solved it with the answer given by Keras with TensorFlow backend not using GPU

You need to uninstall both tensorflow and tensorflow-gpu. And than reinstall tensorflow-gpu.
If both are installed than Keras will use only CPU version.


问:
Open API inherited example data
I'm using OpenAPI 3.0 to define an API for a service I am building. I'm running into an issue reusing schema components inside other components. For example, I have a Note object which contains a Profile object of the person who created the note. This works as expected by referencing the Profile object using the $ref keyword. The issue is when showing the example there isn't any data for the profile, and if I place the ref in the example like below it includes the actual OpenAPI block of Profile not just the example data for the Profile component.

I'm wondering if there is a way of reusing components in other components and also reusing the example set on those components?

Ex:

```<code>FullNote:
  allOf:
    - $ref: '#/components/schemas/BaseNote'
    - type: object
      title: A single note response
      required:
      - id
      - dateCreated
      - profile
      properties:
        id:
          type: integer
          format: int32
        dateCreated:
          type: integer
          format: int64
        profile:
          type: object
          $ref: '#/components/schemas/Profile'
      example:
        id: 123456789
        dateCreated: 1509048083045
        profile:
          $ref: '#/components/schemas/Profile'
</code>```

答:
The example keyword (not to be confused with exampleS) does NOT support $ref. The whole example needs to be specified inline:

    FullNote:
      allOf:
        - $ref: '#/components/schemas/BaseNote'
        - type: object
          ...
          example:
            id: 123456789
            dateCreated: 1509048083045
            influencer:
              prop1: value1  # <----
              prop2: value2
```

<p>Alternatively, you can use property-level examples - in this case tools like Swagger UI will build the schema example from property examples.</p>

<pre class="lang-yaml prettyprint-override"><code>    FullNote:
      allOf:
        - $ref: '#/components/schemas/BaseNote'
        - type: object
          ...
          properties:
            id:
              type: integer
              format: int32
              example: 123456789      # <----
            dateCreated:
              type: integer
              format: int64
              example: 1509048083045  # <----
            profile:
              # This property will use examples from the Profile schema
              $ref: '#/components/schemas/Profile'
    Profile:
      type: object
      properties:
        prop1:
          type: string
          example: value1   # <----
</code>```

Title: Open API inherited example data

Body:
I'm using OpenAPI 3.0 to define an API for a service I am building. I'm running into an issue reusing schema components inside other components. For example, I have a Note object which contains a Profile object of the person who created the note. This works as expected by referencing the Profile object using the $ref keyword. The issue is when showing the example there isn't any data for the profile, and if I place the ref in the example like below it includes the actual OpenAPI block of Profile not just the example data for the Profile component.

I'm wondering if there is a way of reusing components in other components and also reusing the example set on those components?

Ex:

FullNote:
  allOf:
    - $ref: '#/components/schemas/BaseNote'
    - type: object
      title: A single note response
      required:
      - id
      - dateCreated
      - profile
      properties:
        id:
          type: integer
          format: int32
        dateCreated:
          type: integer
          format: int64
        profile:
          type: object
          $ref: '#/components/schemas/Profile'
      example:
        id: 123456789
        dateCreated: 1509048083045
        profile:
          $ref: '#/components/schemas/Profile'

Body:
The example keyword (not to be confused with exampleS) does NOT support $ref. The whole example needs to be specified inline:

    FullNote:
      allOf:
        - $ref: '#/components/schemas/BaseNote'
        - type: object
          ...
          example:
            id: 123456789
            dateCreated: 1509048083045
            influencer:
              prop1: value1  # <----
              prop2: value2

Alternatively, you can use property-level examples - in this case tools like Swagger UI will build the schema example from property examples.

    FullNote:
      allOf:
        - $ref: '#/components/schemas/BaseNote'
        - type: object
          ...
          properties:
            id:
              type: integer
              format: int32
              example: 123456789      # <----
            dateCreated:
              type: integer
              format: int64
              example: 1509048083045  # <----
            profile:
              # This property will use examples from the Profile schema
              $ref: '#/components/schemas/Profile'
    Profile:
      type: object
      properties:
        prop1:
          type: string
          example: value1   # <----


问:
why super.onDestroy is showing "Cannot resolve method onDestroy()" inside background Thread
while using onDestroy() method in saveInBackground() gives an error that is Cannot resolve method onDestroy() so below is my code for doing so

```<code> ParseRelation<ParseObject> p = ParseUser.getCurrentUser().getRelation("brkRelation");
    ParseQuery p2 = p.getQuery();
    List<ParseObject> oc = null;
    try {
        oc = p2.find();

        for (ParseObject country2 : oc) {

            if (country2 != null) {
                country2.put("online", false);
                country2.saveInBackground(new SaveCallback() {
                    @Override
                    public void done(ParseException e) {
                        if (e == null) {

                            super.onDestroy();
                        } else {
                            Toast.makeText(getApplicationContext(), "Please Check your Internet Connection", Toast.LENGTH_LONG).show();
                        }
                    }
                });

            }
        }
    } catch (ParseException e1) {
        e1.printStackTrace();
    }
</code>```

Before exiting my app I want to do save something in my db

gives me an error Cannot resolve method onDestroy()

答:
As stated in the above answer, you are not in the escope of the Activity class.

The super refers to SaveCallback and not the Activity, you can simple do:

```<code>TheActivityName.super.onDestroy();
</code>```

If you want to use the actual implementation in the class (not the super) you call TheActivityName.this.onDestroy(), or just onDestroy() cause the class is in escope (in this second case if you have a method named exactly as the outer class you want to refer to you need the Name.this)

Body:
while using onDestroy() method in saveInBackground() gives an error that is Cannot resolve method onDestroy() so below is my code for doing so

 ParseRelation<ParseObject> p = ParseUser.getCurrentUser().getRelation("brkRelation");
    ParseQuery p2 = p.getQuery();
    List<ParseObject> oc = null;
    try {
        oc = p2.find();

        for (ParseObject country2 : oc) {

            if (country2 != null) {
                country2.put("online", false);
                country2.saveInBackground(new SaveCallback() {
                    @Override
                    public void done(ParseException e) {
                        if (e == null) {

                            super.onDestroy();
                        } else {
                            Toast.makeText(getApplicationContext(), "Please Check your Internet Connection", Toast.LENGTH_LONG).show();
                        }
                    }
                });

            }
        }
    } catch (ParseException e1) {
        e1.printStackTrace();
    }

Before exiting my app I want to do save something in my db

gives me an error Cannot resolve method onDestroy()

Body:
As stated in the above answer, you are not in the escope of the Activity class.

The super refers to SaveCallback and not the Activity, you can simple do:

TheActivityName.super.onDestroy();

If you want to use the actual implementation in the class (not the super) you call TheActivityName.this.onDestroy(), or just onDestroy() cause the class is in escope (in this second case if you have a method named exactly as the outer class you want to refer to you need the Name.this)


问:
Angular 5 - Cannot resolve observable in Observable.catch()
My first time here, I hope that you can help me.

I'm trying to create a response interceptor on Angular 5. I want to handle responses with status [202] successfully.

I'm doing a call to a webservice, the interceptor is working well it catches the error. If I return Observable.throw('') this will arrive to the error function on subscribe, but when I try to return a new Observable to resolve the exception, it is not arriving on success method of subscribe.

The interceptor code:

```<code>import {Injectable} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor,
HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class Handle2xxResponseInterceptor implements HttpInterceptor{

 intercept(req: HttpRequest<any>, next: HttpHandler):
 Observable<HttpEvent<any>> {

   return next.handle(req).catch(error => {
     if (error instanceof HttpErrorResponse) {
       if (error.status === 202) {
        return Observable.of(error); // or return Observable.empty();
       }
     }
     return Observable.throw(error);
   });
 }
}
</code>```

Thank you people.

答:
You're not able to catch 202 because 202 isn't an http error code and catch only catches errors.  Instead, just use a normal map or do operator or higher order operator like switchMap to do whatever you want with it:</p>

```<code>return next.handle(req).switchMap(response => {
  if (response.status === 202) {
    // process error
    return Observable.empty();
  }
  return Observable.of(response);
});
</code>```

Body:
My first time here, I hope that you can help me.

I'm trying to create a response interceptor on Angular 5. I want to handle responses with status [202] successfully.

I'm doing a call to a webservice, the interceptor is working well it catches the error. If I return Observable.throw('') this will arrive to the error function on subscribe, but when I try to return a new Observable to resolve the exception, it is not arriving on success method of subscribe.

The interceptor code:

import {Injectable} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor,
HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class Handle2xxResponseInterceptor implements HttpInterceptor{

 intercept(req: HttpRequest<any>, next: HttpHandler):
 Observable<HttpEvent<any>> {

   return next.handle(req).catch(error => {
     if (error instanceof HttpErrorResponse) {
       if (error.status === 202) {
        return Observable.of(error); // or return Observable.empty();
       }
     }
     return Observable.throw(error);
   });
 }
}

Thank you people.

Body:
You're not able to catch 202 because 202 isn't an http error code and catch only catches errors.  Instead, just use a normal map or do operator or higher order operator like switchMap to do whatever you want with it:

return next.handle(req).switchMap(response => {
  if (response.status === 202) {
    // process error
    return Observable.empty();
  }
  return Observable.of(response);
});