问:
Using $variable in PHP MySQL LIMIT
This is my current code which i'm using inside a php script.

```<code>$prodid = $_GET['id'];
$query = mysql_query("SELECT * FROM table1 WHERE productid = '$prodid'
ORDER by amount DESC LIMIT 3");
</code>```

I've set the LIMIT as 3. But I want to define something like '$count' and the value for $count should be fetched from a MySQL query i.e

```<code>$count = mysql_query("SELECT count FROM table1 WHERE productid = '$prodid'");
</code>```

The LIMIT must change with respect to the '$prodid'. Like this,

```<code>mysql_query("SELECT * FROM table1 WHERE productid = '$prodid'
ORDER by amount DESC LIMIT '$count'");
</code>```

答:
A few things.

First, you are using this query to find the number of rows to fetch.

```<code> "SELECT count FROM table1 WHERE productid = '$prodid'"
</code>```

That should say

```<code> "SELECT COUNT(*) FROM table1 WHERE productid = '$prodid'"
</code>```

in order to get a count of rows.

And, it should say

```<code> "SELECT COUNT(*) FROM table1 WHERE productid = " . intval($prodid)
</code>```

to avoid sql injection (assuming your prodid values are integers).

Second, the query above gives back a one-row result set. You need to actually read that row. I'm not going to tell you how to do that using mysql_ because only a fool uses mysql_ these days. Please, please use PDO or mysqli_.

Third, this query

```<code>"SELECT * FROM table1 WHERE productid = " . intval($prodid) . " ORDER by amount DESC"
</code>```

always returns the number of rows your previous query wanted. So your LIMIT clause is entirely unnecessary in the example you've given.

Title: Using $variable in PHP MySQL LIMIT

Body:
This is my current code which i'm using inside a php script.

$prodid = $_GET['id'];
$query = mysql_query("SELECT * FROM table1 WHERE productid = '$prodid'
ORDER by amount DESC LIMIT 3");

I've set the LIMIT as 3. But I want to define something like '$count' and the value for $count should be fetched from a MySQL query i.e

$count = mysql_query("SELECT count FROM table1 WHERE productid = '$prodid'");

The LIMIT must change with respect to the '$prodid'. Like this,

mysql_query("SELECT * FROM table1 WHERE productid = '$prodid'
ORDER by amount DESC LIMIT '$count'");

Body:
A few things.

First, you are using this query to find the number of rows to fetch.

 "SELECT count FROM table1 WHERE productid = '$prodid'"

That should say

 "SELECT COUNT(*) FROM table1 WHERE productid = '$prodid'"

in order to get a count of rows.

And, it should say

 "SELECT COUNT(*) FROM table1 WHERE productid = " . intval($prodid)

to avoid sql injection (assuming your prodid values are integers).

Second, the query above gives back a one-row result set. You need to actually read that row. I'm not going to tell you how to do that using mysql_ because only a fool uses mysql_ these days. Please, please use PDO or mysqli_.

Third, this query

"SELECT * FROM table1 WHERE productid = " . intval($prodid) . " ORDER by amount DESC"

always returns the number of rows your previous query wanted. So your LIMIT clause is entirely unnecessary in the example you've given.


来源: stackexchange

问:
Error when using the command "virtualenv venv" to create Python virtual environment
When I used the command virtualenv venv to create the Python virtual environment, the following error occurred:

```<code>D:\Flask>virtualenv venv
Using base prefix 'd:\\APP\\python'
New python executable in D:\Flask\venv\Scripts\python.exe
Installing setuptools, pip, wheel...
  Complete output from command D:\Flask\venv\Scripts\python.exe - setuptools pip wheel:
  Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
ImportError: No module named 'pkgutil'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
  File "d:\APP\python\lib\runpy.py", line 170, in _run_module_as_main
    "__main__", mod_spec)
  File "d:\APP\python\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "D:\APP\python\Scripts\virtualenv.exe\__main__.py", line 9, in <module>
  File "d:\APP\python\lib\site-packages\virtualenv.py", line 713, in main
    symlink=options.symlink)
  File "d:\APP\python\lib\site-packages\virtualenv.py", line 945, in create_environment
    download=download,
  File "d:\APP\python\lib\site-packages\virtualenv.py", line 901, in install_wheel
    call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=SCRIPT)
  File "d:\APP\python\lib\site-packages\virtualenv.py", line 797, in call_subprocess
    % (cmd_desc, proc.returncode))
OSError: Command D:\Flask\venv\Scripts\python.exe - setuptools pip wheel failed with error code 1
</code>```

I googled it but didn't find a solution. Does anyone know how to deal with it?

答:
use python -m venv path/to/your/venv to create a virtual environment and then activate it with path/to/your/venv/Scripts/activate.bat (deactivate for quitting the venv)

example:

```<code>python -m venv test
test\Scripts\activate.bat
(test) deactivate
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When I used the command virtualenv venv to create the Python virtual environment, the following error occurred:

D:\Flask>virtualenv venv
Using base prefix 'd:\\APP\\python'
New python executable in D:\Flask\venv\Scripts\python.exe
Installing setuptools, pip, wheel...
  Complete output from command D:\Flask\venv\Scripts\python.exe - setuptools pip wheel:
  Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
ImportError: No module named 'pkgutil'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
  File "d:\APP\python\lib\runpy.py", line 170, in _run_module_as_main
    "__main__", mod_spec)
  File "d:\APP\python\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "D:\APP\python\Scripts\virtualenv.exe\__main__.py", line 9, in <module>
  File "d:\APP\python\lib\site-packages\virtualenv.py", line 713, in main
    symlink=options.symlink)
  File "d:\APP\python\lib\site-packages\virtualenv.py", line 945, in create_environment
    download=download,
  File "d:\APP\python\lib\site-packages\virtualenv.py", line 901, in install_wheel
    call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=SCRIPT)
  File "d:\APP\python\lib\site-packages\virtualenv.py", line 797, in call_subprocess
    % (cmd_desc, proc.returncode))
OSError: Command D:\Flask\venv\Scripts\python.exe - setuptools pip wheel failed with error code 1

I googled it but didn't find a solution. Does anyone know how to deal with it?

Body:
use python -m venv path/to/your/venv to create a virtual environment and then activate it with path/to/your/venv/Scripts/activate.bat (deactivate for quitting the venv)

example:

python -m venv test
test\Scripts\activate.bat
(test) deactivate


问:
HANA index server won't start
I've installed HANA Express edition from binary in a VM (4 cores and 8GB of RAM) when I run HDB info it give me

```<code>USER       PID  PPID %CPU    VSZ   RSS COMMAND
hxeadm   12253 12252  0.0 115512  2024 -bash
hxeadm   12305 12253  0.0 113256  1616  \_ /bin/sh /usr/sap/HXE/HDB01/HDB info
hxeadm   12340 12305  0.0 151060  1804      \_ ps fx -U hxeadm -o user,pid,ppid,pcpu,vsz,rss,args
hxeadm    4641     1  0.0  23044  1708 sapstart pf=/usr/sap/HXE/SYS/profile/HXE_HDB01_amds-bd
hxeadm    4788  4641  0.0 232064 36552  \_ /usr/sap/HXE/HDB01/amds-bd/trace/hdb.sapHXE_HDB01 -d -nw -f /usr/sap/HXE/HDB01/amds-bd/daemon.ini pf=/usr/sap/HXE/SYS/profile/H

hxeadm    5239  4788  6.2 3184688 2271760      \_ hdbnameserver
hxeadm   10672  4788  1.1 1121576 416644      \_ hdbcompileserver
hxeadm   10681  4788  0.2 1028188 297320      \_ hdbpreprocessor
hxeadm   10826  4788  0.3 1336672 519228      \_ hdbwebdispatcher
hxeadm    3562     1  0.0 432156 26000 /usr/sap/HXE/HDB01/exe/sapstartsrv pf=/usr/sap/HXE/SYS/profile/HXE_HDB01_amds-bd -D -u hxeadm
</code>```

as you can see, the hdbindexserver is not started, and to be more sure I've checked the port number 30015, ant it's not used at all.

I've tried with the Virtual machine provisioned by HANA installer, but I've got the same results.

My question is how to start the index server?

Thank you in advance.

答:
Since you have an OS level access, you can try to start it manually:

```<code>/usr/sap/HXE/HDB01/exe/hdbindexserver
</code>```

and see why it fails in logs, which are located at

```<code>/usr/sap/HXE/HDB01/<name_of_your_server>/trace/indexserver_alert_sixtb.trc
</code>```

You can check other files in the same folder as well.

It is also possible to start indexserver from HANA Studio. Right click on the instance (with SYSTEM user) --> Configuration and Monitoring --> Open Administration --> Landscape

The logs are available under --> Diagnosis Files in the Administration.

ContentLicense: CC BY-SA 4.0

Title: HANA index server won't start

Body:
I've installed HANA Express edition from binary in a VM (4 cores and 8GB of RAM) when I run HDB info it give me

USER       PID  PPID %CPU    VSZ   RSS COMMAND
hxeadm   12253 12252  0.0 115512  2024 -bash
hxeadm   12305 12253  0.0 113256  1616  \_ /bin/sh /usr/sap/HXE/HDB01/HDB info
hxeadm   12340 12305  0.0 151060  1804      \_ ps fx -U hxeadm -o user,pid,ppid,pcpu,vsz,rss,args
hxeadm    4641     1  0.0  23044  1708 sapstart pf=/usr/sap/HXE/SYS/profile/HXE_HDB01_amds-bd
hxeadm    4788  4641  0.0 232064 36552  \_ /usr/sap/HXE/HDB01/amds-bd/trace/hdb.sapHXE_HDB01 -d -nw -f /usr/sap/HXE/HDB01/amds-bd/daemon.ini pf=/usr/sap/HXE/SYS/profile/H

hxeadm    5239  4788  6.2 3184688 2271760      \_ hdbnameserver
hxeadm   10672  4788  1.1 1121576 416644      \_ hdbcompileserver
hxeadm   10681  4788  0.2 1028188 297320      \_ hdbpreprocessor
hxeadm   10826  4788  0.3 1336672 519228      \_ hdbwebdispatcher
hxeadm    3562     1  0.0 432156 26000 /usr/sap/HXE/HDB01/exe/sapstartsrv pf=/usr/sap/HXE/SYS/profile/HXE_HDB01_amds-bd -D -u hxeadm

as you can see, the hdbindexserver is not started, and to be more sure I've checked the port number 30015, ant it's not used at all.

I've tried with the Virtual machine provisioned by HANA installer, but I've got the same results.

My question is how to start the index server?

Thank you in advance.

Body:
Since you have an OS level access, you can try to start it manually:

/usr/sap/HXE/HDB01/exe/hdbindexserver

and see why it fails in logs, which are located at

/usr/sap/HXE/HDB01/<name_of_your_server>/trace/indexserver_alert_sixtb.trc

You can check other files in the same folder as well.

It is also possible to start indexserver from HANA Studio. Right click on the instance (with SYSTEM user) --> Configuration and Monitoring --> Open Administration --> Landscape

The logs are available under --> Diagnosis Files in the Administration.


问:
How to check if credentials are correct or database does exists before creating "new PDO"
```<code>$dbname='database_name';

$dbuser='database_user';
$dbpass='database_password';
$dbhost='localhost';
$con = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
$con->query("SET NAMES 'utf8'");
</code>```

How can I check if database_name, database_user, database_password are correct or if the database exists.

答:
As it has been suggested, use a try/catch:</p>

```<code>$dbname='database_name';
$dbuser='database_user';
$dbpass='database_password';
$dbhost='localhost';

try {
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
    // if you do not want to output message you can log the errors
    echo $e->getMessage();
    $errorCode = $e->getCode();
}
</code>```

Body:
$dbname='database_name';

$dbuser='database_user';
$dbpass='database_password';
$dbhost='localhost';
$con = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
$con->query("SET NAMES 'utf8'");

How can I check if database_name, database_user, database_password are correct or if the database exists.

Body:
As it has been suggested, use a try/catch:

$dbname='database_name';
$dbuser='database_user';
$dbpass='database_password';
$dbhost='localhost';

try {
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
    // if you do not want to output message you can log the errors
    echo $e->getMessage();
    $errorCode = $e->getCode();
}


问:
C++ append int to wstring
Before(using ASCII) i was using std::string as buffer like this:

```<code>std::string test = "";
int value = 6;
test.append("some string");
test.append((char*)value, 4);
test.append("some string");
</code>```

with expected value in test:

"some srtring\x6\x0\x0\x0somestring"

Now i am tring to use Unicode and i wanna keep the same "code" but trubles happens:

```<code>std::wstring test = "";
int value = 6;
test.append("some string");
test.append((wchar_t*)value, 4); (buffer overflow cause reading 8 bytes)
test.append("some string");
</code>```

How can i append bytes like in std::string?
Doing:

```<code>std::wstring test = "";
int value = 6;
test.append("some string");
test.append((wchar_t*)value, 2);
test.append("some string");
</code>```

Solve partially the problem cause after i can't append bools.

EDIT:
i can even use wstringstream if a binary copy is applied.(normally not)

答: I think a IStream is a proper way to do this...i'll make an interface to handle different types. I was abusing std::string for an easy "dynamic binary array", with std::wstring this is not possible,for many reasons but most silly one is that require at least 2 bytes, so no room for a bool</p>

Title: C++ append int to wstring

Body:
Before(using ASCII) i was using std::string as buffer like this:

std::string test = "";
int value = 6;
test.append("some string");
test.append((char*)value, 4);
test.append("some string");

with expected value in test:

"some srtring\x6\x0\x0\x0somestring"

Now i am tring to use Unicode and i wanna keep the same "code" but trubles happens:

std::wstring test = "";
int value = 6;
test.append("some string");
test.append((wchar_t*)value, 4); (buffer overflow cause reading 8 bytes)
test.append("some string");

How can i append bytes like in std::string?
Doing:

std::wstring test = "";
int value = 6;
test.append("some string");
test.append((wchar_t*)value, 2);
test.append("some string");

Solve partially the problem cause after i can't append bools.

EDIT:
i can even use wstringstream if a binary copy is applied.(normally not)


问:
Refreshing vue-router view after ajax request
I have a vue router with two components,a list and a detail view, with a link back to the list view. On the same page I have a list of the same data that is shown in the list-view component.

The data is fetched via ajax, and as such is not ready when the router-view is drawn. When the data is ready however, the non-router list is updated, but the router view is not.

How do I communicate to the router view that it should redraw with new data?

If I click on an item in the non-router list, the router-view changes to the details component as expected, and if I then click the "show list" it changes back to the list-component, but this time it is populated with the right data.

I have created a js-fiddle that contains the relevant code: https://jsfiddle.net/pengman/jkwvphf9/2/
(It fakes the ajax by using setTimeout, but the effect is the same)

Html code:

```<code><div id="app">
Router-view:
  <router-view class="view"></router-view>
  <br>
  Unrouted list:
  <div class="list-group">
    <router-link v-for="plante in planter" class="list-group-item" :to="{ name: 'plante', params: { nummer: plante.Nummer }}">{{ plante.Navn }} | </router-link>
  </div>
</div>

<template id="plante-listing-template">

        <ul>
            <li v-for="plante in planter">
                {{ plante.Navn }} <router-link :to="{ name: 'plante', params: { nummer: plante.Nummer }}">Vis</router-link>
            </li>
        </ul>
    </template>

    <template id="plante-detail-template">
        <div>
            plante detail template:
            <h3>{{ plante.Navn }}</h3>
            <router-link to="/">Show List</router-link>
        </div>
        <br>
    </template>
</code>```

Javascript code:

```<code>var PlanteListing = {
  template: '#plante-listing-template',

  data: function () {
    return {
      planter: this.$parent.planter
    }
  },
  watch: {
    '$route'(to, from) {
      // vi skal opdatere data, saa vi skal beregne igen
      this.planter = this.$parent.planter;
    },
    'dataloaded'() {
      this.planter = this.$parent.planter;
    }
  }
};

var PlanteDetail = {
  template: '#plante-detail-template',
  data: function () {
    var parent = this.$parent;
    var nummerFromRoute = this.$route.params.nummer;
    //console.log(nummerFromRoute);
    var filtered = this.$parent.planter.filter(function (item) {
      return (item.Nummer == nummerFromRoute) ? item : false;
    });

    return {
      plante: filtered[0]
    }
  },
  watch: {
    '$route'(to, from) {
      // vi skal opdatere data, saa vi skal beregne igen
      var nummerFromRoute = this.$route.params.nummer;

      var filtered = this.$parent.planter.filter(function (item) {
        return (item.Nummer == nummerFromRoute) ? item : false;
      });
      this.plante = filtered[0];
    },
  }
};

var router = new VueRouter({
  mode: 'hash',
  base: window.location.href,
  routes: [
    { path: '/', component: PlanteListing },
    { name: 'plante', path: '/:nummer', component: PlanteDetail }
  ]
});

var app = new Vue({
  router,
  data: {
    planter: []
  },
  components: { PlanteListing: PlanteListing },
  methods: {
    getJson: function () {
      var self = this;
            /* Real code:
      $.getJSON("content/planter.json", function (param) {
        this.planter = param;
      }.bind(this));
      */
      /* Simulation code: */
      setTimeout(function(){self.planter = [  {    "Nummer": "0",    "Navn": "Bertha Winters"  },  {    "Nummer": "1",    "Navn": "Jeannie Small"  },  {    "Nummer": "2",    "Navn": "Mckay Joyner"  },  {    "Nummer": "3",    "Navn": "Janelle Banks"  },  {    "Nummer": "4",    "Navn": "Bray Moran"  },  {    "Nummer": "5",    "Navn": "Hooper Schwartz"  }]; console.log('data loaded')}, 500);
    }
  },
  created: function () {
    this.getJson();
  }
}).$mount('#app');
</code>```

答:
Typically you do not want to have a component reach out of itself to get data (as you are doing with this.$parent.planter). Instead, you want to pass it props. To that end, I've modified your code a bit.

The first thing is I upgraded your vue-router to the latest version. This allows you to use the props argument on routes.

```<code>var router = new VueRouter({
  mode: 'hash',
  base: window.location.href,
  routes: [
    { path: '/', component: PlanteListing },
    { name: 'plante', path: '/:nummer', component: PlanteDetail, props: true }
  ]
});
</code>```

Secondly, you are using planter in all your routes, so I have provided it as a property on the router-view.

```<code><router-view class="view" :planter="planter"></router-view>
</code>```

This allows us to clean up your component routes and add the data they need as props.

```<code>var PlanteListing = {
  template: '#plante-listing-template',
  props:["planter"]
};

var PlanteDetail = {
  template: '#plante-detail-template',
  props:["planter", "nummer"],
  data: function () {
    var filtered = this.planter.filter(item => item.Nummer == this.nummer);
    return {
      plante: filtered[0]
    }
  }
};
</code>```

There is no need to tell the router to redraw; because the data are props, Vue just takes care of that for us.

Here is your updated fiddle.

Body:
I have a vue router with two components,a list and a detail view, with a link back to the list view. On the same page I have a list of the same data that is shown in the list-view component.

The data is fetched via ajax, and as such is not ready when the router-view is drawn. When the data is ready however, the non-router list is updated, but the router view is not.

How do I communicate to the router view that it should redraw with new data?

If I click on an item in the non-router list, the router-view changes to the details component as expected, and if I then click the "show list" it changes back to the list-component, but this time it is populated with the right data.

I have created a js-fiddle that contains the relevant code: https://jsfiddle.net/pengman/jkwvphf9/2/
(It fakes the ajax by using setTimeout, but the effect is the same)

Html code:

Router-view:
  <router-view class="view"></router-view>

  Unrouted list:

    <router-link v-for="plante in planter" class="list-group-item" :to="{ name: 'plante', params: { nummer: plante.Nummer }}">{{ plante.Navn }} | </router-link>

<template id="plante-listing-template">

                {{ plante.Navn }} <router-link :to="{ name: 'plante', params: { nummer: plante.Nummer }}">Vis</router-link>

    </template>

    <template id="plante-detail-template">

            plante detail template:

{{ plante.Navn }}

            <router-link to="/">Show List</router-link>

    </template>

Javascript code:

var PlanteListing = {
  template: '#plante-listing-template',

  data: function () {
    return {
      planter: this.$parent.planter
    }
  },
  watch: {
    '$route'(to, from) {
      // vi skal opdatere data, saa vi skal beregne igen
      this.planter = this.$parent.planter;
    },
    'dataloaded'() {
      this.planter = this.$parent.planter;
    }
  }
};

var PlanteDetail = {
  template: '#plante-detail-template',
  data: function () {
    var parent = this.$parent;
    var nummerFromRoute = this.$route.params.nummer;
    //console.log(nummerFromRoute);
    var filtered = this.$parent.planter.filter(function (item) {
      return (item.Nummer == nummerFromRoute) ? item : false;
    });

    return {
      plante: filtered[0]
    }
  },
  watch: {
    '$route'(to, from) {
      // vi skal opdatere data, saa vi skal beregne igen
      var nummerFromRoute = this.$route.params.nummer;

      var filtered = this.$parent.planter.filter(function (item) {
        return (item.Nummer == nummerFromRoute) ? item : false;
      });
      this.plante = filtered[0];
    },
  }
};

var router = new VueRouter({
  mode: 'hash',
  base: window.location.href,
  routes: [
    { path: '/', component: PlanteListing },
    { name: 'plante', path: '/:nummer', component: PlanteDetail }
  ]
});

var app = new Vue({
  router,
  data: {
    planter: []
  },
  components: { PlanteListing: PlanteListing },
  methods: {
    getJson: function () {
      var self = this;
            /* Real code:
      $.getJSON("content/planter.json", function (param) {
        this.planter = param;
      }.bind(this));
      */
      /* Simulation code: */
      setTimeout(function(){self.planter = [  {    "Nummer": "0",    "Navn": "Bertha Winters"  },  {    "Nummer": "1",    "Navn": "Jeannie Small"  },  {    "Nummer": "2",    "Navn": "Mckay Joyner"  },  {    "Nummer": "3",    "Navn": "Janelle Banks"  },  {    "Nummer": "4",    "Navn": "Bray Moran"  },  {    "Nummer": "5",    "Navn": "Hooper Schwartz"  }]; console.log('data loaded')}, 500);
    }
  },
  created: function () {
    this.getJson();
  }
}).$mount('#app');

Body:
Typically you do not want to have a component reach out of itself to get data (as you are doing with this.$parent.planter). Instead, you want to pass it props. To that end, I've modified your code a bit.

The first thing is I upgraded your vue-router to the latest version. This allows you to use the props argument on routes.

var router = new VueRouter({
  mode: 'hash',
  base: window.location.href,
  routes: [
    { path: '/', component: PlanteListing },
    { name: 'plante', path: '/:nummer', component: PlanteDetail, props: true }
  ]
});

Secondly, you are using planter in all your routes, so I have provided it as a property on the router-view.

<router-view class="view" :planter="planter"></router-view>

This allows us to clean up your component routes and add the data they need as props.

var PlanteListing = {
  template: '#plante-listing-template',
  props:["planter"]
};

var PlanteDetail = {
  template: '#plante-detail-template',
  props:["planter", "nummer"],
  data: function () {
    var filtered = this.planter.filter(item => item.Nummer == this.nummer);
    return {
      plante: filtered[0]
    }
  }
};

There is no need to tell the router to redraw; because the data are props, Vue just takes care of that for us.

Here is your updated fiddle.


问:
Conflicting names error when installing Alamofire pod
I created an app with a watch and a today extension running Xcode 8.2.1. with Swift 3. For all targets, I want to use Alamofire to fire up requests. This worked perfectly fine with the iOS app and the Watch Extension, but pod install throws following error when trying to add it to the today target:

```<code>The 'Pods-xY' target has frameworks with conflicting names: alamofire.
</code>```

Here's my podfile:

```<code>target 'xY' do
  use_frameworks!
  pod 'Alamofire', '~> 4.4'
end

target 'xYToday' do
  use_frameworks!
  pod 'Alamofire', '~> 4.4'
end

target 'xYWatch Extension' do
  use_frameworks!
  pod 'Alamofire', '~> 4.4'
end
</code>```

答:
I ran into the same issue, just today. Apparently it is not possible to use the same framework in a today extension and in an app. See this comment.

Cocoapods should give a decent error message, which is a bug, but for now, only Apple could fix this like both you and I would have expected, see this comment by the same guy later in the thread.

Bummer!

Body:
I created an app with a watch and a today extension running Xcode 8.2.1. with Swift 3. For all targets, I want to use Alamofire to fire up requests. This worked perfectly fine with the iOS app and the Watch Extension, but pod install throws following error when trying to add it to the today target:

The 'Pods-xY' target has frameworks with conflicting names: alamofire.

Here's my podfile:

target 'xY' do
  use_frameworks!
  pod 'Alamofire', '~> 4.4'
end

target 'xYToday' do
  use_frameworks!
  pod 'Alamofire', '~> 4.4'
end

target 'xYWatch Extension' do
  use_frameworks!
  pod 'Alamofire', '~> 4.4'
end


问:
NodeMCU and HX711 using ESPlorer
I don't know if his is the correct topic to ask this but here it goes:

I have a NodeMCU devkit 0.9 and I'm am able to use ESPlorer to upload basic code like the web server with some buttons that turn on and off LEDs on the board.

I was trying to interface NodeMCU with a load cell amplifier (HX711), which I saw has libraries for NodeMCU. How can I "include" hx711.c in my .lua file for it to recognize the functions inside hx711.c?

The error that appears when I try to send to ESP is

LUA interpreter error detected
  stdin:1: attempt to index global 'hx711' (a nil value)..."

Best regards.

答: You need to build a NodeMCU firmware that includes the HX711 module. Then you need to flash the new firmware to your devkit.</p>

Title: NodeMCU and HX711 using ESPlorer


问:
Access class members from nested functions

i have this class in javascript

```<code>var MyGird = Class.extend({
  classMemeber1 : "Some Value"
  ,clickEvent : function(){
        this.editor.on({
            afteredit: function() {
                //
                //  HOW TO I ACCESS classMemeber1 from here? ?
                //
                //
            }
        })
})
</code>```

how do i access classMemeber1 from inside of afteredit...

Thanks

答:
If you write ES6, you can use arrow functions: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

In your example, should be something like (not tested):

var MyGird = Class.extend({
    classMemeber1: "Some Value",
    clickEvent: () => {
        this.editor.on({
            afteredit: () => () {
                alert(this.classMemeber1);
            }
        });
    },
    // ...
});
```

Body:
i have this class in javascript

var MyGird = Class.extend({
  classMemeber1 : "Some Value"
  ,clickEvent : function(){
        this.editor.on({
            afteredit: function() {
                //
                //  HOW TO I ACCESS classMemeber1 from here? ?
                //
                //
            }
        })
})

how do i access classMemeber1 from inside of afteredit...

Thanks


问:
Laravel, select from DB from the end, but in asc order
I want to get rows from the end of the table, but in asc order.

We have this data: Result: 1, 2, 3, 4, 5, ..., 99.
Message::select()->where('thread_id', $id)->orderBy('updated_at', 'asc')->get();

If we change orderBy to desc and use it with take(5), then we have: Result: 99, 98, 97, 96, 95.
Message::select()->where('thread_id', $id)->skip(0)->take(5)->orderBy('updated_at', 'desc')->get();

How can I get Result: 95, 96, 97, 98, 99?

p.s. of course I can do it with skip(95)->take(5)->orderBy('updated_at', 'asc'), but how to do it dynamically.

答:
Solved by this way:

```<code>$messages_query = Message::select()->where('thread_id', 1)->orderBy('updated_at', 'asc');
$count = $messages_query->count();
$messages = $messages_query->skip($count-$count_to_take)->take($count_to_take)->get();
</code>```

Where $count_to_take for example =10.

Body:
Solved by this way:

$messages_query = Message::select()->where('thread_id', 1)->orderBy('updated_at', 'asc');
$count = $messages_query->count();
$messages = $messages_query->skip($count-$count_to_take)->take($count_to_take)->get();

Where $count_to_take for example =10.


问:
How to center the elements in ConstraintLayout
I am using ConstraintLayout in my application to make applications layout. I am trying to a create a screen wheren one EditText and Button should be in center and Button should be below of EditText with a marginTop only 16dp.

Here is my layout and screenshot how it is looking right now.

activity_authenticate_content.xml

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    tools:context="com.icici.iciciappathon.login.AuthenticationActivity">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/client_id_input_layout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <android.support.design.widget.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/login_client_id"
            android:inputType="textEmailAddress" />

    </android.support.design.widget.TextInputLayout>

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/authenticate"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="@string/login_auth"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="@id/client_id_input_layout"
        app:layout_constraintRight_toRightOf="@id/client_id_input_layout"
        app:layout_constraintTop_toTopOf="@id/client_id_input_layout" />

</android.support.constraint.ConstraintLayout>
</code>```

答:
Update:

Chain

You can now use the chain feature in packed mode as describe in Eugene's answer.

Guideline

You can use a horizontal guideline at 50% position and add bottom and top (8dp) constraints to edittext and button:

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/client_id_input_layout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent">

        <android.support.design.widget.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/login_client_id"
            android:inputType="textEmailAddress"/>

    </android.support.design.widget.TextInputLayout>

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/authenticate"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/login_auth"
        app:layout_constraintTop_toTopOf="@+id/guideline"
        android:layout_marginTop="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"/>

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5"/>

</android.support.constraint.ConstraintLayout>
</code>```

Body:
I am using ConstraintLayout in my application to make applications layout. I am trying to a create a screen wheren one EditText and Button should be in center and Button should be below of EditText with a marginTop only 16dp.

Here is my layout and screenshot how it is looking right now.

activity_authenticate_content.xml

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    tools:context="com.icici.iciciappathon.login.AuthenticationActivity">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/client_id_input_layout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <android.support.design.widget.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/login_client_id"
            android:inputType="textEmailAddress" />

    </android.support.design.widget.TextInputLayout>

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/authenticate"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="@string/login_auth"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="@id/client_id_input_layout"
        app:layout_constraintRight_toRightOf="@id/client_id_input_layout"
        app:layout_constraintTop_toTopOf="@id/client_id_input_layout" />

</android.support.constraint.ConstraintLayout>

Body:
Update:

Chain

You can now use the chain feature in packed mode as describe in Eugene's answer.

Guideline

You can use a horizontal guideline at 50% position and add bottom and top (8dp) constraints to edittext and button:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/client_id_input_layout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent">

        <android.support.design.widget.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/login_client_id"
            android:inputType="textEmailAddress"/>

    </android.support.design.widget.TextInputLayout>

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/authenticate"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/login_auth"
        app:layout_constraintTop_toTopOf="@+id/guideline"
        android:layout_marginTop="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"/>

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5"/>

</android.support.constraint.ConstraintLayout>


问:
How to fetch values from a JSON file on click event using ID and display the values in a form
I'm trying to view and edit data on two separate DIV tags.
I have implemented the click even to show the edit form on click event of the edit button in the view page.
Now what i want is, if i click the edit button, i want to fetch the particular items Values and populate it in a form.
i.e, checkbox values should be checked, input fields filled and radiobutton selected.
Here is how i got so far,

HTML:

```<code><div class="panelList" id="panelList" hidden>
<form action="#" name="">
    <label class="uno">Panel Category:</label>
    <span class="spec1">
    <input type="checkbox" value="1" name="panel2[]">&nbspRegular&nbsp&nbsp
    <input type="checkbox" value="2" name="panel2[]">&nbspReduced fee</input>&nbsp&nbsp
    <input type="checkbox" value="3" name="panel2[]">&nbspLimited Assistance Referral</input>&nbsp&nbsp
    <input type="checkbox" value="4" name="panel2[]">&nbspCourt Programs</input>
    </span>
    </br>
    <label class="uno">Group Panel:</label>
    <span class="spec2">
        <input type='text' list='listid2' id='gpanel2'>
        <datalist id='listid2' ></datalist>
    </span></br>
    <label class="uno">Panel Title :</label>
    <span class="spec3">
        <input type="text" name=""></br>
    </span>
    <label class="uno">Free Panel :</label>
    <span class="spec4">
      <input type="radio" name="free2" value="yes" checked>Yes
      <input type="radio" name="free2" value="no">No
    </span>
    </br>
    <div id="fees2">
        <label class="uno">Fees $ :</label>
        <span class="spec5">
        <input type="text" id="fees3" name="fees3" disabled="disabled" >
        </span>
    </div>
    </br></br></br>
    <div class="col-md-offset-3">
    <input type="submit" class="btn btn-primary" value="Update" ></input>&nbsp&nbsp
    <input type="reset" class="btn btn-danger" id="cancel2" value="Cancel" onclick="cancelFunction();">
    </div>
</form>
</div>
<div class="addMember" id="addMember" ng-show="panel.isSelected(2)">
</div>
</code>```

JS:

```<code> function editFunction(value)
  {
    $("#panelList").show();
    $("#addMember").hide();
    $.getJSON("active.json"),function(result)
    {
        //console.log("hi");
        var categoryArray = result;

        for (var i = 0; i < categoryArray.length; i++)
        {
            if (categoryArray[i].id == value)
            {
                return(categoryArray[i]);

            }
        }
    }
    return true;
}

$.getJSON("active.json", function(result)
{
    var panel_arr = ["", "Regular", "Reduced Fee", "Limited Assurance","Court Programs"];
    var ul_block = $("<ul/>");
    $.each(result, function(i, data)
    {
        var panels = data.panel.split(",");
        var uli_block = $("<ul/>");
            $.each(panels, function(j, jdata)
            {
                var ulii_block = $("<ul/>");
                $(ulii_block).append($("<li/>").html(data.ptitle+'&nbsp&nbsp<a href="#epanel" id='+data.id+' class="btn btn-default active" role="button" onclick="editFunction(id);">Edit</a>'+'&nbsp&nbsp<a href="#" class="btn btn-default active" role="button">Delete</a>'));

                $(uli_block).append($("<li/>").html('<span class="Collapsable">'+panel_arr[panels[j]]+'</span>')).append(ulii_block);
            });
        $(ul_block).append($("<li/>").html('<span class="Collapsable">'+data.gpanel+'</span>').append(uli_block));
    });
    $("#addMember").append(ul_block);
    $(".Collapsable").click(function () {
      $(this).parent().children().toggle();
      $(this).toggle();
    });
    $(".Collapsable").each(function(){
      $(this).parent().children().toggle();
      $(this).toggle();
    });

});
</code>```

JSON:

```<code>[
{
  "id":"1",
  "gpanel":"sfd",
  "ptitle":"sdffd",
  "panel":"1,4",
  "free":"yes",
  "fees":"0.00"
 },
 {
  "id":"2",
  "gpanel":"sdfd",
  "ptitle":"sdfds",
  "panel":"4",
  "free":"yes",
  "fees":"0.00"
 },
 {
  "id":"3",
  "gpanel":"sdf",
  "ptitle":"sdf",
  "panel":"4",
  "free":"yes",
  "fees":"0.00"
 },
 {
  "id":"4",
  "gpanel":"sfd",
  "ptitle":"fes",
  "panel":"1",
  "free":"yes",
  "fees":"0.00"
 },
 {
  "id":"5",
  "gpanel":"bbbfff",
  "ptitle":"hgffg",
  "panel":"1,2",
  "free":"yes",
  "fees":"0.00"
 }
 ]
</code>```

答:
To make this work, you should not pass id to editFunction, since that variable will be out of scope at the moment the button is clicked.

Also, it seems overkill to request the data from the server again when the user clicks the edit button. Instead you could pass the corresponding object to editFunction.

NB: If later you have functionality that mutates that object, you will maintain state, and when the user edits that data again, the previous changes will still be there.

In order to pass an object, it will be more practical to rewrite some of your code that generates the HTML content: instead of relying on the html method, use jQuery methods to create these elements. Then you can easily attach a click handler to the edit button that can access a data object.

Here is a snippet that shows the changes. Of course, I do not have your CSS, so this looks ugly, but it works:

function editFunction(data) { // Pass all related data as argument
    $("#panelList").show();
    $("#addMember").hide();
    // Set form elements
    $('.spec1 input').prop('checked', false);
    data.panel.split(",").forEach(function (jdata) {
        $('.spec1 input[value=' + jdata + ']').prop('checked', true);
    });
    $('.spec2 input').val(data.gpanel);
    $('.spec3 input').val(data.ptitle);
    $('.spec4 input[value=' + data.free + ']').prop('checked', true);
    $('.spec5 input').val(data.fees);
    return false;
}

function processResult (result) {
    var panel_arr = ["", "Regular", "Reduced Fee", "Limited Assurance",
                     "Court Programs"];
    var ul_block = $("
");
    $.each(result, function(i, data)
    {
        var panels = data.panel.split(",");
        var uli_block = $("
");
        $.each(panels, function(j, jdata)
        {
            var ulii_block = $("
");
            // Use jQuery methods for generating the content
            $edit = $('').attr('href', 'javascript:;')
                             .addClass('btn btn-default active')
                             .attr('role', 'button').text('Edit')
                             .css('margin-left', 5);
            $del = $('').addClass('btn btn-default active')
                             .attr('role', 'button').text('Delete')
                             .css('margin-left', 5);
            $(ulii_block).append(
                $("
").text(data.ptitle).append($edit, $del));
            $(uli_block).append($("
").append(
                    $('').addClass("Collapsable").text(panel_arr[panels[j]])
            )).append(ulii_block);
            // ...so you can attach a click handler that passes an object as argument
            $edit.click(editFunction.bind(null, data));
        });
        $(ul_block).append($("
").append(
             $('').addClass("Collapsable").text(data.gpanel)
        ).append(uli_block));
    });
    $("#addMember").append(ul_block);
    $(".Collapsable").click(function () {
      $(this).parent().children().toggle();
      $(this).toggle();
    });
    $(".Collapsable").each(function(){
      $(this).parent().children().toggle();
      $(this).toggle();
    });
}

// This snippet does not do a request, so uncomment this:
//$.getJSON("active.json", processResult);

// Dummy data (exclude this when doing the real request)
processResult([
{
  "id":"1",
  "gpanel":"sfd",
  "ptitle":"sdffd",
  "panel":"1,4",
  "free":"yes",
  "fees":"0.00"
 },
 {
  "id":"2",
  "gpanel":"sdfd",
  "ptitle":"sdfds",
  "panel":"4",
  "free":"yes",
  "fees":"0.00"
 },
 {
  "id":"3",
  "gpanel":"sdf",
  "ptitle":"sdf",
  "panel":"4",
  "free":"yes",
  "fees":"0.00"
 },
 {
  "id":"4",
  "gpanel":"sfd",
  "ptitle":"fes",
  "panel":"1",
  "free":"yes",
  "fees":"0.00"
 },
 {
  "id":"5",
  "gpanel":"bbbfff",
  "ptitle":"hgffg",
  "panel":"1,2",
  "free":"no",
  "fees":"1.00"
 }
 ]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panelList" id="panelList" hidden>
<form action="#" name="">
    <label class="uno">Panel Category:</label>
    <span class="spec1">
    <input type="checkbox" value="1" name="panel2[]">&nbspRegular&nbsp&nbsp
    <input type="checkbox" value="2" name="panel2[]">&nbspReduced fee</input>&nbsp&nbsp
    <input type="checkbox" value="3" name="panel2[]">&nbspLimited Assistance Referral</input>&nbsp&nbsp
    <input type="checkbox" value="4" name="panel2[]">&nbspCourt Programs</input>
    </span>
    </br>
    <label class="uno">Group Panel:</label>
    <span class="spec2">
        <input type='text' list='listid2' id='gpanel2'>
        <datalist id='listid2' ></datalist>
    </span></br>
    <label class="uno">Panel Title :</label>
    <span class="spec3">
        <input type="text" name=""></br>
    </span>
    <label class="uno">Free Panel :</label>
    <span class="spec4">
      <input type="radio" name="free2" value="yes" checked>Yes
      <input type="radio" name="free2" value="no">No
    </span>
    </br>
    <div id="fees2">
        <label class="uno">Fees $ :</label>
        <span class="spec5">
        <input type="text" id="fees3" name="fees3" disabled="disabled" >
        </span>
    </div>
    </br></br></br>
    <div class="col-md-offset-3">
    <input type="submit" class="btn btn-primary" value="Update" ></input>&nbsp&nbsp
    <input type="reset" class="btn btn-danger" id="cancel2" value="Cancel" onclick="cancelFunction();">
    </div>
</form>
</div>
<div class="addMember" id="addMember" ng-show="panel.isSelected(2)">
</div></code>```

It is now up to you to write the code for updating the information back into the object when the user clicks the Update button.

Body:
I'm trying to view and edit data on two separate DIV tags.
I have implemented the click even to show the edit form on click event of the edit button in the view page.
Now what i want is, if i click the edit button, i want to fetch the particular items Values and populate it in a form.
i.e, checkbox values should be checked, input fields filled and radiobutton selected.
Here is how i got so far,

HTML:

<form action="#" name="">
    Panel Category:

    <input type="checkbox" value="1" name="panel2[]">&nbspRegular&nbsp&nbsp
    <input type="checkbox" value="2" name="panel2[]">&nbspReduced fee</input>&nbsp&nbsp
    <input type="checkbox" value="3" name="panel2[]">&nbspLimited Assistance Referral</input>&nbsp&nbsp
    <input type="checkbox" value="4" name="panel2[]">&nbspCourt Programs</input>

    Group Panel:

        <input type='text' list='listid2' id='gpanel2'>
        <datalist id='listid2' ></datalist>

    Panel Title :

        <input type="text" name="">

    Free Panel :

      <input type="radio" name="free2" value="yes" checked>Yes
      <input type="radio" name="free2" value="no">No

        Fees $ :

        <input type="text" id="fees3" name="fees3" disabled="disabled" >

    <input type="submit" class="btn btn-primary" value="Update" ></input>&nbsp&nbsp
    <input type="reset" class="btn btn-danger" id="cancel2" value="Cancel" onclick="cancelFunction();">

</form>

JS:

 function editFunction(value)
  {
    $("#panelList").show();
    $("#addMember").hide();
    $.getJSON("active.json"),function(result)
    {
        //console.log("hi");
        var categoryArray = result;

        for (var i = 0; i < categoryArray.length; i++)
        {
            if (categoryArray[i].id == value)
            {
                return(categoryArray[i]);

            }
        }
    }
    return true;
}

$.getJSON("active.json", function(result)
{
    var panel_arr = ["", "Regular", "Reduced Fee", "Limited Assurance","Court Programs"];
    var ul_block = $("
");
    $.each(result, function(i, data)
    {
        var panels = data.panel.split(",");
        var uli_block = $("
");
            $.each(panels, function(j, jdata)
            {
                var ulii_block = $("
");
                $(ulii_block).append($("
").html(data.ptitle+'&nbsp&nbspEdit'+'&nbsp&nbspDelete'));

                $(uli_block).append($("
").html(''+panel_arr[panels[j]]+'')).append(ulii_block);
            });
        $(ul_block).append($("
").html(''+data.gpanel+'').append(uli_block));
    });
    $("#addMember").append(ul_block);
    $(".Collapsable").click(function () {
      $(this).parent().children().toggle();
      $(this).toggle();
    });
    $(".Collapsable").each(function(){
      $(this).parent().children().toggle();
      $(this).toggle();
    });

});

JSON:

[
{
  "id":"1",
  "gpanel":"sfd",
  "ptitle":"sdffd",
  "panel":"1,4",
  "free":"yes",
  "fees":"0.00"
 },
 {
  "id":"2",
  "gpanel":"sdfd",
  "ptitle":"sdfds",
  "panel":"4",
  "free":"yes",
  "fees":"0.00"
 },
 {
  "id":"3",
  "gpanel":"sdf",
  "ptitle":"sdf",
  "panel":"4",
  "free":"yes",
  "fees":"0.00"
 },
 {
  "id":"4",
  "gpanel":"sfd",
  "ptitle":"fes",
  "panel":"1",
  "free":"yes",
  "fees":"0.00"
 },
 {
  "id":"5",
  "gpanel":"bbbfff",
  "ptitle":"hgffg",
  "panel":"1,2",
  "free":"yes",
  "fees":"0.00"
 }
 ]

Body:
To make this work, you should not pass id to editFunction, since that variable will be out of scope at the moment the button is clicked.

Also, it seems overkill to request the data from the server again when the user clicks the edit button. Instead you could pass the corresponding object to editFunction.

NB: If later you have functionality that mutates that object, you will maintain state, and when the user edits that data again, the previous changes will still be there.

In order to pass an object, it will be more practical to rewrite some of your code that generates the HTML content: instead of relying on the html method, use jQuery methods to create these elements. Then you can easily attach a click handler to the edit button that can access a data object.

Here is a snippet that shows the changes. Of course, I do not have your CSS, so this looks ugly, but it works:

function editFunction(data) { // Pass all related data as argument
    $("#panelList").show();
    $("#addMember").hide();
    // Set form elements
    $('.spec1 input').prop('checked', false);
    data.panel.split(",").forEach(function (jdata) {
        $('.spec1 input[value=' + jdata + ']').prop('checked', true);
    });
    $('.spec2 input').val(data.gpanel);
    $('.spec3 input').val(data.ptitle);
    $('.spec4 input[value=' + data.free + ']').prop('checked', true);
    $('.spec5 input').val(data.fees);
    return false;
}

function processResult (result) {
    var panel_arr = ["", "Regular", "Reduced Fee", "Limited Assurance",
                     "Court Programs"];
    var ul_block = $("<ul/>");
    $.each(result, function(i, data)
    {
        var panels = data.panel.split(",");
        var uli_block = $("<ul/>");
        $.each(panels, function(j, jdata)
        {
            var ulii_block = $("<ul/>");
            // Use jQuery methods for generating the content
            $edit = $('<a/>').attr('href', 'javascript:;')
                             .addClass('btn btn-default active')
                             .attr('role', 'button').text('Edit')
                             .css('margin-left', 5);
            $del = $('<a/>').addClass('btn btn-default active')
                             .attr('role', 'button').text('Delete')
                             .css('margin-left', 5);
            $(ulii_block).append(
                $("<li/>").text(data.ptitle).append($edit, $del));
            $(uli_block).append($("<li/>").append(
                    $('<span>').addClass("Collapsable").text(panel_arr[panels[j]])
            )).append(ulii_block);
            // ...so you can attach a click handler that passes an object as argument
            $edit.click(editFunction.bind(null, data));
        });
        $(ul_block).append($("<li/>").append(
             $('<span>').addClass("Collapsable").text(data.gpanel)
        ).append(uli_block));
    });
    $("#addMember").append(ul_block);
    $(".Collapsable").click(function () {
      $(this).parent().children().toggle();
      $(this).toggle();
    });
    $(".Collapsable").each(function(){
      $(this).parent().children().toggle();
      $(this).toggle();
    });
}

// This snippet does not do a request, so uncomment this:
//$.getJSON("active.json", processResult);

// Dummy data (exclude this when doing the real request)
processResult([
{
  "id":"1",
  "gpanel":"sfd",
  "ptitle":"sdffd",
  "panel":"1,4",
  "free":"yes",
  "fees":"0.00"
 },
 {
  "id":"2",
  "gpanel":"sdfd",
  "ptitle":"sdfds",
  "panel":"4",
  "free":"yes",
  "fees":"0.00"
 },
 {
  "id":"3",
  "gpanel":"sdf",
  "ptitle":"sdf",
  "panel":"4",
  "free":"yes",
  "fees":"0.00"
 },
 {
  "id":"4",
  "gpanel":"sfd",
  "ptitle":"fes",
  "panel":"1",
  "free":"yes",
  "fees":"0.00"
 },
 {
  "id":"5",
  "gpanel":"bbbfff",
  "ptitle":"hgffg",
  "panel":"1,2",
  "free":"no",
  "fees":"1.00"
 }
 ]);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panelList" id="panelList" hidden>
<form action="#" name="">
    <label class="uno">Panel Category:</label>
    <span class="spec1">
    <input type="checkbox" value="1" name="panel2[]">&nbspRegular&nbsp&nbsp
    <input type="checkbox" value="2" name="panel2[]">&nbspReduced fee</input>&nbsp&nbsp
    <input type="checkbox" value="3" name="panel2[]">&nbspLimited Assistance Referral</input>&nbsp&nbsp
    <input type="checkbox" value="4" name="panel2[]">&nbspCourt Programs</input>
    </span>
    </br>
    <label class="uno">Group Panel:</label>
    <span class="spec2">
        <input type='text' list='listid2' id='gpanel2'>
        <datalist id='listid2' ></datalist>
    </span></br>
    <label class="uno">Panel Title :</label>
    <span class="spec3">
        <input type="text" name=""></br>
    </span>
    <label class="uno">Free Panel :</label>
    <span class="spec4">
      <input type="radio" name="free2" value="yes" checked>Yes
      <input type="radio" name="free2" value="no">No
    </span>
    </br>
    <div id="fees2">
        <label class="uno">Fees $ :</label>
        <span class="spec5">
        <input type="text" id="fees3" name="fees3" disabled="disabled" >
        </span>
    </div>
    </br></br></br>
    <div class="col-md-offset-3">
    <input type="submit" class="btn btn-primary" value="Update" ></input>&nbsp&nbsp
    <input type="reset" class="btn btn-danger" id="cancel2" value="Cancel" onclick="cancelFunction();">
    </div>
</form>
</div>
<div class="addMember" id="addMember" ng-show="panel.isSelected(2)">
</div>

It is now up to you to write the code for updating the information back into the object when the user clicks the Update button.


问:
How to fetch the element inside tinymce using jquery?
How to fetch an element from getContent in tinymce using jquery</p>

答:
You cannot fetch an element from ed.getContent() that easily. You would have to parse the javascript string in order to do so.

I assume you want to access the image tag you were reffering to in your other question.
This can be easily done onClick:

```<code>ed.onClick.add(function(ed, evt){

    // Firefox
    if (evt.explicitOriginalTarget){
      if (evt.explicitOriginalTarget.nodeName.toLowerCase() == 'img'){
        console.log(evt.explicitOriginalTarget); // this is the img-element
      }
    }
    // IE
    else if (evt.target) {
      if (evt.target.nodeName.toLowerCase() == 'img'){
        console.log(evt.target); // this is the img-element
      }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You cannot fetch an element from ed.getContent() that easily. You would have to parse the javascript string in order to do so.

I assume you want to access the image tag you were reffering to in your other question.
This can be easily done onClick:

ed.onClick.add(function(ed, evt){

    // Firefox
    if (evt.explicitOriginalTarget){
      if (evt.explicitOriginalTarget.nodeName.toLowerCase() == 'img'){
        console.log(evt.explicitOriginalTarget); // this is the img-element
      }
    }
    // IE
    else if (evt.target) {
      if (evt.target.nodeName.toLowerCase() == 'img'){
        console.log(evt.target); // this is the img-element
      }
    }
}


问:
Is it possible to change the text of selected item in a drop down?
I have a dropdown in which I am displaying items as below:

1             Apple

2              Banana

3              Mango

4              Orange

Now when I select any option, I just want the Number to be displayed not the entire item text. i.e when I select "1    Apple", I just want "1" to be displayed. How do I achieve this?

I've tried changing the text using

```<code> $("#ddlFruits option:selected").text($("#ddlFruits option:selected").text().split(' ')[0])
</code>```

but this also changes the item in dropdown.

答:
If you want to only display the number when an option is selected, but keep the number and text when making a change, use a change and mousedown combination of events

$('select').change(function() {
  option = $(this).val().split(' ')
  $('option:selected', this).data('orig', $(this).val()).html(option[0])
}).mousedown(function() {
  $('select option').each(function() {
   $(this).html($(this).data('orig'))
  })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option>1 Apple </option>
  <option>2 Banana</option>
  <option>3 Mango</option>
  <option>4 Orange</option>
</select></code>```

Body:
I have a dropdown in which I am displaying items as below:

1             Apple

2              Banana

3              Mango

4              Orange

Now when I select any option, I just want the Number to be displayed not the entire item text. i.e when I select "1    Apple", I just want "1" to be displayed. How do I achieve this?

I've tried changing the text using

 $("#ddlFruits option:selected").text($("#ddlFruits option:selected").text().split(' ')[0])

but this also changes the item in dropdown.

Body:
If you want to only display the number when an option is selected, but keep the number and text when making a change, use a change and mousedown combination of events

$('select').change(function() {
  option = $(this).val().split(' ')
  $('option:selected', this).data('orig', $(this).val()).html(option[0])
}).mousedown(function() {
  $('select option').each(function() {
   $(this).html($(this).data('orig'))
  })
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option>1 Apple </option>
  <option>2 Banana</option>
  <option>3 Mango</option>
  <option>4 Orange</option>
</select>


问:
Display tree structure in Ruby on rails
I anyone help me out to display the tree structure in view. I have successfully created the parent child associations between single table called "Element". Also the entries are saving in proper manner.

I have build the code for that but it works at a level, because I have used the loop I want to optimize that, I hope seeing the code you could have the quick solutions.

```<code>class Element
  include Mongoid::Document
  validates :name, presence: true

  field :name, type: String
  field :description, type: String
  field :top, type: String

  has_many :media_files

  has_and_belongs_to_many :parents, :class_name => 'Element'
  has_and_belongs_to_many :childrens, :class_name => 'Element'

  def self.js_tree
    json_data = Array.new
    elements = Element.where(top: "true")
    get_inner_elements elements, json_data
   return json_data.uniq {|e| e[:id] }.to_json
  end

  def self.get_inner_elements elements, json_data
    elements.each do |element|
      single_element element, json_data
      element.childrens.each do |inner_element_one|
        single_element inner_element_one, json_data, element.id
        inner_element_one.childrens.each do |inner_element_two|
          single_element inner_element_two, json_data, inner_element_one.id
          inner_element_two.childrens.each do |inner_element_three|
            single_element inner_element_three, json_data, inner_element_two.id
            inner_element_three.childrens.each do |inner_element_four|
              single_element inner_element_four, json_data, inner_element_three.id
            end
          end
        end
      end
    end
    return json_data
  end

  def self.single_element element, json_data, parent=nil
    json_data << {
        :id     => "#{element.id}",
        :parent => "#{parent.nil? ? '#' : parent}",
        :a_attr=> { class: "foldor-icon" },
        :text   => "#{element.name}"
      }
      element.media_files.each do |mf|
        json_data << {
          :id     => "file_#{element.id}_#{mf.id}",
          :parent => "#{element.id}",
          :text   => mf.file_filename,
          :icon     => mf.icon,
        }
      end
    return json_data
  end

end
</code>```

Front End :

```<code><script type="text/javascript">
  data = $.parseJSON('<%= raw Element.js_tree %>')
  $('#container').jstree({
   'core' : {
      'data' : data
    }
  });
</script>
</code>```

The get_inner_elements need to be optimized Please anyone suggest how to do that there is something recursion need to be used I am unable to apply that.

Thannks

答:
I think you should try using a recursive algorithm.

```<code>def self.get_inner_elements(elements, json_data)
    elements.each do |element|
        if elements.children.count > 0
            single_element(element, json_data, element.parent?)
            get_inner_elements(element.children, json_data)
        else
            single_element(element, json_data, element.parent?)
        end
    end
    json_data
end
</code>```

It may be not perfectly optimized, but it is a bit more readable than that big tree you have.

One caveat here is that not the same order of elements will be preserved, if this is not one of the requirements, you can use it easily, if not, you will have to re-order the json_data you have on the output

Title: Display tree structure in Ruby on rails

Body:
I anyone help me out to display the tree structure in view. I have successfully created the parent child associations between single table called "Element". Also the entries are saving in proper manner.

I have build the code for that but it works at a level, because I have used the loop I want to optimize that, I hope seeing the code you could have the quick solutions.

class Element
  include Mongoid::Document
  validates :name, presence: true

  field :name, type: String
  field :description, type: String
  field :top, type: String

  has_many :media_files

  has_and_belongs_to_many :parents, :class_name => 'Element'
  has_and_belongs_to_many :childrens, :class_name => 'Element'

  def self.js_tree
    json_data = Array.new
    elements = Element.where(top: "true")
    get_inner_elements elements, json_data
   return json_data.uniq {|e| e[:id] }.to_json
  end

  def self.get_inner_elements elements, json_data
    elements.each do |element|
      single_element element, json_data
      element.childrens.each do |inner_element_one|
        single_element inner_element_one, json_data, element.id
        inner_element_one.childrens.each do |inner_element_two|
          single_element inner_element_two, json_data, inner_element_one.id
          inner_element_two.childrens.each do |inner_element_three|
            single_element inner_element_three, json_data, inner_element_two.id
            inner_element_three.childrens.each do |inner_element_four|
              single_element inner_element_four, json_data, inner_element_three.id
            end
          end
        end
      end
    end
    return json_data
  end

  def self.single_element element, json_data, parent=nil
    json_data << {
        :id     => "#{element.id}",
        :parent => "#{parent.nil? ? '#' : parent}",
        :a_attr=> { class: "foldor-icon" },
        :text   => "#{element.name}"
      }
      element.media_files.each do |mf|
        json_data << {
          :id     => "file_#{element.id}_#{mf.id}",
          :parent => "#{element.id}",
          :text   => mf.file_filename,
          :icon     => mf.icon,
        }
      end
    return json_data
  end

end

Front End :

The get_inner_elements need to be optimized Please anyone suggest how to do that there is something recursion need to be used I am unable to apply that.

Thannks

Body:
I think you should try using a recursive algorithm.

def self.get_inner_elements(elements, json_data)
    elements.each do |element|
        if elements.children.count > 0
            single_element(element, json_data, element.parent?)
            get_inner_elements(element.children, json_data)
        else
            single_element(element, json_data, element.parent?)
        end
    end
    json_data
end

It may be not perfectly optimized, but it is a bit more readable than that big tree you have.

One caveat here is that not the same order of elements will be preserved, if this is not one of the requirements, you can use it easily, if not, you will have to re-order the json_data you have on the output


问:
Can I access a class without an __init__? - Python
I want to be able to print "hello harry" from a module. This is my module (called test23):

```<code>class tool:

    def handle(self,name):
        self.name = "hello " + name
</code>```

This is my script:

```<code>import test23

harry= test23.tool().handle(" harry")
print harry.name
</code>```

I can't seem to print "hello harry" inside my script idle. How would I go about doing this?

答:
tool.handle() doesn't return an object, so you need to store the object before you call the method:

```<code>import test23

harry = test23.tool()
harry.handle("harry")
print harry.name
</code>```

Body:
I want to be able to print "hello harry" from a module. This is my module (called test23):

class tool:

    def handle(self,name):
        self.name = "hello " + name

This is my script:

import test23

harry= test23.tool().handle(" harry")
print harry.name

I can't seem to print "hello harry" inside my script idle. How would I go about doing this?

Body:
tool.handle() doesn't return an object, so you need to store the object before you call the method:

import test23

harry = test23.tool()
harry.handle("harry")
print harry.name


问:
JMeter : How to record HTTPS traffic?
I'm using Apache JMeter 2.3, which now supports "attempt HTTPS spoofing" under the Proxy Server element.

I've tried this on several different servers, and have had no success.
Has anyone been able to successfully record from an HTTPS source with this setting?

Or barring successfully recording, can anyone share a work-around? When available, I simply have HTTPS turned off at the server level, but this is not always feasible. Thoughts?

答:
Yes, I have used it with "attempt HTTPS spoofing" on. Things are simple enough:

Turn HTTPS Spoofing on (of course).

Make sure that the browser sends Http request to Jmeter, so that Jmeter can record it and then send the encrypted request back to the server. So, the URL in the browser should start with http:// (and not with https://). The details could be found in my blog.

Please let me know if it works for you.

LastEditorDisplayName: lc

Title: JMeter : How to record HTTPS traffic?


问:
Python wireless transfers with SonyQX1
I'm currently using the sony QX1 for wireless transfers for large images. The camera is being triggered over the USB port. Pictures from the camera are being transferred with URLLib to a raspberry pi. (I can't use the api to trigger the camera. It has to be from this external source.)

The camera is triggered around every 2.5 seconds. Through timing testing it seems like I'm able to get the larger picture back to the pi at ~ 3.2 seconds per image.

I've noticed that when the camera is triggered my transfer is terminated. I'm assuming this has to do with the embedded design of the camera itself and there isn't a way to get around this but please correct me if I'm wrong!

Does the camera support the range header? Basically I grab the image size from the header. I'm trying to grab the beginning X bytes until the camera triggers again then grab the next X bytes until I get the entire image.

Thanks for the help and let me know if I need to give a deeper explanation of what is going on here.

答:
I don't know about the range header, but it will still not allow you to take more pictures than your downloadspeed allows (unless you have some larger than 2.5 seconds intervals now and then).
Maybe you can reduce the image resolution to a size that fits into the 2.5 sec interval? Or (just some thinking outside of the box:-) use 2 QX1's switching, so you get a 5 second interval for each...</p>

Title: Python wireless transfers with SonyQX1


问:
Python calculator - input validation
Hi all a Python newbie here, I just created the following simple program that asks for three inputs, checks if/waits until those inputs are numbers, and then prints out their sum.

My question is: How can I make my code more compact? E.g can I use only one block of code instead of three? Can I make the input-checking smarter?

Any suggestions are welcome. Thanks.

```<code>print ("-ADD THREE NUMBERS-")

while True:
    a = input("Please enter a:")
    try:
        a = float(a)
        break
    except ValueError:
        print ("'a' must be a number.")

while True:
    b = input("Please enter b:")
    try:
        b = float(b)
        break
    except ValueError:
        print ("'b' must be a number.")

while True:
    c = input("Please enter c:")
    try:
        c = float(c)
        break
    except ValueError:
        print ("'c' must be a number.")

print(a+b+c)
</code>```

答:
I suggest you to use a list to save all "variables" ('a','b','c') that you want show to the user.

So the code became compacter:

```<code>input_requested = ['a', 'b', 'c']
results = []

print ("-ADD THREE NUMBERS-")
for input in input_requested:
    while True:
        user_input = input("Please enter '{}':".format(input))
        try:
            results.append(float(user_input))
            break
        except ValueError:
            print ("'{}' must be a number.".format(input))

print(sum(i for i in results))
</code>```

When the input is correct save it in a list, otherwise catch the exception like your code.

Ate the end, in order to print the sum of all inputs, you can use

```<code>sum(i for i in results)
</code>```

which loop on the list of inputs and sum directly the elements.

Title: Python calculator - input validation

Body:
Hi all a Python newbie here, I just created the following simple program that asks for three inputs, checks if/waits until those inputs are numbers, and then prints out their sum.

My question is: How can I make my code more compact? E.g can I use only one block of code instead of three? Can I make the input-checking smarter?

Any suggestions are welcome. Thanks.

print ("-ADD THREE NUMBERS-")

while True:
    a = input("Please enter a:")
    try:
        a = float(a)
        break
    except ValueError:
        print ("'a' must be a number.")

while True:
    b = input("Please enter b:")
    try:
        b = float(b)
        break
    except ValueError:
        print ("'b' must be a number.")

while True:
    c = input("Please enter c:")
    try:
        c = float(c)
        break
    except ValueError:
        print ("'c' must be a number.")

print(a+b+c)

Body:
I suggest you to use a list to save all "variables" ('a','b','c') that you want show to the user.

So the code became compacter:

input_requested = ['a', 'b', 'c']
results = []

print ("-ADD THREE NUMBERS-")
for input in input_requested:
    while True:
        user_input = input("Please enter '{}':".format(input))
        try:
            results.append(float(user_input))
            break
        except ValueError:
            print ("'{}' must be a number.".format(input))

print(sum(i for i in results))

When the input is correct save it in a list, otherwise catch the exception like your code.

Ate the end, in order to print the sum of all inputs, you can use

sum(i for i in results)

which loop on the list of inputs and sum directly the elements.


问:
Nodejs api call from angular2 service
I have node api that returns data to browser using this api :

```<code>app.get('/api/patients',function(req,res){
    Patient.getPatients(function(err,patients){
        if(err){
            throw err;
        }
        console.log(patients.length);
        res.json(patients);

    });
});
</code>```

I am trying to call this api from the service class.

```<code>import { Injectable } from '@angular/core';
import { Patient } from '../patient.interface';

@Injectable()
export class PatientDataService {

    patients : Patient[] =[];

    constructor() { }

    getAllPatients(): Patient[]
    {
          // What to do here ??
    }

}
</code>```

How do i return data from node api to service ?

答:
Use this

```<code>@Injectable()
export class PatientDataService {

    patients : Patient[] =[];

    constructor(private http:Http) { }

        getAllPatients()
         {
          return this.http.get('base_url/api/people').map((res)=>res.json());

        }

}
</code>```

and in your component inject this service and call

```<code>this.patientService.getAllPatients().subscribe((data)=>{
   //data is your patient list
})
</code>```

Title: Nodejs api call from angular2 service

Body:
I have node api that returns data to browser using this api :

app.get('/api/patients',function(req,res){
    Patient.getPatients(function(err,patients){
        if(err){
            throw err;
        }
        console.log(patients.length);
        res.json(patients);

    });
});

I am trying to call this api from the service class.

import { Injectable } from '@angular/core';
import { Patient } from '../patient.interface';

@Injectable()
export class PatientDataService {

    patients : Patient[] =[];

    constructor() { }

    getAllPatients(): Patient[]
    {
          // What to do here ??
    }

}

How do i return data from node api to service ?

Body:
Use this

@Injectable()
export class PatientDataService {

    patients : Patient[] =[];

    constructor(private http:Http) { }

        getAllPatients()
         {
          return this.http.get('base_url/api/people').map((res)=>res.json());

        }

}

and in your component inject this service and call

this.patientService.getAllPatients().subscribe((data)=>{
   //data is your patient list
})


问:
Social Media Buttons Not Center in

I try to center the social media buttons in a
, but it keeps on aligning left.

```<code>echo '<div class="socialWrapper">';
echo '<div class="fb-like" data-href=" '  . $_SERVER['REQUEST_URI'] . '" data-layout="button_count" data-action="like" data-size="small" data-show-faces="true" data-share="true" style="vertical-align:top;zoom:1;*display:inline;"></div> ';
echo '<a href="https://twitter.com/share" class="twitter-share-button" data-show-count="false"></a><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script> ';
echo '<div class="g-plusone" data-size="medium"></div>';
echo '</div>';
</code>```

CSS file

```<code>div.socialWrapper{
    margin:auto;
    width:100%;
    text-align:center;
}
</code>```

答: try div.socialWrapper{display: flex; justify-content: center; flex-direction: row;}

Title: Social Media Buttons Not Center in <div>

Body:
I try to center the social media buttons in a
, but it keeps on aligning left.

echo '
';
echo '

 ';
echo ' ';
echo '

';
echo '
';

CSS file

div.socialWrapper{
    margin:auto;
    width:100%;
    text-align:center;
}


问:
matching occurrence of opposite number in a list python
I have a list such has

```<code>results = [100, 100, -100, 100, -100, -100]
</code>```

I would like to figure out the first occurrence of the opposite number. so first 100 would be match with the first -100, the second 100 would be match with the second -100.

I would like to have position as output such has:

```<code>[0, 2], [1, 4], [3, 5]
</code>```

i.e : [0,2] represent the results[0] and  results[2]  where first occurrence of 100 is match with the first occurrence of -100

edit : you can assume there will always be the same amount of positive / negative and that the list will only contain 1 number

any help would be appricated

答:
IMO, the fastest approach (for large inputs) should be the following one (though, my solution doesn't assume that the input list contains just one value and its opposite, so it can be made even faster if that assumption is added):

```<code>x = [100, 300, -300, 100, -100, -100]

from collections import defaultdict, deque

unmatched_positives = defaultdict(deque)

solution=[]
for i, val  in enumerate(x):
    if val > 0:
        unmatched_positives[val].append(i)
    else:
        solution.append( (unmatched_positives[-val].popleft(), i) )

print('Unsorted solution:', solution)
# If you need the result to be sorted
print('Sorted solution:', sorted(solution))
</code>```

Output:

```<code>Unsorted solution: [(1, 2), (0, 4), (3, 5)]
Sorted solution: [(0, 4), (1, 2), (3, 5)]
</code>```

Body:
I have a list such has

results = [100, 100, -100, 100, -100, -100]

I would like to figure out the first occurrence of the opposite number. so first 100 would be match with the first -100, the second 100 would be match with the second -100.

I would like to have position as output such has:

[0, 2], [1, 4], [3, 5]

i.e : [0,2] represent the results[0] and  results[2]  where first occurrence of 100 is match with the first occurrence of -100

edit : you can assume there will always be the same amount of positive / negative and that the list will only contain 1 number

any help would be appricated

Body:
IMO, the fastest approach (for large inputs) should be the following one (though, my solution doesn't assume that the input list contains just one value and its opposite, so it can be made even faster if that assumption is added):

x = [100, 300, -300, 100, -100, -100]

from collections import defaultdict, deque

unmatched_positives = defaultdict(deque)

solution=[]
for i, val  in enumerate(x):
    if val > 0:
        unmatched_positives[val].append(i)
    else:
        solution.append( (unmatched_positives[-val].popleft(), i) )

print('Unsorted solution:', solution)
# If you need the result to be sorted
print('Sorted solution:', sorted(solution))

Output:

Unsorted solution: [(1, 2), (0, 4), (3, 5)]
Sorted solution: [(0, 4), (1, 2), (3, 5)]


问:
Sort List Of Objects By Properties C# (Custom Sort Order)
I currently have a list of objects that I am trying sort for a custom made grid view. I am hoping that I can achieve it without creating several customized algorithms. Currently I have a method called on page load that sorts the list by customer name, then status. I have a customized status order (new, in progress, has issues, completed, archived) and no matter which sort is used (customer, dates, so on) it should sort the status in the correct order. For example:

I have two customers with two orders each, the first customer is Betty White, the second is Mickey Mouse. Currently, Betty has a new order, and a completed order and Mickey has an order in progress and another on that has issues. So the display order should be:

Betty, New :: Betty, Completed

Mickey, In Progress :: Mickey, Has Issues

I am currently using Packages.OrderBy(o => o.Customer).ThenBy(o => o.Status). This works effectively to get the customers sorted, however this doesn't eliminate the custom sorting of the status property.

What would be the most efficient and standards acceptable method to achieve this result?

```<code>case PackageSortType.Customer:
     Packages = Packages.OrderBy(o => o.Customer).ThenBy(o=>o.Status).ToList<Package>();
break;
</code>```

I previously created a method that sorted by status only, however it is my belief that throwing the OrderBy into that algorithm would just jumble the status back up in the end.

```<code>private void SortByStatus() {
    // Default sort order is: New, In Progress, Has Issues, Completed, Archived
    List<Package> tempPackages = new List<Package>();
    string[] statusNames = new string[5] { "new", "inProgress", "hasIssue", "completed", "archived" };
    string currentStatus = string.Empty;

    for (int x = 0; x < 5; x++) {
        currentStatus = statusNames[x];

        for (int y = 0; y < Packages.Count; y++) {
            if (tempPackages.Contains(Packages[y])) continue;
            else {
                if (Packages[y].Status == currentStatus)
                    tempPackages.Add(Packages[y]);
            }
        }
    }
    Packages.Clear();
    Packages = tempPackages;
}
</code>```

Also, I'm not sure if it is relevant or not; however, the Packages list is stored in Session.

EDIT

Thanks to Alex Paven I have resolved the issue of custom sorting my status. I ended up creating a new class for the status and making it derive from IComparable, then created a CompareTo method that forced the proper sorting of the status.

For those who are curious about the solution I came up with (it still needs to be cleaned up), it's located below:

```<code>public class PackageStatus : IComparable<PackageStatus> {
public string Value { get; set; }
int id = 0;
static string[] statusNames = new string[5] { "new", "inProgress", "hasIssue", "completed", "archived" };

public int CompareTo(PackageStatus b) {
    if (b != null) {
        if (this == b) {
            return 0;
        }

        for (int i = 0; i < 5; i++) {
            if (this.Value == statusNames[i]) { id = i; }
            if (b.Value == statusNames[i]) { b.id = i; }
        }
    }

    return Comparer<int>.Default.Compare(id, b.id);
}
}
</code>```

Use:

```<code>Packages.OrderBy(o => o.Customer).ThenBy(o => o.Status).ToList<Package>();
</code>```

答: I'm not sure what exactly you're asking; why can't you use the Linq expressions in your first code sample? There's OrderByDescending in addition to OrderBy, so you can mix and match the sort order as you desire.</p>

Body:
I currently have a list of objects that I am trying sort for a custom made grid view. I am hoping that I can achieve it without creating several customized algorithms. Currently I have a method called on page load that sorts the list by customer name, then status. I have a customized status order (new, in progress, has issues, completed, archived) and no matter which sort is used (customer, dates, so on) it should sort the status in the correct order. For example:

I have two customers with two orders each, the first customer is Betty White, the second is Mickey Mouse. Currently, Betty has a new order, and a completed order and Mickey has an order in progress and another on that has issues. So the display order should be:

Betty, New :: Betty, Completed

Mickey, In Progress :: Mickey, Has Issues

I am currently using Packages.OrderBy(o => o.Customer).ThenBy(o => o.Status). This works effectively to get the customers sorted, however this doesn't eliminate the custom sorting of the status property.

What would be the most efficient and standards acceptable method to achieve this result?

case PackageSortType.Customer:
     Packages = Packages.OrderBy(o => o.Customer).ThenBy(o=>o.Status).ToList<Package>();
break;

I previously created a method that sorted by status only, however it is my belief that throwing the OrderBy into that algorithm would just jumble the status back up in the end.

private void SortByStatus() {
    // Default sort order is: New, In Progress, Has Issues, Completed, Archived
    List<Package> tempPackages = new List<Package>();
    string[] statusNames = new string[5] { "new", "inProgress", "hasIssue", "completed", "archived" };
    string currentStatus = string.Empty;

    for (int x = 0; x < 5; x++) {
        currentStatus = statusNames[x];

        for (int y = 0; y < Packages.Count; y++) {
            if (tempPackages.Contains(Packages[y])) continue;
            else {
                if (Packages[y].Status == currentStatus)
                    tempPackages.Add(Packages[y]);
            }
        }
    }
    Packages.Clear();
    Packages = tempPackages;
}

Also, I'm not sure if it is relevant or not; however, the Packages list is stored in Session.

EDIT

Thanks to Alex Paven I have resolved the issue of custom sorting my status. I ended up creating a new class for the status and making it derive from IComparable, then created a CompareTo method that forced the proper sorting of the status.

For those who are curious about the solution I came up with (it still needs to be cleaned up), it's located below:

public class PackageStatus : IComparable<PackageStatus> {
public string Value { get; set; }
int id = 0;
static string[] statusNames = new string[5] { "new", "inProgress", "hasIssue", "completed", "archived" };

public int CompareTo(PackageStatus b) {
    if (b != null) {
        if (this == b) {
            return 0;
        }

        for (int i = 0; i < 5; i++) {
            if (this.Value == statusNames[i]) { id = i; }
            if (b.Value == statusNames[i]) { b.id = i; }
        }
    }

    return Comparer<int>.Default.Compare(id, b.id);
}
}

Use:

Packages.OrderBy(o => o.Customer).ThenBy(o => o.Status).ToList<Package>();


问:
Can anyone send me a link for best boilerplate in react redux?
I want the perfect boilerplate for react redux. Can any one send me a github link?</p>

答:
I have created react redux apollo graphql boilerplate. However recently I wanted to user react redux only so I created separate branch without apollo.

It is probably not the best thing out there but I used webpack2, react, redux and hot reloading. Also you can import almost anything in modules. I hope it will help you.

https://github.com/developer239/ReactReduxApolloGraphQLHotBoilerplate/tree/no-apollo

This question will probably be deleted.  You should NOT ask for complete solutions. Stackoverflow should help you get your own code working. I feel your pain though. Starting with react is really confusing.


问:
How to inject config properties in Spring Boot to Spring Retry annotation?
In spring boot application, I define some config properties in yaml file as below.

```<code>my.app.maxAttempts = 10
my.app.backOffDelay = 500L
</code>```

And an example bean

```<code>@ConfigurationProperties(prefix = "my.app")
public class ConfigProperties {
  private int maxAttempts;
  private long backOffDelay;

  public int getMaxAttempts() {
    return maxAttempts;
  }

  public void setMaxAttempts(int maxAttempts) {
    this.maxAttempts = maxAttempts;
  }

  public void setBackOffDelay(long backOffDelay) {
    this.backOffDelay = backOffDelay;
  }

  public long getBackOffDelay() {
    return backOffDelay;
  }
</code>```

How can I inject the values of my.app.maxAttempts and my.app.backOffdelay to Spring Retry annotation? In the example below, I want to replace the value 10 of maxAttempts and 500Lof backoff value with the corresponding references of config properties.

```<code>@Retryable(maxAttempts=10, include=TimeoutException.class, backoff=@Backoff(value = 500L))
</code>```

答:
You can use Spring EL as shown below to load the properties:</p>

```<code>@Retryable(maxAttempts="${my.app.maxAttempts}",
  include=TimeoutException.class,
  backoff=@Backoff(value ="${my.app.backOffDelay}"))
</code>```

Body:
In spring boot application, I define some config properties in yaml file as below.

my.app.maxAttempts = 10
my.app.backOffDelay = 500L

And an example bean

@ConfigurationProperties(prefix = "my.app")
public class ConfigProperties {
  private int maxAttempts;
  private long backOffDelay;

  public int getMaxAttempts() {
    return maxAttempts;
  }

  public void setMaxAttempts(int maxAttempts) {
    this.maxAttempts = maxAttempts;
  }

  public void setBackOffDelay(long backOffDelay) {
    this.backOffDelay = backOffDelay;
  }

  public long getBackOffDelay() {
    return backOffDelay;
  }

How can I inject the values of my.app.maxAttempts and my.app.backOffdelay to Spring Retry annotation? In the example below, I want to replace the value 10 of maxAttempts and 500Lof backoff value with the corresponding references of config properties.

@Retryable(maxAttempts=10, include=TimeoutException.class, backoff=@Backoff(value = 500L))

Body:
You can use Spring EL as shown below to load the properties:

@Retryable(maxAttempts="${my.app.maxAttempts}",
  include=TimeoutException.class,
  backoff=@Backoff(value ="${my.app.backOffDelay}"))