问:
Jakson polymorphic Enum case
I am glued with some Jackson polymorphic problem.

I work on a web JDR Character Editor personnal project. I use Springboot and try to stuck with the phylosophy. Moreover, I try to make some independent packages, because of study-case for my real work (another springboot project).

With no Jackson configuration, I have no problem for serialization of a Competence. But when I try to get back any modification on the web editor, so when Jackson make a deserialization of a Competence, problems occur with "dependance" property.

Here are my classes:

The one I try to serialize/deserialize:

```public class Competence implements Composante, ComposanteTemplate {

    public enum Categorie {
        APPRENTI,
        COMPAGNON
    }

    private String nom;
    private String description;
    private Categorie categorie;
    private Chapitre chapitre;
    private AttributTemplate dependance;
    private List sousCompetences = new ArrayList();

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Competence getTemplate() {
        return this;
    }

    public Categorie getCategorie() {
        return categorie;
    }

    public void setCategorie(Categorie categorie) {
        this.categorie = categorie;
    }

    public Chapitre getChapitre() {
        return chapitre;
    }

    public void setChapitre(Chapitre chapitre) {
        this.chapitre = chapitre;
    }

    public AttributTemplate getDependance() {
        return dependance;
    }

    public void setDependance(AttributTemplate dependance) {
        this.dependance = dependance;
    }

    public List getSousCompetences() {
        return sousCompetences;
    }

    public void setSousCompetences(List sousCompetences) {
        this.sousCompetences = sousCompetences;
    }

    public boolean isOuverte() {
        return !sousCompetences.isEmpty();
    }
}```

The superclass of the property I have a problem with:

```public interface AttributTemplate extends ComposanteTemplate {}```

The two subclasses which could be use for Competence#dependance property:

```public enum Carac implements AttributTemplate, Attribut {

    FORT(Type.PHYSIQUE),
    AGILE(Type.PHYSIQUE),
    RESISTANT(Type.PHYSIQUE),
    OBSERVATEUR(Type.PHYSIQUE),
    SAVANT(Type.MENTALE),
    RUSE(Type.MENTALE),
    TALENTUEUX(Type.MENTALE),
    CHARMEUR(Type.MENTALE);

    public enum Type {
        PHYSIQUE,
        MENTALE
    }

    public final Type type;
    public final String nom = name().toLowerCase();

    private String description;

    Carac(Type type) {
        this.type = type;
    }

    @Override
    public String getNom() { return nom; }

    @Override
    public String getDescription() { return description;  }

    @Override
    public Carac getTemplate() { return this; }

    public void setDescription(String description) { this.description = description; }

}```

```public enum ArtTemplate implements AttributTemplate {

    ART_GUERRIER(2, 1),
    ART_ETRANGE(1, 2),
    ART_GUILDIEN(1, 1);

    public static final String ART_PREFIX = "ART";

    public final String nom = name().toLowerCase().replace("_", " ");
    public final int nbCaracsPhysiques;
    public final int nbCaracsMentales;

    private String description;

    ArtTemplate(int nbCaracsPhysiques, int nbCaracsMentales) {
        this.nbCaracsMentales = nbCaracsMentales;
        this.nbCaracsPhysiques = nbCaracsPhysiques;
    }

    @Override
    public String getNom() {
        return nom;
    }

    @Override
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getNbCaracs() {
        return nbCaracsPhysiques + nbCaracsMentales;
    }

}```

The result json (and then the json I send) is:

```{"nom":"Comp_1489746646510","description":"ezbuixnwrclfvmgwdviubcauenzytpzzvumnohwyhpuynxaqhkjdbqygtrmbtlschthovuyoiolkauucwokkfjnaujnufshrjboykuqce","categorie":"APPRENTI","chapitre":"GUERRE","dependance":"ART_ETRANGE","ouverte":false,"sousCompetences":[]}```

QUESTION:
I understand that my problem is caused by the abstract relation AttributTemplate, and then when Jackson try to deserialize, he does not know which of Carac or ArtTemplate class to use.
I try to keep unchanged Competence (Competence come from an external jar), so no annotation on this class is possible.

I've tried many of the solutions I found (Jackson 1.5: Polymorphic Type Handling, first steps ) and the only one which has worked was to define a DeserializationProblemHandler

```<code>mapper.addHandler(new DeserializationProblemHandler() {
 @Override
 public Object handleMissingInstantiator(DeserializationContext ctxt, Class<?> instClass, JsonParser p, String msg) throws IOException {
     if (instClass == AttributTemplate.class) {
         String name = p.getText();
         return !name.startsWith(ArtTemplate.ART_PREFIX) ? Carac.valueOf(name) : ArtTemplate.valueOf(name);
     }
     return super.handleMissingInstantiator(ctxt, instClass, p, msg);
 }
</code>```

});

But I feel bad with this solution, because I am sure there is an other beautiful one.

So is it possible to configure the mapper in order that he is able to determine which of Carac or ArtTemplate he must use to get AttributTemplate?

EDIT:
I managed to have this:

```{"nom":"Comp_1489756873433","description":"kruzueemlwisibshlkotasayfkhdqkqolvhlqgsnntndkpvbmmgklqysabiakaolempmupeyiqaztdcrhwimdksgzybbdzttwnwqjxhfo","categorie":"COMPAGNON","chapitre":"GUERRE","dependance":["mova.ged.perso.inne.Carac","AGILE"],"ouverte":true,"sousCompetences":[...]}```

by configuring like this the mapper

```
    abstract class CompetenceMixIn {

        private AttributTemplate dependance;

        @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.EXISTING_PROPERTY, property="dependance")
        @JsonSubTypes({ @JsonSubTypes.Type(value = Carac.class, name = "carac"), @JsonSubTypes.Type(value = ArtTemplate.class, name = "artTemplate") })
        public void setDependance(AttributTemplate dependance) {
            this.dependance = dependance;
        }
    }```

```ObjectMapper mapper = jsonConverter.getObjectMapper();
mapper.addMixIn(Competence.class, CompetenceMixIn.class);```

As you could see, I'm still parasited with the array that wrapped dependance value. I would (...)"dependance": "AGILE", (...) not (...)"dependance":["mova.ged.perso.inne.Carac", "AGILE"], (...)

And I don't know what to change in order to have this.

答:
i have been looking into what you are trying to do. Unfortunatelly, I believe there are issues with Enums + inheritance.

I have an alternative solution that you could be using which is to use a custom creator and ignore unknown properties. See the following example:

```<code>public class JacksonInheritance {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();

        Competence c = new Competence();
        c.desc = "desc";
        c.nome = "nome";
        c.template = Att1.TEST_Att1;
        String test = mapper.writeValueAsString(c);
        System.out.println(test);

        Competence readValue = mapper.readValue(test, Competence.class);
        System.out.println(readValue.template);
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class Competence {

        private static final Map<String, AttributeTemplate> templates;
        static {
            templates = new HashMap<>();
            Stream.of(Att1.values()).forEach( a -> templates.put(a.name(), a));
            Stream.of(Att2.values()).forEach( a -> templates.put(a.name(), a));
        }

        @JsonProperty
        String nome;
        @JsonProperty
        String desc;
        @JsonIgnore
        AttributeTemplate template;

        @JsonProperty("template_type")
        public String getTempl() {
            // Here you can do whichever way uou would like to serialise your template. This will be the key
            return template.toString();
        }

        @JsonCreator
        public static Competence create(@JsonProperty("template_type") String templateType) {
            Competence c = new Competence();
            c.template =  templates.get(templateType);
            return c;
        }
    }

    public static interface AttributeTemplate {
    }

    public static enum Att1 implements AttributeTemplate {
        TEST_Att1;
    }

    public static enum Att2 implements AttributeTemplate {

        TEST2_Att2;
    }
}
</code>```

Here I am detaching the enum logic from the jackson logic and implement my own. This does not require a custom serialisation.

I basically say that I serialise my enum as its value (you can obviously choose which ever properties you would like for this).

My output json then looks as:

```<code>{"template_type":"TEST_Att1","nome":"nome","desc":"desc"}
</code>```

At the return step I now know that the information I need to construct the correct enum template type from the template_type attribute. This is what I can inject into my factory method create.

In the create I can use my statically created map to populate the correct enum into my object. We can just create this map statically since our enums are finite and static.

The beauty of this is also that the generator is only used for creation. Using @JsonIgnoreProperties(ignoreUnknown = true), we can tell jackson to not freak out by all our custom elements in the json. It will simply deserialise any fields it can detect and leave the other ones (since we are using a custom template_type for our enum resolution).

Finally, I am ignoring the actual template in my bean because jackson won't be able to construct that.

I hope that this works for you/helps you.  Sorry about the delay.

Reason for not using inheritance:

There seem to be issues with enum + inheritance in jackson. Particularly jackson by default uses reflection and calls the private constructor of the enum for generation. You may be able to get creators to work in a similar way as above though.

The deserialisation expects the template. I am going of the assumption that you do NOT necessarily want to serialise all elements of the enum. This is because the enum name, in my case TEST_Att1 makes the enum unique. There is no need to serialise and send all the different attributes these enums have around. However, Deserialization with @JsonSubTypes for no value - missing property error shows that jackson requires your template field to be at least present. This is a a slight issue, because you want to use an external property for this instead (so why include a null-field as suggested in your json just to make jackson happy)

This may not be the best solution, but I think it is relatively elegant given the restrictions. I hope that helps you,

Artur

Title: Jakson polymorphic Enum case

Body:
I am glued with some Jackson polymorphic problem.

I work on a web JDR Character Editor personnal project. I use Springboot and try to stuck with the phylosophy. Moreover, I try to make some independent packages, because of study-case for my real work (another springboot project).

With no Jackson configuration, I have no problem for serialization of a Competence. But when I try to get back any modification on the web editor, so when Jackson make a deserialization of a Competence, problems occur with "dependance" property.

Here are my classes:

The one I try to serialize/deserialize:

public class Competence implements Composante, ComposanteTemplate {

    public enum Categorie {
        APPRENTI,
        COMPAGNON
    }

    private String nom;
    private String description;
    private Categorie categorie;
    private Chapitre chapitre;
    private AttributTemplate dependance;
    private List sousCompetences = new ArrayList();

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Competence getTemplate() {
        return this;
    }

    public Categorie getCategorie() {
        return categorie;
    }

    public void setCategorie(Categorie categorie) {
        this.categorie = categorie;
    }

    public Chapitre getChapitre() {
        return chapitre;
    }

    public void setChapitre(Chapitre chapitre) {
        this.chapitre = chapitre;
    }

    public AttributTemplate getDependance() {
        return dependance;
    }

    public void setDependance(AttributTemplate dependance) {
        this.dependance = dependance;
    }

    public List getSousCompetences() {
        return sousCompetences;
    }

    public void setSousCompetences(List sousCompetences) {
        this.sousCompetences = sousCompetences;
    }

    public boolean isOuverte() {
        return !sousCompetences.isEmpty();
    }
}

The superclass of the property I have a problem with:

public interface AttributTemplate extends ComposanteTemplate {}

The two subclasses which could be use for Competence#dependance property:

public enum Carac implements AttributTemplate, Attribut {

    FORT(Type.PHYSIQUE),
    AGILE(Type.PHYSIQUE),
    RESISTANT(Type.PHYSIQUE),
    OBSERVATEUR(Type.PHYSIQUE),
    SAVANT(Type.MENTALE),
    RUSE(Type.MENTALE),
    TALENTUEUX(Type.MENTALE),
    CHARMEUR(Type.MENTALE);

    public enum Type {
        PHYSIQUE,
        MENTALE
    }

    public final Type type;
    public final String nom = name().toLowerCase();

    private String description;

    Carac(Type type) {
        this.type = type;
    }

    @Override
    public String getNom() { return nom; }

    @Override
    public String getDescription() { return description;  }

    @Override
    public Carac getTemplate() { return this; }

    public void setDescription(String description) { this.description = description; }

}

public enum ArtTemplate implements AttributTemplate {

    ART_GUERRIER(2, 1),
    ART_ETRANGE(1, 2),
    ART_GUILDIEN(1, 1);

    public static final String ART_PREFIX = "ART";

    public final String nom = name().toLowerCase().replace("_", " ");
    public final int nbCaracsPhysiques;
    public final int nbCaracsMentales;

    private String description;

    ArtTemplate(int nbCaracsPhysiques, int nbCaracsMentales) {
        this.nbCaracsMentales = nbCaracsMentales;
        this.nbCaracsPhysiques = nbCaracsPhysiques;
    }

    @Override
    public String getNom() {
        return nom;
    }

    @Override
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getNbCaracs() {
        return nbCaracsPhysiques + nbCaracsMentales;
    }

}

The result json (and then the json I send) is:

{"nom":"Comp_1489746646510","description":"ezbuixnwrclfvmgwdviubcauenzytpzzvumnohwyhpuynxaqhkjdbqygtrmbtlschthovuyoiolkauucwokkfjnaujnufshrjboykuqce","categorie":"APPRENTI","chapitre":"GUERRE","dependance":"ART_ETRANGE","ouverte":false,"sousCompetences":[]}

QUESTION:
I understand that my problem is caused by the abstract relation AttributTemplate, and then when Jackson try to deserialize, he does not know which of Carac or ArtTemplate class to use.
I try to keep unchanged Competence (Competence come from an external jar), so no annotation on this class is possible.

I've tried many of the solutions I found (Jackson 1.5: Polymorphic Type Handling, first steps ) and the only one which has worked was to define a DeserializationProblemHandler

mapper.addHandler(new DeserializationProblemHandler() {
 @Override
 public Object handleMissingInstantiator(DeserializationContext ctxt, Class<?> instClass, JsonParser p, String msg) throws IOException {
     if (instClass == AttributTemplate.class) {
         String name = p.getText();
         return !name.startsWith(ArtTemplate.ART_PREFIX) ? Carac.valueOf(name) : ArtTemplate.valueOf(name);
     }
     return super.handleMissingInstantiator(ctxt, instClass, p, msg);
 }

});

But I feel bad with this solution, because I am sure there is an other beautiful one.

So is it possible to configure the mapper in order that he is able to determine which of Carac or ArtTemplate he must use to get AttributTemplate?

EDIT:
I managed to have this:

{"nom":"Comp_1489756873433","description":"kruzueemlwisibshlkotasayfkhdqkqolvhlqgsnntndkpvbmmgklqysabiakaolempmupeyiqaztdcrhwimdksgzybbdzttwnwqjxhfo","categorie":"COMPAGNON","chapitre":"GUERRE","dependance":["mova.ged.perso.inne.Carac","AGILE"],"ouverte":true,"sousCompetences":[...]}

by configuring like this the mapper

    abstract class CompetenceMixIn {

        private AttributTemplate dependance;

        @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.EXISTING_PROPERTY, property="dependance")
        @JsonSubTypes({ @JsonSubTypes.Type(value = Carac.class, name = "carac"), @JsonSubTypes.Type(value = ArtTemplate.class, name = "artTemplate") })
        public void setDependance(AttributTemplate dependance) {
            this.dependance = dependance;
        }
    }

ObjectMapper mapper = jsonConverter.getObjectMapper();
mapper.addMixIn(Competence.class, CompetenceMixIn.class);

As you could see, I'm still parasited with the array that wrapped dependance value. I would (...)"dependance": "AGILE", (...) not (...)"dependance":["mova.ged.perso.inne.Carac", "AGILE"], (...)

And I don't know what to change in order to have this.

Body:
i have been looking into what you are trying to do. Unfortunatelly, I believe there are issues with Enums + inheritance.

I have an alternative solution that you could be using which is to use a custom creator and ignore unknown properties. See the following example:

public class JacksonInheritance {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();

        Competence c = new Competence();
        c.desc = "desc";
        c.nome = "nome";
        c.template = Att1.TEST_Att1;
        String test = mapper.writeValueAsString(c);
        System.out.println(test);

        Competence readValue = mapper.readValue(test, Competence.class);
        System.out.println(readValue.template);
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class Competence {

        private static final Map<String, AttributeTemplate> templates;
        static {
            templates = new HashMap<>();
            Stream.of(Att1.values()).forEach( a -> templates.put(a.name(), a));
            Stream.of(Att2.values()).forEach( a -> templates.put(a.name(), a));
        }

        @JsonProperty
        String nome;
        @JsonProperty
        String desc;
        @JsonIgnore
        AttributeTemplate template;

        @JsonProperty("template_type")
        public String getTempl() {
            // Here you can do whichever way uou would like to serialise your template. This will be the key
            return template.toString();
        }

        @JsonCreator
        public static Competence create(@JsonProperty("template_type") String templateType) {
            Competence c = new Competence();
            c.template =  templates.get(templateType);
            return c;
        }
    }

    public static interface AttributeTemplate {
    }

    public static enum Att1 implements AttributeTemplate {
        TEST_Att1;
    }

    public static enum Att2 implements AttributeTemplate {

        TEST2_Att2;
    }
}

Here I am detaching the enum logic from the jackson logic and implement my own. This does not require a custom serialisation.

I basically say that I serialise my enum as its value (you can obviously choose which ever properties you would like for this).

My output json then looks as:

{"template_type":"TEST_Att1","nome":"nome","desc":"desc"}

At the return step I now know that the information I need to construct the correct enum template type from the template_type attribute. This is what I can inject into my factory method create.

In the create I can use my statically created map to populate the correct enum into my object. We can just create this map statically since our enums are finite and static.

The beauty of this is also that the generator is only used for creation. Using @JsonIgnoreProperties(ignoreUnknown = true), we can tell jackson to not freak out by all our custom elements in the json. It will simply deserialise any fields it can detect and leave the other ones (since we are using a custom template_type for our enum resolution).

Finally, I am ignoring the actual template in my bean because jackson won't be able to construct that.

I hope that this works for you/helps you.  Sorry about the delay.

Reason for not using inheritance:

There seem to be issues with enum + inheritance in jackson. Particularly jackson by default uses reflection and calls the private constructor of the enum for generation. You may be able to get creators to work in a similar way as above though.

The deserialisation expects the template. I am going of the assumption that you do NOT necessarily want to serialise all elements of the enum. This is because the enum name, in my case TEST_Att1 makes the enum unique. There is no need to serialise and send all the different attributes these enums have around. However, Deserialization with @JsonSubTypes for no value - missing property error shows that jackson requires your template field to be at least present. This is a a slight issue, because you want to use an external property for this instead (so why include a null-field as suggested in your json just to make jackson happy)

This may not be the best solution, but I think it is relatively elegant given the restrictions. I hope that helps you,

Artur


来源: stackexchange

问:
MYSQL Query : get date which was entered on same name of day
I have a bunch of data that contain date and some numbers. The table looks like this.

```<code>ID  |   date                   |   amount  |
--------------------------------------------
1   |   2017-01-01 00:00:00    |   100     |
2   |   2017-02-04 00:00:00    |   5       |
3   |   2017-03-11 00:00:00    |   100     |
4   |   2017-04-14 00:00:00    |   20      |
5   |   2017-05-07 00:00:00    |   5       |
</code>```

So let's say today is monday. What I have to do is get data from table which 'date' is monday, same as today.
I would like to know is there any way do this just using sql query.

答:
Assuming that you column is name col_date You can use  WEEKDAY(col_date) = 0  </p>

```<code>SELECT DISTINCT(col_date) FROM `table` WHERE WEEKDAY(col_date)=0
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a bunch of data that contain date and some numbers. The table looks like this.

ID  |   date                   |   amount  |
--------------------------------------------
1   |   2017-01-01 00:00:00    |   100     |
2   |   2017-02-04 00:00:00    |   5       |
3   |   2017-03-11 00:00:00    |   100     |
4   |   2017-04-14 00:00:00    |   20      |
5   |   2017-05-07 00:00:00    |   5       |

So let's say today is monday. What I have to do is get data from table which 'date' is monday, same as today.
I would like to know is there any way do this just using sql query.

Body:
Assuming that you column is name col_date You can use  WEEKDAY(col_date) = 0

SELECT DISTINCT(col_date) FROM `table` WHERE WEEKDAY(col_date)=0


问:
How can I find out when a dataset was allocated?
I need to get the exact time when a dataset was allocated (not opened). I've searched all the SMF records but can't find anything suitable. Any ideas? It was allocated via SVC99 from a vendor STC. I'm pretty sure it's allocated and then OPENed, as the first SMF record referencing the dataset is DISP=OLD.

The dataset is not SMS managed.

答:
I think you are out of luck.

To my knowledge, creation time is not an attribute of any dataset. So looking through the SMF records probably wont help. You might be able to get the time of the first action perform after allocation, but that doesn't sound like it will help you. I found a thread on the IBM Mainframe forum that basically confirms my thought.

It says:

The only way to get the creation time of a data set is through
  analyzing SMF data for the date the data set was created, the creation
  time is not an attribute of the data set.

I'm not even certain you could get the time that way as no SMF data is
  written when the data set is created. The best you can do is the time
  the first I/O to the data set completes and a type 15 SMF record is
  written.


问:
Can a PyQt Embedded MatPlotLib Graph Be Interactive?
I have a stacked bar plot of analytics data embedded in my GUI which I would like to be more interactive. When the user hovers or clicks on a bar the plotted value should appear. Can this be done? I haven't been able to find anything about it in the documentation. Alternatively I could use something like PyGal but I don't know how to embed it into PyQt. Advice on either would be appreciated.</p>

答:
The easiest solution is to use matplotlib events. They work the same whether you use a standalone plotting window or embed into a GUI. </p>

<p>A good introduction can be found in the matplotlib manual's event handling page. </p>

Body:
The easiest solution is to use matplotlib events. They work the same whether you use a standalone plotting window or embed into a GUI.

A good introduction can be found in the matplotlib manual's event handling page.


问:
Issue using While+if statements together in Python
Can someone please check below code, as i am using while and If statement together in python and calling one more python code, but it is executing all the code except calling the other python code.</p>

```<code>import os
import psycopg2
import os.path
import subprocess
import sys

if os.path.isfile("Z:\\xyz\\New.xlsx"):
    while True:
        conn = psycopg2.connect(database="gp_bdl", user="adwed1", password="***", host="bdlgp12", port="6200")
        cur = conn.cursor()
        print ("Opened database successfully")
        try:
            cur.execute('''select function1();''')
            conn.commit()
            conn.close()

        except psycopg2.OperationalError:
            continue
        break;
        if os.path.isfile("Z:\\xyz\\second.xlsx"):
         print("Next has started")
         subprocess.call([sys.executable,'Next Python.py'])
    else:
         print("Nothing")
else:
   print("No Process")*
</code>```

答:
Everything after your break statement is dead code. If your try raises an error, the continue statement is starting a new iteration (different from pass, which just keep the flow going from that point).

But if it doesn't raise an exception, you're breaking out of the while, so your first if in unreachable.

Body:
Can someone please check below code, as i am using while and If statement together in python and calling one more python code, but it is executing all the code except calling the other python code.

import os
import psycopg2
import os.path
import subprocess
import sys

if os.path.isfile("Z:\\xyz\\New.xlsx"):
    while True:
        conn = psycopg2.connect(database="gp_bdl", user="adwed1", password="***", host="bdlgp12", port="6200")
        cur = conn.cursor()
        print ("Opened database successfully")
        try:
            cur.execute('''select function1();''')
            conn.commit()
            conn.close()

        except psycopg2.OperationalError:
            continue
        break;
        if os.path.isfile("Z:\\xyz\\second.xlsx"):
         print("Next has started")
         subprocess.call([sys.executable,'Next Python.py'])
    else:
         print("Nothing")
else:
   print("No Process")*


问:
Enter Not Working in document.getElementById.value
right now i m using \n to enter line break

```<code>document.getElementById('inputarea').value = "<h1>\nHead\n</h1>";
</code>```

i want to write code as

```<code>document.getElementById('inputarea').value = "
<h1>
Head
</h1>";
</code>```

but its not working. I m displaying value in text area.

suggest any way to display code without using \n or br.

答:
Use HTML Backtick (`) instead

Check the snippet

document.getElementById('inputarea').value = `

Head

`;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea id="inputarea"></textarea></code>```

Body:
right now i m using \n to enter line break

document.getElementById('inputarea').value = "
\nHead\n
";

i want to write code as

document.getElementById('inputarea').value = "

Head

";

but its not working. I m displaying value in text area.

suggest any way to display code without using \n or br.

Body:
Use HTML Backtick (`) instead

Check the snippet

document.getElementById('inputarea').value = `<h1>
Head
</h1>`;

<textarea id="inputarea"></textarea>


答:
```<code>select * from TableName where DAYNAME(`date`)=DAYNAME(CURDATE())
</code>```

Title: MYSQL Query : get date which was entered on same name of day


问:
Using Kafka instead of Redis for the queue purposes
I have a small project that uses Redis for the task queue purposes. Here is how it basically works.

I have two components in the system: desktop client (can be more than one) and a server-side app. Server-side app has a pull of tasks for the desktop client(s). When a client comes, the first available task from the pull is given to it. As the task has an id, when the desktop client gets back with the results, the server-side app can recognize the task by its id. Basically, I do the following in Redis:

Keep all the tasks as objects.

Keep queue (pool) of tasks in several lists: queue, provided, processing.

When a task is being provided to the desktop client, I use RPOPLPUSH in Redis to move the id from the queue list to the provided list.

When I get a response from the desktop client, I use LREM for the given task ID from the provided list (if it fails, I got a task that was not provided or was already processed, or just never existed - so, I break the execution). Then I use LPUSH to add the task id to the processing list. Given that I have unique task ids (controlled on the level of my app), I avoid duplicates in the Redis lists.

When the task is finished (the result got from the desktop client is processed and somehow saved), I remove the task from the processing list and delete the task object from Redis.

If anything goes wrong on any step (i.e. the task gets stuck on the processing or provided list), I can move the task back to the queue list and re-process it.

Now, the question: is it somehow possible to do the similar stuff in Apache Kafka? I do not need the exact behavior as in Redis - all I need is to be able to provide a task to the desktop client (it shouldn't be possible to provide the same task twice) and mark/change its state according to the actual processing status (new, provided, processing), so that I could control the process and restore the tasks that were not processed due to some problem. If it's possible, could anyone please describe the applicable workflow?

答:
It is possible for kafka to act as a standard queue. Check the consumer group feature.

If the question is about the appropriateness, please also refer Is Apache Kafka appropriate for use as a task queue?

We are using kafka as a task queue, one of the consideration went in favor of kafka was that it is already in our application ecosystem, found it easier than adding one more component.


问:
is there anyway to call lambda function with html contents?
```<code>function sample($test1, $test2, $inner_html) {
    $html = call_user_func($inner_html);
    echo $test1 .  ' ' . $test2 . ' ' . $html;
}

sample('test1', 'test2', function(){
                    echo 'first test.'
      ?>
       <b>this is a test.</>
      <?
                    echo 'last test.';
});
</code>```

答:
If you put something out you can only get that output if you buffer the output using the output control’s ob_start:

```<code>function sample($test1, $test2, $inner_html) {
    ob_start();
    $returnValue = call_user_func($inner_html);
    $output = ob_get_clean();
    echo $test1 .  ' ' . $test2 . ' ' . $output;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
function sample($test1, $test2, $inner_html) {
    $html = call_user_func($inner_html);
    echo $test1 .  ' ' . $test2 . ' ' . $html;
}

sample('test1', 'test2', function(){
                    echo 'first test.'
      ?>
       this is a test.</>
      <?
                    echo 'last test.';
});

Body:
If you put something out you can only get that output if you buffer the output using the output control’s ob_start:

function sample($test1, $test2, $inner_html) {
    ob_start();
    $returnValue = call_user_func($inner_html);
    $output = ob_get_clean();
    echo $test1 .  ' ' . $test2 . ' ' . $output;
}


问:
Django get_or_create returning models.DoesNotExist while importing a CSV
I have spent quite sometime to figure this out. I am simply trying to import a CSV file using Python's csv module and Django's get_or_create().

This is my simple code (built upon this code):

```<code>import csv
from .models import Person

def import_data():
    with open('/path/to/csv/people_list.csv') as f:
           reader = csv.reader(f)
           for row in reader:
               _, created = Person.objects.get_or_create(
                   name=row[0],
                   p_id=row[1],
                   current_status=row[2],
                   )
</code>```

I get the following error when I run import_data() on the shell

```<code>peoplelisting.models.DoesNotExist: Person matching query does not exist.
</code>```

Yes, this particular Person does not exist but isnt that the whole point of using get_or_create()? If it doesnt exist, create it?

答:
After a lot of playing around, finally figured the issue was the following:

My csv also contained a header row which I was not ignoring. I had thought I'll proceed piece-meal and would ignore the header only after I get the csv-importing to work but the header itself was creating the problem (thanks to this post which (indirectly) helped a lot). The values in the header did not match the schema (max_length etc.) and thats what Person matching query does not exist was referring to. Ignoring the header made it work. I just hope that the error message was more descriptive though. Hope it helps someone else save the hours I spent debugging a simple thing. Here's the correct code:

```<code>import csv
from .models import Person

def import_data():
    with open('/path/to/csv/people_list.csv') as f:
           reader = csv.reader(f)
           for row in reader:
              if row[0] != 'Person_name': #where Person_name is first column's name
                 _, created = Org.objects.get_or_create(
                     name=row[0],
                     p_id=row[1],
                     current_status=row[2],
                     )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have spent quite sometime to figure this out. I am simply trying to import a CSV file using Python's csv module and Django's get_or_create().

This is my simple code (built upon this code):

import csv
from .models import Person

def import_data():
    with open('/path/to/csv/people_list.csv') as f:
           reader = csv.reader(f)
           for row in reader:
               _, created = Person.objects.get_or_create(
                   name=row[0],
                   p_id=row[1],
                   current_status=row[2],
                   )

I get the following error when I run import_data() on the shell

peoplelisting.models.DoesNotExist: Person matching query does not exist.

Yes, this particular Person does not exist but isnt that the whole point of using get_or_create()? If it doesnt exist, create it?

Body:
After a lot of playing around, finally figured the issue was the following:

My csv also contained a header row which I was not ignoring. I had thought I'll proceed piece-meal and would ignore the header only after I get the csv-importing to work but the header itself was creating the problem (thanks to this post which (indirectly) helped a lot). The values in the header did not match the schema (max_length etc.) and thats what Person matching query does not exist was referring to. Ignoring the header made it work. I just hope that the error message was more descriptive though. Hope it helps someone else save the hours I spent debugging a simple thing. Here's the correct code:

import csv
from .models import Person

def import_data():
    with open('/path/to/csv/people_list.csv') as f:
           reader = csv.reader(f)
           for row in reader:
              if row[0] != 'Person_name': #where Person_name is first column's name
                 _, created = Org.objects.get_or_create(
                     name=row[0],
                     p_id=row[1],
                     current_status=row[2],
                     )


问:
provide application update only for iPhone
I have an app in App store which supports iPhone & iPad.
Now I want to update the app only for iPhone and I do not want to support iPad.

Is it possible?

If I'm posting this question in the wrong forum, please let me know the correct forum.

答:
No, you can't do that,  you will be get an error in time of uploading the app, what you can do now is hide your existing app from all territory and upload your app with a new bundle id with supported device iphone, in this case the user never get the update notification for your existing live app, it will be a new app.

Thanks.


问:
Parallelized code dependent from other functions
Here is the structure of a function I have created inside which a parallelization has been implemented.

```<code>    parallelized.function <- function(...){

          # Function used in the parallelization
            used.in.par <- function(...)
          # Function needed by used.in.par (auxiliars)
            aux1<-function(...)
            aux2<-function(...)
          #---------------------------------------------------#
          # PARALLELIZATION PROCESS
            suppressMessages(library(foreach))
            suppressMessages(library(doParallel))

                   ..................................

               %dopar%{ used.in.par(...) }

          #---------------------------------------------------#
         return(something)
         }
</code>```

The code works, but it supposes to define aux1 and  aux2 inside parallelized.function to work well (which needs a lot of lines of code).

Is there any way to call aux1 and aux2 functions instead of writing all the code inside parallelized.function?

I tried creating new scripts with aux functions and writing source(".../aux1.R") and source(".../aux2.R") inside parallelized.function without success.

Thank you,

答:
foreach package would do that for you. In order to acccess function that was not defined in the current environment, you should use .export; and loading required packages on each of the workers would be possible by using .packages option.

```<code>foreach(
  ...,
  .export = c('aux1', 'aux2'),
  .packages = c(...)
) %dopar% {
  ...
}
</code>```

Note that loading foreach and doParallel package inside foreach loop is not required. But you missed the part when you register clusters.

Body:
Here is the structure of a function I have created inside which a parallelization has been implemented.

    parallelized.function <- function(...){

          # Function used in the parallelization
            used.in.par <- function(...)
          # Function needed by used.in.par (auxiliars)
            aux1<-function(...)
            aux2<-function(...)
          #---------------------------------------------------#
          # PARALLELIZATION PROCESS
            suppressMessages(library(foreach))
            suppressMessages(library(doParallel))

                   ..................................

               %dopar%{ used.in.par(...) }

          #---------------------------------------------------#
         return(something)
         }

The code works, but it supposes to define aux1 and  aux2 inside parallelized.function to work well (which needs a lot of lines of code).

Is there any way to call aux1 and aux2 functions instead of writing all the code inside parallelized.function?

I tried creating new scripts with aux functions and writing source(".../aux1.R") and source(".../aux2.R") inside parallelized.function without success.

Thank you,

Body:
foreach package would do that for you. In order to acccess function that was not defined in the current environment, you should use .export; and loading required packages on each of the workers would be possible by using .packages option.

foreach(
  ...,
  .export = c('aux1', 'aux2'),
  .packages = c(...)
) %dopar% {
  ...
}

Note that loading foreach and doParallel package inside foreach loop is not required. But you missed the part when you register clusters.


问:
Using regex in SQL
I've run into a problem where I cannot go any longer on my own.
I currently have a database which basically lists my cellphone with different applications on it.

The applications are listed with the status within the same database column which means that i separate the application from the status with a ";" and i separate the different applications with a ",".

Example :

```<code>ipboard,4.83->6.3,Running;testAcap,6.9-0,Stopped;
ipboard,2.3333->5.366,Stopped;Videostream,1.2,Stopped;
</code>```

Now, how would i go about finding all the ipboards that currently as an app is stopped? As you see, the string before the status can vary in lenght due to the different versions. And I do not want a list of everything that is stopped, just the ipboard in this case.

My crappy query so far that selects all strings with ipboard in them at all(All of them doesnt have it) :

```<code>select *
  from acaps
  where acaps like '%ipb%'
</code>```

For me the next logical thing to do would be something like :

```<code>select *
  from acaps
  where acaps like '%ipb%'
  and subshitblabla where "Stopped" after the "," after the ipboard string.
</code>```

Anyone knows how to get this working?

答:
Thanks everyone for shown interest. Found a sollution that works for me, posting here as reference for others.</p>

```<code>SELECT * FROM `acaps`
where acaps REGEXP '(ipboard)[,][0-9\-\>\.]*[,](Stopped)\;.*'
</code>```

Title: Using regex in SQL

Body:
I've run into a problem where I cannot go any longer on my own.
I currently have a database which basically lists my cellphone with different applications on it.

The applications are listed with the status within the same database column which means that i separate the application from the status with a ";" and i separate the different applications with a ",".

Example :

ipboard,4.83->6.3,Running;testAcap,6.9-0,Stopped;
ipboard,2.3333->5.366,Stopped;Videostream,1.2,Stopped;

Now, how would i go about finding all the ipboards that currently as an app is stopped? As you see, the string before the status can vary in lenght due to the different versions. And I do not want a list of everything that is stopped, just the ipboard in this case.

My crappy query so far that selects all strings with ipboard in them at all(All of them doesnt have it) :

select *
  from acaps
  where acaps like '%ipb%'

For me the next logical thing to do would be something like :

select *
  from acaps
  where acaps like '%ipb%'
  and subshitblabla where "Stopped" after the "," after the ipboard string.

Anyone knows how to get this working?

Body:
Thanks everyone for shown interest. Found a sollution that works for me, posting here as reference for others.

SELECT * FROM `acaps`
where acaps REGEXP '(ipboard)[,][0-9\-\>\.]*[,](Stopped)\;.*'


问:
Unable to create virtual table in sqlite3 in electron app
I am using my own sqlite3.dll in electron. So i need to register all the functions of sqlite3 with 'ffi' that I need to use. It was working pretty well till now. Ex for sqlite3_exec, i've registered this in ffi as follows

```<code>var lib = ffi.library('sqlite3',sqlite3_exec': ['int', [sqlite3Ptr, 'string', 'pointer', 'pointer', stringPtr]],)
</code>```

and while using i use it as follows:

```<code>var res = lib.sqlite3_exec(dbHandle, query, null, null, null);
</code>```

It works perfect.

Now I need to create virtual table. So when i try to create virtual table with the same code, I get error. Did a bit of research and got to know that I need to register a function with ffi that will allow me to create virtual table.

the function is as follows:

```<code>'sqlite3_create_module': ['int',[sqlite3Ptr, 'string', 'pointer', 'pointer']]
</code>```

This is basically C syntax, I need to pass address of following module as the third parameter

```<code>static sqlite3_module module = {
    .iVersion = 1,
    .xCreate = test_CreateConnect,
    .xConnect = test_CreateConnect,
    .xBestIndex = test_BestIndex,
    .xDisconnect = test_DisconnectDestroy,
    .xDestroy = test_DisconnectDestroy,
    .xOpen = test_Open,
    .xClose = test_Close,
    .xFilter = test_Filter,
    .xNext = test_Next,
    .xEof = test_Eof,
    .xColumn = test_Column,
    .xRowid = test_Rowid,
    .xRename = test_Rename,
</code>```

};

Its in C syntax, I've tried to change it to JS syntax as much as possible, but still nothing positive.

So if you've any solution for this please help.

答:
If it's about creating a virtual table using fts3 or fts4 then you do not need to register the module with sqlite3 as  FTS3 and FTS4 are included with the SQLite core source code,but they are not enabled by default.
To enable them use the following two switches in the compiler command line :

```<code>-DSQLITE_ENABLE_FTS3
-DSQLITE_ENABLE_FTS3_PARENTHESIS
</code>```

Then you can use it as follows:

```<code>sqlite3 = ref.types.void; // we don't know what the layout of "sqlite3" looks like
sqlite3_stmt = ref.types.void;
sqlite3Ptr = ref.refType(sqlite3);
sqlite3PtrPtr = ref.refType(sqlite3Ptr);
stringPtr = ref.refType(ref.types.CString);
stmtPtr = ref.refType(sqlite3_stmt);
stmtPtrPtr = ref.refType(stmtPtr) ;

// binding to a few "libsqlite3" functions...
libsqlite3 = ffi.Library('sqlite3', {
    'sqlite3_open': ['int', ['string', sqlite3PtrPtr]],
    'sqlite3_close': ['int', [sqlite3Ptr]],
    'sqlite3_exec': ['int', [sqlite3Ptr, 'string', 'pointer', 'pointer', stringPtr]],
    'sqlite3_changes': ['int', [sqlite3Ptr]],
    'sqlite3_user_add': ['int', [sqlite3Ptr, 'string', 'string', 'int', 'int']],
    'sqlite3_user_authenticate': ['int', [sqlite3Ptr, 'string', 'string', 'int']],
    'sqlite3_prepare_v2': ['int',[sqlite3Ptr, 'string', 'int', stmtPtrPtr, stringPtr]],
    'sqlite3_bind_blob': [ 'int', [stmtPtr, 'int', 'string' , 'int', 'pointer'] ],
    'sqlite3_step':[ 'int', [stringPtr] ],
    'sqlite3_finalize': ['int', [stringPtr]],
    'sqlite3_column_bytes': ['string',[stringPtr,'int']],
    'sqlite3_column_blob': ['string',[stringPtr,'int']]
});
 dbHandle = dbPtrPtr.deref();
 var queryvtab = "CREATE VIRTUAL TABLE virtual_table_name USING fts3()";
 var commr = libsqlite3.sqlite3_exec(dbHandle, queryvtab, null, null, null);
</code>```

Body:
I am using my own sqlite3.dll in electron. So i need to register all the functions of sqlite3 with 'ffi' that I need to use. It was working pretty well till now. Ex for sqlite3_exec, i've registered this in ffi as follows

var lib = ffi.library('sqlite3',sqlite3_exec': ['int', [sqlite3Ptr, 'string', 'pointer', 'pointer', stringPtr]],)

and while using i use it as follows:

var res = lib.sqlite3_exec(dbHandle, query, null, null, null);

It works perfect.

Now I need to create virtual table. So when i try to create virtual table with the same code, I get error. Did a bit of research and got to know that I need to register a function with ffi that will allow me to create virtual table.

the function is as follows:

'sqlite3_create_module': ['int',[sqlite3Ptr, 'string', 'pointer', 'pointer']]

This is basically C syntax, I need to pass address of following module as the third parameter

static sqlite3_module module = {
    .iVersion = 1,
    .xCreate = test_CreateConnect,
    .xConnect = test_CreateConnect,
    .xBestIndex = test_BestIndex,
    .xDisconnect = test_DisconnectDestroy,
    .xDestroy = test_DisconnectDestroy,
    .xOpen = test_Open,
    .xClose = test_Close,
    .xFilter = test_Filter,
    .xNext = test_Next,
    .xEof = test_Eof,
    .xColumn = test_Column,
    .xRowid = test_Rowid,
    .xRename = test_Rename,

};

Its in C syntax, I've tried to change it to JS syntax as much as possible, but still nothing positive.

So if you've any solution for this please help.

Body:
If it's about creating a virtual table using fts3 or fts4 then you do not need to register the module with sqlite3 as  FTS3 and FTS4 are included with the SQLite core source code,but they are not enabled by default.
To enable them use the following two switches in the compiler command line :

-DSQLITE_ENABLE_FTS3
-DSQLITE_ENABLE_FTS3_PARENTHESIS

Then you can use it as follows:

sqlite3 = ref.types.void; // we don't know what the layout of "sqlite3" looks like
sqlite3_stmt = ref.types.void;
sqlite3Ptr = ref.refType(sqlite3);
sqlite3PtrPtr = ref.refType(sqlite3Ptr);
stringPtr = ref.refType(ref.types.CString);
stmtPtr = ref.refType(sqlite3_stmt);
stmtPtrPtr = ref.refType(stmtPtr) ;

// binding to a few "libsqlite3" functions...
libsqlite3 = ffi.Library('sqlite3', {
    'sqlite3_open': ['int', ['string', sqlite3PtrPtr]],
    'sqlite3_close': ['int', [sqlite3Ptr]],
    'sqlite3_exec': ['int', [sqlite3Ptr, 'string', 'pointer', 'pointer', stringPtr]],
    'sqlite3_changes': ['int', [sqlite3Ptr]],
    'sqlite3_user_add': ['int', [sqlite3Ptr, 'string', 'string', 'int', 'int']],
    'sqlite3_user_authenticate': ['int', [sqlite3Ptr, 'string', 'string', 'int']],
    'sqlite3_prepare_v2': ['int',[sqlite3Ptr, 'string', 'int', stmtPtrPtr, stringPtr]],
    'sqlite3_bind_blob': [ 'int', [stmtPtr, 'int', 'string' , 'int', 'pointer'] ],
    'sqlite3_step':[ 'int', [stringPtr] ],
    'sqlite3_finalize': ['int', [stringPtr]],
    'sqlite3_column_bytes': ['string',[stringPtr,'int']],
    'sqlite3_column_blob': ['string',[stringPtr,'int']]
});
 dbHandle = dbPtrPtr.deref();
 var queryvtab = "CREATE VIRTUAL TABLE virtual_table_name USING fts3()";
 var commr = libsqlite3.sqlite3_exec(dbHandle, queryvtab, null, null, null);


问:
MS bot , not reacting to Activity unless i remove the conversation data?
so i have to dialog activities, the 1st one for managing the user profile, the second will take car of the conversation.

```<code>       StateClient stateClient = activity.GetStateClient();
       BotData userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);
            if (userData.GetProperty<bool>("ProfileDone") == false)
            {
                await Conversation.SendAsync(activity, () => new ProfileSetup());
            }
            else
            {
                await Conversation.SendAsync(activity, () => new RootLuisDi());
            }
</code>```

Now when the 1st time interacting with the bot, it sends the user to the ProfileSetup, no issues. After completing the profile and set the ProfileDone flag to true. If the user interacts again it goes to RootLuisDi() but nothing trigger there. However, if I removed the conversation and chat again it actually works. !!

答:
I wouldn't branch the conversation in the controller. My suggestion for you is to create a RootDialog and branch the conversation there calling/forwarding the messages to the other dialogs accordingly.

You could even use your RootLuisDi dialog as the root and branch the conversation there. Override the MessageReceived method, check for the profile flag and forward the message to the ProfileSetup dialog or call to the base.MessageReceived.

Check this to read more about how to initiate new dialogs.

Body:
so i have to dialog activities, the 1st one for managing the user profile, the second will take car of the conversation.

       StateClient stateClient = activity.GetStateClient();
       BotData userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);
            if (userData.GetProperty<bool>("ProfileDone") == false)
            {
                await Conversation.SendAsync(activity, () => new ProfileSetup());
            }
            else
            {
                await Conversation.SendAsync(activity, () => new RootLuisDi());
            }

Now when the 1st time interacting with the bot, it sends the user to the ProfileSetup, no issues. After completing the profile and set the ProfileDone flag to true. If the user interacts again it goes to RootLuisDi() but nothing trigger there. However, if I removed the conversation and chat again it actually works. !!


问:
NSNumberFormatter positiveFormat
I need to format decimal numbers using NSNumberFormatter.
The result needs to be as follow

7 => 7

7.1 => 7.10

so if number have decimal part show it with 2 decimals.

I've tried with maximumFractionDigits = 2 and positiveFormat = @"###0.00" but it's not giving result I'm expecting

7 => 7.00

7.1 => 7.10

What is best positiveFormat to achieve my result?

here is code I'm using

```<code>NSNumberFormatter *numberFormatter = [NSNumberFormatter new];
numberFormatter.minimumFractionDigits = 0;
numberFormatter.maximumFractionDigits = 2;
numberFormatter.positiveFormat = @"###0.00";
</code>```

My solution

```<code>if ([number doubleValue] == [number integerValue]) {
    // use formatter with minimumFractionDigits = 0 and maximumFractionDigits = 0
} else {
    // use formatter with minimumFractionDigits = 2 and maximumFractionDigits = 2
}
</code>```

答:
There is no way to achieve that by setting properties of NSNumberFormatter. You can achieve that in two ways:

First way:

subclass NSNumberFormatter and implement it's stringFromNumber: method (or any related that you use for formatting. Then you set manually both minimumFractionDigits and maximumFractionDigits before formatting, like this (pseudocode) in stringFromNumber override, "numberHasDecimalFraction" is boolean condition you have to implement:

```<code>if(numberHasDecimalFraction){
    self.minimumFractionDigits = 2;
    self.maximumFractionDigits = 2;
}else{
    self.minimumFractionDigits = 0;
    self.maximumFractionDigits = 0;
}

return [super stringFromNumber: number];
</code>```

Second way:

Create a wrapper around two formatters and use it to format falling back on one of them depending on condition of having fraction digits similar to what you have in first way.

Title: NSNumberFormatter positiveFormat

Body:
I need to format decimal numbers using NSNumberFormatter.
The result needs to be as follow

7 => 7

7.1 => 7.10

so if number have decimal part show it with 2 decimals.

I've tried with maximumFractionDigits = 2 and positiveFormat = @"###0.00" but it's not giving result I'm expecting

7 => 7.00

7.1 => 7.10

What is best positiveFormat to achieve my result?

here is code I'm using

NSNumberFormatter *numberFormatter = [NSNumberFormatter new];
numberFormatter.minimumFractionDigits = 0;
numberFormatter.maximumFractionDigits = 2;
numberFormatter.positiveFormat = @"###0.00";

My solution

if ([number doubleValue] == [number integerValue]) {
    // use formatter with minimumFractionDigits = 0 and maximumFractionDigits = 0
} else {
    // use formatter with minimumFractionDigits = 2 and maximumFractionDigits = 2
}

Body:
There is no way to achieve that by setting properties of NSNumberFormatter. You can achieve that in two ways:

First way:

subclass NSNumberFormatter and implement it's stringFromNumber: method (or any related that you use for formatting. Then you set manually both minimumFractionDigits and maximumFractionDigits before formatting, like this (pseudocode) in stringFromNumber override, "numberHasDecimalFraction" is boolean condition you have to implement:

if(numberHasDecimalFraction){
    self.minimumFractionDigits = 2;
    self.maximumFractionDigits = 2;
}else{
    self.minimumFractionDigits = 0;
    self.maximumFractionDigits = 0;
}

return [super stringFromNumber: number];

Second way:

Create a wrapper around two formatters and use it to format falling back on one of them depending on condition of having fraction digits similar to what you have in first way.


问:
Problem with adding to list inside a loop in java
I wrote a code to check if an array is not in a list, then it should add it to another list. I used a linked list for this. But my problem is the program always add multiple copies of the current array and remove what's inside in the list before: My code is as follows:

```<code>import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Trial{

    public static void main(final String[] args){

        final List<int[]> G = new LinkedList<int[]>();
        final List<int[]> New = new LinkedList<int[]>();

        final int[] f = new int[2];

        for(int i = 0; i < 2; i++){
            for(int j = 0; j < 2; j++){
                f[0] = i;
                f[1] = j;
                // System.out.println("f is "+Arrays.toString(f));
                if(!(G.contains(f))){
                    System.out.println("current f is " + Arrays.toString(f));
                    // I print here in order to see what is f
                    New.add(f);
                    System.out.println("content of the list New");
                    // I print the list New to see its contents
                    for(int k = 0; k < New.size(); k++){
                        System.out.println(Arrays.toString(New.get(k)));
                    }
                    System.out.println("finished printing the list New");
                }
            }
        }

    }

}
</code>```

And this is the result I got after running:

```<code>current f is [0, 0]
content of the list New
[0, 0]
finished printing the list New
current f is [0, 1]
content of the list New
[0, 1]
[0, 1]
finished printing the list New
current f is [1, 0]
content of the list New
[1, 0]
[1, 0]
[1, 0]
finished printing the list New
current f is [1, 1]
content of the list New
[1, 1]
[1, 1]
[1, 1]
[1, 1]
finished printing the list New
</code>```

Please help!!!!

答:
if I'm not mistaken this is a classical error in Java

your not creating new objects !!! so your always adding and modifying the same one ego in the end your list contains one 1 object over and over again.

wha tyou want is to move

```<code>int [] f = new int [2];
</code>```

into your for loop

Body:
I wrote a code to check if an array is not in a list, then it should add it to another list. I used a linked list for this. But my problem is the program always add multiple copies of the current array and remove what's inside in the list before: My code is as follows:

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Trial{

    public static void main(final String[] args){

        final List<int[]> G = new LinkedList<int[]>();
        final List<int[]> New = new LinkedList<int[]>();

        final int[] f = new int[2];

        for(int i = 0; i < 2; i++){
            for(int j = 0; j < 2; j++){
                f[0] = i;
                f[1] = j;
                // System.out.println("f is "+Arrays.toString(f));
                if(!(G.contains(f))){
                    System.out.println("current f is " + Arrays.toString(f));
                    // I print here in order to see what is f
                    New.add(f);
                    System.out.println("content of the list New");
                    // I print the list New to see its contents
                    for(int k = 0; k < New.size(); k++){
                        System.out.println(Arrays.toString(New.get(k)));
                    }
                    System.out.println("finished printing the list New");
                }
            }
        }

    }

}

And this is the result I got after running:

current f is [0, 0]
content of the list New
[0, 0]
finished printing the list New
current f is [0, 1]
content of the list New
[0, 1]
[0, 1]
finished printing the list New
current f is [1, 0]
content of the list New
[1, 0]
[1, 0]
[1, 0]
finished printing the list New
current f is [1, 1]
content of the list New
[1, 1]
[1, 1]
[1, 1]
[1, 1]
finished printing the list New

Please help!!!!

Body:
if I'm not mistaken this is a classical error in Java

your not creating new objects !!! so your always adding and modifying the same one ego in the end your list contains one 1 object over and over again.

wha tyou want is to move

int [] f = new int [2];

into your for loop


问:
php imagecropauto() not working
I've written some code that copies a chunk of a big image to a new smaller image and saves it to the server. That all works just fine

However, I would like it to trim off any white background around the text and this is the part that doesn't work

Here is my code

```<code>$sourceImage = imagecreatefromjpeg($image);
$tempImg = imagecreatetruecolor($data[2],$data[3]);
imagecopy($tempImg,$sourceImage, 0, 0, $data[0], $data[1], $data[2], $data[3]);
imagejpeg($tempImg,$destImage,90);
imagedestroy($tempImg);
chmod($destImage,0775);
// these next two lines don't work
$original_img = imagecreatefromjpeg($destImage);
$cropped_destImage = imagecropauto($original_img , IMG_CROP_THRESHOLD, 2, 16777215);
</code>```

Can anyone see what I'm doing wrong here ?

Thanks

答:
Found it!!

I hadn't realized I needed to turn the resource back into a jpeg :

```<code>$original_img = imagecreatefromjpeg($destImage);
$cropped_destImage = imagecropauto($original_img , IMG_CROP_THRESHOLD, 5, 16777215);
imagejpeg($cropped_destImage,$destImage,90);
</code>```

Title: php imagecropauto() not working

Body:
I've written some code that copies a chunk of a big image to a new smaller image and saves it to the server. That all works just fine

However, I would like it to trim off any white background around the text and this is the part that doesn't work

Here is my code

$sourceImage = imagecreatefromjpeg($image);
$tempImg = imagecreatetruecolor($data[2],$data[3]);
imagecopy($tempImg,$sourceImage, 0, 0, $data[0], $data[1], $data[2], $data[3]);
imagejpeg($tempImg,$destImage,90);
imagedestroy($tempImg);
chmod($destImage,0775);
// these next two lines don't work
$original_img = imagecreatefromjpeg($destImage);
$cropped_destImage = imagecropauto($original_img , IMG_CROP_THRESHOLD, 2, 16777215);

Can anyone see what I'm doing wrong here ?

Thanks

Body:
Found it!!

I hadn't realized I needed to turn the resource back into a jpeg :

$original_img = imagecreatefromjpeg($destImage);
$cropped_destImage = imagecropauto($original_img , IMG_CROP_THRESHOLD, 5, 16777215);
imagejpeg($cropped_destImage,$destImage,90);


问:
Rendering the same scene in two independent windows
I am trying to renderer the same scene in two different QOpenGLWindows. I don't want to duplicate memory, for this reason I am trying to use the share context but I'm not sure how it works.

I'm using the attribute Qt::AA_ShareOpenGLContexts because the documentation says that It makes that every shader context will be shared between them.

However, I'm generating the VBO in one context and generating a VAO and Shader Program in each context (because it cannot be shared) but the second widget does not paint anything.

I suppose that my problem arises because the VBO is not shared between contexts. Qt::AA_ShareOpenGLContexts is not enough? Maybe I have to use QOpenGLContext::globalShareContext(), how could I use it?

The following text explains what I am doing...

Whit the following method, I generate the Object which contains the information about the object thaat I want to paint in the scene:

```<code>void AEOpenGLViewer::setVertices(std::vector<Vertex> vertices, GLenum primitive) {
    makeCurrent();
    GLObject *theObject = new GLObject(vertices, primitive);
    testingObjects.push_back(theObject);
    doneCurrent();
}
</code>```

In the constructor I generate the VBO:

```<code>GLObject::GLObject(std::vector<Vertex> vertices, GLenum primitiveType){
    this->vertices = vertices;
    this->primitiveType = primitiveType;

    vbo.create();
    vbo.bind();
    vbo.setUsagePattern(QOpenGLBuffer::StaticDraw);
    vbo.allocate(vertices.data(), vertices.size() * sizeof(Vertex));
    vbo.release();
}
</code>```

About the VAO and Shader program, I generate them when I'm going to paint the GLObject:

```<code>void GLObject::draw(QOpenGLContext* context, const QMatrix4x4& view, const QMatrix4x4& proj){
    if (!shaderProgram.contains(context))
        setupShader(context);

    if (!shaderProgram[context]->isLinked())
        shaderProgram[context]->link();

    shaderProgram[context]->bind();
    {
        shaderProgram[context]->setUniformValue(uniformWorldToCamera, view);
        shaderProgram[context]->setUniformValue(uniformCameraToView, proj);

        //If vao does not exists, create it.
        if (!this->vao.contains(context))
            setupVAO(context);

        QOpenGLVertexArrayObject *vao = this->vao[context];
        vao->bind();

        shaderProgram[context]->setUniformValue(uniformModelToWorld, transform.toMatrix());
        glDrawArrays(primitiveType, 0, vertices.size());

        vao->release();
    }
    shaderProgram[context]->release();
}
</code>```

Each GLObject contains, using QMap, multiple shaderPrograms and VAO, one per context:

```<code>class GLObject
{
public:

    ...

private:

    ...

    QMap<QOpenGLContext*, QOpenGLVertexArrayObject*> vao; //VAO cannot be shared, for this reason I will create a VAO per Widget (represent by QUuid)
    QMap<QOpenGLContext*, QOpenGLShaderProgram*> shaderProgram;

    //Private helpers
    void setupVAO(QOpenGLContext* context);
    void setupShader(QOpenGLContext* context);
};
</code>```

Finally, the QOpenGLWidgets have a std::vector that it is copy in the different Widgets.

答:
Qt::AA_ShareOpenGLContexts works perfectly, I get it to work with this attribute. I have two main problem:

First, you have to know that the context is generated when QOpenGLWidgets will paint for the first time. It is very important because VBO must be created in a shared context. So do a QOpenGLWidget::show() first and then generate the VBO.

Second problem was regarding state management, I was binding the QOpenGLVertexArrayObject and enabling the attribute array and setting the attribute buffer of QOpenGLShaderProgram but to do this you must to binding the VBO too... I was not doing it.

Finally, I generate a shader program and VAO per context.

Thanks.

Body:
I am trying to renderer the same scene in two different QOpenGLWindows. I don't want to duplicate memory, for this reason I am trying to use the share context but I'm not sure how it works.

I'm using the attribute Qt::AA_ShareOpenGLContexts because the documentation says that It makes that every shader context will be shared between them.

However, I'm generating the VBO in one context and generating a VAO and Shader Program in each context (because it cannot be shared) but the second widget does not paint anything.

I suppose that my problem arises because the VBO is not shared between contexts. Qt::AA_ShareOpenGLContexts is not enough? Maybe I have to use QOpenGLContext::globalShareContext(), how could I use it?

The following text explains what I am doing...

Whit the following method, I generate the Object which contains the information about the object thaat I want to paint in the scene:

void AEOpenGLViewer::setVertices(std::vector<Vertex> vertices, GLenum primitive) {
    makeCurrent();
    GLObject *theObject = new GLObject(vertices, primitive);
    testingObjects.push_back(theObject);
    doneCurrent();
}

In the constructor I generate the VBO:

GLObject::GLObject(std::vector<Vertex> vertices, GLenum primitiveType){
    this->vertices = vertices;
    this->primitiveType = primitiveType;

    vbo.create();
    vbo.bind();
    vbo.setUsagePattern(QOpenGLBuffer::StaticDraw);
    vbo.allocate(vertices.data(), vertices.size() * sizeof(Vertex));
    vbo.release();
}

About the VAO and Shader program, I generate them when I'm going to paint the GLObject:

void GLObject::draw(QOpenGLContext* context, const QMatrix4x4& view, const QMatrix4x4& proj){
    if (!shaderProgram.contains(context))
        setupShader(context);

    if (!shaderProgram[context]->isLinked())
        shaderProgram[context]->link();

    shaderProgram[context]->bind();
    {
        shaderProgram[context]->setUniformValue(uniformWorldToCamera, view);
        shaderProgram[context]->setUniformValue(uniformCameraToView, proj);

        //If vao does not exists, create it.
        if (!this->vao.contains(context))
            setupVAO(context);

        QOpenGLVertexArrayObject *vao = this->vao[context];
        vao->bind();

        shaderProgram[context]->setUniformValue(uniformModelToWorld, transform.toMatrix());
        glDrawArrays(primitiveType, 0, vertices.size());

        vao->release();
    }
    shaderProgram[context]->release();
}

Each GLObject contains, using QMap, multiple shaderPrograms and VAO, one per context:

class GLObject
{
public:

    ...

private:

    ...

    QMap<QOpenGLContext*, QOpenGLVertexArrayObject*> vao; //VAO cannot be shared, for this reason I will create a VAO per Widget (represent by QUuid)
    QMap<QOpenGLContext*, QOpenGLShaderProgram*> shaderProgram;

    //Private helpers
    void setupVAO(QOpenGLContext* context);
    void setupShader(QOpenGLContext* context);
};

Finally, the QOpenGLWidgets have a std::vector that it is copy in the different Widgets.


问:
df.sqlContext.sql() not recognizing DB table
I have below code running in spark env::

```<code>import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import org.apache.spark.sql.SQLContext
import sqlContext.implicits._
import java.util.Properties

val conf = new SparkConf().setAppName("test").setMaster("local").set("spark.driver.allowMultipleContexts", "true");
val sc = new SparkContext(conf)
val sqlContext = new SQLContext(sc)
val df = sqlContext.read.format("jdbc").option("url","jdbc:sqlserver://server_IP:port").option("databaseName","DB_name").option("driver","com.microsoft.sqlserver.jdbc.SQLServerDriver").option("dbtable","tbl").option("user","uid").option("password","pwd").load()

val df2 = df.sqlContext.sql("SELECT col1,col2 FROM tbl LIMIT 5")
exit()
</code>```

When I am trying to execute the above code, I get the error as "org.apache.spark.sql.AnalysisException: Table not found: tbl;", however, if I remove df2, and execute the code, I can see the content of the table tbl successfully. IS there anything am doing wrong? I am using spark 1.6.1, so I checked the documentation, the syntax to fire the sql query through sqlcontext is rightly placed by me "https://spark.apache.org/docs/1.6.0/sql-programming-guide.html", please refer "Running SQL Queries Programmatically" topic.

Following are the only trace from the full trace error ::

```<code>conf: org.apache.spark.SparkConf = org.apache.spark.SparkConf@5eea8854
sc: org.apache.spark.SparkContext = org.apache.spark.SparkContext@7790a6fb
sqlContext: org.apache.spark.sql.SQLContext = org.apache.spark.sql.SQLContext@a9f4621
df: org.apache.spark.sql.DataFrame = [col1: int, col2: string, col3: string, col4: string, col5: string, col6: string, col7: string, col8: string, col9: timestamp, col10: timestamp, col11: string, col12: string]
org.apache.spark.sql.AnalysisException: Table not found: tbl;
</code>```

答:
the df in your code is a DataFrame.

If you want to do any select operations do like df.select().

If you want to execute query by using sqlcontext.sql() you have first register the dataframe as temporary table with df.registerTempTable(tableName: String).

Body:
I have below code running in spark env::

import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import org.apache.spark.sql.SQLContext
import sqlContext.implicits._
import java.util.Properties

val conf = new SparkConf().setAppName("test").setMaster("local").set("spark.driver.allowMultipleContexts", "true");
val sc = new SparkContext(conf)
val sqlContext = new SQLContext(sc)
val df = sqlContext.read.format("jdbc").option("url","jdbc:sqlserver://server_IP:port").option("databaseName","DB_name").option("driver","com.microsoft.sqlserver.jdbc.SQLServerDriver").option("dbtable","tbl").option("user","uid").option("password","pwd").load()

val df2 = df.sqlContext.sql("SELECT col1,col2 FROM tbl LIMIT 5")
exit()

When I am trying to execute the above code, I get the error as "org.apache.spark.sql.AnalysisException: Table not found: tbl;", however, if I remove df2, and execute the code, I can see the content of the table tbl successfully. IS there anything am doing wrong? I am using spark 1.6.1, so I checked the documentation, the syntax to fire the sql query through sqlcontext is rightly placed by me "https://spark.apache.org/docs/1.6.0/sql-programming-guide.html", please refer "Running SQL Queries Programmatically" topic.

Following are the only trace from the full trace error ::

conf: org.apache.spark.SparkConf = org.apache.spark.SparkConf@5eea8854
sc: org.apache.spark.SparkContext = org.apache.spark.SparkContext@7790a6fb
sqlContext: org.apache.spark.sql.SQLContext = org.apache.spark.sql.SQLContext@a9f4621
df: org.apache.spark.sql.DataFrame = [col1: int, col2: string, col3: string, col4: string, col5: string, col6: string, col7: string, col8: string, col9: timestamp, col10: timestamp, col11: string, col12: string]
org.apache.spark.sql.AnalysisException: Table not found: tbl;


问:
How to create awk regex to match only one "space" between two words?
I have a sentence of form 2016-23-12 90-34-23 want to create an awk script to match it.

a.awk

```<code>$1 ~ /^[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}[[:space:]][[:digit:]]{2}-[[:digit:]]{2}-[[:digit:]]{2}/{
  ts = $1 " " $2
  print
}
</code>```

Run using:

```<code>awk -f a.awk --posix

2016-23-12 90-34-23
</code>```

Output:

Nothing

Body:
I have a sentence of form 2016-23-12 90-34-23 want to create an awk script to match it.

a.awk

$1 ~ /^[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}[[:space:]][[:digit:]]{2}-[[:digit:]]{2}-[[:digit:]]{2}/{
  ts = $1 " " $2
  print
}

Run using:

awk -f a.awk --posix

2016-23-12 90-34-23

Output:

Nothing

Body:
Try this -

$echo "2016-23-12 90-34-23"  | awk '{if($0 ~ /^[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}[[:space:]][[:digit:]]{2}-[[:digit:]]{2}-[[:digit:]]{2}$/) {print $0}}'
2016-23-12 90-34-23

$echo "2016-23-121 190-34-23"  | awk '{if($0 ~ /^[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}[[:space:]][[:digit:]]{2}-[[:digit:]]{2}-[[:digit:]]{2}$/) {print $0}}'
   ##### No result


问:
Opencart if product available Button show else disable that button
Hi i'm creating a application using Opencart. It fully customized, i have doubt in this.

I have filter.tpl page, in this page i need to display and hide button based on product availability
Eg:
If product available show like this
enter image description here

else button show like this enter image description here

Am trying this fowling code using ajax

filter.tpl

```<code>$('input[name=\'filter_name\']').autocomplete({
'source': function(request, response) {
    $.ajax({
        url: 'index.php?route=catalog/product/getProductCheck' +  encodeURIComponent(request),
        dataType: 'json',
        success: function(json) {
            response($.map(json, function(item) {
                return {
                    label: item['name'],
                    value: item['product_id']
                }
            }));
        }
    });
},
'select': function(item) {
    $('input[name=\'filter_name\']').val(item['label']);
}
</code>```

});

In controller
product.php

```<code>public function getProductCheck()
{
        /*Some code here*/
}
</code>```

答:
I got the out put am using javascript following code

```<code><div class="form-group">
    <div style='display:none;' id='instock'>
        <a class='instock-btn'>Product / Solution Available</a>
            <input type='submit' class='btn-orng available' name='' value="Click here for more details" size='20' />
    </div>
    <div style='display:none;' id="outstock">
        <input type='submit' class='outstock-btn' name='' value="Product / Solution Not Available" size='20' />
        <input type='submit' class='btn-orng' name='' value="We will contact you at the earliest" size='20' />
    </div>
</div>
</code>```

script

```<code>$(document).ready(function(){
    $('#dia1').on('change', function() {
        //var value =
      if (this.value <='320' )
      {
        $("#instock").show();
        $("#outstock").hide();
      }
      else
      {
        $("#instock").hide();
        $("#outstock").show();
      }
    });
     $('#len1').on('change', function() {
        //var value =
      if (this.value <='310' )
      {
        $("#instock").show();
        $("#outstock").hide();
      }
      else
      {
        $("#instock").hide();
        $("#outstock").show();
      }
    });
});
</code>```

Body:
Hi i'm creating a application using Opencart. It fully customized, i have doubt in this.

I have filter.tpl page, in this page i need to display and hide button based on product availability
Eg:
If product available show like this
enter image description here

else button show like this enter image description here

Am trying this fowling code using ajax

filter.tpl

$('input[name=\'filter_name\']').autocomplete({
'source': function(request, response) {
    $.ajax({
        url: 'index.php?route=catalog/product/getProductCheck' +  encodeURIComponent(request),
        dataType: 'json',
        success: function(json) {
            response($.map(json, function(item) {
                return {
                    label: item['name'],
                    value: item['product_id']
                }
            }));
        }
    });
},
'select': function(item) {
    $('input[name=\'filter_name\']').val(item['label']);
}

});

In controller
product.php

public function getProductCheck()
{
        /*Some code here*/
}

Body:
I got the out put am using javascript following code

<div class="form-group">
    <div style='display:none;' id='instock'>
        <a class='instock-btn'>Product / Solution Available</a>
            <input type='submit' class='btn-orng available' name='' value="Click here for more details" size='20' />
    </div>
    <div style='display:none;' id="outstock">
        <input type='submit' class='outstock-btn' name='' value="Product / Solution Not Available" size='20' />
        <input type='submit' class='btn-orng' name='' value="We will contact you at the earliest" size='20' />
    </div>
</div>

script

$(document).ready(function(){
    $('#dia1').on('change', function() {
        //var value =
      if (this.value <='320' )
      {
        $("#instock").show();
        $("#outstock").hide();
      }
      else
      {
        $("#instock").hide();
        $("#outstock").show();
      }
    });
     $('#len1').on('change', function() {
        //var value =
      if (this.value <='310' )
      {
        $("#instock").show();
        $("#outstock").hide();
      }
      else
      {
        $("#instock").hide();
        $("#outstock").show();
      }
    });
});


问:
JSON::JWS::VerificationFailed Exception
I am developing the Single Sign-on (SSO) feature for a system (using OpenID Connect with a Gluu server as the OP). Details of the system are listed as follows:

```<code>Programming Language:
Ruby on Rails

Ruby Gem of OpenID Connect:
omniauth-openid-connect (https://github.com/jjbohn/omniauth-openid-connect)

Authorization Endpoint:
/oxauth/seam/resource/restv1/oxauth/authorize

Token Endpoint:
/oxauth/seam/resource/restv1/oxauth/token
</code>```

However, the response (token) from the Gluu server causes a JSON::JWS::VerificationFailed exception at the system under development (raised by the Ruby Gem omniauth-openid-connect). Apparently, the default method of the Gluu server in signing the token is not compatible with the expectation of the Ruby Gem.

Anything I have missed (in the configuration of the Gluu server / in the settings of the Ruby Gem).

答: I just find the solution for my problem.  The setting "discovery" of the Gem must be turned on (by default, it is turned off).</p>

Title: JSON::JWS::VerificationFailed Exception

Body:
I am developing the Single Sign-on (SSO) feature for a system (using OpenID Connect with a Gluu server as the OP). Details of the system are listed as follows:

Programming Language:
Ruby on Rails

Ruby Gem of OpenID Connect:
omniauth-openid-connect (https://github.com/jjbohn/omniauth-openid-connect)

Authorization Endpoint:
/oxauth/seam/resource/restv1/oxauth/authorize

Token Endpoint:
/oxauth/seam/resource/restv1/oxauth/token

However, the response (token) from the Gluu server causes a JSON::JWS::VerificationFailed exception at the system under development (raised by the Ruby Gem omniauth-openid-connect). Apparently, the default method of the Gluu server in signing the token is not compatible with the expectation of the Ruby Gem.

Anything I have missed (in the configuration of the Gluu server / in the settings of the Ruby Gem).


问:
Can a PyQt Embedded MatPlotLib Graph Be Interactive?
I have a stacked bar plot of analytics data embedded in my GUI which I would like to be more interactive. When the user hovers or clicks on a bar the plotted value should appear. Can this be done? I haven't been able to find anything about it in the documentation. Alternatively I could use something like PyGal but I don't know how to embed it into PyQt. Advice on either would be appreciated.</p>

答:
To my best knowledge, not by default.

I fear, you have to work a bit for yourself, as I dont know a common widget for that. There are other QT designers which already offer more interactive plots, like:
http://www.taurus-scada.org/en/latest/devel/designer_tutorial.html
But, as far as I remember, it does not offer what you want. I would rather think about to create you own widget.


问:
Set the Version of a Secret When Setting the Secret in Azure KeyVault
It doesn't seem like it's possible currently to set the version of an Azure Key Vault secret when uploading the secret. I'm using SetSecretAsync. Am I missing something? Even when attempting the operation from the Azure Portal, you aren't given the opportunity to set the version, nor is there a way to back up or restore a secret.

It seems like this is intentional (given the seeming lack of methods to do it), but consider the background of why I'm doing this. We're concerned with a secret being deleted by mistake or even the vault itself being deleted by mistake. As we're using the secrets for encryption/decryption purposes, if the secrets or vault were to be deleted, we would have an issue... So we are planning to back up the secrets to blob storage in the event we do need to restore them. With keys in the vault, a simple way to do this type of operation is available, but it doesn't seem secrets were given this same treatment unfortunately.

答:
Based on operations performed directly from the portal while delete secret seems to be permanent, update (New Version option in portal, there is no update) on the other hand is merely adding a new version where as version cannot be explicitly mentioned but internally managed by KeyVault. Even in API Reference you can get all the versions of a single secret (see below). So update REST API might as well be just setting a new version and not actually overwriting. So as long as UPDATE is used and instead of delete probably set expiry through update we are covered.

https://learn.microsoft.com/en-us/rest/api/keyvault/getsecretversions


问:
ListBox duplicate check
I did post another question yesterday but I haven't had any further responses because there were two answers posted. Unfortunately none of them will work for me. Apologies if this is against the rules to repost a similar question.

I am trying to check a ListBox for duplicates when pressing a button. It should be adding the value of what's a ComboBox to the ListBox.

All the answers suggested using Linq queries, like this

```<code>myListBox.Items.Any(item=>((EnquiryListItem)item).Text == ComboBox1.SelectedText.ToString())
</code>```

or this

```<code>if (!myListBox.Items.Cast<String>().Any(item => item == ComboBox1.SelectedText.ToString())){
</code>```

However, my control doesn't have an entry for Any or Cast.

I tried using a foreach loop like the one below, but I get an error, object does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'object' could be found.

```<code>            foreach (var item in ListBox1.Items)
            {
               if (item.Text.Contains(Combobox1.SelectedText.ToString()))
               {
                   //select item in the ListBox
                   debugMsg("Duplicate","");
                   break;
               } else {
                ListBox1.Items.Add(Combobox1.SelectedItem); }
            }
</code>```

Is there any other method I can use? I've searched both SO and the internet in general but come across the same suggestions each time - almost always using Linq, which apparently won't work for my vendor specific SDK windows form application. They have documented their ListBox control and suggest that it inherits the .NET control but only supply code to add/remove items, with no duplicate checking.

答:
Used the foreach loop without Text, as suggested by EpicKip

```<code>            if ( ListBox1.Items.Contains( ComboBox1.SelectedItem ) )
            {
                debugMsg( "duplicate", "" );
            }
            else
            {
                ListBox1.Items.Add( ComboBox1.SelectedItem );
            }
</code>```

Title: ListBox duplicate check

Body:
I did post another question yesterday but I haven't had any further responses because there were two answers posted. Unfortunately none of them will work for me. Apologies if this is against the rules to repost a similar question.

I am trying to check a ListBox for duplicates when pressing a button. It should be adding the value of what's a ComboBox to the ListBox.

All the answers suggested using Linq queries, like this

myListBox.Items.Any(item=>((EnquiryListItem)item).Text == ComboBox1.SelectedText.ToString())

or this

if (!myListBox.Items.Cast<String>().Any(item => item == ComboBox1.SelectedText.ToString())){

However, my control doesn't have an entry for Any or Cast.

I tried using a foreach loop like the one below, but I get an error, object does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'object' could be found.

            foreach (var item in ListBox1.Items)
            {
               if (item.Text.Contains(Combobox1.SelectedText.ToString()))
               {
                   //select item in the ListBox
                   debugMsg("Duplicate","");
                   break;
               } else {
                ListBox1.Items.Add(Combobox1.SelectedItem); }
            }

Is there any other method I can use? I've searched both SO and the internet in general but come across the same suggestions each time - almost always using Linq, which apparently won't work for my vendor specific SDK windows form application. They have documented their ListBox control and suggest that it inherits the .NET control but only supply code to add/remove items, with no duplicate checking.

Body:
Used the foreach loop without Text, as suggested by EpicKip

            if ( ListBox1.Items.Contains( ComboBox1.SelectedItem ) )
            {
                debugMsg( "duplicate", "" );
            }
            else
            {
                ListBox1.Items.Add( ComboBox1.SelectedItem );
            }


问:
I'm trying to load PDF(over 2MB) from a uri with barteksc Android Viewer, but it doesn't work
I started this from simple example and here's the code.

I tested several pdf documents from url but I could see only blank spaces on my mobile screeen.

Those pdf documents was opened in the browsers though...

so am I missing something?

please get me some advices...

thanks in advance!!

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    PDFView pdfView = (PDFView) findViewById(R.id.pdfView);
    pdfView.fromUri(Uri.parse("http://xxxxxx/xxx.pdf"))
            .enableSwipe(true)
            .enableDoubletap(true)
            .swipeVertical(false)
            .defaultPage(1)
            .showMinimap(false)
            .enableAnnotationRendering(false)
            .password(null)
            .showPageWithAnimation(true)
            .load();
}
</code>```

答:
The library cant load from Http, you need download file and load from local Uri.

And remember you need android.permission.WRITE_EXTERNAL_STORAGE for download and read file.

As per android official doc :

Android 6.0 Marshmallow introduced a new permissions model that lets
  apps request permissions from the user at runtime, rather than prior
  to installation. Apps that support the new model request permissions
  when the app actually requires the services or data protected by the
  services.

Body:
I started this from simple example and here's the code.

I tested several pdf documents from url but I could see only blank spaces on my mobile screeen.

Those pdf documents was opened in the browsers though...

so am I missing something?

please get me some advices...

thanks in advance!!

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

    PDFView pdfView = (PDFView) findViewById(R.id.pdfView);
    pdfView.fromUri(Uri.parse("http://xxxxxx/xxx.pdf"))
            .enableSwipe(true)
            .enableDoubletap(true)
            .swipeVertical(false)
            .defaultPage(1)
            .showMinimap(false)
            .enableAnnotationRendering(false)
            .password(null)
            .showPageWithAnimation(true)
            .load();
}


问:
modx ditto filtering
I have this line of code:
[[Ditto? &depth=3 &tpl=@FILEweb_assets/chunks/x/x.html &parents=3 &filter=template,7|endDate,[+now+],3]]

The above line displays all items which using template 7. Now I want to make a change so that it will display all items with template 7 and 10. What should I do??

thanks

答:
According to the documentation you can simply add another clause as follows</p>

```<code>[[Ditto? &depth=3 &tpl=@FILEweb_assets/chunks/x/x.html &parents=3 &filter=template,7|template,10|endDate,[+now+],3]]
</code>```

Title: modx ditto filtering

Body:
According to the documentation you can simply add another clause as follows

[[Ditto? &depth=3 &tpl=@FILEweb_assets/chunks/x/x.html &parents=3 &filter=template,7|template,10|endDate,[+now+],3]]


问:
Tika returning empty string
I am using Apache Tika 1.14 and pdf box 2.0.5. When I try to extract the content from a pdf document, it is returning empty string.

```<code>import java.io.File;
import java.io.IOException;

import org.apache.tika.Tika;
import org.apache.tika.exception.TikaException;

public class Test {
    public static void main(String args[]) throws IOException, TikaException{
        String filePath = "sample.pdf";

        Tika tika = new Tika();
        String content = tika.parseToString(new File(filePath));

        System.out.println(content);
    }
}
</code>```

Following are the maven dependencies I am using.

```<code><!-- https://mvnrepository.com/artifact/org.apache.tika/tika-core -->
    <dependency>
        <groupId>org.apache.tika</groupId>
        <artifactId>tika-core</artifactId>
        <version>1.14</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
    <dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>2.0.5</version>
    </dependency>
</code>```

答:
You need to add 'tika-parsers' library to your project. Add following dependency and retry.</p>

```<code><!-- https://mvnrepository.com/artifact/org.apache.tika/tika-parsers -->
<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-parsers</artifactId>
    <version>1.14</version>
</dependency>
</code>```

Title: Tika returning empty string

Body:
I am using Apache Tika 1.14 and pdf box 2.0.5. When I try to extract the content from a pdf document, it is returning empty string.

import java.io.File;
import java.io.IOException;

import org.apache.tika.Tika;
import org.apache.tika.exception.TikaException;

public class Test {
    public static void main(String args[]) throws IOException, TikaException{
        String filePath = "sample.pdf";

        Tika tika = new Tika();
        String content = tika.parseToString(new File(filePath));

        System.out.println(content);
    }
}

Following are the maven dependencies I am using.

    <dependency>
        <groupId>org.apache.tika</groupId>
        <artifactId>tika-core</artifactId>
        <version>1.14</version>
    </dependency>

    <dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>2.0.5</version>
    </dependency>

Body:
You need to add 'tika-parsers' library to your project. Add following dependency and retry.

<!-- https://mvnrepository.com/artifact/org.apache.tika/tika-parsers -->
<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-parsers</artifactId>
    <version>1.14</version>
</dependency>


问:
How to clone button between tabs C# Visual Studio 2015
Example

Hi! How can I clone a button on other tabs? I need the same button in many tabs, the same button with the same proprieties, same code, same events, same name, ect.

"Compress file" button is going to be the same in Tab1, Tab4, Tab6 and Tab8... is going to do the same thing in many tabs, therebefore I don't want to make a new button every time. I don't want to make 10000 buttons which do the same thing.

I need to clone many buttons, not just "compress file", that's why I can't just put "Compress file" outside the TabControl and make it invisible or visible.

I'm working on Visual Studio 2015 with C#.

答:
You may need just to add your button on front of your TabControl not on one of the tab pages, so it will be shown on all of your tab pages but if you have to change its location, you should change the location of the button programmatically each time you switch to other tab page. Also, if you don't need it to be shown on some of the tab pages then you should make it invisible on that tab page.
Anyway, I really don't like to do it this way, but I would rather to add all the buttons I need on each tab and connect all of them on the same events' handlers.

NOTE: if you could not add the button on front of your tab control, you can use view > Other Windows > Document Outline to change it.


问:
How to remove "JS chart by amCharts" text from amChart?
How can I remove the branding text from an amChart chart?

JS chart by amCharts

Is there a way to remove that text in the chart configuration?

Image of such a chart:

答:
amCharts employee here. The branding text/logo is on the free version of the library. As stated on the license terms:

Free license

Use anywhere you want as long as you don't mind a small amCharts attribution on charts

If you want to remove the text, you have to purchase a license. See the license FAQ for information on what license is appropriate for your use case. You can reach out to AmCharts support for further clarification on the license terms.

If you already have a license and are using amCharts v3, just download the files from the support site, upload them to your web server and use those instead of the files on the amCharts CDN. If you're using npm or just wish to use the CDN files with your license, contact amCharts for instructions on how to apply your license. Do note that support for amCharts v3 will end at the end of 2020, so you may want to consider migrating to v4 for any further support and fixes.

If you have a license and you are using amCharts v4, the instructions are available in your support account. You will need to create a support account if you don't already have one and attach your license (order ID and email used to purchase the license) to your account to view the instructions.

Finally, if you're still having trouble with applying your license, contact amCharts and provide your order details.

We don't provide instructions on how to hide credits on a public forum for obvious reasons.