问:
Speed up creation of mysql table (from select)
I've got a query that runs in about 1.6 seconds and returns 150Kish rows.  I have been building a memory engine based temp table from this query and this operation takes about 6.5 seconds.  I've sifted through lots of documentation on the mysql site as well as futzed with indexes on the temp table (hardly any difference at all when I have indexes vs not having them) trying to find some way for the table creation to be a bit better performing.  Does anybody have any suggestions with respect to config options that may speed up creating an in memory temp table (or non temp table)?  To clear up what exactly I'm looking for (I think) is some sort of table config options that may increase the speed of the creation.  I've gone through most of the ones listed on the mysql 5.7 site but nothing seems to change the time it takes to create the temp/standard table in memory.  </p>

```<code>CREATE TEMPORARY TABLE
IF NOT EXISTS myTempTable
(ugID INT,stID INT, INDEX st (`st`) )
ENGINE=MEMORY AS
select ugID, stID
from a_complex_query_that_runs_in_under_2_seconds_but_takes_6_to_write_to_a_temptable_with_150k_rows

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   PRIMARY <derived15> ALL NULL    NULL    NULL    NULL    559
1   PRIMARY creatorEntity   eq_ref  PRIMARY PRIMARY 4   creatorAssignment.OwnerObjectID 1   Using index
1   PRIMARY <derived2>  ALL NULL    NULL    NULL    NULL    152580  Using where; Using join buffer
15  DERIVED VMAssignment    ref AssociatedObjectID,AssociatedObject AssociatedObject    2       2902    Using where
2   DERIVED test_   range   AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObjectID  4   NULL    214 Using where; Using temporary; Using filesort
2   DERIVED cfv_    ref CustomFieldID,EntityID,CFEntity,CFValue,CFEntityValue   CustomFieldID   4   testCloud.test_.AssignmentValue 4232    Using where
2   DERIVED ent_    ref VMStoreID   VMStoreID   4   testCloud.cfv_.EntityID 1   Using index
3   UNION   test_   ref AssociatedObjectID,AssociatedObject AssociatedObject    2       2902    Using where; Using temporary; Using filesort
3   UNION   cfv_    ref CustomFieldID,EntityID,CFEntity,CFValue,CFEntityValue   CFValue 772 func,func   4   Using where
3   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.cfv_.EntityID 1   Using index
4   UNION   test_   const   PRIMARY PRIMARY 4       1   Using index
5   UNION   test_   index_merge AssociatedObjectID,AssociatedObject AssociatedObjectID,AssociatedObject 4,6 NULL    1   Using intersect(AssociatedObjectID,AssociatedObject); Using where; Using index; Using temporary; Using filesort
5   UNION   entity_ ref PRIMARY,ClassName   ClassName   2       23326   Using where
5   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
6   UNION   entity_ ref PRIMARY,ClassName   ClassName   2       23326   Using where; Using temporary; Using filesort
6   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
6   UNION   test_   ref AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssignmentValue 768 testCloud.entity_.State 1   Using where
7   UNION   entity_ ref PRIMARY,ClassName   ClassName   2       23326   Using where; Using temporary; Using filesort
7   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
7   UNION   test_   ref AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssignmentValue 768 testCloud.entity_.Zip   1   Using where
8   UNION   test_   range   AssociatedObjectID,AssociatedObject AssociatedObjectID  4   NULL    150 Using where; Using temporary; Using filesort
8   UNION   entity_ ref PRIMARY,ClassName,Address   Address 456 func,func   4   Using where
8   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
9   UNION   test_   range   AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObjectID  4   NULL    203 Using where; Using temporary; Using filesort
9   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.test_.AssignmentValue 1   Using where; Using index
10  UNION   test_   const   PRIMARY PRIMARY 4       1   Using index
11  UNION   test_   ref AssociatedObjectID,AssociatedObject AssociatedObjectID  4       1   Using where; Using temporary; Using filesort
11  UNION   entity_ ref PRIMARY,ClassName   ClassName   2       23326   Using where
11  UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
12  UNION   test_   ref AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObject    2       2902    Using where; Using temporary; Using filesort
12  UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.test_.AssignmentValue 1   Using where; Using index
13  UNION   test_   range   AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObjectID  4   NULL    239 Using where; Using temporary; Using filesort
13  UNION   list_stores ref VMListID,VMStoreID,VMStoreID_2,VMStoreID_3,VMStoreID_4,VMStoreID_5,VMStoreID_6,VMStoreID_7,VMStoreID_8,VMStoreID_9,VMStoreID_10,VMStoreID_11,VMStoreID_12,VMStoreID_13,VMStoreID_14,VMStoreID_15,VMStoreID_16   VMListID    4   testCloud.test_.AssignmentValue 318 Using where
13  UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.list_stores.VMStoreID 1   Using index
14  UNION   test_   range   AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObjectID  4   NULL    70  Using where; Using temporary; Using filesort
14  UNION   sto_    ref PRIMARY,RetailerID  RetailerID  4   testCloud.test_.AssignmentValue 63  Using where; Using index
14  UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.sto_.ID   1   Using index
NULL    UNION RESULT    <union2,3,4,5,6,7,8,9,10,11,12,13,14>   ALL NULL    NULL    NULL    NULL    NULL
</code>```

答: It is recommended to create the index after the table has been populated with your data. This will reduce your runtime. Theory behind this is that the index will be created as a whole in memory after the insert and will then be written to disk which is a lot faster than updating the index with every insert. The index will also have a perfect tree layout when created after the insert.</p>

Body:
I've got a query that runs in about 1.6 seconds and returns 150Kish rows.  I have been building a memory engine based temp table from this query and this operation takes about 6.5 seconds.  I've sifted through lots of documentation on the mysql site as well as futzed with indexes on the temp table (hardly any difference at all when I have indexes vs not having them) trying to find some way for the table creation to be a bit better performing.  Does anybody have any suggestions with respect to config options that may speed up creating an in memory temp table (or non temp table)?  To clear up what exactly I'm looking for (I think) is some sort of table config options that may increase the speed of the creation.  I've gone through most of the ones listed on the mysql 5.7 site but nothing seems to change the time it takes to create the temp/standard table in memory.

CREATE TEMPORARY TABLE
IF NOT EXISTS myTempTable
(ugID INT,stID INT, INDEX st (`st`) )
ENGINE=MEMORY AS
select ugID, stID
from a_complex_query_that_runs_in_under_2_seconds_but_takes_6_to_write_to_a_temptable_with_150k_rows

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   PRIMARY <derived15> ALL NULL    NULL    NULL    NULL    559
1   PRIMARY creatorEntity   eq_ref  PRIMARY PRIMARY 4   creatorAssignment.OwnerObjectID 1   Using index
1   PRIMARY <derived2>  ALL NULL    NULL    NULL    NULL    152580  Using where; Using join buffer
15  DERIVED VMAssignment    ref AssociatedObjectID,AssociatedObject AssociatedObject    2       2902    Using where
2   DERIVED test_   range   AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObjectID  4   NULL    214 Using where; Using temporary; Using filesort
2   DERIVED cfv_    ref CustomFieldID,EntityID,CFEntity,CFValue,CFEntityValue   CustomFieldID   4   testCloud.test_.AssignmentValue 4232    Using where
2   DERIVED ent_    ref VMStoreID   VMStoreID   4   testCloud.cfv_.EntityID 1   Using index
3   UNION   test_   ref AssociatedObjectID,AssociatedObject AssociatedObject    2       2902    Using where; Using temporary; Using filesort
3   UNION   cfv_    ref CustomFieldID,EntityID,CFEntity,CFValue,CFEntityValue   CFValue 772 func,func   4   Using where
3   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.cfv_.EntityID 1   Using index
4   UNION   test_   const   PRIMARY PRIMARY 4       1   Using index
5   UNION   test_   index_merge AssociatedObjectID,AssociatedObject AssociatedObjectID,AssociatedObject 4,6 NULL    1   Using intersect(AssociatedObjectID,AssociatedObject); Using where; Using index; Using temporary; Using filesort
5   UNION   entity_ ref PRIMARY,ClassName   ClassName   2       23326   Using where
5   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
6   UNION   entity_ ref PRIMARY,ClassName   ClassName   2       23326   Using where; Using temporary; Using filesort
6   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
6   UNION   test_   ref AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssignmentValue 768 testCloud.entity_.State 1   Using where
7   UNION   entity_ ref PRIMARY,ClassName   ClassName   2       23326   Using where; Using temporary; Using filesort
7   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
7   UNION   test_   ref AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssignmentValue 768 testCloud.entity_.Zip   1   Using where
8   UNION   test_   range   AssociatedObjectID,AssociatedObject AssociatedObjectID  4   NULL    150 Using where; Using temporary; Using filesort
8   UNION   entity_ ref PRIMARY,ClassName,Address   Address 456 func,func   4   Using where
8   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
9   UNION   test_   range   AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObjectID  4   NULL    203 Using where; Using temporary; Using filesort
9   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.test_.AssignmentValue 1   Using where; Using index
10  UNION   test_   const   PRIMARY PRIMARY 4       1   Using index
11  UNION   test_   ref AssociatedObjectID,AssociatedObject AssociatedObjectID  4       1   Using where; Using temporary; Using filesort
11  UNION   entity_ ref PRIMARY,ClassName   ClassName   2       23326   Using where
11  UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
12  UNION   test_   ref AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObject    2       2902    Using where; Using temporary; Using filesort
12  UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.test_.AssignmentValue 1   Using where; Using index
13  UNION   test_   range   AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObjectID  4   NULL    239 Using where; Using temporary; Using filesort
13  UNION   list_stores ref VMListID,VMStoreID,VMStoreID_2,VMStoreID_3,VMStoreID_4,VMStoreID_5,VMStoreID_6,VMStoreID_7,VMStoreID_8,VMStoreID_9,VMStoreID_10,VMStoreID_11,VMStoreID_12,VMStoreID_13,VMStoreID_14,VMStoreID_15,VMStoreID_16   VMListID    4   testCloud.test_.AssignmentValue 318 Using where
13  UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.list_stores.VMStoreID 1   Using index
14  UNION   test_   range   AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObjectID  4   NULL    70  Using where; Using temporary; Using filesort
14  UNION   sto_    ref PRIMARY,RetailerID  RetailerID  4   testCloud.test_.AssignmentValue 63  Using where; Using index
14  UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.sto_.ID   1   Using index
NULL    UNION RESULT    <union2,3,4,5,6,7,8,9,10,11,12,13,14>   ALL NULL    NULL    NULL    NULL    NULL


来源: stackexchange

问:
Problems: Sending and Receiving Data
I am trying to perform two processes using bean, my problem is that I can not find the way these processes are performed continuously. The first process is to send an object and the second process is the response of the object.

```<code>@Component
public class Proceso implements InitializingBean{
    private static final String XML_SCHEMA_LOCATION = "/proceso/model/schema/proceso.xsd";
    private Envio envio;
    private Respuesta respuesta;

    public void Proceso_envio(Proceso proceso, OutputStream outputstream) throws JAXBException{
      envio.marshal(proceso, outputstream);}

    public void Proceso_respuesta(InputStream inputstream) throws JAXBException, FileNotFoundException{
    Object obj = unmarshaller.unmarshal(inputStream);
    return (Proceso_respuesta) obj;}

    @Override
    public void afterPropertiesSet() throws Exception{
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(getClass().getResource(XML_SCHEMA_LOCATION));
        JAXBContext jc = JAXBContext.newInstance(Envio.class, Respuesta.class);

        this.marshaller = jc.createMarshaller();
        this.marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        this.marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.displayName());
        this.marshaller.setSchema(schema);

        this.unmarshaller = jc.createUnmarshaller();

        this.unmarshaller.setSchema(schema);
     }
</code>```

I imagine that with the code my question becomes clearer.

答:
try to add Syncronized to your methods

i had this trouble many times because the receiver was trying to read something that is not finished

More info in the javadoc: https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html

when you add this key word to the methods this will wait to the other until it insnt finished

ContentLicense: CC BY-SA 3.0

Title: Problems: Sending and Receiving Data

Body:
I am trying to perform two processes using bean, my problem is that I can not find the way these processes are performed continuously. The first process is to send an object and the second process is the response of the object.

@Component
public class Proceso implements InitializingBean{
    private static final String XML_SCHEMA_LOCATION = "/proceso/model/schema/proceso.xsd";
    private Envio envio;
    private Respuesta respuesta;

    public void Proceso_envio(Proceso proceso, OutputStream outputstream) throws JAXBException{
      envio.marshal(proceso, outputstream);}

    public void Proceso_respuesta(InputStream inputstream) throws JAXBException, FileNotFoundException{
    Object obj = unmarshaller.unmarshal(inputStream);
    return (Proceso_respuesta) obj;}

    @Override
    public void afterPropertiesSet() throws Exception{
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(getClass().getResource(XML_SCHEMA_LOCATION));
        JAXBContext jc = JAXBContext.newInstance(Envio.class, Respuesta.class);

        this.marshaller = jc.createMarshaller();
        this.marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        this.marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.displayName());
        this.marshaller.setSchema(schema);

        this.unmarshaller = jc.createUnmarshaller();

        this.unmarshaller.setSchema(schema);
     }

I imagine that with the code my question becomes clearer.


问:
Calling native APIs in Electron
In the documentation for Electron it states:

In web pages, calling native GUI related APIs is not allowed

I don't understand what is meant by "native GUI related APIs". If I create a web page in Electron and add jQuery and then manipulate some element on the page, this works. I don't have to call back to the main process to perform UI updates. Does "native GUI related APIs" refer to something much more lower level (such as some API that is not based on Javascript)?

答:
Native Gui API's refers to desktop API such as Menu and Tray

https://github.com/electron/electron/blob/master/docs/api/menu.md
https://electron.atom.io/docs/api/tray/

i.e. API's which allow you to interact with the Desktop Environment.

e.g You will not be able to create a Tray application using Web Pages

Title: Calling native APIs in Electron


问:
jQuery - Calculate sum of two numbers inside one td and display inside new td?
Hello Stackoverflowers,

I have this code:

```<code>    <table class="table">
        <tbody>
            <tr>
                <td><a href="#">New thing</a></td>
                <td>2017/06/04 08:00</td>
                <td><a href="#">One Thing</a><span>Another thing</span></td>
                <td class="random">R</td>
                <td><a href="#">12-11      </a></td>
            </tr>
            <tr>
                <td><a href="#">New thing</a></td>
                <td>2017/06/04 08:00</td>
                <td><a href="#">One Thing</a><span>Another thing</span></td>
                <td class="random">R</td>
                <td><a href="#">22-23      </a></td>
            </tr>
        </tbody>
    </table>
</code>```

In the result I want to use jQuery to get a sum of numbers inside last table TD and display it into new TD. Like in the following code:

```<code><table class="table">
    <tbody>
        <tr>
            <td><a href="#">New thing</a></td>
            <td>2017/06/04 08:00</td>
            <td><a href="#">One Thing</a><span>Another thing</span></td>
            <td class="random">R</td>
            <td><a href="#">12-11      </a></td>
            <td>[ 23 ]</td>
        </tr>
        <tr>
            <td><a href="#">New thing</a></td>
            <td>2017/06/04 08:00</td>
            <td><a href="#">One Thing</a><span>Another thing</span></td>
            <td class="random">R</td>
            <td><a href="#">22-23      </a></td>
            <td>[ 45 ]</td>
        </tr>
    </tbody>
</table>
</code>```

thank you in advance.

答:
```<code>$(document).ready(function(){
    var a=$('tr td:last-child');
    for(var i=0;i<a.length;i++){
var newElement = a[i].innerText.split('-').reduce(function(prev,curr){
return parseInt(prev) + parseInt(curr);
});

a[i].after("<td>"+newElement+"</td>");
}
});
</code>```

Body:
Hello Stackoverflowers,

I have this code:

                New thing
                2017/06/04 08:00
                One ThingAnother thing
                R
                12-11

                New thing
                2017/06/04 08:00
                One ThingAnother thing
                R
                22-23

In the result I want to use jQuery to get a sum of numbers inside last table TD and display it into new TD. Like in the following code:

            New thing
            2017/06/04 08:00
            One ThingAnother thing
            R
            12-11
            [ 23 ]

            New thing
            2017/06/04 08:00
            One ThingAnother thing
            R
            22-23
            [ 45 ]

thank you in advance.


问:
Polymer: prevent submitting form when input invalid
I have a component that encapsulate an paper-input as you can see in the following code:

```<code><dom-module id="my-p">
  <template>
    <div class="my-class>
        <paper-input
            type="number"
            value="{{value}}"
            name="{{name}}"
            error-message="Error"
            invalid="{{invalid}}"
            label="{{name}}"
            allowed-pattern="[0-9,]"
            required="{{required}}"></paper-input>
    </div>
  </template>

  <script>
    Polymer({
        is: 'my-p',
        properties: {
            name: String,
            value : {
                type: Number,
                notify : true
            },
            required : Boolean,
            invalid: {
              type: Boolean,
              value: false,
              notify: true
            },
        }
    });
  </script>
</dom-module>
</code>```

Besides, I have another component to add some previous component into a form:

```<code><dom-module id="my-form">
  <template>
    <h2>My test</h2>
    <form is="iron-form" id="form" method="get">
        <my-p name="my input 1" value="{{value1}}" invalid="{{!_m(value1, value2)}}" required="true"></my-p>
        <my-p name="my input 2" value="{{value2}}" invalid="{{!_m(value1, value2)}}"></my-p>

        <paper-input name="paper" type="number" label="paper" required="true"></paper-input>

        <button type="submit">Send</button>
        <paper-button raised id="btn" on-click="_send">Send</paper-button>
    </form>
  </template>

  <script>
    Polymer({
        is: 'my-form',
        _m(v1, v2) {
            var n1 = parseInt(v1);
            var n2 = parseInt(v2);
            var valid = n1 >= (n2 + 2);
            return valid;
        },_send() {
            console.log("ok2");
        }
    });
  </script>
</dom-module>
</code>```

required attribute works when I click on first submit button: form is not submitted if required inputs are empty.

The problem is when any input is invalid: form is submitted.

Can I prevent submitting form if there is any invalid input?

答:
Don't do it with button, instead call your own function where you manually check if is form valid and then manually submit form.

iron-form has validate function but i don't think ti will work here since you are using encapsulated paper-input. Fortunately, paper-input has submit function too, so you call this function on every single my-p element.

example:

```<code>   <form is="iron-form" id="form" method="get">
        <my-p name="my input 1" value="{{value1}}" required></my-p>

        <paper-input name="paper" type="number" label="paper" required="true"></paper-input>

        <paper-button raised on-tap="checkAndSendForm">Send</paper-button>
    </form>
</code>```

Then, inside JS, define function checkAndSendForm:

```<code>checkAndSendForm() {
  var validated = true;
  var inputs = this.querySelectorAll("my-p[required]"); // select all required inputs
  for(var i = 0; i < inputs.length; i++){ // iterate through all required inputs
    if(!inputs[i].validate()) {
      validated = false; // input validation failed and will stop submit
    }
  }

  if(validated) {
    this.$.form.submit(); // manually submit the form
  }
}
</code>```

Inside my-p element you have to define function validate which will just call another validate function on paper-input.

```<code>validate() {
  this.querySelector("paper-input").validate(); // validate paper-input
}
</code>```

And i would also suggest you to set reflectToAttribute on required property inside my-p element. But this is only because I used selector  querySelectorAll("my-p[required]");

```<code>required: {
  type: Boolean,
  reflectToAttribute: true
}
</code>```

Body:
I have a component that encapsulate an paper-input as you can see in the following code:

<dom-module id="my-p">
  <template>

        <paper-input
            type="number"
            value="{{value}}"
            name="{{name}}"
            error-message="Error"
            invalid="{{invalid}}"
            label="{{name}}"
            allowed-pattern="[0-9,]"
            required="{{required}}"></paper-input>

  </template>

</dom-module>

Besides, I have another component to add some previous component into a form:

<dom-module id="my-form">
  <template>

My test

    <form is="iron-form" id="form" method="get">
        <my-p name="my input 1" value="{{value1}}" invalid="{{!_m(value1, value2)}}" required="true"></my-p>
        <my-p name="my input 2" value="{{value2}}" invalid="{{!_m(value1, value2)}}"></my-p>

        <paper-input name="paper" type="number" label="paper" required="true"></paper-input>

        <button type="submit">Send</button>
        <paper-button raised id="btn" on-click="_send">Send</paper-button>
    </form>
  </template>

</dom-module>

required attribute works when I click on first submit button: form is not submitted if required inputs are empty.

The problem is when any input is invalid: form is submitted.

Can I prevent submitting form if there is any invalid input?

Body:
Don't do it with button, instead call your own function where you manually check if is form valid and then manually submit form.

iron-form has validate function but i don't think ti will work here since you are using encapsulated paper-input. Fortunately, paper-input has submit function too, so you call this function on every single my-p element.

example:

   <form is="iron-form" id="form" method="get">
        <my-p name="my input 1" value="{{value1}}" required></my-p>

        <paper-input name="paper" type="number" label="paper" required="true"></paper-input>

        <paper-button raised on-tap="checkAndSendForm">Send</paper-button>
    </form>

Then, inside JS, define function checkAndSendForm:

checkAndSendForm() {
  var validated = true;
  var inputs = this.querySelectorAll("my-p[required]"); // select all required inputs
  for(var i = 0; i < inputs.length; i++){ // iterate through all required inputs
    if(!inputs[i].validate()) {
      validated = false; // input validation failed and will stop submit
    }
  }

  if(validated) {
    this.$.form.submit(); // manually submit the form
  }
}

Inside my-p element you have to define function validate which will just call another validate function on paper-input.

validate() {
  this.querySelector("paper-input").validate(); // validate paper-input
}

And i would also suggest you to set reflectToAttribute on required property inside my-p element. But this is only because I used selector  querySelectorAll("my-p[required]");

required: {
  type: Boolean,
  reflectToAttribute: true
}


问:
Python should return more than 1 argument
Hello I'm beginner in python and I'm trying to execute this program to create an inverted index for a collection file:

```<code>import sys
import re
from porterStemmer import PorterStemmer
from collections import defaultdict
from array import array
import gc

porter=PorterStemmer()

class CreateIndex:

def __init__(self):
    self.index=defaultdict(list)    #the inverted index

def getStopwords(self):
    '''get stopwords from the stopwords file'''
    f=open(self.stopwordsFile, 'r')
    stopwords=[line.rstrip() for line in f]
    self.sw=dict.fromkeys(stopwords)
    f.close()

def getTerms(self, line):
    '''given a stream of text, get the terms from the text'''
    line=line.lower()
    line=re.sub(r'[^a-z0-9 ]',' ',line) #put spaces instead of non-alphanumeric characters
    line=line.split()
    line=[x for x in line if x not in self.sw]  #eliminate the stopwords
    line=[ porter.stem(word, 0, len(word)-1) for word in line]
    return line

def parseCollection(self):
    ''' returns the id, title and text of the next page in the collection '''
    doc=[]
    for line in self.collFile:
        if line=='</page>\n':
            break
        doc.append(line)

    curPage=''.join(doc)
    pageid=re.search('<id>(.*?)</id>', curPage, re.DOTALL)
    pagetitle=re.search('<title>(.*?)</title>', curPage, re.DOTALL)
    pagetext=re.search('<text>(.*?)</text>', curPage, re.DOTALL)

    if pageid==None or pagetitle==None or pagetext==None:
        return {}

    d={}
    d['id']=pageid.group(1)
    d['title']=pagetitle.group(1)
    d['text']=pagetext.group(1)

    return d

def writeIndexToFile(self):
    '''write the inverted index to the file'''
    f=open(self.indexFile, 'w')
    for term in self.index.iterkeys():
        postinglist=[]
        for p in self.index[term]:
            docID=p[0]
            positions=p[1]
            postinglist.append(':'.join([str(docID) ,','.join(map(str,positions))]))
        print >> f, ''.join((term,'|',';'.join(postinglist)))

    f.close()

def getParams(self):
    '''get the parameters stopwords file, collection file, and the output index file'''
    param=sys.argv
    self.stopwordsFile=param[0]
    self.collectionFile=param[1]
    self.indexFile=param[2]

def createIndex(self):
    '''main of the program, creates the index'''
    self.getParams()
    self.collFile=open(self.collectionFile,'r')
    self.getStopwords()

    #bug in python garbage collector!
    #appending to list becomes O(N) instead of O(1) as the size grows if gc is enabled.
    gc.disable()

    pagedict={}
    pagedict=self.parseCollection()
    #main loop creating the index
    while pagedict != {}:
        lines='\n'.join((pagedict['title'],pagedict['text']))
        pageid=int(pagedict['id'])
        terms=self.getTerms(lines)

        #build the index for the current page
        termdictPage={}
        for position, term in enumerate(terms):
            try:
                termdictPage[term][1].append(position)
            except:
                termdictPage[term]=[pageid, array('I',[position])]

        #merge the current page index with the main index
        for termpage, postingpage in termdictPage.iteritems():
            self.index[termpage].append(postingpage)

        pagedict=self.parseCollection()

    gc.enable()

    self.writeIndexToFile()

if __name__=="__main__":
c=CreateIndex()
c.createIndex()
</code>```

and it says that there is only 1 argument in the sys.argv...

how should the other arguments appear???

答:
In the getParams function, you can see that your code request 3 parameters.
When you call your program:

```<code>python your_program.py
# sys.argv[0] = 'your_program.py'
</code>```

It has 1 argument. So you need two more:

```<code>python your_program.py arg_1 arg_2
# sys.argv[0] = 'your_program.py'
# sys.argv[1] = 'arg_1'
# sys.argv[2] = 'arg_2
</code>```

Body:
Hello I'm beginner in python and I'm trying to execute this program to create an inverted index for a collection file:

import sys
import re
from porterStemmer import PorterStemmer
from collections import defaultdict
from array import array
import gc

porter=PorterStemmer()

class CreateIndex:

def __init__(self):
    self.index=defaultdict(list)    #the inverted index

def getStopwords(self):
    '''get stopwords from the stopwords file'''
    f=open(self.stopwordsFile, 'r')
    stopwords=[line.rstrip() for line in f]
    self.sw=dict.fromkeys(stopwords)
    f.close()

def getTerms(self, line):
    '''given a stream of text, get the terms from the text'''
    line=line.lower()
    line=re.sub(r'[^a-z0-9 ]',' ',line) #put spaces instead of non-alphanumeric characters
    line=line.split()
    line=[x for x in line if x not in self.sw]  #eliminate the stopwords
    line=[ porter.stem(word, 0, len(word)-1) for word in line]
    return line

def parseCollection(self):
    ''' returns the id, title and text of the next page in the collection '''
    doc=[]
    for line in self.collFile:
        if line=='</page>\n':
            break
        doc.append(line)

    curPage=''.join(doc)
    pageid=re.search('<id>(.*?)</id>', curPage, re.DOTALL)
    pagetitle=re.search('<title>(.*?)</title>', curPage, re.DOTALL)
    pagetext=re.search('<text>(.*?)</text>', curPage, re.DOTALL)

    if pageid==None or pagetitle==None or pagetext==None:
        return {}

    d={}
    d['id']=pageid.group(1)
    d['title']=pagetitle.group(1)
    d['text']=pagetext.group(1)

    return d

def writeIndexToFile(self):
    '''write the inverted index to the file'''
    f=open(self.indexFile, 'w')
    for term in self.index.iterkeys():
        postinglist=[]
        for p in self.index[term]:
            docID=p[0]
            positions=p[1]
            postinglist.append(':'.join([str(docID) ,','.join(map(str,positions))]))
        print >> f, ''.join((term,'|',';'.join(postinglist)))

    f.close()

def getParams(self):
    '''get the parameters stopwords file, collection file, and the output index file'''
    param=sys.argv
    self.stopwordsFile=param[0]
    self.collectionFile=param[1]
    self.indexFile=param[2]

def createIndex(self):
    '''main of the program, creates the index'''
    self.getParams()
    self.collFile=open(self.collectionFile,'r')
    self.getStopwords()

    #bug in python garbage collector!
    #appending to list becomes O(N) instead of O(1) as the size grows if gc is enabled.
    gc.disable()

    pagedict={}
    pagedict=self.parseCollection()
    #main loop creating the index
    while pagedict != {}:
        lines='\n'.join((pagedict['title'],pagedict['text']))
        pageid=int(pagedict['id'])
        terms=self.getTerms(lines)

        #build the index for the current page
        termdictPage={}
        for position, term in enumerate(terms):
            try:
                termdictPage[term][1].append(position)
            except:
                termdictPage[term]=[pageid, array('I',[position])]

        #merge the current page index with the main index
        for termpage, postingpage in termdictPage.iteritems():
            self.index[termpage].append(postingpage)

        pagedict=self.parseCollection()

    gc.enable()

    self.writeIndexToFile()

if __name__=="__main__":
c=CreateIndex()
c.createIndex()

and it says that there is only 1 argument in the sys.argv...

how should the other arguments appear???

Body:
In the getParams function, you can see that your code request 3 parameters.
When you call your program:

python your_program.py
# sys.argv[0] = 'your_program.py'

It has 1 argument. So you need two more:

python your_program.py arg_1 arg_2
# sys.argv[0] = 'your_program.py'
# sys.argv[1] = 'arg_1'
# sys.argv[2] = 'arg_2


问:
How do I add a LinearLayoutCompat view to an existing xml layout dynamically?
I have a database containing of Texts.My activity has a TextView at the top(this should be constantly intact throughout) and below that I have a RelativeLayout which will be my container. In my code, as soon as the activity (in which I will be inserting view dynamically) launches, I create a LinearLayoutCompact object and set some properties. Then I process the cursor to the table data and I create a TextView for each database element and add it to the LinearLayoutCompat object. Finally I try to add this object into the RelativeLayout container where the app crashes. I am using LayoutInflater and treating the RelativeLayout container as a ViewGroup (I found this way after doing some research). However, if I simply use setContentView on the LinearLayoutCompat object it works fine but also replaces that TextView I want to be present. Here are the files I think will be necessary :

veg_option.xml  (layout of my activity)

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView             <!-- The one I want intact throughout -->
        android:id="@+id/narrowText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Let's narrow down now !"
        android:textSize="20sp"
        android:textColor="@color/wineBrown"
        android:gravity="center"
        android:padding="10dp"
        android:layout_marginTop="30dp"
        android:elevation="4dp"/>
   <RelativeLayout               <!-- Trying to use this as container -->
        android:id="@+id/dataCont"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

    </RelativeLayout>

</LinearLayout>
</code>```

VegOptions.java   (The activity where all action is supposed to happen)

```<code>package com.techpappy.whattoeat;

/**
 * Created by Mehul on 31-05-2017.
 */

import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.AppCompatTextView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.util.ArrayList;

public class VegOptions extends AppCompatActivity{

    protected DBSource vegDBSource;
    private Cursor cursor;
    protected ArrayList<String> mTypes;
    LayoutInflater li = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = li.inflate(R.layout.veg_option, null);
    ViewGroup dataConPt = (ViewGroup) findViewById(R.id.dataCont);

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.veg_option);
        vegDBSource = new DBSource(VegOptions.this);
        disp();
    }

    private void disp()
    {
        vegDBSource.open();
        cursor = vegDBSource.getInfo();
        LinearLayoutCompat linearLayoutCompat = defaultPage(cursor);
       //setContentView(linearLayoutCompat);  Works fine but replaces all
        dataConPt.addView(linearLayoutCompat);
    }
//Here my LinearLayoutCompat object is prepared and returned
    public LinearLayoutCompat defaultPage(Cursor mCursor) {
        LinearLayoutCompat layout = new LinearLayoutCompat(this);
        LinearLayoutCompat.LayoutParams params = new LinearLayoutCompat.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT);
        layout.setLayoutParams(params);
        layout.setGravity(Gravity.CENTER);
        layout.setOrientation(LinearLayoutCompat.VERTICAL);
        mCursor.moveToFirst();  //Each iteration adds one TextView
        do {
            AppCompatTextView defaultText = new AppCompatTextView(this);
            defaultText.setText(mCursor.getString(mCursor.getColumnIndex(DataBaseHelper.COLUMN_TYPES)));
            defaultText.setTextAppearance(getApplicationContext(), R.style.TextFontMain);
            defaultText.setTextSize(30);
            defaultText.setPadding(0,30,0,30);
            final String temp = (String) defaultText.getText();
            defaultText.setGravity(Gravity.CENTER);
            defaultText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                     Toast.makeText(getApplicationContext(), temp, Toast.LENGTH_SHORT).show();
                }
            });
            layout.addView(defaultText);
            mCursor.moveToNext();
        }  while(mCursor.isAfterLast() == false);
        return layout;  //LinearLayoutCompat containing all Texts returned
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        vegDBSource.close();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }
}
</code>```

My previous questions have been downvoted but this time I have done a fair amount of research and found the correct way but I can't get it to work in my unique case

stacktrace

```<code>6-05 19:32:17.679 3450-3450/com.techpappy.whattoeat E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.techpappy.whattoeat, PID: 3450
                                                                       java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.techpappy.whattoeat/com.techpappy.whattoeat.VegOptions}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2567)
                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                           at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                           at android.os.Looper.loop(Looper.java:154)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                        Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                                                                           at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
                                                                           at com.techpappy.whattoeat.VegOptions.<init>(VegOptions.java:33)
                                                                           at java.lang.Class.newInstance(Native Method)
                                                                           at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2557)
                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                           at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                           at android.os.Looper.loop(Looper.java:154)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
</code>```

答: Simply initialized the LayoutInflator, View and the ViewGroup inside the onCreate() method and the problem was fixed. </p>

Body:
I have a database containing of Texts.My activity has a TextView at the top(this should be constantly intact throughout) and below that I have a RelativeLayout which will be my container. In my code, as soon as the activity (in which I will be inserting view dynamically) launches, I create a LinearLayoutCompact object and set some properties. Then I process the cursor to the table data and I create a TextView for each database element and add it to the LinearLayoutCompat object. Finally I try to add this object into the RelativeLayout container where the app crashes. I am using LayoutInflater and treating the RelativeLayout container as a ViewGroup (I found this way after doing some research). However, if I simply use setContentView on the LinearLayoutCompat object it works fine but also replaces that TextView I want to be present. Here are the files I think will be necessary :

veg_option.xml  (layout of my activity)

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/narrowText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Let's narrow down now !"
        android:textSize="20sp"
        android:textColor="@color/wineBrown"
        android:gravity="center"
        android:padding="10dp"
        android:layout_marginTop="30dp"
        android:elevation="4dp"/>
   <RelativeLayout
        android:id="@+id/dataCont"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

    </RelativeLayout>

</LinearLayout>

VegOptions.java   (The activity where all action is supposed to happen)

package com.techpappy.whattoeat;

/**
 * Created by Mehul on 31-05-2017.
 */

import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.AppCompatTextView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.util.ArrayList;

public class VegOptions extends AppCompatActivity{

    protected DBSource vegDBSource;
    private Cursor cursor;
    protected ArrayList<String> mTypes;
    LayoutInflater li = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = li.inflate(R.layout.veg_option, null);
    ViewGroup dataConPt = (ViewGroup) findViewById(R.id.dataCont);

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.veg_option);
        vegDBSource = new DBSource(VegOptions.this);
        disp();
    }

    private void disp()
    {
        vegDBSource.open();
        cursor = vegDBSource.getInfo();
        LinearLayoutCompat linearLayoutCompat = defaultPage(cursor);
       //setContentView(linearLayoutCompat);  Works fine but replaces all
        dataConPt.addView(linearLayoutCompat);
    }
//Here my LinearLayoutCompat object is prepared and returned
    public LinearLayoutCompat defaultPage(Cursor mCursor) {
        LinearLayoutCompat layout = new LinearLayoutCompat(this);
        LinearLayoutCompat.LayoutParams params = new LinearLayoutCompat.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT);
        layout.setLayoutParams(params);
        layout.setGravity(Gravity.CENTER);
        layout.setOrientation(LinearLayoutCompat.VERTICAL);
        mCursor.moveToFirst();  //Each iteration adds one TextView
        do {
            AppCompatTextView defaultText = new AppCompatTextView(this);
            defaultText.setText(mCursor.getString(mCursor.getColumnIndex(DataBaseHelper.COLUMN_TYPES)));
            defaultText.setTextAppearance(getApplicationContext(), R.style.TextFontMain);
            defaultText.setTextSize(30);
            defaultText.setPadding(0,30,0,30);
            final String temp = (String) defaultText.getText();
            defaultText.setGravity(Gravity.CENTER);
            defaultText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                     Toast.makeText(getApplicationContext(), temp, Toast.LENGTH_SHORT).show();
                }
            });
            layout.addView(defaultText);
            mCursor.moveToNext();
        }  while(mCursor.isAfterLast() == false);
        return layout;  //LinearLayoutCompat containing all Texts returned
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        vegDBSource.close();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }
}

My previous questions have been downvoted but this time I have done a fair amount of research and found the correct way but I can't get it to work in my unique case

stacktrace

6-05 19:32:17.679 3450-3450/com.techpappy.whattoeat E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.techpappy.whattoeat, PID: 3450
                                                                       java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.techpappy.whattoeat/com.techpappy.whattoeat.VegOptions}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2567)
                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                           at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                           at android.os.Looper.loop(Looper.java:154)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                        Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                                                                           at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
                                                                           at com.techpappy.whattoeat.VegOptions.<init>(VegOptions.java:33)
                                                                           at java.lang.Class.newInstance(Native Method)
                                                                           at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2557)
                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                           at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                           at android.os.Looper.loop(Looper.java:154)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                           at java.lang.reflect.Method.invoke(Native Method)


问:
CSS menu - stop child items from changing parent width
I have a two-level CSS menu. Both levels should be displayed horizontally.

I have this pretty much set up, but there are a few issues I can't figure out.

1) Can I stop the "Projects" link from gaining the same width as the below elements? ("Live" and "Work" combined)

2) Can I left-align "Live" and "Work" below "Projects" without messing up the above structure?

This is the end result I want to achieve:

3) Is this possible using inline-block elements instead of floats? Should I use those instead? Knowing the menu should be positioned absolute at the top right of the page.

JSFiddle: https://jsfiddle.net/v23xejtj

.menu-block--main      { position: absolute; top: 5%; right: 5%;

  // level 1
  ul                   { list-style-type: none; margin: 0; padding: 0;
    li                 { float: left; background-color: green; }
    li a               { display: block; color: #000; text-align: center;
      padding: 14px 16px; text-decoration: none; text-transform: uppercase; }
    li a:hover         { background-color: red; }
  }

  // level 2
  ul li ul             {
    li                 { float: left; }
  }

}
```

<pre class="lang-html prettyprint-override"><code><nav class="menu-block--main">
  <ul class="main-menu">
    <li class="menu-item"><a>Projects</a>
      <ul>
        <li class="menu-item"><a>Live</a></li>
        <li class="menu-item"><a>Work</a></li>
      </ul>
    </li>
    <li class="menu-item"><a>Activities</a></li>
    <li class="menu-item"><a>Team</a></li>
    <li class="menu-item"><a>Blog</a></li>
    <li class="menu-item"><a>Contact</a></li>
  </ul>
</nav>
</code>```

答:
Maybe you mean to make sub menu, i think like this:

```<code>.menu-block--main{
    ul.main-menu{
      background: #444;
      text-align: center;
      padding: 0;
      margin: 0;
      list-style: none;

      li{
        font-family: 'Oswald', sans-serif;
        font-size: 1.2em;
        line-height: 40px;
        text-align: left;

        a{
          text-decoration: none;
          color: #fff;
          display: block;
          padding-left: 15px;
          border-bottom: 1px solid #888;
          transition: .3s background-color;
          &:hover{
            background-color: #005f5f;
          }
          &:active{
            background-color: #aaa;
            color: #444;
            cursor: default;
          }
        }
      }
      li{
        font-size: .8em;
      }
    }
}
</code>```

... hopefully can help you

Body:
I have a two-level CSS menu. Both levels should be displayed horizontally.

I have this pretty much set up, but there are a few issues I can't figure out.

1) Can I stop the "Projects" link from gaining the same width as the below elements? ("Live" and "Work" combined)

2) Can I left-align "Live" and "Work" below "Projects" without messing up the above structure?

This is the end result I want to achieve:

3) Is this possible using inline-block elements instead of floats? Should I use those instead? Knowing the menu should be positioned absolute at the top right of the page.

JSFiddle: https://jsfiddle.net/v23xejtj

.menu-block--main      { position: absolute; top: 5%; right: 5%;

  // level 1
  ul                   { list-style-type: none; margin: 0; padding: 0;
    li                 { float: left; background-color: green; }
    li a               { display: block; color: #000; text-align: center;
      padding: 14px 16px; text-decoration: none; text-transform: uppercase; }
    li a:hover         { background-color: red; }
  }

  // level 2
  ul li ul             {
    li                 { float: left; }
  }

}

Projects

Live

Work

Activities

Team

Blog

Contact

Body:
Maybe you mean to make sub menu, i think like this:

.menu-block--main{
    ul.main-menu{
      background: #444;
      text-align: center;
      padding: 0;
      margin: 0;
      list-style: none;

      li{
        font-family: 'Oswald', sans-serif;
        font-size: 1.2em;
        line-height: 40px;
        text-align: left;

        a{
          text-decoration: none;
          color: #fff;
          display: block;
          padding-left: 15px;
          border-bottom: 1px solid #888;
          transition: .3s background-color;
          &:hover{
            background-color: #005f5f;
          }
          &:active{
            background-color: #aaa;
            color: #444;
            cursor: default;
          }
        }
      }
      li{
        font-size: .8em;
      }
    }
}

... hopefully can help you


问:
How to keep comments inside a view definition with PostgreSQL?
I need to keep the comments I add inside a SQL query when I create views from complex queries, in order to come back to views definition more easily. Within pgAdminIII, when I create a view and then consult the view definition, the comments are deleted and indentation completely revised... Is there a way to change this behaviour?

View creation:

```<code>CREATE OR REPLACE VIEW public.v_test AS

-- Count number of null lines within table 'test'
(SELECT * FROM public.test WHERE client IS NULL);
</code>```

View definition after creation, as displayed in pgAdminIII:

```<code>-- View: v_test

-- DROP VIEW v_test;

CREATE OR REPLACE VIEW v_test AS
 SELECT test.gid,
    test.client
   FROM test
  WHERE test.client IS NULL;

ALTER TABLE v_test
  OWNER TO postgres;
</code>```

Thanks for help!

答:
Postgres doesn't store a view definition as is, hence you cannot store comments this way. Use the comment command:

```<code>create view my_view as select 1;
comment on view my_view is 'It is my view';

select obj_description('my_view'::regclass);

 obj_description
-----------------
 It is my view
(1 row)
</code>```

You can see the comment in PgAdmin3:

```<code>-- View: public.my_view

-- DROP VIEW public.my_view;

CREATE OR REPLACE VIEW public.my_view AS
 SELECT 1;

ALTER TABLE public.my_view
  OWNER TO postgres;
COMMENT ON VIEW public.my_view
  IS 'it is my view';
</code>```

Body:
I need to keep the comments I add inside a SQL query when I create views from complex queries, in order to come back to views definition more easily. Within pgAdminIII, when I create a view and then consult the view definition, the comments are deleted and indentation completely revised... Is there a way to change this behaviour?

View creation:

CREATE OR REPLACE VIEW public.v_test AS

-- Count number of null lines within table 'test'
(SELECT * FROM public.test WHERE client IS NULL);

View definition after creation, as displayed in pgAdminIII:

-- View: v_test

-- DROP VIEW v_test;

CREATE OR REPLACE VIEW v_test AS
 SELECT test.gid,
    test.client
   FROM test
  WHERE test.client IS NULL;

ALTER TABLE v_test
  OWNER TO postgres;

Thanks for help!

Body:
Postgres doesn't store a view definition as is, hence you cannot store comments this way. Use the comment command:

create view my_view as select 1;
comment on view my_view is 'It is my view';

select obj_description('my_view'::regclass);

 obj_description
-----------------
 It is my view
(1 row)

You can see the comment in PgAdmin3:

-- View: public.my_view

-- DROP VIEW public.my_view;

CREATE OR REPLACE VIEW public.my_view AS
 SELECT 1;

ALTER TABLE public.my_view
  OWNER TO postgres;
COMMENT ON VIEW public.my_view
  IS 'it is my view';


问:
Recurse directory in squirrel
Is it possible to examine the contents of a directory in squirrel? I need a list of file names, including their paths, in a given directory and its subdirectories.

I'm writing a script for use in Code::Blocks, which uses squirrel as a scripting language. I've had a look at the squirrel standard library, but couldn't find any file related operations. It might also be possible to outsource this task to an external script (bash or whatever), but I'd prefer not to do that.

答:
Download tinydir form : https://github.com/cxong/tinydir

Add system api for squrriel:

```<code>static SQInteger _system_getfiles(HSQUIRRELVM v)
{
    const SQChar *dirPath;
    sq_getstring(v, 2, &dirPath);
    sq_newarray(v,0);

    printf("Get dir %s;\r\n", dirPath);
    tinydir_dir dir;
    tinydir_open(&dir, dirPath);

    while (dir.has_next)
    {
        tinydir_file file;
        tinydir_readfile(&dir, &file);

//        printf("%s\r\n", file.name);
//        if (file.is_dir)
//        {
//            printf("/");
//        }
//        printf("\n");

        if (!file.is_dir)
        {
            sq_pushstring(v, file.name, -1);
            sq_arrayappend(v, -2);
        }

        tinydir_next(&dir);
    }

    tinydir_close(&dir);

//    sq_newarray(v,0);
//    sq_pushstring(v, "test_001.c", -1);
//    sq_arrayappend(v, -2);
//    sq_pushstring(v, "test_002.c", -1);
//    sq_arrayappend(v, -2);
//    sq_pushstring(v, "test_003.c", -1);
//    sq_arrayappend(v, -2);

    return 1;
}
#define _DECL_FUNC(name,nparams,pmask) {_SC(#name),_system_##name,nparams,pmask}
static const SQRegFunction systemlib_funcs[]={
    _DECL_FUNC(getenv,2,_SC(".s")),
    _DECL_FUNC(system,2,_SC(".s")),
    _DECL_FUNC(clock,0,NULL),
    _DECL_FUNC(time,1,NULL),
    _DECL_FUNC(date,-1,_SC(".nn")),
    _DECL_FUNC(remove,2,_SC(".s")),
    _DECL_FUNC(rename,3,_SC(".ss")),
    _DECL_FUNC(getfiles,2,_SC(".s")),
    {NULL,(SQFUNCTION)0,0,NULL}
};
#undef _DECL_FUNC
</code>```

The test result:

```<code>sq>local files=getfiles("c:");foreach(file in files){print(file + "\r\n");}
Get dir c:;
devcon64.exe
espacePlugin.log
java14224.reg
MyProject.smp
ns_fp.ocx
pagefile.sys
ScanResult.log
test.log
test1.log
UpdateDocPermission.log
UpdateVMLog.txt
UserAgentData.log
UserData.log

sq>
</code>```

Title: Recurse directory in squirrel

Body:
Download tinydir form : https://github.com/cxong/tinydir

Add system api for squrriel:

static SQInteger _system_getfiles(HSQUIRRELVM v)
{
    const SQChar *dirPath;
    sq_getstring(v, 2, &dirPath);
    sq_newarray(v,0);

    printf("Get dir %s;\r\n", dirPath);
    tinydir_dir dir;
    tinydir_open(&dir, dirPath);

    while (dir.has_next)
    {
        tinydir_file file;
        tinydir_readfile(&dir, &file);

//        printf("%s\r\n", file.name);
//        if (file.is_dir)
//        {
//            printf("/");
//        }
//        printf("\n");

        if (!file.is_dir)
        {
            sq_pushstring(v, file.name, -1);
            sq_arrayappend(v, -2);
        }

        tinydir_next(&dir);
    }

    tinydir_close(&dir);

//    sq_newarray(v,0);
//    sq_pushstring(v, "test_001.c", -1);
//    sq_arrayappend(v, -2);
//    sq_pushstring(v, "test_002.c", -1);
//    sq_arrayappend(v, -2);
//    sq_pushstring(v, "test_003.c", -1);
//    sq_arrayappend(v, -2);

    return 1;
}
#define _DECL_FUNC(name,nparams,pmask) {_SC(#name),_system_##name,nparams,pmask}
static const SQRegFunction systemlib_funcs[]={
    _DECL_FUNC(getenv,2,_SC(".s")),
    _DECL_FUNC(system,2,_SC(".s")),
    _DECL_FUNC(clock,0,NULL),
    _DECL_FUNC(time,1,NULL),
    _DECL_FUNC(date,-1,_SC(".nn")),
    _DECL_FUNC(remove,2,_SC(".s")),
    _DECL_FUNC(rename,3,_SC(".ss")),
    _DECL_FUNC(getfiles,2,_SC(".s")),
    {NULL,(SQFUNCTION)0,0,NULL}
};
#undef _DECL_FUNC

The test result:

sq>local files=getfiles("c:");foreach(file in files){print(file + "\r\n");}
Get dir c:;
devcon64.exe
espacePlugin.log
java14224.reg
MyProject.smp
ns_fp.ocx
pagefile.sys
ScanResult.log
test.log
test1.log
UpdateDocPermission.log
UpdateVMLog.txt
UserAgentData.log
UserData.log

sq>


问:
Saving data with dynamic input name to database?
Allright, before that i'm a beginner in PHP.
So forgive me for this silly question.

Say that id_user '1' have 2 items, so it will create 2 input form for each item.

These are the input forms:

```<code><input value="0" type="text" name="store_<?php echo $id= "I got this value from id.item in database, in this case '5'" ?>" required="required">

<input value="0" type="text" name="take_<?php echo $id= "I got this value from id.item in database, in this case '5'" ?>" required="required">

<input value="0" type="text" name="store_<?php echo $id= "I got this value from id.item in database, in this case '6'" ?>" required="required">

<input value="0" type="text" name="take_<?php echo $id= "I got this value from id.item in database, in this case '6'" ?>" required="required">
</code>```

Note : value take_{id} and store_{id} are retrieved from table 'item' coloumn 'id_item' in database.

The user input these values :

```<code>*value 'store' for id_item 5 is 3
*value 'take' for id_item 5 is 2
*value 'store' for id_item 6 is 1
*value 'take' for id_item 6 is 1
</code>```

How do i save value 'store' and 'take' from user input to database with their associated id?
Considering 1 user can have multiple item.

This is table item.

```<code>    ->id_user (referencing id_user from user's table)
    ->id_item # this primary key
    ->Take
    ->Store
</code>```

So the final result will be like this:

```<code>id_user : 1
id_item : 5
Store : 3
Take : 2
</code>```

And like this

```<code>id_user : 1
id_item : 6
Store : 1
Take : 1
</code>```

I've been googled all day, and i think regex with pattern 'store_' and 'take_' should do it? or there is another way to accomplish this?

Thankyou :)

答:
Say you're generating your HTML <input ... /> fields from a PHP loop, something like:

```<code>foreach($dbResult as $item) {
    echo "<input type=\"text\" name=\"store[{$item->getId()}]\" />\n"
        . "<input type=\"text\" name=\"take[{$item->getId()}]\" />\n";
}
</code>```

Which should give you a $_POST array like this (using the user input values in your example):

```<code>Array
(
    [store] => Array
        (
            [5] => 3
            [6] => 1
        )

    [take] => Array
        (
            [5] => 2
            [6] => 1
        )

)
</code>```

Where the store and take array keys are the item ids.

You can then use the keys from either array to generate your loop and insert the data into your database (using PDO as an example - errors would need handling in a live environment):

```<code>if(!empty($_POST['store'])) {

    // we can use the keys from just the `store` array
    // as they'll be the same as those in the `take` array
    foreach(array_keys($_POST['store']) as $itemId) {

        $userId = $_SESSION['user_id']; // from the session for example...
        $storeValue = $_POST['store'][$itemId];
        $takeValue = $_POST['take'][$itemId];

        $qry = "INSERT INTO item(item.id_user, item.id_item, item.store, item.take) "
            . "VALUES(:user_id, :item_id, :store_value, :take_value)";

        $stmt = $db->prepare($qry);
        $stmt->bindParam(':user_id', $userId, PDO::PARAM_INT);
        $stmt->bindParam(':item_id', $itemId, PDO::PARAM_INT);
        $stmt->bindParam(':store_value', $storeValue, PDO::PARAM_INT);
        $stmt->bindParam(':take_value', $takeValue, PDO::PARAM_INT);
        $stmt->execute();
    }
}
</code>```

Body:
Allright, before that i'm a beginner in PHP.
So forgive me for this silly question.

Say that id_user '1' have 2 items, so it will create 2 input form for each item.

These are the input forms:

<input value="0" type="text" name="store_<?php echo $id= "I got this value from id.item in database, in this case '5'" ?>" required="required">

<input value="0" type="text" name="take_<?php echo $id= "I got this value from id.item in database, in this case '5'" ?>" required="required">

<input value="0" type="text" name="store_<?php echo $id= "I got this value from id.item in database, in this case '6'" ?>" required="required">

<input value="0" type="text" name="take_<?php echo $id= "I got this value from id.item in database, in this case '6'" ?>" required="required">

Note : value take_{id} and store_{id} are retrieved from table 'item' coloumn 'id_item' in database.

The user input these values :

*value 'store' for id_item 5 is 3
*value 'take' for id_item 5 is 2
*value 'store' for id_item 6 is 1
*value 'take' for id_item 6 is 1

How do i save value 'store' and 'take' from user input to database with their associated id?
Considering 1 user can have multiple item.

This is table item.

    ->id_user (referencing id_user from user's table)
    ->id_item # this primary key
    ->Take
    ->Store

So the final result will be like this:

id_user : 1
id_item : 5
Store : 3
Take : 2

And like this

id_user : 1
id_item : 6
Store : 1
Take : 1

I've been googled all day, and i think regex with pattern 'store_' and 'take_' should do it? or there is another way to accomplish this?

Thankyou :)

Body:
Say you're generating your HTML <input ... /> fields from a PHP loop, something like:

foreach($dbResult as $item) {
    echo "<input type=\"text\" name=\"store[{$item->getId()}]\" />\n"
        . "<input type=\"text\" name=\"take[{$item->getId()}]\" />\n";
}

Which should give you a $_POST array like this (using the user input values in your example):

Array
(
    [store] => Array
        (
            [5] => 3
            [6] => 1
        )

    [take] => Array
        (
            [5] => 2
            [6] => 1
        )

)

Where the store and take array keys are the item ids.

You can then use the keys from either array to generate your loop and insert the data into your database (using PDO as an example - errors would need handling in a live environment):

if(!empty($_POST['store'])) {

    // we can use the keys from just the `store` array
    // as they'll be the same as those in the `take` array
    foreach(array_keys($_POST['store']) as $itemId) {

        $userId = $_SESSION['user_id']; // from the session for example...
        $storeValue = $_POST['store'][$itemId];
        $takeValue = $_POST['take'][$itemId];

        $qry = "INSERT INTO item(item.id_user, item.id_item, item.store, item.take) "
            . "VALUES(:user_id, :item_id, :store_value, :take_value)";

        $stmt = $db->prepare($qry);
        $stmt->bindParam(':user_id', $userId, PDO::PARAM_INT);
        $stmt->bindParam(':item_id', $itemId, PDO::PARAM_INT);
        $stmt->bindParam(':store_value', $storeValue, PDO::PARAM_INT);
        $stmt->bindParam(':take_value', $takeValue, PDO::PARAM_INT);
        $stmt->execute();
    }
}


问:
Better way to structure/new keyword
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

```<code>boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();
</code>```

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

```<code>boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();
</code>```

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

答:
I think the problem with

```<code>if (condition1 && condition2 && ...)
</code>```

was simply that it could become hard to read and edit if there are lots of conditions, although you could always write it like this:

```<code>if ( condition1 &&
     condition2 &&
     condition3 ... )
    doStuff();
</code>```

How about you turn the loop into a function:

```<code>bool all()
{
    if (!condition1) return false;
    if (!condition2) return false;
    if (!condition3) return false;
    ....
    return true;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Better way to structure/new keyword

Body:
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

Body:
I think the problem with

if (condition1 && condition2 && ...)

was simply that it could become hard to read and edit if there are lots of conditions, although you could always write it like this:

if ( condition1 &&
     condition2 &&
     condition3 ... )
    doStuff();

How about you turn the loop into a function:

bool all()
{
    if (!condition1) return false;
    if (!condition2) return false;
    if (!condition3) return false;
    ....
    return true;
}


问:
"contains" method with Set does not work even after overriding the equals method
There is an entity :

```<code>@Entity
@Table(name = "menu")
public class Menu {

    @Id
    @SequenceGenerator(name="s_menu", sequenceName="s_menu", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="s_menu")
    @Column(name = "menu_id")
    private int id;

    @Column(name = "gmnu_code")
    private Integer groupeMenu;

    @Column(name = "menu_lib")
    private String lib;

    @Column(name = "menu_ordre")
    private Integer ordre;

    @Column(name = "menu_visible")
    private Integer visible;

    @Column(name = "menu_deleted")
    private Integer deleted;

    @Column(name = "menu_bouton")
    private Integer bouton;

    @Column(name = "menu_parent")
    private Integer parent;

    @Column(name = "menu_controlleur")
    private String controlleur;

    @Column(name = "menu_navigation")
    private String navigation;

    @Column(name = "menu_flag_trace")
    private Integer flag_trace;

    @Column(name = "menu_trace")
    private String trace;

    @ManyToMany(fetch = FetchType.EAGER, mappedBy = "menus")
    @JsonBackReference
    private Set<Role> roles = new HashSet<Role>();

    @Transient
    private int depth;

    @Transient
    private boolean affectedToARole;

    @Transient
    private Environment env;

    public Menu() {
        super();
    }

    public Menu(Integer gmnu_code, String menu_lib, Integer menu_ordre, Integer menu_visible, Integer menu_deleted, Integer menu_bouton, Integer menu_parent, String menu_controlleur, String menu_navigation, Integer menu_flag_trace, String menu_trace) {
        super();
        this.groupeMenu = gmnu_code;
        this.lib = menu_lib;
        this.ordre = menu_ordre;
        this.visible = menu_visible;
        this.deleted = menu_deleted;
        this.bouton = menu_bouton;
        this.parent = menu_parent;
        this.controlleur = menu_controlleur;
        this.navigation = menu_navigation;
        this.flag_trace = menu_flag_trace;
        this.trace = menu_trace;
    }

    public Menu(Integer gmnu_code, String menu_lib, Integer menu_ordre, Integer menu_visible, Integer menu_deleted, Integer menu_bouton, Integer menu_parent, String menu_controlleur, String menu_navigation, Integer menu_flag_trace, String menu_trace, Set<Role> roles) {
        super();
        this.groupeMenu = gmnu_code;
        this.lib = menu_lib;
        this.ordre = menu_ordre;
        this.visible = menu_visible;
        this.deleted = menu_deleted;
        this.bouton = menu_bouton;
        this.parent = menu_parent;
        this.controlleur = menu_controlleur;
        this.navigation = menu_navigation;
        this.flag_trace = menu_flag_trace;
        this.trace = menu_trace;
        this.roles = roles;
    }

    public int getId() {
        return id;
    }

    public void setId(int menu_id) {
        this.id = menu_id;
    }

    public Integer getGroupeMenu() {
        return groupeMenu;
    }

    public void setGroupeMenu(Integer gmnu_code) {
        this.groupeMenu = gmnu_code;
    }

    public String getLib() {
        if (this.env != null)
            return env.getProperty(lib.trim());
        return lib;
    }

    public void setLib(String menu_lib) {
        this.lib = menu_lib;
    }

    public Integer getOrdre() {
        return ordre;
    }

    public void setOrdre(Integer menu_ordre) {
        this.ordre = menu_ordre;
    }

    public Integer getVisible() {
        return visible;
    }

    public void setVisible(Integer menu_visible) {
        this.visible = menu_visible;
    }

    public Integer getDeleted() {
        return deleted;
    }

    public void setDeleted(Integer menu_deleted) {
        this.deleted = menu_deleted;
    }

    public Integer getBouton() {
        return bouton;
    }

    public void setBouton(Integer menu_bouton) {
        this.bouton = menu_bouton;
    }

    public Integer getParent() {
        return parent;
    }

    public void setParent(Integer menu_parent) {
        this.parent = menu_parent;
    }

    public String getControlleur() {
        return controlleur;
    }

    public void setControlleur(String menu_controlleur) {
        this.controlleur = menu_controlleur;
    }

    public String getNavigation() {
        try {
            if (this.env != null)
                return env.getProperty(navigation.trim());
            return navigation.trim();
        } catch (NullPointerException npe) {
            return " --- ";
        }
    }

    public void setNavigation(String menu_navigation) {
        this.navigation = menu_navigation;
    }

    public String getTrace() {
        if (this.env != null)
            return HtmlUtils.htmlUnescape(env.getProperty(trace));
        return trace;
    }

    public void setTrace(String menu_trace) {
        this.trace = HtmlUtils.htmlUnescape(menu_trace);
    }

    public Integer getFlag_trace() {
        return flag_trace;
    }

    public void setFlag_trace(Integer menu_flag_trace) {
        this.flag_trace = menu_flag_trace;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

    public void setEnv(Environment env) {
        this.env = env;
    }

    public int getDepth() {
        return depth;
    }

    public void setDepth(int depth) {
        this.depth = depth;
    }

    public boolean isAffectedToARole() {
        return affectedToARole;
    }

    public void setAffectedToARole(boolean affectedToARole) {
        this.affectedToARole = affectedToARole;
    }

    @Override
    public boolean equals(Object obj) { // pour pouvoir utiliser la méthode "contains" sur une liste de Menu

        if (this == null && obj == null)
            return true;

        if (this != null && obj != null && obj instanceof Menu)
            return id == ((Menu)obj).getId();

        return super.equals(obj);

    }

}
</code>```

I want to test if a Set of Menu's contains a particular Menu :

```<code>Set<Menu> affected_menus = roleDao.getListMenu(role_code); // gets all menus affected to a role_code

for (Menu menu : temp) {
    if (!affected_menus.isEmpty() && affected_menus.contains(menu))
        menu.setAffectedToARole(true);
    else
        menu.setAffectedToARole(false);
}
</code>```

At runtime all code goes to menu.setAffectedToARole(false);

So what is wrong ?

答:
you should also override hashCode() method

here some info: Why do I need to override the equals and hashCode methods in Java?

Body:
There is an entity :

@Entity
@Table(name = "menu")
public class Menu {

    @Id
    @SequenceGenerator(name="s_menu", sequenceName="s_menu", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="s_menu")
    @Column(name = "menu_id")
    private int id;

    @Column(name = "gmnu_code")
    private Integer groupeMenu;

    @Column(name = "menu_lib")
    private String lib;

    @Column(name = "menu_ordre")
    private Integer ordre;

    @Column(name = "menu_visible")
    private Integer visible;

    @Column(name = "menu_deleted")
    private Integer deleted;

    @Column(name = "menu_bouton")
    private Integer bouton;

    @Column(name = "menu_parent")
    private Integer parent;

    @Column(name = "menu_controlleur")
    private String controlleur;

    @Column(name = "menu_navigation")
    private String navigation;

    @Column(name = "menu_flag_trace")
    private Integer flag_trace;

    @Column(name = "menu_trace")
    private String trace;

    @ManyToMany(fetch = FetchType.EAGER, mappedBy = "menus")
    @JsonBackReference
    private Set<Role> roles = new HashSet<Role>();

    @Transient
    private int depth;

    @Transient
    private boolean affectedToARole;

    @Transient
    private Environment env;

    public Menu() {
        super();
    }

    public Menu(Integer gmnu_code, String menu_lib, Integer menu_ordre, Integer menu_visible, Integer menu_deleted, Integer menu_bouton, Integer menu_parent, String menu_controlleur, String menu_navigation, Integer menu_flag_trace, String menu_trace) {
        super();
        this.groupeMenu = gmnu_code;
        this.lib = menu_lib;
        this.ordre = menu_ordre;
        this.visible = menu_visible;
        this.deleted = menu_deleted;
        this.bouton = menu_bouton;
        this.parent = menu_parent;
        this.controlleur = menu_controlleur;
        this.navigation = menu_navigation;
        this.flag_trace = menu_flag_trace;
        this.trace = menu_trace;
    }

    public Menu(Integer gmnu_code, String menu_lib, Integer menu_ordre, Integer menu_visible, Integer menu_deleted, Integer menu_bouton, Integer menu_parent, String menu_controlleur, String menu_navigation, Integer menu_flag_trace, String menu_trace, Set<Role> roles) {
        super();
        this.groupeMenu = gmnu_code;
        this.lib = menu_lib;
        this.ordre = menu_ordre;
        this.visible = menu_visible;
        this.deleted = menu_deleted;
        this.bouton = menu_bouton;
        this.parent = menu_parent;
        this.controlleur = menu_controlleur;
        this.navigation = menu_navigation;
        this.flag_trace = menu_flag_trace;
        this.trace = menu_trace;
        this.roles = roles;
    }

    public int getId() {
        return id;
    }

    public void setId(int menu_id) {
        this.id = menu_id;
    }

    public Integer getGroupeMenu() {
        return groupeMenu;
    }

    public void setGroupeMenu(Integer gmnu_code) {
        this.groupeMenu = gmnu_code;
    }

    public String getLib() {
        if (this.env != null)
            return env.getProperty(lib.trim());
        return lib;
    }

    public void setLib(String menu_lib) {
        this.lib = menu_lib;
    }

    public Integer getOrdre() {
        return ordre;
    }

    public void setOrdre(Integer menu_ordre) {
        this.ordre = menu_ordre;
    }

    public Integer getVisible() {
        return visible;
    }

    public void setVisible(Integer menu_visible) {
        this.visible = menu_visible;
    }

    public Integer getDeleted() {
        return deleted;
    }

    public void setDeleted(Integer menu_deleted) {
        this.deleted = menu_deleted;
    }

    public Integer getBouton() {
        return bouton;
    }

    public void setBouton(Integer menu_bouton) {
        this.bouton = menu_bouton;
    }

    public Integer getParent() {
        return parent;
    }

    public void setParent(Integer menu_parent) {
        this.parent = menu_parent;
    }

    public String getControlleur() {
        return controlleur;
    }

    public void setControlleur(String menu_controlleur) {
        this.controlleur = menu_controlleur;
    }

    public String getNavigation() {
        try {
            if (this.env != null)
                return env.getProperty(navigation.trim());
            return navigation.trim();
        } catch (NullPointerException npe) {
            return " --- ";
        }
    }

    public void setNavigation(String menu_navigation) {
        this.navigation = menu_navigation;
    }

    public String getTrace() {
        if (this.env != null)
            return HtmlUtils.htmlUnescape(env.getProperty(trace));
        return trace;
    }

    public void setTrace(String menu_trace) {
        this.trace = HtmlUtils.htmlUnescape(menu_trace);
    }

    public Integer getFlag_trace() {
        return flag_trace;
    }

    public void setFlag_trace(Integer menu_flag_trace) {
        this.flag_trace = menu_flag_trace;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

    public void setEnv(Environment env) {
        this.env = env;
    }

    public int getDepth() {
        return depth;
    }

    public void setDepth(int depth) {
        this.depth = depth;
    }

    public boolean isAffectedToARole() {
        return affectedToARole;
    }

    public void setAffectedToARole(boolean affectedToARole) {
        this.affectedToARole = affectedToARole;
    }

    @Override
    public boolean equals(Object obj) { // pour pouvoir utiliser la méthode "contains" sur une liste de Menu

        if (this == null && obj == null)
            return true;

        if (this != null && obj != null && obj instanceof Menu)
            return id == ((Menu)obj).getId();

        return super.equals(obj);

    }

}

I want to test if a Set of Menu's contains a particular Menu :

Set<Menu> affected_menus = roleDao.getListMenu(role_code); // gets all menus affected to a role_code

for (Menu menu : temp) {
    if (!affected_menus.isEmpty() && affected_menus.contains(menu))
        menu.setAffectedToARole(true);
    else
        menu.setAffectedToARole(false);
}

At runtime all code goes to menu.setAffectedToARole(false);

So what is wrong ?


问:
onchange="" doesn't work in select tag
I have two tags of select. Their IDs is "study-phase" and "study-year".
I want when the value of study phase to process a CSS code.

HTML:

```<code><select name="study-phase" onchange="myFunction()" id="study-phase" class="sp-input">
    <option value=""></option>
    <option id="pri" value="pri">Primary</option>
    <option id="pre" value="pre">Prep</option>
    <option id="sec" value="sec">Secondary</option>
</select>
<select name="study-year" id="study-year" class="sp-input">
    <option value=""></option>
    <option id="a" value="aa">Grade 1</option>
    <option id="b" value="">Grade 2</option>
    <option id="c" value="">Grade 3</option>
    <option id="d" value="">Grade 4</option>
    <option id="e" value="">Grade 5</option>
    <option id="f" value="">Grade 6</option>
    <option id="g" value="">Grade 7</option>
    <option id="h" value="">Grade 8</option>
    <option id="i" value="">Grade 9</option>
    <option id="j" value="">Grade 10</option>
</select>
<style type="text/css">
    #a , #b , #c , #d , #f , #g , #h , #j , #k , #e , #i {
        display: none;
    }
</style>
</code>```

JS:

```<code>$(function(myFunction()){
   if (document.getElementById("study-phase").value == "pri") {
       document.getElementById("a").style.display = "block";
   }
});
</code>```

And after run the code the css code which I  want don't launch.
What's the problem here ?

答:
To done this jquery will be more efficient so you just need to do some thing like this:-

1.Remove onchange="myFunction()" form your select

2.Add this code on your script:-

```<code> $('#study-phase').on('change',function(){
 if ($(this).val() == "pri") {
    $("#a")css('display','block');
 }});
</code>```

It will work fine

Title: onchange="" doesn't work in select tag

Body:
I have two tags of select. Their IDs is "study-phase" and "study-year".
I want when the value of study phase to process a CSS code.

HTML:

<select name="study-phase" onchange="myFunction()" id="study-phase" class="sp-input">
    <option value=""></option>
    <option id="pri" value="pri">Primary</option>
    <option id="pre" value="pre">Prep</option>
    <option id="sec" value="sec">Secondary</option>
</select>
<select name="study-year" id="study-year" class="sp-input">
    <option value=""></option>
    <option id="a" value="aa">Grade 1</option>
    <option id="b" value="">Grade 2</option>
    <option id="c" value="">Grade 3</option>
    <option id="d" value="">Grade 4</option>
    <option id="e" value="">Grade 5</option>
    <option id="f" value="">Grade 6</option>
    <option id="g" value="">Grade 7</option>
    <option id="h" value="">Grade 8</option>
    <option id="i" value="">Grade 9</option>
    <option id="j" value="">Grade 10</option>
</select>

JS:

$(function(myFunction()){
   if (document.getElementById("study-phase").value == "pri") {
       document.getElementById("a").style.display = "block";
   }
});

And after run the code the css code which I  want don't launch.
What's the problem here ?

Body:
To done this jquery will be more efficient so you just need to do some thing like this:-

1.Remove onchange="myFunction()" form your select

2.Add this code on your script:-

 $('#study-phase').on('change',function(){
 if ($(this).val() == "pri") {
    $("#a")css('display','block');
 }});

It will work fine


问:
How to access AngularJS scope variable from template script using $window
I am able to successfully access the javascript variable in my AngularJs controller using the $window service, by learning from this answer how to access global js variables in angularjs directive.

Here is a code pen to demonstrate what I mean: https://codepen.io/anon/pen/lznxe

I want to achieve the opposite, that is accessing $window.variable in my template javascript.

I tried doing this. However, the alert box only shows the output:

Undefined

Template Javascript:

```<code><script>
   alert(window.globalVar);
</script>
</code>```

AngularJS Controller:

```<code> app.controller("myCtrl", function($scope,$http,$interval,$window){
     $window.globalVar="test";
 )};
</code>```

Here is a code pen to demonstrate the problem that I am describing: https://codepen.io/anon/pen/NgqNBa

How can I achieve what I want? The main goal is to access the $scope variable to be used in the Template Javascript. Thanks in advance.

答: It looks like the script in the

Body:
I am able to successfully access the javascript variable in my AngularJs controller using the $window service, by learning from this answer how to access global js variables in angularjs directive.

Here is a code pen to demonstrate what I mean: https://codepen.io/anon/pen/lznxe

I want to achieve the opposite, that is accessing $window.variable in my template javascript.

I tried doing this. However, the alert box only shows the output:

Undefined

Template Javascript:

AngularJS Controller:

 app.controller("myCtrl", function($scope,$http,$interval,$window){
     $window.globalVar="test";
 )};

Here is a code pen to demonstrate the problem that I am describing: https://codepen.io/anon/pen/NgqNBa

How can I achieve what I want? The main goal is to access the $scope variable to be used in the Template Javascript. Thanks in advance.

Body: It looks like the script in the <script> tags get executed too early. With a setTimeout of 1000 it seems to work. Try to add an onLoad on your <body> tag, so your script gets executed after the variable is defined.


问:
Long first time to plot with Gadfly
I created simple plotting example with Julia

```<code>using Gadfly
draw(SVG("example.svg", 10cm, 10cm),
  plot(x=rand(10), y=rand(10))
)
</code>```

And ran it as time julia example.jl it took it 27 sec to finish. Is it normal behaviour? Is it possible to speed it up?

Latest Julia 0.5.2 and Pkg.

答:
I'm not an expert so take this with a pinch of salt, but you're draw and SVG functions are compiled the first time they're run, that's why the long running time.
If you call the function again, it takes a lot less time. You're paying a penalty to compile the function calls first, but all later executions are quite quick.

I amended you're script to measure the time spent in different calls:

```<code>@time using Gadfly
@time draw(SVG("example.svg", 10cm, 10cm),
  plot(x=rand(10), y=rand(10))
)
@time draw(SVG("example2.svg", 10cm, 10cm),
  plot(x=rand(10), y=rand(10))
)
</code>```

Running this from the console with julia example.jl gives me the following:

```<code>$ julia example.jl
2.728577 seconds (3.32 M allocations: 141.186 MB, 10.29% gc time)
20.434172 seconds (27.48 M allocations: 1.109 GB, 1.95% gc time)
0.023084 seconds (32.59 k allocations: 1.444 MB)
</code>```

Title: Long first time to plot with Gadfly

Body:
I created simple plotting example with Julia

using Gadfly
draw(SVG("example.svg", 10cm, 10cm),
  plot(x=rand(10), y=rand(10))
)

And ran it as time julia example.jl it took it 27 sec to finish. Is it normal behaviour? Is it possible to speed it up?

Latest Julia 0.5.2 and Pkg.

Body:
I'm not an expert so take this with a pinch of salt, but you're draw and SVG functions are compiled the first time they're run, that's why the long running time.
If you call the function again, it takes a lot less time. You're paying a penalty to compile the function calls first, but all later executions are quite quick.

I amended you're script to measure the time spent in different calls:

@time using Gadfly
@time draw(SVG("example.svg", 10cm, 10cm),
  plot(x=rand(10), y=rand(10))
)
@time draw(SVG("example2.svg", 10cm, 10cm),
  plot(x=rand(10), y=rand(10))
)

Running this from the console with julia example.jl gives me the following:

$ julia example.jl
2.728577 seconds (3.32 M allocations: 141.186 MB, 10.29% gc time)
20.434172 seconds (27.48 M allocations: 1.109 GB, 1.95% gc time)
0.023084 seconds (32.59 k allocations: 1.444 MB)