问:
Is key-value pair available in Typescript?
Is key,value pair available in typescript? If yes how to do that. Can anyone provide sample example links.</p>

答:
Not for the questioner, but for all others, which are interested:
See: How to define Typescript Map of key value pair. where key is a number and value is an array of objects

The solution is therefore:

```<code>let yourVar: Map<YourKeyType, YourValueType>;
// now you can use it:
yourVar = new Map<YourKeyType, YourValueType>();
yourVar[YourKeyType] = <YourValueType> yourValue;
</code>```

Cheers!

Body:
Not for the questioner, but for all others, which are interested:
See: How to define Typescript Map of key value pair. where key is a number and value is an array of objects

The solution is therefore:

let yourVar: Map<YourKeyType, YourValueType>;
// now you can use it:
yourVar = new Map<YourKeyType, YourValueType>();
yourVar[YourKeyType] = <YourValueType> yourValue;

Cheers!


来源: stackexchange

问:
python insert into sql error
I'm getting an SQL error in the following python code when I try to insert some values collected in the python code into my database via SQL. I'm getting an SQL error on the code highlighted in BOLD. Any help appreciated!</p>

```<code>def add_ingredients(cursor) :
    while True:
      ingredient = raw_input("Name of ingredient (q to quit):")
      if ingredient.lower() !='q':
          num = raw_input("Number in storage: ")
          description = raw_input("description: ")
          sql = '''insert into ingredients
             (title, amount, description)
            values
             **(:title, :amount, :description)'''**
          cursor.execute(sql,
           {"title":ingredient, "amount":num, "description":description})
          print "Added!"
      else:
          print "Okay, quitting."
          break
</code>```

答:
MySQL Connector does not expect named parameters like that. As the documentation shows, you should use the %(var_name)s format for dictionary interpolation:

```<code> sql = '''insert into ingredients (title, amount, description)
          values (%(title)s, %(amount)s, %(description)s)'''
  cursor.execute(sql, {"title": ingredient, "amount": num, "description": description})
</code>```

ContentLicense: CC BY-SA 3.0

Title: python insert into sql error

Body:
I'm getting an SQL error in the following python code when I try to insert some values collected in the python code into my database via SQL. I'm getting an SQL error on the code highlighted in BOLD. Any help appreciated!

def add_ingredients(cursor) :
    while True:
      ingredient = raw_input("Name of ingredient (q to quit):")
      if ingredient.lower() !='q':
          num = raw_input("Number in storage: ")
          description = raw_input("description: ")
          sql = '''insert into ingredients
             (title, amount, description)
            values
             **(:title, :amount, :description)'''**
          cursor.execute(sql,
           {"title":ingredient, "amount":num, "description":description})
          print "Added!"
      else:
          print "Okay, quitting."
          break

Body:
MySQL Connector does not expect named parameters like that. As the documentation shows, you should use the %(var_name)s format for dictionary interpolation:

 sql = '''insert into ingredients (title, amount, description)
          values (%(title)s, %(amount)s, %(description)s)'''
  cursor.execute(sql, {"title": ingredient, "amount": num, "description": description})


问:
Write request and response data to file in jmeter
I have one testcase which contains 7 requests. I need to write both request (whole request which is passing along with dynamic values) and response data (whole response) to a file for all of them during run time. Please help me how can I do this in JMeter?</p>

答:
Use flexible file writer in the request. Give |requestData| and |responseData|
in "Record each sample as" field. Give the path where you want to save your data in Filename field. That's it.You will be able to see a file which contains the request and response data for the sampler request.Hope this helps!</p>


问:
php errors when logged out because of session user_id
I'm making a product details page, and on the product details page I'm having if functions to see if the $_SESSION user_id is the same as the $product user_id to echo something or not for example. When no user is logged in, I get alot of errors that it can't find the $session user_id. How can I solve this problem so when there is no user logged in it does the same as if the session user_id is wrong to the product user_id?

for example:

```<code><?php if ( $_SESSION['user_id'] != $product["user_id"]): ?>
 <h3>Email van de eigenaar:</h4>
<?php echo $userarray['email'];?>
       <?php endif; ?>
 </div>
</code>```

So if the session user_id is wrong to the product user_id i want the same thing to happen when there is no $_SESSION user_id found which is echoing this: <?php echo $userarray['email'];?>

This is my whole details page:

```<code><?php include_once ('templates/header.php'); ?>

<div class="all-content">
       <div class="row">
        <div class="col-lg-12 bg-warning" style="font-size:25px">

            <!-- Maak variables voor gele balkje ingelogt of niet -->
            <?php $overditcadeau = '<center>Over dit cadeau</center>'; ?>
            <?php $mijncadeau = '<center>Mijn cadeau</center>'; ?>

         <?php   if ($_SESSION['user_id'] != $product["user_id"]) {
    echo $overditcadeau;
 } else {
    echo $mijncadeau;
  } ?>

        </div>
        </div>
<div class="container">
    <br><br>

<?php    $userarray = $this->db->get_Where('users', array('user_id'=>$product["user_id"]))->row_array();  ?>

    <!-- Als het cadeau niet van de ingelogde gebruiker is laat email van de eigenaar van het cadeau zien -->
    <?php if ( $_SESSION['user_id'] != $product["user_id"]): ?>
 <h3>Email van de eigenaar:</h4>
<?php echo $userarray['email'];?>
       <?php endif; ?>
 </div>

<div class="container">
 <div class="row">

     <div class="overditcadeau" >
    <div class="overditcadeau_foto">
    <img src="<?php echo base_url(); ?>upload/<?php echo $product['product_foto']; ?>" id="cadeaufoto_overditcadeau">
</div>

<div class="overditcadeau_tekst1">
  <h1> <div class="product_naam"> <?php echo $product['product_naam']; ?>  </div> </h1>
   <h3>Over dit cadeau</h3>
     <div class="product_beschrijving"><?php echo $product['product_beschrijving']; ?> </div>
   </div>
   <div class="overditcadeau_tekst2">

       <!--Als het cadeau niet van de ingelogde gebruiker is laat een button zien dat heet cadeau aanvragen -->
       <div class="cadeau_aanvragen">
  <?php if ( $_SESSION['user_id'] != $product["user_id"]): ?>
     <a href="<?php echo base_url() ?>/Cadeau_ontvang"> <button type="button" class="btn btn-default">Ik wil dit cadeau!</button></a>

     <button onclick="myFunction()">Ik wil dit cadeau!</button>
<script>
function myFunction() {
    alert("Uw cadeau aanvraag is geaccepteerd, Klik hier om een bericht naar de eigenaar van het cadeau te sturen.");
}
</script>

<?php endif; ?>
</div>

<!--Als het cadeau van de ingelogde gebruiker is laat een button zien dat heet cadeau bewerken-->
<div class="cadeau_bewerken">
        <?php if ( $_SESSION['user_id'] ==  $product["user_id"]): ?>
    <a class="btn btn-primary" href="<?php echo base_url() ?>/KdGwController/details_bewerken/<?php echo $product['product_id']; ?>"> Cadeau bewerken </a>
<?php endif; ?>
    </div>
    <br>
    <div class="cadeau_verwijderen">
        <?php if ( $_SESSION['user_id'] ==  $product["user_id"]): ?>
    <a class="btn btn-primary" href="<?php echo base_url() ?>/Delete_ctrl/delete_product_id/<?php echo $product['product_id']; ?>"> Cadeau verwijderen </a>
<?php endif; ?>
    </div>

    <!--Als het cadeau van de ingelogde gebruiker is laat aantal geïnteresseerden zien-->
    <div class="aantal_geinteresseerden">
         <?php if ( $_SESSION['user_id'] ==  $product["user_id"]): ?>
    <h4>Aantal geïnteresseerden:</h4>
<?php endif; ?>
    </div>

<?php if ( $_SESSION['user_id'] != $product["user_id"]): ?>
     <div class="aangeboden_door">   Aangeboden door:
<tr>
    <td>
        <a href="<?php echo base_url() . 'User/userdetails/'.$product['user_id']?>">
          <?php echo $userarray['voornaam'];?>
        </a>
    </td>
    </tr>
</div>

<?php endif; ?>
</div>

     </div>
     </div>
</div>

<div class="container">

<footer>
 <p>© kadokado 2017, Inc.</p>
</footer>
<hr>
</div>
</div>
<div class="clearfix"></div>
<?php include_once ('templates/footer.php'); ?>
</code>```

答:
Only way is to check if $_SESSION['user_id'] is set everywhere you are using this.

As a quick fix (if you have a lot of references to $_SESSION['user_id']), you can put to your second line:

```<code>if (empty($_SESSION['user_id'])) $_SESSION['user_id'] = -1;
</code>```

Body:
I'm making a product details page, and on the product details page I'm having if functions to see if the $_SESSION user_id is the same as the $product user_id to echo something or not for example. When no user is logged in, I get alot of errors that it can't find the $session user_id. How can I solve this problem so when there is no user logged in it does the same as if the session user_id is wrong to the product user_id?

for example:

<?php if ( $_SESSION['user_id'] != $product["user_id"]): ?>

Email van de eigenaar:

<?php echo $userarray['email'];?>
       <?php endif; ?>

So if the session user_id is wrong to the product user_id i want the same thing to happen when there is no $_SESSION user_id found which is echoing this: <?php echo $userarray['email'];?>

This is my whole details page:

<?php include_once ('templates/header.php'); ?>

            <?php $overditcadeau = 'Over dit cadeau'; ?>
            <?php $mijncadeau = 'Mijn cadeau'; ?>

         <?php   if ($_SESSION['user_id'] != $product["user_id"]) {
    echo $overditcadeau;
 } else {
    echo $mijncadeau;
  } ?>

<?php    $userarray = $this->db->get_Where('users', array('user_id'=>$product["user_id"]))->row_array();  ?>

    <?php if ( $_SESSION['user_id'] != $product["user_id"]): ?>

Email van de eigenaar:

<?php echo $userarray['email'];?>
       <?php endif; ?>

    <img src="<?php echo base_url(); ?>upload/<?php echo $product['product_foto']; ?>" id="cadeaufoto_overditcadeau">

 <?php echo $product['product_naam']; ?>

Over dit cadeau

<?php echo $product['product_beschrijving']; ?>

  <?php if ( $_SESSION['user_id'] != $product["user_id"]): ?>
     <a href="<?php echo base_url() ?>/Cadeau_ontvang"> <button type="button" class="btn btn-default">Ik wil dit cadeau!</button>

     <button onclick="myFunction()">Ik wil dit cadeau!</button>

<?php endif; ?>

        <?php if ( $_SESSION['user_id'] ==  $product["user_id"]): ?>
    <a class="btn btn-primary" href="<?php echo base_url() ?>/KdGwController/details_bewerken/<?php echo $product['product_id']; ?>"> Cadeau bewerken
<?php endif; ?>

        <?php if ( $_SESSION['user_id'] ==  $product["user_id"]): ?>
    <a class="btn btn-primary" href="<?php echo base_url() ?>/Delete_ctrl/delete_product_id/<?php echo $product['product_id']; ?>"> Cadeau verwijderen
<?php endif; ?>

         <?php if ( $_SESSION['user_id'] ==  $product["user_id"]): ?>

Aantal geïnteresseerden:

<?php endif; ?>

<?php if ( $_SESSION['user_id'] != $product["user_id"]): ?>

   Aangeboden door:

        <a href="<?php echo base_url() . 'User/userdetails/'.$product['user_id']?>">
          <?php echo $userarray['voornaam'];?>

<?php endif; ?>

© kadokado 2017, Inc.

<?php include_once ('templates/footer.php'); ?>

Body:
Only way is to check if $_SESSION['user_id'] is set everywhere you are using this.

As a quick fix (if you have a lot of references to $_SESSION['user_id']), you can put to your second line:

if (empty($_SESSION['user_id'])) $_SESSION['user_id'] = -1;


问:
How to get root node attributes on java
I have an xml file like down below. I want to get pharmacies nodes' latitude and longitude attributes.I can get chilnodes attributes but couldnt get root node attributes. I am new on java and xml. I could not find a solution how to do.

```<code><pharmacies Acc="4" latitude="36.8673380" longitude="30.6346640" address="Ayujkila">
        <pharmacy name="sadde" owner="" address="dedes" distance="327.000555668" phone="342343" lat="36.8644" long="30.6345" accuracy="8"/>
        <pharmacy name="Sun " owner="" address="degerse" distance="364.450016586" phone="45623" lat="36.8641" long="30.6353" accuracy="8"/>
        <pharmacy name="lara" owner="" address="freacde" distance="927.262190129" phone="564667" lat="36.8731" long="30.6422" accuracy="8"
    <end/>
    </pharmacies>
</code>```

This is my part of code. I get xml file from a url address.

```<code>                    DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
                 DocumentBuilder db = dbf.newDocumentBuilder();
                 Document doc = db.parse(new InputSource(url.openStream()));
                 doc.getDocumentElement().normalize();
                    NodeList nodeList =doc.getElementsByTagName("pharmacy");
                 for (int i = 0; i < nodeList.getLength(); i++){
                      Node node =nodeList.item(i);
                      Element fstElmnt = (Element) node;
                      NodeList pharmacyList = fstElmnt.getElementsByTagName("pharmacy");
                      Element pharmacyElement = (Element) pharmacyList.item(0);
              Element pharmacyElement = (Element) pharmacyList.item(0);

              HashMap<String,String>map=new HashMap<String,String>();
              map.put("name", pharmacyElement.getAttribute("name"));
              map.put("distance", pharmacyElement.getAttribute("phone"));
              list.add(map);

              latt.add(pharmacyElement.getAttribute("lat"));

                    ....
</code>```

答: doc.getDocumentElement() will return the root element and you can call getAttribute( attrName ) on it like you would on any other element.

ContentLicense: CC BY-SA 2.5

Title: How to get root node attributes on java

Body:
I have an xml file like down below. I want to get pharmacies nodes' latitude and longitude attributes.I can get chilnodes attributes but couldnt get root node attributes. I am new on java and xml. I could not find a solution how to do.

<pharmacies Acc="4" latitude="36.8673380" longitude="30.6346640" address="Ayujkila">
        <pharmacy name="sadde" owner="" address="dedes" distance="327.000555668" phone="342343" lat="36.8644" long="30.6345" accuracy="8"/>
        <pharmacy name="Sun " owner="" address="degerse" distance="364.450016586" phone="45623" lat="36.8641" long="30.6353" accuracy="8"/>
        <pharmacy name="lara" owner="" address="freacde" distance="927.262190129" phone="564667" lat="36.8731" long="30.6422" accuracy="8"
    <end/>
    </pharmacies>

This is my part of code. I get xml file from a url address.

                    DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
                 DocumentBuilder db = dbf.newDocumentBuilder();
                 Document doc = db.parse(new InputSource(url.openStream()));
                 doc.getDocumentElement().normalize();
                    NodeList nodeList =doc.getElementsByTagName("pharmacy");
                 for (int i = 0; i < nodeList.getLength(); i++){
                      Node node =nodeList.item(i);
                      Element fstElmnt = (Element) node;
                      NodeList pharmacyList = fstElmnt.getElementsByTagName("pharmacy");
                      Element pharmacyElement = (Element) pharmacyList.item(0);
              Element pharmacyElement = (Element) pharmacyList.item(0);

              HashMap<String,String>map=new HashMap<String,String>();
              map.put("name", pharmacyElement.getAttribute("name"));
              map.put("distance", pharmacyElement.getAttribute("phone"));
              list.add(map);

              latt.add(pharmacyElement.getAttribute("lat"));

                    ....


问:
Apache tomcat server local host url
when i run my application using tomcat server in eclipse i will be redirected to following URL: "HTTP://localhost:8080/example/login" .

/login is my controller request mapping , but example is also getting appended. How can I remove that from my URL.

the following is my server.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<Server port="8005" shutdown="SHUTDOWN">
    <Listener className="org.apache.catalina.startup.VersionLoggerListener"/>
    <Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>
    <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
    <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
    <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>

    <GlobalNamingResources>
        <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
    </GlobalNamingResources>

    <Service name="Catalina">

        <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
        <Connector port="8009" protocol="AJP/1.3" redirectPort="8443"/>

        <Engine defaultHost="localhost" name="Catalina">

            <Realm className="org.apache.catalina.realm.LockOutRealm">
                <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
            </Realm>

            <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">

                <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t "%r" %s %b" prefix="localhost_access_log" suffix=".txt"/>

                <Context docBase="sourcelead" path="/sourcelead" reloadable="true" source="org.eclipse.jst.jee.server:sourcelead"/><Context docBase="spring-mvc" path="/spring-mvc" reloadable="true" source="org.eclipse.jst.jee.server:spring-mvc"/></Host>
        </Engine>
    </Service>
</Server>
</code>```

答:
You should change your project settings in Eclipse.

Right click on your project

-Properties

-Web Project Settings

-Change your context path

And finally clean and rebuild your project.

Title: Apache tomcat server local host url

Body:
when i run my application using tomcat server in eclipse i will be redirected to following URL: "HTTP://localhost:8080/example/login" .

/login is my controller request mapping , but example is also getting appended. How can I remove that from my URL.

the following is my server.xml

<?xml version="1.0" encoding="UTF-8"?>
<Server port="8005" shutdown="SHUTDOWN">
    <Listener className="org.apache.catalina.startup.VersionLoggerListener"/>
    <Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>
    <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
    <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
    <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>

    <GlobalNamingResources>
        <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
    </GlobalNamingResources>

    <Service name="Catalina">

        <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
        <Connector port="8009" protocol="AJP/1.3" redirectPort="8443"/>

        <Engine defaultHost="localhost" name="Catalina">

            <Realm className="org.apache.catalina.realm.LockOutRealm">
                <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
            </Realm>

            <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">

                <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t "%r" %s %b" prefix="localhost_access_log" suffix=".txt"/>

                <Context docBase="sourcelead" path="/sourcelead" reloadable="true" source="org.eclipse.jst.jee.server:sourcelead"/><Context docBase="spring-mvc" path="/spring-mvc" reloadable="true" source="org.eclipse.jst.jee.server:spring-mvc"/></Host>
        </Engine>
    </Service>
</Server>


问:
Interview Question: Find Median From Mega Number Of Integers
There is a file that contains 10G(1000000000) number of integers, please find the Median of these integers. you are given 2G memory to do this. Can anyone come up with an reasonable way? thanks!  </p>

答:
Here is the algorithm described by @Rex Kerr implemented in Java.

```<code>/**
 * Computes the median.
 * @param arr Array of strings, each element represents a distinct binary number and has the same number of bits (padded with leading zeroes if necessary)
 * @return the median (number of rank ceil((m+1)/2) ) of the array as a string
 */
static String computeMedian(String[] arr) {

    // rank of the median element
    int m = (int) Math.ceil((arr.length+1)/2.0);

    String bitMask = "";
    int zeroBin = 0;

    while (bitMask.length() < arr[0].length()) {

        // puts elements which conform to the bitMask into one of two buckets
        for (String curr : arr) {
            if (curr.startsWith(bitMask))
                if (curr.charAt(bitMask.length()) == '0')
                    zeroBin++;
        }

        // decides in which bucket the median is located
        if (zeroBin >= m)
            bitMask = bitMask.concat("0");
        else {
            m -= zeroBin;
            bitMask = bitMask.concat("1");
        }

        zeroBin = 0;
    }

    return bitMask;
}
</code>```

Some test cases and updates to the algorithm can be found here.

Body:
Here is the algorithm described by @Rex Kerr implemented in Java.

/**
 * Computes the median.
 * @param arr Array of strings, each element represents a distinct binary number and has the same number of bits (padded with leading zeroes if necessary)
 * @return the median (number of rank ceil((m+1)/2) ) of the array as a string
 */
static String computeMedian(String[] arr) {

    // rank of the median element
    int m = (int) Math.ceil((arr.length+1)/2.0);

    String bitMask = "";
    int zeroBin = 0;

    while (bitMask.length() < arr[0].length()) {

        // puts elements which conform to the bitMask into one of two buckets
        for (String curr : arr) {
            if (curr.startsWith(bitMask))
                if (curr.charAt(bitMask.length()) == '0')
                    zeroBin++;
        }

        // decides in which bucket the median is located
        if (zeroBin >= m)
            bitMask = bitMask.concat("0");
        else {
            m -= zeroBin;
            bitMask = bitMask.concat("1");
        }

        zeroBin = 0;
    }

    return bitMask;
}

Some test cases and updates to the algorithm can be found here.


问:
Unable to Acquire the State Change Lock
Our products are using the latest production-ready release of SWT, 3.7.2. Now since no one back then knew what the next Java version would be called (and how would they know that 8 came after 7, that's like higher mathematics), we were forced to swap the org.eclipse.osgi from 3.7.2 to 3.10.0, so that we can now support Java 8. While that's maybe not the best of ideas, in theory it should work.

Of course, being the major screw-up that Eclipse Luna is, there is this one "error" when we start our applications (about 50 percent of the time, I'd guess):

```<code>org.osgi.framework.BundleException: Unable to acquire the state change lock for the module: osgi.identity; osgi.identity="org.eclipse.osgi"; type="osgi.bundle"; version:Version="3.10.0.v20140606-1445"; singleton:="true" [id=0] STARTED [STARTED] invalid
at org.eclipse.osgi.container.Module.lockStateChange(Module.java:329)
at org.eclipse.osgi.container.SystemModule.init(SystemModule.java:44)
at org.eclipse.osgi.container.SystemModule.start(SystemModule.java:170)
at org.eclipse.osgi.internal.framework.EquinoxBundle.start(EquinoxBundle.java:393)
at org.eclipse.osgi.internal.framework.EquinoxBundle.start(EquinoxBundle.java:412)
at org.eclipse.equinox.internal.simpleconfigurator.ConfigApplier.startBundles(ConfigApplier.java:307)
at org.eclipse.equinox.internal.simpleconfigurator.ConfigApplier.install(ConfigApplier.java:108)
at org.eclipse.equinox.internal.simpleconfigurator.SimpleConfiguratorImpl.applyConfiguration(SimpleConfiguratorImpl.java:129)
at org.eclipse.equinox.internal.simpleconfigurator.SimpleConfiguratorImpl.applyConfiguration(SimpleConfiguratorImpl.java:143)
at org.eclipse.equinox.internal.simpleconfigurator.Activator.start(Activator.java:48)
at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:771)
at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:1)
at java.security.AccessController.doPrivileged(Native Method)
at org.eclipse.osgi.internal.framework.BundleContextImpl.startActivator(BundleContextImpl.java:764)
at org.eclipse.osgi.internal.framework.BundleContextImpl.start(BundleContextImpl.java:721)
at org.eclipse.osgi.internal.framework.EquinoxBundle.startWorker0(EquinoxBundle.java:936)
at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.startWorker(EquinoxBundle.java:319)
at org.eclipse.osgi.container.Module.doStart(Module.java:571)
at org.eclipse.osgi.container.Module.start(Module.java:439)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1582)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1562)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1533)
at org.eclipse.osgi.container.SystemModule.startWorker(SystemModule.java:242)
at org.eclipse.osgi.container.Module.doStart(Module.java:571)
at org.eclipse.osgi.container.Module.start(Module.java:439)
at org.eclipse.osgi.container.SystemModule.start(SystemModule.java:172)
at org.eclipse.osgi.internal.framework.EquinoxBundle.start(EquinoxBundle.java:393)
at org.eclipse.osgi.internal.framework.EquinoxBundle.start(EquinoxBundle.java:412)
at org.eclipse.osgi.launch.Equinox.start(Equinox.java:115)
at org.eclipse.core.runtime.adaptor.EclipseStarter.startup(EclipseStarter.java:320)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:232)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:622)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:577)
at org.eclipse.equinox.launcher.Main.run(Main.java:1410)
at org.eclipse.equinox.launcher.Main.main(Main.java:1386)
</code>```

There's not much information on the web what the problem is, most suggest to just delete the workspace, but for most it only happens when starting up Eclipse, not the final applications - nonetheless, I deleted workspaces and the runtime-folders. Nothing helps. The "error" gets thrown in the exported product as well, but as far as I can tell, everything still works as expected.

Is there a way to fix it? And if not, is there a way to just hide that stupid exception (disable logging for a moment, clearing the log, whatever, I'm not picky)?

答:
Issue pop-up after upgrading eclipse neon through update-site along with installation of some new plugins.

Step 01:
I removed .fileTable.* lock files from ${eclipse_home}/configuration/org.eclipse.osgi/.manager directory.

Step 02:
Removed osgi cache and other plugins cache by starting in eclipse clean mode

eclipse -clean

Title: Unable to Acquire the State Change Lock

Body:
Our products are using the latest production-ready release of SWT, 3.7.2. Now since no one back then knew what the next Java version would be called (and how would they know that 8 came after 7, that's like higher mathematics), we were forced to swap the org.eclipse.osgi from 3.7.2 to 3.10.0, so that we can now support Java 8. While that's maybe not the best of ideas, in theory it should work.

Of course, being the major screw-up that Eclipse Luna is, there is this one "error" when we start our applications (about 50 percent of the time, I'd guess):

org.osgi.framework.BundleException: Unable to acquire the state change lock for the module: osgi.identity; osgi.identity="org.eclipse.osgi"; type="osgi.bundle"; version:Version="3.10.0.v20140606-1445"; singleton:="true" [id=0] STARTED [STARTED] invalid
at org.eclipse.osgi.container.Module.lockStateChange(Module.java:329)
at org.eclipse.osgi.container.SystemModule.init(SystemModule.java:44)
at org.eclipse.osgi.container.SystemModule.start(SystemModule.java:170)
at org.eclipse.osgi.internal.framework.EquinoxBundle.start(EquinoxBundle.java:393)
at org.eclipse.osgi.internal.framework.EquinoxBundle.start(EquinoxBundle.java:412)
at org.eclipse.equinox.internal.simpleconfigurator.ConfigApplier.startBundles(ConfigApplier.java:307)
at org.eclipse.equinox.internal.simpleconfigurator.ConfigApplier.install(ConfigApplier.java:108)
at org.eclipse.equinox.internal.simpleconfigurator.SimpleConfiguratorImpl.applyConfiguration(SimpleConfiguratorImpl.java:129)
at org.eclipse.equinox.internal.simpleconfigurator.SimpleConfiguratorImpl.applyConfiguration(SimpleConfiguratorImpl.java:143)
at org.eclipse.equinox.internal.simpleconfigurator.Activator.start(Activator.java:48)
at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:771)
at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:1)
at java.security.AccessController.doPrivileged(Native Method)
at org.eclipse.osgi.internal.framework.BundleContextImpl.startActivator(BundleContextImpl.java:764)
at org.eclipse.osgi.internal.framework.BundleContextImpl.start(BundleContextImpl.java:721)
at org.eclipse.osgi.internal.framework.EquinoxBundle.startWorker0(EquinoxBundle.java:936)
at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.startWorker(EquinoxBundle.java:319)
at org.eclipse.osgi.container.Module.doStart(Module.java:571)
at org.eclipse.osgi.container.Module.start(Module.java:439)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1582)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1562)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1533)
at org.eclipse.osgi.container.SystemModule.startWorker(SystemModule.java:242)
at org.eclipse.osgi.container.Module.doStart(Module.java:571)
at org.eclipse.osgi.container.Module.start(Module.java:439)
at org.eclipse.osgi.container.SystemModule.start(SystemModule.java:172)
at org.eclipse.osgi.internal.framework.EquinoxBundle.start(EquinoxBundle.java:393)
at org.eclipse.osgi.internal.framework.EquinoxBundle.start(EquinoxBundle.java:412)
at org.eclipse.osgi.launch.Equinox.start(Equinox.java:115)
at org.eclipse.core.runtime.adaptor.EclipseStarter.startup(EclipseStarter.java:320)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:232)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:622)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:577)
at org.eclipse.equinox.launcher.Main.run(Main.java:1410)
at org.eclipse.equinox.launcher.Main.main(Main.java:1386)

There's not much information on the web what the problem is, most suggest to just delete the workspace, but for most it only happens when starting up Eclipse, not the final applications - nonetheless, I deleted workspaces and the runtime-folders. Nothing helps. The "error" gets thrown in the exported product as well, but as far as I can tell, everything still works as expected.

Is there a way to fix it? And if not, is there a way to just hide that stupid exception (disable logging for a moment, clearing the log, whatever, I'm not picky)?


问:
Expected BEGIN_ARRAY but was BEGIN_OBJECT retrofit2
I have some problem about retrofit2

How to fix Expected BEGIN_ARRAY but was BEGIN_OBJECT in retrofit2

I don't know to fix it

What's my wrong ?

my json is

```<code>{
    "result": true,
    "message": "success",
    "data": [
        {
            "id": "10",
            "type_name": "pppppp"
        },
        {
            "id_mt": "11",
            "type_name": "aaaaaa"
        }
    ]
}
</code>```

and my model class is

```<code>public class MessageFastModel {
    private boolean result;
    private String message;

    private List<DataBean> data;

    public boolean isResult() {
        return result;
    }

    public void setResult(boolean result) {
        this.result = result;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {
        private String id;
        private String type_name;

        public String getId() {
            return id;
        }

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

        public String getType_name() {
            return type_name;
        }

        public void setType_name(String type_name) {
            this.type_name = type_name;
        }
    }
}
</code>```

My code is

```<code> @FormUrlEncoded
 @POST("api/message_type")
 Call<MessageFastModel> listMessageFast(@Field("token") String token);
</code>```

and

```<code>Call<MessageFastModel> dddddCall = ooooo.listMessageFast(Preferences.getToken());
                        dddddCall.enqueue(new Callback<MessageFastModel>() {
                            @Override
                            public void onResponse(Call<MessageFastModel> call, Response<MessageFastModel> response) {
                                if (response.isSuccessful()) {
                                    Log.d("ddd", "onResponse: " + response.body().getData().size());
                                }
                            }

                            @Override
                            public void onFailure(Call<MessageFastModel> call, Throwable t) {
                                Log.e("ddd", "onFailure: " + t.getMessage());
                            }
                        });
</code>```

but My error is

E/ddd: onFailure: java.lang.IllegalStateException: Expected
  BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 44 path $.data

what's problem ? thanks!

答:
When you have problem

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 44 path $.data

We must know that where need JSONArray .You have List<DataBean> data .So your data must use JSONArray .

And may be your problem at

```<code>Log.d("ddd", "onResponse: " + response.body().getData().size());
</code>```

You can do like this .

```<code>System.out.println(response.body().string());
</code>```

And show your message .

And try this class .

```<code>public class MessageFastModel {
    private boolean result;
    private String message;

    private DataBean data;

    public boolean isResult() {
        return result;
    }

    public void setResult(boolean result) {
        this.result = result;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public DataBean getData() {
        return data;
    }

    public void setData(DataBean data) {
        this.data = data;
    }

    public static class DataBean {
        private String id;
        private String type_name;

        public String getId() {
            return id;
        }

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

        public String getType_name() {
            return type_name;
        }

        public void setType_name(String type_name) {
            this.type_name = type_name;
        }
    }
}
</code>```

And remove Log.d("ddd", "onResponse: " + response.body().getData().size());

Body:
I have some problem about retrofit2

How to fix Expected BEGIN_ARRAY but was BEGIN_OBJECT in retrofit2

I don't know to fix it

What's my wrong ?

my json is

{
    "result": true,
    "message": "success",
    "data": [
        {
            "id": "10",
            "type_name": "pppppp"
        },
        {
            "id_mt": "11",
            "type_name": "aaaaaa"
        }
    ]
}

and my model class is

public class MessageFastModel {
    private boolean result;
    private String message;

    private List<DataBean> data;

    public boolean isResult() {
        return result;
    }

    public void setResult(boolean result) {
        this.result = result;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {
        private String id;
        private String type_name;

        public String getId() {
            return id;
        }

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

        public String getType_name() {
            return type_name;
        }

        public void setType_name(String type_name) {
            this.type_name = type_name;
        }
    }
}

My code is

 @FormUrlEncoded
 @POST("api/message_type")
 Call<MessageFastModel> listMessageFast(@Field("token") String token);

and

Call<MessageFastModel> dddddCall = ooooo.listMessageFast(Preferences.getToken());
                        dddddCall.enqueue(new Callback<MessageFastModel>() {
                            @Override
                            public void onResponse(Call<MessageFastModel> call, Response<MessageFastModel> response) {
                                if (response.isSuccessful()) {
                                    Log.d("ddd", "onResponse: " + response.body().getData().size());
                                }
                            }

                            @Override
                            public void onFailure(Call<MessageFastModel> call, Throwable t) {
                                Log.e("ddd", "onFailure: " + t.getMessage());
                            }
                        });

but My error is

E/ddd: onFailure: java.lang.IllegalStateException: Expected
  BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 44 path $.data

what's problem ? thanks!

Body:
When you have problem

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 44 path $.data

We must know that where need JSONArray .You have List<DataBean> data .So your data must use JSONArray .

And may be your problem at

Log.d("ddd", "onResponse: " + response.body().getData().size());

You can do like this .

System.out.println(response.body().string());

And show your message .

And try this class .

public class MessageFastModel {
    private boolean result;
    private String message;

    private DataBean data;

    public boolean isResult() {
        return result;
    }

    public void setResult(boolean result) {
        this.result = result;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public DataBean getData() {
        return data;
    }

    public void setData(DataBean data) {
        this.data = data;
    }

    public static class DataBean {
        private String id;
        private String type_name;

        public String getId() {
            return id;
        }

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

        public String getType_name() {
            return type_name;
        }

        public void setType_name(String type_name) {
            this.type_name = type_name;
        }
    }
}

And remove Log.d("ddd", "onResponse: " + response.body().getData().size());


问:
Is there a simple way to get a object by _id in Kotlin?
I'm a beginner of Kotlin, I hope to get a object by _id in the following data structure, so I write the fun getMDetailByID(aMDetailsList:MDetailsList, _id:Long)... which is a traditional method.

But I think the fun is too complex, is there a simple way do that? such as use Lambda expression.

```<code>class UIMain : AppCompatActivity() {

    data class BluetoothDef(val Status:Boolean=false)
    data class WiFiDef(val Name:String, val Status:Boolean=false)

    data class MDetail (
            val _id: Long,
            val bluetooth: BluetoothDef,
            val wiFi:WiFiDef
    )

    data class MDetailsList(val mListMetail: MutableList<MDetail>)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_main)

        var mBluetoothDef1=BluetoothDef()
        var mWiFiDef1=WiFiDef("MyConnect 1",true)
        var aMDetail1= MDetail(5L,mBluetoothDef1,mWiFiDef1)

        var mBluetoothDef2=BluetoothDef(true)
        var mWiFiDef2=WiFiDef("MyConnect 2")
        var aMDetail2= MDetail(6L,mBluetoothDef2,mWiFiDef2)

        val mListMetail:MutableList<MDetail> = mutableListOf(aMDetail1,aMDetail2)

        var aMDetailsList=MDetailsList(mListMetail)

        var c=getMDetailByID(aMDetailsList,5L)

    }

    fun getMDetailByID(aMDetailsList:MDetailsList, _id:Long):MDetail?{
        var aMDetail: MDetail?=null

        var a=aMDetailsList.mListMetail

        for (b in a){
            if (b._id==_id){
                aMDetail=b
            }
        }

        return aMDetail

    }

}
</code>```

答:
Simpler code can be like:    </p>

```<code>fun getMDetailByID(aMDetailsList: MDetailsList, _id: Long) = aMDetailsList.mListMetail.filter { it._id == _id }.lastOrNull()
</code>```

Body:
I'm a beginner of Kotlin, I hope to get a object by _id in the following data structure, so I write the fun getMDetailByID(aMDetailsList:MDetailsList, _id:Long)... which is a traditional method.

But I think the fun is too complex, is there a simple way do that? such as use Lambda expression.

class UIMain : AppCompatActivity() {

    data class BluetoothDef(val Status:Boolean=false)
    data class WiFiDef(val Name:String, val Status:Boolean=false)

    data class MDetail (
            val _id: Long,
            val bluetooth: BluetoothDef,
            val wiFi:WiFiDef
    )

    data class MDetailsList(val mListMetail: MutableList<MDetail>)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_main)

        var mBluetoothDef1=BluetoothDef()
        var mWiFiDef1=WiFiDef("MyConnect 1",true)
        var aMDetail1= MDetail(5L,mBluetoothDef1,mWiFiDef1)

        var mBluetoothDef2=BluetoothDef(true)
        var mWiFiDef2=WiFiDef("MyConnect 2")
        var aMDetail2= MDetail(6L,mBluetoothDef2,mWiFiDef2)

        val mListMetail:MutableList<MDetail> = mutableListOf(aMDetail1,aMDetail2)

        var aMDetailsList=MDetailsList(mListMetail)

        var c=getMDetailByID(aMDetailsList,5L)

    }

    fun getMDetailByID(aMDetailsList:MDetailsList, _id:Long):MDetail?{
        var aMDetail: MDetail?=null

        var a=aMDetailsList.mListMetail

        for (b in a){
            if (b._id==_id){
                aMDetail=b
            }
        }

        return aMDetail

    }

}

Body:
Simpler code can be like:

fun getMDetailByID(aMDetailsList: MDetailsList, _id: Long) = aMDetailsList.mListMetail.filter { it._id == _id }.lastOrNull()


问:
Do a count and group by weeks or months
I have an object array like this:

```<code>[ { date: '2017-11-17', count: 2 }, { date: '2017-11-16', count: 24 }, { date: '2017-11-15', count: 42 }, { date: '2017-11-14', count: 23 }, { date: '2017-11-13', count: 33 }, { date: '2017-11-12', count: 22 }, { date: '2017-11-11', count: 11 }, { date: '2017-10-04', count: 66 } ]
</code>```

Using the momentJS library and pure javascript only (no lodash _groupBy etc), how can I group the results and add together the 'count' to be like this:

Week Grouping: (Monday is start of week)

```<code>[ { date: '2017-11-13', count: 104 }, { date: '2017-11-06', count: 22 }, { date: '2017-10-02', count: 66 } ]
</code>```

Month Grouping: (1st of month is start of month)

```<code>[ { date: '2017-11-01', count: 26 }, { date: '2017-10-01', count: 66 } ]
</code>```

Thank You.

答:
Here's a function I wrote. You pass it your array as the first argument, and 'week' or 'month' as the second one.</p>

```<code>function groupBy(elements, duration) {
  const formatted = elements.map(elem => {
    return { date: moment(elem.date).startOf(duration).format('YYYY-MM-DD'), count: elem.count }
  })

  const dates = formatted.map(elem => elem.date)
  const uniqueDates = dates.filter((date, index) => dates.indexOf(date) === index)

  return uniqueDates.map(date => {
    const count = formatted.filter(elem => elem.date === date).reduce((count, elem) => count + elem.count, 0)
    return { date, count }
  })
}
</code>```

Title: Do a count and group by weeks or months

Body:
I have an object array like this:

[ { date: '2017-11-17', count: 2 }, { date: '2017-11-16', count: 24 }, { date: '2017-11-15', count: 42 }, { date: '2017-11-14', count: 23 }, { date: '2017-11-13', count: 33 }, { date: '2017-11-12', count: 22 }, { date: '2017-11-11', count: 11 }, { date: '2017-10-04', count: 66 } ]

Using the momentJS library and pure javascript only (no lodash _groupBy etc), how can I group the results and add together the 'count' to be like this:

Week Grouping: (Monday is start of week)

[ { date: '2017-11-13', count: 104 }, { date: '2017-11-06', count: 22 }, { date: '2017-10-02', count: 66 } ]

Month Grouping: (1st of month is start of month)

[ { date: '2017-11-01', count: 26 }, { date: '2017-10-01', count: 66 } ]

Thank You.

Body:
Here's a function I wrote. You pass it your array as the first argument, and 'week' or 'month' as the second one.

function groupBy(elements, duration) {
  const formatted = elements.map(elem => {
    return { date: moment(elem.date).startOf(duration).format('YYYY-MM-DD'), count: elem.count }
  })

  const dates = formatted.map(elem => elem.date)
  const uniqueDates = dates.filter((date, index) => dates.indexOf(date) === index)

  return uniqueDates.map(date => {
    const count = formatted.filter(elem => elem.date === date).reduce((count, elem) => count + elem.count, 0)
    return { date, count }
  })
}


问:
how to avoid dirty checking in hibernate
I have a entity call Company, and another entity call token.

1 Company will have many tokens.

So in my Company entity, I will have something like follow:

```<code> @OneToMany(mappedBy = "companyId")
 public Set< Token > getTokens() {
    return tokens;
 }
</code>```

However, I will have some logic during the return, it will change the token list before return, its something like follow:

```<code>@OneToMany(mappedBy = "companyId")
 public Set< Token > getTokens() {
    tokens.remove( token );
    return tokens;
 }
</code>```

Because of I changing the value in token list, thus, every time I select the company object from db using hibernate, the company table will be updated automatically.

Base on my understanding, this is a behavior of hibernate dirty checking. So when Hibernate detect that there something changes on it, it will do the update to database.

Is there any way that can avoid this? For example maybe just call existing hibernate function, so that hibernate will know the token list is dirty, and it will no do the update.

Yes, I know the filtering logic in the getTokens() is not suitable. By right filtering logic should not apply in entity level. But because of currently there is many place using this method, if I change in this entity level, then there will impact others and if I change other place as well, it will need to retest whole application again.

Thus I am trying to find a better way on this.

答:
What you actually want is to prevent Hibernate from auto flushing.

See hibernate docs:

Flushing is the process of synchronizing the underlying persistent
  store with persistable state held in memory.

A solution to this problem is to change the default configuration of FlushMode from auto to manual by setting FlushMode.MANUAL. In this way the dirty check mechanism will stop causing the aforementioned synchronization.

Although the Session is only ever flushed when Session.flush() is explicitly called by the application as described in the hibernate documentation.

Here it has to be mentioned that if you follow the suggested solution you need to pay the price of the explicitly flushing which means that you need to explicitly
call the Session.flush() method every time you want to commit something on the database.

Read here some useful material regarding FlushMode as were officially documented in hibernate documentation.

UPDATE:

This solution applies on the Session, so if you want to apply this only on the specific entity you should try to create two methods. One for setting it to MANUAL and one for back to the default AUTO. In this way you will change your value after MANUAL setting to prevent flushing and subsequently you will set it back to the default in order not to affect the other entities.

Maybe the below implementation will help:

```<code>@Autowired
private SessionFactory sessionFactory;

@OneToMany(mappedBy = "companyId")
 public Set< Token > getTokens() {
    setFlushModeManual();
    tokens.remove( token );
    setFlushModeAuto();
    return tokens;
 }

private void setFlushModeManual() {
    sessionFactory.getCurrentSession().setFlushMode(FlushMode.MANUAL);
}

private void setFlushModeAuto() {
    sessionFactory.getCurrentSession().setFlushMode(FlushMode.AUTO);
}
</code>```

Body:
I have a entity call Company, and another entity call token.

1 Company will have many tokens.

So in my Company entity, I will have something like follow:

 @OneToMany(mappedBy = "companyId")
 public Set< Token > getTokens() {
    return tokens;
 }

However, I will have some logic during the return, it will change the token list before return, its something like follow:

@OneToMany(mappedBy = "companyId")
 public Set< Token > getTokens() {
    tokens.remove( token );
    return tokens;
 }

Because of I changing the value in token list, thus, every time I select the company object from db using hibernate, the company table will be updated automatically.

Base on my understanding, this is a behavior of hibernate dirty checking. So when Hibernate detect that there something changes on it, it will do the update to database.

Is there any way that can avoid this? For example maybe just call existing hibernate function, so that hibernate will know the token list is dirty, and it will no do the update.

Yes, I know the filtering logic in the getTokens() is not suitable. By right filtering logic should not apply in entity level. But because of currently there is many place using this method, if I change in this entity level, then there will impact others and if I change other place as well, it will need to retest whole application again.

Thus I am trying to find a better way on this.

Body:
What you actually want is to prevent Hibernate from auto flushing.

See hibernate docs:

Flushing is the process of synchronizing the underlying persistent
  store with persistable state held in memory.

A solution to this problem is to change the default configuration of FlushMode from auto to manual by setting FlushMode.MANUAL. In this way the dirty check mechanism will stop causing the aforementioned synchronization.

Although the Session is only ever flushed when Session.flush() is explicitly called by the application as described in the hibernate documentation.

Here it has to be mentioned that if you follow the suggested solution you need to pay the price of the explicitly flushing which means that you need to explicitly
call the Session.flush() method every time you want to commit something on the database.

Read here some useful material regarding FlushMode as were officially documented in hibernate documentation.

UPDATE:

This solution applies on the Session, so if you want to apply this only on the specific entity you should try to create two methods. One for setting it to MANUAL and one for back to the default AUTO. In this way you will change your value after MANUAL setting to prevent flushing and subsequently you will set it back to the default in order not to affect the other entities.

Maybe the below implementation will help:

@Autowired
private SessionFactory sessionFactory;

@OneToMany(mappedBy = "companyId")
 public Set< Token > getTokens() {
    setFlushModeManual();
    tokens.remove( token );
    setFlushModeAuto();
    return tokens;
 }

private void setFlushModeManual() {
    sessionFactory.getCurrentSession().setFlushMode(FlushMode.MANUAL);
}

private void setFlushModeAuto() {
    sessionFactory.getCurrentSession().setFlushMode(FlushMode.AUTO);
}


问:
Angular2 fire fails Namespace 'firebase' has no exported member 'Promise'
I have installed angular2 fire

```<code> "angularfire2": "^5.0.0-rc.0",
</code>```

Now in my app module(root module)

```<code>export const firebaseConfig = {
  apiKey: "mykey",
  authDomain: "....",
  databaseURL: "...",
  projectId: "...",
  storageBucket: "...",
  messagingSenderId: "..."
};

imports:[
    AngularFireModule.initializeApp(firebaseConfig),
    AngularFireDatabaseModule
 ]
</code>```

Now am geting an error

```<code> Class 'FirebaseApp' incorrectly implements interface 'App'.
  Property 'firestore' is missing in type 'FirebaseApp'.

node_modules/angularfire2/firebase.app.module.d.ts (12,28):
  Namespace 'firebase' has no exported member 'Promise'.
</code>```

Where am i going wrong or what else do i need to add to have it work

答: firebase.Promise was removed in Firebase 4.5.0.  "angularfire2": "^5.0.0-rc.2" accounts for this change. This version should solve the issue you're having.

Body:
I have installed angular2 fire

 "angularfire2": "^5.0.0-rc.0",

Now in my app module(root module)

export const firebaseConfig = {
  apiKey: "mykey",
  authDomain: "....",
  databaseURL: "...",
  projectId: "...",
  storageBucket: "...",
  messagingSenderId: "..."
};

imports:[
    AngularFireModule.initializeApp(firebaseConfig),
    AngularFireDatabaseModule
 ]

Now am geting an error

 Class 'FirebaseApp' incorrectly implements interface 'App'.
  Property 'firestore' is missing in type 'FirebaseApp'.

node_modules/angularfire2/firebase.app.module.d.ts (12,28):
  Namespace 'firebase' has no exported member 'Promise'.

Where am i going wrong or what else do i need to add to have it work


问:
Update chart with new data not working
I'm drawing a bar chart with some initial data and then trying to update when a button is clicked. I get the error "Uncaught TypeError: Cannot read property 'length' of undefined". The error occurs after update buttom is clicked. How do I fix this and enable the update function to draw a new bar chart?

```<code><div id="chart"></div>
<button id="update" onclick="update()">Update</button>
</code>```

D3 code:

```<code>    var myData = [21, 3, 5, 21, 15];
    //Width and height
    var w = 250;
    var h = 250;
    var yScale = null;

    function draw(initialData) {
      var xScale = d3.scale.ordinal()
        .domain(d3.range(initialData.length))
        .rangeRoundBands([0, w], 0.05);

      yScale = d3.scale.linear()
        .domain([0, d3.max(initialData)])
        .range([0, h]);

      //Create SVG element
      var svg = d3.select("#chart")
        .append("svg")
        .attr("width", w)
        .attr("height", h);

      svg.selectAll("rect")
        .data(initialData)
        .enter()
        .append("rect")
        .attr("x", function(d, i) {
          return xScale(i);
        })
        .attr("y", function(d) {
          return h - yScale(d);
        })
        .attr("width", xScale.rangeBand())
        .attr("height", function(d) {
          return yScale(d);
        })
        .attr("fill", "steelblue");

      svg.selectAll("text")
        .data(initialData)
        .enter()
        .append("text")
        .text(function(d) {
          return d;
        })
        .attr("text-anchor", "middle")
        .attr("x", function(d, i) {
          return xScale(i) + xScale.rangeBand() / 2;
        })
        .attr("y", function(d) {
          return h - yScale(d) + 14;
        })
        .attr("font-family", "sans-serif")
        .attr("font-size", "11px")
        .attr("fill", "white");
    }

    draw(myData);

    var newData = [15, 5, 3, 15, 21];
    //update function
    function update(newData) {
      yScale.domain([0, d3.max(newData)]);

      var rects = d3.select("#chart svg")
        .selectAll("rect")
        .data(newData);

      // enter selection
      rects
        .enter().append("rect");

      // update selection
      rects
        .transition()
        .duration(300)
        .attr("y", function(d) {
          return h - yScale(d);
        })
        .attr("height", function(d) {
          return yScale(d);
        })

      // exit selection
      rects
        .exit().remove();

      var texts = d3.select("#chart svg")
        .selectAll("text")
        .data(newData);

      // enter selection
      texts
        .enter().append("rect");

      // update selection
      texts
        .transition()
        .duration(300)
        .attr("y", function(d) {
          return h - yScale(d) + 14;
        })
        .text(function(d) {
          return d;
        })

      // exit selection
      texts
        .exit().remove();
    }
</code>```

答:
The problem is that your update function expects an array of data as parameter but you call it without params.
You can add button click listener using d3 like that.

```<code>d3.select("#update").on("click", function(){ update(newData); })
</code>```

Created a fiddle for you

Title: Update chart with new data not working

Body:
I'm drawing a bar chart with some initial data and then trying to update when a button is clicked. I get the error "Uncaught TypeError: Cannot read property 'length' of undefined". The error occurs after update buttom is clicked. How do I fix this and enable the update function to draw a new bar chart?

<button id="update" onclick="update()">Update</button>

D3 code:

    var myData = [21, 3, 5, 21, 15];
    //Width and height
    var w = 250;
    var h = 250;
    var yScale = null;

    function draw(initialData) {
      var xScale = d3.scale.ordinal()
        .domain(d3.range(initialData.length))
        .rangeRoundBands([0, w], 0.05);

      yScale = d3.scale.linear()
        .domain([0, d3.max(initialData)])
        .range([0, h]);

      //Create SVG element
      var svg = d3.select("#chart")
        .append("svg")
        .attr("width", w)
        .attr("height", h);

      svg.selectAll("rect")
        .data(initialData)
        .enter()
        .append("rect")
        .attr("x", function(d, i) {
          return xScale(i);
        })
        .attr("y", function(d) {
          return h - yScale(d);
        })
        .attr("width", xScale.rangeBand())
        .attr("height", function(d) {
          return yScale(d);
        })
        .attr("fill", "steelblue");

      svg.selectAll("text")
        .data(initialData)
        .enter()
        .append("text")
        .text(function(d) {
          return d;
        })
        .attr("text-anchor", "middle")
        .attr("x", function(d, i) {
          return xScale(i) + xScale.rangeBand() / 2;
        })
        .attr("y", function(d) {
          return h - yScale(d) + 14;
        })
        .attr("font-family", "sans-serif")
        .attr("font-size", "11px")
        .attr("fill", "white");
    }

    draw(myData);

    var newData = [15, 5, 3, 15, 21];
    //update function
    function update(newData) {
      yScale.domain([0, d3.max(newData)]);

      var rects = d3.select("#chart svg")
        .selectAll("rect")
        .data(newData);

      // enter selection
      rects
        .enter().append("rect");

      // update selection
      rects
        .transition()
        .duration(300)
        .attr("y", function(d) {
          return h - yScale(d);
        })
        .attr("height", function(d) {
          return yScale(d);
        })

      // exit selection
      rects
        .exit().remove();

      var texts = d3.select("#chart svg")
        .selectAll("text")
        .data(newData);

      // enter selection
      texts
        .enter().append("rect");

      // update selection
      texts
        .transition()
        .duration(300)
        .attr("y", function(d) {
          return h - yScale(d) + 14;
        })
        .text(function(d) {
          return d;
        })

      // exit selection
      texts
        .exit().remove();
    }

Body:
The problem is that your update function expects an array of data as parameter but you call it without params.
You can add button click listener using d3 like that.

d3.select("#update").on("click", function(){ update(newData); })

Created a fiddle for you


问:
How can I make a script focus on an application?
I am creating some automated test scripts to test a piece of software.  Im doing this in a modular way so that I can more easily dictate which scripts are being and change this, while having all the scripts pre-compiled

I have a script which is launched with parameters from a batch, this opens up my compiled script which enters in the login details and presses OK to any dialogs that may appear.  This part works as intended.

At the end of the script I am trying to re-gain focus onto the main application window, set the window to fullscreen and then run the next batch file to perform the next test etc.

in this example "$practice" refers to the main application's window title, which I have derived using the AutoItv3 Info tool.

```<code>WinWaitActive($practice)
$hWnd = WinGetHandle($practice)

; FullScreen
WinSetState($practice,"",@SW_RESTORE)
WinSetState($practice,"",@SW_MAXIMIZE)

RunWait(@ComSpec & " /c " & "TestStart.bat")
</code>```

However, this is not regaining focus and maximising the window as expected, i think the applications splash screen could be interfering.

If I manually Click into any part of the application to focus on it, then the dialog will be set to fullscreen and then my second script will run.

What should I do to make this last part of the script behave as I wish?

答:
WinActivate ( "title" [, "text"] ) - Activates (gives focus to) a window.

title   - The title/hWnd/class of the window to activate. See Title
special definition.

text    [optional] The text of the window to activate. Default is an
empty string. See Text special definition.

More info here.

Body:
I am creating some automated test scripts to test a piece of software.  Im doing this in a modular way so that I can more easily dictate which scripts are being and change this, while having all the scripts pre-compiled

I have a script which is launched with parameters from a batch, this opens up my compiled script which enters in the login details and presses OK to any dialogs that may appear.  This part works as intended.

At the end of the script I am trying to re-gain focus onto the main application window, set the window to fullscreen and then run the next batch file to perform the next test etc.

in this example "$practice" refers to the main application's window title, which I have derived using the AutoItv3 Info tool.

WinWaitActive($practice)
$hWnd = WinGetHandle($practice)

; FullScreen
WinSetState($practice,"",@SW_RESTORE)
WinSetState($practice,"",@SW_MAXIMIZE)

RunWait(@ComSpec & " /c " & "TestStart.bat")

However, this is not regaining focus and maximising the window as expected, i think the applications splash screen could be interfering.

If I manually Click into any part of the application to focus on it, then the dialog will be set to fullscreen and then my second script will run.

What should I do to make this last part of the script behave as I wish?


问:
MySQL json extract/search not matching
this is driving me crazy.
Can someone explain, why the first call returns a path, but when selecting the path from a table, no path is found?

(MySQL-Version 5.7.20)

Working as expected:

```<code>SELECT JSON_SEARCH(
  '{"mm": [{"id":"1","field":"test","value":33}]}',
  'one', '1', null, '$.mm[*].id') as path;
  -- output: path== "$.mm[0].id"
</code>```

Not working:

```<code>drop table test;
create table test(
    id int primary key,
    data json
);

insert into test (id, data) values (1, '{}');
update test set data=JSON_SET(data, '$.mm', json_array()) where id=1;
update test set data=JSON_ARRAY_APPEND(data, '$.mm', '{"id":"1","field":"test","value":33}') where id=1;
SELECT JSON_SEARCH(data, 'one', '1', null, '$.mm[*].id') as path from test where id=1;
-- output: path==NULL
-- expected: path== "$.mm[0].id"
</code>```

Pretty sure i did some error here, but i can't figure out which one ...

Thank you

答:
Got it...
One has to cast the string to json in order to have a object type in the table. This is true for append and set. When using JSON_SEARCH the first parameter is automaticly converted to json if it's a string.</p>

Title: MySQL json extract/search not matching

Body:
this is driving me crazy.
Can someone explain, why the first call returns a path, but when selecting the path from a table, no path is found?

(MySQL-Version 5.7.20)

Working as expected:

SELECT JSON_SEARCH(
  '{"mm": [{"id":"1","field":"test","value":33}]}',
  'one', '1', null, '$.mm[*].id') as path;
  -- output: path== "$.mm[0].id"

Not working:

drop table test;
create table test(
    id int primary key,
    data json
);

insert into test (id, data) values (1, '{}');
update test set data=JSON_SET(data, '$.mm', json_array()) where id=1;
update test set data=JSON_ARRAY_APPEND(data, '$.mm', '{"id":"1","field":"test","value":33}') where id=1;
SELECT JSON_SEARCH(data, 'one', '1', null, '$.mm[*].id') as path from test where id=1;
-- output: path==NULL
-- expected: path== "$.mm[0].id"

Pretty sure i did some error here, but i can't figure out which one ...

Thank you


问:
IBDesignablesAgentCocoaTouch and Interface Builder Cocoa Touch Tool are eating my CPU
Does anyone know what these two: IBDesignablesAgentCocoaTouch and Interface Builder Cocoa Touch Tool are doing ?

Every time I have Xcode open these two are using so much CPU that my fans are at max speed.

I am using Xcode 9 beta 5 at the moment. Not sure if these all started with beta 5 or beta 4.

Can I do something to prevent them using so much CPU ?

答:
I had this issue for a few hours and in the end I finally fixed it. IBCTT was eating up cpu and memory 5gb at one point and Xcode was unresponsive. I updated everything, cleared every cache and even tried throttling the tool but in the end the issue was simple but hard to detect. If that seems like your issue read on.

What you must do is clear all constraints on any view in the storyboard with errors if you are able to load it at least once. Then reset to suggested constraints and save.

If your storyboard has many views you want to Editor -> Refactor to storyboard the most complex or recently added/edited view.

You may notice in the crash report that it mentions an error not reporting a reason. Seems that I was having an error that I couldn't detect since the storyboard wouldn't load anyways. Refactoring out the view with the issue, then loading it first on a fresh restart showed the error and allowed me to clear constraints immediately.

Then restart Xcode by shutting down without force quitting to avoid the crash report and allow Xcode to start normally. Clear build folder then recompile.

This issue followed me through three installs of Xcode, 9.1 GM and 9.2 beta 1 and 2(9c34b) and a couple High Sierra beta updates (4 currently), so the issue seems to be deep within the AutoLayout engine. In all fairness to Apple constraints are a powerful idea but the variations involved on tools end is a nightmare.

Also my Interface Builder Cocoa Touch Tool is back to 84mb in Activity Monitor so I'm back to work....good luck!


答:
The <pharmacies> element itself can be obtained using

```<code>Element pharmacies = doc.getDocumentElement();
</code>```

You can get the attributes from that.

Title: How to get root node attributes on java

Body:
I have an xml file like down below. I want to get pharmacies nodes' latitude and longitude attributes.I can get chilnodes attributes but couldnt get root node attributes. I am new on java and xml. I could not find a solution how to do.

<pharmacies Acc="4" latitude="36.8673380" longitude="30.6346640" address="Ayujkila">
        <pharmacy name="sadde" owner="" address="dedes" distance="327.000555668" phone="342343" lat="36.8644" long="30.6345" accuracy="8"/>
        <pharmacy name="Sun " owner="" address="degerse" distance="364.450016586" phone="45623" lat="36.8641" long="30.6353" accuracy="8"/>
        <pharmacy name="lara" owner="" address="freacde" distance="927.262190129" phone="564667" lat="36.8731" long="30.6422" accuracy="8"
    <end/>
    </pharmacies>

This is my part of code. I get xml file from a url address.

                    DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
                 DocumentBuilder db = dbf.newDocumentBuilder();
                 Document doc = db.parse(new InputSource(url.openStream()));
                 doc.getDocumentElement().normalize();
                    NodeList nodeList =doc.getElementsByTagName("pharmacy");
                 for (int i = 0; i < nodeList.getLength(); i++){
                      Node node =nodeList.item(i);
                      Element fstElmnt = (Element) node;
                      NodeList pharmacyList = fstElmnt.getElementsByTagName("pharmacy");
                      Element pharmacyElement = (Element) pharmacyList.item(0);
              Element pharmacyElement = (Element) pharmacyList.item(0);

              HashMap<String,String>map=new HashMap<String,String>();
              map.put("name", pharmacyElement.getAttribute("name"));
              map.put("distance", pharmacyElement.getAttribute("phone"));
              list.add(map);

              latt.add(pharmacyElement.getAttribute("lat"));

                    ....

Body:
The <pharmacies> element itself can be obtained using

Element pharmacies = doc.getDocumentElement();

You can get the attributes from that.


问:
stop background to be draggable on a button click
I have some code that when I press button the background in the div start to be draggable. I would like to do something like when I click on some else button  the background stop to be draggable and when again I press button the bg start to be draggable again.</p>

```<code><html>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
<script src="draggable_background.js"></script>

<style>
div { width: 320px; height: 240px; display: inline-block; font-family:
sans-serif; border: 2px solid #aaa;}
</style>

<body>
<div id="default" style="background:url('aaa.jpg')">default</div>

<br><br>
<button id="first"></button>

<script>
$(document).ready(function(){
$('#first').click(function() {
  $('#default').backgroundDraggable();
  $('div').each(function() {
    var $this = $(this),
        html = $this.html();
    $this.empty().append($('<p>').html(html))
  });
  });
});

</body>
</html>
</code>```

答:
try this
<button id="second">Second

in jQuery

```<code><script>
 $('#second').on('click',function(){
    $('#default').backgroundDraggable('destroy');
  });

 </script>
</code>```

Body:
I have some code that when I press button the background in the div start to be draggable. I would like to do something like when I click on some else button  the background stop to be draggable and when again I press button the bg start to be draggable again.

default

<button id="first"></button>

Body:
try this
<button id="second">Second</div>
in jQuery

<script>
 $('#second').on('click',function(){
    $('#default').backgroundDraggable('destroy');
  });

 </script>


问:
How to share the value of local property in class among different objects?
Ok so I am working with code that looks something like this,

```<code>class A
{
   public bool ProprertyDummy
   {
      get;
      set;
   }
}

class B
{
   void method()
   {
      A obj1 = new A();
      //Set and get obj1.ProprertyDummy
      //Share the PropertyDummy with method of class C
   }
}

class C
{
   void method()
   {
      A obj2 = new A();
      //Set and get obj2.ProprertyDummy
      //Share the PropertyDummy with method of class B
   }
}

class D
{
   void method()
   {
      A obj3 = new A();
      //Set and get obj3.ProprertyDummy
      //Should not affect the property PropertyDummy shared by methods of class B and C
   }
}
</code>```

Now what I want to do is share property of class A i.e PropertyDummy among methods of class B and C but not D. The sequence in which the methods from different classes will execute is not defined and there might even be calls from one class method to other class method.

Note : I only want to share the property PropertyDummy and not the other members of class A among B and C.

Can anyone suggest some way to achieve what I am trying to do. Any help is appreciated.

For example now let us consider a class Text having a property Visibility. Now two different classes TextNumbers and TextAlphabets that contain a object of Text(not inherit) want to share the property so that change in 1 will be reflected in other. However there is no defined sequence for their use.
Now other class TextSymbols also have object of Text but does not share the property.

答: since ob1,obj2 and obj3 are 3 different instances of class A ,the property will not get affected to each other in any way ,i guess</p>

Body:
Ok so I am working with code that looks something like this,

class A
{
   public bool ProprertyDummy
   {
      get;
      set;
   }
}

class B
{
   void method()
   {
      A obj1 = new A();
      //Set and get obj1.ProprertyDummy
      //Share the PropertyDummy with method of class C
   }
}

class C
{
   void method()
   {
      A obj2 = new A();
      //Set and get obj2.ProprertyDummy
      //Share the PropertyDummy with method of class B
   }
}

class D
{
   void method()
   {
      A obj3 = new A();
      //Set and get obj3.ProprertyDummy
      //Should not affect the property PropertyDummy shared by methods of class B and C
   }
}

Now what I want to do is share property of class A i.e PropertyDummy among methods of class B and C but not D. The sequence in which the methods from different classes will execute is not defined and there might even be calls from one class method to other class method.

Note : I only want to share the property PropertyDummy and not the other members of class A among B and C.

Can anyone suggest some way to achieve what I am trying to do. Any help is appreciated.

For example now let us consider a class Text having a property Visibility. Now two different classes TextNumbers and TextAlphabets that contain a object of Text(not inherit) want to share the property so that change in 1 will be reflected in other. However there is no defined sequence for their use.
Now other class TextSymbols also have object of Text but does not share the property.


问:
how to define a Scala function that takes multiple return values
I want to write a generic function that returns both session(Cassandra database) and connection(MySQL) is it possible?

Here is my code:

```<code>def getdb: Session = {
    var cluster = Cluster.builder().addContactPoint("127.0.0.1").build()
    var session: Session = cluster.connect("keyspace")
    if (session.getState != null) {
      currentDB = "cassandra"
      return session
      }
      else{
      //code for mysql connection
      return Connection
      }
}
</code>```

How should I define my function such that get db should return to whichever it is connected.

答:
Before trying to solve this problem from syntax/return type point of view, I would think about two other points:

System architecture. Do you really need two storage systems which are discovered dynamically by your application? Just wondering, what is a practical use case for such scenario.

Application architecture. If you really need to support two storage types, try to hide specific details behind common interface (trait). Then your method return type will be of interface type and it will return particular implementation.

Body:
I want to write a generic function that returns both session(Cassandra database) and connection(MySQL) is it possible?

Here is my code:

def getdb: Session = {
    var cluster = Cluster.builder().addContactPoint("127.0.0.1").build()
    var session: Session = cluster.connect("keyspace")
    if (session.getState != null) {
      currentDB = "cassandra"
      return session
      }
      else{
      //code for mysql connection
      return Connection
      }
}

How should I define my function such that get db should return to whichever it is connected.


问:
Qt Command Pattern QHash/QMap
I've recently implemented a command design pattern in Java with the use of:

```<code>private HashMap<Component, CommandInterface> commands;
</code>```

Where Component is any Java Component (JButton, JMenuItem, ...) and CommandInterface is an interface for my Command-Classes.

So my question is: How can I accomplish this with C++/Qt ?

I've already used QMap and QHash, but both of them need an overloaded operator (operator< or operator==) for their Key-values.

Is the only possible way to derive from QObject and overload operator< ?

Thanks in advance.

答:
One very important difference between Java and C++ is that C++ makes a distinction between an object pointer (reference in Java) QObject* o; and an object value QObject o;

That being said, Qt strongly encourages to create the QObject on the heap (using new). So you end up with QObject pointers QObject*. Then your hashmap will work because comparing the pointers is like comparing integers.

```<code>QHash<QObject*, CommandInterface*> commands;
</code>```

Do not forget to manage the lifetime of your objects though, you do not have a garbage collector like in Java. You can use the Qt tree ownership for convenience, depending on your needs : http://doc.qt.io/qt-5/objecttrees.html

Title: Qt Command Pattern QHash/QMap

Body:
I've recently implemented a command design pattern in Java with the use of:

private HashMap<Component, CommandInterface> commands;

Where Component is any Java Component (JButton, JMenuItem, ...) and CommandInterface is an interface for my Command-Classes.

So my question is: How can I accomplish this with C++/Qt ?

I've already used QMap and QHash, but both of them need an overloaded operator (operator< or operator==) for their Key-values.

Is the only possible way to derive from QObject and overload operator< ?

Thanks in advance.

Body:
One very important difference between Java and C++ is that C++ makes a distinction between an object pointer (reference in Java) QObject* o; and an object value QObject o;

That being said, Qt strongly encourages to create the QObject on the heap (using new). So you end up with QObject pointers QObject*. Then your hashmap will work because comparing the pointers is like comparing integers.

QHash<QObject*, CommandInterface*> commands;

Do not forget to manage the lifetime of your objects though, you do not have a garbage collector like in Java. You can use the Qt tree ownership for convenience, depending on your needs : http://doc.qt.io/qt-5/objecttrees.html


问:
how to set single custom validation message for multiple input field?
```<code>public function rules(Request $request)
{
  if ($request->isMethod('POST')) {
    return [
      "skill" => "required|array",
      "skillyear.*" => "required_with:skill|numeric",
    ];
  }
 public function messages()
{
 return [
     'skill.required'=>'Select at least one skill',
     'skillyear.*.required_with'=>"Experience year is required for the selected skill"
];}
</code>```

so, for each field i'm getting message like this
enter image description here
how can I get only one message for all these.

答:
Change as below. Add a new element as skillyears and you you will get error in skillyears, to get single error

```<code>public function rules(Request $request)
{
  if ($request->isMethod('POST')) {
    $request->skillyears = count($request->skillyear);
    return [
      "skill" => "required|array",
      "skillyear.*" => "numeric",
      "skillyears" => "required_with:skill|min:1"
    ];
  }
 public function messages()
{
 return [
     'skill.required'=>'Select at least one skill',
     'skillyears.min' => "Experience year is required for the selected skill",
];}
</code>```

May be it is not exact but you can get idea to make as you want

Body:
public function rules(Request $request)
{
  if ($request->isMethod('POST')) {
    return [
      "skill" => "required|array",
      "skillyear.*" => "required_with:skill|numeric",
    ];
  }
 public function messages()
{
 return [
     'skill.required'=>'Select at least one skill',
     'skillyear.*.required_with'=>"Experience year is required for the selected skill"
];}

so, for each field i'm getting message like this
enter image description here
how can I get only one message for all these.

Body:
Change as below. Add a new element as skillyears and you you will get error in skillyears, to get single error

public function rules(Request $request)
{
  if ($request->isMethod('POST')) {
    $request->skillyears = count($request->skillyear);
    return [
      "skill" => "required|array",
      "skillyear.*" => "numeric",
      "skillyears" => "required_with:skill|min:1"
    ];
  }
 public function messages()
{
 return [
     'skill.required'=>'Select at least one skill',
     'skillyears.min' => "Experience year is required for the selected skill",
];}

May be it is not exact but you can get idea to make as you want


问:
Detect functions with too long length (>100 lines)?
Is there any way to detect the functions in my Node App that are longer than 100 lines?
Im using JSHint but it doesnt have any option to detect it.</p>

答:
You can't do such a thing with jslint, according to the docs :

Warning This option has been deprecated and will be removed in the
  next major release of JSHint. JSHint is limiting its scope to issues
  of code correctness. If you would like to enforce rules relating to
  code style, check out the JSCS project. This option lets you set the
  maximum length of a line.

the poperty maxlen is deprecated you don't have to rely on it


答:
You can use eslint and use the max-statements option to allow a maximum number of lines in a function

Link : https://eslint.org/docs/rules/max-statements

Title: Detect functions with too long length (>100 lines)?

Body:
Is there any way to detect the functions in my Node App that are longer than 100 lines?
Im using JSHint but it doesnt have any option to detect it.


问:
JSF, Primefaces Tree onNodeClick with GET
I have a tree (p:tree) and I would like to GET (no POST) the whole page after each node selection. How can I do it ?</p>

```<code><p:tree ... >
 <p:ajax event="select" listener="#{tree.onNodeSelect}"/>
 <p:treeNode ... >
  ....
</p:tree>
</code>```

答:
It does remember the selected nod programmatically, but it doesn't reflect visually on the tree, that means the tree doesn't highlight the selected node once it was re-rendered.

and another issue is that, after re-render the
 component, the tree will be totally folded up.

I think this is related..

Body:
I have a tree (p:tree) and I would like to GET (no POST) the whole page after each node selection. How can I do it ?

  ....

Body:
It does remember the selected nod programmatically, but it doesn't reflect visually on the tree, that means the tree doesn't highlight the selected node once it was re-rendered.

and another issue is that, after re-render the <p:tree> component, the tree will be totally folded up.

I think this is related..


问:
How can I style a text field in iOS (Swift)?
I am a beginner and just started learning iOS. I want to achieve this layout, using Swift:

答:
you can add a view container to your view, inside that container .. add a button and a textfield then add positioning constraints on them.

as you can see in the picture .. it illustrates the idea .. you can style it the way you want e.g. change the height of your textfield .. change its border style etc. the same with your button.

example


问:
Using mathematics in jquery to hide/show backgrounds with animation
Good evening, I am tired and have been fighting with this for hours. I am using a sample I found and altering it for my needs. It uses jquery.bgpos.js to create a sliding background that changes behind another layer (the navigation) when the mouse is passed over it. It uses positioning and some inline styles in the page and I cannot get things to match up right.

My example is shown here. When you hover over the text tabs, the background changes but do not position themselves correctly because, well, I have screwed it up. I hate to post all this code here but I am running out of time and only seek someone with a better understanding to correct my errors. Thanks.

Here's the html for the menu with background:

```<code><div id="menuWrapper" class="menuWrapper bg1">
                <ul class="menu" id="menu">
                    <li class="bg1" style="background-position:0 0;">
                        <a id="bg1" href="#">Home</a>
                        <ul class="sub1" style="background-position:0 0;">
                            <li><a href="#">Story</a></li>
                            <li><a href="#">Profile</a></li>
                            <li><a href="#">Discography</a></li>
                        </ul>
                    </li>
                    <li class="bg1" style="background-position:-163px 0px;">
                        <a id="bg2" href="#">News</a>
                        <ul class="sub2" style="background-position:-163px 0;">
                            <li><a href="#">Submenu 1</a></li>
                            <li><a href="#">Submenu 2</a></li>
                            <li><a href="#">Submenu 3</a></li>
                        </ul>
                    </li>
                    <li class="bg1" style="background-position:-299px 0px;">
                        <a id="bg3" href="#">The Band </a>
                        <ul class="sub3" style="background-position:-163px 0;">
                            <li><a href="#">Submenu 1</a></li>
                            <li><a href="#">Submenu 2</a></li>
                            <li><a href="#">Submenu 3</a></li>
                      </ul>
                  </li>
                  <li class="bg1" style="background-position:-449px 0px;">
                        <a id="bg4" href="#">Shows </a>
                        <ul class="sub4" style="background-position:-163px 0;">
                            <li><a href="#">Submenu 1</a></li>
                            <li><a href="#">Submenu 2</a></li>
                            <li><a href="#">Submenu 3</a></li>
                      </ul>
                  </li>
                    <li class="bg1" style="background-position:-599px 0px;">
                        <a id="bg5" href="#">The Music</a>
                        <ul class="sub5" style="background-position:-163px 0;">
                            <li><a href="#">Submenu 1</a></li>
                            <li><a href="#">Submenu 2</a></li>
                            <li><a href="#">Submenu 3</a></li>
                        </ul>
                    </li>
                    <li class="last bg1" style="background-position:-754px 0px;">
                        <a id="bg6" href="#">Videos</a>
                        <ul class="sub6" style="background-position:-163px 0;">
                            <li><a href="#">Submenu 1</a></li>
                            <li><a href="#">Submenu 2</a></li>
                            <li><a href="#">Submenu 3</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
</code>```

And here's the css:

```<code>/* MENU */
.menuWrapper{
    font-family: "Bebas Neue", Arial, Helvetica, sans-serif;
    font-style: normal;
    font-weight: normal;
    text-transform:uppercase;
    letter-spacing: normal;
    line-height: 1.45em;
    height:485px;
    width:980px;
    background-position:0 0;
    background-repeat:no-repeat;
    background-color:transparent;
    margin-top: 0px;
    margin-right: 10px;
    margin-bottom: 0px;
    margin-left: 10px;
    float: left;
}
ul.menu{
    list-style:none;
    width:980px;
}
ul.menu > li{
    float:left;
    width:163px;
    height:542px;
    background-repeat:repeat-x;
    background-color:transparent;
}
ul.menu > li.last{
    border:none;
}
.bg1{
    background-image: url(../images/1.jpg);
}
.bg2{
    background-image: url(../images/2.jpg);
}
.bg3{
    background-image: url(../images/3.jpg);
}
.bg4{
    background-image: url(../images/4.jpg);
}
.bg5{
    background-image: url(../images/5.jpg);
}
.bg6{
    background-image: url(../images/6.jpg);
}
ul.menu > li > a{
    float:left;
    width:163px;
    height:50px;
    text-align:center;
    line-height:1.5em;
    color:#FFF;
    background-color:#000;
    letter-spacing:1px;
    cursor:pointer;
    text-decoration:none;
    font-size: 2.25em;
}
ul.menu > li ul{
    list-style:none;
    float:left;
    margin-top:0px;
    width:100%;
    height:110px;
    padding-top:20px;
    background-repeat:no-repeat;
    background-color:transparent;
}
ul.menu > li ul li{
    display:none;
}
ul.menu > li ul.sub1{
    background-image:url(../images/bg1sub.png);
}
ul.menu > li ul.sub2{
    background-image:url(../images/bg2sub.png);
}
ul.menu > li ul.sub3{
    background-image:url(../images/bg3sub.png);
}
ul.menu > li ul.sub4{
    background-image:url(../images/bg1sub.png);
}
ul.menu > li ul.sub5{
    background-image:url(../images/bg2sub.png);
}
ul.menu > li ul.sub6{
    background-image:url(../images/bg3sub.png);
}
ul.menu > li ul li a{
    color:#fff;
    text-decoration:none;
    line-height:1.25em;
    margin-left:20px;
    font-size:1.5em;
    width: 163px;
}
ul.menu > li ul.sub1 li{
    display:block;
}
ul.menu > li ul li a:hover{

}
</code>```

Finally, here's the js within my page (the part that's kicking my but)

```<code><script type="text/javascript">
    $(function() {
    /* position of the <li> that is currently shown */
    var current = 0;

    var loaded  = 0;
    for(var i = 1; i <4; ++i)
    $('<img />').load(function(){
    ++loaded;
    if(loaded == 3){
    $('#bg1,#bg2,#bg3,#bg4,#bg5,#bg6').mouseover(function(e){

    var $this = $(this);
    /* if we hover the current one, then don't do anything */
    if($this.parent().index() == current)
    return;

    /* item is bg1 or bg2 or bg3, depending where we are hovering */
    var item = e.target.id;

    /*
    this is the sub menu overlay. Let's hide the current one if we hover the first <li> or if we come from the last one, then the overlay should move left -> right, otherwise right->left
    */
    if(item == 'bg1' || current == 5)
    $('#menu .sub'+parseInt(current+1)).stop().animate({backgroundPosition:"(-489px 0)"},300,function(){
    $(this).find('li').hide();
    });
    else
    $('#menu .sub'+parseInt(current+1)).stop().animate({backgroundPosition:"(163px 0)"},300,function(){
    $(this).find('li').hide();
    });

    if(item == 'bg1' || current == 5){
    /* if we hover the first <li> or if we come from the last one, then the images should move left -> right */
    $('#menu > li').animate({backgroundPosition:"(-1000px 0)"},0).removeClass('bg1 bg2 bg3 bg4 bg5 bg6').addClass(item);
    move(1,item);
    }
    else{
    /* if we hover the first <li> or if we come from the last one, then the images should move right -> left */
    $('#menu > li').animate({backgroundPosition:"(1000px 0)"},0).removeClass('bg1 bg2 bg3 bg4 bg5 bg6').addClass(item);
    move(0,item);
    }

    /*
    We want that if we go from the first one to the last one (without hovering the middle one), or from the last one to the first one, the middle menu's overlay should also slide, either from left to right or right to left.
    */
    if(current == 5 && item == 'bg1'){
    $('#menu .sub'+parseInt(current)).stop().animate({backgroundPosition:"(-163px 0)"},300);
    }
    if(current == 0 && item == 'bg6'){
    $('#menu .sub'+parseInt(current+5)).stop().animate({backgroundPosition:"(163px 0)"},300);
    }

    /* change the current element */
    current = $this.parent().index();

    /* let's make the overlay of the current one appear */

    $('#menu .sub'+parseInt(current+1)).stop().animate({backgroundPosition:"(0 0)"},300,function(){
    $(this).find('li').fadeIn();
    });
    });
    }
    }).attr('src', 'images/'+i+'.jpg');

    /*
    dir:1 - move left->right
    dir:0 - move right->left
    */
    function move(dir,item){
    if(dir){
    $('#bg1').parent().stop().animate({backgroundPosition:"(0 0)"},200);
    $('#bg2').parent().stop().animate({backgroundPosition:"(-163px 0)"},300);
    $('#bg3').parent().stop().animate({backgroundPosition:"(-326px 0)"},400);
    $('#bg4').parent().stop().animate({backgroundPosition:"(-489px 0)"},500);
    ('#bg5').parent().stop().animate({backgroundPosition:"(-652px 0)"},600);
    $('#bg6').parent().stop().animate({backgroundPosition:"(-815px 0)"},700,function(){
    $('#menuWrapper').removeClass('bg1 bg2 bg3 bg4 bg5 bg6').addClass(item);
    });
    }
    else{
    $('#bg1').parent().stop().animate({backgroundPosition:"(0 0)"},700,function(){
    $('#menuWrapper').removeClass('bg1 bg2 bg3 bg4 bg5 bg6').addClass(item);
    });
    $('#bg2').parent().stop().animate({backgroundPosition:"(-163px 0)"},600);
    $('#bg3').parent().stop().animate({backgroundPosition:"(-326px 0)"},500);
    $('#bg4').parent().stop().animate({backgroundPosition:"(-489px 0)"},400);
    $('#bg5').parent().stop().animate({backgroundPosition:"(-652px 0)"},300);
    $('#bg6').parent().stop().animate({backgroundPosition:"(-815px 0)"},200);
    }
    }
    });
    </script>
</code>```

答:
I'm still a little unsure of what your problems is. when I initially look at the page the backgrounds are screwed up but after I start mousing over things then it actually makes them line up.

The reason that they don't look right initially is probably related to the fact that the UL.subN initial background position is -163px 0. However, when you are changing it programatically for "mouseout" you are setting it to -489px. I suspect if you started with them all at -489px then it would work.

I hope this is helpful but if not maybe some a screenshot of the bit of page that looks wrong to you.

Body:
Good evening, I am tired and have been fighting with this for hours. I am using a sample I found and altering it for my needs. It uses jquery.bgpos.js to create a sliding background that changes behind another layer (the navigation) when the mouse is passed over it. It uses positioning and some inline styles in the page and I cannot get things to match up right.

My example is shown here. When you hover over the text tabs, the background changes but do not position themselves correctly because, well, I have screwed it up. I hate to post all this code here but I am running out of time and only seek someone with a better understanding to correct my errors. Thanks.

Here's the html for the menu with background:

                        Home

Story

Profile

Discography

                        News

Submenu 1

Submenu 2

Submenu 3

                        The Band

Submenu 1

Submenu 2

Submenu 3

                        Shows

Submenu 1

Submenu 2

Submenu 3

                        The Music

Submenu 1

Submenu 2

Submenu 3

                        Videos

Submenu 1

Submenu 2

Submenu 3

And here's the css:

/* MENU */
.menuWrapper{
    font-family: "Bebas Neue", Arial, Helvetica, sans-serif;
    font-style: normal;
    font-weight: normal;
    text-transform:uppercase;
    letter-spacing: normal;
    line-height: 1.45em;
    height:485px;
    width:980px;
    background-position:0 0;
    background-repeat:no-repeat;
    background-color:transparent;
    margin-top: 0px;
    margin-right: 10px;
    margin-bottom: 0px;
    margin-left: 10px;
    float: left;
}
ul.menu{
    list-style:none;
    width:980px;
}
ul.menu > li{
    float:left;
    width:163px;
    height:542px;
    background-repeat:repeat-x;
    background-color:transparent;
}
ul.menu > li.last{
    border:none;
}
.bg1{
    background-image: url(../images/1.jpg);
}
.bg2{
    background-image: url(../images/2.jpg);
}
.bg3{
    background-image: url(../images/3.jpg);
}
.bg4{
    background-image: url(../images/4.jpg);
}
.bg5{
    background-image: url(../images/5.jpg);
}
.bg6{
    background-image: url(../images/6.jpg);
}
ul.menu > li > a{
    float:left;
    width:163px;
    height:50px;
    text-align:center;
    line-height:1.5em;
    color:#FFF;
    background-color:#000;
    letter-spacing:1px;
    cursor:pointer;
    text-decoration:none;
    font-size: 2.25em;
}
ul.menu > li ul{
    list-style:none;
    float:left;
    margin-top:0px;
    width:100%;
    height:110px;
    padding-top:20px;
    background-repeat:no-repeat;
    background-color:transparent;
}
ul.menu > li ul li{
    display:none;
}
ul.menu > li ul.sub1{
    background-image:url(../images/bg1sub.png);
}
ul.menu > li ul.sub2{
    background-image:url(../images/bg2sub.png);
}
ul.menu > li ul.sub3{
    background-image:url(../images/bg3sub.png);
}
ul.menu > li ul.sub4{
    background-image:url(../images/bg1sub.png);
}
ul.menu > li ul.sub5{
    background-image:url(../images/bg2sub.png);
}
ul.menu > li ul.sub6{
    background-image:url(../images/bg3sub.png);
}
ul.menu > li ul li a{
    color:#fff;
    text-decoration:none;
    line-height:1.25em;
    margin-left:20px;
    font-size:1.5em;
    width: 163px;
}
ul.menu > li ul.sub1 li{
    display:block;
}
ul.menu > li ul li a:hover{

}

Finally, here's the js within my page (the part that's kicking my but)