问:
identify live spark master at the time of spark-submit
I have 5 node spark cluster where 2 node are running master. in HA(by Zookeeper) scenario any one will be elected as master.</p>

```<code>at the time of submitting application using command

/bin/spark-submit  --class SparkAggregator.java --deploy-mode cluster --supervise --master spark://host1:7077

getting error
Can only accept driver submissions in ALIVE state. Current state: STANDBY.

spark-submit doe not allow multiple master name in --master.

Question:
How to identify the elected master at the time of spark-submit.

Thanks
Pankaj
</code>```

Body:
I have 5 node spark cluster where 2 node are running master. in HA(by Zookeeper) scenario any one will be elected as master.

at the time of submitting application using command

/bin/spark-submit  --class SparkAggregator.java --deploy-mode cluster --supervise --master spark://host1:7077

getting error
Can only accept driver submissions in ALIVE state. Current state: STANDBY.

spark-submit doe not allow multiple master name in --master.

Question:
How to identify the elected master at the time of spark-submit.

Thanks
Pankaj

Body:
Spark has a hidden API which tell you about the status of the Spark Cluster

API Request- http://SPARK_MASTER_IP:8080/json/

Output -

    {
  "url" : "spark://10.204.216.233:7077",
  "workers" : [ {
    "id" : "worker-20170606104140-10.204.217.96-40047",
    "host" : "10.204.217.96",
    "port" : 40047,
    "webuiaddress" : "http://10.204.217.96:8081",
    "cores" : 4,
    "coresused" : 0,
    "coresfree" : 4,
    "memory" : 29713,
    "memoryused" : 0,
    "memoryfree" : 29713,
    "state" : "ALIVE",
    "lastheartbeat" : 1496760671542
  }, {
    "id" : "worker-20170606104144-10.204.219.15-42749",
    "host" : "10.204.219.15",
    "port" : 42749,
    "webuiaddress" : "http://10.204.219.15:8081",
    "cores" : 4,
    "coresused" : 0,
    "coresfree" : 4,
    "memory" : 29713,
    "memoryused" : 0,
    "memoryfree" : 29713,
    "state" : "ALIVE",
    "lastheartbeat" : 1496760675649
  }, {
    "id" : "worker-20170606104151-10.204.217.249-35869",
    "host" : "10.204.217.249",
    "port" : 35869,
    "webuiaddress" : "http://10.204.217.249:8081",
    "cores" : 4,
    "coresused" : 0,
    "coresfree" : 4,
    "memory" : 29713,
    "memoryused" : 0,
    "memoryfree" : 29713,
    "state" : "ALIVE",
    "lastheartbeat" : 1496760682270
  } ],
  "cores" : 12,
  "coresused" : 0,
  "memory" : 89139,
  "memoryused" : 0,
  "activeapps" : [ ],
  "completedapps" : [ ],
  "activedrivers" : [ ],
  "status" : "ALIVE"
}


来源: stackexchange

问:
ffmpeg VBR -> CBR conversion and streaming of MPEG-2 TS video files
I am trying to convert a source VBR SPTS MPEG-2 TS file into CBR using ffmpeg. The code I am using is the following:

```<code>#!/bin/bash

pkill ffmpeg

ffmpeg \
        -re -i source.ts -c copy \
        -muxrate 18000K \
        -f mpegts \
        udp://destination_ip:1234?pkt_size=1316
</code>```

The source VPID bitrate is ~ 10Mbps and the APID is 296Kbps. So according to my understanding this code should deliver 18Mbps CBR where the difference between the muxrate and the bitrate of all the PIDs is filled with null packets.

The problem is that the output is far from perfect. The overall bitrate is semi-CBR at best. It ranges between 12Mbps and 15Mbps and I see a lot of PCR accuracy and PCR repetition errors along with CC errors both on the VPID and APID.

答:
Some ideas:

make sure you have a recent version of ffmpeg because at some point there was a bug which messed up PCR insertion when stream copying

if you want constant UDP output you must use the bitrate option like:

```<code>-flush_packets 0 -f mpegts "udp://destination_ip:1234?pkt_size=1316&bitrate=18000000"
</code>```

UDP is an unreliable protocol and you might experience packet loss (unfortunately the bitrate option only works for UDP for now AFAIK)

if you have a dedicated connection but still experience CC errors check the destination OS max UDP buffer sizes and make sure it can handle 18 Mbps

ContentLicense: CC BY-SA 3.0

Body:
I am trying to convert a source VBR SPTS MPEG-2 TS file into CBR using ffmpeg. The code I am using is the following:

#!/bin/bash

pkill ffmpeg

ffmpeg \
        -re -i source.ts -c copy \
        -muxrate 18000K \
        -f mpegts \
        udp://destination_ip:1234?pkt_size=1316

The source VPID bitrate is ~ 10Mbps and the APID is 296Kbps. So according to my understanding this code should deliver 18Mbps CBR where the difference between the muxrate and the bitrate of all the PIDs is filled with null packets.

The problem is that the output is far from perfect. The overall bitrate is semi-CBR at best. It ranges between 12Mbps and 15Mbps and I see a lot of PCR accuracy and PCR repetition errors along with CC errors both on the VPID and APID.

Body:
Some ideas:

make sure you have a recent version of ffmpeg because at some point there was a bug which messed up PCR insertion when stream copying

if you want constant UDP output you must use the bitrate option like:

-flush_packets 0 -f mpegts "udp://destination_ip:1234?pkt_size=1316&bitrate=18000000"

UDP is an unreliable protocol and you might experience packet loss (unfortunately the bitrate option only works for UDP for now AFAIK)

if you have a dedicated connection but still experience CC errors check the destination OS max UDP buffer sizes and make sure it can handle 18 Mbps


问:
navigation menu top and bottom,no drop up at the bottom

<!DOCTYPE html>

    Sales

      Link 1
      Link 2
      Link 3

    Search

      Link 1
      Link 2
      Link 3

    Transfers

      Link 1
      Link 2
      Link 3

   Returns

      Link 1
      Link 2
      Link 3

<ulf>
<lif class="dropup">
    Order

      Link 1
      Link 2
      Link 3

  </lif>
<lif class="dropup">
    Reports

      Link 1
      Link 2
      Link 3

  </lif>
  <lif class="dropup">
    Exports/Imports

      Link 1
      Link 2
      Link 3

  </lif>
   <lif class="dropup">
   Settings

      Link 1
      Link 2
      Link 3

 </lif>

</ulf>

```

The top navigation is working properly. I mean the drop down is functional,but the bottom navigation isn't working. I want to do something like drop up. Can someone please check the code and give me some instruction on what i have to do?

答:
You just need to remove position: absolute; from .dropup-content, and replace it with this CSS:

```<code>  position: fixed;
  bottom: 47px;
</code>```

And and Bob's your uncle!

ulf {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  position: fixed;
  bottom: 0%;
  width: 100%;
}
lif {
  float: left;
  border-right: 1px solid #bbb;
}
lif a, .dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}
lif a:hover, .dropup:hover .dropbtn {
  background-color: red;
}
lif.dropup {
  display: inline-block;
}
.dropup-content {
  display: none;
  position: fixed;
  bottom: 47px;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}
.dropup-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}
.dropup-content a:hover {
  background-color: #f1f1f1
}
.dropup:hover .dropup-content {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<style>
</style>
<style>
</style>
</head>
<body>
<ulf>
<lif class="dropup">
    Order
    <div class="dropup-content">
      Link 1
      Link 2
      Link 3
    </div>
  </lif>
<lif class="dropup">
    Reports
    <div class="dropup-content">
      Link 1
      Link 2
      Link 3
    </div>
  </lif>
  <lif class="dropup">
    Exports/Imports
    <div class="dropup-content">
      Link 1
      Link 2
      Link 3
    </div>
  </lif>
   <lif class="dropup">
   Settings
     <div class="dropup-content">
      Link 1
      Link 2
      Link 3
    </div>
 </lif>

</ulf>

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

CodePen example:

Body:
<!DOCTYPE html>

    Sales

      Link 1
      Link 2
      Link 3

    Search

      Link 1
      Link 2
      Link 3

    Transfers

      Link 1
      Link 2
      Link 3

   Returns

      Link 1
      Link 2
      Link 3

<ulf>
<lif class="dropup">
    Order

      Link 1
      Link 2
      Link 3

  </lif>
<lif class="dropup">
    Reports

      Link 1
      Link 2
      Link 3

  </lif>
  <lif class="dropup">
    Exports/Imports

      Link 1
      Link 2
      Link 3

  </lif>
   <lif class="dropup">
   Settings

      Link 1
      Link 2
      Link 3

 </lif>

</ulf>

The top navigation is working properly. I mean the drop down is functional,but the bottom navigation isn't working. I want to do something like drop up. Can someone please check the code and give me some instruction on what i have to do?

Body:
You just need to remove position: absolute; from .dropup-content, and replace it with this CSS:

  position: fixed;
  bottom: 47px;

And and Bob's your uncle!

ulf {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  position: fixed;
  bottom: 0%;
  width: 100%;
}
lif {
  float: left;
  border-right: 1px solid #bbb;
}
lif a, .dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}
lif a:hover, .dropup:hover .dropbtn {
  background-color: red;
}
lif.dropup {
  display: inline-block;
}
.dropup-content {
  display: none;
  position: fixed;
  bottom: 47px;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}
.dropup-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}
.dropup-content a:hover {
  background-color: #f1f1f1
}
.dropup:hover .dropup-content {
  display: block;
}

<!DOCTYPE html>
<html>
<head>
<style>
</style>
<style>
</style>
</head>
<body>
<ulf>
<lif class="dropup">
    <a href="javascript:void(0)" class="dropbtn">Order</a>
    <div class="dropup-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </lif>
<lif class="dropup">
    <a href="javascript:void(0)" class="dropbtn">Reports</a>
    <div class="dropup-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </lif>
  <lif class="dropup">
    <a href="javascript:void(0)" class="dropbtn">Exports/Imports</a>
    <div class="dropup-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </lif>
   <lif class="dropup">
   <a href="javascript:void(0)" class="dropbtn">Settings</a>
     <div class="dropup-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
 </lif>

</ulf>

</body>
</html>

CodePen example:


问:
UIApplication.registerForRemoteNotifications() must be called from main thread only
Xcode 9 (iOS 11) showing me an error/warning while registering for Push (remote) notification.

Here is error message

And here is code, I've tried:

```<code>let center  = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
        if error == nil{
              UIApplication.shared.registerForRemoteNotifications()
        }
 }
</code>```

Error/Warning Line:

UIApplication.shared.registerForRemoteNotifications()

How to resolve this?

答:
The error message is pretty clear: dispatch registerForRemoteNotifications to the main thread.

I would use the granted parameter and handle the error accordingly

```<code>center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
        if granted {
              DispatchQueue.main.async {
                  UIApplication.shared.registerForRemoteNotifications()
              }
        } else {
           print(error!)
           // handle the error
        }
}
</code>```

Body:
Xcode 9 (iOS 11) showing me an error/warning while registering for Push (remote) notification.

Here is error message

And here is code, I've tried:

let center  = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
        if error == nil{
              UIApplication.shared.registerForRemoteNotifications()
        }
 }

Error/Warning Line:

UIApplication.shared.registerForRemoteNotifications()

How to resolve this?

Body:
The error message is pretty clear: dispatch registerForRemoteNotifications to the main thread.

I would use the granted parameter and handle the error accordingly

center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
        if granted {
              DispatchQueue.main.async {
                  UIApplication.shared.registerForRemoteNotifications()
              }
        } else {
           print(error!)
           // handle the error
        }
}


问:
Condition in creating table
I want to put a condition on a certain field while creating a table.

This field have to be >20.

I tried this :

```<code>Create table tblvideos(
VideoID identity(1,1) primarykey,
Rental bigint default>20
);
</code>```

答:
you are looking for check constraint

```<code>Create table tblvideos(
VideoID identity(1,1) primarykey,
Rental bigint
CHECK (Rental >=20) );
</code>```

if you want name check constraint,you can do below

```<code>   Create table tblvideos(
    VideoID  int identity(1,1) primary key,
    Rental bigint,
   CONSTRAINT CHK_limt CHECK (rental>=20)
  );
</code>```

Title: Condition in creating table

Body:
I want to put a condition on a certain field while creating a table.

This field have to be >20.

I tried this :

Create table tblvideos(
VideoID identity(1,1) primarykey,
Rental bigint default>20
);

Body:
you are looking for check constraint

Create table tblvideos(
VideoID identity(1,1) primarykey,
Rental bigint
CHECK (Rental >=20) );

if you want name check constraint,you can do below

   Create table tblvideos(
    VideoID  int identity(1,1) primary key,
    Rental bigint,
   CONSTRAINT CHK_limt CHECK (rental>=20)
  );


问:
Css for header,section and footer arrangement
I have basic html code :

```<code><header></header>
<main>
<nav></nav>
<section></section>
</main>
<footer></footer>
</code>```

and I need css to have the header at the top, the footer at the bottom, the nav and the section between the header and footer, with the nav on the left and the section on the right.

As an example : https://fr.wikipedia.org/

But in the case where the main content is smaller than the screen size, I need to have the footer fixed on the bottom of the screen.

My CSS is something like that :

```<code>    header, nav, section, footer {
        padding: 1px 0;
    }

    header {
        background-color: lightcoral;
        text-align: center;
        background: #FF9900 url("/Content/Images/Etoile.png") 5px center no-repeat;
        background-size: 100px;
    }

    main {
        margin: auto;
    }

    nav {
        float: left;
        width: 15%;
        background-color: lightsalmon;
    }

    section {
        float : right;
        width : 85%;
        background-color: lightblue;
    }

    footer {
        background-color: lightgreen;
        text-align: center;
        clear: both;
    }
</code>```

Could you help me please ?

答:
What you're trying to do is create a simple page layout. You can check out this resource for general information about how to do this, since there are multiple ways.

An example taken from the above resource is using the CSS float property. It should give you enough to start with for your solution.

<!DOCTYPE html>

City Gallery

London

Paris

Tokyo

London

London is the capital city of England. It is the most populous city in the  United Kingdom, with a metropolitan area of over 13 million inhabitants.

Standing on the River Thames, London has been a major settlement for two millennia, its history going back to its founding by the Romans, who named it Londinium.

Copyright © W3Schools.com

```

Body:
I have basic html code :

and I need css to have the header at the top, the footer at the bottom, the nav and the section between the header and footer, with the nav on the left and the section on the right.

As an example : https://fr.wikipedia.org/

But in the case where the main content is smaller than the screen size, I need to have the footer fixed on the bottom of the screen.

My CSS is something like that :

    header, nav, section, footer {
        padding: 1px 0;
    }

    header {
        background-color: lightcoral;
        text-align: center;
        background: #FF9900 url("/Content/Images/Etoile.png") 5px center no-repeat;
        background-size: 100px;
    }

    main {
        margin: auto;
    }

    nav {
        float: left;
        width: 15%;
        background-color: lightsalmon;
    }

    section {
        float : right;
        width : 85%;
        background-color: lightblue;
    }

    footer {
        background-color: lightgreen;
        text-align: center;
        clear: both;
    }

Could you help me please ?

Body:
What you're trying to do is create a simple page layout. You can check out this resource for general information about how to do this, since there are multiple ways.

An example taken from the above resource is using the CSS float property. It should give you enough to start with for your solution.

<!DOCTYPE html>
<html>
<head>
<style>
div.container {
    width: 100%;
    border: 1px solid gray;
}

header, footer {
    padding: 1em;
    color: white;
    background-color: black;
    clear: left;
    text-align: center;
}

nav {
    float: left;
    max-width: 160px;
    margin: 0;
    padding: 1em;
}

nav ul {
    list-style-type: none;
    padding: 0;
}

nav ul a {
    text-decoration: none;
}

article {
    margin-left: 170px;
    border-left: 1px solid gray;
    padding: 1em;
    overflow: hidden;
}
</style>
</head>
<body>

<div class="container">

<header>
   <h1>City Gallery</h1>
</header>

<nav>
  <ul>
    <li><a href="#">London</a></li>
    <li><a href="#">Paris</a></li>
    <li><a href="#">Tokyo</a></li>
  </ul>
</nav>

<article>
  <h1>London</h1>
  <p>London is the capital city of England. It is the most populous city in the  United Kingdom, with a metropolitan area of over 13 million inhabitants.</p>
  <p>Standing on the River Thames, London has been a major settlement for two millennia, its history going back to its founding by the Romans, who named it Londinium.</p>
</article>

<footer>Copyright &copy; W3Schools.com</footer>

</div>

</body>
</html>


问:
Graphql resolve function on nested fields not getting called
With this query, in graphQL, the resolve function on desiredSubfield is not getting called, and the query returns null.  How can I properly resolve a nested field?

Query:

```<code>{
    "query": "query ($requiredArg: String!, $anotherArg: String) { user(requiredArg: $requiredArg) { desiredSubfield(anotherArg: $anotherArg) { _id name} } }",
    "variables": {
        "requiredArg": "someString",
        "anotherArg": "anotherString"
    }
}
</code>```

Associated Object:

```<code>export default {
  type: userType,
  args: {
    requiredArg: {
      name: 'requiredArg',
      type: new GraphQLNonNull(GraphQLString),
    },
  fields: () => {
    return {
      desiredSubfield: {
        type: subfieldType,
        args: subfieldType.args,
        resolve(source, params, root, ast) {
          console.log('subfield resolve is hit');
          return fetchUser();
        },
      },
    };
  },
  resolve(source, params, root, ast) {
    console.log('in main resolve');
  }
};
</code>```

答:
Well, looks like I figured it out (sigh)

Problem is the dummy resolve function I wrote for the non-nested fields didn't return. Behold the fix:

```<code>export default {
  type: userType,
  args: {
    requiredArg: {
      name: 'requiredArg',
      type: new GraphQLNonNull(GraphQLString),
    },
  fields: () => {
    return {
      desiredSubfield: {
        type: subfieldType,
        args: subfieldType.args,
        resolve(source, params, root, ast) {
          console.log('subfield resolve is hit');
          return fetchUser();
        },
      },
    };
  },
  resolve(source, params, root, ast) {
    console.log('in main resolve');
    return true;
  }
};
</code>```

I'll leave this here in case anyone else runs into the same thing.

Body:
With this query, in graphQL, the resolve function on desiredSubfield is not getting called, and the query returns null.  How can I properly resolve a nested field?

Query:

{
    "query": "query ($requiredArg: String!, $anotherArg: String) { user(requiredArg: $requiredArg) { desiredSubfield(anotherArg: $anotherArg) { _id name} } }",
    "variables": {
        "requiredArg": "someString",
        "anotherArg": "anotherString"
    }
}

Associated Object:

export default {
  type: userType,
  args: {
    requiredArg: {
      name: 'requiredArg',
      type: new GraphQLNonNull(GraphQLString),
    },
  fields: () => {
    return {
      desiredSubfield: {
        type: subfieldType,
        args: subfieldType.args,
        resolve(source, params, root, ast) {
          console.log('subfield resolve is hit');
          return fetchUser();
        },
      },
    };
  },
  resolve(source, params, root, ast) {
    console.log('in main resolve');
  }
};

Body:
Well, looks like I figured it out (sigh)

Problem is the dummy resolve function I wrote for the non-nested fields didn't return. Behold the fix:

export default {
  type: userType,
  args: {
    requiredArg: {
      name: 'requiredArg',
      type: new GraphQLNonNull(GraphQLString),
    },
  fields: () => {
    return {
      desiredSubfield: {
        type: subfieldType,
        args: subfieldType.args,
        resolve(source, params, root, ast) {
          console.log('subfield resolve is hit');
          return fetchUser();
        },
      },
    };
  },
  resolve(source, params, root, ast) {
    console.log('in main resolve');
    return true;
  }
};

I'll leave this here in case anyone else runs into the same thing.


问:
How to declare a fixed size for an array in C++
Quick and stupid question.
How do I declare the size for an array if I'm not allowed to use global variables?

Suppose I have the file Album.h:

```<code>class Album {
private:
    Song songs[MAX_SONGS];

    //...

}
</code>```

where do I put MAX_SONGS = 30?
const int MAX_SONGS = 30
is considered a variable right?
Please notice that the size should be known to the entire program.

答:
To avoid static usage, use enum:

```<code>class Album {
    private:
        enum { MAX_SONGS = 30 };
        Song songs[MAX_SONGS];

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

Body:
Quick and stupid question.
How do I declare the size for an array if I'm not allowed to use global variables?

Suppose I have the file Album.h:

class Album {
private:
    Song songs[MAX_SONGS];

    //...

}

where do I put MAX_SONGS = 30?
const int MAX_SONGS = 30
is considered a variable right?
Please notice that the size should be known to the entire program.

Body:
To avoid static usage, use enum:

class Album {
    private:
        enum { MAX_SONGS = 30 };
        Song songs[MAX_SONGS];

        //...
    }


问:
How do I show flip effect in flex viewstate?
I'm new to Flex.

I want to build cool web application in flex.

For displaying content of my site, I use viewstack and button bar. It is ready, but now I'd like to add some animation effect in that.

For example changing the navigation content shows flip animation.
So how do I do that?

Help full link.

答: That example shows the most basic kind of animation which is readily available using open and widely supported web-standards such as HTML, CSS, and JavaScript. The jQuery library will allow you to do this in just a few lines of code. Do you have an absolute requirement for flex?</p>

ContentLicense: CC BY-SA 2.5


问:
Laravel 'Access denied for root' due to running my app in a virtual box?
I am working through the Laracasts db tutorial to learn how to work with databases in a properly 'Laravel' way. I have set up a local MySql instance and I have run the migrations to set up my tables and fields and also for the built in Laravel user authentication/login/register functions. It all works perfectly on the command line. My user 'root' and password allow me to browse my new db, select and add records as you might expect. However, when I run the app through my browser I get 'Access denied for user root'.

Is this because I'm running my app under 'Homestead/Vagrant'? Do I need to copy my MySQL database to the vagrant box somehow - maybe setting it up with the homestead yaml file? I'm confused!

答: IF you are hosting your MySQL database on your host but your app inside the vagrant box it won't work. Instead let homestead/vagrant run the MySQL database inside the box and connect into it.</p>


问:
Creating Django Filter in a bootstrap dropdown based on the django-admin created categories
I am 2 months into Python-Django and I do not have the full experience to carry on with my what I want to do.

I like to create a Filter or a Dropdown Filter such that anyone can choose from the for-loop rendered categories in the dropdown to filter or search by category. I managed to create a full search with Haystack with Whoosh (You can test my Haystack Search here and search with category called marketing)

Can someone shed more light on how I can filter my list based on categories looped in a dropdown? Am really confused.

Here the code to my working Haystack Search

search_indexes.py

```<code>import datetime
from haystack import indexes
from haystack.query import EmptySearchQuerySet
from .models import Mentor
from .models import *

class MentorIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    author1 = indexes.EdgeNgramField(model_attr='first_name')
    author2 = indexes.EdgeNgramField(model_attr='last_name')
    author3 = indexes.EdgeNgramField(model_attr='category')
    author4 = indexes.EdgeNgramField(model_attr='email')
    author5 = indexes.EdgeNgramField(model_attr='location')

    def get_model(self):
        return Mentor

    def index_queryset(self, using=None):
        """Used when the entire index for model is updated."""
        return self.get_model().objects.all()
</code>```

home.html

```<code><form method="get" action="/search/" class="navbar-form">
    <div class="form-group" style="display:inline;">
        <div class="input-group" style="display:table;">
            <input class="form-control" name="q" placeholder="Search Mentors Here. You can search by Location, Email, Name, e.t.c." autocomplete="off" autofocus="autofocus" type="text">
            <span class="input-group-btn" style="width:1%;">
                <button class="btn btn-danger" type="submit">
                    <span class=" glyphicon glyphicon-search"></span>
                </button>
            </span>
      </div>
    </div>
</form>
</code>```

app url config (url.py)

```<code>from django.conf.urls import include, url
from mentoring_application.views import profile

urlpatterns = [
    url(r'^profile/(?P<pk>\d+)/$', profile, {}, name='mentor-profile'),
]
</code>```

project url config (url.py)

```<code>from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from mentoring_application.views import HomeView, profile

admin.autodiscover()

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', HomeView.as_view()),
    url(r'^mentor/', include('mentoring_application.urls', namespace='mentor')),
    url(r'^search/', include('haystack.urls'))
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

views.py

```<code>from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.views import View
from .models import *
from .models import Mentor
from django.shortcuts import render, get_object_or_404

# Create your views here.

class HomeView(View):
    # @staticmethod
    def get(self, request, *args, **kwargs):
        mentors = Mentor.objects.all()
        return render(request, "mentoring_application/home.html", {"mentors": mentors})

def profile(request, pk, template='mentoring_application/profile.html'):
    mentor = get_object_or_404(Mentor, pk=pk)  # pk is primary key, so url will be site.com/profile/3
    context = {'mentor': mentor}
    return render(request, template, context)
</code>```

For more clarity, this picture shows a category filter I like to do.

答:
In accordance to the comment given by @TimS and some other helps from another community, I wrote a solution to filter by category and it works.

Below is the hack that made its work:

home.html

This is the looped dropdown from categories table. I created a name element called category-filter for the selection of the categories on my template.

```<code><div class="row" style="margin-bottom: 50px;">
    <div class="col-sm-6 pull-right">
        <form method="get">
            <select id="men-filter-cat" class="form-control" name="category-filter" onchange="this.form.submit();">
                <option value="all">Filter by category</option>
                {% for c in categories %}
                    <option value="{{ c.category }}" {% if selected == c.category %}selected=selected"{% endif %}>
                        {{ c.category }}
                    </option>
                {% endfor %}
            </select>
        </form>
    </div>
</div>
</code>```

views.py

I redefined my HomeView to respond to the selected request with a variable called chosen_filter and my views.py becomes:

```<code>class HomeView(View):
    def get(self, request, *args, **kwargs):
        mentors = Mentor.objects.all()
        chosen_filter = self.request.GET.get('category-filter')
        if chosen_filter:
            mentors = mentors.filter(category__category=chosen_filter)
        return render(request, "mentoring_application/home.html", {"mentors": mentors, 'selected': chosen_filter, 'categories': Category.objects.all().order_by('category')})

def profile(request, pk, template='mentoring_application/profile.html'):
    mentor = get_object_or_404(Mentor, pk=pk)  # pk is primary key, so url will be site.com/profile/3
    context = {'mentor': mentor}
    return render(request, template, context)
</code>```

This is what worked for me. Thanks.

Body:
I am 2 months into Python-Django and I do not have the full experience to carry on with my what I want to do.

I like to create a Filter or a Dropdown Filter such that anyone can choose from the for-loop rendered categories in the dropdown to filter or search by category. I managed to create a full search with Haystack with Whoosh (You can test my Haystack Search here and search with category called marketing)

Can someone shed more light on how I can filter my list based on categories looped in a dropdown? Am really confused.

Here the code to my working Haystack Search

search_indexes.py

import datetime
from haystack import indexes
from haystack.query import EmptySearchQuerySet
from .models import Mentor
from .models import *

class MentorIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    author1 = indexes.EdgeNgramField(model_attr='first_name')
    author2 = indexes.EdgeNgramField(model_attr='last_name')
    author3 = indexes.EdgeNgramField(model_attr='category')
    author4 = indexes.EdgeNgramField(model_attr='email')
    author5 = indexes.EdgeNgramField(model_attr='location')

    def get_model(self):
        return Mentor

    def index_queryset(self, using=None):
        """Used when the entire index for model is updated."""
        return self.get_model().objects.all()

home.html

<form method="get" action="/search/" class="navbar-form">

            <input class="form-control" name="q" placeholder="Search Mentors Here. You can search by Location, Email, Name, e.t.c." autocomplete="off" autofocus="autofocus" type="text">

                <button class="btn btn-danger" type="submit">

                </button>

</form>

app url config (url.py)

from django.conf.urls import include, url
from mentoring_application.views import profile

urlpatterns = [
    url(r'^profile/(?P<pk>\d+)/$', profile, {}, name='mentor-profile'),
]

project url config (url.py)

from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from mentoring_application.views import HomeView, profile

admin.autodiscover()

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', HomeView.as_view()),
    url(r'^mentor/', include('mentoring_application.urls', namespace='mentor')),
    url(r'^search/', include('haystack.urls'))
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.views import View
from .models import *
from .models import Mentor
from django.shortcuts import render, get_object_or_404

# Create your views here.

class HomeView(View):
    # @staticmethod
    def get(self, request, *args, **kwargs):
        mentors = Mentor.objects.all()
        return render(request, "mentoring_application/home.html", {"mentors": mentors})

def profile(request, pk, template='mentoring_application/profile.html'):
    mentor = get_object_or_404(Mentor, pk=pk)  # pk is primary key, so url will be site.com/profile/3
    context = {'mentor': mentor}
    return render(request, template, context)

For more clarity, this picture shows a category filter I like to do.

Body:
In accordance to the comment given by @TimS and some other helps from another community, I wrote a solution to filter by category and it works.

Below is the hack that made its work:

home.html

This is the looped dropdown from categories table. I created a name element called category-filter for the selection of the categories on my template.

<div class="row" style="margin-bottom: 50px;">
    <div class="col-sm-6 pull-right">
        <form method="get">
            <select id="men-filter-cat" class="form-control" name="category-filter" onchange="this.form.submit();">
                <option value="all">Filter by category</option>
                {% for c in categories %}
                    <option value="{{ c.category }}" {% if selected == c.category %}selected=selected"{% endif %}>
                        {{ c.category }}
                    </option>
                {% endfor %}
            </select>
        </form>
    </div>
</div>

views.py

I redefined my HomeView to respond to the selected request with a variable called chosen_filter and my views.py becomes:

class HomeView(View):
    def get(self, request, *args, **kwargs):
        mentors = Mentor.objects.all()
        chosen_filter = self.request.GET.get('category-filter')
        if chosen_filter:
            mentors = mentors.filter(category__category=chosen_filter)
        return render(request, "mentoring_application/home.html", {"mentors": mentors, 'selected': chosen_filter, 'categories': Category.objects.all().order_by('category')})

def profile(request, pk, template='mentoring_application/profile.html'):
    mentor = get_object_or_404(Mentor, pk=pk)  # pk is primary key, so url will be site.com/profile/3
    context = {'mentor': mentor}
    return render(request, template, context)

This is what worked for me. Thanks.


问:
Prevent express body-parser from removing body prior to request.pipe
I am trying to create a simple express middleware filter which should look at the POST body and determine if it should be piped to the correct server, or blocked. If I use body-parser it appears that I do get the req.body available to me, but it disappears from the request when I pipe the request to another external server.

The way I have tried to solve this is the following:

```<code>//Router
router.route('')
    .post(authController.isAuthenticated,
        urlHelper.bodyParser,             //Without these two, everything pipes correctly
        urlHelper.filterBasedOnSomething, //Without these two, everything pipes correctly
        urlHelper.pipeToTrustedZone);
</code>```

In urlHelper:

```<code>const filterBasedOnSomething = function (req, res, next) {
        if (req.body
            && req.body.something === 'some string'
            && req.body.somethingElse === 'some other value') {
            return res.status(403).send("You shall not pass");
        } else {
            next();
        }
    }
const pipeToTrustedZone = function (req, res) {
        //Here we are figuring out the correct forwarding url. This is simplified a little for the question, but it is well tested and works.
        var url = getProxiedPath(req.baseUrl) + req.originalUrl;
        req.pipe(request({ qs: req.query, uri: url }).on('error', function (err) {
            log.info(err);
            return res.sendStatus(400);
        }))
            .pipe(res);

};
module.exports = {
  bodyParser: require('body-parser').json(),
  filterBasedOnSomething: filterBasedOnSomething,
  pipeToTrustedZone: pipeToTrustedZone,
  //..
}
</code>```

This seem to give me the req.body in my filter-method, but the body is consumed and is not received after it has been piped forward. I have tried multiple things, like req.emit('data', JSON.stringify(req.body)); and req.write(.., but it all seem to fail.

Is there a way for me to look at the request body before piping it further without deleting it? Or is there an inherit problem with my approach?

I have found multiple github issues and SO questions relating to this, but I haven't been successful in getting any of those approaches to work.:

https://github.com/expressjs/body-parser/issues/74

Writing express middleware to get raw request body before body-parser

https://github.com/expressjs/body-parser/issues/94

答:
Is there a way for me to look at the request body before piping it further without deleting it? Or is there an inherit problem with my approach?

The inherent problem is that you want to read a stream first and then pipe it - even though the stream has already been read and it's gone.

What you need to do is to either cache the stream while it is read so that it can be piped later or to reconstruct the body from the output of body-parser.

But you cannot rewind a stream and start reading it once again because it would mean recording all of the stream events in memory and the usual advantage of using streams is that you don't need to record everything in memory, you just process one data event at a time.

If the decision of whether or not you want to pipe the stream can be based on the data outside of the body - like a path or some headers etc. - then you can use the body-parser middleware only for those cases that are not piped.

But if the decision is based on the actual contents of the body as is the case in your example then you have no choice but to read it first - at which point it cannot be read again.

There are few modules that could help you with that:

https://www.npmjs.com/package/raw-body-parser

https://www.npmjs.com/package/body-parser-rawbody

but you may be better off by reconstructing the body from the parsed output of body-parser with something like:

```<code>request({ qs: req.query, uri: url, body: req.body, json: true })
</code>```

and piping only the response.

Body:
I am trying to create a simple express middleware filter which should look at the POST body and determine if it should be piped to the correct server, or blocked. If I use body-parser it appears that I do get the req.body available to me, but it disappears from the request when I pipe the request to another external server.

The way I have tried to solve this is the following:

//Router
router.route('')
    .post(authController.isAuthenticated,
        urlHelper.bodyParser,             //Without these two, everything pipes correctly
        urlHelper.filterBasedOnSomething, //Without these two, everything pipes correctly
        urlHelper.pipeToTrustedZone);

In urlHelper:

const filterBasedOnSomething = function (req, res, next) {
        if (req.body
            && req.body.something === 'some string'
            && req.body.somethingElse === 'some other value') {
            return res.status(403).send("You shall not pass");
        } else {
            next();
        }
    }
const pipeToTrustedZone = function (req, res) {
        //Here we are figuring out the correct forwarding url. This is simplified a little for the question, but it is well tested and works.
        var url = getProxiedPath(req.baseUrl) + req.originalUrl;
        req.pipe(request({ qs: req.query, uri: url }).on('error', function (err) {
            log.info(err);
            return res.sendStatus(400);
        }))
            .pipe(res);

};
module.exports = {
  bodyParser: require('body-parser').json(),
  filterBasedOnSomething: filterBasedOnSomething,
  pipeToTrustedZone: pipeToTrustedZone,
  //..
}

This seem to give me the req.body in my filter-method, but the body is consumed and is not received after it has been piped forward. I have tried multiple things, like req.emit('data', JSON.stringify(req.body)); and req.write(.., but it all seem to fail.

Is there a way for me to look at the request body before piping it further without deleting it? Or is there an inherit problem with my approach?

I have found multiple github issues and SO questions relating to this, but I haven't been successful in getting any of those approaches to work.:

https://github.com/expressjs/body-parser/issues/74

Writing express middleware to get raw request body before body-parser

https://github.com/expressjs/body-parser/issues/94

Body:
Is there a way for me to look at the request body before piping it further without deleting it? Or is there an inherit problem with my approach?

The inherent problem is that you want to read a stream first and then pipe it - even though the stream has already been read and it's gone.

What you need to do is to either cache the stream while it is read so that it can be piped later or to reconstruct the body from the output of body-parser.

But you cannot rewind a stream and start reading it once again because it would mean recording all of the stream events in memory and the usual advantage of using streams is that you don't need to record everything in memory, you just process one data event at a time.

If the decision of whether or not you want to pipe the stream can be based on the data outside of the body - like a path or some headers etc. - then you can use the body-parser middleware only for those cases that are not piped.

But if the decision is based on the actual contents of the body as is the case in your example then you have no choice but to read it first - at which point it cannot be read again.

There are few modules that could help you with that:

https://www.npmjs.com/package/raw-body-parser

https://www.npmjs.com/package/body-parser-rawbody

but you may be better off by reconstructing the body from the parsed output of body-parser with something like:

request({ qs: req.query, uri: url, body: req.body, json: true })

and piping only the response.


问:
RestSharp: POST request in demo-api.hitbtc.com doesn't work
I want to create a bot for demo-api.hitbtc.com. All GET request works great.

```<code>using System;
using System.Security.Cryptography;
using RestSharp;
using System.Linq;
using System.Text;

static void Main(string[] args)
    {
        const string apiKey = "xxx";
        const string secretKey = "xxx";

        var client1 = new RestClient("http://demo-api.hitbtc.com");
        var request1 = new RestRequest("/api/1/trading/new_order", Method.POST);
        request1.AddParameter("nonce", GetNonce().ToString());
        request1.AddParameter("apikey", apiKey);

        string sign1 = CalculateSignature(client1.BuildUri(request1).PathAndQuery, secretKey);
        request1.AddHeader("X-Signature", sign1);

        request1.RequestFormat = DataFormat.Json;
        request1.AddBody(new
        {
            clientOrderId = "58f32654723a4b60ad6b",
            symbol = "BTCUSD",
            side = "buy",
            quantity = "0.01",
            type = "market",
            timeInForce = "GTC"
        });

        var response1 = client1.Execute(request1);

        Console.WriteLine(response1.Content);
        Console.ReadLine();
}

        private static long GetNonce()
    {
        return DateTime.Now.Ticks * 10 / TimeSpan.TicksPerMillisecond; // use millisecond timestamp or whatever you want
    }

    public static string CalculateSignature(string text, string secretKey)
    {
        using (var hmacsha512 = new HMACSHA512(Encoding.UTF8.GetBytes(secretKey)))
        {
            hmacsha512.ComputeHash(Encoding.UTF8.GetBytes(text));
            return string.Concat(hmacsha512.Hash.Select(b => b.ToString("x2")).ToArray()); // minimalistic hex-encoding and lower case
        }
    }
</code>```

But when I want to try POST request, I got this error:

```<code>{"code":"InvalidContent","message":"Missing apikey parameter"}
</code>```

In hitbtc.com API Documentation has said that: "Each request should include the following parameters: nonce, apikey, signature".
Where is the problem?

答:
It appears RestSharp removes query string parameters by default when performing POST operations.  To work around this, you will need to tell it that your parameters are intended to be query string parameters:

```<code>request1.AddQueryParameter("nonce", GetNonce().ToString());
request1.AddQueryParameter("apikey", apiKey);
</code>```

instead of using reqest1.AddParameter(name, value)

Body:
I want to create a bot for demo-api.hitbtc.com. All GET request works great.

using System;
using System.Security.Cryptography;
using RestSharp;
using System.Linq;
using System.Text;

static void Main(string[] args)
    {
        const string apiKey = "xxx";
        const string secretKey = "xxx";

        var client1 = new RestClient("http://demo-api.hitbtc.com");
        var request1 = new RestRequest("/api/1/trading/new_order", Method.POST);
        request1.AddParameter("nonce", GetNonce().ToString());
        request1.AddParameter("apikey", apiKey);

        string sign1 = CalculateSignature(client1.BuildUri(request1).PathAndQuery, secretKey);
        request1.AddHeader("X-Signature", sign1);

        request1.RequestFormat = DataFormat.Json;
        request1.AddBody(new
        {
            clientOrderId = "58f32654723a4b60ad6b",
            symbol = "BTCUSD",
            side = "buy",
            quantity = "0.01",
            type = "market",
            timeInForce = "GTC"
        });

        var response1 = client1.Execute(request1);

        Console.WriteLine(response1.Content);
        Console.ReadLine();
}

        private static long GetNonce()
    {
        return DateTime.Now.Ticks * 10 / TimeSpan.TicksPerMillisecond; // use millisecond timestamp or whatever you want
    }

    public static string CalculateSignature(string text, string secretKey)
    {
        using (var hmacsha512 = new HMACSHA512(Encoding.UTF8.GetBytes(secretKey)))
        {
            hmacsha512.ComputeHash(Encoding.UTF8.GetBytes(text));
            return string.Concat(hmacsha512.Hash.Select(b => b.ToString("x2")).ToArray()); // minimalistic hex-encoding and lower case
        }
    }

But when I want to try POST request, I got this error:

{"code":"InvalidContent","message":"Missing apikey parameter"}

In hitbtc.com API Documentation has said that: "Each request should include the following parameters: nonce, apikey, signature".
Where is the problem?

Body:
It appears RestSharp removes query string parameters by default when performing POST operations.  To work around this, you will need to tell it that your parameters are intended to be query string parameters:

request1.AddQueryParameter("nonce", GetNonce().ToString());
request1.AddQueryParameter("apikey", apiKey);

instead of using reqest1.AddParameter(name, value)


问:
how to check if bodymovin animation is complete?
I want the to destroy the animation when is complete animating. tried addEventListener that didn't work.

```<code>anim = bodymovin.loadAnimation(params);
animContainer.addEventListener("complete", myScript);

function myScript(){
      anim.destroy();
}
</code>```

答:
One way to go would be to listen for native 'transitionend' event on the element that is being animated.</p>

```<code>element.addEventListener("transitionend", anim.destroy());
</code>```

Body:
I want the to destroy the animation when is complete animating. tried addEventListener that didn't work.

anim = bodymovin.loadAnimation(params);
animContainer.addEventListener("complete", myScript);

function myScript(){
      anim.destroy();
}

Body:
One way to go would be to listen for native 'transitionend' event on the element that is being animated.

element.addEventListener("transitionend", anim.destroy());


问:
How to read XML Data using PHP
I have below XML format :

```<code><?xml version="1.0" encoding="utf-8"?>
<Partners Default="123">
<PID id="123" Value="Kell Partners" DefGID="345">
          <GID id="345" Country="US" Value="3.5% + $0.35/transaction + $0/month" Default="True"></GID>
          <GID id="455" Country="US" Value="3.5% + $0.35/transaction + $0/month"></GID>
          <GID id="789" Country="US" Value="3.5% + $0.35/transaction + $0/month"></GID>
          <GID id="159" Country="EU" Value="3.5% + $0.35/transaction + $0/month" Default="True"></GID>
</PID>
<PID id="456" Value="Test Company 2" DefGID="224">
          <GID id="222" Country="CA" Value="3.5% + $0.35/transaction + $0/month" Default="True"></GID>
          <GID id="224" Country="CA" Value="3.5% + $0.35/transaction + $0/month"></GID>
          <GID id="225" Country="UK" Value="3.5% + $0.35/transaction + $0/month"></GID>
          <GID id="226" Country="UK" Value="3.5% + $0.35/transaction + $0/month" Default="True"></GID>
</PID>
</Partners>
</code>```

I am using below code snippet to read xml data in PHP where My xml showing parents nodes as @attributes.

```<code><?php
$xmlparser=simplexml_load_file("partners.xml") or die("Cannot open the file.");
echo "```";
print_r($xmlparser->attributes());

?>
```

In above question I want read the

 default from Partners node..I am unable to read by using above code..

and by using Default i will get the child nodes data.

答:
```<code><?php
$xml=simplexml_load_file("partners.xml") or die("Cannot open the file.");
echo "```";
foreach($xml->children() as $child) {
    foreach($child as $value) {
        print_r($value->children());
    }
}
echo "```";
?>
</code>```

By this code you can get the data of GID nodes. To get it you don't have to get Partners Default value.

Title: How to read XML Data using PHP

Body:
I have below XML format :

<?xml version="1.0" encoding="utf-8"?>
<Partners Default="123">
<PID id="123" Value="Kell Partners" DefGID="345">
          <GID id="345" Country="US" Value="3.5% + $0.35/transaction + $0/month" Default="True"></GID>
          <GID id="455" Country="US" Value="3.5% + $0.35/transaction + $0/month"></GID>
          <GID id="789" Country="US" Value="3.5% + $0.35/transaction + $0/month"></GID>
          <GID id="159" Country="EU" Value="3.5% + $0.35/transaction + $0/month" Default="True"></GID>
</PID>
<PID id="456" Value="Test Company 2" DefGID="224">
          <GID id="222" Country="CA" Value="3.5% + $0.35/transaction + $0/month" Default="True"></GID>
          <GID id="224" Country="CA" Value="3.5% + $0.35/transaction + $0/month"></GID>
          <GID id="225" Country="UK" Value="3.5% + $0.35/transaction + $0/month"></GID>
          <GID id="226" Country="UK" Value="3.5% + $0.35/transaction + $0/month" Default="True"></GID>
</PID>
</Partners>

I am using below code snippet to read xml data in PHP where My xml showing parents nodes as @attributes.

<?php
$xmlparser=simplexml_load_file("partners.xml") or die("Cannot open the file.");
echo "
";
print_r($xmlparser->attributes());

?>

In above question I want read the

 default from Partners node..I am unable to read by using above code..

and by using Default i will get the child nodes data.

Body:
<?php
$xml=simplexml_load_file("partners.xml") or die("Cannot open the file.");
echo "<pre>";
foreach($xml->children() as $child) {
    foreach($child as $value) {
        print_r($value->children());
    }
}
echo "</pre>";
?>

By this code you can get the data of GID nodes. To get it you don't have to get Partners Default value.


问:
Creating a "logical exclusive or" operator in Java

Observations:

Java has a logical AND operator.

Java has a logical OR operator.

Java has a logical NOT operator.

Problem:

Java has no logical XOR operator, according to sun.  I would like to define one.

Method Definition:

As a method it is simply defined as follows:

```<code>public static boolean logicalXOR(boolean x, boolean y) {
    return ( ( x || y ) && ! ( x && y ) );
}
</code>```

Method Call:

This method is called in the following way:

```<code>boolean myVal = logicalXOR(x, y);
</code>```

Operator Usage:

I would much rather have an operator, used as follows:

```<code>boolean myVal = x ^^ y;
</code>```

Question:

I can't find anything on how to go about defining a new operator in Java.  Where should I start?

答: A and B would have to be boolean values to make != the same as xor so that the truth table would look the same. You could also use !(A==B) lol.</p>

Body:
Observations:

Java has a logical AND operator.

Java has a logical OR operator.

Java has a logical NOT operator.

Problem:

Java has no logical XOR operator, according to sun.  I would like to define one.

Method Definition:

As a method it is simply defined as follows:

public static boolean logicalXOR(boolean x, boolean y) {
    return ( ( x || y ) && ! ( x && y ) );
}

Method Call:

This method is called in the following way:

boolean myVal = logicalXOR(x, y);

Operator Usage:

I would much rather have an operator, used as follows:

boolean myVal = x ^^ y;

Question:

I can't find anything on how to go about defining a new operator in Java.  Where should I start?


问:
Insert not working correctly in codeigniter
I am trying to insert data into the database and my code does add a new row but all the values are null. I don't know what's causing it. The view is inside a modal in html. Here's my code: Thanks for your help

Controller:

```<code>public function addItem(){
    $save = array(
        'inventoryID' => $this->input->post('rfid'),
        'masterCode' => $this->input->post('masterCode'),
        'itemName' => $this->input->post('itemName'),
        'colorName' => $this->input->post('colorName'),
        'location' => $this->input->post('location'),
        'itemCategory' => $this->input->post('itemCategory'),
        'materialDescription' => $this->input->post('materialDescription'),
        'supplier' => $this->input->post('supplier'),
        'itemDescription' => $this->input->post('itemDescription'),
        'comments' => $this->input->post('comments'),
        'itemCode' => $this->input->post('itemCode'),
        'colorCode' => $this->input->post('colorCode')
    );
    $this->searchModel->form_insert($save);

    //load the header
    $this->load->view('base.php',$save);
    //load the page
    redirect('Search');
    //load the footer
    $this->load->view('footer.php',$save);
}
</code>```

Model:

function form_insert($data){

```<code>    // Inserting in Table(inventory) of Database(library)
    $this->load->database();
    $this->db->insert('inventory', $data);
    $inventoryID = $this->db->insert_id();
}
</code>```

View:

```<code><div id="addItem" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <form method ="post" action= "<?php echo site_url("Search/addItem"); ?>">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
          <h4 class="modal-title">Add an Item</h4>
        </div>
        <div class="modal-body">
          <form role="form">
            <table>
              <tr>
                <td><input type="text" name="rfid" placeholder="RFID" required/></td>
                <td><input type="text" name="itemCode" placeholder="Item Code" required/></td>
                <td><input type="text" name="masterCode" placeholder="Master Code" /></td>
              </tr>
              <tr>
                <td><input type="text" name="itemName" placeholder="Item Name" required/></td>
                <td><input type="text" name="colorCode" placeholder="Color Code" /></td>
                <td><input type="text" name="colorName" placeholder="Color Name" /></td>
              </tr>
              <tr>
                <td><input type="text" name="location" placeholder="Location" required/></td>
                <td><input type="text" name="makelocation" placeholder="Location Made" required/></td>
                <td><input type="text" name="itemCategory" placeholder="Item Category" /></td>
              </tr>
              <tr>
                <td><input type="text" name="materialDescription" placeholder="Material Description" /></td>
                <td><input type="text" name="supplier" placeholder="Supplier/Vendor" required/></td>
                <td><input type="text" name="checkoutAllowed" placeholder="Checkout Allowed" /></td>
              </tr>
            </table>
            <div class="row personal-info">
              <div class="col-sm-4">
                <div class="form-group">
                  <textarea name="itemDescription" placeholder="Insert information regarding the weather this item is suitable for and where it is used"></textarea>
                  <textarea name="Comments" placeholder="Additional Coments on the Item"></textarea>
                </div>
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer" style="text-align:center;">
          <a href="<?php echo site_url("Search/addItem") ?>"><input class="btn btn-primary" name="addItem" value="Add Item"></a>
        </div>
      </form>
    </div>
  </div>
</div>
</code>```

答:
The problem is that you do not actually "submit" the form data. Your button links to the correct controller/method but does not send any data to the controller when you use a link, i.e. href=.... You need a submit button.

The change is quite simple. Change the code for the button as follows.

```<code><div class="modal-footer" style="text-align:center;">
  <input type="submit" class="btn btn-primary" name="addItem" value="Add Item">
</div>
</code>```

There is another issue. You have two <form> tags.
Remove the line

```<code><form method ="post" action="<?php echo site_url("Search/addItem"); ?>">
</code>```

And change the line

```<code><form role="form">
</code>```

to

```<code><form method="post" action="<?php echo site_url("Search/addItem"); ?>" role="form">
</code>```

You also need to remove the extra form close tag two lines above the button's code. Nested <form>s are not allowed. And you need to move the closing tag for
 So to make it more clear here is what your view should finally look like.

```<code><div id="addItem" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title">Add an Item</h4>
      </div>
      <div class="modal-body">
        <form method ="post" action= "<?php echo site_url("Search/addItem"); ?>" role="form">
          <table>
            <tr>
              <td><input type="text" name="rfid" placeholder="RFID" required/></td>
              <td><input type="text" name="itemCode" placeholder="Item Code" required/></td>
              <td><input type="text" name="masterCode" placeholder="Master Code" /></td>
            </tr>
            <tr>
              <td><input type="text" name="itemName" placeholder="Item Name" required/></td>
              <td><input type="text" name="colorCode" placeholder="Color Code" /></td>
              <td><input type="text" name="colorName" placeholder="Color Name" /></td>
            </tr>
            <tr>
              <td><input type="text" name="location" placeholder="Location" required/></td>
              <td><input type="text" name="makelocation" placeholder="Location Made" required/></td>
              <td><input type="text" name="itemCategory" placeholder="Item Category" /></td>
            </tr>
            <tr>
              <td><input type="text" name="materialDescription" placeholder="Material Description" /></td>
              <td><input type="text" name="supplier" placeholder="Supplier/Vendor" required/></td>
              <td><input type="text" name="checkoutAllowed" placeholder="Checkout Allowed" /></td>
            </tr>
          </table>
          <div class="row personal-info">
            <div class="col-sm-4">
              <div class="form-group">
                <textarea name="itemDescription" placeholder="Insert information regarding the weather this item is suitable for and where it is used"></textarea>
                <textarea name="Comments" placeholder="Additional Coments on the Item"></textarea>
              </div>
            </div>
          </div>
          <div class="modal-footer" style="text-align:center;">
            <input type="submit" class="btn btn-primary" name="addItem" value="Add Item">
          </div>
        </form>
      </div>
    </div>
  </div>
</div>
</code>```

Body:
I am trying to insert data into the database and my code does add a new row but all the values are null. I don't know what's causing it. The view is inside a modal in html. Here's my code: Thanks for your help

Controller:

public function addItem(){
    $save = array(
        'inventoryID' => $this->input->post('rfid'),
        'masterCode' => $this->input->post('masterCode'),
        'itemName' => $this->input->post('itemName'),
        'colorName' => $this->input->post('colorName'),
        'location' => $this->input->post('location'),
        'itemCategory' => $this->input->post('itemCategory'),
        'materialDescription' => $this->input->post('materialDescription'),
        'supplier' => $this->input->post('supplier'),
        'itemDescription' => $this->input->post('itemDescription'),
        'comments' => $this->input->post('comments'),
        'itemCode' => $this->input->post('itemCode'),
        'colorCode' => $this->input->post('colorCode')
    );
    $this->searchModel->form_insert($save);

    //load the header
    $this->load->view('base.php',$save);
    //load the page
    redirect('Search');
    //load the footer
    $this->load->view('footer.php',$save);
}

Model:

function form_insert($data){

    // Inserting in Table(inventory) of Database(library)
    $this->load->database();
    $this->db->insert('inventory', $data);
    $inventoryID = $this->db->insert_id();
}

View:

      <form method ="post" action= "<?php echo site_url("Search/addItem"); ?>">

          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Add an Item

          <form role="form">

                <input type="text" name="rfid" placeholder="RFID" required/>
                <input type="text" name="itemCode" placeholder="Item Code" required/>
                <input type="text" name="masterCode" placeholder="Master Code" />

                <input type="text" name="itemName" placeholder="Item Name" required/>
                <input type="text" name="colorCode" placeholder="Color Code" />
                <input type="text" name="colorName" placeholder="Color Name" />

                <input type="text" name="location" placeholder="Location" required/>
                <input type="text" name="makelocation" placeholder="Location Made" required/>
                <input type="text" name="itemCategory" placeholder="Item Category" />

                <input type="text" name="materialDescription" placeholder="Material Description" />
                <input type="text" name="supplier" placeholder="Supplier/Vendor" required/>
                <input type="text" name="checkoutAllowed" placeholder="Checkout Allowed" />

                  <textarea name="itemDescription" placeholder="Insert information regarding the weather this item is suitable for and where it is used"></textarea>
                  <textarea name="Comments" placeholder="Additional Coments on the Item"></textarea>

          </form>

          <a href="<?php echo site_url("Search/addItem") ?>"><input class="btn btn-primary" name="addItem" value="Add Item">

      </form>

Body:
The problem is that you do not actually "submit" the form data. Your button links to the correct controller/method but does not send any data to the controller when you use a link, i.e. <a href=.... You need a submit button.

The change is quite simple. Change the code for the button as follows.

<div class="modal-footer" style="text-align:center;">
  <input type="submit" class="btn btn-primary" name="addItem" value="Add Item">
</div>

There is another issue. You have two <form> tags.
Remove the line

<form method ="post" action="<?php echo site_url("Search/addItem"); ?>">

And change the line

<form role="form">

to

<form method="post" action="<?php echo site_url("Search/addItem"); ?>" role="form">

You also need to remove the extra form close tag two lines above the button's code. Nested <form>s are not allowed. And you need to move the closing tag for <div class="modal-content"> So to make it more clear here is what your view should finally look like.

<div id="addItem" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title">Add an Item</h4>
      </div>
      <div class="modal-body">
        <form method ="post" action= "<?php echo site_url("Search/addItem"); ?>" role="form">
          <table>
            <tr>
              <td><input type="text" name="rfid" placeholder="RFID" required/></td>
              <td><input type="text" name="itemCode" placeholder="Item Code" required/></td>
              <td><input type="text" name="masterCode" placeholder="Master Code" /></td>
            </tr>
            <tr>
              <td><input type="text" name="itemName" placeholder="Item Name" required/></td>
              <td><input type="text" name="colorCode" placeholder="Color Code" /></td>
              <td><input type="text" name="colorName" placeholder="Color Name" /></td>
            </tr>
            <tr>
              <td><input type="text" name="location" placeholder="Location" required/></td>
              <td><input type="text" name="makelocation" placeholder="Location Made" required/></td>
              <td><input type="text" name="itemCategory" placeholder="Item Category" /></td>
            </tr>
            <tr>
              <td><input type="text" name="materialDescription" placeholder="Material Description" /></td>
              <td><input type="text" name="supplier" placeholder="Supplier/Vendor" required/></td>
              <td><input type="text" name="checkoutAllowed" placeholder="Checkout Allowed" /></td>
            </tr>
          </table>
          <div class="row personal-info">
            <div class="col-sm-4">
              <div class="form-group">
                <textarea name="itemDescription" placeholder="Insert information regarding the weather this item is suitable for and where it is used"></textarea>
                <textarea name="Comments" placeholder="Additional Coments on the Item"></textarea>
              </div>
            </div>
          </div>
          <div class="modal-footer" style="text-align:center;">
            <input type="submit" class="btn btn-primary" name="addItem" value="Add Item">
          </div>
        </form>
      </div>
    </div>
  </div>
</div>


问:
Performance SQLAlchemy and or
I use the following sqlalchemy code to retrieve some data from a database

```<code>q = session.query(hd_tbl).\
    join(dt_tbl, hd_tbl.c['data_type'] == dt_tbl.c['ID']).\
    filter(or_(and_(hd_tbl.c['object_id'] == get_id(row['object']),
                    hd_tbl.c['data_type'] == get_id(row['type']),
                    hd_tbl.c['data_provider'] == get_id(row['provider']),
                    hd_tbl.c['data_account'] == get_id(row['account']))
           for index, row in data.iterrows())).\
    with_entities(hd_tbl.c['ID'], hd_tbl.c['object_id'],
                  hd_tbl.c['data_type'], hd_tbl.c['data_provider'],
                  hd_tbl.c['data_account'], dt_tbl.c['value_type'])
</code>```

where hd_tbland dt_tbl are two tables in sql db, and datais pandas dataframe containing typically around 1k-9k entries. hd_tbl contains at the moment around 90k rows.

The execution time seems to exponentially grow with the length of data. The corresponding sql statement (by sqlalchemy) looks as follows:

```<code>SELECT data_header.`ID`, data_header.object_id, data_header.data_type, data_header.data_provider, data_header.data_account, basedata_data_type.value_type
FROM data_header INNER JOIN basedata_data_type ON data_header.data_type = basedata_data_type.`ID`
WHERE data_header.object_id = %s AND data_header.data_type = %s AND data_header.data_provider = %s AND data_header.data_account = %s OR
data_header.object_id = %s AND data_header.data_type = %s AND data_header.data_provider = %s AND data_header.data_account = %s OR
 ...
 data_header.object_id = %s AND data_header.data_type = %s AND data_header.data_provider = %s AND data_header.data_account = %s OR
</code>```

The tables and columns are fully indexed, and performance is not satisfying. Currently it is way faster to read all the data of hd_tbl and dt_tbl into memory and merge with pandas merge function. However, this is seems to be suboptimal. Anyone having an idea on how to improve the sqlalchemy call?

EDIT:
I was able to improve performance signifcantly by using sqlalchemy tuple_ in the following way:

```<code>header_tuples = [tuple([int(y) for y in tuple(x)]) for x in
                 data_as_int.values]
q = session.query(hd_tbl). \
    join(dt_tbl, hd_tbl.c['data_type'] == dt_tbl.c['ID']). \
    filter(tuple_(hd_tbl.c['object_id'], hd_tbl.c['data_type'],
                  hd_tbl.c['data_provider'],
                  hd_tbl.c['data_account']).in_(header_tuples)). \
    with_entities(hd_tbl.c['ID'], hd_tbl.c['object_id'],
                  hd_tbl.c['data_type'], hd_tbl.c['data_provider'],
                  hd_tbl.c['data_account'], dt_tbl.c['value_type'])
</code>```

with corresponding query...

```<code>SELECT data_header.`ID`, data_header.object_id, data_header.data_type, data_header.data_provider, data_header.data_account, basedata_data_type.value_type
FROM data_header INNER JOIN basedata_data_type ON data_header.data_type = basedata_data_type.`ID`
WHERE (data_header.object_id, data_header.data_type, data_header.data_provider, data_header.data_account) IN ((%(param_1)s, %(param_2)s, %(param_3)s, %(param_4)s), (%(param_5)s, ...))
</code>```

答:
I'd recommend you create a composite index on fields object_id, data_type, data_provider, ... with the same order, which they are placed in table, and make sure they're following in the same order in your WHERE condition. It may speed-up a bit your requests by cost of the disk space.

Also you may use several consequent small SQL requests instead a large query with complex OR condition. Accumulate extracted data on the application side or, if amount is large enough, in a fast temporary storage (a temporary table, noSQL, etc.)

In addition you may check MySQL configuration and increase values, related to memory volume per a thread, request, etc. A good idea is to check is your composite index fits into available memory, or it is useless.

I guess DB tuning may help a lot to increase productivity. Otherwise you may analyze your application's architecture to get more significant results.

Title: Performance SQLAlchemy and or

Body:
I use the following sqlalchemy code to retrieve some data from a database

q = session.query(hd_tbl).\
    join(dt_tbl, hd_tbl.c['data_type'] == dt_tbl.c['ID']).\
    filter(or_(and_(hd_tbl.c['object_id'] == get_id(row['object']),
                    hd_tbl.c['data_type'] == get_id(row['type']),
                    hd_tbl.c['data_provider'] == get_id(row['provider']),
                    hd_tbl.c['data_account'] == get_id(row['account']))
           for index, row in data.iterrows())).\
    with_entities(hd_tbl.c['ID'], hd_tbl.c['object_id'],
                  hd_tbl.c['data_type'], hd_tbl.c['data_provider'],
                  hd_tbl.c['data_account'], dt_tbl.c['value_type'])

where hd_tbland dt_tbl are two tables in sql db, and datais pandas dataframe containing typically around 1k-9k entries. hd_tbl contains at the moment around 90k rows.

The execution time seems to exponentially grow with the length of data. The corresponding sql statement (by sqlalchemy) looks as follows:

SELECT data_header.`ID`, data_header.object_id, data_header.data_type, data_header.data_provider, data_header.data_account, basedata_data_type.value_type
FROM data_header INNER JOIN basedata_data_type ON data_header.data_type = basedata_data_type.`ID`
WHERE data_header.object_id = %s AND data_header.data_type = %s AND data_header.data_provider = %s AND data_header.data_account = %s OR
data_header.object_id = %s AND data_header.data_type = %s AND data_header.data_provider = %s AND data_header.data_account = %s OR
 ...
 data_header.object_id = %s AND data_header.data_type = %s AND data_header.data_provider = %s AND data_header.data_account = %s OR

The tables and columns are fully indexed, and performance is not satisfying. Currently it is way faster to read all the data of hd_tbl and dt_tbl into memory and merge with pandas merge function. However, this is seems to be suboptimal. Anyone having an idea on how to improve the sqlalchemy call?

EDIT:
I was able to improve performance signifcantly by using sqlalchemy tuple_ in the following way:

header_tuples = [tuple([int(y) for y in tuple(x)]) for x in
                 data_as_int.values]
q = session.query(hd_tbl). \
    join(dt_tbl, hd_tbl.c['data_type'] == dt_tbl.c['ID']). \
    filter(tuple_(hd_tbl.c['object_id'], hd_tbl.c['data_type'],
                  hd_tbl.c['data_provider'],
                  hd_tbl.c['data_account']).in_(header_tuples)). \
    with_entities(hd_tbl.c['ID'], hd_tbl.c['object_id'],
                  hd_tbl.c['data_type'], hd_tbl.c['data_provider'],
                  hd_tbl.c['data_account'], dt_tbl.c['value_type'])

with corresponding query...

SELECT data_header.`ID`, data_header.object_id, data_header.data_type, data_header.data_provider, data_header.data_account, basedata_data_type.value_type
FROM data_header INNER JOIN basedata_data_type ON data_header.data_type = basedata_data_type.`ID`
WHERE (data_header.object_id, data_header.data_type, data_header.data_provider, data_header.data_account) IN ((%(param_1)s, %(param_2)s, %(param_3)s, %(param_4)s), (%(param_5)s, ...))


问:
win32api and python causing my screen to go black when it moves the mouse
For whatever reason the screen is going black after the second or third movement of the mouse. First is the function i use to move the mouse:

```<code>import ctypes
import time

SendInput = ctypes.windll.user32.SendInput

def MoveMouse(x, y):
    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    x = int(x*(65536/ctypes.windll.user32.GetSystemMetrics(0))+1)
    y = int(y*(65536/ctypes.windll.user32.GetSystemMetrics(1))+1)
    ii_.mi = MouseInput(x, y, 0, 0x0001 | 0x8000, 1, ctypes.pointer(extra))
    x = Input(ctypes.c_ulong(0), ii_)
    ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
</code>```

this causes the screen to go black

```<code>import numpy as np
from PIL import ImageGrab
import cv2
import time
import win32api, win32con
from directkeys import PressKey,ReleaseKey, W, A, S, D, MoveMouse
from grabscreen import grab_screen
x_pad = 0
y_pad = 0
def left():
    PressKey(W)
    PressKey(A)
    #ReleaseKey(W)
    ReleaseKey(D)
    #ReleaseKey(A)
    time.sleep(.9)
    ReleaseKey(A)
def leftClick():
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
    time.sleep(.1)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
    print ("Click.")
def mousePos(cord):
    win32api.SetCursorPos((x_pad + cord[0], y_pad + cord[1]))
def screen_record():
    last_time = time.time()
    while(True):
        # 800x600 windowed mode for GTA 5, at the top left position of your main screen.
        # 40 px accounts for title bar.
        printscreen =  grab_screen(region=(0,40,800,640))
        #rgb_im = printscreen.convert('RGB')
        pixels =int(printscreen[300, 300, 0])
        print(pixels)
        #r, g, b = printscreen.getpixel((551, 350 ))
        if pixels == 255:
            #if r == 127and g == 26 and b == 25:
            x, y = win32api.GetCursorPos()
            #x += 44
            time.sleep(1)
            MoveMouse(x, y)
            time.sleep(1)
#

        #print (r, g, b)
screen_record()
</code>```

Thanks any help would be appreciated. To summarize i need help determining why the Move Mouse function is causing my entire desktop monitor to black out until the function is no longer being used.

答:
Had the same issue, try changing in:

```<code>ii_.mi = MouseInput(x, y, 0, 0x0001 | 0x8000, 1, ctypes.pointer(extra))
</code>```

the fifth parameter (I.E. "1") to a 0, so it looks like this:

```<code>ii_.mi = MouseInput(x, y, 0, 0x0001 | 0x8000, 0, ctypes.pointer(extra))
</code>```

Worked for me...
Good luck

Body:
For whatever reason the screen is going black after the second or third movement of the mouse. First is the function i use to move the mouse:

import ctypes
import time

SendInput = ctypes.windll.user32.SendInput

def MoveMouse(x, y):
    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    x = int(x*(65536/ctypes.windll.user32.GetSystemMetrics(0))+1)
    y = int(y*(65536/ctypes.windll.user32.GetSystemMetrics(1))+1)
    ii_.mi = MouseInput(x, y, 0, 0x0001 | 0x8000, 1, ctypes.pointer(extra))
    x = Input(ctypes.c_ulong(0), ii_)
    ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))

this causes the screen to go black

import numpy as np
from PIL import ImageGrab
import cv2
import time
import win32api, win32con
from directkeys import PressKey,ReleaseKey, W, A, S, D, MoveMouse
from grabscreen import grab_screen
x_pad = 0
y_pad = 0
def left():
    PressKey(W)
    PressKey(A)
    #ReleaseKey(W)
    ReleaseKey(D)
    #ReleaseKey(A)
    time.sleep(.9)
    ReleaseKey(A)
def leftClick():
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
    time.sleep(.1)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
    print ("Click.")
def mousePos(cord):
    win32api.SetCursorPos((x_pad + cord[0], y_pad + cord[1]))
def screen_record():
    last_time = time.time()
    while(True):
        # 800x600 windowed mode for GTA 5, at the top left position of your main screen.
        # 40 px accounts for title bar.
        printscreen =  grab_screen(region=(0,40,800,640))
        #rgb_im = printscreen.convert('RGB')
        pixels =int(printscreen[300, 300, 0])
        print(pixels)
        #r, g, b = printscreen.getpixel((551, 350 ))
        if pixels == 255:
            #if r == 127and g == 26 and b == 25:
            x, y = win32api.GetCursorPos()
            #x += 44
            time.sleep(1)
            MoveMouse(x, y)
            time.sleep(1)
#

        #print (r, g, b)
screen_record()

Thanks any help would be appreciated. To summarize i need help determining why the Move Mouse function is causing my entire desktop monitor to black out until the function is no longer being used.

Body:
Had the same issue, try changing in:

ii_.mi = MouseInput(x, y, 0, 0x0001 | 0x8000, 1, ctypes.pointer(extra))

the fifth parameter (I.E. "1") to a 0, so it looks like this:

ii_.mi = MouseInput(x, y, 0, 0x0001 | 0x8000, 0, ctypes.pointer(extra))

Worked for me...
Good luck


问:
MySQL: Using variable on a WHERE IN clause
I'm becoming mad trying to use an "array" of values obtained from a GROUP_CONCAT into a WHERE IN statement, when GROUP_CONCAT only takes one "id" it works ok but when it takes more it doesn't.

As it follows:

```<code>START TRANSACTION;
DECLARE @coupon_ids VARCHAR(MAX);
-- Take one or more ids
SET @coupon_ids:=(SELECT IFNULL( (SELECT GROUP_CONCAT(coupon_id) FROM some_table WHERE order_id=(SELECT entity_id FROM sales_order WHERE increment_id=310033638) GROUP BY order_id),  (SELECT coupon_id FROM some_table WHERE coupon_id=310033638)));
SELECT @coupon_ids;
INSERT INTO some_table_gift VALUES (NULL,TRIM('whatever'),'','');
SET @lastid:=LAST_INSERT_ID();
-- Here if @coupon_ids is just one id, like 123 it works, if it is a list of them like 123,234,254 it doesn't works
UPDATE some_table SET owner_id=@lastid,is_gift=1 WHERE coupon_id IN (@coupon_ids);
COMMIT;
-- Same here
SELECT coupon_id,owner_id,is_gift FROM some_table WHERE coupon_id IN (@coupon_ids);
</code>```

Does anyone know how to work with this?

Thanks!

答:
What's your filed type for coupon_id, if it is not any number type than it will not work.

One way you can add quote (single quote) for each result in GROUP_CONCAT Write

```<code>GROUP_CONCAT(coupon_id SEPARATOR '","')
</code>```

remove SELECT @coupon_ids

And

in QUERY try this WHERE coupon_id IN ("@coupon_ids")

Body:
I'm becoming mad trying to use an "array" of values obtained from a GROUP_CONCAT into a WHERE IN statement, when GROUP_CONCAT only takes one "id" it works ok but when it takes more it doesn't.

As it follows:

START TRANSACTION;
DECLARE @coupon_ids VARCHAR(MAX);
-- Take one or more ids
SET @coupon_ids:=(SELECT IFNULL( (SELECT GROUP_CONCAT(coupon_id) FROM some_table WHERE order_id=(SELECT entity_id FROM sales_order WHERE increment_id=310033638) GROUP BY order_id),  (SELECT coupon_id FROM some_table WHERE coupon_id=310033638)));
SELECT @coupon_ids;
INSERT INTO some_table_gift VALUES (NULL,TRIM('whatever'),'','');
SET @lastid:=LAST_INSERT_ID();
-- Here if @coupon_ids is just one id, like 123 it works, if it is a list of them like 123,234,254 it doesn't works
UPDATE some_table SET owner_id=@lastid,is_gift=1 WHERE coupon_id IN (@coupon_ids);
COMMIT;
-- Same here
SELECT coupon_id,owner_id,is_gift FROM some_table WHERE coupon_id IN (@coupon_ids);

Does anyone know how to work with this?

Thanks!

Body:
What's your filed type for coupon_id, if it is not any number type than it will not work.

One way you can add quote (single quote) for each result in GROUP_CONCAT Write

GROUP_CONCAT(coupon_id SEPARATOR '","')

remove SELECT @coupon_ids

And

in QUERY try this WHERE coupon_id IN ("@coupon_ids")


问:
linux compilation - conflicting libraries
So I am not working on a computer but on an embedded device running ubuntu.

I am trying to compile openCV code but I have the feeling that I am in a deadlock!

This is the error I get:
problem:

```<code>/usr/bin/ld: warning: libopencv_core.so.3.2, needed by //usr/local/lib/libopencv_imgcodecs.so, may conflict with libopencv_core.so.2.4
/usr/bin/ld: /tmp/ccYlsBYW.o: undefined reference to symbol '_ZN2cv11setIdentityERKNS_17_InputOutputArrayERKNS_7Scalar_IdEE'
/usr/local/lib//libopencv_core.so.3.2: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
</code>```

rename 2.4 libraries:

```<code>ubuntu@tegra-ubuntu:/usr/lib$ sudo mv libopencv_core.so libopencv_core.soMyOld
ubuntu@tegra-ubuntu:/usr/lib$ sudo mv libopencv_core.so.2.4 libopencv_core.so.2.4MyOld
ubuntu@tegra-ubuntu:/usr/lib$ sudo mv libopencv_core.so.2.4.10 libopencv_core.so.2.4.10MyOld
</code>```

recompile code

```<code>/usr/bin/ld: warning: libopencv_core.so.2.4, needed by /usr/lib/gcc/arm-linux-gnueabihf/4.8/../../../../lib/libopencv_imgproc.so, not found (try using -rpath or -rpath-link)
/usr/bin/ld: warning: libopencv_imgproc.so.3.2, needed by //usr/local/lib/libopencv_imgcodecs.so, may conflict with libopencv_imgproc.so.2.4
/usr/bin/ld: /tmp/ccmcvWug.o: undefined reference to symbol '_ZN2cv6circleERKNS_17_InputOutputArrayENS_6Point_IiEEiRKNS_7Scalar_IdEEiii'
/usr/local/lib//libopencv_imgproc.so.3.2: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
</code>```

renaming 3.2 libraries:

```<code>ubuntu@tegra-ubuntu:/usr/local/lib$ sudo mv libopencv_core.so
ubuntu@tegra-ubuntu:/usr/local/lib$ sudo mv libopencv_core.so.3.2 libopencv_core.so.3.2MyOld
ubuntu@tegra-ubuntu:/usr/local/lib$ sudo mv libopencv_core.so.3.2.0 libopencv_core.so.3.2.0MyOld
</code>```

recompile

```<code>/usr/bin/ld: warning: libopencv_core.so.3.2, needed by //usr/local/lib/libopencv_imgcodecs.so, not found (try using -rpath or -rpath-link)
/usr/bin/ld: warning: libopencv_imgproc.so.3.2, needed by //usr/local/lib/libopencv_imgcodecs.so, may conflict with libopencv_imgproc.so.2.4
/usr/bin/ld: /tmp/cclHSHtB.o: undefined reference to symbol '_ZN2cv6circleERKNS_17_InputOutputArrayENS_6Point_IiEEiRKNS_7Scalar_IdEEiii'
/usr/local/lib//libopencv_imgproc.so.3.2: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
</code>```

What can I do to solve this issue? Uninstalling everything and reinstalling is not an option...

EDIT:

I compile with this command:

```<code>g++ src/personDetection.cpp src/personRecognition.cpp main.cpp -lopencv_core -lopencv_imgproc -lopencv_highgui -lopencv_imgcodecs -lopencv_calib3d -lopencv_features2d -lopencv_video -lopencv_videoio -pthread -o main
</code>```

答:
-L option is used to specify the directory path. Compiler will search this directory with other system standard directories, such as directories in LIBRARY_PATH. But it searches directories specified with -L first.

-l option is used to specify the name of the library.

In your case, 2.4 version libraries are in /usr/lib and 3.2 version libraries are in /usr/local/lib. Your code, probably, is expecting 2.4 version, but your system may be set to search /usr/local/lib before searching /usr/lib and this may be the cause of your problem.

By specifying -L/usr/lib you are telling compiler to search /usr/lib first, resulting in using 2.4 version libraries.

UPDATE

```<code>$ gcc -m64 -Xlinker --verbose  2>/dev/null | grep SEARCH | sed 's/SEARCH_DIR("=\?\([^"]\+\)"); */\1\n/g'  | grep -vE '^$'
</code>```

Above command will show you the list of default searched directories when linking. (copied the command from this article)

In my machine(Ubuntu 16.04, 64-bit), /usr/local/lib appears before /usr/lib. This means that a library in /usr/local/lib can override libraries in /usr/lib. (link)

Body:
So I am not working on a computer but on an embedded device running ubuntu.

I am trying to compile openCV code but I have the feeling that I am in a deadlock!

This is the error I get:
problem:

/usr/bin/ld: warning: libopencv_core.so.3.2, needed by //usr/local/lib/libopencv_imgcodecs.so, may conflict with libopencv_core.so.2.4
/usr/bin/ld: /tmp/ccYlsBYW.o: undefined reference to symbol '_ZN2cv11setIdentityERKNS_17_InputOutputArrayERKNS_7Scalar_IdEE'
/usr/local/lib//libopencv_core.so.3.2: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

rename 2.4 libraries:

ubuntu@tegra-ubuntu:/usr/lib$ sudo mv libopencv_core.so libopencv_core.soMyOld
ubuntu@tegra-ubuntu:/usr/lib$ sudo mv libopencv_core.so.2.4 libopencv_core.so.2.4MyOld
ubuntu@tegra-ubuntu:/usr/lib$ sudo mv libopencv_core.so.2.4.10 libopencv_core.so.2.4.10MyOld

recompile code

/usr/bin/ld: warning: libopencv_core.so.2.4, needed by /usr/lib/gcc/arm-linux-gnueabihf/4.8/../../../../lib/libopencv_imgproc.so, not found (try using -rpath or -rpath-link)
/usr/bin/ld: warning: libopencv_imgproc.so.3.2, needed by //usr/local/lib/libopencv_imgcodecs.so, may conflict with libopencv_imgproc.so.2.4
/usr/bin/ld: /tmp/ccmcvWug.o: undefined reference to symbol '_ZN2cv6circleERKNS_17_InputOutputArrayENS_6Point_IiEEiRKNS_7Scalar_IdEEiii'
/usr/local/lib//libopencv_imgproc.so.3.2: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

renaming 3.2 libraries:

ubuntu@tegra-ubuntu:/usr/local/lib$ sudo mv libopencv_core.so
ubuntu@tegra-ubuntu:/usr/local/lib$ sudo mv libopencv_core.so.3.2 libopencv_core.so.3.2MyOld
ubuntu@tegra-ubuntu:/usr/local/lib$ sudo mv libopencv_core.so.3.2.0 libopencv_core.so.3.2.0MyOld

recompile

/usr/bin/ld: warning: libopencv_core.so.3.2, needed by //usr/local/lib/libopencv_imgcodecs.so, not found (try using -rpath or -rpath-link)
/usr/bin/ld: warning: libopencv_imgproc.so.3.2, needed by //usr/local/lib/libopencv_imgcodecs.so, may conflict with libopencv_imgproc.so.2.4
/usr/bin/ld: /tmp/cclHSHtB.o: undefined reference to symbol '_ZN2cv6circleERKNS_17_InputOutputArrayENS_6Point_IiEEiRKNS_7Scalar_IdEEiii'
/usr/local/lib//libopencv_imgproc.so.3.2: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

What can I do to solve this issue? Uninstalling everything and reinstalling is not an option...

EDIT:

I compile with this command:

g++ src/personDetection.cpp src/personRecognition.cpp main.cpp -lopencv_core -lopencv_imgproc -lopencv_highgui -lopencv_imgcodecs -lopencv_calib3d -lopencv_features2d -lopencv_video -lopencv_videoio -pthread -o main

Body:
-L option is used to specify the directory path. Compiler will search this directory with other system standard directories, such as directories in LIBRARY_PATH. But it searches directories specified with -L first.

-l option is used to specify the name of the library.

In your case, 2.4 version libraries are in /usr/lib and 3.2 version libraries are in /usr/local/lib. Your code, probably, is expecting 2.4 version, but your system may be set to search /usr/local/lib before searching /usr/lib and this may be the cause of your problem.

By specifying -L/usr/lib you are telling compiler to search /usr/lib first, resulting in using 2.4 version libraries.

UPDATE

$ gcc -m64 -Xlinker --verbose  2>/dev/null | grep SEARCH | sed 's/SEARCH_DIR("=\?\([^"]\+\)"); */\1\n/g'  | grep -vE '^$'

Above command will show you the list of default searched directories when linking. (copied the command from this article)

In my machine(Ubuntu 16.04, 64-bit), /usr/local/lib appears before /usr/lib. This means that a library in /usr/local/lib can override libraries in /usr/lib. (link)


问:
Cucumber hooks control flow?
I'm trying to write automated UI tests using Espresso and Cucumber. So far I've managed to successfully execute step definitions for a feature that tests a single activity using ActivityTestRule. I use Cucumber's @Before annotation to prepare for the scenario, for example launch the required activity. The issue is that when I try to execute a test suite containing more than one feature definition all @Before blocks will be called before every scenario. For example when the instrumentation core starts executing scenario 1, it executes the @Before methods both in scenario 1 and scenario 2 resulting in overlapping activity launches and failing tests.

```<code>public class Activity1Stepdefs {

    @Before
    public void setUp() {
        // Called before both scenario 1 and scenario 2, needs to be called only before scenario 1.
    }

    @Given("^scenario 1$")
    public void scenario_1() throws Throwable {
        // Scenario 1
    }
}

public class Activity2Stepdefs {

    @Before
    public void setUp() {
        // Called before both scenario 1 and scenario 2, needs to be called only before scenario 2.
    }

    @Given("^scenario 2$")
    public void scenario_2() throws Throwable {
        // Scenario 2
    }
}
</code>```

Resulting control flow:

Activity1Stepdefs.setUp()

Activity2Stepdefs.setUp()

Activity1Stepdefs.scenario_1()

Activity2Stepdefs.setUp()

Activity1Stepdefs.setUp()

Activity2Stepdefs.scenario_2

Desired control flow:

Activity1Stepdefs.setUp()

Activity1Stepdefs.scenario_1()

Activity2Stepdefs.setUp()

Activity2Stepdefs.scenario_2

答:
This can be achieved by tagged hooks. First assign tags for scenario 1 and 2 in the feature file then create tagged hooks as give below.
Assume I have given tag name for scenario 1 and 2 as scen1 and scen2 respectively.
 before ("@scen1")
    public void scenarioOneSetup()
{ // code for scenario 1 setup }
before ("@scen2")
public void scenarioTwoSetup()
{// code for scenario 2 setup}

Title: Cucumber hooks control flow?

Body:
I'm trying to write automated UI tests using Espresso and Cucumber. So far I've managed to successfully execute step definitions for a feature that tests a single activity using ActivityTestRule. I use Cucumber's @Before annotation to prepare for the scenario, for example launch the required activity. The issue is that when I try to execute a test suite containing more than one feature definition all @Before blocks will be called before every scenario. For example when the instrumentation core starts executing scenario 1, it executes the @Before methods both in scenario 1 and scenario 2 resulting in overlapping activity launches and failing tests.

public class Activity1Stepdefs {

    @Before
    public void setUp() {
        // Called before both scenario 1 and scenario 2, needs to be called only before scenario 1.
    }

    @Given("^scenario 1$")
    public void scenario_1() throws Throwable {
        // Scenario 1
    }
}

public class Activity2Stepdefs {

    @Before
    public void setUp() {
        // Called before both scenario 1 and scenario 2, needs to be called only before scenario 2.
    }

    @Given("^scenario 2$")
    public void scenario_2() throws Throwable {
        // Scenario 2
    }
}

Resulting control flow:

Activity1Stepdefs.setUp()

Activity2Stepdefs.setUp()

Activity1Stepdefs.scenario_1()

Activity2Stepdefs.setUp()

Activity1Stepdefs.setUp()

Activity2Stepdefs.scenario_2

Desired control flow:

Activity1Stepdefs.setUp()

Activity1Stepdefs.scenario_1()

Activity2Stepdefs.setUp()

Activity2Stepdefs.scenario_2