title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Python regular expression for | 38,786,432 | <p>What would be the regular expression for such data</p>
<pre><code>/home//Desktop/3A5F.py
path/sth/R67G.py
a/b/c/d/t/6UY7.py
</code></pre>
<p>i would like to get these</p>
<pre><code>3A5F.py
R67G.py
6UY7.py
</code></pre>
| -2 | 2016-08-05T09:57:24Z | 38,786,553 | <p>It looks like you're parsing paths, in which case you should really be using <a href="https://docs.python.org/3/library/os.path.html#os.path.basename" rel="nofollow"><code>os.path</code></a> instead of regex:</p>
<pre><code>from os.path import basename
basename('/home//Desktop/3A5F.py')
# 3A5F.py
</code></pre>
| 2 | 2016-08-05T10:03:54Z | [
"python",
"regex"
] |
Python regular expression for | 38,786,432 | <p>What would be the regular expression for such data</p>
<pre><code>/home//Desktop/3A5F.py
path/sth/R67G.py
a/b/c/d/t/6UY7.py
</code></pre>
<p>i would like to get these</p>
<pre><code>3A5F.py
R67G.py
6UY7.py
</code></pre>
| -2 | 2016-08-05T09:57:24Z | 38,786,751 | <p>You can use this.</p>
<pre><code>pattern = ".*/(.*$)"
mystring = "/home//Desktop/3A5F.py"
re.findall(pattern, mystring)
</code></pre>
<p>You can also use <code>os.path.split(mystring)</code></p>
| 0 | 2016-08-05T10:15:20Z | [
"python",
"regex"
] |
Django Error: Your URL pattern is invalid. Ensure that urlpatterns is a list of url() instances | 38,786,461 | <p>After upgrading to Django 1.10, I get the following error when I run <code>python manage.py runserver</code>:</p>
<pre><code>?: (urls.E004) Your URL pattern ('^$', 'myapp.views.home') is invalid. Ensure that urlpatterns is a list of url() instances.
HINT: Try using url() instead of a tuple.
</code></pre>
<p>My <code>urlpatterns</code> are as follows:</p>
<pre><code>from myapp.views import home
urlpatterns = [
(r'^$', home, name='home'),
]
</code></pre>
| 1 | 2016-08-05T09:59:01Z | 38,786,462 | <p>To simplify URL configs, <code>patterns()</code> was deprecated in Django 1.8, and removed in 1.10 (<a href="https://docs.djangoproject.com/en/1.10/releases/1.10/#features-removed-in-1-10" rel="nofollow">release notes</a>). In Django 1.10, <code>urlpatterns</code> must be a list of <code>url()</code> instances. Using a tuple in <code>patterns()</code> is not supported any more, and the Django checks framework will raise an error. </p>
<p>Fixing this is easy, just convert any tuples</p>
<pre><code>urlpatterns = [
(r'^$', home, name='home'), # tuple
]
</code></pre>
<p>to <code>url()</code> instances:</p>
<pre><code>urlpatterns = [
url(r'^$', home, name='home'), # url instance
]
</code></pre>
<p>If you get the following <code>NameError</code>,</p>
<pre><code>NameError: name 'url' is not defined
</code></pre>
<p>then add the following import to your <code>urls.py</code>:</p>
<pre><code>from django.conf.urls import url
</code></pre>
<p>If you use strings in your url patterns, e.g. <code>'myapp.views.home'</code>, you'll have to update these to use a callable at the same time. See <a href="http://stackoverflow.com/questions/38744285/django-urls-error-view-must-be-a-callable-or-a-list-tuple-in-the-case-of-includ">this answer</a> for more info.</p>
<p>See the <a href="https://docs.djangoproject.com/en/1.10/topics/http/urls/#url-dispatcher" rel="nofollow">Django URL dispatcher docs</a> for more information about <code>urlpatterns</code>.</p>
| 3 | 2016-08-05T09:59:01Z | [
"python",
"django",
"django-1.10"
] |
Python3 setuptools bidst_rpm : remove /usr/lib/python3.x/site-packages prefix. Adapt rpm install directory to client machine's python path | 38,786,627 | <p>I'm currently trying to create a rpm distribution of a python project I've been working on. I'm using setuptools 25.1.4 on a Fedora 24 and using python3.4. </p>
<p>I can generate my rpm distribution by using :</p>
<pre><code>python3 setup.py bdist_rpm
</code></pre>
<p>And here is a look at my setup.cfg file : </p>
<pre><code> [bdist_rpm]
no-autoreq=1
requires = python3 >= 3.4
mariadb
mariadb-server
mariadb-devel
mysql-connector-python3
redhat-rpm-config
libffi-devel
libffi
libxml2
libxml2-devel
libxslt-devel
</code></pre>
<p>This generates a myproject-1.0.0-1.noarch.rpm file in my dist folder. The rpm distribution has been created using python3.4. </p>
<p>I wish to pass on my rpm file from my host machine to my client machine. I achieve that by doing a simple scp command. Once I'm on my client machine I usually do a sequence of : </p>
<pre><code>dnf install myproject-1.0.0-1.noarch.rpm
rpm -Uvh myproject-1.0.0-1.noarch.rpm
</code></pre>
<p>Which resolves dependency issues and specifies that my package has been installed.
Now my problem comes from where the package is actually installed on my client machine : </p>
<pre><code>/usr/lib/python3.4/site-packages`
</code></pre>
<p>This "path" is generated by the following tar file that setup.py creates and uses to build the rpm distribution : </p>
<blockquote>
<p>myproject-1.0.0.linux-x86_64.tar.gz </p>
</blockquote>
<p>When I untar it , it creates a folder copying the path from my host machine /usr/lib/python3.4/site-packages/my-project/...</p>
<p>This is probably due to the fact that I ran setup.py on my host machine using python3.4</p>
<p>My client machine has python3.5 installed on it by default (thank you Fedora 24)</p>
<p>Of course I could solve this problem by simply executing setup.py using python3.5 on my host machine, but that would be a nasty and unsatisfying fix to my problem.</p>
<p>Now how do I customize this part of setuptools. What I wish to achieve is once the client machine tries to install my rpm , it installs my python project package to the right path of the client machine's python path. </p>
<p>The best situation would be to actually remove the /usr/bin/python3.4/site-packages/ prefix and have it replaced with something as simple as /my-project/ and then once I'm on my client machine put /my-project/ in whatever path the client machine's python active interpretor uses.</p>
<p>I know that the prefix issue has already been addressed at : <a href="http://stackoverflow.com/questions/36333888/setuptools-remove-lib-python3-5-site-packages-prefix-from-zip">setuptools: remove lib/python3.5/site-packages prefix from zip</a> but OP's solution does not work for me.</p>
<p>I'm fairly new here so please point out if I didn't supply enough information.</p>
<p><strong>SOLVED</strong>
I stumbled upon <a href="http://stackoverflow.com/questions/7354096/override-default-installation-directory-for-python-bdist-windows-installer">Override default installation directory for Python bdist Windows installer</a></p>
<p>It worked like a charm adding :</p>
<pre><code>[install]
prefix=/
install_lib=/some/lib/path
install_scripts=/some/bin/path
</code></pre>
<p>to my setup.cfg</p>
| 0 | 2016-08-05T10:08:03Z | 38,806,974 | <p>When you run <code>bdist_rpm</code> it will also create src.rpm. With this file run:</p>
<pre><code>mock -r fedora-24-x86_64 myproject.src.rpm
</code></pre>
<p>It will create fedora-24-x86_64 environment in chroot and build your package there. With correct paths for Fedora 24.</p>
| 0 | 2016-08-06T17:30:40Z | [
"python",
"python-3.x",
"fedora",
"rpm",
"setuptools"
] |
Sequence index plot python | 38,786,935 | <p>I am trying to plot the sequence of a set of time sorted values, in which each value is represented by a different colour. For instance, if my values are like </p>
<pre><code>state_seq = [2, 2, 2, 2, 0, 0, 0, 1, 3, 6, 3, 3, 3, 0, 0]
time_seq = ['2013-05-29 09:31:00', '2013-05-29 09:46:00', '2013-07-23 12:28:00', '2013-07-23 01:53:00', '2013-08-05 02:02:00', '2013-08-05 02:08:00', '2013-08-05 04:28:00', '2013-08-06 10:20:00', '2013-08-06 03:03:00', '2013-08-06 04:13:00', '2013-08-06 04:17:00', '2013-08-06 04:36:00', '2013-08-07 11:07:00', '2013-08-07 12:28:00', '2013-08-07 12:31:00']
</code></pre>
<p>I want each unique element of state_seq to be represented with a colour and plot the sequence. As of now, I am using seaborn palplot to get this done in a trivial way as, </p>
<pre><code>color_set = ["#95a5a6", "#34495e","#9b59b6", "#3498db", "#800000", "#2ecc71", 'y', '#FF4500']
palette = list()
for s in state_seq:
palette.append(color_set[s])
sns.palplot(palette)
</code></pre>
<p>Which gives me something like this (this output may not exactly match with the code snippet - I edited the code for better clarity)
<a href="http://i.stack.imgur.com/sAUyW.png" rel="nofollow"><img src="http://i.stack.imgur.com/sAUyW.png" alt="Sequence from seaborn pal plot"></a></p>
<p>This approach has a setback that I can not represent my time labels in x-axis. Is there a better python alternative perhaps similar to the R-package TraMineR explained here <a href="http://stackoverflow.com/questions/28700002/is-it-possible-to-make-a-graph-with-pattern-fills-using-traminer-and-r-base-grap">Is it possible to make a graph with pattern fills using TraMineR and R base graphs?</a></p>
| 0 | 2016-08-05T10:24:54Z | 38,789,856 | <p>I assume you want square boxes for each value, regardless of the time gap between each. To have a width indicative of the time gap you could <a href="http://stackoverflow.com/questions/466345/converting-string-into-datetime">convert <code>time_seq</code> to datetime objects</a> and then plot the dates directly with matplotlib.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
state_seq = [2, 2, 2, 2, 0, 0, 0, 1, 3, 6, 3, 3, 3, 0, 0]
time_seq = ['2013-05-29 09:31:00', '2013-05-29 09:46:00', '2013-07-23 12:28:00', '2013-07-23 01:53:00', '2013-08-05 02:02:00', '2013-08-05 02:08:00', '2013-08-05 04:28:00', '2013-08-06 10:20:00', '2013-08-06 03:03:00', '2013-08-06 04:13:00', '2013-08-06 04:17:00', '2013-08-06 04:36:00', '2013-08-07 11:07:00', '2013-08-07 12:28:00', '2013-08-07 12:31:00']
color_set = ["#95a5a6", "#34495e","#9b59b6", "#3498db", "#800000", "#2ecc71", 'y', '#FF4500']
for i in range(len(time_seq)):
# fill the yaxis with our colour for each time_seq entry for width 1
plt.fill_between((i,i+1), 1, color=color_set[state_seq[i]])
# keep the coloured boxes square
plt.axis("scaled")
plt.xlim(0, len(time_seq))
plt.axes().get_yaxis().set_visible(False)
# add custom tick labels based on time_seq and set to middle of boxes
plt.xticks(np.arange(0.5,len(time_seq)+0.5, 1), time_seq, rotation='vertical')
# remove xaxis ticks
plt.axes().get_xaxis().set_ticks_position("none")
plt.savefig("boxes.png", bbox_inches="tight")
</code></pre>
<p>Produces:
<a href="http://i.stack.imgur.com/OFKWY.png" rel="nofollow"><img src="http://i.stack.imgur.com/OFKWY.png" alt="enter image description here"></a></p>
| 1 | 2016-08-05T12:58:19Z | [
"python",
"matplotlib",
"seaborn"
] |
Pandas: convert unicode strings to string | 38,786,936 | <p>I have data frame and there are 2 columns with unicode value. I need to convert it to string. I try <code>df.domain.astype(str)</code> but it return unicode strings.
How can I do that?
Data looks like (I need to convert either columns)</p>
<pre><code>domain search_term
vk.com None
facebook.com None
yandex.ru ÑнÑÑÑ ÐºÐ²Ð°ÑÑиÑÑ
locals.ru None
yandex.ru ÑнÑÑÑ ÐºÐ²Ð°ÑÑиÑÑ Ð±ÐµÐ· поÑÑедников в ÐоÑкве
avito.ru None
</code></pre>
| 0 | 2016-08-05T10:25:00Z | 38,787,953 | <p>Would this help?:</p>
<pre><code>for col in types[types=='unicode'].index:
df[col] = df[col].astype(str)
</code></pre>
<p>or:</p>
<pre><code>for col in types[types=='unicode'].index:
df[col] = df[col].apply(lambda x: x.encode('utf-8').strip())
</code></pre>
| 0 | 2016-08-05T11:18:25Z | [
"python",
"pandas"
] |
Run multiple different flask apps with manage.py (flask-script) | 38,787,022 | <p>I have a Flask app set up so it can run two different sites (the sites share businesslogic and database models, so they use the same back end). One is just the regular website, the other is a site that runs tasks (it's a web interface for shooting long running tasks into celery)</p>
<p>The app currently uses Flask-Script (the manage.py command) to start the regular website, but I'd like to use the same script to start the task-site aswell.</p>
<p>In Flask-Script it seems all commands are processes run on a single app. Is it possible to have manage.py start two different apps?</p>
<p>My code is now as follows, where <strong><em>create_app</em></strong> is the factory function for creating the Flask app for the website, and <strong><em>taskserver</em></strong> is the factory function for creating the taskserver website.</p>
<pre><code>import os
from flask_script import Manager
from app import create_app, database, taskserver
if os.getenv('FLASK_CONFIG'):
app = create_app(os.getenv('FLASK_CONFIG'))
manager = Manager(app)
else:
app = create_app
manager = Manager(app)
manager.add_option('-c', '--config_name', dest='config_name', required=False)
@manager.shell
def make_shell_context():
from app.models.data import base_models
return dict(app=app, db=database, models=base_models)
if __name__ == "__main__":
manager.run()
</code></pre>
<p>I hope someone knows how to adapt the manage.py script to be able to start either one.</p>
<p><strong>UPDATE:</strong> </p>
<p>Thanks to @Joro Tenev, the problem is solved.
The code I used eventually is:</p>
<pre><code>import os
from flask_script import Manager
from app import create_website, create_taskserver
def make_app(app_type, config_name):
if os.getenv('FLASK_CONFIG'):
config_name = os.getenv('FLASK_CONFIG')
if app_type == 'webserver':
return create_website(config_name)
else:
return create_taskserver(config_name) # i don't know how your factory works, so adjust accordingly
manager = Manager(make_app)
manager.add_option('-a', '--app_type', dest='app_type', required=True)
manager.add_option('-c', '--config_name', dest='config_name', required=False)
</code></pre>
<p>And to start the different apps, I use:</p>
<pre><code>python manage.py --app_type=webserver --config_name=development runserver
python manage.py --app_type=taskserver --config_name=development runserver
</code></pre>
| 0 | 2016-08-05T10:29:17Z | 38,814,568 | <p>You can pass a function to the constructor of Manager. The function should return a Flask app. You can also pass parameters to the function by using the <code>manager.add_option</code> </p>
<pre><code>manager.add_option('-a','--app_type', dest='app_type',required=True)
def make_app(app_type):
if app_type =='webserver':
return create_app(os.getenv('FLASK_CONFIG'))
elif:
return taskserver(os.getenv('FLASK_CONFIG')) # i don't know how your factory works, so adjust accordingly
manager = Manager(make_app)
</code></pre>
<p>And you'll use it with</p>
<pre><code>$ python manage.py --app_type='webserver'
</code></pre>
<p>Hope this helps :)</p>
| 1 | 2016-08-07T13:21:00Z | [
"python",
"flask",
"flask-script"
] |
Error with json VirusTotal API call in python | 38,787,051 | <p>I need to retrieve the result of VirusTotal scans already performed, providing the hash of the files, without sending the file again.
You can find the documentation of the API <a href="https://www.virustotal.com/it/documentation/public-api/" rel="nofollow">here</a>.</p>
<p>I basically need to send a json of this format: <code>{"resource": "hash", "apikey": api}</code>.
I'm using <strong>requests</strong>, it's very useful and it should handle json even without using the <strong>json</strong> or <strong>simplejson</strong> module.</p>
<p>if I send a request like this it works:</p>
<pre><code>r = requests.post(url, data = {"resource": "dbbe9c39df7c355f970e3a9636fbac04" , "apikey": "myapikey"}
print(r.json())
</code></pre>
<p>but I have many hashes so I need to generate the json programmatically instead of hardcoding it in the program.</p>
<p>First I tried using a dictionary:
the <strong>api</strong> key doesn't change so I put the assignment out of the loop, instead for the <strong>hash</strong> I loop through a <strong>list</strong> of hashes called <strong>md5</strong>.</p>
<pre><code>params = {}
params["apikey"] = api
for hash in md5:
params["resource"] = hash
</code></pre>
<p>I get a dictionary for every loop that I pass to <strong>requests</strong> for the API call.
The dictionary representing the json is of this format:</p>
<pre><code>{'apikey': myapikey', 'resource': 'hash'}
</code></pre>
<p>The documentation shows <code>resource</code> as first element of the json, instead in my generated dictionary I get the <code>apikey</code> first, anyway if they implement correctly the json standard, order shouldn't matter. Anyway that isn't a valid json format because it contains single quotes, it should contain double quotes. I wanted to avoid using another module but I tried using <code>json</code> or <code>simplejson</code> module for converting the dictionary in a valid json (with double quotes) and it works apparently. I know that requests also has a <code>json =</code> paramenter where you can pass a dictionary and it should encode it as json for you but I'm not sure it worked. Otherwise you can just use the <code>data =</code> paramenter and assign the json to it when you make the request.</p>
<p>If I make a request like this:</p>
<pre><code>params = {}
params["apikey"] = api
for hash in md5:
params["resource"] = hash
json_params = json.dumps(params)
r = requests.post(url, data = json_params)
print(r.json())
</code></pre>
<p>I get this error: </p>
<pre><code>Traceback (most recent call last):
File "C:/Users/Fabio/PycharmProjects/dfir/requests-try-prova.py", line 15, in <module>
print(r.json())
File "C:\Users\Fabio\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\models.py", line 812, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Users\Fabio\AppData\Local\Programs\Python\Python35\lib\site-packages\simplejson\__init__.py", line 516, in loads
return _default_decoder.decode(s)
File "C:\Users\Fabio\AppData\Local\Programs\Python\Python35\lib\site-packages\simplejson\decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "C:\Users\Fabio\AppData\Local\Programs\Python\Python35\lib\site-packages\simplejson\decoder.py", line 400, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code></pre>
<p>line 15 in my code is represented by <code>print(r.json())</code></p>
<p>if I <code>print(r.text())</code> instead it says <code>TypeError: 'str' object is not callable</code></p>
<hr>
<p>Then I tried a slightly different approach still using the <code>json</code> module without passing a pre-defined dictionary:</p>
<pre><code>for hash in md5:
r = requests.post(url, data = json.dumps({"resource": hash, "apikey": api}))
print(r.json())
</code></pre>
<p>where <code>hash</code> and <code>api</code> are 2 strings.</p>
<p>I still get the same error:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/Fabio/PycharmProjects/dfir/requests-try-prova.py", line 15, in <module>
print(r.json())
File "C:\Users\Fabio\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\models.py", line 812, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Users\Fabio\AppData\Local\Programs\Python\Python35\lib\site-packages\simplejson\__init__.py", line 516, in loads
return _default_decoder.decode(s)
File "C:\Users\Fabio\AppData\Local\Programs\Python\Python35\lib\site-packages\simplejson\decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "C:\Users\Fabio\AppData\Local\Programs\Python\Python35\lib\site-packages\simplejson\decoder.py", line 400, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code></pre>
<p>From the error it seems the problem is in getting or decoding the json response, but I wonder if the problem is that the request isn't sent correctly in the first place.
If instead of printing the json response I do <code>print(r.status_code())</code> I get a <strong>403</strong> status.</p>
<p>It's a typical HTTP status that means "<code>Forbidden</code>" and also the Virus Total API documentation says: <code>If you try to perform calls to functions for which you do not have the required privileges an HTTP Error 403 Forbidden is raised</code>.</p>
| 1 | 2016-08-05T10:31:09Z | 38,800,086 | <p>I noticed that I used a variable called <code>hash</code> and it could cause an issue because it can be mistaken with a method by the Python interpreter so I renamed it to <code>file_hash</code>. Then instead of using <code>r.json</code> I used <code>r.text</code> for getting the response as text and then I passed it as a argument to the function <code>json.loads</code>, I stored the value in a variable called <code>response</code>. <code>response</code> is a dictionary and it contains keys and values wrapped by <strong>single quotes</strong> rather than double quotes like in a valid json, so I had to take this into account when I wanted to extract the values from the response. I don't get any error now, code runs. The only issue is that after a few retrieved jsons (precisely 4), I got the same error as before: <code>simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)</code>
This is probably because I wasn't getting a json response anymore. If you are asking why, it's because the public API supports only up to <strong>4 requests/minute</strong>, so I had to implement a sleep function in order to pause the report retrieval for 1 minute every 4 requests. (I was aware of this since the beginning). I implemented several other checks and functions in my code, anyway I show you the basic code that works:</p>
<pre><code> for file_hash in md5:
params = {"apikey": api, "resource": file_hash}
r = requests.post(url, data=params)
report = json.loads(r.text)
print(report)
</code></pre>
| 1 | 2016-08-06T02:48:58Z | [
"python",
"json",
"python-requests"
] |
Base.py: Unicode equal comparison failed to convert both arguments to Unicode in | 38,787,173 | <p>I was taking a look to a couple of related questions which treats about the same issue, but I still don't find a way to solve it.</p>
<p>It turns out that every time I execute a Django-related command, it prints me out the expected output plus something like this:</p>
<pre><code>/Library/Python/2.7/site-packages/django/db/backends/sqlite3/base.py:307: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
return name == ":memory:" or "mode=memory" in force_text(name)
</code></pre>
<p>And here is the context of that line:</p>
<pre><code>def is_in_memory_db(self, name):
return name == ":memory:" or "mode=memory" in force_text(name)
</code></pre>
<p>Despite the Django server works, it's kind of annoying having always this message printed out on my screen. So, why is this happening and how could this be solved?</p>
| 1 | 2016-08-05T10:37:34Z | 38,787,241 | <p>use <a href="https://docs.python.org/2/library/stdtypes.html#str.decode" rel="nofollow">decode('utf-8')</a> to make correct comparing:</p>
<pre><code>name.decode('utf-8') == ":memory:" or "mode=memory" in force_text(name)
</code></pre>
<p>Use full info:</p>
<p><a href="https://docs.python.org/2.7/howto/unicode.html" rel="nofollow">Unicode HOWTO</a></p>
<p><a href="https://www.azavea.com/blog/2014/03/24/solving-unicode-problems-in-python-2-7/" rel="nofollow">Solving Unicode Problems in Python 2.7</a></p>
| 1 | 2016-08-05T10:40:29Z | [
"python",
"django",
"unicode"
] |
Substitue extra double quotes in a single CSV fields via bash | 38,787,354 | <p>I need to substitute extra double quotes from CSV log files (fields are comma separated and quoted by double-quotes). The substitution must impact only the last field of CSV.</p>
<p>Input log file example:</p>
<pre><code>"24-12-2015","23:07:08","00","01","00","00","START","00","END","JS786JGDG7899JSGJHG"dsdajasghsahd"
</code></pre>
<p>Expected output:</p>
<pre><code>"24-12-2015","23:07:08","00","01","00","00","START","00","END","JS786JGDG7899JSGJHG''dsdajasghsahd"
</code></pre>
<p>I need to complete this task in bash or python.</p>
| 1 | 2016-08-05T10:46:27Z | 38,787,430 | <p>You can use awk:</p>
<pre><code>awk "{gsub(/'/, \"''\", \$NF)} 1" file.csv
"24-12-2015","23:07:08","00","01","00","00","START","00","END","JS786JGDG7899JSGJHG''dsdajasghsahd"
</code></pre>
| 1 | 2016-08-05T10:50:22Z | [
"python",
"bash",
"csv"
] |
Substitue extra double quotes in a single CSV fields via bash | 38,787,354 | <p>I need to substitute extra double quotes from CSV log files (fields are comma separated and quoted by double-quotes). The substitution must impact only the last field of CSV.</p>
<p>Input log file example:</p>
<pre><code>"24-12-2015","23:07:08","00","01","00","00","START","00","END","JS786JGDG7899JSGJHG"dsdajasghsahd"
</code></pre>
<p>Expected output:</p>
<pre><code>"24-12-2015","23:07:08","00","01","00","00","START","00","END","JS786JGDG7899JSGJHG''dsdajasghsahd"
</code></pre>
<p>I need to complete this task in bash or python.</p>
| 1 | 2016-08-05T10:46:27Z | 38,787,575 | <p>try this; </p>
<pre><code>awk -F, -v OFS="," '{gsub(/\"/,"\47\47",$NF)gsub(/^\47\47/,"\"",$NF);gsub(/\047\047$/,"\"",$NF) }1' file
"24-12-2015","23:07:08","00","01","00","00","START","00","END","JS786JGDG7899JSGJHG''dsdajasghsahd"
</code></pre>
| 0 | 2016-08-05T10:57:40Z | [
"python",
"bash",
"csv"
] |
Define Each New Line As a Variable | 38,787,578 | <p>I have a text file that has many lines of data. I would like to setup a loop that reads each line of data and then defines that line/data as a new variable to be used in my python script.'</p>
<p><strong>File Example:</strong></p>
<pre><code>1
2
3
4
5
6
7
8
9
</code></pre>
<p><strong>Python Script (so far...):</strong></p>
<pre><code>#!/usr/bin/python
f = open('/home/weather/test', 'r')
for line in f.read().split('\n'):
print line
f.close()
</code></pre>
| -2 | 2016-08-05T10:57:56Z | 38,787,649 | <p>You have to create a <code>List</code> and append the variables to it like this</p>
<pre><code>#!/usr/bin/python
f = open('/home/weather/test', 'r')
variables=[]
for line in f.readlines():
variables.append(line)
f.close()
</code></pre>
<p><a href="http://www.tutorialspoint.com/python/python_lists.htm" rel="nofollow">Here</a> is a good tutorial about lists</p>
| 1 | 2016-08-05T11:02:05Z | [
"python"
] |
Define Each New Line As a Variable | 38,787,578 | <p>I have a text file that has many lines of data. I would like to setup a loop that reads each line of data and then defines that line/data as a new variable to be used in my python script.'</p>
<p><strong>File Example:</strong></p>
<pre><code>1
2
3
4
5
6
7
8
9
</code></pre>
<p><strong>Python Script (so far...):</strong></p>
<pre><code>#!/usr/bin/python
f = open('/home/weather/test', 'r')
for line in f.read().split('\n'):
print line
f.close()
</code></pre>
| -2 | 2016-08-05T10:57:56Z | 38,787,669 | <p>Use <code>exec</code> with a string representing the required code:</p>
<pre><code>for i in range(5):
exec('line%d=%d' % (i, i))
print(line0)
print(line1)
print(line2)
print(line3)
print(line4)
</code></pre>
<p>Output:</p>
<pre><code>0
1
2
3
4
</code></pre>
<p>The <code>exec</code> line activates the python interpreter on the given string, so for example when i == 0 you get <code>exec("line0 = 0")</code>, and so <code>line0</code> pops into existance!</p>
| 1 | 2016-08-05T11:03:29Z | [
"python"
] |
Define Each New Line As a Variable | 38,787,578 | <p>I have a text file that has many lines of data. I would like to setup a loop that reads each line of data and then defines that line/data as a new variable to be used in my python script.'</p>
<p><strong>File Example:</strong></p>
<pre><code>1
2
3
4
5
6
7
8
9
</code></pre>
<p><strong>Python Script (so far...):</strong></p>
<pre><code>#!/usr/bin/python
f = open('/home/weather/test', 'r')
for line in f.read().split('\n'):
print line
f.close()
</code></pre>
| -2 | 2016-08-05T10:57:56Z | 38,788,043 | <p>Usually when you want to have dynamically named variables, really you want a sequence or mapping. In your case, sequence (e.g. list) will be enough. List of lines may be retrieved from file by <code>.readlines</code> method.</p>
<pre><code>with open('/home/weather/test', 'r'):
all_lines = f.readlines()
print all_lines[0] # first line
print all_lines[1] # second line
print len(lines) # lines count
</code></pre>
| 2 | 2016-08-05T11:22:37Z | [
"python"
] |
substract values of two nested dictionary python | 38,787,618 | <p>I'd need to get delta of two nested dictionary:</p>
<p>I'm using a function like that to get a nested dictionary </p>
<pre><code>def _get_data(self):
duplicates = defaultdict(list) # to append tuples into a dictionary
counter_dict = AutoVivification()
vpls_dict = AutoVivification()
fpcs = self._get_slot_fpcs_online()
pattern = "GOT:\s+(\d+).*([0-9A-F]{2,2}\:[0-9A-F]{1,2}\:[0-9A-F]{1,2}\:[0-9A-F]{1,2}\:[0-9A-F]{1,2}\:[0-9A-F]{1,2})\s+\d{4}\s+(\d\s+\d).*(\d\s+\d+/\d+)"
regex = re.compile(pattern,re.IGNORECASE)
for i in fpcs:
if i == '11':
for pfe in range(2):
cmd = self._conn.rpc.request_pfe_execute(target='fpc' + str(i),command='show l2metro '+str(pfe)+' mac hw')
cmd_str = etree.tostring(cmd)
for x in regex.findall(cmd_str):
if x[2] =='0 0' and x[3] != '7 255/255':
duplicates[i].append(x)
else:
cmd = self._conn.rpc.request_pfe_execute(target='fpc' + str(i),command='show l2metro 0 mac hw')
cmd_str = etree.tostring(cmd)
for x in regex.findall(cmd_str):
if x[2] =='0 0' and x[3] != '7 255/255':
duplicates[i].append(x)
for k,v in duplicates.iteritems():
for j in v:
cmd_vpls = self._conn.rpc.get_l2_learning_routing_instances()
vpls_instance = ''.join(cmd_vpls.xpath("//l2ald-rtb-entry[l2rtb-id=" + '"' + str(j[0]) + '"'"]/l2rtb-name//text()")[0])
vpls_dict[k][j[1]][j[3]][j[0]][vpls_instance] = self._conn.cli('show configuration routing-instances '+ vpls_instance + ' forwarding-options family vpls filter',warning=False).split('\n')[1].replace('input','').replace(';','')
counter_cmd = self._conn.rpc.get_firewall_filter_information(filtername=str(vpls_dict[k][j[1]][j[3]][j[0]][vpls_instance]).strip())
counter_dict[k][j[1]][j[3]][vpls_instance][vpls_dict[k][j[1]][j[3]][j[0]][vpls_instance].strip()] = ''.join(counter_cmd.xpath('./filter-information/policer/packet-count//text()')).replace('\n','')
return counter_dict
</code></pre>
<p>counter_dict result look likes:</p>
<p>{'10': {'00:07:72:9d:dc:4c': {'0 255/255': {'128379': {'CDALJ1/17223002010': '91304'}}},
'00:0f:bb:fa:25:fd': {'0 255/255': {'232367': {'CDALJ1/14100001093228': '1585097'}}},
'00:1b:c0:f2:f4:fa': {'0 255/255': {'156420': {'CDALJ1/08903762011': '0'},
'166980': {'CDALJ1/19369922011': '0'}}},
'88:e0:f3:61:d8:01': {'0 255/255': {'182099': {'CDALJ1/11274452012': '0'}}},
'ec:13:db:0a:95:01': {'0 255/255': {'182099': {'CDALJ1/11274452012': '0'}}}},</p>
<p>'11': {'00:00:0c:07:ac:75': {'0 255/255': {'232173': {'CDALJ1/14100001093242': '0'}}},
'00:00:0c:07:ac:f5': {'0 255/255': {'293667': {'CDALJ1/14100001095054': '2723092'}}},
'00:00:0c:07:ac:f6': {'0 255/255': {'298967': {'CDALJ1/14100001095106': '0'}}},
'00:00:0c:07:ac:f7': {'0 255/255': {'298969': {'CDALJ1/14100001095107': '0'}}},
'00:07:72:9d:dc:4c': {'0 255/255': {'128379': {'CDALJ1/17223002010': '91304'}}}</p>
<p>[......]</p>
<p>I'm trying to get a delta of inner value keeping dictionary structure :</p>
<p>mac_dict1 = _get_data()</p>
<p>{'10': {'00:07:72:9d:dc:4c': {'0 255/255': {'128379': {'CDALJ1/17223002010': '91304'}}},
'00:0f:bb:fa:25:fd': {'0 255/255': {'232367': {'CDALJ1/14100001093228': '1585097'}}}</p>
<p>sleep5</p>
<p>mac_dict2 = _get_data() </p>
<p>{'10': {'00:07:72:9d:dc:4c': {'0 255/255': {'128379': {'CDALJ1/17223002010': '91310'}}},
'00:0f:bb:fa:25:fd': {'0 255/255': {'232367': {'CDALJ1/14100001093228': '1585100'}}}</p>
<p>result = get_diff(mac_dict1,mac_dict2)</p>
<p>result should be provide a result like that: </p>
<p>{'10': {'00:07:72:9d:dc:4c': {'0 255/255': {'128379': {'CDALJ1/17223002010': '6'}}},
'00:0f:bb:fa:25:fd': {'0 255/255': {'232367': {'CDALJ1/14100001093228': '3'}}}</p>
<p>Could you provide me any hint or tip about how to do that (not the code)? </p>
<p>Thanks</p>
| -3 | 2016-08-05T10:59:38Z | 38,788,512 | <p>You could do that with simple recursive function that will turn <code>str</code> values to <code>int</code> and subtract or recurse in case of <code>dict</code>:</p>
<pre><code>def subtract(x, y):
if isinstance(x, dict) and isinstance(y, dict):
return {key: subtract(x[key], y[key]) for key in x if key in y}
else:
return str(int(x) - int(y))
</code></pre>
<p>Running it with given input:</p>
<pre><code>d1 = {
'10': {
'00:07:72:9d:dc:4c': {'0 255/255': {'128379': {'CDALJ1/17223002010': '91304'}}},
'00:0f:bb:fa:25:fd': {'0 255/255': {'232367': {'CDALJ1/14100001093228': '1585097'}}}
}
}
d2 = {
'10': {
'00:07:72:9d:dc:4c': {'0 255/255': {'128379': {'CDALJ1/17223002010': '91310'}}},
'00:0f:bb:fa:25:fd': {'0 255/255': {'232367': {'CDALJ1/14100001093228': '1585100'}}}
}
}
print subtract(d2, d1)
</code></pre>
<p>Formatted output:</p>
<pre><code>{
'10': {
'00:07:72:9d:dc:4c': {'0 255/255': {'128379': {'CDALJ1/17223002010': '6'}}},
'00:0f:bb:fa:25:fd': {'0 255/255': {'232367': {'CDALJ1/14100001093228': '3'}}}
}
}
</code></pre>
<p>Note that the example code fails if your input contains any other types of values than <code>dict</code> and <code>str</code> that should be interpreted as <code>int</code>.</p>
| 1 | 2016-08-05T11:47:49Z | [
"python",
"dictionary",
"nested"
] |
NOT NULL constraint failed: owner_id in form saving | 38,787,689 | <p>I am trying to make a form which allows users to upload a file (a plain text dictionary file). Here is my model:</p>
<pre><code>from django.conf import settings
from django.db import models
import uuid
class Dictionary(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
owner = models.ForeignKey(settings.AUTH_USER_MODEL)
file = models.FileField(upload_to='uploads/%y/%m/%d')
timestamp = models.DateTimeField(auto_now_add=True)
</code></pre>
<p>Here is the form I use with it. I want to only expose the file parameter for users to set. The owner I intend to set from the request user:</p>
<pre><code>from django.forms import ModelForm
from dic.models import Dictionary
class DictionaryForm(ModelForm):
class Meta:
model = Dictionary
fields = ['file']
def __init__(self, owner, *args, **kwargs):
self.owner = owner
super().__init__(*args, **kwargs)
</code></pre>
<p>Here is my view code, which sends the post data, files, and user to the form:</p>
<pre><code>from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from dic.forms import DictionaryForm
@login_required
def upload(request):
if request.method == 'POST':
form = DictionaryForm(request.user, request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/dic/upload_success')
else:
form = DictionaryForm(request.user)
return render(request, 'dic/upload.html', {'form': form})
</code></pre>
<p>And here is my failing test code:</p>
<pre><code>def test_can_upload_file(self):
user = User.objects.create(username='foo')
user.save()
self.client.force_login(user)
self.assertEqual(Dictionary.objects.count(), 0)
file = StringIO(initial_value='fake data here')
response = self.client.post('/dic/upload', {'file':file})
self.assertEqual(response.status_code, 200)
</code></pre>
<p>The assert line is never run because an error occurs first. The error generated is in the view code, at <code>form.save()</code>. The error generated is:</p>
<pre><code>django.db.utils.IntegrityError: NOT NULL constraint failed: dic_dictionary.owner_id
</code></pre>
<p>Two questions. How do I correctly set the owner value in the form so that this error does not occur? And why does the error occur on the <code>form.save()</code> line, since <code>is_valid()</code> should have checked that no errors would occur?</p>
| 0 | 2016-08-05T11:04:40Z | 38,787,849 | <p><code>is_valid()</code> only validates the fields that you specified in the form (in this case - <code>file</code>). The form is valid - but you get an error later on because the other model field constraints are not met when saving. </p>
<p>Passing the <code>owner</code> to the form isn't going to work because the form is not handling that field. Instead you need to add the <code>owner</code> to the model after the form has validated, but before saving it:</p>
<pre><code>if request.method == 'POST':
form = DictionaryForm(request.POST, request.FILES)
if form.is_valid():
obj = form.save(commit=False)
obj.owner = request.user
obj.save()
return HttpResponseRedirect('/dic/upload_success')
</code></pre>
<p>(Also remove the <code>__init__</code> method on the form).</p>
| 2 | 2016-08-05T11:12:33Z | [
"python",
"django",
"web-applications"
] |
Keras deep variational autoencoder | 38,787,714 | <p>Im trying to adapt the Keras VAE example to a deep network by adding one more layer.</p>
<p>Original code: <a href="https://github.com/fchollet/keras/blob/master/examples/variational_autoencoder.py" rel="nofollow">Original VAE code</a></p>
<p>CHANGES:</p>
<pre><code>batch_size = 200
original_dim = 784
latent_dim = 2
intermediate_dim_deep = 384 # <<<<<<<
intermediate_dim = 256
nb_epoch = 20
#
x = Input(batch_shape=(batch_size, original_dim))
x = Dense(intermediate_dim_deep, activation='relu')(x) # NEW LAYER <<<<<<
h = Dense(intermediate_dim, activation='relu')(x)
z_mean = Dense(latent_dim)(h)
z_log_var = Dense(latent_dim)(h)
#
def sampling(args):
z_mean, z_log_var = args
epsilon = K.random_normal(shape=(batch_size, latent_dim), mean=0.)
return z_mean + K.exp(z_log_var / 2) * epsilon
# note that "output_shape" isn't necessary with the TensorFlow backend
z = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var])
#
# we instantiate these layers separately so as to reuse them later
decoder_h = Dense(intermediate_dim, activation='relu')
decoder_d = Dense(intermediate_dim_deep, activation='rely') # NEW LAYER <<<<<<
decoder_mean = Dense(original_dim, activation='sigmoid')
h_decoded = decoder_h(z)
d_decoded = decoder_d(h_decoded) # ADDED ONE MORE STEP HERE <<<<<<<
x_decoded_mean = decoder_mean(d_decoded)
#
def vae_loss(x, x_decoded_mean):
xent_loss = original_dim * objectives.binary_crossentropy(x, x_decoded_mean)
kl_loss = - 0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)
return xent_loss + kl_loss
#
vae = Model(x, x_decoded_mean)
vae.compile(optimizer='rmsprop', loss=vae_loss)
#####
</code></pre>
<p>Compile I've me this error:</p>
<pre><code>/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py:1615: UserWarning: Model inputs must come from a Keras Input layer, they cannot be the output of a previous non-Input layer. Here, a tensor specified as input to "model_1" was not an Input tensor, it was generated by layer dense_1.
Note that input tensors are instantiated via `tensor = Input(shape)`.
The tensor that caused the issue was: None
str(x.name))
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-8-c9010948cdee> in <module>()
----> 1 vae = Model(x, x_decoded_mean)
2 vae.compile(optimizer='rmsprop', loss=vae_loss)
/usr/local/lib/python2.7/dist-packages/keras/engine/topology.pyc in __init__(self, input, output, name)
1788 'The following previous layers '
1789 'were accessed without issue: ' +
-> 1790 str(layers_with_complete_input))
1791 for x in node.output_tensors:
1792 computable_tensors.append(x)
Exception: Graph disconnected: cannot obtain value for tensor input_1 at layer "input_1". The following previous layers were accessed without issue: []
</code></pre>
<p>I have the other examples in the repo and it seems a valid way to do it.
Am I missing something?</p>
| 0 | 2016-08-05T11:06:14Z | 38,793,964 | <p>When adding the new hidden layer you're overriding the <code>x</code> variable so you're left without an input layer. Also, is 'rely' a valid activation option?</p>
| 0 | 2016-08-05T16:32:24Z | [
"python",
"machine-learning",
"deep-learning",
"keras",
"autoencoder"
] |
Codecademy Advance Python The "In" Operator. Why does key print values? | 38,787,737 | <p>I am having difficulty understanding why the last line in the code is: </p>
<pre><code>print key, my_dict[key]
</code></pre>
<p>instead of... </p>
<pre><code>print key, my_dict[values]
</code></pre>
<p>CODE </p>
<pre><code>my_dict = {
"Name": "Joshua",
"Age": "28",
"Nationality": "UK"
print my_dict.keys()
print my_dict.values()
for key in my_dict:
print key, my_dict[key]
}
</code></pre>
<p>On the last line, we have already said print key, and the instructions say to print the values after printing the key, so why is the code referencing my_dict again and printing (again) [key]. Why does "key" print values? </p>
| 0 | 2016-08-05T11:07:23Z | 38,787,933 | <p>DIctionary is a mapping type.It consists of key value pairs.For each key there will be an associated value.So for retreiving a value associated with a key, we use dict[key].It is just like accessing an element in a list with the index value.In your example if you call <code>my_dict['name']</code> you will get <code>"Joshua"</code></p>
| 0 | 2016-08-05T11:17:19Z | [
"python"
] |
Codecademy Advance Python The "In" Operator. Why does key print values? | 38,787,737 | <p>I am having difficulty understanding why the last line in the code is: </p>
<pre><code>print key, my_dict[key]
</code></pre>
<p>instead of... </p>
<pre><code>print key, my_dict[values]
</code></pre>
<p>CODE </p>
<pre><code>my_dict = {
"Name": "Joshua",
"Age": "28",
"Nationality": "UK"
print my_dict.keys()
print my_dict.values()
for key in my_dict:
print key, my_dict[key]
}
</code></pre>
<p>On the last line, we have already said print key, and the instructions say to print the values after printing the key, so why is the code referencing my_dict again and printing (again) [key]. Why does "key" print values? </p>
| 0 | 2016-08-05T11:07:23Z | 38,787,974 | <p>Lists work like this:</p>
<pre><code>foo = ["spam", "spam", "lovely spam"]
print foo[0] # prints "spam"
</code></pre>
<p>0 is the index for the element "spam".</p>
<p>You are using a dictionary. Dictionaries don't have indexes, they have keys.</p>
<pre><code>my_dict = {
"Name": "Joshua",
"Age": "28",
"Nationality": "UK"
}
print my_dict["Name"]
</code></pre>
<p>In the list at position "0" there is a string "spam".</p>
<p>In the dictionary at position "Name" there is a string "Joshua".</p>
| 1 | 2016-08-05T11:19:24Z | [
"python"
] |
Installing opencv 3.1 with anaconda python3? | 38,787,748 | <p>How do I install opencv with anaconda python3 , opencv picked up my python3 executables</p>
<pre><code>-- Python 2:
-- Interpreter: /usr/bin/python2.7 (ver 2.7.12)
-- Libraries: /usr/lib/x86_64-linux-gnu/libpython2.7.so (ver 2.7.12)
-- numpy: /usr/lib/python2.7/dist-packages/numpy/core/include (ver 1.11.0)
-- packages path: lib/python2.7/dist-packages
--
-- Python 3:
-- Interpreter: /home/tamim/anaconda3/bin/python3 (ver 3.5.2)
-- Libraries: /usr/lib/x86_64-linux-gnu/libpython3.5m.so (ver 3.5.2)
-- numpy: /home/tamim/anaconda3/lib/python3.5/site-packages/numpy/core/include (ver 1.11.1)
-- packages path: lib/python3.5/site-packages
--
-- Python (for build): /usr/bin/python2.7
</code></pre>
<p>I installed opencv with the following make options</p>
<pre><code>cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D WITH_TBB=ON -D BUILD_NEW_PYTHON_SUPPORT=ON -D WITH_V4L=ON -D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON -D BUILD_EXAMPLES=ON -D WITH_QT=ON -D WITH_OPENGL=ON -D ENABLE_FAST_MATH=1 -D CUDA_FAST_MATH=1 -D WITH_CUBLAS=1 -D CUDA_NVCC_FLAGS="-D_FORCE_INLINES" ..
</code></pre>
<p>But after installing it I can't import cv2 within python3 of anaconda. I can however import cv2 from builtin python2 command. So I suppose it build for the python2 version as stated in the last line.</p>
<p>How do I build for anaconda python3 ?</p>
| 0 | 2016-08-05T11:07:59Z | 39,240,127 | <p>I think you don't need to build OpenCV for anaconda, there is this very handy
tool called 'conda' that is available in your terminal once you have installed
the Anaconda python distribution.</p>
<p>I found this site which gives instruction on how to install opencv3</p>
<pre><code>https://anaconda.org/menpo/opencv3
</code></pre>
<p>I personally installed it myself so just try follow along with these instructions.</p>
<p>If you have the Anaconda python distribution installed in your system, you can issue this command (assuming you are working on linux) fire up the terminal:</p>
<pre><code>conda install -c https://conda.binstar.org/menpo opencv
</code></pre>
<p>If the version of python install in your Anaconda is 2.7, the command above should install OpenCV 3.1, but if the version of your python is 3.5, then you should change 'opencv' in the last line to 'opencv3'</p>
<pre><code>conda install -c https//conda.binstar.org/menpo opencv3
</code></pre>
<p>This should install OpenCV in your Anaconda. To see if you have installed it successfully, fire up your Python and issue the following command:</p>
<pre><code>import cv2 # import the opencv library
cv2.__version__ # this will print the version of your opencv2
</code></pre>
<p>Hope that helps =)</p>
| 1 | 2016-08-31T03:07:40Z | [
"python",
"opencv",
"anaconda",
"ubuntu-16.04"
] |
Django admin: Edit fields of one-to-one model class | 38,787,889 | <p>I have two models with the following relationship defined in models.py:</p>
<pre><code>class InnerModel(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class OuterModel(models.Model):
inner = models.OneToOneField(InnerModel)
def __str__(self):
return "OuterModel"
</code></pre>
<p>My forms.py looks like this:</p>
<pre><code>class OuterModelForm(forms.ModelForm)
class Meta:
model = OuterModel
fields = ['inner']
</code></pre>
<p>My admin.py form looks like this:</p>
<pre><code>class OuterModelAdmin(admin.ModelAdmin)
form = OuterModelForm
admin.site.register(OuterModel, OuterModelAdmin)
</code></pre>
<p>When I display the admin page, I can see the InnerModel instance and the name field is present, but the name field is an empty drop-down menu rather than a blank text field that can be edited.</p>
<p>How can I change the InnerModel name field so that it can be edited by admin?</p>
| 0 | 2016-08-05T11:14:40Z | 38,788,308 | <p>You need to use <code>inlines</code> (<a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.inlines" rel="nofollow">doc</a>):</p>
<pre><code>class InnerModelInline(admin.StackedInline):
model = InnerModel
class OuterModelAdmin(admin.ModelAdmin):
inlines = [InnerModelInline]
admin.site.register(OuterModel, OuterModelAdmin)
</code></pre>
<p>Similar question: <a href="http://stackoverflow.com/questions/24623457/django-inline-form-for-onetoone-field-in-admin-site">here</a></p>
| 1 | 2016-08-05T11:35:58Z | [
"python",
"django",
"django-models",
"django-forms",
"django-admin"
] |
Python3 Asyncio shared resources between concurrent tasks | 38,787,989 | <p>I've got a network application written in Python3.5 which takes advantage of pythons Asyncio which concurrently handles each incoming connection. </p>
<p>On every concurrent connection, I want to store the connected clients data in a list. I'm worried that if two clients connect at the same time (which is a possibility) then both tasks will attempt to write to the list at the same time, which will surely raise an issue. How would I solve this?</p>
| 1 | 2016-08-05T11:20:10Z | 38,791,709 | <p>asyncio does context switching only on <em>yield points</em> (<code>await</code> expressions), thus two parallel tasks are not executed at <strong>the same</strong> time.</p>
<p>But if race conditions are still possible (it depends on concrete code structure) you may use <a href="https://docs.python.org/3/library/asyncio-sync.html" rel="nofollow">asyncio synchronization primitives</a> and <a href="https://docs.python.org/3/library/asyncio-queue.html" rel="nofollow">queues</a>.</p>
| 2 | 2016-08-05T14:29:24Z | [
"python",
"python-3.x",
"concurrency",
"python-asyncio",
"shared-resource"
] |
Python3 Asyncio shared resources between concurrent tasks | 38,787,989 | <p>I've got a network application written in Python3.5 which takes advantage of pythons Asyncio which concurrently handles each incoming connection. </p>
<p>On every concurrent connection, I want to store the connected clients data in a list. I'm worried that if two clients connect at the same time (which is a possibility) then both tasks will attempt to write to the list at the same time, which will surely raise an issue. How would I solve this?</p>
| 1 | 2016-08-05T11:20:10Z | 38,791,950 | <p>There is lots of info that is missing in your question.</p>
<ul>
<li>Is your app threaded? If yes, then you have to wrap your list in a <code>threading.Lock</code>.</li>
<li>Do you switch context (e.g. use <code>await</code>) between writes (to the list) in the request handler? If yes, then you have to wrap your list in a <code>asyncio.Lock</code>.</li>
<li>Do you do multiprocessing? If yes then you have to use <code>multiprocessing.Lock</code></li>
<li>Is your app divided onto multiple machines? Then you have to use some external shared database (e.g. Redis).</li>
</ul>
<p>If answers to all of those questions is <em>no</em> then you don't have to do anything since single-threaded async app cannot update shared resource parallely.</p>
| 1 | 2016-08-05T14:41:15Z | [
"python",
"python-3.x",
"concurrency",
"python-asyncio",
"shared-resource"
] |
Issues with downloading dict into CSV accesing NY Times API via Python | 38,788,027 | <p>I am currently trying to download a large number of NY Times articles using their API, based on Python 2.7. To do so, I was able to reuse a piece of code i found online: </p>
<pre><code>[code]from nytimesarticle import articleAPI
api = articleAPI('...')
articles = api.search( q = 'Brazil',
fq = {'headline':'Brazil', 'source':['Reuters','AP', 'The New York Times']},
begin_date = '20090101' )
def parse_articles(articles):
'''
This function takes in a response to the NYT api and parses
the articles into a list of dictionaries
'''
news = []
for i in articles['response']['docs']:
dic = {}
dic['id'] = i['_id']
if i['abstract'] is not None:
dic['abstract'] = i['abstract'].encode("utf8")
dic['headline'] = i['headline']['main'].encode("utf8")
dic['desk'] = i['news_desk']
dic['date'] = i['pub_date'][0:10] # cutting time of day.
dic['section'] = i['section_name']
if i['snippet'] is not None:
dic['snippet'] = i['snippet'].encode("utf8")
dic['source'] = i['source']
dic['type'] = i['type_of_material']
dic['url'] = i['web_url']
dic['word_count'] = i['word_count']
# locations
locations = []
for x in range(0,len(i['keywords'])):
if 'glocations' in i['keywords'][x]['name']:
locations.append(i['keywords'][x]['value'])
dic['locations'] = locations
# subject
subjects = []
for x in range(0,len(i['keywords'])):
if 'subject' in i['keywords'][x]['name']:
subjects.append(i['keywords'][x]['value'])
dic['subjects'] = subjects
news.append(dic)
return(news)
def get_articles(date,query):
'''
This function accepts a year in string format (e.g.'1980')
and a query (e.g.'Amnesty International') and it will
return a list of parsed articles (in dictionaries)
for that year.
'''
all_articles = []
for i in range(0,100): #NYT limits pager to first 100 pages. But rarely will you find over 100 pages of results anyway.
articles = api.search(q = query,
fq = {'headline':'Brazil','source':['Reuters','AP', 'The New York Times']},
begin_date = date + '0101',
end_date = date + '1231',
page = str(i))
articles = parse_articles(articles)
all_articles = all_articles + articles
return(all_articles)
Download_all = []
for i in range(2009,2010):
print 'Processing' + str(i) + '...'
Amnesty_year = get_articles(str(i),'Brazil')
Download_all = Download_all + Amnesty_year
import csv
keys = Download_all[0].keys()
with open('brazil-mentions.csv', 'wb') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(Download_all)
</code></pre>
<p>Without the last bit (starting with "... import csv" this seems to be working fine. If I simply print my results, ("print Download_all") I can see them, however in a very unstructured way. Running the actual code i however get the message:</p>
<pre><code> File "C:\Users\xxx.yyy\AppData\Local\Continuum\Anaconda2\lib\csv.py", line 148, in _dict_to_list
+ ", ".join([repr(x) for x in wrong_fields]))
ValueError: dict contains fields not in fieldnames: 'abstract'
</code></pre>
<p>Since I am quite a newbie at this, I would highly appreciate your help in guiding me how to download the news articles into a csv file in a structured way. </p>
<p>Thanks a lot in advance!
Best regards</p>
| 0 | 2016-08-05T11:21:40Z | 38,788,544 | <p>Where you have:</p>
<pre><code>keys = Download_all[0].keys()
</code></pre>
<p>This takes the column headers for the CSV from the dictionary for the first article. The problem is that the article dictionaries do not all have the same keys, so when you reach the first one that has the extra <code>abstract</code> key, it fails.</p>
<p>It looks like you'll have problems with <code>abstract</code> and <code>snippet</code> which are only added to the dictionary if they exist in the response.</p>
<p>You need to make <code>keys</code> equal to the superset of all possible keys:</p>
<pre><code>keys = Download_all[0].keys() + ['abstract', 'snippet']
</code></pre>
<p>Or, ensure that every dict has a value for every field:</p>
<pre><code>def parse_articles(articles):
...
if i['abstract'] is not None:
dic['abstract'] = i['abstract'].encode("utf8")
else:
dic['abstract'] = ""
...
if i['snippet'] is not None:
dic['snippet'] = i['snippet'].encode("utf8")
else:
dic['snippet'] = ""
</code></pre>
| 0 | 2016-08-05T11:49:52Z | [
"python",
"api",
"csv"
] |
How to get information from widgets | 38,788,073 | <p>I have a PyQt program and in this project I have some calculations based on earlier set preferences.</p>
<p>As an example, I created a small calculator which contains the following files:</p>
<p><em>example_run_vars.py</em>:</p>
<pre><code>from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(324, 332)
self.gridLayout = QtWidgets.QGridLayout(Dialog)
self.gridLayout.setObjectName("gridLayout")
self.B = QtWidgets.QLabel(Dialog)
self.B.setObjectName("B")
self.gridLayout.addWidget(self.B, 0, 0, 1, 1)
self.A_val = QtWidgets.QLineEdit(Dialog)
self.A_val.setObjectName("A_val")
self.gridLayout.addWidget(self.A_val, 0, 1, 1, 1)
self.A = QtWidgets.QLabel(Dialog)
self.A.setObjectName("A")
self.gridLayout.addWidget(self.A, 1, 0, 1, 1)
self.B_val = QtWidgets.QLineEdit(Dialog)
self.B_val.setObjectName("B_val")
self.gridLayout.addWidget(self.B_val, 1, 1, 1, 1)
self.Zerocheck = QtWidgets.QCheckBox(Dialog)
self.Zerocheck.setObjectName("Zerocheck")
self.gridLayout.addWidget(self.Zerocheck, 1, 2, 1, 1)
self.math = QtWidgets.QComboBox(Dialog)
self.math.setObjectName("math")
self.gridLayout.addWidget(self.math, 2, 1, 1, 1)
self.math_else = QtWidgets.QComboBox(Dialog)
self.math_else.setObjectName("math_else")
self.gridLayout.addWidget(self.math_else, 3, 1, 1, 1)
self.Run = QtWidgets.QPushButton(Dialog)
self.Run.setObjectName("Run")
self.gridLayout.addWidget(self.Run, 4, 1, 1, 1)
self.Answer = QtWidgets.QLineEdit(Dialog)
self.Answer.setReadOnly(False)
self.Answer.setObjectName("Answer")
self.gridLayout.addWidget(self.Answer, 5, 1, 1, 1)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.B.setText(_translate("Dialog", "A: "))
self.A.setText(_translate("Dialog", "B: "))
self.Zerocheck.setText(_translate("Dialog", "ZeroCheck"))
self.Run.setText(_translate("Dialog", "Run"))
</code></pre>
<p><em>example.py</em>:</p>
<pre><code>import sys, os
from PyQt5 import QtCore, QtGui, QtWidgets
from example_run_vars import Ui_Dialog
class example(QtWidgets.QDialog):
def __init__(self, parent=None):
# QtGui.QWidget.__init__(self, parent) # PyQt4
super(example, self).__init__(parent) # pyQt5
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.ui.retranslateUi(self)
self.ui.math.addItem('Add')
self.ui.math.addItem('Substract')
self.ui.math.addItem('Multiply')
self.ui.math.addItem('Divide')
self.ui.math.addItem('Power')
self.ui.math.addItem('Sqrt')
self.ui.math.activated[str].connect(self.dosomething)
self.ui.math_else.addItem('math function x')
self.ui.math_else.activated[str].connect(self.dosomething)
self.ui.Zerocheck.setChecked(False)
self.ui.Zerocheck.clicked.connect( self.dosomething)
self.ui.Run.clicked.connect(self.calculate)
def a_changed(self):
pass
def b_changed(self):
pass
def calculate(self):
# return value in Answer text box
pass
def dosomething(self):
# arbritary thing i realy don't know if i need it...
pass
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
exampleDialog = QtWidgets.QDialog()
examplepanel = example()
examplepanel.show()
sys.exit(app.exec_())
</code></pre>
<p>The idea is, when I press the run button in the script, it gives an answer in the textbox. The point is that I have no idea what is the easiest (or programmically the best) method for returning the answer.</p>
<p>I have an idea there are two or tree options:</p>
<ol>
<li>Every checkbox/combobox/textbox does something and puts this somewhere, and the calculate button reads this out.</li>
<li>When calculating, read out all checkboxes/comboboxes/textboxes and add this to the function.</li>
<li>A combination of those two.</li>
</ol>
<p>What is the best method of dealing with kind of situation, and why?</p>
| 2 | 2016-08-05T11:23:35Z | 38,794,039 | <p>The data is <em>already</em> stored in the widgets, so it is inefficient make another copy of it. Also, you would need to set up handlers for each individual widget, which is unnecessarily complicated. In general, it is best to gather all the information from the widgets at the point when the calculation is made.</p>
<p>In your example, I would suggest you keep the <code>calculate</code> slot connected to the run button, but get rid of all the other signals/slots. You should then create functions for all the mathematical operations you need. Each of these functions <strong>must</strong> have two arguments, which will take the A/B values from the line-edits. You could use some of the functions from the <a href="http://docs.python.org/3/library/operator.html#module-operator" rel="nofollow">operator module</a> for this, or just write your own:</p>
<pre><code>def add_func(a, b):
return a + b
</code></pre>
<p>You can then link these functions directly to the combo-box items like this:</p>
<pre><code> self.ui.math.addItem('Add', add_func)
self.ui.math.addItem('Substract', sub_func)
self.ui.math.addItem('Multiply', mult_func)
</code></pre>
<p>With that in place, the <code>calculate</code> slot would then look something like this:</p>
<pre><code> def calculate(self):
a = float(self.ui.A_val.text())
b = float(self.ui.B_val.text())
# get the linked function from the combo-box
func = self.ui.math.currentData()
# calculate the answer
answer = func(a, b)
# show the new answer
self.ui.Answer.setText(str(answer))
</code></pre>
<p>Doing things this way makes it very easy to add, remove or re-order the functions in the combo-box (i.e. the <code>calculate</code> slot never has to change).</p>
| 2 | 2016-08-05T16:37:06Z | [
"python",
"python-3.x",
"pyqt",
"pyqt5"
] |
How to upload crawled data from Scrapy to Amazon S3 as csv or json? | 38,788,096 | <p>What are the steps to upload the crawled data from Scrapy to the Amazon s3 as a csv/jsonl/json file? All i could find from the internet was to upload scraped images to the s3 bucket.</p>
<p>I'm currently using Ubuntu 16.04,
and i have installed boto by the command, </p>
<pre><code>pip install boto
</code></pre>
<p>I have added the following lines to settings.py. Can anyone explain the other changes i have to make.</p>
<pre><code>AWS_ACCESS_KEY_ID = 'access key id'
AWS_SECRET_ACCESS_KEY= 'access key'
FEED_URI = 'bucket path'
FEED_FORMAT = 'jsonlines'
FEED_EXPORT_FIELDS = None
FEED_STORE_EMPTY = False
FEED_STORAGES = {}
FEED_STORAGES_BASE = {
'': None,
'file': None,
'stdout': None,
's3': 'scrapy.extensions.feedexport.S3FeedStorage',
'ftp': None,
}
FEED_EXPORTERS = {}
FEED_EXPORTERS_BASE = {
'json': None,
'jsonlines': None,
'jl': None,
'csv': None,
'xml': None,
'marshal': None,
'pickle': None,
}
</code></pre>
<p><strong>Edit 1 :</strong> When i configure all the above and run <code>scrapy crawl spider</code>,
I get the following error after the crawled results.</p>
<pre><code>2016-08-08 10:57:03 [scrapy] ERROR: Error storing csv feed (200 items) in: s3: myBucket/crawl.csv
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/twisted/python/threadpool.py", line 246, in inContext
result = inContext.theWork()
File "/usr/lib/python2.7/dist-packages/twisted/python/threadpool.py", line 262, in <lambda>
inContext.theWork = lambda: context.call(ctx, func, *args, **kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 118, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 81, in callWithContext
return func(*args,**kw)
File "/usr/local/lib/python2.7/dist-packages/scrapy/extensions/feedexport.py", line 123, in _store_in_thread
key.set_contents_from_file(file)
File "/usr/local/lib/python2.7/dist-packages/boto/s3/key.py", line 1293, in set_contents_from_file
chunked_transfer=chunked_transfer, size=size)
File "/usr/local/lib/python2.7/dist-packages/boto/s3/key.py", line 750, in send_file
chunked_transfer=chunked_transfer, size=size)
File "/usr/local/lib/python2.7/dist-packages/boto/s3/key.py", line 951, in _send_file_internal
query_args=query_args
File "/usr/local/lib/python2.7/dist-packages/boto/s3/connection.py", line 656, in make_request
auth_path = self.calling_format.build_auth_path(bucket, key)
File "/usr/local/lib/python2.7/dist-packages/boto/s3/connection.py", line 94, in build_auth_path
path = '/' + bucket
TypeError: cannot concatenate 'str' and 'NoneType' objects
</code></pre>
| 0 | 2016-08-05T11:24:58Z | 38,822,610 | <p>The problem was solved by adding the following line into <code>settings.py</code> file:</p>
<pre><code>ITEM_PIPELINE = {
'scrapy.pipelines.files.S3FilesStore': 1
}
</code></pre>
<p>along with the S3 credentials mentioned earlier.</p>
<pre><code>AWS_ACCESS_KEY_ID = 'access key id'
AWS_SECRET_ACCESS_KEY= 'access key'
FEED_URI='s3://bucket/folder/filename.json'
</code></pre>
<p>Thank you guys for your guidance. </p>
| 0 | 2016-08-08T06:33:35Z | [
"python",
"json",
"amazon-s3",
"web-scraping",
"scrapy"
] |
Google App engine (Python) - Contact Us info from an anonymous user | 38,788,097 | <p>How to allow someone without credentials to send me an email using the contactus form that I have provided on my Google app engine app?? When I am trying normally using mail modules, it is saying no real mail is bieng sent. Help me fix it!!</p>
| -2 | 2016-08-05T11:25:09Z | 38,788,635 | <p>If I understand you correctly, All you need is to get an alert about the "Contact us form submission activity" by a visitor (anonymous user) on the website.</p>
<p>You can implement it by having an email id like contact@example.com and send email to itself when a user submits the form. You can do it pretty easily, as there are lots of examples over the Internet to do this.</p>
<p>I am not a Python guy, so I cannot help you with the source code.
Hope it will help you somehow.</p>
| 0 | 2016-08-05T11:54:40Z | [
"python",
"google-app-engine"
] |
Parallel python extract by mask ArcGIS | 38,788,222 | <p>I found the following code in a <a href="http://gis.stackexchange.com/questions/94092/script-to-extract-by-mask-a-list-of-raster-files">previous</a> answer. I tried it for about 3000 rasters, it works but very slow. How to excute the code in parallel to fasten the process?</p>
<p>thanks,
moh</p>
<pre><code>import arcpy, os
from arcpy import env
from arcpy.sa import *
env.workspace = "C:/rasters/threshold"
outws = "C:/SIG/MelasCA_30runs_avg/threshold/mesoamerica"
mask = "C:/GIS/mesoamerica.shp"
rasterlist = arcpy.ListDatasets("*", "Raster")
for i in rasterlist:
outExtractByMask = ExtractByMask(i, mask)
outname = os.path.join(outws, str(i)) # Create the full out path
outExtractByMask.save(outname)
</code></pre>
| 0 | 2016-08-05T11:31:48Z | 38,788,400 | <p>You may use threads. Depending on the number of cores you have, execute 4/8/16 simultanously.
Hints for using threads:
<a href="https://pymotw.com/2/threading/" rel="nofollow">https://pymotw.com/2/threading/</a></p>
| 0 | 2016-08-05T11:41:39Z | [
"python",
"parallel-processing",
"arcgis"
] |
Error: spawn EACCES in ubuntu for node.js/express app trying to run python | 38,788,280 | <p>I have made a node.js server to run a python script using <a href="https://github.com/extrabacon/python-shell" rel="nofollow">python-shell </a> and am encountering an EACCES error ever since migrating from windows to Ubuntu. I have to my knowledge and limited ability tried to set the correct permissions to no avail, and have not currently found anyone with a problem such as this with a server trying to run another script. My question is how do I stop such an error occuring?</p>
<p>EDIT: Added JavaScript code, Image of ls-l in main server folder, and js script folder.</p>
<p>Express HTML error log (modified):</p>
<pre><code><h1>spawn EACCES</h1>
<h2></h2>
<pre>Error: spawn EACCES
at exports._errnoException (util.js:870:11)
at ChildProcess.spawn (internal/child_process.js:298:11)
at exports.spawn (child_process.js:362:9)
at new PythonShell (/home/user_name/simple_server/node_modules/python-shell/index.js:59:25)
at run_py_script (/home/user_name/simple_server/routes/rain_track.js:11:19)
at /home/user_name/simple_server/routes/rain_track.js:43:5
at Layer.handle [as handle_request] (/home/user_name/simple_server/node_modules/express/lib/router/layer.js:95:5)
at next (/home/user_name/simple_server/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/home/user_name/simple_server/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/user_name/simple_server/node_modules/express/lib/router/layer.js:95:5)</pre>
</code></pre>
<p>Javascript code:</p>
<pre><code>var express = require('express');
var router = express.Router();
var PythonShell = require('python-shell');
var options = {
mode: 'json',
pythonPath: '/home/user_name/simple_server'
};
function run_py_script(data, res, callback){
var pyshell = new PythonShell('dummy.py', options);
console.log(data.latitude + ", " + data.longitude + "\n");
pyshell.send(""+data.latitude + ", "+ data.longitude+"\n"); // change to data
pyshell.on('message', function(message){
console.log(message);
res.json(message);
});
pyshell.end(function(err){
if (err) {
console.log("Python script error has occured.");
console.log(err);
}
//return err ? callback(null) : callback(null, ret_val);
});
}
/* GET rain_track data. */
router.post('/', function(req, res, next) {
console.log("Location got: "+req.body.coords.latitude + ", " + req.body.coords.longitude);
var location_data = {
"latitude" : req.body.coords.latitude,
"longitude" : req.body.coords.longitude
};
run_py_script(location_data, res, function(err, rain_data) {
if (err){ console.log("error in python script" ); return res.json(null); }
})
});
module.exports = router;
</code></pre>
<p><code>ls -l</code>:</p>
<p><a href="http://i.stack.imgur.com/RcxZ0.png" rel="nofollow"><img src="http://i.stack.imgur.com/RcxZ0.png" alt="ls -l of directories"></a></p>
| 1 | 2016-08-05T11:34:40Z | 38,813,845 | <p>Upon detailed testing I have been unable to find a solution to this issue, and the question has indeed died.</p>
<p>However I successfully found a work-around, finding the issue with the EACCES was with the python path (in the options object). Removing this and running a python script in the server terminal's run location (e.g. <code>/bin</code> directory) would still work fine. </p>
| 0 | 2016-08-07T11:52:34Z | [
"javascript",
"python",
"node.js",
"ubuntu",
"express"
] |
Spyder does not show lists and arrays in variable explorer | 38,788,286 | <p>i don't really know why, but Spyder is not able to show lists or arrays in the variable explorer anymore. Do you have the same problem, any fixes? I have that problem on two computers.</p>
<p>Example:</p>
<pre><code>CSV = []
for x in os.listdir(location):
if x.split(".")[-1] =="CSV":
CSV.append(location+x)
CSV = np.array(CSV)
</code></pre>
<p>Thank you very much!</p>
| 0 | 2016-08-05T11:34:53Z | 38,789,224 | <p>Menu (Tools->Preferences->Variable Explorer) Shortcut (Ctrl+Alt+Shift+P)</p>
<p>Disable all the filters</p>
<p><a href="http://i.stack.imgur.com/tCcCn.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/tCcCn.jpg" alt="enter image description here"></a></p>
| 0 | 2016-08-05T12:24:49Z | [
"python",
"list",
"spyder"
] |
Avoid interpolation problems with numpy float | 38,788,291 | <p>I need to handle timespans in a library I am creating. My first idea was to keep it simple and codify them as years, with float.</p>
<p>The problems arise, for instance, when I wish to perform interpolations. Say I have</p>
<pre><code>xs = np.array([0, 0.7, 1.2, 3.0]) # times
ys = np.array([np.nan, 124.3, 214.0, np.nan]) # values associated
</code></pre>
<p>Outside the [0.7, 1.2] interval I would like to get the value np.nan, but inside, the obvious linear interpolation, particularly
in the extremes.</p>
<p>However, using </p>
<pre><code>#!/usr/bin/python3.5
import numpy as np
from fractions import Fraction
import scipy.interpolate as scInt
if __name__ == "__main__":
xs = np.array([0, 0.7, 1.2, 3.0]) # times
ys = np.array([np.nan, 124.3, 214.0, np.nan]) # values associated
interp = scInt.interp1d(xs, ys)
xsInt = np.array([0, 7/10, 6/5-0.0001, 6/5, 6/5+0.0001])
print(interp(xsInt))
</code></pre>
<p>I get</p>
<pre><code>[nan, 124.3, 213.98206, nan, nan]
</code></pre>
<p>So, the correct value for 7/10, but a nan for 6/5, which is 1.2. There is no mystery in this, machine representation of floats can cause
things like this. But anyway it is an issue I need to deal with.</p>
<p>My first idea was to double the values in fs, so that I would interpolate in
[x1-eps, x1+eps, x2-eps, x2+eps, ..., xn-eps, xn+eps], repeating twice the ys vector:
[y1, y1, y2, y2, y3, y3, ..., yn, yn]. This works, but it is quite ugly.
Then I though I would use fractions.Fraction instead, but Numpy complained saying that "object arrays are not supported".
A pity, this seemed the way to go, although surely there would be a loss of performance.</p>
<p>There is another side of this problem: it would be nice to be able to create dictionaries where the key is a time of the same kind, and I fear when I search
using a float as a key the same, some searches would fail due to the same issue.</p>
<p>My last idea was to use dates, like datetime.date, but I an not too happy with it because of the ambiguity when converting the difference between dates
to year fractions.</p>
<p>What would be the best approach for this, is there a nice solution?</p>
| 0 | 2016-08-05T11:35:11Z | 38,789,092 | <p>I think there is just no easy way out of this.
Floats are fundamentally not suitable to be checked for equality, and by evaluating your interpolation on the edges of its domain (or using floats as keys in dictionaries), you are doing exactly this.</p>
<p>Your solution using epsilons is a bit hacky, but honestly there probably is no more elegant way of working around this problem. </p>
<p>In general, having to check floats for equality can be a symptom of a bad design choice. You recognized this, because you mentioned that you were thinking of using datetime.date. (Which I agree, is overkill.)</p>
<p>The best way to go is to accept that the interpolation is not defined on the edges of its domain and to work this assumption into the design of the program. The exact solution then depends on what you want to do.</p>
<p>Did you consider using seconds or days instead of years? Maybe by using seconds, you can avoid querying your interpolation at the borders of its definition range? If you only use integer values of seconds, you can easily use them as keys in your dictionary.</p>
| 1 | 2016-08-05T12:19:18Z | [
"python",
"numpy",
"floating-point",
"interpolation"
] |
Regex search For HTML Tag with UUID | 38,788,319 | <p>I'm trying to match a single HTML tag with an <code>id</code> attribute which is a UUID. I tested it with an external resource to make sure the regex is correct with the same input string. The UUID is extracted dynamically so the string replacement is necessary. </p>
<p>The output I would would expect is for the last line to print:</p>
<pre><code><tr class="ref_row" id="b9060ff1-015d-4089-a193-8fef57e7c2ef">
</code></pre>
<p>This is the code I tried:</p>
<pre><code>content = '<tbody><tr class="ref_row" id="b9060ff1-015d-4089-a193-8fef57e7c2ef"><td><b>01/08/2016 14:41:00</b></td>'
ref = 'b9060ff1-015d-4089-a193-8fef57e7c2ef'
regex = '<[^>]+?id=\"%s\"[^<]*?>' % ref
element_to_link = re.search(regex, content)
print element_to_link.string
</code></pre>
<p>The output I get when printing is the whole input string, which would suggest the regex is incorrect. What's going on here?</p>
<p>Please don't suggest that I use Beautiful Soup, this should be possible with regular expressions.</p>
| -3 | 2016-08-05T11:36:51Z | 38,788,708 | <p>Why won't you use group method? This works for me:</p>
<pre><code>element_to_link.group(0)
</code></pre>
| 0 | 2016-08-05T11:57:44Z | [
"python",
"regex"
] |
Regex search For HTML Tag with UUID | 38,788,319 | <p>I'm trying to match a single HTML tag with an <code>id</code> attribute which is a UUID. I tested it with an external resource to make sure the regex is correct with the same input string. The UUID is extracted dynamically so the string replacement is necessary. </p>
<p>The output I would would expect is for the last line to print:</p>
<pre><code><tr class="ref_row" id="b9060ff1-015d-4089-a193-8fef57e7c2ef">
</code></pre>
<p>This is the code I tried:</p>
<pre><code>content = '<tbody><tr class="ref_row" id="b9060ff1-015d-4089-a193-8fef57e7c2ef"><td><b>01/08/2016 14:41:00</b></td>'
ref = 'b9060ff1-015d-4089-a193-8fef57e7c2ef'
regex = '<[^>]+?id=\"%s\"[^<]*?>' % ref
element_to_link = re.search(regex, content)
print element_to_link.string
</code></pre>
<p>The output I get when printing is the whole input string, which would suggest the regex is incorrect. What's going on here?</p>
<p>Please don't suggest that I use Beautiful Soup, this should be possible with regular expressions.</p>
| -3 | 2016-08-05T11:36:51Z | 38,789,334 | <p>From the Python re module documentation the <a href="https://docs.python.org/2/library/re.html#re.MatchObject.string" rel="nofollow">MatchObject.string</a> property returns "The string passed to match() or search().". Use one of the methods of MatchObject such as group(), groups() or groupdict().</p>
| 0 | 2016-08-05T12:31:07Z | [
"python",
"regex"
] |
Trying to scrape tripadvisor members using BeautifulSoup | 38,788,367 | <p>So Im trying to scrape this users profile for his ratings on hotels & restaurants separately
<a href="https://www.tripadvisor.in/members-reviews/rahuls896" rel="nofollow">https://www.tripadvisor.in/members-reviews/rahuls896</a></p>
<p>Now the problem is that its showing me all reviews by default when Im reading it via BeautiFulsoup. Thus by default the <strong>class="active"</strong> is assigned to <strong>"REVIEWS_ALL"</strong>. </p>
<pre><code><li data-filter="REVIEWS_ALL" class="active">All</li>
<li data-filter="REVIEWS_HOTELS">Hotels (1)</li>
<li data-filter="REVIEWS_RESTAURANTS">Restaurants (1)</li>
</code></pre>
<p>But I'd like the <strong>class="active"</strong> be assigned to <strong>"REVIEWS_HOTELS"</strong></p>
<pre><code><li data-filter="REVIEWS_ALL">All</li>
<li data-filter="REVIEWS_HOTELS" class="active">Hotels (1)</li>
<li data-filter="REVIEWS_RESTAURANTS">Restaurants (1)</li>
</code></pre>
<p>How can I achieve this automation ?</p>
| 0 | 2016-08-05T11:39:08Z | 38,789,834 | <p>Just try scraping the entire content for the user, then segregate them as per your requirement.</p>
<pre><code>from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://www.tripadvisor.in/members-reviews/rahuls896')
next_button = driver.find_element_by_id("cs-paginate-next")
next_button.click()
</code></pre>
| 0 | 2016-08-05T12:57:44Z | [
"python",
"web-scraping",
"beautifulsoup",
"bs4"
] |
read_csv with parse_date not recognising dates? | 38,788,398 | <p>I have a CSV file that looks like this:</p>
<pre><code>date,important
July 2015,True
August 2015,False
</code></pre>
<p>But when I try to read it into pandas using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">read_csv</a> with the <code>parse_dates</code> flag, it isn't parsing the date column as dates:</p>
<pre><code>df = pd.read_csv('test.csv', parse_dates=True)
df
date important
0 July 2015 True
1 August 2015 False
</code></pre>
<p>I guess this is because they aren't date objects in a recognised format, but is there any way around this?</p>
<p>I can use <code>df.date = pd.to_datetime(df.date)</code> just fine, so I find it odd that I can't do that on import. </p>
| 0 | 2016-08-05T11:41:28Z | 38,788,438 | <p>By default, it parses the index as date and there is no index specified here. Either pass <code>index_col=0</code> or specify the name of the column:</p>
<pre><code>df = pd.read_csv('test.csv', parse_dates=['date'])
df
Out[30]:
date important
0 2015-07-01 True
1 2015-08-01 False
</code></pre>
<p>Or</p>
<pre><code>df = pd.read_csv('test.txt', parse_dates=True, index_col=0)
df
Out[33]:
important
date
2015-07-01 True
2015-08-01 False
</code></pre>
| 1 | 2016-08-05T11:43:47Z | [
"python",
"pandas"
] |
Parse entire directory Etree Parse lxml | 38,788,554 | <p>I need to parse txt files with xml markup in a directory (I already created a corpus with glob), yet etree parse only allows one file at a time. How do I set up a loop to parse all files at once? The goal then is to add these files to Elasticsearch using requests. This is what I have so far:</p>
<pre><code>import json
import os
import re
from lxml import etree
import xmltodict
import glob
corpus=glob.glob('path/*.txt')
ns=dict(tei="http://www.tei-c.org/ns/1.0")
tree = etree.ElementTree(file='path/file.txt')
doc = {
"author": tree.xpath('//tei:author/text()', namespaces=ns)[0],
"title": tree.xpath('//tei:title/text()', namespaces=ns)[0],
"content": "".join(tree.xpath('//tei:text/text()', namespaces=ns))
}
</code></pre>
| -1 | 2016-08-05T11:50:32Z | 38,791,814 | <p>Simply iterate on the <code>corpus</code> list. However, you will want to use a container such as a list or dictionary to hold the individually parsed data. Below assumes .txt files are well-formed .xml files and maintain same structure including <code>tei</code> namespace:</p>
<pre><code>import os, glob
from lxml import etree
corpus = glob.glob('path/*.txt')
ns = dict(tei="http://www.tei-c.org/ns/1.0")
xmlList = []; xmlDict = {}
for file in corpus:
tree = etree.parse(file)
doc = {
"author": tree.xpath('//tei:author/text()', namespaces=ns)[0],
"title": tree.xpath('//tei:title/text()', namespaces=ns)[0],
"content": "".join(tree.xpath('//tei:text/text()', namespaces=ns))
}
# LIST OF DOC DICTS
xmlList.append(doc)
# DICTIONARY OF DOC DICTS, KEY IS FILE NAME
key = os.path.basename(file).replace('.txt', '')
xmlDict[key] = doc
</code></pre>
| 0 | 2016-08-05T14:34:53Z | [
"python",
"xml",
"lxml",
"elementtree",
"jupyter"
] |
Check remote file existence using wildcards -Python | 38,788,712 | <p>I am trying to write a python script to check whether a remote file exists, if not wait until it appears. For the file name I use a wild card. This is what I have tried until now.</p>
<pre><code>import paramiko
transport = paramiko.Transport("10.1.200.213")
transport.connect(username="user", password='password')
sftp=paramiko.SFTPClient.from_transport(transport)
filestat=sftp.stat('/home/jboss-6.4/standalone/deployments/\*ear')
</code></pre>
<p>But this pops an error,</p>
<pre><code> File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 337, in stat
t, msg = self._request(CMD_STAT, path)
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 624, in _request
return self._read_response(num)
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 671, in _read_response
self._convert_status(msg)
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 697, in _convert_status
raise IOError(errno.ENOENT, text)
IOError: [Errno 2] No such file
</code></pre>
<p>How can I use a wildcard to check the remote file existence?</p>
| 0 | 2016-08-05T11:58:00Z | 38,789,493 | <p>There are two ways to do it.</p>
<pre><code>import os
os.path.exists('./file.txt') # True
</code></pre>
<p>Another way that's with wildcard is Using <a href="https://docs.python.org/2/library/glob.html" rel="nofollow">glob function</a></p>
<pre><code>>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
</code></pre>
<p>After the Glob function has given you list of files matching that wildcard in that dir you can just use:</p>
<pre><code>if <file_name> in <list_given_by_glob>:
pass
</code></pre>
| -1 | 2016-08-05T12:39:59Z | [
"python",
"wildcard",
"paramiko",
"pysftp"
] |
Assign a serial number when quantity is more than one | 38,788,754 | <p>I have a model in which a unique serial number is generated, and there is a quantity field in which the user can select how many parts they'd like made. Think of it like a shopping order. I'd like that if the user selects a quantity of more than one, a serial number be assigned to each individual part.
Models:</p>
<pre><code>from __future__ import unicode_literals
from tande.models import Project, Person
from django.db import models
from django.utils import timezone
from django.utils.text import slugify
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.db.models.signals import pre_save
from django.conf import settings
# Create your models here.
class buildrisk(models.Model):
risk = models.CharField(max_length=20, default = 'Select Risk')
def __unicode__ (self):
return self.risk
class sens(models.Model):
sens = models.CharField(max_length=20, default = 'Select Sensitivity')
def __unicode__ (self):
return self.sens
class MOI(models.Model):
method = models.CharField(max_length=20, default = 'Select Method')
def __unicode__ (self):
return self.method
def number():
no = PartRequest.objects.count()
if no == None:
return "PR00001"
else:
return "PR00" + str(no + 100)
def snumber():
no = PartRequest.objects.count()
add = sum(map(int, str(no)))
if no == None:
return "SN00001"
else:
return "SN00" + str(no + 100 + add)
# while n:
# sn, n = sn + n % 10, n // 10
# return sn
class PartRequest(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
part_request_number = models.CharField(_('Part Request Number'),max_length=10, default = number)
serialnumber = models.CharField(_('Serial Number'),max_length=10, default= snumber)
project_manager = models.ForeignKey(Person, related_name = 'Manager', null = True)
requester = models.ForeignKey(Person, related_name = 'Requester', null = True) #drop down
project_id = models.ForeignKey(Project, related_name = 'Project', null=True)
ordernumber = models.PositiveIntegerField(_('Order Number'), default=0)
description = models.CharField(_('Description'), max_length=500)
quantityrequired = models.PositiveIntegerField(_('Quantity'), default=0)
sensitivity = models.ForeignKey(sens, related_name='sensitivity', null=True) #drop down
identification_method = models.ForeignKey(MOI, related_name= 'MOI', null=True)
build_risk = models.ForeignKey(buildrisk, related_name= 'Risk', null=True)
daterequired = models.DateField(_('Date Required'), default = '04/08/16')
slug = models.SlugField(unique=True, null=True)
def __str__(self):
return unicode(self.requester)
def get_absolute_url(self):
return "/buildpage/%s/" %(self.slug)
#return ("buildpage:page3", kwargs = {"slug": self.slug})
def create_slug(instance, new_slug=None):
slug = slugify(instance.part_request_number)
if new_slug is not None:
slug = new_slug
qs = PartRequest.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_receiver, sender = PartRequest)
</code></pre>
<p>Views: </p>
<pre><code>from django.shortcuts import render, get_object_or_404, redirect, get_object_or_404
from django.contrib import messages
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import RequestContext, loader
from django.contrib.auth.decorators import login_required
from .forms import PartRequestForm
from .models import PartRequest
from tande.models import Project, Person
# Create your views here.
@login_required
def home(request):
latest_project_list = Project.objects.all()
context = {'latest_project_list': latest_project_list}
return render(request, 'buildpage/home.html', context)
def partrequestinfo(request):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
req_form = PartRequestForm(request.POST or None, request.FILES or None)
if req_form.is_valid():
instance = req_form.save(commit=False)
instance.user = request.user
print request.POST
print req_form.cleaned_data.get("requester")
print instance
instance.save()
messages.success(request, "Successfully Created")
return HttpResponseRedirect(instance.get_absolute_url())
else:
context = {
"req_form": req_form
}
return render(request, "buildpage/partrequestinfo.html", context)
def partrequestdetail(request, slug=None):
print "in partrequestdetail function"
instance = get_object_or_404(PartRequest, slug=slug)
context = {
"project_id": instance.project_id,
"instance": instance,
}
return render(request, 'buildpage/partrequestdetail.html', context)
def partrequestupdate(request, slug=None):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
instance = get_object_or_404(PartRequest, slug=slug)
req_form = PartRequestForm(request.POST or None, request.FILES or None, instance=instance)
if req_form.is_valid():
instance = req_form.save(commit=False)
print request.POST
print req_form.cleaned_data.get("requester")
print instance
instance.save()
messages.success(request, "Saved")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"project_id": instance.project_id,
"instance": instance,
"req_form": req_form,
}
return render(request, 'buildpage/partrequestinfo.html', context)
def partrequestdelete(request, slug=None):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
instance = get_object_or_404(PartRequest, slug=slug)
messages.success(request, "Successfully Deleted")
return redirect("buildpage:home")
def preparebuildlist(request, slug=None):
return render(request, 'buildpage/preparebuildlist.html')
</code></pre>
| -1 | 2016-08-05T12:00:25Z | 38,793,386 | <p>I can't really understand your models, but I think what you need (if you don't already have it) is a <code>Part</code> model. Have one field in the <code>Part</code> model be the serial number of the part, which can be automatically generated if you want, and so when a user requests X number of parts you can just create and save X <code>Part</code> objects.</p>
| 0 | 2016-08-05T15:57:09Z | [
"python",
"django"
] |
Pandas: AttributeError: 'str' object has no attribute 'iloc' | 38,788,771 | <p>I need to convert columns from unicode to str.
I try</p>
<pre><code>f.edge(str(group['subdomain']).iloc[i], str(group['subdomain'].iloc[i+1]),
label=str(group['search_term'].iloc[i+1]))
</code></pre>
<p>But it returns <code>AttributeError: 'str' object has no attribute 'iloc'</code>
How can I fix that?</p>
| -1 | 2016-08-05T12:01:09Z | 38,788,807 | <p>You're casting before accessing the <code>iloc</code> attribute:</p>
<pre><code>str(group['subdomain']).iloc[i]
# ^
</code></pre>
<p>Move the parenthesis farther to the right:</p>
<pre><code>str(group['subdomain'].iloc[i])
</code></pre>
| 1 | 2016-08-05T12:03:03Z | [
"python",
"pandas"
] |
Extract affine part of SymPy expression | 38,788,781 | <p>I have a sympy expression with one variable <code>x</code>, e.g.,</p>
<pre><code>import sympy
x = sympy.Symbol('x')
f = 3*x**2 + 5*x + 7 + sympy.exp(x)
</code></pre>
<p>I'd like to programmatically extract the <em>affine</em> part of that expression, i.e., the part that does not depend on <code>x</code>; <code>7</code> in the above example. Note that some terms may be nonlinear.</p>
<p>Any hints?</p>
| 0 | 2016-08-05T12:01:56Z | 38,788,894 | <p>If I understood you correctly, you need to use <a href="http://docs.sympy.org/0.7.6/modules/core.html#sympy.core.expr.Expr.coeff" rel="nofollow"><code>coeff</code></a>:</p>
<pre><code>>>> import sympy
>>> x = sympy.Symbol('x')
>>> f = 2*(3*x**2 + 5*x + 7 + sympy.exp(x))
>>> f.coeff(x, 0)
14
</code></pre>
<p>If you have an expression with multiple variables, you may try <a href="http://docs.sympy.org/0.7.6/modules/core.html#sympy.core.add.Add.as_coefficients_dict" rel="nofollow"><code>as_coefficients_dict</code></a>:</p>
<pre><code>>>> import sympy
>>> x = sympy.Symbol('x')
>>> y = sympy.Symbol('y')
>>> f = 4 + 3 * (2 * x + 4 * y + 3 * x * y + sympy.exp(x + y) + 6)
>>> coeffs = f.as_coefficients_dict()
>>> coeffs
defaultdict(<class 'int'>, {exp(x + y): 3, 1: 22, y: 12, x: 6, x*y: 9})
>>> coeffs[1]
22 # 4 + 3 * 6
</code></pre>
| 2 | 2016-08-05T12:08:07Z | [
"python",
"sympy"
] |
what's mean "error: [Errno 2] No such file or directory: 'src/webkit_server'"? | 38,788,816 | <p>I need to install dryscrape for python but I got error, what's the problem?</p>
<pre><code>C:\Users\parvij\Anaconda3\Scripts>pip install dryscrape
</code></pre>
<p>I got this:</p>
<pre><code>Collecting dryscrape
Collecting webkit-server>=1.0 (from dryscrape)
Using cached webkit-server-1.0.tar.gz
Collecting xvfbwrapper (from dryscrape)
Requirement already satisfied (use --upgrade to upgrade): lxml in c:\users\parvij\anaconda3\lib\site-packages (from dryscrape)
Building wheels for collected packages: webkit-server
Running setup.py bdist_wheel for webkit-server ... error
Complete output from command c:\users\parvij\anaconda3\python.exe -u -c"import setuptools,tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d C:\Users\parvij\AppData\Local\Temp\tmp71w59qv6pip-wheel- --python-tag cp35:
running bdist_wheel
running build
'make' is not recognized as an internal or external command,
operable program or batch file.
error: [Errno 2] No such file or directory: 'src/webkit_server'
----------------------------------------
Failed building wheel for webkit-server
Running setup.py clean for webkit-server
Failed to build webkit-server
Installing collected packages: webkit-server, xvfbwrapper, dryscrape
Running setup.py install for webkit-server ... error
Complete output from command c:\users\parvij\anaconda3\python.exe -u -c"import setuptools,tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open',open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\parvij\AppData\Local\Temp\pip-tyzalid7-record\install-record.txt --single-version-externally-managed --compile:
running install
running build
'make' is not recognized as an internal or external command,
operable program or batch file.
error: [Errno 2] No such file or directory: 'src/webkit_server'
----------------------------------------
Command "c:\users\parvij\anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\parvij\AppData\Local\Temp\pip-tyzalid7-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\parvij\AppData\Local\Temp\pip-build-o7nlv0dz\webkit-server\
</code></pre>
<p>my operating system is windows 8</p>
<p>my python version is 3.5</p>
| 1 | 2016-08-05T12:03:40Z | 38,789,024 | <p>From the <a href="http://dryscrape.readthedocs.io/en/latest/installation.html" rel="nofollow">doc</a>, you have to installed also <a href="https://github.com/niklasb/dryscrape/blob/master/requirements.txt" rel="nofollow">requirements</a>.
You can do this as follow</p>
<pre><code>pip install -r requirements.txt
</code></pre>
<p>After this retry to install <strong>dryscrape</strong>.</p>
| 0 | 2016-08-05T12:15:56Z | [
"python",
"python-3.x",
"package",
"install"
] |
Adding Current date to Custom Widget fields | 38,788,819 | <p>I have a custom widget with Date fields and Time Fields, <code>D/M/Y, H/M(24hour)</code>. Now, on create event which is where these are used it come up with their empty_label value that i have setup.</p>
<p>I want this Empty_value to be the current day, current month. BUT i don't know if these will be stored if the user leaves the options alone and clicks save.</p>
<p>So i guess my real question is how would i put the current date /time into the select fields as an option they can select without touching them</p>
<p>Here is part of the code that i think will need to be edited...</p>
<pre><code>class SelectDateTimeWidget(forms.MultiWidget):
supports_microseconds = False
def __init__(self, attrs=None, date_format=None, time_format=None):
widgets = (SelectDateWidget(empty_label=( "Year", "Month", "Day")),
SelectTimeWidget(use_seconds=False))
super(SelectDateTimeWidget, self).__init__(widgets, attrs)
</code></pre>
| 2 | 2016-08-05T12:03:47Z | 38,790,123 | <p>What you want is not to set the current date as "empty label", this would make no sense. Empty is empty, not current date. What you want to do is to select the current date by default, which is done by <a href="https://docs.djangoproject.com/en/stable/ref/forms/api/#dynamic-initial-values" rel="nofollow"><code>Form.initial</code></a>:</p>
<pre><code>from django.utils import timezone
form = YourForm(initial={'the_date_field': timezone.now()})
</code></pre>
| 1 | 2016-08-05T13:10:05Z | [
"python",
"django"
] |
Creating a copy of a function with some vars fixed | 38,788,869 | <p>Assume I have a function</p>
<pre><code>def multiply_by(x, multiplier):
return x * multiplier
</code></pre>
<p>How can I create a copy of that function and fix the multiplier in that function?</p>
<pre><code>multiply_by_5 = multiply_by? <-- here I need python magic
</code></pre>
<p>such that multiply_by_5 would have only one argument x and the multiplier would be 5? So that</p>
<pre><code>multiply_by_5(2)
10
</code></pre>
<p>Is there a way in Python 2.7 to do that?</p>
| 2 | 2016-08-05T12:06:29Z | 38,788,966 | <p>You can use <a href="https://docs.python.org/2/library/functools.html#functools.partial" rel="nofollow"><code>functools.partial</code></a> with keyword argument:</p>
<pre><code>>>> def multiply_by(x, multiplier):
... return x * multiplier
...
>>> from functools import partial
>>> multiply_by_5 = partial(multiply_by, multiplier=5)
>>> multiply_by_5(2)
10
</code></pre>
| 3 | 2016-08-05T12:12:14Z | [
"python",
"python-2.7",
"closures"
] |
Creating a copy of a function with some vars fixed | 38,788,869 | <p>Assume I have a function</p>
<pre><code>def multiply_by(x, multiplier):
return x * multiplier
</code></pre>
<p>How can I create a copy of that function and fix the multiplier in that function?</p>
<pre><code>multiply_by_5 = multiply_by? <-- here I need python magic
</code></pre>
<p>such that multiply_by_5 would have only one argument x and the multiplier would be 5? So that</p>
<pre><code>multiply_by_5(2)
10
</code></pre>
<p>Is there a way in Python 2.7 to do that?</p>
| 2 | 2016-08-05T12:06:29Z | 38,788,974 | <p><a href="https://docs.python.org/3/library/functools.html#functools.partial" rel="nofollow">functools.partial</a> is made exactly for this.</p>
<p>you can use it like</p>
<pre><code>import functools
multiply_by_5=functools.partial(multiply_by,multiplier=5)
</code></pre>
| 2 | 2016-08-05T12:12:53Z | [
"python",
"python-2.7",
"closures"
] |
Creating a copy of a function with some vars fixed | 38,788,869 | <p>Assume I have a function</p>
<pre><code>def multiply_by(x, multiplier):
return x * multiplier
</code></pre>
<p>How can I create a copy of that function and fix the multiplier in that function?</p>
<pre><code>multiply_by_5 = multiply_by? <-- here I need python magic
</code></pre>
<p>such that multiply_by_5 would have only one argument x and the multiplier would be 5? So that</p>
<pre><code>multiply_by_5(2)
10
</code></pre>
<p>Is there a way in Python 2.7 to do that?</p>
| 2 | 2016-08-05T12:06:29Z | 38,788,976 | <p>If you cannot change the <code>multiply_by()</code> function, the simplest and perhaps best way is probably</p>
<pre><code>def multiply_by_5(x):
return multiply_by(x, 5)
</code></pre>
<p>You can also use <code>lambda</code> if you really want a one-liner.</p>
<p>However, you may want to change your first function to</p>
<pre><code>def multiply_by(x, multiplier = 5):
return x * multiplier
</code></pre>
<p>Then you can do either of these:</p>
<pre><code>print(multiply_by(4, 3))
12
print(multiply_by(2))
10
</code></pre>
| 0 | 2016-08-05T12:12:55Z | [
"python",
"python-2.7",
"closures"
] |
Creating a copy of a function with some vars fixed | 38,788,869 | <p>Assume I have a function</p>
<pre><code>def multiply_by(x, multiplier):
return x * multiplier
</code></pre>
<p>How can I create a copy of that function and fix the multiplier in that function?</p>
<pre><code>multiply_by_5 = multiply_by? <-- here I need python magic
</code></pre>
<p>such that multiply_by_5 would have only one argument x and the multiplier would be 5? So that</p>
<pre><code>multiply_by_5(2)
10
</code></pre>
<p>Is there a way in Python 2.7 to do that?</p>
| 2 | 2016-08-05T12:06:29Z | 38,789,095 | <p>As suggested by @niemmi's <a href="http://stackoverflow.com/a/38788966/2289509">answer</a>, <code>functools.partial</code> is probably the way to go. </p>
<p>However, similar work can be done using curried functions:</p>
<pre><code>def multiply_by(multiplier):
def multiply(x):
return multiplier * x
return multiply
>>> multiply_by_5 = multiply_by(5) # no magic
>>> multiply_by_5(2)
10
</code></pre>
<p>Or using the lambda syntax:</p>
<pre><code>def multiply_by(multiplier):
return lambda x: multiplier * x
</code></pre>
<p>Note that <code>partial</code> is more succinct, more efficient, and more directly express your intent in a standard way. The above technique is an example of the concept called closure, which is means that a function defined in inner scope may refer to variables defined in enclosing scopes, and "close" over them, remembering them, and even mutating them.</p>
<p>Since this technique is more general, it might take the reader of your code more time to understand what exactly do you mean in your code, since your code may be arbitrarily complicated.</p>
<hr>
<p>Specifically for multiplication (and other operators) <code>partial</code> can be combined with <code>operator.mul</code>:</p>
<pre><code>>>> import functools, operator
>>> multiply_by_5 = functools.partial(operator.mul, 5)
>>> multiply_by_5(2)
10
</code></pre>
| 2 | 2016-08-05T12:19:23Z | [
"python",
"python-2.7",
"closures"
] |
Creating a copy of a function with some vars fixed | 38,788,869 | <p>Assume I have a function</p>
<pre><code>def multiply_by(x, multiplier):
return x * multiplier
</code></pre>
<p>How can I create a copy of that function and fix the multiplier in that function?</p>
<pre><code>multiply_by_5 = multiply_by? <-- here I need python magic
</code></pre>
<p>such that multiply_by_5 would have only one argument x and the multiplier would be 5? So that</p>
<pre><code>multiply_by_5(2)
10
</code></pre>
<p>Is there a way in Python 2.7 to do that?</p>
| 2 | 2016-08-05T12:06:29Z | 38,789,297 | <p>Here's an alternative that doesn't use <code>functools.partial</code>. Instead we define a function inside a function. The inner function "remembers" any of the local variables of the outer function that it needs (including the outer function's arguments). The magic that makes this happen is called <a href="https://en.wikipedia.org/wiki/Closure_%28computer_programming%29" rel="nofollow">closure</a>. </p>
<pre><code>def multiply_factory(multiplier):
def fixed_multiply(x):
return x * multiplier
return fixed_multiply
multiply_by_3 = multiply_factory(3)
multiply_by_5 = multiply_factory(5)
for i in range(5):
print(i, multiply_by_3(i), multiply_by_5(i))
</code></pre>
<p><strong>output</strong></p>
<pre><code>0 0 0
1 3 5
2 6 10
3 9 15
4 12 20
</code></pre>
<p>If you want, you can use your existing <code>multiply_by</code> function in the closure, although that's slightly less efficient, due to the overhead of an extra function call. Eg:</p>
<pre><code>def multiply_factory(multiplier):
def fixed_multiply(x):
return multiply_by(x, multiplier)
return fixed_multiply
</code></pre>
<p>That can be written more compactly using <code>lambda</code> syntax:</p>
<pre><code>def multiply_factory(multiplier):
return lambda x: multiply_by(x, multiplier)
</code></pre>
| 2 | 2016-08-05T12:29:07Z | [
"python",
"python-2.7",
"closures"
] |
Tensorflow 'features' format | 38,788,912 | <p>I'm a total begginer with AI and tensorflow, so please forgive if this is a dumb question.
I've trained a tensorflow network using a script based on this tutorial:</p>
<p><a href="https://www.tensorflow.org/versions/r0.10/tutorials/wide_and_deep/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.10/tutorials/wide_and_deep/index.html</a></p>
<p>I believe training was ok.
Now I whant to run this method to make a prediction for a single input:</p>
<pre><code>tf.contrib.learn.DNNClassifier.predict_proba(x=x)
</code></pre>
<p>But I cannot find any documentation on how to build the "x" parameter...
I tryed: </p>
<pre><code> x = {k: tf.SparseTensor(indices=[[0, 0]], values=[d_data[k]], shape=[1, 1]) for k in COLUMNS}
</code></pre>
<p>Where:
<strong>d_data</strong> is a dictionary containing about 150 key/value pairs.
<strong>COLUMNS</strong> is a list with all the keys needed.
This same setup was used to train the network.</p>
<p>But got the error: </p>
<pre><code>AttributeError: 'dict' object has no attribute 'dtype'
</code></pre>
<p>So... x should not be a 'dict'... but what should it be then?
Can anyone give me some directions?</p>
<p>Thanks a lot.</p>
| 2 | 2016-08-05T12:09:27Z | 38,794,950 | <p>The BaseEstimator class has better <a href="https://github.com/tensorflow/tensorflow/blob/5c44302d778f43a13bf1b97bffd0b2b6be46ae2f/tensorflow/contrib/learn/python/learn/estimators/estimator.py#L369" rel="nofollow">documentation</a>.</p>
<pre><code>x: Matrix of shape [n_samples, n_features...]. Can be iterator that returns arrays of features. The training input samples for fitting the model. If set, `input_fn` must be `None`.
</code></pre>
<p>I will looking into getting the documentation here fixed. Thanks for pointing out.</p>
| 2 | 2016-08-05T17:36:19Z | [
"python",
"artificial-intelligence",
"tensorflow"
] |
Tensorflow 'features' format | 38,788,912 | <p>I'm a total begginer with AI and tensorflow, so please forgive if this is a dumb question.
I've trained a tensorflow network using a script based on this tutorial:</p>
<p><a href="https://www.tensorflow.org/versions/r0.10/tutorials/wide_and_deep/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.10/tutorials/wide_and_deep/index.html</a></p>
<p>I believe training was ok.
Now I whant to run this method to make a prediction for a single input:</p>
<pre><code>tf.contrib.learn.DNNClassifier.predict_proba(x=x)
</code></pre>
<p>But I cannot find any documentation on how to build the "x" parameter...
I tryed: </p>
<pre><code> x = {k: tf.SparseTensor(indices=[[0, 0]], values=[d_data[k]], shape=[1, 1]) for k in COLUMNS}
</code></pre>
<p>Where:
<strong>d_data</strong> is a dictionary containing about 150 key/value pairs.
<strong>COLUMNS</strong> is a list with all the keys needed.
This same setup was used to train the network.</p>
<p>But got the error: </p>
<pre><code>AttributeError: 'dict' object has no attribute 'dtype'
</code></pre>
<p>So... x should not be a 'dict'... but what should it be then?
Can anyone give me some directions?</p>
<p>Thanks a lot.</p>
| 2 | 2016-08-05T12:09:27Z | 38,902,557 | <p>I got the same error but I think this is because we are using an older release of tensorflow (I am on 0.8.0) and the fit method now can take a different input type 'input_fn' which I think can take the form of a dictionary, see <a href="https://github.com/tensorflow/tensorflow/blob/5c44302d778f43a13bf1b97bffd0b2b6be46ae2f/tensorflow/contrib/learn/python/learn/estimators/estimator.py#L197" rel="nofollow">here</a></p>
<pre><code> def fit(self, x=None, y=None, input_fn=None, steps=None, batch_size=None,
monitors=None, max_steps=None):
</code></pre>
<p>In my current release this function doesn't have 'input_fn', hence why it is mandatory to input a tensor matrix object as x.</p>
<p>Did you manage to find a solution in the meantime?</p>
| 0 | 2016-08-11T17:22:09Z | [
"python",
"artificial-intelligence",
"tensorflow"
] |
python multiprocessing.Queue.put/get's block parameter | 38,788,955 | <p>That is the Official Docs about multiprocessing.Queue.get</p>
<blockquote>
<p>get([block[, timeout]])</p>
<p>Remove and return an item from the queue. If
optional args block is True (the default) and timeout is None (the
default), block if necessary until an item is <code>available</code>. If timeout
is a positive number, it blocks at most timeout seconds and raises the
Queue.Empty exception if no item was available within that time.
Otherwise (block is False), return an item if one is <code>immediately
available</code>, else raise the Queue.Empty exception (timeout is ignored
in that case).</p>
</blockquote>
<p>The question is what is the difference between <code>available</code> and <code>immediately available</code></p>
<p>Thanks in advance.í ½í¸</p>
| 0 | 2016-08-05T12:11:39Z | 38,789,203 | <blockquote>
<p>block if necessary until an item is available</p>
</blockquote>
<p>This simply means <code>Queue</code> is empty when you make the request and it will be blocked until you add an item to the <code>Queue</code>, unless you pass the argument <code>block = False</code> or set some <code>Timeout</code>.</p>
<blockquote>
<p>immediately available</p>
</blockquote>
<p>This means, there is some item on <code>Queue</code> when you make the request and it will be returned immediately.</p>
| 1 | 2016-08-05T12:24:07Z | [
"python"
] |
python multiprocessing.Queue.put/get's block parameter | 38,788,955 | <p>That is the Official Docs about multiprocessing.Queue.get</p>
<blockquote>
<p>get([block[, timeout]])</p>
<p>Remove and return an item from the queue. If
optional args block is True (the default) and timeout is None (the
default), block if necessary until an item is <code>available</code>. If timeout
is a positive number, it blocks at most timeout seconds and raises the
Queue.Empty exception if no item was available within that time.
Otherwise (block is False), return an item if one is <code>immediately
available</code>, else raise the Queue.Empty exception (timeout is ignored
in that case).</p>
</blockquote>
<p>The question is what is the difference between <code>available</code> and <code>immediately available</code></p>
<p>Thanks in advance.í ½í¸</p>
| 0 | 2016-08-05T12:11:39Z | 38,789,231 | <p>In the first case where <code>block=True</code> is set, <code>"available"</code> means when an item is present on the queue and ready to be removed by <code>Queue.get()</code>. The point is that the thread/process will block <em>until</em> there is an item ready to be removed from the queue.</p>
<p>In the second case, <code>block=False</code> so the calling thread will <em>not</em> block if there is no item in the queue (no item is <code>"immediately available"</code> on the queue). Instead <code>Queue.get()</code> will raise <code>Queue.Empty</code> to signify that there is nothing on the queue to read. Your application needs to handle that exception, possibly by performing other tasks and then trying again later.</p>
| 1 | 2016-08-05T12:25:31Z | [
"python"
] |
Python multiprocessing & pathos: import error | 38,788,994 | <p>I am writing some python code using multiprocessing & pathos. I have written a small test program to get used to using the mutiprocessing, that runs fine on my local machine, but it refuses to run on a different cluster. </p>
<p>I am getting the following error:</p>
<pre><code>Traceback (most recent call last):
File "./multi.py", line 116, in <module>
pool = pathos_multiprocessing.Pool(processes=pool_size,maxtasksperchild=1,)
File "/usr/local/lib/python3.4/dist-packages/multiprocess/pool.py", line 150, in __init__
self._setup_queues()
File "/usr/local/lib/python3.4/dist-packages/multiprocess/pool.py", line 243, in _setup_queues
self._inqueue = self._ctx.SimpleQueue()
File "/usr/local/lib/python3.4/dist-packages/multiprocess/context.py", line 110, in SimpleQueue
from .queues import SimpleQueue
File "/usr/local/lib/python3.4/dist-packages/multiprocess/queues.py", line 22, in <module>
import _multiprocess as _multiprocessing
ImportError: No module named '_multiprocess'
</code></pre>
<p>but when I do a</p>
<pre><code>pip3 list
</code></pre>
<p>both pathos and multiprocessing modules are clearly there:</p>
<pre><code>multiprocess (0.70.4)
nbconvert (4.2.0)
nbformat (4.0.1)
nose (1.3.1)
notebook (4.2.0)
numpy (1.10.4)
oauthlib (0.6.1)
pathos (0.2.0)
</code></pre>
<p>Any bright ideas why this might be happening would be welcome!</p>
<p>The small test code is:</p>
<pre><code>#! /usr/bin/env python3
import pathos.multiprocessing as mp
import os
import random
class Pool_set:
def pool_fun(directory_name):
cwd=os.getcwd()
os.mkdir(str(directory_name))
directory=os.path.join(cwd,str(directory_name))
os.chdir(directory)
os.system('{}'.format('sleep '+str(directory_name)))
cwd2=os.getcwd()
print(cwd2)
test_file = open('test_file.out','w')
test_file.write(cwd2)
print("Finished in "+directory)
os.chdir(cwd)
if __name__ == '__main__':
config=[]
pool_set = Pool_set
for i in (random.sample(range(1,100),3)):
config.append(i)
pool_size = mp.cpu_count()
pool = mp.Pool(processes=pool_size,maxtasksperchild=1,)
pool_outputs = pool.map(pool_set.pool_fun,config)
pool.close()
pool.join()
</code></pre>
| 2 | 2016-08-05T12:13:58Z | 39,038,036 | <p>I'm the <code>pathos</code> and <code>multiprocess</code> author. I think there are two possible reasons you can't find <code>_multiprocess</code>. The first, and by far most common reason, is that you don't have a C++ compiler. <code>multiprocessing</code> needs a C++ complier, and if you are on Windows, you have to instal one. See: <a href="https://wiki.python.org/moin/WindowsCompilers" rel="nofollow">https://wiki.python.org/moin/WindowsCompilers</a>. The second is that it could not be found due to a <code>PATH</code>/<code>PYTHONPATH</code> issue with how it was installed if you mess with <code>prefix</code> etc, but that's the far minority case.</p>
| 0 | 2016-08-19T11:33:40Z | [
"python",
"multiprocessing",
"python-import",
"pathos"
] |
How to add custom function to admin forms? | 38,789,013 | <p>I would like to implement a function that updates <code>quantity</code> in <code>LibraryBook</code> each time the admin adds a book in <code>SingleBook</code> on the <code>admin</code> site. I have been searching for means to do so but to no avail. Any pointers including links to documentation would be very much appreciated.
Here is my code:</p>
<pre><code>#models.py
class LibraryBook(models.Model):
book_title = models.CharField(max_length=100, blank=False)
book_author_id = models.ForeignKey(BookAuthors, on_delete=models.CASCADE)
category = models.ForeignKey(BookCategory, on_delete=models.CASCADE)
quantity = models.IntegerField(blank=False, default=0)
number_borrowed = models.IntegerField(default=0)
def __unicode__(self):
return unicode(self.book_title)
class SingleBook(models.Model):
serial_number = models.CharField(primary_key=True , max_length=150, blank=False)
book_id = models.ForeignKey(LibraryBook, on_delete=models.CASCADE)
is_available_returned = models.BooleanField(default=True)
is_borrowed = models.BooleanField(default=False)
def __unicode__(self):
return unicode(self.book_id)
#admin.py
class SingleBookAdmin(admin.ModelAdmin):
list_display = ('book_id', 'serial_number')
class LibraryBookAdmin(admin.ModelAdmin):
list_display = ('book_title', 'book_author_id', 'quantity')
search_fields = ('book_title', 'book_author_id')
fields = ('book_title', 'book_author_id', 'quantity')
</code></pre>
<p>PS: I have omitted the import and <code>admin.site.register</code> code</p>
<pre><code>Django==1.9.8
django-material==0.8.0
django-model-utils==2.5.1
psycopg2==2.6.2
wheel==0.24.0
</code></pre>
| 2 | 2016-08-05T12:15:17Z | 38,789,694 | <p>Use <a href="https://docs.djangoproject.com/en/1.9/topics/signals/" rel="nofollow">signals</a>. Just attach <code>post_save</code> signal to <code>SingleBook</code> model and update according <code>LibraryBook</code> in it. <code>post_save</code> signal takes <code>created</code> argument, so you can determine if book is newly created or edited and apply your action based on that.</p>
<p>Also attach <code>post_delete</code> signal to decrease counter when <code>SingleBook</code> is removed.</p>
<p>To avoid race conditions (when 2 admins are adding books at the same time), I'm suggesting use of queryset <code>update</code> method together with <code>F</code> on changing <code>LibraryBook</code> counter, example:</p>
<pre><code>LibraryBook.objects.filter(id=single_book.book_id_id).update(quantity=F('quantity') + 1)
</code></pre>
<p>Doing it that way will ensure that actual math operation will be performed on database level.</p>
| 0 | 2016-08-05T12:50:59Z | [
"python",
"django",
"python-2.7",
"django-models",
"django-admin"
] |
How to add custom function to admin forms? | 38,789,013 | <p>I would like to implement a function that updates <code>quantity</code> in <code>LibraryBook</code> each time the admin adds a book in <code>SingleBook</code> on the <code>admin</code> site. I have been searching for means to do so but to no avail. Any pointers including links to documentation would be very much appreciated.
Here is my code:</p>
<pre><code>#models.py
class LibraryBook(models.Model):
book_title = models.CharField(max_length=100, blank=False)
book_author_id = models.ForeignKey(BookAuthors, on_delete=models.CASCADE)
category = models.ForeignKey(BookCategory, on_delete=models.CASCADE)
quantity = models.IntegerField(blank=False, default=0)
number_borrowed = models.IntegerField(default=0)
def __unicode__(self):
return unicode(self.book_title)
class SingleBook(models.Model):
serial_number = models.CharField(primary_key=True , max_length=150, blank=False)
book_id = models.ForeignKey(LibraryBook, on_delete=models.CASCADE)
is_available_returned = models.BooleanField(default=True)
is_borrowed = models.BooleanField(default=False)
def __unicode__(self):
return unicode(self.book_id)
#admin.py
class SingleBookAdmin(admin.ModelAdmin):
list_display = ('book_id', 'serial_number')
class LibraryBookAdmin(admin.ModelAdmin):
list_display = ('book_title', 'book_author_id', 'quantity')
search_fields = ('book_title', 'book_author_id')
fields = ('book_title', 'book_author_id', 'quantity')
</code></pre>
<p>PS: I have omitted the import and <code>admin.site.register</code> code</p>
<pre><code>Django==1.9.8
django-material==0.8.0
django-model-utils==2.5.1
psycopg2==2.6.2
wheel==0.24.0
</code></pre>
| 2 | 2016-08-05T12:15:17Z | 38,789,904 | <h2>override save_model</h2>
<p>If you only want to make the changes when an admin updates a record, the best way is to override the <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model" rel="nofollow">save_model</a> method in ModelAdmin</p>
<blockquote>
<p>The save_model method is given the HttpRequest, a model instance, a
ModelForm instance and a boolean value based on whether it is adding
or changing the object. Here you can do any pre- or post-save
operations.</p>
</blockquote>
<pre><code>class SingleBookAdmin(admin.ModelAdmin):
list_display = ('book_id', 'serial_number')
def save_model(self, request, obj, form, change):
admin.ModelAdmin.save_model(self, request, obj, form, change)
if obj.is_borrowed:
do something to obj.book_id.quantity
else:
do something to obj.book_id.quantity
</code></pre>
<h2>post_save signal</h2>
<pre><code>from django.dispatch.dispatcher import receiver
from django.db.models.signals import post_save
@receiver(post_save, sender=SingleBook)
def user_updated(sender,instance, **kwargs):
''' Fired when a SingleBook is updated or saved
we will use the opporunity to change quantity'''
# your logic here
</code></pre>
<h2>Other pointers</h2>
<p>If on the other hand, you wanted to make changes based on all user actions, catching the post_save signal is the way to go. In either case, you might want to override the <a href="https://docs.djangoproject.com/en/1.9/ref/models/instances/#django.db.models.Model.from_db" rel="nofollow">from_db</a> method in the model to keep track of which fields have changed.</p>
<p>You might also want to change <code>quantity</code> and <code>number_borrowed</code> to <code>IntegerFields</code> (unless you are only using sqlite in which case it doesn't matter)</p>
<p>Also <code>book_author_id</code> should probably be book_author and <code>book_id</code> should probably be book (this is not a rule, just a convention to avoid the ugly book_id_id reference)</p>
| 3 | 2016-08-05T13:00:16Z | [
"python",
"django",
"python-2.7",
"django-models",
"django-admin"
] |
Error installing mysql-connector-python on Amazon Linux AMI via pip-3.4 | 38,789,039 | <p>Apologies in advance if this is an easy fix, I have searched for an answer with no luck. </p>
<p>I'm trying to install the mysql-connector[-python] package on Amazon's Linux AMI. For my purposes, I want to use Python 3.4. I've installed Python 3.4 and pip-3.4 with yum and have successfully installed a few packages already:</p>
<pre><code> pip-3.4 list
</code></pre>
<p>gives</p>
<pre><code> numpy (1.11.1)
pip (6.1.1)
setuptools (25.1.4)
virtualenv (15.0.2)
</code></pre>
<p>However, when I try:</p>
<pre><code> sudo pip-3.4 install mysql-connector-python
</code></pre>
<p>I get</p>
<pre><code> Collecting mysql-connector-python
Could not find a version that satisfies the requirement mysql-connector-python (from versions: )
No matching distribution found for mysql-connector-python
</code></pre>
<p><code>sudo pip-3.4 install mysql-connector-python --allow-external mysql-connector-python</code> gives the same error. A google search suggested I use <code>sudo pip-3.4 install mysql-connector-python-rf --allow-external mysql-connector-python-rf</code> but then this gives the error: </p>
<pre><code> Collecting mysql-connector-python-rf
Using cached mysql-connector-python-rf-2.1.3.tar.gz
Installing collected packages: mysql-connector-python-rf
Running setup.py install for mysql-connector-python-rf
Complete output from command /usr/bin/python3.4 -c "import setuptools, tokenize;__file__='/tmp/pip-build-hotls6f7/mysql-connector-python-rf/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-wzpbgx5g-record/install-record.txt --single-version-externally-managed --compile:
usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: -c --help [cmd1 cmd2 ...]
or: -c --help-commands
or: -c cmd --help
error: option --single-version-externally-managed not recognized
----------------------------------------
Command "/usr/bin/python3.4 -c "import setuptools, tokenize;__file__='/tmp/pip-build-hotls6f7/mysql-connector-python-rf/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-wzpbgx5g-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-hotls6f7/mysql-connector-python-rf
</code></pre>
<p>I've tried a number of things, such as</p>
<pre><code> echo https://cdn.mysql.com/Downloads/Connector-Python/mysql-connector-python-2.1.3.tar.gz >> requirements.txt
sudo -H pip-3.4 install -r ./requirements.txt
</code></pre>
<p>which gives a similar error,</p>
<pre><code> sudo pip-3.4 install https://cdn.mysql.com/Downloads/Connector-Python/mysql-connector-python-2.1.3.tar.gz
</code></pre>
<p>which gives the same <code>error: option --single-version-externally-managed not recognized</code> error. I should also note that pip suggests I upgrade using <code>sudo pip-3.4 install --upgrade pip</code>, but when I do this pip breaks completely, even <code>pip-3.4 list</code> or <code>pip-3.4 --version</code> gives me <code>pkg_resources.VersionConflict: (pip 8.1.2 (/usr/local/lib/python3.4/site-packages), Requirement.parse('pip==6.1.1'))</code>. </p>
<p>I'm at a bit of loss as to what to do, any help would be greatly appreciated.</p>
| 1 | 2016-08-05T12:16:36Z | 38,789,416 | <p>Answering my own question here, I know it doesn't solve the problem I had directly, but I've managed to get mysql-connector installed so that, in Python3(.4), <code>import mysql.connector</code> doesn't give any errors. Here's what I did: </p>
<pre><code> wget http://cdn.mysql.com/Downloads/Connector-Python/mysql-connector-python-2.0.4.zip#md5=3df394d89300db95163f17c843ef49df
unzip mysql-connector-python-2.0.4.zip
cd mysql-connector-python-2.0.4
sudo python3 setup.py install
</code></pre>
<p>Now, in Python3:</p>
<pre><code> >>>import mysql.connector
>>>
</code></pre>
<p>I'm still curious as to why I had previously gotten the error <code>error: option --single-version-externally-managed not recognized</code>. My guess is that it's an issue with <code>setuptools</code>, but I had upgraded it to the newest version (as well as <code>virtualenv</code>). </p>
| 1 | 2016-08-05T12:35:40Z | [
"python",
"mysql",
"amazon-ec2",
"pip"
] |
Python multi module global variables. A bug in python? | 38,789,057 | <p>Recently I set up this example and am surprised by the results. I will demonstrate this with code:</p>
<p>File1: <strong>b.py</strong>:</p>
<pre><code>delta = 0.0
def example():
global delta
delta = 1
def ret_delta():
return delta
</code></pre>
<p>File2: <strong>a.py</strong>:</p>
<pre><code>from b import *
example()
#WHY ARE THESE DIFFERENT?
print(delta) # prints: 0.0
print(ret_delta()) # prints: 1
</code></pre>
<p>This doesn't make sense! Why would accessing the variable and calling a function that returns that variable make any difference?</p>
<p>For your reference I am using python 3.5.2 on Windows 32 bit</p>
| 4 | 2016-08-05T12:17:11Z | 38,789,159 | <p>When you do</p>
<p><code>from b import *</code></p>
<p>in <code>a.py</code>, it imports all names defined in the module <code>b</code> (including <code>delta</code>) into <code>a</code>'s namespace. As <code>float</code> in an immutable type in Python, you can consider <code>a.delta</code> a completely separate variable from <code>b.delta</code>, pointing to a different value.
Thus, the first <code>print()</code> prints the initial value of <code>a.delta</code>, while the second prints the updated value of <code>b.delta</code>.</p>
| 5 | 2016-08-05T12:22:08Z | [
"python",
"python-3.x",
"module",
"global-variables"
] |
Python multi module global variables. A bug in python? | 38,789,057 | <p>Recently I set up this example and am surprised by the results. I will demonstrate this with code:</p>
<p>File1: <strong>b.py</strong>:</p>
<pre><code>delta = 0.0
def example():
global delta
delta = 1
def ret_delta():
return delta
</code></pre>
<p>File2: <strong>a.py</strong>:</p>
<pre><code>from b import *
example()
#WHY ARE THESE DIFFERENT?
print(delta) # prints: 0.0
print(ret_delta()) # prints: 1
</code></pre>
<p>This doesn't make sense! Why would accessing the variable and calling a function that returns that variable make any difference?</p>
<p>For your reference I am using python 3.5.2 on Windows 32 bit</p>
| 4 | 2016-08-05T12:17:11Z | 38,789,198 | <p><code>from b import *</code> creates a series of new references in your <code>a</code> module globals. Each one of those copies the reference from <code>b</code> name. They are <em>independent</em> globals however.</p>
<p>Remember that in Python, names are merely <em>labels</em>; they are 'tied' to objects. You create this relationship by assignment, and you can create more than one label per object. That's what is happening here, you have labels in <code>b</code> and labels in <code>a</code>, and after <code>from b import *</code> the labels in both modules refer to the same objects.</p>
<p>However, you then assign a <strong>different object</strong> to the <code>delta</code> name in <code>b</code>. Now that label is no longer referencing the old <code>0.0</code> float object. But you didn't alter what the <code>delta</code> label in <code>a</code> is tied to.</p>
<p>If you were to prefix the names with the module name, you'd get <code>a.delta</code> and <code>b.delta</code>; the assignment <code>b.delta = 1</code> wouldn't alter <code>a.delta</code>, they live in different namespaces.</p>
<p>You may want to read up on how Python names work; see the excellent <a href="http://nedbatchelder.com/text/names.html" rel="nofollow"><em>Facts and myths about Python names and values</em> presentation</a> by Ned Batchelder.</p>
| 2 | 2016-08-05T12:23:52Z | [
"python",
"python-3.x",
"module",
"global-variables"
] |
BASH "echo -n value" in Python 2.6/2.x or Python 3.x within a loop - single line without space | 38,789,153 | <p>Like in BASH, I can use "echo -n" within a loop and print all elements in an array (or list in Python) in a single line without any space " " character. See the "<strong>echo -n</strong> value" below in second for loop.</p>
<pre><code>Arun Sangal@pc MINGW64 ~
$ a=(1 2 33 four)
Arun Sangal@pc MINGW64 ~
$ for v in ${a[@]}; do echo $v; done
1
2
33
four
Arun Sangal@pc MINGW64 ~
$ for v in ${a[@]}; do echo -n $v; done
1233four
Arun Sangal@pc MINGW64 ~
$ for v in ${a[@]}; do echo -n "$v "; done
1 2 33 four
</code></pre>
<p>How can I do the same in Python using <strong>for</strong> loop while iterating each list value.</p>
<p><strong>PS</strong>: I don't want to use "".join(list). Also, it seems like "".join(list) will WORK only if my list in Python has values as "strings" type then "".join(list) will work (like BASH <strong>echo -n</strong>) but if the list has Integer aka non-string values (for ex: as shown in the list <strong>numbers</strong> in the code below), "".join(numbers) or "".join(str(numbers)) still didn't work (like BASH <strong>echo -n</strong>); in this case, even though I used <strong>print num,</strong> in the loop, it still introduced a space " " character.</p>
<p>I'm trying to use <strong>print value,</strong> (with a command) but it's introducing a space " " character.</p>
<p>In Python 2.x, the following code is showing:</p>
<pre><code>numbers = [7, 9, 12, 54, 99] #"".join(..) will NOT work or print val, will not work here
strings = ["1", "2", "33", "four"] #"".join(..) will work as values are strings type.
print "This list contains: "
#This will print each value in list numbers but in individual new line per iteration of the loop.
for num in numbers:
print num
print ""
print "".join(str(numbers))
print "".join(strings)
#PS: This won't work if the values are "non-string" format as I'm still getting a space character (see output below) for each print statement for printing num value
for num in numbers:
print num,
</code></pre>
<p>output as:</p>
<pre><code>This list contains:
7
9
12
54
99
[7, 9, 12, 54, 99]
1233four
7 9 12 54 99
</code></pre>
<p>What I'm looking for is, how can I print all elements of list <strong>numbers</strong> (as shown below) using for loop and a print statement in a single line when the list has non-string values?</p>
<pre><code>79125499
</code></pre>
| 0 | 2016-08-05T12:21:54Z | 38,789,269 | <p>
You could to this:</p>
<pre><code>a = [1, 2, 3, 4]
concat = ""
for i in a:
concat = concat + str(i)
print concat
</code></pre>
<p>or without using a separate variable:</p>
<pre><code># needed if Python version 2.6+
from __future__ import print_function
a = [1, 2, 3, 4]
for i in a:
print(i, end="")
</code></pre>
| 1 | 2016-08-05T12:27:26Z | [
"python",
"python-2.7",
"echo",
"line",
"pretty-print"
] |
BASH "echo -n value" in Python 2.6/2.x or Python 3.x within a loop - single line without space | 38,789,153 | <p>Like in BASH, I can use "echo -n" within a loop and print all elements in an array (or list in Python) in a single line without any space " " character. See the "<strong>echo -n</strong> value" below in second for loop.</p>
<pre><code>Arun Sangal@pc MINGW64 ~
$ a=(1 2 33 four)
Arun Sangal@pc MINGW64 ~
$ for v in ${a[@]}; do echo $v; done
1
2
33
four
Arun Sangal@pc MINGW64 ~
$ for v in ${a[@]}; do echo -n $v; done
1233four
Arun Sangal@pc MINGW64 ~
$ for v in ${a[@]}; do echo -n "$v "; done
1 2 33 four
</code></pre>
<p>How can I do the same in Python using <strong>for</strong> loop while iterating each list value.</p>
<p><strong>PS</strong>: I don't want to use "".join(list). Also, it seems like "".join(list) will WORK only if my list in Python has values as "strings" type then "".join(list) will work (like BASH <strong>echo -n</strong>) but if the list has Integer aka non-string values (for ex: as shown in the list <strong>numbers</strong> in the code below), "".join(numbers) or "".join(str(numbers)) still didn't work (like BASH <strong>echo -n</strong>); in this case, even though I used <strong>print num,</strong> in the loop, it still introduced a space " " character.</p>
<p>I'm trying to use <strong>print value,</strong> (with a command) but it's introducing a space " " character.</p>
<p>In Python 2.x, the following code is showing:</p>
<pre><code>numbers = [7, 9, 12, 54, 99] #"".join(..) will NOT work or print val, will not work here
strings = ["1", "2", "33", "four"] #"".join(..) will work as values are strings type.
print "This list contains: "
#This will print each value in list numbers but in individual new line per iteration of the loop.
for num in numbers:
print num
print ""
print "".join(str(numbers))
print "".join(strings)
#PS: This won't work if the values are "non-string" format as I'm still getting a space character (see output below) for each print statement for printing num value
for num in numbers:
print num,
</code></pre>
<p>output as:</p>
<pre><code>This list contains:
7
9
12
54
99
[7, 9, 12, 54, 99]
1233four
7 9 12 54 99
</code></pre>
<p>What I'm looking for is, how can I print all elements of list <strong>numbers</strong> (as shown below) using for loop and a print statement in a single line when the list has non-string values?</p>
<pre><code>79125499
</code></pre>
| 0 | 2016-08-05T12:21:54Z | 38,789,505 | <p>If I understand you right, you are trying to print numbers without space between them? If so try the following. </p>
<pre><code>from __future__ import print_function
for i in range(1, 11):
print (i, end='')
</code></pre>
<p>Result</p>
<pre><code>12345678910
Process finished with exit code 0
</code></pre>
| 1 | 2016-08-05T12:40:34Z | [
"python",
"python-2.7",
"echo",
"line",
"pretty-print"
] |
How to call method of second parent class using method of child class in python? | 38,789,345 | <p>Below is my code:</p>
<pre><code>class Parent1(object):
def __init__(self):
print "!!! ___initialization Parent1___ !!!"
def method(self):
print "*** method of Parent1 is called ***"
class Parent2(object):
def __init__(self):
print "!!! ___initialization Parent2___ !!!"
def method(self):
print "*** method of Parent2 is called ***"
class Child(Parent1,Parent2):
def __init__(self):
print "!!! ___initialization Child___ !!!"
def method(self):
super(Child,self).method()
print "*** method of Child is called ***"
Ch = Child()
Ch.method()
</code></pre>
<p>I want to call <code>method()</code> of <code>Parent2</code> class using object of child class. Conditions are only child class object should be created and no change in child class declaration (<code>class Child(Parent1,Parent2):</code> should not changed.)</p>
| 0 | 2016-08-05T12:31:52Z | 38,789,442 | <pre><code>Parent2.method(self)
</code></pre>
<p>That's all you need - the <code>instance.method()</code> is just syntactic sugar for <code>ClassName.method(instance)</code>, so all you need to do is call it without the syntactic sugar and it'll do fine.</p>
<p>I changed the <code>Child</code> class to this:</p>
<pre><code>class Child(Parent1,Parent2):
def __init__(self):
print "!!! ___initialization Child___ !!!"
def method(self):
super(Child,self).method()
print "*** method of Child is called ***"
Parent2.method(self)
</code></pre>
<p>And:</p>
<pre><code># Out:
$ python c.py
!!! ___initialization Child___ !!!
*** method of Parent1 is called ***
*** method of Child is called ***
*** method of Parent2 is called ***
</code></pre>
<p>You get the expected output perfectly fine.</p>
| 1 | 2016-08-05T12:36:56Z | [
"python",
"python-2.7",
"python-3.x",
"ipython",
"multiple-inheritance"
] |
Return json from cherrypy before_handler tool | 38,789,389 | <p>I have a cherrypy application in which I've implemented a custom tool( a request filter) that I've attached to before_handler hook.
Bellow is the filter implementation:</p>
<pre><code>def custom_filter():
method = cherrypy.request.method
if method == 'POST':
print 'check POST token'
try:
request_headers = cherrypy.request.headers
token = request_headers['Authorization']
if not _auth.validate_token(token):
return 'error message'
except:
print 'Error in post filter'
</code></pre>
<p>What I want is to return a message to the client if the token is invalid. The return statement is not working. Is it possible to do this? If not, is there an alternative?</p>
| 0 | 2016-08-05T12:34:02Z | 39,515,345 | <p>Based on <a href="http://stackoverflow.com/questions/32133758/stop-request-processing-in-cherrypy-and-return-200-response-from-a-tool">this</a> post and after some investigations I found a solution that works for me: stop the execution of the request and then add a response body.</p>
<pre><code>def custom_filter():
method = cherrypy.request.method
if method == 'POST':
print 'check POST token'
try:
request_headers = cherrypy.request.headers
token = request_headers['Authorization']
if not _auth.validate_token(token):
cherrypy.request.handler = None # stop request
cherrypy.response.status = 403
cherrypy.response.body = 'test' # add response message
except:
print 'Error in post filter'
</code></pre>
| 0 | 2016-09-15T15:49:33Z | [
"python",
"json",
"cherrypy"
] |
Any way to remove the last check in my converter? | 38,789,450 | <p>For an interview question I made a roman to integer converter:</p>
<pre><code>def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
mapping = {"I": 1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}
numeral_list = list(s)
num_list = [[mapping[i], -1] for i in numeral_list]
count = 0
i = 0
while(i < len(num_list) - 1):
if num_list[i] < num_list[i + 1]:
count += num_list[i + 1][0] - num_list[i][0]
num_list[i+1][1] = 1
num_list[i][1] = 1
i += 2
else:
count += num_list[i][0]
num_list[i][1] = 1
i += 1
if num_list[-1][1] == -1:
count += num_list[-1][0]
return count
</code></pre>
<p>As you can see I sometimes miss the last digit because I didn't want to get an index error. To avoid that I added an extra attribute that would check if the last element was checked or not (in cases where s[len(s)-2] < s[len(s)-1], s[len(s)-1] is checked, but if s[len(s)-2] > s[len(s)-1] then s[len(s)-1] is not checked.</p>
<p>Having an extra check and using extra space just for one element is highly erroneous. Where am I going wrong in my logic?</p>
<p>EDIT: Here was my code before</p>
<pre><code>def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
mapping = {"I": 1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}
numeral_list = list(s)
num_list = [mapping[i] for i in numeral_list]
count = 0
i = 0
while(i < len(num_list)-1):
if num_list[i] < num_list[i + 1]:
count += num_list[i + 1] - num_list[i]
i += 2
else:
count += num_list[i]
i += 1
return count
</code></pre>
<p>It failed on several test cases since it did not count the last digit</p>
| 0 | 2016-08-05T12:37:39Z | 38,790,217 | <p>What they are looking for before anything else is whether your code is easily readable and maintainable. That's more important than being right, in my opinion, although the interviewer may disagree -- so make it also correct.</p>
<p>Check for invalid inputs. What if they give a string like 'VXQIII'? Do you want to enforce any rules or are you okay with giving 'VVVVV' = 25?</p>
<p>Throw in a unit test or test function for bonus points.</p>
<p>You invent a complicated structure with mysterious code numbers instead of using a clearly named variable like 'has_been_counted'. This makes your code hard to read. Therefore all your code will be hard for other programmers to read and maintain. And when I say other programmers, I mean you, next week, when you can't remember why you did that.</p>
<p>Additionally, that seen flag is unnecessary. You already have an array index telling you what you have and have not seen. </p>
<p>Python specific:</p>
<p>For an interview use pep-8. You can figure out how strict they are about style later, but python people can be pickier about that than most languages.</p>
<p>Self is unused, and it's not shown as being a class member anyway. "print romanToInt('XCIV')" will raise an error. </p>
<p>Speaking of errors, Python people may appreciate catching invalid characters with a try..except around the mapping lookup, and then reraise as ValueError('Not a valid roman numeral'). Maybe a python person can comment on what exception type to use for that, but I think ValueError is the right one.</p>
<p>converting s to a list of characters is unnecessary. You can already iterate a string as a list of characters.</p>
<pre><code>for letter in 'XCIV':
print letter
X
C
I
V
</code></pre>
| 1 | 2016-08-05T13:13:58Z | [
"python"
] |
Numpy array and Matlab Matrix are mismatching [3D] | 38,789,455 | <p>The following octave code shows a sample 3D matrix using Octave/Matlab </p>
<pre><code>octave:1> A=zeros(3,3,3);
octave:2>
octave:2> A(:,:,1)= [[1 2 3];[4 5 6];[7 8 9]];
octave:3>
octave:3> A(:,:,2)= [[11 22 33];[44 55 66];[77 88 99]];
octave:4>
octave:4> A(:,:,3)= [[111 222 333];[444 555 666];[777 888 999]];
octave:5>
octave:5>
octave:5> A
A =
ans(:,:,1) =
1 2 3
4 5 6
7 8 9
ans(:,:,2) =
11 22 33
44 55 66
77 88 99
ans(:,:,3) =
111 222 333
444 555 666
777 888 999
octave:6> A(1,3,2)
ans = 33
</code></pre>
<p>And I need to convert the same matrix using numpy ... unfortunately When I'm trying to access the same index using array in numpy I get different values as shown below!!</p>
<pre><code>import numpy as np
array = np.array([[[1 ,2 ,3],[4 ,5 ,6],[7 ,8 ,9]], [[11 ,22 ,33],[44 ,55 ,66],[77 ,88 ,99]], [[111 ,222 ,333],[444 ,555 ,666],[777 ,888 ,999]]])
>>> array[0,2,1]
8
</code></pre>
<p>Also I read the following document that shows the difference between matrix implementation in Matlab and in Python numpy <a href="https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html" rel="nofollow">Numpy for Matlab users</a> but I didn't find a sample 3d array and the mapping of it into Matlab and vice versa!</p>
<p>the answer is different for example accessing the element(1,3,2) in Matlab doesn't match the same index using numpy (0,2,1) </p>
<p><strong><em>Octave/Matlab</em></strong></p>
<p><strong>octave:6> A(1,3,2)</strong></p>
<p><strong>ans = 33</strong></p>
<p><strong><em>Python</em></strong></p>
<p><strong>>>> array[0,2,1]</strong></p>
<p><strong>8</strong></p>
| 1 | 2016-08-05T12:37:57Z | 38,792,057 | <p>The way your array is constructed in numpy is different than it is in MATLAB.</p>
<p>Where your MATLAB array is <code>(y, x, z)</code>, your numpy array is <code>(z, y, x)</code>. Your 3d numpy array is a series of 'stacked' 2d arrays, so you're indexing "outside->inside" (for lack of a better term). Here's your array definition expanded so this (hopefully) makes a little more sense:</p>
<pre><code>[[[1, 2, 3],
[4, 5, 6], # Z = 0
[7 ,8 ,9]],
[[11 ,22 ,33],
[44 ,55 ,66], # Z = 1
[77 ,88 ,99]],
[[111 ,222 ,333],
[444 ,555 ,666], # Z = 2
[777 ,888 ,999]]
]
</code></pre>
<p>So with:</p>
<pre><code>import numpy as np
A = np.array([[[1 ,2 ,3],[4 ,5 ,6],[7 ,8 ,9]], [[11 ,22 ,33],[44 ,55 ,66],[77 ,88 ,99]], [[111 ,222 ,333],[444 ,555 ,666],[777 ,888 ,999]]])
B = A[1, 0, 2]
</code></pre>
<p><code>B</code> returns <code>33</code>, as expected.</p>
<p>If you want a less mind-bending way to indexing your array, consider generating it as you did in MATLAB.</p>
| 3 | 2016-08-05T14:46:39Z | [
"python",
"arrays",
"matlab",
"numpy",
"matrix"
] |
Numpy array and Matlab Matrix are mismatching [3D] | 38,789,455 | <p>The following octave code shows a sample 3D matrix using Octave/Matlab </p>
<pre><code>octave:1> A=zeros(3,3,3);
octave:2>
octave:2> A(:,:,1)= [[1 2 3];[4 5 6];[7 8 9]];
octave:3>
octave:3> A(:,:,2)= [[11 22 33];[44 55 66];[77 88 99]];
octave:4>
octave:4> A(:,:,3)= [[111 222 333];[444 555 666];[777 888 999]];
octave:5>
octave:5>
octave:5> A
A =
ans(:,:,1) =
1 2 3
4 5 6
7 8 9
ans(:,:,2) =
11 22 33
44 55 66
77 88 99
ans(:,:,3) =
111 222 333
444 555 666
777 888 999
octave:6> A(1,3,2)
ans = 33
</code></pre>
<p>And I need to convert the same matrix using numpy ... unfortunately When I'm trying to access the same index using array in numpy I get different values as shown below!!</p>
<pre><code>import numpy as np
array = np.array([[[1 ,2 ,3],[4 ,5 ,6],[7 ,8 ,9]], [[11 ,22 ,33],[44 ,55 ,66],[77 ,88 ,99]], [[111 ,222 ,333],[444 ,555 ,666],[777 ,888 ,999]]])
>>> array[0,2,1]
8
</code></pre>
<p>Also I read the following document that shows the difference between matrix implementation in Matlab and in Python numpy <a href="https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html" rel="nofollow">Numpy for Matlab users</a> but I didn't find a sample 3d array and the mapping of it into Matlab and vice versa!</p>
<p>the answer is different for example accessing the element(1,3,2) in Matlab doesn't match the same index using numpy (0,2,1) </p>
<p><strong><em>Octave/Matlab</em></strong></p>
<p><strong>octave:6> A(1,3,2)</strong></p>
<p><strong>ans = 33</strong></p>
<p><strong><em>Python</em></strong></p>
<p><strong>>>> array[0,2,1]</strong></p>
<p><strong>8</strong></p>
| 1 | 2016-08-05T12:37:57Z | 38,792,064 | <p>I think that the problem is the way you create the matrix in numpy and also the different representation of matlab and numpy, why you don't use the same system in matlab and numpy</p>
<pre><code>> array = np.zeros((3,3,3),dtype=np.int)
> array
array([[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]])
> array[:,:,0] = np.array([[1,2,3],[4,5,6],[7,8,9]])
> array[:,:,1] = np.array([[11,22,33],[44,55,66],[77,88,99]])
> array[:,:,2] = np.array([[111,222,333],[444,555,666],[777,888,999]])
> array
array([[[ 1, 11, 111],
[ 2, 22, 222],
[ 3, 33, 333]],
[[ 4, 44, 444],
[ 5, 55, 555],
[ 6, 66, 666]],
[[ 7, 77, 777],
[ 8, 88, 888],
[ 9, 99, 999]]])
> array[0,2,1]
33
</code></pre>
| 1 | 2016-08-05T14:46:55Z | [
"python",
"arrays",
"matlab",
"numpy",
"matrix"
] |
Numpy array and Matlab Matrix are mismatching [3D] | 38,789,455 | <p>The following octave code shows a sample 3D matrix using Octave/Matlab </p>
<pre><code>octave:1> A=zeros(3,3,3);
octave:2>
octave:2> A(:,:,1)= [[1 2 3];[4 5 6];[7 8 9]];
octave:3>
octave:3> A(:,:,2)= [[11 22 33];[44 55 66];[77 88 99]];
octave:4>
octave:4> A(:,:,3)= [[111 222 333];[444 555 666];[777 888 999]];
octave:5>
octave:5>
octave:5> A
A =
ans(:,:,1) =
1 2 3
4 5 6
7 8 9
ans(:,:,2) =
11 22 33
44 55 66
77 88 99
ans(:,:,3) =
111 222 333
444 555 666
777 888 999
octave:6> A(1,3,2)
ans = 33
</code></pre>
<p>And I need to convert the same matrix using numpy ... unfortunately When I'm trying to access the same index using array in numpy I get different values as shown below!!</p>
<pre><code>import numpy as np
array = np.array([[[1 ,2 ,3],[4 ,5 ,6],[7 ,8 ,9]], [[11 ,22 ,33],[44 ,55 ,66],[77 ,88 ,99]], [[111 ,222 ,333],[444 ,555 ,666],[777 ,888 ,999]]])
>>> array[0,2,1]
8
</code></pre>
<p>Also I read the following document that shows the difference between matrix implementation in Matlab and in Python numpy <a href="https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html" rel="nofollow">Numpy for Matlab users</a> but I didn't find a sample 3d array and the mapping of it into Matlab and vice versa!</p>
<p>the answer is different for example accessing the element(1,3,2) in Matlab doesn't match the same index using numpy (0,2,1) </p>
<p><strong><em>Octave/Matlab</em></strong></p>
<p><strong>octave:6> A(1,3,2)</strong></p>
<p><strong>ans = 33</strong></p>
<p><strong><em>Python</em></strong></p>
<p><strong>>>> array[0,2,1]</strong></p>
<p><strong>8</strong></p>
| 1 | 2016-08-05T12:37:57Z | 38,792,658 | <p>MATLAB and Python index differently. To investigate this, lets create a linear array of number <code>1</code> to <code>8</code> and then <code>reshape</code> the result to be a <code>2</code>-by-<code>2</code>-by-<code>2</code> matrix in each language:</p>
<p>MATLAB:</p>
<pre><code>M_flat = 1:8
M = reshape(M_flat, [2,2,2])
</code></pre>
<p>which returns</p>
<pre><code>M =
ans(:,:,1) =
1 3
2 4
ans(:,:,2) =
5 7
6 8
</code></pre>
<p>Python:</p>
<pre><code>import numpy as np
P_flat = np.array(range(1,9))
P = np.reshape(P, [2,2,2])
</code></pre>
<p>which returns</p>
<pre><code>array([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])
</code></pre>
<p>The first thing you should notice is that the first two dimensions have switched. This is because MATLAB uses column-major indexing which means we count down the columns first whereas Python use row-major indexing and hence it counts across the rows first.</p>
<p>Now let's try indexing them. So let's try slicing along the different dimensions. In MATLAB, I know to get a slice out of the third dimension I can do</p>
<pre><code>M(:,:,1)
ans =
1 3
2 4
</code></pre>
<p>Now let's try the same in Python</p>
<pre><code>P[:,:,0]
array([[1, 3],
[5, 7]])
</code></pre>
<p>So that's completely different. To get the MATLAB 'equivalent' we need to go</p>
<pre><code>P[0,:,:]
array([[1, 2],
[3, 4]])
</code></pre>
<p>Now this returns the transpose of the MATLAB version which is to be expected due the the row-major vs column-major difference.</p>
<p>So what does this mean for indexing? It looks like Python puts the major index at the end which is <strong>the reverse</strong> of MALTAB.</p>
<p>Let's say I index as follows in MATLAB</p>
<pre><code>M(1,2,2)
ans =
7
</code></pre>
<p>now to get the <code>7</code> from Python we should go </p>
<pre><code>P(1,1,0)
</code></pre>
<p>which is the MATLAB syntax reversed. Note that is is reversed because we created the Python matrix with a row-major ordering in mind. If you create it as you did in your code you would have to swap the last 2 indices so rather create the matrix correctly in the first place as Ander has suggested in the comments. </p>
| 0 | 2016-08-05T15:16:17Z | [
"python",
"arrays",
"matlab",
"numpy",
"matrix"
] |
Numpy array and Matlab Matrix are mismatching [3D] | 38,789,455 | <p>The following octave code shows a sample 3D matrix using Octave/Matlab </p>
<pre><code>octave:1> A=zeros(3,3,3);
octave:2>
octave:2> A(:,:,1)= [[1 2 3];[4 5 6];[7 8 9]];
octave:3>
octave:3> A(:,:,2)= [[11 22 33];[44 55 66];[77 88 99]];
octave:4>
octave:4> A(:,:,3)= [[111 222 333];[444 555 666];[777 888 999]];
octave:5>
octave:5>
octave:5> A
A =
ans(:,:,1) =
1 2 3
4 5 6
7 8 9
ans(:,:,2) =
11 22 33
44 55 66
77 88 99
ans(:,:,3) =
111 222 333
444 555 666
777 888 999
octave:6> A(1,3,2)
ans = 33
</code></pre>
<p>And I need to convert the same matrix using numpy ... unfortunately When I'm trying to access the same index using array in numpy I get different values as shown below!!</p>
<pre><code>import numpy as np
array = np.array([[[1 ,2 ,3],[4 ,5 ,6],[7 ,8 ,9]], [[11 ,22 ,33],[44 ,55 ,66],[77 ,88 ,99]], [[111 ,222 ,333],[444 ,555 ,666],[777 ,888 ,999]]])
>>> array[0,2,1]
8
</code></pre>
<p>Also I read the following document that shows the difference between matrix implementation in Matlab and in Python numpy <a href="https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html" rel="nofollow">Numpy for Matlab users</a> but I didn't find a sample 3d array and the mapping of it into Matlab and vice versa!</p>
<p>the answer is different for example accessing the element(1,3,2) in Matlab doesn't match the same index using numpy (0,2,1) </p>
<p><strong><em>Octave/Matlab</em></strong></p>
<p><strong>octave:6> A(1,3,2)</strong></p>
<p><strong>ans = 33</strong></p>
<p><strong><em>Python</em></strong></p>
<p><strong>>>> array[0,2,1]</strong></p>
<p><strong>8</strong></p>
| 1 | 2016-08-05T12:37:57Z | 38,803,741 | <p>I think that python uses this type of indexing to create arrays as shown in the following figure:</p>
<p><a href="https://www.google.com.eg/search?q=python+indexing+arrays+numpy&biw=1555&bih=805&source=lnms&tbm=isch&sa=X&ved=0ahUKEwia7b2J1qzOAhUFPBQKHXtdCBkQ_AUIBygC#imgrc=7JQu1w_4TCaAnM%3A" rel="nofollow">https://www.google.com.eg/search?q=python+indexing+arrays+numpy&biw=1555&bih=805&source=lnms&tbm=isch&sa=X&ved=0ahUKEwia7b2J1qzOAhUFPBQKHXtdCBkQ_AUIBygC#imgrc=7JQu1w_4TCaAnM%3A</a></p>
<p>And, there are many ways to store your data, you can choose order='F' to count the columns first as matlab does, while the default is order='C' that count the rows first.... </p>
| 1 | 2016-08-06T11:25:30Z | [
"python",
"arrays",
"matlab",
"numpy",
"matrix"
] |
Cross validation predictor score the same | 38,789,457 | <p>I am trying to choose the csv file with data which has better prediction scores.
I am trying to determine cross validation scores using the following code:</p>
<pre><code>from __future__ import division
import os,csv
from sklearn import cross_validation
import numpy as np
from sklearn import svm
from sklearn import metrics
files = [e for e in os.listdir('.') if e.endswith('.csv')]
csvout = open('xval.csv','wb')
csvwriter=csv.writer(csvout)
for f in files:
X,Y=[],[]
feat=f[4:-4]
print feat
csvin = open(f,'rb')
csvread=csv.reader(csvin)
for row in csvread:
X.append([row[0]])
Y.append(1 if row[1]=='True' else 0)
clf = svm.SVC(kernel='linear', C=1)
predicted = cross_validation.cross_val_predict(clf, X, Y, cv=3)
print metrics.accuracy_score(Y, predicted)
csvout.close()
</code></pre>
<p>The two csvs are as follows, a.csv and b.csv:</p>
<pre><code>0.8307059089237866,False
0.07933411654760168,False
0.07933411654760168,False
0.07933411654760168,False
0.07933411654760168,False
0.8050114148789536,False
0.7050883824823811,True
0.07933411654760168,True
0.07933411654760168,True
0.07933411654760168,True
0.07933411654760168,True
0.07933411654760168,True
0.07933411654760168,True
0.07933411654760168,True
0.07933411654760168,True
0.6251499565651232,True
0.3507377775833331,False
0.2609619627153587,False
0.24483806968609972,False
0.7122564948467026,False
0.7172548646226102,False
0.1321163493448647,False
0.023658678331543205,True
0.5954080270729952,True
0.632479304055982,True
0.22412105580276065,True
0.3431509885671966,True
0.5954080270729952,True
0.1137442754294842,True
0.8312144672461341,True
0.1137442754294842,True
</code></pre>
<p>However, I am getting the exact same predictor score. How is this possible?</p>
| 0 | 2016-08-05T12:38:05Z | 38,790,226 | <p>The current code will not work because the variable CV (number of folds) of the cross_val_predict() function is bigger than the number of samples of the class 0 (False). If you lower it to less (or equal) than 6 it will work and you'll get an accuracy of 0.6 for a.csv and 0.625 for b.csv.</p>
| 1 | 2016-08-05T13:14:20Z | [
"python",
"scikit-learn",
"cross-validation"
] |
Save Python search results in variable and working with its elements | 38,789,519 | <p>Since I am pretty new to Python this might be an easy question for you!</p>
<p>I'd like to execute a process for all directories with a specific name in a given folder 'folder_a' (which includes 'folder_1','folder_2',...). </p>
<p>First question: How do I get a list of all the directories and folder_a? What I tried was: </p>
<blockquote>
<p>for sub_folders in glob.glob("<em>OPER</em>.safe"): print sub_folders</p>
</blockquote>
<p>However, this only creates a string of all directories, which is not really helpful in my case.</p>
<p>Second question: If I have got the list and like to access each folder one by one with a for-loop, how do I do it?</p>
<p>Thank you so much in advance!</p>
| 1 | 2016-08-05T12:41:14Z | 38,790,074 | <p>To iterate over the contents of a directory, you can use python's excellent <code>os.walk</code> function:</p>
<pre><code>import os
for root, dirs, files is os.walk(root_dir):
for d in dirs:
if search_term in d:
do_something_to_directory(d)
</code></pre>
<p><code>os.walk()</code> generates tuples, with <code>root</code> being the directory where you start your iteration, <code>dirs</code> is a list of the directories, and <code>files</code> is a list of the files.</p>
<p><a class='doc-link' href="http://stackoverflow.com/documentation/python/267/files-folders-io#t=201608051320382125348">Docs here.</a></p>
<p><strong>EDIT:</strong> If you want to get the files from inside a certain sub-directory, iterate over the <em>files</em> and filter for the desired directory name. Try this to see what I mean:</p>
<pre><code>for root, dirs, files in os.walk(starting_directory_path):
for f in files:
absolute_path = os.path.join(root, f)
if 'Desired Folder Name' in absolute_path:
print absolute_path
</code></pre>
<p>Since <code>os.walk()</code> is recursive, all the files in all sub-directories will be in the <code>files</code> list. You'll only want to use the <code>dirs</code> list is you're looking specifically for a directory. All files will be in files.</p>
| 4 | 2016-08-05T13:07:56Z | [
"python",
"loops"
] |
Python: TypeError: 'TreeNode' object is not iterable | 38,789,552 | <p>Here's my code:</p>
<pre><code># Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n==0:
return []
return self.generateTreesHelper(range(1, n+1))
def generateTreesHelper(self, lst):
if len(lst) == 0:
return [None]
elif len(lst) == 1:
return TreeNode(lst[0])
else:
res = []
for i in range(0, len(lst)):
left_trees = self.generateTreesHelper(lst[:i])
right_trees = self.generateTreesHelper(lst[i+1:])
for left in left_trees:
for right in right_trees:
root = TreeNode(lst[i])
root.left = left
root.right = right
res.append(root)
return res
</code></pre>
<p>The code is to generate all structurally unique BST's (binary search trees) that store values 1...n.</p>
<h2>For example,</h2>
<p>Given n = 3, The program should return all 5 unique BST's shown below.</p>
<blockquote>
<p>[[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]].</p>
</blockquote>
<p>However, I keep getting the error message.</p>
<blockquote>
<p>TypeError: 'int' object is not iterable.</p>
</blockquote>
| 0 | 2016-08-05T12:43:12Z | 38,792,236 | <p>I don't know how you get <em>that</em> </p>
<pre><code>TypeError: 'int' object is not iterable.
</code></pre>
<p>error. On both Python 2.6 and 3.6 I get the error mentioned in your question's title:</p>
<pre><code>TypeError: 'TreeNode' object is not iterable
</code></pre>
<p>This is because <code>return TreeNode(lst[0])</code> returns a TreeNode. It should return a <em>list</em> containing that TreeNode, so that it can be iterated over in your <code>left_trees</code> and <code>right_trees</code> <code>for</code> loops.</p>
<p>Here's a repaired version of your code, with a simple <code>__repr__</code> method so that we can see that the output is correct.</p>
<pre><code>class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __repr__(self):
if self.left is None and self.right is None:
s = '{}'.format(self.val)
else:
s = '[val:{}, left:{}, right:{}]'.format(self.val, self.left, self.right)
return s
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n==0:
return []
return self.generateTreesHelper(range(1, n+1))
def generateTreesHelper(self, lst):
if len(lst) == 0:
return [None]
elif len(lst) == 1:
return [TreeNode(lst[0])]
else:
res = []
for i in range(0, len(lst)):
left_trees = self.generateTreesHelper(lst[:i])
right_trees = self.generateTreesHelper(lst[i+1:])
for left in left_trees:
for right in right_trees:
root = TreeNode(lst[i])
root.left = left
root.right = right
res.append(root)
return res
print(Solution().generateTrees(3))
</code></pre>
<p><strong>output</strong></p>
<pre><code>[[val:1, left:None, right:[val:2, left:None, right:3]], [val:1, left:None, right:[val:3, left:2, right:None]], [val:2, left:1, right:3], [val:3, left:[val:1, left:None, right:2], right:None], [val:3, left:[val:2, left:1, right:None], right:None]]
</code></pre>
| 1 | 2016-08-05T14:55:01Z | [
"python",
"algorithm",
"binary-tree"
] |
Programmatically define a new function from a list of other functions | 38,789,554 | <p>I have:</p>
<pre><code>def f(x, y): return x**2 + y**2
def g(x, y): return x**3 + y**3
def h(x, y): return x**4 + y**4
</code></pre>
<p>And I'd like to make a new function:</p>
<pre><code>def J(x, y):
return f(x,y)*g(x,y)*h(x,y)
</code></pre>
<p>However, I am unable to find a way to do this programmatically.
That is, take something like:</p>
<pre><code>myFunctions = [f,g,h]
</code></pre>
<p>and return a new function <code>J</code> which returns the product of <code>f</code>, <code>g</code> and <code>h</code>.</p>
<p>Another wrinkle is that while <code>f</code>, <code>g</code> and <code>h</code> will always have an identical number of arguments, that number could change. That is, they could all have could have five arguments instead of two. </p>
<p>Desired behaviour:</p>
<pre><code>print(J(2, 2)) # 4096
</code></pre>
<hr>
<h3>EDIT</h3>
<p>The number of functions in <code>myFunctions</code> is also arbitrary.
I thought this was implied in my question, but upon rereading it I see that I did not make that at all clear. My apologies.</p>
| 1 | 2016-08-05T12:43:15Z | 38,789,691 | <p>You could allow <code>J</code> to take as many arguments as necessary, then multiply the final list that f, g, and h give:</p>
<pre><code>def f(x, y): return x**2 + y**2
def g(x, y): return x**3 + y**3
def h(x, y): return x**4 + y**4
def multiply(mylist):
return reduce(lambda a, b: a*b, mylist)
myfuncs = [f,g,h]
def J(*args):
return multiply([myfunc(*args) for myfunc in myfuncs])
</code></pre>
<p>Since f, g, and h will have the same amount of arguments, this should work for all cases.</p>
| 3 | 2016-08-05T12:50:53Z | [
"python",
"python-3.x",
"functional-programming"
] |
Programmatically define a new function from a list of other functions | 38,789,554 | <p>I have:</p>
<pre><code>def f(x, y): return x**2 + y**2
def g(x, y): return x**3 + y**3
def h(x, y): return x**4 + y**4
</code></pre>
<p>And I'd like to make a new function:</p>
<pre><code>def J(x, y):
return f(x,y)*g(x,y)*h(x,y)
</code></pre>
<p>However, I am unable to find a way to do this programmatically.
That is, take something like:</p>
<pre><code>myFunctions = [f,g,h]
</code></pre>
<p>and return a new function <code>J</code> which returns the product of <code>f</code>, <code>g</code> and <code>h</code>.</p>
<p>Another wrinkle is that while <code>f</code>, <code>g</code> and <code>h</code> will always have an identical number of arguments, that number could change. That is, they could all have could have five arguments instead of two. </p>
<p>Desired behaviour:</p>
<pre><code>print(J(2, 2)) # 4096
</code></pre>
<hr>
<h3>EDIT</h3>
<p>The number of functions in <code>myFunctions</code> is also arbitrary.
I thought this was implied in my question, but upon rereading it I see that I did not make that at all clear. My apologies.</p>
| 1 | 2016-08-05T12:43:15Z | 38,789,698 | <p>The variable number of arguments problem can be resolved by this:</p>
<pre><code>def f(*args): return sum(map(lambda x: x**2, args))
def g(*args): return sum(map(lambda x: x**3, args))
def h(*args): return sum(map(lambda x: x**4, args))
</code></pre>
<p>And then you could simply define the <code>J</code> function</p>
<pre><code>def J(*args):
return f(*args)*g(*args)*h(*args)
</code></pre>
<p>If you want to support variable number of functions, then you could define J as the following and pass in the list of functions as the first item of the list and the arguments as the following items.</p>
<pre><code>def J(*args):
funcs = args[0]
args = args[1:]
temp = map(lambda x: x(*args), funcs)
return reduce(lambda x,y: x*y, temp, 1)
</code></pre>
| 0 | 2016-08-05T12:51:12Z | [
"python",
"python-3.x",
"functional-programming"
] |
Programmatically define a new function from a list of other functions | 38,789,554 | <p>I have:</p>
<pre><code>def f(x, y): return x**2 + y**2
def g(x, y): return x**3 + y**3
def h(x, y): return x**4 + y**4
</code></pre>
<p>And I'd like to make a new function:</p>
<pre><code>def J(x, y):
return f(x,y)*g(x,y)*h(x,y)
</code></pre>
<p>However, I am unable to find a way to do this programmatically.
That is, take something like:</p>
<pre><code>myFunctions = [f,g,h]
</code></pre>
<p>and return a new function <code>J</code> which returns the product of <code>f</code>, <code>g</code> and <code>h</code>.</p>
<p>Another wrinkle is that while <code>f</code>, <code>g</code> and <code>h</code> will always have an identical number of arguments, that number could change. That is, they could all have could have five arguments instead of two. </p>
<p>Desired behaviour:</p>
<pre><code>print(J(2, 2)) # 4096
</code></pre>
<hr>
<h3>EDIT</h3>
<p>The number of functions in <code>myFunctions</code> is also arbitrary.
I thought this was implied in my question, but upon rereading it I see that I did not make that at all clear. My apologies.</p>
| 1 | 2016-08-05T12:43:15Z | 38,789,715 | <p>A function can accept arbitrarily many arguments using <code>*</code> like this:</p>
<pre><code>def J(*args):
</code></pre>
<p>This will store all of <code>J</code>'s arguments in the list <code>args</code>. That list can then be converted back into multiple arguments to call other functions like this:</p>
<pre><code>def J(*args):
return f(*args) * g(*args)
</code></pre>
<p>This solves the problem of the number of arguments changing. So now let's handle the fact that there can be arbitrarily many functions. First we need to call the function in your list. We can just do that by iterating over them and using <code>()</code>:</p>
<pre><code>def J(*args):
return [func(*args) for func in myFunctions]
</code></pre>
<p>This will return a list of the functions' return values. So all we need now is to get the product of a collection:</p>
<pre><code>from functools import reduce
from operator import mul
def product(numbers):
return reduce(mul, list, 1)
def J(*args):
return product(func(*args) for func in myFunctions)
</code></pre>
| 3 | 2016-08-05T12:52:15Z | [
"python",
"python-3.x",
"functional-programming"
] |
Programmatically define a new function from a list of other functions | 38,789,554 | <p>I have:</p>
<pre><code>def f(x, y): return x**2 + y**2
def g(x, y): return x**3 + y**3
def h(x, y): return x**4 + y**4
</code></pre>
<p>And I'd like to make a new function:</p>
<pre><code>def J(x, y):
return f(x,y)*g(x,y)*h(x,y)
</code></pre>
<p>However, I am unable to find a way to do this programmatically.
That is, take something like:</p>
<pre><code>myFunctions = [f,g,h]
</code></pre>
<p>and return a new function <code>J</code> which returns the product of <code>f</code>, <code>g</code> and <code>h</code>.</p>
<p>Another wrinkle is that while <code>f</code>, <code>g</code> and <code>h</code> will always have an identical number of arguments, that number could change. That is, they could all have could have five arguments instead of two. </p>
<p>Desired behaviour:</p>
<pre><code>print(J(2, 2)) # 4096
</code></pre>
<hr>
<h3>EDIT</h3>
<p>The number of functions in <code>myFunctions</code> is also arbitrary.
I thought this was implied in my question, but upon rereading it I see that I did not make that at all clear. My apologies.</p>
| 1 | 2016-08-05T12:43:15Z | 38,790,024 | <p>Another option:</p>
<pre><code>from functools import reduce, partial
from operator import mul
def f(x, y): return x**2 + y**2
def g(x, y): return x**3 + y**3
def h(x, y): return x**4 + y**4
myFunctions = [f,g,h]
J = partial(lambda funcs, *args: reduce(mul, (func(*args) for func in funcs), 1), myFunctions)
print J(2, 2)
</code></pre>
<p>Has the nice property that J takes the same number of arguments as functions f, g & h rather than <code>*args</code>.</p>
| 1 | 2016-08-05T13:06:00Z | [
"python",
"python-3.x",
"functional-programming"
] |
Python: Do not map empty result of multiprocessing.Pool( ) | 38,789,568 | <p>Program have function that may return None value, for minimize spend time this function calling in parallel workers.
In code below, result of this function have the "None" values, how to exclude this is values from the "ret"?</p>
<pre><code>#!/usr/bin/python
import sys,multiprocessing,time
maxNumber = sys.maxint+2
def numGen():
cnt=0
while cnt < maxNumber:
cnt +=1
yield cnt
def oddCheck(num):
global maxNumber
# time.sleep(1)
if not bool(num%1000000):
print "[%s%%] %s" % (int((num/maxNumber)*100),num)
if num%2:
return num
pool = multiprocessing.Pool( )
if sys.maxint < maxNumber:
print "We have problem on %s"%sys.maxint
# quit()
ret = pool.imap(oddCheck, numGen())
pool.close()
pool.join()
for x in ret:
print x
</code></pre>
| 1 | 2016-08-05T12:44:17Z | 38,790,023 | <p><code>oddCheck</code> returns <code>None</code> when <code>num</code> is not a even number (you do not have a return statement in this case, so <code>None</code> will be returned).</p>
<p>If you want to avoid <code>None</code> results, just use a list comprehension to filter them:</p>
<pre><code>ret = [x for x in pool.imap(oddCheck, numGen()) if x is not None]
</code></pre>
<p>It should do the trick ;-)</p>
| 2 | 2016-08-05T13:06:00Z | [
"python",
"multithreading",
"dictionary"
] |
How to set a general option in Python to display only N digits everywhere? | 38,789,609 | <p>I want to work with 3 digits after the decimal point in Python. What is the relevant setting to modify ?</p>
<p>I want that <code>1.0 / 3</code> would return 0.333, and not 0.3333333333333333 like it is the case in my Jupyter Notebook, using python 2.7.11 and Anaconda 4.0.0.</p>
<p>In my research, I heard about the Decimal class, but I don't want to use Decimal(x) in my code every time I display a float, neither the string formating or the round function, though I use it for the time being (because I don't want to use it every time).</p>
<p>I think there is a general solution, a setting computed only once.</p>
| 0 | 2016-08-05T12:46:18Z | 38,789,920 | <p>use numpy and try this;</p>
<pre><code>round(1.0/3, 3)
</code></pre>
<p>or</p>
<pre><code>>>> 1.0/3
0.3333333333333333
>>> '{:0.3f}'.format(1.0/3)
'0.333'
</code></pre>
| 0 | 2016-08-05T13:01:16Z | [
"python",
"number-formatting"
] |
How to set a general option in Python to display only N digits everywhere? | 38,789,609 | <p>I want to work with 3 digits after the decimal point in Python. What is the relevant setting to modify ?</p>
<p>I want that <code>1.0 / 3</code> would return 0.333, and not 0.3333333333333333 like it is the case in my Jupyter Notebook, using python 2.7.11 and Anaconda 4.0.0.</p>
<p>In my research, I heard about the Decimal class, but I don't want to use Decimal(x) in my code every time I display a float, neither the string formating or the round function, though I use it for the time being (because I don't want to use it every time).</p>
<p>I think there is a general solution, a setting computed only once.</p>
| 0 | 2016-08-05T12:46:18Z | 38,791,090 | <p>There is no "one-time" solution to your problem.
And I think that your approach might be a little misguided.</p>
<p>I suppose that your interaction with Jupyter or Ipython has lead you to the conclusion that python is quite handy as a numerical calculator. Unfortunately both of the aforementioned programs are just wrappers or <a href="https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop" rel="nofollow">REPL</a> programs and in the background come with the full programming language flexibility that Python offers.</p>
| 0 | 2016-08-05T13:57:57Z | [
"python",
"number-formatting"
] |
How to retrieve a total pixel value above an average-based threshold in Python | 38,789,670 | <p>Currently, I am practicing with retrieving the total of the pixel values above a threshold based on the mean of the whole image. (I am very new to Python). I am using Python 3.5.2, and the above code was copied from the Atom program I am using to write and experiment with the code.</p>
<p>For the time being, I am just practicing with the red channel - but eventually, I will need to individually analyse all colour channels.</p>
<p>The complete code that I am using so far:</p>
<pre><code>import os
from skimage import io
from tkinter import *
from tkinter.filedialog import askopenfilename
def callback():
M = askopenfilename() #to select a file
image = io.imread(M) #to read the selected file
red = image[:,:,0] #selecting the red channel
red_av = red.mean() #average pixel value of the red channel
threshold = red_av + 100 #setting the threshold value
red_val = red > threshold
red_sum = sum(red_val)
print(red_sum)
Button(text = 'Select Image', command = callback).pack(fill = X)
mainloop()
</code></pre>
<p>Now, everything works so far, except when I run the program, red_sum comes out to be the number of pixels above the threshold, not the total of the pixels.</p>
<p>What I am I missing? I am thinking that my (possible naive) way of declaring the <code>red_val</code> variable has something to do with it.</p>
<p>But, how do I retrieve the total pixel value above the threshold?</p>
| 1 | 2016-08-05T12:49:53Z | 38,790,729 | <p>When you did (red > threshold) you got a mask such that all the pixels in red that are above the thrshold got the value 1 and 0 other wise. Now to get the values you can just multiply the mask with the red channel. The multiplcation will zero all the values that are less than the threshold and will leave the values over the threshold unchanged.</p>
<p>The code:</p>
<pre><code>red_val = (red > threshold)*red
red_sum = sum(red_val)
</code></pre>
| 1 | 2016-08-05T13:39:01Z | [
"python",
"python-3.x",
"image-processing",
"pixels",
"threshold"
] |
How to retrieve a total pixel value above an average-based threshold in Python | 38,789,670 | <p>Currently, I am practicing with retrieving the total of the pixel values above a threshold based on the mean of the whole image. (I am very new to Python). I am using Python 3.5.2, and the above code was copied from the Atom program I am using to write and experiment with the code.</p>
<p>For the time being, I am just practicing with the red channel - but eventually, I will need to individually analyse all colour channels.</p>
<p>The complete code that I am using so far:</p>
<pre><code>import os
from skimage import io
from tkinter import *
from tkinter.filedialog import askopenfilename
def callback():
M = askopenfilename() #to select a file
image = io.imread(M) #to read the selected file
red = image[:,:,0] #selecting the red channel
red_av = red.mean() #average pixel value of the red channel
threshold = red_av + 100 #setting the threshold value
red_val = red > threshold
red_sum = sum(red_val)
print(red_sum)
Button(text = 'Select Image', command = callback).pack(fill = X)
mainloop()
</code></pre>
<p>Now, everything works so far, except when I run the program, red_sum comes out to be the number of pixels above the threshold, not the total of the pixels.</p>
<p>What I am I missing? I am thinking that my (possible naive) way of declaring the <code>red_val</code> variable has something to do with it.</p>
<p>But, how do I retrieve the total pixel value above the threshold?</p>
| 1 | 2016-08-05T12:49:53Z | 38,791,228 | <p>Another method I found that worked (providing the total pixel value) was to use masked values:</p>
<pre><code>import numpy.ma as ma
...
red_val = ma.masked_outside(red, threshold, 255).sum()
</code></pre>
<p>From the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ma.masked_outside.html#numpy.ma.masked_outside" rel="nofollow">SciPy.org documentation</a> about masking, what this does is:</p>
<blockquote>
<p>Mask an array outside a given interval.</p>
</blockquote>
<p>In the example, anything outside of the interval of the <code>threshold</code> (defined in my question) and <code>255</code> is 'masked' and does not feature in calculating the sum of pixel values.</p>
| 0 | 2016-08-05T14:05:31Z | [
"python",
"python-3.x",
"image-processing",
"pixels",
"threshold"
] |
Extracting specific data from multiple strings | 38,789,708 | <p>Been playing around with this. Haven't cleaned it up yet. It basically does what nslookup does. Takes a (or multiple) host name from a text file and returns the corressponding IP address. </p>
<pre><code>def getIPAddresses(file):
emptyList = []
someString = ".com"
with open(file, "r+") as output:
for line in output:
emptyList.append(line)
my_new_list = [x.strip() + someString for x in emptyList]
return(my_new_list)
def lookup():
try:
while True:
enterSomething = input("Enter something: ")
if os.path.exists(enterSomething):
for n in getIPAddresses(enterSomething):
ip_info = socket.getaddrinfo(n, 80)
b = list(["nslookup of " + str(n) +"\n"] + ip_info +(["\n" + "Result of " +str(n)]))
values = ''.join(str(v) for v in b)
abc = values+ "\n"
print()
print(abc)
break
elif not os.path.exists(enterSomething):
print("No such file or directory " + str(enterSomething))
except(UnicodeError):
print("")
</code></pre>
<p>So if I had a text file with the following:</p>
<pre><code>www.google
www.espn
</code></pre>
<p>it would return </p>
<pre><code>nslookup of www.google.com
(<AddressFamily.AF_INET: 2>, 0, 0, '', ('172.217.1.68', 80))(<AddressFamily.AF_INET6: 23>, 0, 0, '', ('2607:f8b0:4006:808::2004', 80, 0, 0))
Result of www.google.com
nslookup of www.espn.com
(<AddressFamily.AF_INET: 2>, 0, 0, '', ('199.181.133.5', 80))
Result of www.espn.com
</code></pre>
<p>My question is that is there is a way I can extract only the corresponding ip addresses such as <code>172.217.1.68</code> and <code>2607:f8b0:4006:808::2004</code> for www.google.com and so on?</p>
| 0 | 2016-08-05T12:51:46Z | 38,789,901 | <p>So your code returns a tuple, tuples can be indexed much like a list.</p>
<p>here's what I tested </p>
<pre><code>google = socket.getaddrinfo('www.google.com', 80)
google[0][4]
returns ('74.125.141.104', 80)
</code></pre>
<p>thus to get the ip address associated
do</p>
<pre><code>google[0][4][0]
</code></pre>
<p>to get</p>
<pre><code>'74.125.141.104'
</code></pre>
| 0 | 2016-08-05T13:00:08Z | [
"python",
"string",
"loops"
] |
Selecting rows from Pandas Series where rows are arrays | 38,789,717 | <p>I'm trying to analyze US polling data, specifically, I'm trying to work out which States are safe, marginal, or tight ('closeness'). I have a dataframe with survey results by time and their 'closeness'. I'm using this Pandas statement to get a summary of the 'closeness' entries.</p>
<pre><code>s=self.daily.groupby('State')['closeness'].unique()
</code></pre>
<p>This is giving me this series (selection shown for brevity):</p>
<pre><code>State
AK [safe]
AL [safe]
CA [safe]
CO [safe, tight, marginal]
FL [marginal, tight]
IA [safe, tight, marginal]
ID [safe]
IL [safe]
IN [tight, safe]
Name: closeness, dtype: object
</code></pre>
<p>The rows are of type array, so, for example, <code>s[0]</code> gives:</p>
<pre><code>array(['safe'], dtype=object)
</code></pre>
<p>I'm trying to select from this series, but I can't get the syntax right. For example, I'm trying to select just the 'safe' States using this syntax:</p>
<pre><code>ipdb> s[s == 'safe']
*** ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code></pre>
<p>this doesn't work either:</p>
<pre><code>test[test == ['safe'])
</code></pre>
<p>Here's what I'd like to do: select States that are 'marginal' or 'tight', select States that are 'safe' and only 'safe' and so on. Does anyone have any idea of the syntax I should use, or a better approach in the first place?</p>
<p>============
Here's a sample of the data before the groupby:</p>
<pre><code>ipdb> self.daily.head(3)
Date Democratic share Margin Method Other share \
0 2008-11-04 0.378894 -0.215351 Election 0.026861
1 2008-11-04 0.387404 -0.215765 Election 0.009427
2 2008-11-04 0.388647 -0.198512 Election 0.024194
Republican share State closeness winner
0 0.594245 AK safe Republican
1 0.603169 AL safe Republican
</code></pre>
| 1 | 2016-08-05T12:52:29Z | 38,789,874 | <p>Say you have a DataFrame with a series of lists, say:</p>
<pre><code>df = pd.DataFrame({'a': [['safe'], ['safe', 'tight'], []]})
</code></pre>
<p>Then to see which ones are exactly safe, you can use:</p>
<pre><code>In [7]: df.a.apply(lambda x: x == ['safe'])
Out[7]:
0 True
1 False
2 False
Name: a, dtype: bool
</code></pre>
<p>To find the ones which include safe, you can use:</p>
<pre><code> In [9]: df.a.apply(lambda x: 'safe' in x)
Out[9]:
0 True
1 True
2 False
Name: a, dtype: bool
</code></pre>
<p>and so on.</p>
| 1 | 2016-08-05T12:58:49Z | [
"python",
"pandas"
] |
Selecting rows from Pandas Series where rows are arrays | 38,789,717 | <p>I'm trying to analyze US polling data, specifically, I'm trying to work out which States are safe, marginal, or tight ('closeness'). I have a dataframe with survey results by time and their 'closeness'. I'm using this Pandas statement to get a summary of the 'closeness' entries.</p>
<pre><code>s=self.daily.groupby('State')['closeness'].unique()
</code></pre>
<p>This is giving me this series (selection shown for brevity):</p>
<pre><code>State
AK [safe]
AL [safe]
CA [safe]
CO [safe, tight, marginal]
FL [marginal, tight]
IA [safe, tight, marginal]
ID [safe]
IL [safe]
IN [tight, safe]
Name: closeness, dtype: object
</code></pre>
<p>The rows are of type array, so, for example, <code>s[0]</code> gives:</p>
<pre><code>array(['safe'], dtype=object)
</code></pre>
<p>I'm trying to select from this series, but I can't get the syntax right. For example, I'm trying to select just the 'safe' States using this syntax:</p>
<pre><code>ipdb> s[s == 'safe']
*** ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code></pre>
<p>this doesn't work either:</p>
<pre><code>test[test == ['safe'])
</code></pre>
<p>Here's what I'd like to do: select States that are 'marginal' or 'tight', select States that are 'safe' and only 'safe' and so on. Does anyone have any idea of the syntax I should use, or a better approach in the first place?</p>
<p>============
Here's a sample of the data before the groupby:</p>
<pre><code>ipdb> self.daily.head(3)
Date Democratic share Margin Method Other share \
0 2008-11-04 0.378894 -0.215351 Election 0.026861
1 2008-11-04 0.387404 -0.215765 Election 0.009427
2 2008-11-04 0.388647 -0.198512 Election 0.024194
Republican share State closeness winner
0 0.594245 AK safe Republican
1 0.603169 AL safe Republican
</code></pre>
| 1 | 2016-08-05T12:52:29Z | 38,796,232 | <p>dataframe sample given by OP :</p>
<pre><code>In[66]:df
Out[66]:
Date Democratic share Margin Method Other share 0 2008-11-04 0.378894 -0.215351 Election 0.026861
1 2008-11-04 0.387404 -0.215765 Election 0.009427
2 2008-11-04 0.388647 -0.198512 Election 0.024194
3 2008-11-04 0.384547 -0.194545 Election 0.024194
4 2008-11-04 0.345330 -0.194512 Election 0.024459
Republican share State closeness winner
0 0.594245 AK safe Republican
1 0.603169 AL safe Republican
2 0.454545 CA tight Democratic
3 0.453450 CO marginal Democratic
4 0.454545 FL tight Republic
</code></pre>
<p>then by using grupby:</p>
<pre><code>In[67]:s=df.groupby('State')['closeness'].unique()
In[68]:s
Out[68]:
State
AK [safe]
AL [safe]
CA [tight]
CO [marginal]
FL [tight]
</code></pre>
<p>then using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow">np.where</a>:</p>
<pre><code>In[69]:s.ix[np.where(s=='safe')]
Out[69]:
State
AK [safe]
AL [safe]
Name: closeness, dtype: object
</code></pre>
| 0 | 2016-08-05T19:06:59Z | [
"python",
"pandas"
] |
Selecting rows from Pandas Series where rows are arrays | 38,789,717 | <p>I'm trying to analyze US polling data, specifically, I'm trying to work out which States are safe, marginal, or tight ('closeness'). I have a dataframe with survey results by time and their 'closeness'. I'm using this Pandas statement to get a summary of the 'closeness' entries.</p>
<pre><code>s=self.daily.groupby('State')['closeness'].unique()
</code></pre>
<p>This is giving me this series (selection shown for brevity):</p>
<pre><code>State
AK [safe]
AL [safe]
CA [safe]
CO [safe, tight, marginal]
FL [marginal, tight]
IA [safe, tight, marginal]
ID [safe]
IL [safe]
IN [tight, safe]
Name: closeness, dtype: object
</code></pre>
<p>The rows are of type array, so, for example, <code>s[0]</code> gives:</p>
<pre><code>array(['safe'], dtype=object)
</code></pre>
<p>I'm trying to select from this series, but I can't get the syntax right. For example, I'm trying to select just the 'safe' States using this syntax:</p>
<pre><code>ipdb> s[s == 'safe']
*** ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code></pre>
<p>this doesn't work either:</p>
<pre><code>test[test == ['safe'])
</code></pre>
<p>Here's what I'd like to do: select States that are 'marginal' or 'tight', select States that are 'safe' and only 'safe' and so on. Does anyone have any idea of the syntax I should use, or a better approach in the first place?</p>
<p>============
Here's a sample of the data before the groupby:</p>
<pre><code>ipdb> self.daily.head(3)
Date Democratic share Margin Method Other share \
0 2008-11-04 0.378894 -0.215351 Election 0.026861
1 2008-11-04 0.387404 -0.215765 Election 0.009427
2 2008-11-04 0.388647 -0.198512 Election 0.024194
Republican share State closeness winner
0 0.594245 AK safe Republican
1 0.603169 AL safe Republican
</code></pre>
| 1 | 2016-08-05T12:52:29Z | 38,797,268 | <p>I think constructing the series <code>s</code> by using <code>.unique()</code> is not the best way of attacking this problem. Try using <code>pd.crosstab</code> instead.</p>
<pre><code>import pandas as pd
daily = pd.DataFrame({'State': ['AK', 'AL', 'CA', 'CO', 'CO', 'CO', 'FL',
'FL', 'IA', 'IA', 'IA', 'ID', 'IL', 'IN', 'IN'],
'closeness': ['safe', 'safe', 'safe', 'safe', 'tight',
'marginal', 'marginal', 'tight', 'safe',
'tight', 'marginal', 'safe', 'safe',
'tight', 'safe']})
ct = pd.crosstab(daily['State'], daily['closeness'])
print(ct)
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>closeness marginal safe tight
State
AK 0 1 0
AL 0 1 0
CA 0 1 0
CO 1 1 1
FL 1 0 1
IA 1 1 1
ID 0 1 0
IL 0 1 0
IN 0 1 1
</code></pre>
<p>One the one hand, this <code>ct</code> contains exactly the same information as your <code>s</code>; on the other, it makes it trivial to select states the way you want. The two examples you proposed:</p>
<pre><code># states that are 'marginal' or 'tight'
print(ct.loc[(ct['marginal'] > 0) | (ct['tight'] > 0)]
.index.values)
# => ['CO', 'FL', 'IA', 'IN']
# States that are 'safe' and only 'safe'
print(ct.loc[(ct['safe'] > 0) & (ct['marginal'] == 0) & (ct['tight'] == 0)]
.index.values)
# => ['AK', 'AL', 'CA', 'ID', 'IL']
</code></pre>
<p>Or, using the perhaps more readable <code>.query()</code>:</p>
<pre><code># states that are 'marginal' or 'tight'
print(ct.query('marginal > 0 | tight > 0').index.values)
# => ['CO', 'FL', 'IA', 'IN']
# States that are 'safe' and only 'safe'
print(ct.query('safe > 0 & marginal == 0 & tight == 0')
.index.values)
# => ['AK', 'AL', 'CA', 'ID', 'IL']
</code></pre>
<p>Yet if you insist on using your <code>s</code>, here is how you can construct <code>ct</code> from it:</p>
<pre><code>ct = s.str.join(' ').str.get_dummies(sep=' ')
</code></pre>
| 0 | 2016-08-05T20:23:50Z | [
"python",
"pandas"
] |
Euclidean distance between elements in two different matrices? | 38,789,757 | <p>I am trying to determine the Euclidean distance for my documents from their centroids. The dimensions of the two arrays in question (<code>points</code> and <code>centers</code>) satisfy the <code>XA</code> and <code>XB</code> dimensional requirements for <code>scipy.spatial.distance.cdist</code>, but I don't know why I'm getting the below <code>ValueError</code>.</p>
<p>My code:</p>
<pre><code>import pandas as pd, numpy as np
from scipy.spatial.distance import cdist
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
corpus = pd.Series(["bye bye brutal good bye apple banana orange", "bye bye hello apple banana", "corn wheat apple banana goodbye cookie brutal", "fruit cake banana apple bye sweet sweet"])
X = vectorizer.fit_transform(corpus)
model = Kmeans(n_clusters = 2)
model.fit(X)
centers = model.cluster_centroids_
cdist(X, centers)
</code></pre>
<p>This is the error I get:</p>
<pre><code>ValueError: setting an array element with a sequence.
</code></pre>
<p>From <code>scipy.spatial.distance.cdist</code>'s documentation:</p>
<pre><code>Parameters: XA: ndarray
An Ma by n array of Ma original observations in an n-dimensional space
XB: ndarray
An Mb by n array of Mb original observations in an n-dimensional space
...
</code></pre>
<p>My <code>X</code> and <code>centers</code> <code>numpy</code> arrays certainly satisfy these dimensional conditions for <code>cdist</code>, right? What am I missing?</p>
| 0 | 2016-08-05T12:54:27Z | 38,790,315 | <p>Just a small change that you need to do:</p>
<pre><code>cdist(X.toarray(),centers)
</code></pre>
<p>Since X is an object of type <code>scipy.sparse.csr.csr_matrix</code> it will not be directly taken as a valid input by the scipy function. The method toarray() converts it to a valid numpy array</p>
| 2 | 2016-08-05T13:19:11Z | [
"python",
"numpy"
] |
Copying part of a list in Python | 38,789,853 | <p>I've searched for a relevant thread on how to do this but I cannot find anything.</p>
<p>I have an array:</p>
<pre><code>x = [a,a,a,b,a,a]
</code></pre>
<p>I want to copy the elements of the array into a new array until I find 'b'. I tried to do this with a loop but I get an error that "y is not defined", I tried initializing y but that didn't work either. Any ideas? I'm sure there is a better way to do this.</p>
<pre><code>for ii in x:
if x[ii].find(num) == 0:
break
else:
y[ii] = x[ii]
</code></pre>
| 1 | 2016-08-05T12:58:11Z | 38,789,951 | <pre><code>y = []
for e in x:
if e == 2:
break
y.append(e)
</code></pre>
<p>?</p>
| 2 | 2016-08-05T13:02:48Z | [
"python",
"arrays",
"list",
"for-loop"
] |
Copying part of a list in Python | 38,789,853 | <p>I've searched for a relevant thread on how to do this but I cannot find anything.</p>
<p>I have an array:</p>
<pre><code>x = [a,a,a,b,a,a]
</code></pre>
<p>I want to copy the elements of the array into a new array until I find 'b'. I tried to do this with a loop but I get an error that "y is not defined", I tried initializing y but that didn't work either. Any ideas? I'm sure there is a better way to do this.</p>
<pre><code>for ii in x:
if x[ii].find(num) == 0:
break
else:
y[ii] = x[ii]
</code></pre>
| 1 | 2016-08-05T12:58:11Z | 38,789,986 | <p>You could use <a href="https://docs.python.org/3/library/itertools.html#itertools.takewhile" rel="nofollow"><code>itertools.takewhile</code></a>:</p>
<pre><code>>>> x = [1,1,1,2,1,1]
>>> import itertools
>>> y = list(itertools.takewhile(lambda i: i != 2, x))
>>> y
[1, 1, 1]
</code></pre>
<p>When using a loop, you have to use <code>y.append</code>; if you do <code>y[ii] = ...</code>, then you will get an <code>IndexError</code> as you try to set e.g. the first element of an array that has zero elements. Also, when you loop like this <code>for ii in x:</code> then <code>ii</code> is already the element from <code>x</code>, i.e. you do <em>not</em> have to do <code>x[ii]</code>. In your case, this did not give an exception, since <code>x[1]</code> would be a valid element of <code>x</code>, but it would not be what you expected.</p>
| 2 | 2016-08-05T13:04:14Z | [
"python",
"arrays",
"list",
"for-loop"
] |
Copying part of a list in Python | 38,789,853 | <p>I've searched for a relevant thread on how to do this but I cannot find anything.</p>
<p>I have an array:</p>
<pre><code>x = [a,a,a,b,a,a]
</code></pre>
<p>I want to copy the elements of the array into a new array until I find 'b'. I tried to do this with a loop but I get an error that "y is not defined", I tried initializing y but that didn't work either. Any ideas? I'm sure there is a better way to do this.</p>
<pre><code>for ii in x:
if x[ii].find(num) == 0:
break
else:
y[ii] = x[ii]
</code></pre>
| 1 | 2016-08-05T12:58:11Z | 38,789,994 | <p>Try this:</p>
<pre><code>x = [1,1,1,2,1,1]
b = 2
try:
y = x[:x.index(b)]
except ValueError:
y = x[:]
</code></pre>
<p>For example:</p>
<pre><code>In [10]: x = [1,1,1,2,1,1]
...: b = 2
...:
...: try:
...: y = x[:x.index(b)]
...: except ValueError:
...: # b was not found in x. Just copy the whole thing.
...: y = x[:]
...:
In [11]: y
Out[11]: [1, 1, 1]
</code></pre>
<p>See <a href="https://docs.python.org/2.7/tutorial/datastructures.html" rel="nofollow"><code>list.index()</code></a> and the <a href="https://docs.python.org/3/tutorial/introduction.html#lists" rel="nofollow">shallow-copy slice</a> for more information.</p>
| 2 | 2016-08-05T13:04:41Z | [
"python",
"arrays",
"list",
"for-loop"
] |
Copying part of a list in Python | 38,789,853 | <p>I've searched for a relevant thread on how to do this but I cannot find anything.</p>
<p>I have an array:</p>
<pre><code>x = [a,a,a,b,a,a]
</code></pre>
<p>I want to copy the elements of the array into a new array until I find 'b'. I tried to do this with a loop but I get an error that "y is not defined", I tried initializing y but that didn't work either. Any ideas? I'm sure there is a better way to do this.</p>
<pre><code>for ii in x:
if x[ii].find(num) == 0:
break
else:
y[ii] = x[ii]
</code></pre>
| 1 | 2016-08-05T12:58:11Z | 38,790,186 | <p>Way to get things done with <a href="https://docs.python.org/2/reference/expressions.html#generator-expressions" rel="nofollow"><strong>generator expression</strong></a>:</p>
<pre><code>x = ['a', 'a', 'a', 'b', 'a', 'a']
items = list(next(iter([])) if item == 'b' else item for item in x)
print items
['a', 'a', 'a']
</code></pre>
| 1 | 2016-08-05T13:12:50Z | [
"python",
"arrays",
"list",
"for-loop"
] |
Copying part of a list in Python | 38,789,853 | <p>I've searched for a relevant thread on how to do this but I cannot find anything.</p>
<p>I have an array:</p>
<pre><code>x = [a,a,a,b,a,a]
</code></pre>
<p>I want to copy the elements of the array into a new array until I find 'b'. I tried to do this with a loop but I get an error that "y is not defined", I tried initializing y but that didn't work either. Any ideas? I'm sure there is a better way to do this.</p>
<pre><code>for ii in x:
if x[ii].find(num) == 0:
break
else:
y[ii] = x[ii]
</code></pre>
| 1 | 2016-08-05T12:58:11Z | 38,790,190 | <p>Though it is somehow similar to Will's answer, but in here it shows the use of <a href="https://docs.python.org/3/library/functions.html?highlight=slice#slice" rel="nofollow"><code>slice</code></a> built-in slicing object:</p>
<pre><code>>>> x = ['a','a','a','b','a','a']
>>> s = slice(x.index('b'))
>>>
>>> x[s]
['a', 'a', 'a']
</code></pre>
| 0 | 2016-08-05T13:12:58Z | [
"python",
"arrays",
"list",
"for-loop"
] |
Copying part of a list in Python | 38,789,853 | <p>I've searched for a relevant thread on how to do this but I cannot find anything.</p>
<p>I have an array:</p>
<pre><code>x = [a,a,a,b,a,a]
</code></pre>
<p>I want to copy the elements of the array into a new array until I find 'b'. I tried to do this with a loop but I get an error that "y is not defined", I tried initializing y but that didn't work either. Any ideas? I'm sure there is a better way to do this.</p>
<pre><code>for ii in x:
if x[ii].find(num) == 0:
break
else:
y[ii] = x[ii]
</code></pre>
| 1 | 2016-08-05T12:58:11Z | 38,790,364 | <p>I would split the array by the <code>b</code> index:</p>
<pre><code>>>> x = ['a','a','a','b','a','a']
>>> c = x.index('b')
>>> x[:c]
['a', 'a', 'a']
>>> x[c:]
['b', 'a', 'a']
</code></pre>
| 0 | 2016-08-05T13:20:52Z | [
"python",
"arrays",
"list",
"for-loop"
] |
regular expression for parentheses within quotes | 38,789,869 | <p>I want to split a string into several parts in parentheses, but the quoted things (possibly including parentheses) should be treated as a single symbol. For example, the string </p>
<p>(id1, "Hello simple"), (id2, "Hello \n weird (all chars) Ã@")</p>
<p>should be split into two parts</p>
<p>1) id1, "Hello simple"</p>
<p>2) id2, "Hello \n weird (all chars) Ã@"</p>
<p>How can I do this in Python?</p>
| -1 | 2016-08-05T12:58:41Z | 38,790,105 | <p>If you really need to use <code>regex</code>, this works with the current string from your post:</p>
<pre><code>import re
pat = re.compile(r'\(([a-zA-Z0-9"\(\)\s]+)\)')
matches = re.findall(pat, '(Hello "(world)"), (2016)')
# ['Hello "(world)"', '2016']
</code></pre>
<p>However, the <code>split</code> function may also be a viable options for the format of text. If all data is surrounded by a single pair of parantheses, you can do:</p>
<pre><code>results = [x[1:-1] for x in '(Hello "(world)"), (2016)'.split(', ')]
# ['Hello "(world)"', '2016']
</code></pre>
| 0 | 2016-08-05T13:09:22Z | [
"python"
] |
How to find the maximum no of digits in the list in python | 38,789,873 | <p>For example
If the list contains numbers 3 , 14 , 24 , 6 , 157 , 132 ,12
It should give the maximum no of digits as 3 </p>
| 1 | 2016-08-05T12:58:47Z | 38,789,911 | <p>Try this:</p>
<pre><code>max = list[0]
for i in range(1,len(list)):
if len(list[i]) > max:
max = len(list[i])
</code></pre>
| 0 | 2016-08-05T13:00:48Z | [
"python"
] |
How to find the maximum no of digits in the list in python | 38,789,873 | <p>For example
If the list contains numbers 3 , 14 , 24 , 6 , 157 , 132 ,12
It should give the maximum no of digits as 3 </p>
| 1 | 2016-08-05T12:58:47Z | 38,789,976 | <pre><code>tempMaxDig = 0
for item in numList:
num = len(str(item))
if num > tempMaxDig:
tempMaxDig = num
return tempMaxDig
</code></pre>
| 0 | 2016-08-05T13:03:42Z | [
"python"
] |
How to find the maximum no of digits in the list in python | 38,789,873 | <p>For example
If the list contains numbers 3 , 14 , 24 , 6 , 157 , 132 ,12
It should give the maximum no of digits as 3 </p>
| 1 | 2016-08-05T12:58:47Z | 38,789,989 | <p>Try this</p>
<pre><code>mylist = [3, 14, 24, 6, 157, 132, 12]
print (len(str(max([abs(element) for element in mylist]))))
#3
#This will work for negative numbers too
</code></pre>
| 2 | 2016-08-05T13:04:25Z | [
"python"
] |
How to find the maximum no of digits in the list in python | 38,789,873 | <p>For example
If the list contains numbers 3 , 14 , 24 , 6 , 157 , 132 ,12
It should give the maximum no of digits as 3 </p>
| 1 | 2016-08-05T12:58:47Z | 38,789,992 | <p>Just use :</p>
<pre><code>len(str(max(list)))
</code></pre>
<p>what we are doing here finding the maximum number, then lenght of that.</p>
| 0 | 2016-08-05T13:04:31Z | [
"python"
] |
How to find the maximum no of digits in the list in python | 38,789,873 | <p>For example
If the list contains numbers 3 , 14 , 24 , 6 , 157 , 132 ,12
It should give the maximum no of digits as 3 </p>
| 1 | 2016-08-05T12:58:47Z | 38,790,075 | <p>"Try this</p>
<pre><code>mylist = [3, 14, 24, 6, 157, 132, 12]
print (len(str(max(mylist)))
</code></pre>
<p>"</p>
<p>Sorry I would comment but < 50 rep. Credit to @soumendra</p>
<p>Soumendra's solution works but not for negative numbers. Easy way to do this is:</p>
<pre><code>mylist = [3, 14, 24, 6, 157, 132, 12]
a = len(str(max(mylist)))
b = len(str(min(mylist)))
print max([a, b])
</code></pre>
| 0 | 2016-08-05T13:07:57Z | [
"python"
] |
How to find the maximum no of digits in the list in python | 38,789,873 | <p>For example
If the list contains numbers 3 , 14 , 24 , 6 , 157 , 132 ,12
It should give the maximum no of digits as 3 </p>
| 1 | 2016-08-05T12:58:47Z | 38,790,108 | <p>The key is to treat the elements as strings so you can ask for their length or number of digits.</p>
<p>Some code </p>
<pre><code>#Your list
L = [ 3 , 14 , 24 , 6 , 157 , 132 ,12]
# Imperative
max_digits = 0
for element in L:
n_digits = len(str(element))
if n_digits > max_digits:
max_digits = n_digits
# Funtional
max_digits = reduce(lambda x,y: x if x>y else y, map(lambda x: len(str(x)), L), 0)
</code></pre>
| 0 | 2016-08-05T13:09:30Z | [
"python"
] |
How to find the maximum no of digits in the list in python | 38,789,873 | <p>For example
If the list contains numbers 3 , 14 , 24 , 6 , 157 , 132 ,12
It should give the maximum no of digits as 3 </p>
| 1 | 2016-08-05T12:58:47Z | 38,790,136 | <p>In case your list contains negative numbers you could pass generator expression calling <a href="https://docs.python.org/3.5/library/functions.html#abs" rel="nofollow"><code>abs</code></a> as an argument for <a href="https://docs.python.org/3.5/library/functions.html#max" rel="nofollow"><code>max</code></a>:</p>
<pre><code>>>> mylist = [3, 14, 24, 6, 157, 132, 12, -100]
>>> len(str(max(abs(x) for x in mylist)))
3
</code></pre>
<p>Note that above only works with integers. If your list contains other types of numbers, like <code>float</code> or <a href="https://docs.python.org/3.5/library/decimal.html" rel="nofollow"><code>Decimal</code></a> then changes are required.</p>
| 3 | 2016-08-05T13:10:29Z | [
"python"
] |
How to find the maximum no of digits in the list in python | 38,789,873 | <p>For example
If the list contains numbers 3 , 14 , 24 , 6 , 157 , 132 ,12
It should give the maximum no of digits as 3 </p>
| 1 | 2016-08-05T12:58:47Z | 38,790,377 | <p>The first requirement is to decide <em>exactly</em> what <strong>you</strong> mean by "number of digits." For example, <code>-2.1352</code> contains ... how many digits? One? Five? Six? Seven? An argument could be made in favor of each of these.</p>
<p>Then, in the case of <em>floating point</em> numbers, there's the question of rounding. Float-binary is base-<em>two</em> which must be converted to base-<em>ten</em> at some number of digits' (decimal) precision. Is that number <em>fixed?</em> Would <code>-2.3</code> (two digits? one? three?) be displayed as <code>-2.3000</code> hence five digits (four? six?).</p>
<p>A "code golf" exercise like this can be tackled in any number of ways. Step-one is to hammer out exactly what you <em>mean</em> in your statement of the problem to be coded.</p>
| 1 | 2016-08-05T13:21:42Z | [
"python"
] |
When using scipy.optimize.fmin_bfgs I got TypeError: f() missing 1 required positional argument: | 38,789,983 | <p>I'm trying to calculate minima of the six-hump camelback function using scipy.optimize.fmin_bfgs() function. Here is my code: </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize
def f(x,y):
return (4 - 2.1*x**2 + x**4/3)*x**2 + x*y + (4*y**2 - 4)*y**2
x0 = [0,0]
optimize.fmin_bfgs(f, x0)
</code></pre>
<p>Output: </p>
<pre><code>TypeError: f() missing 1 required positional argument: 'y'
</code></pre>
<p>I guess there is something wrong with the way I pass x0?</p>
| 2 | 2016-08-05T13:04:10Z | 38,790,301 | <p>Per this page there should be one array argument to <code>f</code>: <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html</a></p>
<p>Do instead:</p>
<pre><code>def f(x):
return (4 - 2.1*x[0]**2 + x[0]**4/3)*x[0]**2 + x[0]*x[1] + (4*x[1]**2 - 4)*x[1]**2
x0 = [0,0]
optimize.fmin_bfgs(f,x0)
</code></pre>
| 2 | 2016-08-05T13:18:45Z | [
"python",
"numpy",
"scipy"
] |
How to get all the tags in an XML using python? | 38,790,012 | <p>I have been researching in the Python Docs for a way to get the tag names from an XML file, but I haven't been very successful. Using the XML file below, one can get the country name tags, and all its associated child tags. Does anyone know how this is done?</p>
<pre><code><?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
</code></pre>
| 0 | 2016-08-05T13:05:27Z | 38,790,079 | <p>Look into the built-in XML functionality of Python, traverse the document recursively and collect all tags in a set.</p>
| -1 | 2016-08-05T13:08:01Z | [
"python",
"xml",
"python-3.x"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.