问:
Python Multiprocessing Modules
EDIT: Updated with environment information (see first section)

Environment

I'm using Python 2.7

Ubuntu 16.04

Issue

I have an application which I've simplified into a three-stage process:

Gather data from multiple data sources (HTTP requests, system info, etc)

Compute metrics based on this data

Output these metrics in various formats

Each of these stages must complete before moving on to the next stage, however each stage consists of multiple sub-tasks that can be run in parallel (I can send off 3 HTTP requests and read system logs while waiting for them to return)

I've divided up the stages into modules and the sub-tasks into submodules, so my project hierarchy looks like so:

```<code>+ datasources
|-- __init__.py
|-- data_one.py
|-- data_two.py
|-- data_three.py
+ metrics
|-- __init__.py
|-- metric_one.py
|-- metric_two.py
+ outputs
|-- output_one.py
|-- output_two.py
- app.py
</code>```

app.py looks roughly like so (pseudo-code for brevity):

```<code>import datasources
import metrics
import outputs

for datasource in dir(datasources):
    datasource.refresh()
for metric in dir(metrics):
    metric.calculate()
for output in dir(outputs):
    output.dump()
</code>```

(There's additional code wrapping the dir call to ignore system modules, there's exception handling, etc -- but this is the gist of it)

Each datasource sub-module looks roughly like so:

```<code>data = []

def refresh():
    # Populate the "data" member somehow
    data = [1, 2, 3]
    return
</code>```

Each metric sub-module looks roughly like so:

```<code>import datasources.data_one as data_one
import datasources.data_two as data_two

data = []

def calculate():
    # Use the datasources to compute the metric
    data = [sum(x) for x in zip(data_one, data_two)]
    return
</code>```

In order to parallelize the first stage (datasources) I wrote something simple like the following:

```<code>def run_thread(datasource):
    datasource.refresh()

threads = []
for datasource in dir(datasources):
    thread = threading.Thread(target=run_thread, args=(datasource))
    threads.append(thread)
    thread.start()
for thread in threads:
    thread.join()
</code>```

This works, and afterwards I can compute any metric and the datasources.x.data attribute is populated

In order to parallelize the second stage (metrics) because it depends less on I/O and more on CPU, I felt like simple threading wouldn't actually speed things up and I would need the multiprocessing module in order to take advantage of multiple cores. I wrote the following:

```<code>def run_pool(calculate):
    calculate()

pool = multiprocessing.Pool()
pool.map(run_pool, [m.calculate for m in dir(metrics)]
pool.close()
pool.join()
</code>```

This code runs for a few seconds (so I think it's working?) but then when I try:

```<code>metrics.metric_one.data
</code>```

it returns [], like the module was never run

Somehow by using the multiprocessing module it seems to be scoping the threads so that they no longer share the data attribute. How should I go about rewriting this so that I can compute each metric in parallel, taking advantage of multiple cores, but still have access to the data when it's done?

答:
Updated again, per comments:
Since you're in 2.7, and you're dealing with modules instead of objects, you're having problems pickling what you need.  The workaround is not pretty.  It involves passing the name of each module to your operating function.  I updated the partial section, and also updated to remove the with syntax.

A few things:

First, in general, it's better to multicore than thread.  With threading, you always run a risk of dealing with the Global Interpreter Lock, which can be extremely inefficient.  This becomes a non-issue if you use multicore.

Second, you've got the right concept, but you make it strange by having a global-to-the-module data member.  Make your sources return the data you're interested in, and make your metrics (and outputs) take a list of data as input and output the resultant list.

This would turn your pseudocode into something like this:

app.py:

```<code>import datasources
import metrics
import outputs

pool = multiprocessing.Pool()
data_list = pool.map(lambda o: o.refresh, list(dir(datasources)))
pool.close()
pool.join()

pool = multiprocessing.Pool()
metrics_funcs = [(m, data_list) for m in dir(metrics)]
metrics_list = pool.map(lambda m: m[0].calculate(m[1]), metrics_funcs)
pool.close()
pool.join()

pool = multiprocessing.Pool()
output_funcs = [(o, data_list, metrics_list) for o in dir(outputs)]
output_list = pool.map(lambda o: o[0].dump(o[1], o[2]), output_funcs)
pool.close()
pool.join()
</code>```

Once you do this, your data source would look like this:

```<code>def refresh():
    # Populate the "data" member somehow
    return [1, 2, 3]
</code>```

And your metrics would look like this:

```<code>def calculate(data_list):
    # Use the datasources to compute the metric
    return [sum(x) for x in zip(data_list)]
</code>```

And finally, your output could look like this:

```<code>def dump(data_list, metrics_list):
    # do whatever; you now have all the information
</code>```

Removing the data "global" and passing it makes each piece a lot cleaner (and a lot easier to test).  This highlights making each piece completely independent.  As you can see, all I'm doing is changing what's in the list that gets passed to map, and in this case, I'm injecting all the previous calculations by passing them as a tuple and unpacking them in the function.  You don't have to use lambdas, of course.  You can define each function separately, but there's really not much to define.  However, if you do define each function, you could use partial functions to reduce the number of arguments you pass.  I use that pattern a lot, and in your more complicated code, you may need to.  Here's one example:

```<code>from functools import partial

do_dump(module_name, data_list, metrics_list):
    globals()[module_name].dump(data_list, metrics_list)

invoke = partial(do_dump, data_list=data_list, metrics_list=metrics_list)
with multiprocessing.Pool() as pool:
    output_list = pool.map(invoke, [o.__name__ for o in dir(outputs)])
    pool.close()
    pool.join()
</code>```

Update, per comments:

When you use map, you're guaranteed that the order of your inputs matches the order of your outputs, i.e. data_list[i] is the output for running dir(datasources)[i].refresh().  Rather than importing the datasources modules into metrics, I would make this change to app.py:

```<code>data_list = ...
pool.close()
pool.join()
data_map = {name: data_list[i] for i, name in enumerate(dir(datasources))}
</code>```

And then pass data_map into each metric.  Then the metric gets the data that it wants by name, e.g.

```<code>d1 = data_map['data_one']
d2 = data_map['data_two']
return [sum(x) for x in zip([d1, d2])]
</code>```

Title: Python Multiprocessing Modules

Body:
EDIT: Updated with environment information (see first section)

Environment

I'm using Python 2.7

Ubuntu 16.04

Issue

I have an application which I've simplified into a three-stage process:

Gather data from multiple data sources (HTTP requests, system info, etc)

Compute metrics based on this data

Output these metrics in various formats

Each of these stages must complete before moving on to the next stage, however each stage consists of multiple sub-tasks that can be run in parallel (I can send off 3 HTTP requests and read system logs while waiting for them to return)

I've divided up the stages into modules and the sub-tasks into submodules, so my project hierarchy looks like so:

+ datasources
|-- __init__.py
|-- data_one.py
|-- data_two.py
|-- data_three.py
+ metrics
|-- __init__.py
|-- metric_one.py
|-- metric_two.py
+ outputs
|-- output_one.py
|-- output_two.py
- app.py

app.py looks roughly like so (pseudo-code for brevity):

import datasources
import metrics
import outputs

for datasource in dir(datasources):
    datasource.refresh()
for metric in dir(metrics):
    metric.calculate()
for output in dir(outputs):
    output.dump()

(There's additional code wrapping the dir call to ignore system modules, there's exception handling, etc -- but this is the gist of it)

Each datasource sub-module looks roughly like so:

data = []

def refresh():
    # Populate the "data" member somehow
    data = [1, 2, 3]
    return

Each metric sub-module looks roughly like so:

import datasources.data_one as data_one
import datasources.data_two as data_two

data = []

def calculate():
    # Use the datasources to compute the metric
    data = [sum(x) for x in zip(data_one, data_two)]
    return

In order to parallelize the first stage (datasources) I wrote something simple like the following:

def run_thread(datasource):
    datasource.refresh()

threads = []
for datasource in dir(datasources):
    thread = threading.Thread(target=run_thread, args=(datasource))
    threads.append(thread)
    thread.start()
for thread in threads:
    thread.join()

This works, and afterwards I can compute any metric and the datasources.x.data attribute is populated

In order to parallelize the second stage (metrics) because it depends less on I/O and more on CPU, I felt like simple threading wouldn't actually speed things up and I would need the multiprocessing module in order to take advantage of multiple cores. I wrote the following:

def run_pool(calculate):
    calculate()

pool = multiprocessing.Pool()
pool.map(run_pool, [m.calculate for m in dir(metrics)]
pool.close()
pool.join()

This code runs for a few seconds (so I think it's working?) but then when I try:

metrics.metric_one.data

it returns [], like the module was never run

Somehow by using the multiprocessing module it seems to be scoping the threads so that they no longer share the data attribute. How should I go about rewriting this so that I can compute each metric in parallel, taking advantage of multiple cores, but still have access to the data when it's done?

Body:
Updated again, per comments:
Since you're in 2.7, and you're dealing with modules instead of objects, you're having problems pickling what you need.  The workaround is not pretty.  It involves passing the name of each module to your operating function.  I updated the partial section, and also updated to remove the with syntax.

A few things:

First, in general, it's better to multicore than thread.  With threading, you always run a risk of dealing with the Global Interpreter Lock, which can be extremely inefficient.  This becomes a non-issue if you use multicore.

Second, you've got the right concept, but you make it strange by having a global-to-the-module data member.  Make your sources return the data you're interested in, and make your metrics (and outputs) take a list of data as input and output the resultant list.

This would turn your pseudocode into something like this:

app.py:

import datasources
import metrics
import outputs

pool = multiprocessing.Pool()
data_list = pool.map(lambda o: o.refresh, list(dir(datasources)))
pool.close()
pool.join()

pool = multiprocessing.Pool()
metrics_funcs = [(m, data_list) for m in dir(metrics)]
metrics_list = pool.map(lambda m: m[0].calculate(m[1]), metrics_funcs)
pool.close()
pool.join()

pool = multiprocessing.Pool()
output_funcs = [(o, data_list, metrics_list) for o in dir(outputs)]
output_list = pool.map(lambda o: o[0].dump(o[1], o[2]), output_funcs)
pool.close()
pool.join()

Once you do this, your data source would look like this:

def refresh():
    # Populate the "data" member somehow
    return [1, 2, 3]

And your metrics would look like this:

def calculate(data_list):
    # Use the datasources to compute the metric
    return [sum(x) for x in zip(data_list)]

And finally, your output could look like this:

def dump(data_list, metrics_list):
    # do whatever; you now have all the information

Removing the data "global" and passing it makes each piece a lot cleaner (and a lot easier to test).  This highlights making each piece completely independent.  As you can see, all I'm doing is changing what's in the list that gets passed to map, and in this case, I'm injecting all the previous calculations by passing them as a tuple and unpacking them in the function.  You don't have to use lambdas, of course.  You can define each function separately, but there's really not much to define.  However, if you do define each function, you could use partial functions to reduce the number of arguments you pass.  I use that pattern a lot, and in your more complicated code, you may need to.  Here's one example:

from functools import partial

do_dump(module_name, data_list, metrics_list):
    globals()[module_name].dump(data_list, metrics_list)

invoke = partial(do_dump, data_list=data_list, metrics_list=metrics_list)
with multiprocessing.Pool() as pool:
    output_list = pool.map(invoke, [o.__name__ for o in dir(outputs)])
    pool.close()
    pool.join()

Update, per comments:

When you use map, you're guaranteed that the order of your inputs matches the order of your outputs, i.e. data_list[i] is the output for running dir(datasources)[i].refresh().  Rather than importing the datasources modules into metrics, I would make this change to app.py:

data_list = ...
pool.close()
pool.join()
data_map = {name: data_list[i] for i, name in enumerate(dir(datasources))}

And then pass data_map into each metric.  Then the metric gets the data that it wants by name, e.g.

d1 = data_map['data_one']
d2 = data_map['data_two']
return [sum(x) for x in zip([d1, d2])]


来源: stackexchange

问:
Angular js inside of an ng-if
I know this is not how the code should be structured but I am limited.  I am trying to include a datatable inside angular ng-if section.  When I take off the ng-if statement the js runs fine.  I am looking for ways around this where it works.  I have tried to move the js outside of the ng-if, but then the datatable doesn't work.  Any hint in the right direction would be helpful.  Thanks.</p>

```<code><div ng-if="test">
    <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
    <!-- Results table -->
    <table id="example2" class="table table-striped table-bordered" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Account</th>
                <th>Created On</th>
                <th>Table ID</th>
                <th>Edit</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-click="displayStatementToggle()">
                <th>123</th>
                <th>2011-04-28 13:32:07</th>
                <th>Mortgage</th>
                <th>Edit</th>
            </tr>
            <tr ng-click="displayStatementToggle()">
                <th>123</th>
                <th>2016-04-18 14:36:07</th>
                <th>Monthly</th>
                <th>Edit</th>
            </tr>
        </tbody>
    </table>
    <script>
        $(document).ready(function() {
            $('#example2').DataTable();
        });
    </script>
</div>
</code>```

答:
ng-if will create a child scope which is different from your controller scope. Try to use ng-show instead</p>

```<code><div ng-show="test">
    <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
    <!-- Results table -->
    <table id="example2" class="table table-striped table-bordered" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Account</th>
                <th>Created On</th>
                <th>Table ID</th>
                <th>Edit</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-click="displayStatementToggle()">
                <th>123</th>
                <th>2011-04-28 13:32:07</th>
                <th>Mortgage</th>
                <th>Edit</th>
            </tr>
            <tr ng-click="displayStatementToggle()">
                <th>123</th>
                <th>2016-04-18 14:36:07</th>
                <th>Monthly</th>
                <th>Edit</th>
            </tr>
        </tbody>
    </table>
    <script>
        $(document).ready(function() {
            $('#example2').DataTable();
        });
    </script>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Angular js inside of an ng-if

Body:
I know this is not how the code should be structured but I am limited.  I am trying to include a datatable inside angular ng-if section.  When I take off the ng-if statement the js runs fine.  I am looking for ways around this where it works.  I have tried to move the js outside of the ng-if, but then the datatable doesn't work.  Any hint in the right direction would be helpful.  Thanks.

                Account
                Created On
                Table ID
                Edit

                123
                2011-04-28 13:32:07
                Mortgage
                Edit

                123
                2016-04-18 14:36:07
                Monthly
                Edit

Body:
ng-if will create a child scope which is different from your controller scope. Try to use ng-show instead

<div ng-show="test">
    <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
    <!-- Results table -->
    <table id="example2" class="table table-striped table-bordered" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Account</th>
                <th>Created On</th>
                <th>Table ID</th>
                <th>Edit</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-click="displayStatementToggle()">
                <th>123</th>
                <th>2011-04-28 13:32:07</th>
                <th>Mortgage</th>
                <th>Edit</th>
            </tr>
            <tr ng-click="displayStatementToggle()">
                <th>123</th>
                <th>2016-04-18 14:36:07</th>
                <th>Monthly</th>
                <th>Edit</th>
            </tr>
        </tbody>
    </table>
    <script>
        $(document).ready(function() {
            $('#example2').DataTable();
        });
    </script>
</div>


问:
how to get repeated integer value from string specific operators in python
I have a string value that contains numbers symbols and character.
The string is :

```<code>"1=value.2=value.4=value + 3=value.4=value+5=value"
</code>```

How to find how many repeated key value in whole string and also find repeated key values separated by + operator?

Is there a better way than splitting the string?

答:
here is the another way . If my understanding is right.</p>

```<code>import re
s = "1=value.2=value.4=value + 3=value.4=value+5=value"
# finding the all value like '1=value' as a list
new_dict_list = re.findall(r'\d+=?\w+', s)
# declaring dict for creating key value dict
new_dict={}
# declare a dict for creating key counting repetition
count_dict_key = {}
for ls in new_dict_list:
    # split the list element for finding and storing key and value
    split_value = ls.split('=')
    key = split_value[0]
    value = split_value[1]
    # checking the repetition key
    if split_value[0] in new_dict:
        count_dict_key[key] = ''.join(new_dict_list).count(key)
    else:
        new_dict[split_value[0]]=value
        count_dict_key[split_value[0]]=1

print("printing new dictionary....\n",new_dict)
print("counting key...\n",count_dict_key)
</code>```

Body:
I have a string value that contains numbers symbols and character.
The string is :

"1=value.2=value.4=value + 3=value.4=value+5=value"

How to find how many repeated key value in whole string and also find repeated key values separated by + operator?

Is there a better way than splitting the string?

Body:
here is the another way . If my understanding is right.

import re
s = "1=value.2=value.4=value + 3=value.4=value+5=value"
# finding the all value like '1=value' as a list
new_dict_list = re.findall(r'\d+=?\w+', s)
# declaring dict for creating key value dict
new_dict={}
# declare a dict for creating key counting repetition
count_dict_key = {}
for ls in new_dict_list:
    # split the list element for finding and storing key and value
    split_value = ls.split('=')
    key = split_value[0]
    value = split_value[1]
    # checking the repetition key
    if split_value[0] in new_dict:
        count_dict_key[key] = ''.join(new_dict_list).count(key)
    else:
        new_dict[split_value[0]]=value
        count_dict_key[split_value[0]]=1

print("printing new dictionary....\n",new_dict)
print("counting key...\n",count_dict_key)


问:
How would you model a collection of users and friends in Firebase?
I'm trying to create a database (json) with Firebase.
I searched the docs and the net but couldn't find a clear way to start.
I want to have a database of users.
each user (represented as UID) should have a nickname and a list of friends.

I tried making a .json file that looks like this:

```<code>{
  users:{

  }
}
</code>```

and adding it to the Firebase console to get started but it wouldn't work.
How can I do it?

the database should look like this:

```<code>{
  users:{
       UID:{
          nickname: hello
          friends: UID2
       }
       UID2:{
          nickname: world
          friends: UID
  }
}
</code>```

I don't know if I got that right, so I would really appreciate any help you guys could give me at this subject.
Thanks in advance!

答:
Seems like a good place to start. I would make two changes though.

keep the list is friends separate

keep the friends as a set, instead of a single value or array

keep the list is friends separate

A basic recommendation when using the Firebase Database is to keep your data structure shallow/flat. There are many reasons for this, and you have at least two.

With your current data structure, say that you want to show a list of user names. You can only get that list by listening to /users. And that means you don't just get the user name for each user, but also their list of friends. Chances that you're going to show all that data to the user are minimal, so that means that you've just wasted some of their bandwidth.

Say that you want to allow everyone to read the list of user names. But you only want each user to be able to read their own list of friends. Your current data structure makes that hard, since permission cascades and rules are not filters.

A better structure is to keep the list of user profiles (currently just their name) separate from the list of friends for each user.

keep the friends as a set

You current have just a single value for the friends property. As you start building the app you will need to store multiple friends. The most common is to then store an array or list of UIDS:

```<code>[ UID1, UID2, UID3 ]
</code>```

Or

```<code>{
  "-K.......1": "UID1"
  "-K.......5": "UID2"
  "-K.......9": "UID3"
}
</code>```

These are unfortunately the wrong type for this data structure. Both the array and the second collection are lists: an ordered collection of (potentially) non-unique values. But a collection of friends doesn't have to be ordered, it has to be unique. I'm either in the collection or I'm not in there, I can't be in there multiple times and the order typically doesn't matter. That's why you often end up looking for friends.contains("UID1") or ref.orderByValue().equalTo("UID1") operations with the above models.

A much better model is to store the data as a set. A set is a collection of unordered values, which have to be unique. Perfect for a collection of friends. To store that in Firebase, we use the UID as the key of the collection. And since we can't store a key without a value, we use true as the dummy value.

So this leads to this data model:

```<code>{
  users:{
     UID:{
       nickname: hello
     }
     UID2:{
       nickname: world
     }
  }
  friends:{
     UID:{
       UID2: true
     }
     UID2:{
       UID: true
     }
  }
}
</code>```

There is a lot more to say/learn about NoSQL data modeling in general and Firebase specifically. To learn about that, I recommend reading NoSQL data modeling and watching Firebase for SQL developers.

Body:
I'm trying to create a database (json) with Firebase.
I searched the docs and the net but couldn't find a clear way to start.
I want to have a database of users.
each user (represented as UID) should have a nickname and a list of friends.

I tried making a .json file that looks like this:

{
  users:{

  }
}

and adding it to the Firebase console to get started but it wouldn't work.
How can I do it?

the database should look like this:

{
  users:{
       UID:{
          nickname: hello
          friends: UID2
       }
       UID2:{
          nickname: world
          friends: UID
  }
}

I don't know if I got that right, so I would really appreciate any help you guys could give me at this subject.
Thanks in advance!

Body:
Seems like a good place to start. I would make two changes though.

keep the list is friends separate

keep the friends as a set, instead of a single value or array

keep the list is friends separate

A basic recommendation when using the Firebase Database is to keep your data structure shallow/flat. There are many reasons for this, and you have at least two.

With your current data structure, say that you want to show a list of user names. You can only get that list by listening to /users. And that means you don't just get the user name for each user, but also their list of friends. Chances that you're going to show all that data to the user are minimal, so that means that you've just wasted some of their bandwidth.

Say that you want to allow everyone to read the list of user names. But you only want each user to be able to read their own list of friends. Your current data structure makes that hard, since permission cascades and rules are not filters.

A better structure is to keep the list of user profiles (currently just their name) separate from the list of friends for each user.

keep the friends as a set

You current have just a single value for the friends property. As you start building the app you will need to store multiple friends. The most common is to then store an array or list of UIDS:

[ UID1, UID2, UID3 ]

Or

{
  "-K.......1": "UID1"
  "-K.......5": "UID2"
  "-K.......9": "UID3"
}

These are unfortunately the wrong type for this data structure. Both the array and the second collection are lists: an ordered collection of (potentially) non-unique values. But a collection of friends doesn't have to be ordered, it has to be unique. I'm either in the collection or I'm not in there, I can't be in there multiple times and the order typically doesn't matter. That's why you often end up looking for friends.contains("UID1") or ref.orderByValue().equalTo("UID1") operations with the above models.

A much better model is to store the data as a set. A set is a collection of unordered values, which have to be unique. Perfect for a collection of friends. To store that in Firebase, we use the UID as the key of the collection. And since we can't store a key without a value, we use true as the dummy value.

So this leads to this data model:

{
  users:{
     UID:{
       nickname: hello
     }
     UID2:{
       nickname: world
     }
  }
  friends:{
     UID:{
       UID2: true
     }
     UID2:{
       UID: true
     }
  }
}

There is a lot more to say/learn about NoSQL data modeling in general and Firebase specifically. To learn about that, I recommend reading NoSQL data modeling and watching Firebase for SQL developers.


问:
PHP question about global variables and form requests
This is probably a stupid question but will ask anyway sine I have no idea.

I have written basic php code which serve forms. Say I have a login page and I serve it using the login.php page and it will be called in the login.html page like this -

```<code><form action="login.php" method="post">
</code>```

By this it is also implied that every POST needs its own php file, doesn't it? This kind of feels weird. Is there a way to have a single file, say code.php, and just have each of the forms as functions instead?

EDIT: Specifically, say I have 5 forms that are used one after the other in my application. Say after login the user does A, B, C and D tasks each of which are sent to the server as a POST request. So instead of having A.php, B.php, C.php and D.php I would like to have a single code.php and have A(), B(), C() and D() as functions. Is there a way to do this?

Also on the same note, how do I deal with say a global array (e.g. an array of currently logged in users) across multiple forms? I want to do this without writing to a DB. I know its probably better to write to a DB and query but is it even possible to do it with a global array? The reason I was thinking about having all the form functions in one file is to use a global array.

Thanks,
- Pav

答:
There is no reason why you can't just have login.html and login.php as the same file. Combine the code on both of these pages into one block of code and then use an if statement to check whether the form has been posted. This was you can either serve the form to login or present the result of a successfully completed form.

A Session global variable will handle your global array problem but I don't think it's appropriate for your example. That example would need a database table to store when a user logs in as there is no other way to update the global variables on your instance of the application from someone else's instance.

EDIT

I would use a Session variable to determine how much of the form has been completed and then maybe use a switch statement to serve the correct form:

```<code>function a(){
    //process form A
    //if form A okay
        $_SESSION['form_progress'] = 'b';
}
function b(){
    //process form B
    //if form B okay
        $_SESSION['form_progress'] = 'c';
}
function c(){
    //process form C
    //if form C okay
        $_SESSION['form_progress'] = 'd';
}

switch($_SESSION['form_progress']){
    case 'b':
       //serve form B
       break;
    case 'c':
       //serve form C
       break;
    case default:
       //serve form A
       break;
}
</code>```

Hope this helps

ContentLicense: CC BY-SA 2.5

Body:
This is probably a stupid question but will ask anyway sine I have no idea.

I have written basic php code which serve forms. Say I have a login page and I serve it using the login.php page and it will be called in the login.html page like this -

<form action="login.php" method="post">

By this it is also implied that every POST needs its own php file, doesn't it? This kind of feels weird. Is there a way to have a single file, say code.php, and just have each of the forms as functions instead?

EDIT: Specifically, say I have 5 forms that are used one after the other in my application. Say after login the user does A, B, C and D tasks each of which are sent to the server as a POST request. So instead of having A.php, B.php, C.php and D.php I would like to have a single code.php and have A(), B(), C() and D() as functions. Is there a way to do this?

Also on the same note, how do I deal with say a global array (e.g. an array of currently logged in users) across multiple forms? I want to do this without writing to a DB. I know its probably better to write to a DB and query but is it even possible to do it with a global array? The reason I was thinking about having all the form functions in one file is to use a global array.

Thanks,
- Pav

Body:
There is no reason why you can't just have login.html and login.php as the same file. Combine the code on both of these pages into one block of code and then use an if statement to check whether the form has been posted. This was you can either serve the form to login or present the result of a successfully completed form.

A Session global variable will handle your global array problem but I don't think it's appropriate for your example. That example would need a database table to store when a user logs in as there is no other way to update the global variables on your instance of the application from someone else's instance.

EDIT

I would use a Session variable to determine how much of the form has been completed and then maybe use a switch statement to serve the correct form:

function a(){
    //process form A
    //if form A okay
        $_SESSION['form_progress'] = 'b';
}
function b(){
    //process form B
    //if form B okay
        $_SESSION['form_progress'] = 'c';
}
function c(){
    //process form C
    //if form C okay
        $_SESSION['form_progress'] = 'd';
}

switch($_SESSION['form_progress']){
    case 'b':
       //serve form B
       break;
    case 'c':
       //serve form C
       break;
    case default:
       //serve form A
       break;
}

Hope this helps


问:
When exactly does Python import?

Question

If I have import statements nested in an if/else block, am I increasing efficiency? I know some languages do "one passes" over code for import and syntax issues. I'm just not sure how in depth Python goes into this.

My Hypothesis

Because Python is interpreted and not compiled, by nesting the import statements within the else block, those libraries will not be imported until that line is reached, thus saving system resources unless otherwise needed.

Scenario

I have written a script that will be used by both the more computer literate and those are lesser so. My department is very comfortable with running scripts from the command line with arguments so I have set it up to take arguments for what it needs and, if it does not find the arguments it was expecting, it will launch a GUI with headings, buttons, and more verbose instructions. However, this means that I am importing libraries that are only being used in the event that the arguments were not provided.

Additional Information

The GUI is very, very basic (A half dozen text fields and possibly fewer buttons) so I am not concerned with just creating and spawning a custom GUI class in which the necessary libraries would be imported. If this gets more complicated, I'll consider it in the future or even push to change to web interface.

My script fully functions as I would expect it to. The question is simply about resource consumption.

答:
import statements are executed as they're encountered in normal execution, so if the conditional prevents that line from being executed, the import doesn't occur, and you'll have avoided unnecessary work.

That said, if the module is going to be imported in some other way (say, unconditionally imported module B depends on A, and you're conditionally importing A), the savings are trivial; after the first import of a module, subsequent imports just get a new reference to the same cached module; the import machinery has to do some complicated stuff to handle import hooks and the like first, but in the common case, it's still fairly cheap (sub-microsecond when importing an already cached module).

The only way this will save you anything is if the module in question would not be imported in any way otherwise, in which case you avoid the work of loading it and the memory used by the loaded module.

Title: When exactly does Python import?


问:
JQuery function created inside a user control inside a repeater inside an update panel is not working
When I move my user control outside of the repeater and (still inside the update panel) pass its properties manually instead of using repeater, everything works fine. But when I use the repeater to pass properties to my user control, the user control gets loaded from database fine and appears on the final client page which shows those parameters (PID, StID) passes successfully but its jQuery function stops working. So again jQuery works fine outside of the repeater.

Things I tried:

Since they say repeater messes up with the unique ID of the elements, I used class instead. This did not work. I also used unique IDs for class and element ID's, which didn't work either. Now I am using unique names for classes inside repeater because my PID is a GUID and I construct unique stuff there for class names.

Moved myusercontrol out of repeater. This works.

I created another page and I manually give properties to my user control. This works fine.

I wrote one similar script to what u see in the post but outside of the repeater to simply hide and show my  element inside the user control within the repeater. but that also did not work! I cannot even see the html output of the user control in the final page>view source ( I guess MS uses different mechanism to hide them ) although I see user control on the final page! unless I put the user control outside the repeater or I use chrome dev tool then I can see the html output of user control. I am not sure if it has something to do with this.

MyPage.aspx

```<code><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
    <asp:Panel ID="Panel1" runat="server" Height="49px" Style="margin-left: 211px">
                <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                    <ContentTemplate>
                        <asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSrc1" ViewStateMode="Enabled" EnableViewState="False">
                            <ItemTemplate>
                                <div id='FC<%# Eval("PID")%><%# Eval("SID")%>'>
                                    <UserControl:MView runat="Server" PelID='<%#Eval("PID")%>' StID='<%#Eval("SID") %>' ID="Mview1" ViewStateMode="Enabled" EnableViewState="False" />
                                </div>
                            </ItemTemplate>
                        </asp:Repeater>
                        <asp:SqlDataSource ID="SqlDataSrc1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString2 %>" SelectCommand="SELECT PID, SID FROM [fc] LEFT JOIN [pt] ON [pt].ID = [fc].PID WHERE ([pt].[TID] = @TID)">
                            <SelectParameters>
                                <asp:ControlParameter ControlID="TreeView1" Name="TID" PropertyName="SelectedValue" DefaultValue="5AF4D771-9DA9-46B9-8075-200DF8652063" Type="String" />
                            </SelectParameters>
                        </asp:SqlDataSource>
           </ContentTemplate>
            </asp:UpdatePanel>
        </asp:Panel>
</code>```

User.Ascx

```<code>    $(document).ready(function () {
       $("body").on( 'click', "#front<%= PID.ToString()%><%=StID.ToString()%>",function (e) {
           alert('test');
           $("div.divBC<%= PID.ToString()%><%=StID.ToString()%>").hide();
            $("div.divCF<%= PID.ToString()%><%=StID.ToString()%>").show();
           e.preventDefault();
           e.disablePopup();
           return false;

        });

        $("body").on('click', "#back<%= PID.ToString()%><%=StID.ToString()%>", function (e) {
            alert("before Back");
            $("div.divCF<%= PID.ToString()%><%=StID.ToString()%>").hide();
            $("div.divBC<%= PID.ToString()%><%=StID.ToString()%>").css('visibility', 'visible');
            $("div.divBC<%= PID.ToString()%><%=StID.ToString()%>").show();
            e.preventDefault();
            e.disablePopup();
            return false;
        });
    });

</script>
    <table style="width: 100%;">
        <tr>
            <td>
                <asp:Label ID="Lable1" runat="server" Text="--"></asp:Label></td>
            <td>
                <asp:Label ID="Label2" runat="server" Text="--"></asp:Label></td>
            <td>
                <asp:Label ID="Label3" runat="server" Text="--"></asp:Label></td>
        </tr>
        <tr>
            <td colspan="3" >
                <hr style="color: #C0C0C0" />
                <span>
                    Time:
                    <asp:Literal runat="server" ID="SpecialTime"></asp:Literal>

                    Last Time : [under construction! ]
                    <asp:Literal runat="server" ID="OtherThings"></asp:Literal>
                </span>
                <hr />
                <div class="divCF<%= PID.ToString()%><%=StID.ToString()%>">
                    <hr/>
                    <h3>
                        <span>
                            <br />
                            <asp:Literal runat="server" ID="Title"></asp:Literal>
                        </span>
                    </h3>
                </div>
                <div class="divBC<%= PID.ToString()%><%=StID.ToString()%>" style="visibility:hidden">
                    <asp:Literal runat="server" ID="TextCnt"></asp:Literal>
                    <input type="hidden" value="<%= PID.ToString() %>" id="PDHolder"/>
                    <input type="hidden" value="<%= StID.ToString() %>" id="StIDHolder"/>
                    <hr/>
                </div>
            </td>
        </tr>
        <tr>
            <td> </td>
            <td>
                <button id="front<%= PID.ToString()%><%=StID.ToString()%>">Front</button>
                <button id="back<%= PID.ToString()%><%=StID.ToString()%>">Back</button>
            </center>
            </td>
            <td> </td>
        </tr>
    </table>
</code>```

答:
Repeated

```<code><button id="front">
</code>```

and

```<code>$("body").on( 'click', "#front",function (e)
</code>```

do not mix well.

Another thing. You must include jQuery javascript only once in a page.

Body:
When I move my user control outside of the repeater and (still inside the update panel) pass its properties manually instead of using repeater, everything works fine. But when I use the repeater to pass properties to my user control, the user control gets loaded from database fine and appears on the final client page which shows those parameters (PID, StID) passes successfully but its jQuery function stops working. So again jQuery works fine outside of the repeater.

Things I tried:

Since they say repeater messes up with the unique ID of the elements, I used class instead. This did not work. I also used unique IDs for class and element ID's, which didn't work either. Now I am using unique names for classes inside repeater because my PID is a GUID and I construct unique stuff there for class names.

Moved myusercontrol out of repeater. This works.

I created another page and I manually give properties to my user control. This works fine.

I wrote one similar script to what u see in the post but outside of the repeater to simply hide and show my  element inside the user control within the repeater. but that also did not work! I cannot even see the html output of the user control in the final page>view source ( I guess MS uses different mechanism to hide them ) although I see user control on the final page! unless I put the user control outside the repeater or I use chrome dev tool then I can see the html output of user control. I am not sure if it has something to do with this.

MyPage.aspx

    <asp:Panel ID="Panel1" runat="server" Height="49px" Style="margin-left: 211px">
                <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                    <ContentTemplate>
                        <asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSrc1" ViewStateMode="Enabled" EnableViewState="False">
                            <ItemTemplate>
                                <div id='FC<%# Eval("PID")%><%# Eval("SID")%>'>
                                    <UserControl:MView runat="Server" PelID='<%#Eval("PID")%>' StID='<%#Eval("SID") %>' ID="Mview1" ViewStateMode="Enabled" EnableViewState="False" />

                            </ItemTemplate>
                        </asp:Repeater>
                        <asp:SqlDataSource ID="SqlDataSrc1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString2 %>" SelectCommand="SELECT PID, SID FROM [fc] LEFT JOIN [pt] ON [pt].ID = [fc].PID WHERE ([pt].[TID] = @TID)">
                            <SelectParameters>
                                <asp:ControlParameter ControlID="TreeView1" Name="TID" PropertyName="SelectedValue" DefaultValue="5AF4D771-9DA9-46B9-8075-200DF8652063" Type="String" />
                            </SelectParameters>
                        </asp:SqlDataSource>
           </ContentTemplate>
            </asp:UpdatePanel>
        </asp:Panel>

User.Ascx

    $(document).ready(function () {
       $("body").on( 'click', "#front<%= PID.ToString()%><%=StID.ToString()%>",function (e) {
           alert('test');
           $("div.divBC<%= PID.ToString()%><%=StID.ToString()%>").hide();
            $("div.divCF<%= PID.ToString()%><%=StID.ToString()%>").show();
           e.preventDefault();
           e.disablePopup();
           return false;

        });

        $("body").on('click', "#back<%= PID.ToString()%><%=StID.ToString()%>", function (e) {
            alert("before Back");
            $("div.divCF<%= PID.ToString()%><%=StID.ToString()%>").hide();
            $("div.divBC<%= PID.ToString()%><%=StID.ToString()%>").css('visibility', 'visible');
            $("div.divBC<%= PID.ToString()%><%=StID.ToString()%>").show();
            e.preventDefault();
            e.disablePopup();
            return false;
        });
    });

</script>

                <asp:Label ID="Lable1" runat="server" Text="--"></asp:Label>

                <asp:Label ID="Label2" runat="server" Text="--"></asp:Label>

                <asp:Label ID="Label3" runat="server" Text="--"></asp:Label>

                    Time:
                    <asp:Literal runat="server" ID="SpecialTime"></asp:Literal>

                    Last Time : [under construction! ]
                    <asp:Literal runat="server" ID="OtherThings"></asp:Literal>

                <div class="divCF<%= PID.ToString()%><%=StID.ToString()%>">

                            <asp:Literal runat="server" ID="Title"></asp:Literal>

                <div class="divBC<%= PID.ToString()%><%=StID.ToString()%>" style="visibility:hidden">
                    <asp:Literal runat="server" ID="TextCnt"></asp:Literal>
                    <input type="hidden" value="<%= PID.ToString() %>" id="PDHolder"/>
                    <input type="hidden" value="<%= StID.ToString() %>" id="StIDHolder"/>

                <button id="front<%= PID.ToString()%><%=StID.ToString()%>">Front</button>
                <button id="back<%= PID.ToString()%><%=StID.ToString()%>">Back</button>

Body:
Repeated

<button id="front">

and

$("body").on( 'click', "#front",function (e)

do not mix well.

Another thing. You must include jQuery javascript only once in a page.


问:
What's the scripting language that works best when binding with c++?
I am working on a project that heavily relies on many c++ objects that I created. In stead of compiling the codes every time when I use different objects, I am thinking using scripts that can instantiate c++ objects and call their functions without recompiling. What are the possible candidates? Thanks for the answer in advance.</p>

答:
sol2 is a good C++ wrapper for Lua: it offers fast execution time and minimal dependencies.

An alterantive is ChaiScript, but it's not as fast as sol2.


问:
What is the benefit of using redux?
I am thinking about learning reactjs recently and I hope if someone could help me to understand the circumstances to use redux, as I am confused by its complicated logic.

First, I have used angular2+ for a while, and so I am also trying to grab the idea from the what I have already know.

I have seen many examples of redux but I don't understand the benefit to use actions and dispatch.

What is the benefit of using redux store using actions and reducers instead of just use class and subject like this?

```<code>class Store{
    subject = new BehaviorSubject(0);
    get value(){
        return this.subject.getValue();
    }
    inc(){
        this.subject.next(this.subject.value+1);
    }
    dec(){
        this.subject.next(this.subject.value-1);
    }
    clear(){
        this.subject.next(0);
    }
}

class Demo extends React.Component<{}, {}>{
    store = new Store();
    componentWillMount(){
        this.store.subject.subscribe(_ => this.forceUpdate())
    }
    render(){
        const value = this.store.value;
        const { inc, dec, clear } = this.store;
        const store = this.store;
        return (
            <div>
                <span>{`current value is ${value}`}</span>
                <button onClick={inc.bind(store)}>INC</button>
                <button onClick={dec.bind(store)}>DEC</button>
                <button onClick={clear.bind(store)}>CLEAR</button>
            </div>
        );
    }
}
</code>```

答: @Dmitry Sokurenko's answer is good.  For more info, see Dan Abramov's posts on You Might Not Need Redux and The Case for Flux, as well as the Redux FAQ on "when should I use Redux?".  Also, while you're not using React, you might also be interested in an article I co-wrote about the benefits of using Redux in a React app.</p>

Title: What is the benefit of using redux?

Body:
I am thinking about learning reactjs recently and I hope if someone could help me to understand the circumstances to use redux, as I am confused by its complicated logic.

First, I have used angular2+ for a while, and so I am also trying to grab the idea from the what I have already know.

I have seen many examples of redux but I don't understand the benefit to use actions and dispatch.

What is the benefit of using redux store using actions and reducers instead of just use class and subject like this?

class Store{
    subject = new BehaviorSubject(0);
    get value(){
        return this.subject.getValue();
    }
    inc(){
        this.subject.next(this.subject.value+1);
    }
    dec(){
        this.subject.next(this.subject.value-1);
    }
    clear(){
        this.subject.next(0);
    }
}

class Demo extends React.Component<{}, {}>{
    store = new Store();
    componentWillMount(){
        this.store.subject.subscribe(_ => this.forceUpdate())
    }
    render(){
        const value = this.store.value;
        const { inc, dec, clear } = this.store;
        const store = this.store;
        return (

                {`current value is ${value}`}
                <button onClick={inc.bind(store)}>INC</button>
                <button onClick={dec.bind(store)}>DEC</button>
                <button onClick={clear.bind(store)}>CLEAR</button>

        );
    }
}


问:
How to lower case entire column data in Google Cloud BigQuery
I am trying to find a "quick" way to lower case all the data (strings) in a table's column inside Google Cloud BigQuery.

Before going into building a script, I'm looking for more shorter way like Query.

How can I query BigQuery to lower case entire column?

答:
How can I query BigQuery to lower case entire column?

Definitely LOWER is the function to use

For example

```<code>#standardSQL
WITH `dataset.table` AS (
  SELECT
    'https://stackoverflow.com/q/44970976/5221944' AS url,
    'How to lower case entire column data in Google Cloud BigQuery' AS title
)
SELECT * REPLACE(LOWER(title) AS title)
FROM `dataset.table`
</code>```

I am trying to find a "quick" way to lower case all the data

From what I see in your question  - I would not recommend using DML's UPDATE as it is Costly and not necessarily "quick" and for sure not flexible in case if you later will want to change your mind let say to have it UPPER or somehow differently (camel style for example)

The quick way in your case I see in creating view like below. It is cheap ($0.00) and flexible to accomodate any logic of transforming columns in original table

```<code>SELECT * REPLACE(LOWER(title) AS title)
FROM `dataset.table`
</code>```

Body:
How can I query BigQuery to lower case entire column?

Definitely LOWER is the function to use

For example

#standardSQL
WITH `dataset.table` AS (
  SELECT
    'https://stackoverflow.com/q/44970976/5221944' AS url,
    'How to lower case entire column data in Google Cloud BigQuery' AS title
)
SELECT * REPLACE(LOWER(title) AS title)
FROM `dataset.table`

I am trying to find a "quick" way to lower case all the data

From what I see in your question  - I would not recommend using DML's UPDATE as it is Costly and not necessarily "quick" and for sure not flexible in case if you later will want to change your mind let say to have it UPPER or somehow differently (camel style for example)

The quick way in your case I see in creating view like below. It is cheap ($0.00) and flexible to accomodate any logic of transforming columns in original table

SELECT * REPLACE(LOWER(title) AS title)
FROM `dataset.table`


问:
Form not showing, Only the button shows Django
I am trying to show a newsletter form, and it is not shown in the page

This is my models.py

```<code>from django.db import models

# Create your models here.

class newsletter_user(models.Model):
    email = models.EmailField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.email
</code>```

This is my forms.py

```<code>from django import forms
from .models import newsletter_user

class newsletterForm(forms.ModelForm):

    class Meta:
        model = newsletter_user
        fields = ['email']

        def clean_email(self):
            email = self.cleaned_data.get('email')
            return email
</code>```

This is my admin.py

```<code>from django.contrib import admin

from .models import newsletter_user
# Register your models here.
class newsletterAdmin(admin.ModelAdmin):
    list_display = ('email','date_added',)

admin.site.register(newsletter_user,newsletterAdmin)
</code>```

This is the views.py

```<code>from django.shortcuts import render
from .models import newsletter_user
from .forms import newsletterForm

# Create your views here.
def newsletter_subscribe(request):
    form = newsletterForm(request.POST or none)

    if form.is_valid():
        instance = form.save(commit=false)
        if newsletter_user.objects.filter(email=instance.email).exists():
            print("already exists")
        else:
            instance.save()

    context = {'form':form,}
    template = "/blog/templates/footer.html"
    return render(request, template, context)
</code>```

This is the html

```<code><form method="post" action=''>
    <div class = "input-group">
        {{form}}  {% csrf_token %}
        <span class = "input-group-btn">
            <button class="btn btn-default" type="submit">Subscribe</button>

        </span>
    </div>
</form>
</code>```

This is my urls.py

```<code>urlpatterns = [

    url(r'^admin/', admin.site.urls),
    url(r'^$', views.BlogIndex.as_view(), name='home'),
    url(r'^(?P<slug>[-\w]+)/$', views.BlogDetail.as_view(), name='entry_detail'),
    url(r'^ckeditor/', include('ckeditor_uploader.urls')),
    url(r'^footer/$', subscribe_views.newsletter_subscribe, name='subscribe'),
]
</code>```

My Project directory

The button is shown
But the form is not shown..

This is my source in web browser RIGHT-CLICK->VIEW SOURCE

答:
You may need to make some changes in your view somewhat like this,

```<code>def newsletter_subscribe(request):
    if request.method == 'POST':
        form = newsletterForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=false)
            if newsletter_user.objects.filter(email=instance.email).exists():
                print("already exists")
            else:
                instance.save()
    else:
        form = newsletterForm()
    context = {'form':form,}
    template = "/blog/templates/footer.html"
    return render(request, template, context)
</code>```

You only need to initialise the form with request.POST , if request method is actually "POST". Else, just initialise a blank form.

Body:
I am trying to show a newsletter form, and it is not shown in the page

This is my models.py

from django.db import models

# Create your models here.

class newsletter_user(models.Model):
    email = models.EmailField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.email

This is my forms.py

from django import forms
from .models import newsletter_user

class newsletterForm(forms.ModelForm):

    class Meta:
        model = newsletter_user
        fields = ['email']

        def clean_email(self):
            email = self.cleaned_data.get('email')
            return email

This is my admin.py

from django.contrib import admin

from .models import newsletter_user
# Register your models here.
class newsletterAdmin(admin.ModelAdmin):
    list_display = ('email','date_added',)

admin.site.register(newsletter_user,newsletterAdmin)

This is the views.py

from django.shortcuts import render
from .models import newsletter_user
from .forms import newsletterForm

# Create your views here.
def newsletter_subscribe(request):
    form = newsletterForm(request.POST or none)

    if form.is_valid():
        instance = form.save(commit=false)
        if newsletter_user.objects.filter(email=instance.email).exists():
            print("already exists")
        else:
            instance.save()

    context = {'form':form,}
    template = "/blog/templates/footer.html"
    return render(request, template, context)

This is the html

<form method="post" action=''>

        {{form}}  {% csrf_token %}

            <button class="btn btn-default" type="submit">Subscribe</button>

</form>

This is my urls.py

urlpatterns = [

    url(r'^admin/', admin.site.urls),
    url(r'^$', views.BlogIndex.as_view(), name='home'),
    url(r'^(?P<slug>[-\w]+)/$', views.BlogDetail.as_view(), name='entry_detail'),
    url(r'^ckeditor/', include('ckeditor_uploader.urls')),
    url(r'^footer/$', subscribe_views.newsletter_subscribe, name='subscribe'),
]

My Project directory

The button is shown
But the form is not shown..

This is my source in web browser RIGHT-CLICK->VIEW SOURCE

Body:
You may need to make some changes in your view somewhat like this,

def newsletter_subscribe(request):
    if request.method == 'POST':
        form = newsletterForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=false)
            if newsletter_user.objects.filter(email=instance.email).exists():
                print("already exists")
            else:
                instance.save()
    else:
        form = newsletterForm()
    context = {'form':form,}
    template = "/blog/templates/footer.html"
    return render(request, template, context)

You only need to initialise the form with request.POST , if request method is actually "POST". Else, just initialise a blank form.


问:
Compiler Error CS0246 Listener Service IIS 2008 R2
I have inherited a project after my colleague moved on. I have a C# project for a listener service that will be called by a cloud based application sending us requests and data. All tests work fine in dev, the problem occurs when I deploy the application on IIS 2008 R2.

The Target Framework set in the project in Visual Studio is .Net Framework 4.5.

The Virtual Directory on IIS that contains the compiled application is within an application pool set to use '.Net Framework v4.0.30319'. From my research I've seen that this Framework version should work with all applications deployed for v4.5.

The virtual directory contains the asmx file for the listener service, the Web.Config file and a bin directory containing all the binaries.

When I call the asmx file in IE I get the following error:

Compiler Error Message: CS0246: The type or namespace name 'XXX' could not be found (are you missing a using directive or an assembly reference?)

The reference XXX is listed as a using statement and is within a folder structure in the same project. It is not pointing to a separate project. I read the following Microsoft article and everything in it appears to be correct. However the comment at the end suggests that error CS0246 can also be raise when the DLL was compiled for .Net 4.5, then copied to a Project with target Plattform 4.0.

Can someone please confirm if the above application pool setting will work with an application built for .Net v4.5 and suggest why the asmx file will not compile on the webserver please?

答:
The problem seems to be in the assembly which contains the XXX
  type.You may have an older version or a different version of this assembly which does not contain this type or namespace.

Find out the dll of your type

Go to the bin directory and find out which version of this dll is present

Cross check this version with the dev environment.

If that does not work,you can manually copy this assembly from your dev environment and put in the IIS server


问:
In GridSearchCV, how do I pass only the default parameters in param_grid?
I'm a beginner, and I have the following code below.

```<code>from sklearn.naive_bayes import GaussianNB
from sklearn.decomposition import PCA

pca = PCA()
model = GaussianNB()
steps = [('pca', pca), ('model', model)]
pipeline = Pipeline(steps)

cv = StratifiedShuffleSplit(n_splits=5, test_size=0.2, random_state=42)
modelwithpca = GridSearchCV(pipeline, param_grid= ,cv=cv)
modelwithpca.fit(X_train,y_train)
</code>```

This is a local testing, what I'm trying to accomplish is,

i. Perform PCA on the dataset

ii. Use Gaussian Naive Bayes with only the default parameters

iii. Use StratifiedShuffleSplit

So in the end I want the above steps to be carried over to another function that dumps the classifier, the dataset and the feature list to test for performance.

```<code>dump_classifier_and_data(modelwithpca, dataset, features)
</code>```

In the param_grid part, I don't want to test any list of parameters. I just want to have the default parameters used in Gaussian Naive Bayes if that makes sense. What do I change?

Also should there be any changes as to how I instantiate the classifier objects?

答:
The purpose of GridSearchCV is to test with different parameters for at least one thing in your pipeline (if you don't want to test for different parameters you don't need to use GridSearchCV).
So, in general, if you want let's say to test for different PCA n_components.
The format to use a pipeline with GridSearchCV would be the following:

```<code>gscv = GridSearchCV(pipeline, param_grid={'{step_name}__{parameter_name}': [possible values]}, cv=cv)
</code>```

e.g.:

```<code># this would perform cv for the 3 different values of n_components for pca
gscv = GridSearchCV(pipeline, param_grid={'pca__n_components': [3, 6, 10]}, cv=cv)
</code>```

If you use GridSearchCV to tune PCA as above, this of course would mean that your model would have the default values.

If you don't need parameter tuning then GridSearchCV is not the way to go, since using the default parameters of your model for GridSearchCV like this, will only produce a parameter grid with one combination, so it would be like just performing only CV. It wouldn't make sense to do it like this - if I have understood your question correctly:

```<code>from sklearn.naive_bayes import GaussianNB
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline

pca = PCA()
model = GaussianNB()
steps = [('pca', pca), ('model', model)]
pipeline = Pipeline(steps)

cv = StratifiedShuffleSplit(n_splits=5, test_size=0.2, random_state=42)
# get the default parameters of your model and use them as a param_grid
modelwithpca = GridSearchCV(pipeline, param_grid={'model__' + k: [v] for k, v in model.get_params().items()}, cv=cv)

# will run 5 times as your cv is configured
modelwithpca.fit(X_train,y_train)
</code>```

Hope this helps, good luck!

Body:
I'm a beginner, and I have the following code below.

from sklearn.naive_bayes import GaussianNB
from sklearn.decomposition import PCA

pca = PCA()
model = GaussianNB()
steps = [('pca', pca), ('model', model)]
pipeline = Pipeline(steps)

cv = StratifiedShuffleSplit(n_splits=5, test_size=0.2, random_state=42)
modelwithpca = GridSearchCV(pipeline, param_grid= ,cv=cv)
modelwithpca.fit(X_train,y_train)

This is a local testing, what I'm trying to accomplish is,

i. Perform PCA on the dataset

ii. Use Gaussian Naive Bayes with only the default parameters

iii. Use StratifiedShuffleSplit

So in the end I want the above steps to be carried over to another function that dumps the classifier, the dataset and the feature list to test for performance.

dump_classifier_and_data(modelwithpca, dataset, features)

In the param_grid part, I don't want to test any list of parameters. I just want to have the default parameters used in Gaussian Naive Bayes if that makes sense. What do I change?

Also should there be any changes as to how I instantiate the classifier objects?

Body:
The purpose of GridSearchCV is to test with different parameters for at least one thing in your pipeline (if you don't want to test for different parameters you don't need to use GridSearchCV).
So, in general, if you want let's say to test for different PCA n_components.
The format to use a pipeline with GridSearchCV would be the following:

gscv = GridSearchCV(pipeline, param_grid={'{step_name}__{parameter_name}': [possible values]}, cv=cv)

e.g.:

# this would perform cv for the 3 different values of n_components for pca
gscv = GridSearchCV(pipeline, param_grid={'pca__n_components': [3, 6, 10]}, cv=cv)

If you use GridSearchCV to tune PCA as above, this of course would mean that your model would have the default values.

If you don't need parameter tuning then GridSearchCV is not the way to go, since using the default parameters of your model for GridSearchCV like this, will only produce a parameter grid with one combination, so it would be like just performing only CV. It wouldn't make sense to do it like this - if I have understood your question correctly:

from sklearn.naive_bayes import GaussianNB
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline

pca = PCA()
model = GaussianNB()
steps = [('pca', pca), ('model', model)]
pipeline = Pipeline(steps)

cv = StratifiedShuffleSplit(n_splits=5, test_size=0.2, random_state=42)
# get the default parameters of your model and use them as a param_grid
modelwithpca = GridSearchCV(pipeline, param_grid={'model__' + k: [v] for k, v in model.get_params().items()}, cv=cv)

# will run 5 times as your cv is configured
modelwithpca.fit(X_train,y_train)

Hope this helps, good luck!


问:
Android - Missing files between file explorers
I'm trying to access the two files, Spring v2.json and Test.json, in my Android app. However, I will add them using Windows with my phone connected, but when I run my app, the file seems to disappear.

Getting the file

```<code>    File file = new File(getExternalFilesDir(null), "Spring v2.json");
</code>```

Check is the file exists

```<code>  if (file.exists()) {
    TransferObserver observer = transferUtility.download(
        "easelbucket",    // bucket to download from
        "sections/" + objectKey,        // key for object to be downloaded
        file          // file to download object to
    );
  } else {
    Toast.makeText(this, "File does not exist", Toast.LENGTH_SHORT).show();
    return null;
  }
</code>```

I know that the file stops existing because (1) the if statement enters the else block, and (2) the app crashes when it attempts to use the result of the file.

答:
```<code>File file = new File(getExternalFilesDir(null), "/Spring v2.json")
</code>```

You forget slash before filename.
Also check if

```<code>.canRead();
</code>```

and

```<code>.canExecute();
</code>```

Body:
I'm trying to access the two files, Spring v2.json and Test.json, in my Android app. However, I will add them using Windows with my phone connected, but when I run my app, the file seems to disappear.

Getting the file

    File file = new File(getExternalFilesDir(null), "Spring v2.json");

Check is the file exists

  if (file.exists()) {
    TransferObserver observer = transferUtility.download(
        "easelbucket",    // bucket to download from
        "sections/" + objectKey,        // key for object to be downloaded
        file          // file to download object to
    );
  } else {
    Toast.makeText(this, "File does not exist", Toast.LENGTH_SHORT).show();
    return null;
  }

I know that the file stops existing because (1) the if statement enters the else block, and (2) the app crashes when it attempts to use the result of the file.

Body:
File file = new File(getExternalFilesDir(null), "/Spring v2.json")

You forget slash before filename.
Also check if

.canRead();

and

.canExecute();


问:
Pandas codification before comparison
I'm using Pandas to look for a reference in a huge database. The problem is that I don't know the 'type' of this reference (string, int...).

```<code>Result = DataFrame.loc[(DataFrameComposants["Reference"] == str(Reference)]
</code>```

I would like to convert the whole dataFrame into string because if the same reference has been stocked into an 'int' the comparison will be FALSE.

How can I do that ?

答:
In order to change the type of a dataframe to string, you can use pandas astype:

```<code>reference_to_string = DataFrameComposants['Reference'].astype(str)
</code>```

I am not entirely sure what you tried to do with your code...What is "Reference" in str(Reference) ?

Title: Pandas codification before comparison

Body:
I'm using Pandas to look for a reference in a huge database. The problem is that I don't know the 'type' of this reference (string, int...).

Result = DataFrame.loc[(DataFrameComposants["Reference"] == str(Reference)]

I would like to convert the whole dataFrame into string because if the same reference has been stocked into an 'int' the comparison will be FALSE.

How can I do that ?

Body:
In order to change the type of a dataframe to string, you can use pandas astype:

reference_to_string = DataFrameComposants['Reference'].astype(str)

I am not entirely sure what you tried to do with your code...What is "Reference" in str(Reference) ?


问:
Access 2016 VBA code to export to Excel, 'could not find installable ISAM'
I have a database in Access with multiple tables. My end goal is to create a form with a button, that when pressed, runs a macro. This macro will run custom VBA code.

When run, I want the macro to create a new Excel workbook with one worksheet, and import one specific table into that worksheet.

Currently, this is my VBA code. I have literally 0 experience with VBA, so have no idea if this code will work or not. I found this code online as an answer to a question about a similar goal, and is not mine (Export MS Access tables through VBA to an excel spreadsheet in same directory)

```<code>Option Compare Database

Public Function exportToExcel()

Dim outputFileName As String
outputFileName = CurrentProject.Path & "\Export_" & Format(Date, "yyyyMMdd") & ".xlsx"

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel2Xml, "all_data", outputFileName, True

End Function
</code>```

I opened the VBA editor, created a new module called export module that is in the Modules folder in the navigator pane on the right side of the VBA editor window. The Option Compare Database bit was there already, and I typed the rest into this new module.

After saving the module, I created a new Macro, in which I have the RunCode command, and the Function field being =exportToExcel(). When I run the Macro, I get the error

```<code>Run-time error '3170':
Could not find installable ISAM.
</code>```

Does anyone know where this error is coming from, and how I fix it? Also would you be able to comment on my VBA code and tell me if anything is wrong and what I should change, or if I'm even going about automating an export to Excel in the correct way?

Thank you so much for your help.

答:
Did more digging an was able to find a solution if anybody finds this question in the future.

I don't know what the whole ISAM issue was, but this tutorial was critical to completing my desired task. I created a new module in the VBA editor, and wrote this code inside.

```<code>Sub exportToXL()

On Error GoTo ErrorHandler

Dim dbTable As String
Dim xlWorksheetPath As String

'<PATH> is the location you want the Excel file saved to, C:\ etc...
xlWorksheetPath = "<PATH>"

xlWorksheetPath = xlWorksheetPath & "xlExportAccessToExcel.xls"

'table1 is generic table name, this is the name of the table you want to export
dbTable = "table1"

DoCmd.TransferSpreadsheet transfertype:=acExport, spreadsheettype:=acSpreadsheetTypeExcel9, tablename:=dbTable, FileName:=xlWorksheetPath, hasfieldnames:=True

ErrorHandlerExit:

    Exit Sub

ErrorHandler:

    MsgBox "Error No: " & Err.Number & ";Description: " & Err.Description

    Resume ErrorHandlerExit

End Sub
</code>```

I ran this module straight from inside the VBA editor, navigated to the file location i specified, and found a new Excel workbook with the desired data inside!

Hope this helps somebody in the future.

Body:
I have a database in Access with multiple tables. My end goal is to create a form with a button, that when pressed, runs a macro. This macro will run custom VBA code.

When run, I want the macro to create a new Excel workbook with one worksheet, and import one specific table into that worksheet.

Currently, this is my VBA code. I have literally 0 experience with VBA, so have no idea if this code will work or not. I found this code online as an answer to a question about a similar goal, and is not mine (Export MS Access tables through VBA to an excel spreadsheet in same directory)

Option Compare Database

Public Function exportToExcel()

Dim outputFileName As String
outputFileName = CurrentProject.Path & "\Export_" & Format(Date, "yyyyMMdd") & ".xlsx"

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel2Xml, "all_data", outputFileName, True

End Function

I opened the VBA editor, created a new module called export module that is in the Modules folder in the navigator pane on the right side of the VBA editor window. The Option Compare Database bit was there already, and I typed the rest into this new module.

After saving the module, I created a new Macro, in which I have the RunCode command, and the Function field being =exportToExcel(). When I run the Macro, I get the error

Run-time error '3170':
Could not find installable ISAM.

Does anyone know where this error is coming from, and how I fix it? Also would you be able to comment on my VBA code and tell me if anything is wrong and what I should change, or if I'm even going about automating an export to Excel in the correct way?

Thank you so much for your help.

Body:
Did more digging an was able to find a solution if anybody finds this question in the future.

I don't know what the whole ISAM issue was, but this tutorial was critical to completing my desired task. I created a new module in the VBA editor, and wrote this code inside.

Sub exportToXL()

On Error GoTo ErrorHandler

Dim dbTable As String
Dim xlWorksheetPath As String

'<PATH> is the location you want the Excel file saved to, C:\ etc...
xlWorksheetPath = "<PATH>"

xlWorksheetPath = xlWorksheetPath & "xlExportAccessToExcel.xls"

'table1 is generic table name, this is the name of the table you want to export
dbTable = "table1"

DoCmd.TransferSpreadsheet transfertype:=acExport, spreadsheettype:=acSpreadsheetTypeExcel9, tablename:=dbTable, FileName:=xlWorksheetPath, hasfieldnames:=True

ErrorHandlerExit:

    Exit Sub

ErrorHandler:

    MsgBox "Error No: " & Err.Number & ";Description: " & Err.Description

    Resume ErrorHandlerExit

End Sub

I ran this module straight from inside the VBA editor, navigated to the file location i specified, and found a new Excel workbook with the desired data inside!

Hope this helps somebody in the future.


问:
how to remove xml namesapce with SAX parser
I need to do xml transformation with SAX parser, for that i need to remove namespace from the xml. Since we are handling with huge xml, i need to use SAX parser.

sample input xml:

```<code><root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope"
 xmlns:ns2="http://www.google.com/generation/type">
    <ns2:meta>
        <gender xmlns="" xmlns:ns5="http://www.google.com/generation">M</gender>
        <dateOfBirth xmlns="" xmlns:ns5="http://www.google.com/generation">1976-07-19</dateOfBirth>
        <ns2:languageRef>ENG</ns2:languageRef>
    </ns2:meta>
    <root>
</code>```

with the help of SAX parser, i need the below output.

```<code>       <root>
            <meta>
                <gender>M</gender>
                <dateOfBirth>1976-07-19</dateOfBirth>
                <languageRef>ENG</languageRef>
            </ns2:meta>
        <root>
</code>```

Thanks in advance..

The code which i tried,

i tried with XMLFlterImpl,

```<code>XMLReader xr = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) {

  @Override
  public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {

    if (qName.contains(":")) {
      String[] data = data = qName.split(":");

      super.startElement(uri, localName, data[1], atts);
    } else {
      super.startElement(uri, localName, qName, atts);
    }
  }
</code>```

this removes the element name prefix(namespace), but not sure how to remove the namespace attributes

答:
In this code:

```<code>super.startElement(uri, localName, data[1], atts);
</code>```

you are passing the original namespace URI unchanged to the output. You need to get rid of it, use:

```<code>super.startElement("", localName, data[1], atts);
</code>```

Body:
I need to do xml transformation with SAX parser, for that i need to remove namespace from the xml. Since we are handling with huge xml, i need to use SAX parser.

sample input xml:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope"
 xmlns:ns2="http://www.google.com/generation/type">
    <ns2:meta>
        <gender xmlns="" xmlns:ns5="http://www.google.com/generation">M</gender>
        <dateOfBirth xmlns="" xmlns:ns5="http://www.google.com/generation">1976-07-19</dateOfBirth>
        <ns2:languageRef>ENG</ns2:languageRef>
    </ns2:meta>
    <root>

with the help of SAX parser, i need the below output.

       <root>
            <meta>
                <gender>M</gender>
                <dateOfBirth>1976-07-19</dateOfBirth>
                <languageRef>ENG</languageRef>
            </ns2:meta>
        <root>

Thanks in advance..

The code which i tried,

i tried with XMLFlterImpl,

XMLReader xr = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) {

  @Override
  public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {

    if (qName.contains(":")) {
      String[] data = data = qName.split(":");

      super.startElement(uri, localName, data[1], atts);
    } else {
      super.startElement(uri, localName, qName, atts);
    }
  }

this removes the element name prefix(namespace), but not sure how to remove the namespace attributes

Body:
In this code:

super.startElement(uri, localName, data[1], atts);

you are passing the original namespace URI unchanged to the output. You need to get rid of it, use:

super.startElement("", localName, data[1], atts);


问:
the efficient and accurate way of parsing a web html to text field with formating?
i want to parse the web html to flex text field i have three approaches in mind to do soo

to use string function splice etc. to replace tags with the one which text fields can understand but is it too complex and processing over head is there that reduces the efficiency but i have max control to do changes what i needed.

parsing the html to xml and then use this as the text input to text field what about the efficiency and control need to know about from this question.

regular expressions .

which one will be the most suitable in paring the web text.

help required

regards.

答:
I'd suggest to completely change your approach. If you need a simple HTML to be displayed, then you can directly parse it by the flash/flex. In other cases, when you have a complex HTML page(s), then you should use IFrame. That's really simple and efficient approach and could be very useful in your case. Here you can find its description:
 Flex and Iframe,Flex Iframe Project site.

Good luck!


问:
ios - Error when hiding button through code Objective-c
I'm trying to hide a button through code, but the program crashes every time I try to hide it.

The error I get:

```<code>'NSInvalidArgumentException', reason: '-[UIBarButtonItem setHidden:]: unrecognized selector sent to instance 0x14ef8f30'
</code>```

.h file code:

```<code>@property (strong) UIButton *takeAll;
</code>```

.m code:

```<code>    @synthesize takeAll;

// function

   [self.takeAll setHidden:YES];
</code>```

答:
If you have subclass of UIView inside UIBarButtonItem you can hide it with this code`

[barButtonItem.customView setHidden:YES];

Body:
I'm trying to hide a button through code, but the program crashes every time I try to hide it.

The error I get:

'NSInvalidArgumentException', reason: '-[UIBarButtonItem setHidden:]: unrecognized selector sent to instance 0x14ef8f30'

.h file code:

@property (strong) UIButton *takeAll;

.m code:

    @synthesize takeAll;

// function

   [self.takeAll setHidden:YES];


问:
Monitor Spring Boot JMX with Zabbix
Spring Boot JMX values are Jsons like

```<code>{
    "mem": 986624,
    "mem.free": 933858,
    "processors": 8,
    "threads": 15,
    "threads.daemon": 11,
    "threads.peak": 15,
    "threads.totalStarted": 42,
    "uptime": 494836,
    "instance.uptime": 489782,
    "datasource.primary.active": 5,
    "datasource.primary.usage": 0.25
}
</code>```

How can I configure Zabbix to read and count, for example,  datasource.primary.usage? Is there any way of doing it except writing some complex script in Zabbix?

答: JSON parsing in item values is not currently supported in Zabbix. It is allegedly coming in Zabbix 3.4.</p>

Title: Monitor Spring Boot JMX with Zabbix

Body:
Spring Boot JMX values are Jsons like

{
    "mem": 986624,
    "mem.free": 933858,
    "processors": 8,
    "threads": 15,
    "threads.daemon": 11,
    "threads.peak": 15,
    "threads.totalStarted": 42,
    "uptime": 494836,
    "instance.uptime": 489782,
    "datasource.primary.active": 5,
    "datasource.primary.usage": 0.25
}

How can I configure Zabbix to read and count, for example,  datasource.primary.usage? Is there any way of doing it except writing some complex script in Zabbix?


问:
How to filter aggregate over the attributes of a subdocument?
I am currently using MongoDB as returner backend on SaltStack and I need to query the database, for example to get the list of the steps of a job that failed, each jobReturn is an object like this (here is a part of it):

```<code>{
    "_id" : ObjectId("595d12c99fee8e5d23f344a8"),
    "fun" : "state.apply",
    "jid" : "20170705162344866073",
    "return" : {
        "svn_|-Template tideway should have the revision HEAD active for the staging environment (Live)_|-http://svn-svc-xxx-es/staging/xxx-template-tideway/trunk_|-latest" : {
            "comment" : "Checked out revision 456.",
            "name" : "http://svn.svc.xxx.es/staging/xxx-template-tideway/trunk",
            "start_time" : "18:24:13.939000",
            "result" : true,
            "duration" : 752.0,
            "__run_num__" : 35,
            "changes" : {
                "new" : "http://svn.svc.xxx.es/staging/xxx-template-tideway/trunk",
                "revision" : "456\r"
            },
            "__id__" : "Template tideway should have the revision HEAD active for the staging environment (Live)"
        },
        "win_dacl_|-The application user should have full access to the application directories_|-C:\\inetpub\\wwwroot_|-present" : {
            "comment" : "",
            "name" : "C:\\inetpub\\wwwroot",
            "start_time" : "18:24:39.668000",
            "result" : true,
            "duration" : 7.0,
            "__run_num__" : 61,
            "changes" : {},
            "__id__" : "The application user should have full access to the application directories"
        },
        "svn_|-Template capucine should have the revision HEAD active for the staging environment (Live)_|-http://svn-svc-xxx-es/staging/xxx-template-capucine/trunk_|-latest" : {
            "comment" : "Checked out revision 456.",
            "name" : "http://svn.svc.xxx.es/staging/xxx-template-capucine/trunk",
            "start_time" : "18:24:07.544000",
            "result" : true,
            "duration" : 673.0,
            "__run_num__" : 23,
            "changes" : {
                "new" : "http://svn.svc.xxx.es/staging/xxx-template-capucine/trunk",
                "revision" : "456\r"
            },
            "__id__" : "Template capucine should have the revision HEAD active for the staging environment (Live)"
        },
        .....
    }
}
</code>```

Here for example, I need to get this object but with all the "return" objects that have "result": false

I tried to use $project but it's only working on list.

I can't modify the way the application is putting the data. I agree that a list of objects would have been a better solution in this schema.

What would be the best way to do this ?

答:
I found a solution using the $objectToArray expression in MongoDB 3.4.4+:

```<code>db.saltReturns.aggregate([
    { $match: { "fun": { $eq: "state.apply" }}},
    { $project: {
        matches: {
            $filter: {
                input: { $objectToArray: "$return" },
                as: "return",
                cond: { $eq: ["$$return.v.result", true] }
            }
        }
    }}
])
</code>```

Body:
I am currently using MongoDB as returner backend on SaltStack and I need to query the database, for example to get the list of the steps of a job that failed, each jobReturn is an object like this (here is a part of it):

{
    "_id" : ObjectId("595d12c99fee8e5d23f344a8"),
    "fun" : "state.apply",
    "jid" : "20170705162344866073",
    "return" : {
        "svn_|-Template tideway should have the revision HEAD active for the staging environment (Live)_|-http://svn-svc-xxx-es/staging/xxx-template-tideway/trunk_|-latest" : {
            "comment" : "Checked out revision 456.",
            "name" : "http://svn.svc.xxx.es/staging/xxx-template-tideway/trunk",
            "start_time" : "18:24:13.939000",
            "result" : true,
            "duration" : 752.0,
            "__run_num__" : 35,
            "changes" : {
                "new" : "http://svn.svc.xxx.es/staging/xxx-template-tideway/trunk",
                "revision" : "456\r"
            },
            "__id__" : "Template tideway should have the revision HEAD active for the staging environment (Live)"
        },
        "win_dacl_|-The application user should have full access to the application directories_|-C:\\inetpub\\wwwroot_|-present" : {
            "comment" : "",
            "name" : "C:\\inetpub\\wwwroot",
            "start_time" : "18:24:39.668000",
            "result" : true,
            "duration" : 7.0,
            "__run_num__" : 61,
            "changes" : {},
            "__id__" : "The application user should have full access to the application directories"
        },
        "svn_|-Template capucine should have the revision HEAD active for the staging environment (Live)_|-http://svn-svc-xxx-es/staging/xxx-template-capucine/trunk_|-latest" : {
            "comment" : "Checked out revision 456.",
            "name" : "http://svn.svc.xxx.es/staging/xxx-template-capucine/trunk",
            "start_time" : "18:24:07.544000",
            "result" : true,
            "duration" : 673.0,
            "__run_num__" : 23,
            "changes" : {
                "new" : "http://svn.svc.xxx.es/staging/xxx-template-capucine/trunk",
                "revision" : "456\r"
            },
            "__id__" : "Template capucine should have the revision HEAD active for the staging environment (Live)"
        },
        .....
    }
}

Here for example, I need to get this object but with all the "return" objects that have "result": false

I tried to use $project but it's only working on list.

I can't modify the way the application is putting the data. I agree that a list of objects would have been a better solution in this schema.

What would be the best way to do this ?

Body:
I found a solution using the $objectToArray expression in MongoDB 3.4.4+:

db.saltReturns.aggregate([
    { $match: { "fun": { $eq: "state.apply" }}},
    { $project: {
        matches: {
            $filter: {
                input: { $objectToArray: "$return" },
                as: "return",
                cond: { $eq: ["$$return.v.result", true] }
            }
        }
    }}
])


问:
Overlay HTML radio button on video
I would like to overlay HTML radio buttons on top of a video such that you can select them. I know the coordinates of the pixels for each of the coloured box if that helps. Like in the example below, the black circles would represent the radio buttons that I can click. How do I format it using CSS?

```<code><style>
  #container {
      width: 428px;
      height: 200px;
      position: relative;
  }

  #overlay {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 50px;
      left: 50px;
      color: red;
      font-size: 40px;
      z-index: 10;
  }

  #base {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0px;
      left: 0px;
  }
</style>
  </head>
  <body>
    <div id="container">
      <div id="overlay">
        <form action="">
          <input type="radio" name="white" value="1" />
          <input type="radio" name="white" value="2" />
          <input type="radio" name="white" value="3" />
          <input type="radio" name="white" value="4" />
          <input type="button" id="continue" value="Continue"/>
        </form>
      </div>
      <div id="base">
        <video controls>
          <source src="videos/event_0_Junli_Standing_20150322_181647_00_0.6.mp4" type="video/mp4">
          Your browser does not support the video tag.
        </video>
      </div>
    </div>
  </body>
</code>```

答:
My best bet would just be to have the radio buttons in position: absolute and move them over the video with top: and right:.

JSfiddle demo

Title: Overlay HTML radio button on video

Body:
I would like to overlay HTML radio buttons on top of a video such that you can select them. I know the coordinates of the pixels for each of the coloured box if that helps. Like in the example below, the black circles would represent the radio buttons that I can click. How do I format it using CSS?

        <form action="">
          <input type="radio" name="white" value="1" />
          <input type="radio" name="white" value="2" />
          <input type="radio" name="white" value="3" />
          <input type="radio" name="white" value="4" />
          <input type="button" id="continue" value="Continue"/>
        </form>

        <video controls>
          <source src="videos/event_0_Junli_Standing_20150322_181647_00_0.6.mp4" type="video/mp4">
          Your browser does not support the video tag.
        </video>


问:
Ruby - Filtering array of hashes based on another array
I am trying to filter an array of hashes based on another array. What's the best way to accomplish this? Here are the 2 brutes I've right now:

```<code>x=[1,2,3]
y = [{dis:4,as:"hi"},{dis:2,as:"li"}]

1) aa = []
x.each do |a|
  qq = y.select{|k,v| k[:dis]==a}
  aa+=qq unless qq.empty?
end

2) q = []
y.each do |k,v|
  x.each do |ele|
    if k[:dis]==ele
      q << {dis: ele,as: k[:as]}
    end
  end
end
</code>```

Here's the output I'm intending:

[{dis:2,as:"li"}]

答:
Yes use select, nonetheless here's another way which works:

```<code>y.each_with_object([]) { |hash,obj| obj << hash if x.include? hash[:dis] }
</code>```

Body:
I am trying to filter an array of hashes based on another array. What's the best way to accomplish this? Here are the 2 brutes I've right now:

x=[1,2,3]
y = [{dis:4,as:"hi"},{dis:2,as:"li"}]

1) aa = []
x.each do |a|
  qq = y.select{|k,v| k[:dis]==a}
  aa+=qq unless qq.empty?
end

2) q = []
y.each do |k,v|
  x.each do |ele|
    if k[:dis]==ele
      q << {dis: ele,as: k[:as]}
    end
  end
end

Here's the output I'm intending:

[{dis:2,as:"li"}]

Body:
Yes use select, nonetheless here's another way which works:

y.each_with_object([]) { |hash,obj| obj << hash if x.include? hash[:dis] }


问:
How to find matplotlib style name?
Is it possible to know the name of the current matplotlib style? I know that I can get the list of all available styles using plt.style.available, but what I want is the possibility of getting the name of the style currently in use. I am working in the ipython console of spyder, python 3.5, but I would be surprised if answer to this would depend on my working environment :)

答:
Looking at the source of plt.style.use, I don't see any signs that using a new style does anything to store the name of the style being used.

I thought about manually checking the current rcParams against every available style, something like this:

```<code>import matplotlib.pyplot as plt

for style in plt.style.available:
    for key in plt.style.library[style]:
        if plt.rcParams[key] != plt.style.library[style][key]:
            break
    else:
        print('Current style is consistent with {}.'.format(style))
</code>```

But none of the available styles matched for my default style. Then I also printed the reasons for mismatch:

```<code>for style in plt.style.available:
    for key in plt.style.library[style]:
        val_now,val_style = plt.rcParams[key],plt.style.library[style][key]
        if val_now != val_style:
            print('Discarding style {}: {} vs {} for key {}'.format(style,val_now,val_style,key))
            break
    else:
        print('Current style is consistent with {}.'.format(style))
</code>```

Part of the output:

Discarding style seaborn-paper: 0.6 vs 0.4 for key xtick.minor.width
Discarding style seaborn-whitegrid: w vs white for key figure.facecolor
Discarding style seaborn-talk: 0.8 vs 1.3 for key grid.linewidth
```

<p>Note the second item: <code>w</code> vs <code>white</code>. Now this is a problem. Named colors don't easily test as equal with the same color by different names or RGBA values etc.</p>

<p>I then thought about converting every color using <code>matplotlib.colors.to_rgba()</code>, but if you want to do it properly, you need to fully parse the parameters, including gems like this:</p>

<pre class="lang-none prettyprint-override"><code>Discarding style grayscale: figure.facecolor,w vs figure.facecolor,0.75
</code>```

Even if the latter value corresponded to white, we'd need to parse that value first and find the color buried inside.

To me it seems that the only safe implementation would be to make plt.style.use store the name of the style somewhere. But then what happens if anything in the rcParams is changed manually? Then there won't be a style which is currently loaded. This is then a counterargument against storing the style name. Whenever the params were changed, there would have to be a check that invalidates the last plt.style.use call's style name. I'm not sure there's an obvious solution to your problem.

Title: How to find matplotlib style name?

Body:
Looking at the source of plt.style.use, I don't see any signs that using a new style does anything to store the name of the style being used.

I thought about manually checking the current rcParams against every available style, something like this:

import matplotlib.pyplot as plt

for style in plt.style.available:
    for key in plt.style.library[style]:
        if plt.rcParams[key] != plt.style.library[style][key]:
            break
    else:
        print('Current style is consistent with {}.'.format(style))

But none of the available styles matched for my default style. Then I also printed the reasons for mismatch:

for style in plt.style.available:
    for key in plt.style.library[style]:
        val_now,val_style = plt.rcParams[key],plt.style.library[style][key]
        if val_now != val_style:
            print('Discarding style {}: {} vs {} for key {}'.format(style,val_now,val_style,key))
            break
    else:
        print('Current style is consistent with {}.'.format(style))

Part of the output:

Discarding style seaborn-paper: 0.6 vs 0.4 for key xtick.minor.width
Discarding style seaborn-whitegrid: w vs white for key figure.facecolor
Discarding style seaborn-talk: 0.8 vs 1.3 for key grid.linewidth

Note the second item: w vs white. Now this is a problem. Named colors don't easily test as equal with the same color by different names or RGBA values etc.

I then thought about converting every color using matplotlib.colors.to_rgba(), but if you want to do it properly, you need to fully parse the parameters, including gems like this:

Discarding style grayscale: figure.facecolor,w vs figure.facecolor,0.75

Even if the latter value corresponded to white, we'd need to parse that value first and find the color buried inside.

To me it seems that the only safe implementation would be to make plt.style.use store the name of the style somewhere. But then what happens if anything in the rcParams is changed manually? Then there won't be a style which is currently loaded. This is then a counterargument against storing the style name. Whenever the params were changed, there would have to be a check that invalidates the last plt.style.use call's style name. I'm not sure there's an obvious solution to your problem.