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
list
Give multiple terminal commands in a single file and run all the commands at once?
39,207,545
<p>I'm a beginner into Raspberry pi and i have a basic doubt.</p> <p>I'm basically trying to make my raspberry pi into a beacon and advertise data from it to a Android app. </p> <p>I wonder if I can give multiple terminal commands in a single file and run all the commands simply by compiling and running the file?</p> <p>I followed <a href="https://learn.adafruit.com/pibeacon-ibeacon-with-a-raspberry-pi/overview" rel="nofollow">this tutorial</a>. </p> <p>My basic doubt is that, each time i have to check if a device is available(bluetooth) and advertise it, it takes a command for each of this. Can i integrate multiple raspberry pi commands into a file and run all these commands simply by compiling and running the file (as a script)?</p> <p>Few of the commands are as follows :</p> <pre><code>sudo hcitool lescan, sudo hcitool hci0, sudo hcitool -i hci0 0x008, </code></pre> <p>and few commands like these..</p>
1
2016-08-29T13:30:17Z
39,209,244
<p>If you truly want to use python for this you could use the subprocess module.</p> <pre><code>import subprocess with open ('/home/pi/bluetoothcommands.txt') as btcommands: for line in btcommands: subprocess.run (line) </code></pre> <p>If you wanted this in a loop:</p> <pre><code>import subprocess with open ('/home/pi/bluetoothcommands.txt') as btcommands: while True: for line in btcommands: subprocess.run (line) </code></pre> <p>In the /home/pi/bluetoothcommands.txt file:</p> <pre><code>sudo hcitool lescan sudo hcitool hci0 sudo hcitool -i hci0 0x008 </code></pre>
1
2016-08-29T14:54:39Z
[ "python", "linux", "raspberry-pi", "bluetooth-lowenergy", "ibeacon" ]
save input() into the variable(python)
39,207,593
<p>Here is my code:</p> <pre><code>def chose_range(): while True: choice = int(input("Choose the range 100 or 1000:")) if choice == 100: n = 100 break elif choice == 1000: n = 1000 break else: print('Error, enter the right number') return n </code></pre> <p>I want to save result of this command into the variable. How can I do this in python 3?</p>
-3
2016-08-29T13:32:57Z
39,207,653
<p>Do not return within your while-loop you break (you have one indent to much).</p> <pre><code>def chose_range(): while True: choice = int(input("Choose the range 100 or 1000:")) if choice == 100: n = 100 break elif choice == 1000: n = 1000 break else: print('Error, enter the right number') return n x = chose_range() </code></pre>
2
2016-08-29T13:35:43Z
[ "python", "user-input" ]
save input() into the variable(python)
39,207,593
<p>Here is my code:</p> <pre><code>def chose_range(): while True: choice = int(input("Choose the range 100 or 1000:")) if choice == 100: n = 100 break elif choice == 1000: n = 1000 break else: print('Error, enter the right number') return n </code></pre> <p>I want to save result of this command into the variable. How can I do this in python 3?</p>
-3
2016-08-29T13:32:57Z
39,207,656
<p>Did you mean something like</p> <pre><code>res = chose_range() </code></pre>
0
2016-08-29T13:35:51Z
[ "python", "user-input" ]
save input() into the variable(python)
39,207,593
<p>Here is my code:</p> <pre><code>def chose_range(): while True: choice = int(input("Choose the range 100 or 1000:")) if choice == 100: n = 100 break elif choice == 1000: n = 1000 break else: print('Error, enter the right number') return n </code></pre> <p>I want to save result of this command into the variable. How can I do this in python 3?</p>
-3
2016-08-29T13:32:57Z
39,207,660
<p>If you mean "save the result of calling <code>chose_range()</code> into a variable (you didn't say which), then:</p> <pre><code>theVariable = chose_range() </code></pre> <p>However, note that your function does not always return a value to be saved; if it hits a <code>break</code> statement, it exits the loop without executing the <code>return</code> statement, at least in how your posted code is indented.</p>
0
2016-08-29T13:36:02Z
[ "python", "user-input" ]
Import Winreg in a Python Script
39,207,650
<p>I am currently working on a Jenkins freestyle job and one of the build steps is to run a Python script. I have been working on this job for a couple of days now and this is one of the last build steps needed to finish it off. I have reached a point where I get an error letting me know that the <strong>import winreg</strong> module does not exist. </p> <p>I have installed Jenkins on CentOS and have read some documentation stating that I am unable to import this module on this distribution.</p> <p>Is there no other way to solve this than to switch over to a Windows machine? </p> <p>Thanks</p>
0
2016-08-29T13:35:39Z
39,208,547
<p>It makes sense, the <a href="https://docs.python.org/2/library/_winreg.html#module-_winreg" rel="nofollow">_winreg docs</a> says:</p> <blockquote> <p>These functions expose the Windows registry API to Python.</p> </blockquote> <p>You could try to make it run on a windows virtual machine in your centos host or just following the official <a href="https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins+on+Red+Hat+distributions" rel="nofollow">Installing+Jenkins+on+Red+Hat+distributions</a> guide</p>
0
2016-08-29T14:19:27Z
[ "python", "winreg" ]
setup.py console_scripts entry point does not resolve import
39,207,670
<p>I have following setup.py:</p> <pre><code>from setuptools import setup from distutils.core import setup setup( name="foobar", version="0.1.0", author="Batman", author_email="batman@gmail.com", packages = ["foobar"], include_package_data=True, install_requires=[ "asyncio", ], entry_points={ 'console_scripts': [ 'foobar = foobar.__main__:main' ] }, ) </code></pre> <p>Now, the <strong>main</strong>.py file gets installed and callable by foobar out of console after installation, which is what I wanted. Problem is, <strong>main</strong>.py has import at line 3 and that does not work. </p> <p>So my folder structure is as follows</p> <pre><code>dummy/setup.py dummy/requirements.txt dummy/foobar/__init__.py dummy/foobar/__main__.py dummy/foobar/wont_be_imported_one.py </code></pre> <p>I run <code>python3 setup.py bdist</code> being in dummy directory. Upon running foobar after installation, I get error </p> <pre><code>File "/usr/local/bin/foobar", line 9, in &lt;module&gt; load_entry_point('foobar==0.1.0', 'console_scripts', 'foobar')() [...] ImportError: No module named 'wont_be_imported_one'. </code></pre> <p>UPDATE. <code>__init__.py</code> has content of</p> <pre><code>from wont_be_imported_one import wont_be_imported_one </code></pre> <p><code>wont_be_imported_one.py</code> has from <code>wont_be_imported_one</code> function which I actually need to import.</p>
1
2016-08-29T13:36:36Z
39,258,478
<p>In Python 3, <code>import</code>s are absolute by default, and so <code>from wont_be_imported_one import ...</code> inside of <code>foobar</code> will be interpreted as a reference to some module named <code>wont_be_imported_one</code> outside of <code>foobar</code>. You need to use a relative import instead:</p> <pre><code>from .wont_be_imported_one import wont_be_imported_one # ^ Add this </code></pre> <p>See <a href="https://www.python.org/dev/peps/pep-0328/" rel="nofollow">PEP 328</a> for more information.</p>
2
2016-08-31T20:29:29Z
[ "python", "setuptools" ]
Finding and comparing the minimum timedelta of 2 datetime lists python
39,207,851
<p>I have 2 lists containing <strong>datetime.timedelta</strong> values. Need help finding the minimum of both lists and comparing them to find out which is greater.</p> <p>Note: I am fairly new to Python</p> <p>This is the first list, extracting datetime values from dicts v,w:</p> <pre><code>for y in range(len(v)): try: gap.append(v[y]-w[y]) except: print "End of list" </code></pre> <p>And this is the second list, calculating intervals within dict values:</p> <pre><code>for y in range(len(v)): try: comp.append(v[y]-v[y+1]) except: print "End of list" </code></pre> <p>I want to be able to do this:</p> <pre><code>if min(comp)&lt;min(gap): print "Anomaly detected" else: print "Looks good" </code></pre>
1
2016-08-29T13:45:06Z
39,209,265
<p>you can use max and min to find out </p> <pre><code>w = [datetime.timedelta(10), datetime.timedelta(9), datetime.timedelta(0)] v = [datetime.timedelta(11), datetime.timedelta(12), datetime.timedelta(13)] max(min(v),min(w)) datetime.timedelta(11) </code></pre>
0
2016-08-29T14:55:41Z
[ "python", "python-2.7", "datetime", "timedelta" ]
Logs not getting created in Django Project
39,207,854
<p>My Django project is not creating logs, this is the Logging info in my setting.py:</p> <pre><code>LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/home/bithu/bservice/bservice/logs/djangoLog.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, },} </code></pre> <p><code>and this is how I call it from my views.py:</code></p> <p><code>import logging logger = logging.getLogger(__name__) from django.shortcuts import render from django.http import HttpResponse</code></p> <p><code>def test_view(request): #return 'OK' if request.method == 'POST': logger.info('checking') logger.info('checking') return HttpResponse('Testing Web Service.......')</code></p> <p>I have created the log files manually and given it 777 permission still the logs are not getting created .</p> <p>Can somebody shed some light on it please.</p>
0
2016-08-29T13:45:08Z
39,230,819
<p>Maybe you can try:</p> <pre><code># rest of config 'loggers': { 'your_app_name': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, },} </code></pre>
0
2016-08-30T14:53:48Z
[ "python", "django", "python-2.7", "logging" ]
Stacking a pair of columns by looking at the first column
39,207,866
<p>I struggle with making the move from Excel to Python since I'm so used to having everything be visible. Below, I'm trying to convert the table up top to the table below. Wanted to use pandas dataframes but if there's a different solution that's better then I'd love to hear it.</p> <p>Also, as an added bonus, if someone can point me to some resources that are empathetic to visual excel converts to Python, that would be awesome!</p> <p>*Note, there are actually ~350 rows of this and we could go as far as ID12 and Code 12. Also, a state could repeat in my raw data source just like VA is doing here.</p> <pre><code>State ID Code ID2 Code2 ID3 Code3 VA RIC 733 FFX 787 NULL NULL NC WIL 798 GSB 698 WSS 444 VA NPN 757 NULL NULL NULL NULL </code></pre> <p>Required Output:</p> <pre><code>State ID Code VA RIC 733 VA FFX 787 VA NPN 757 NC WIL 798 NC GSB 698 NC WSS 444 </code></pre>
1
2016-08-29T13:45:31Z
39,208,059
<p>I think <a href="https://github.com/pydata/pandas/blob/master/pandas/core/reshape.py#L805" rel="nofollow"><code>lreshape</code></a> would be ideal for this situation.</p> <pre><code>pd.lreshape(df, {'Code': ['Code', 'Code2', 'Code3'], 'ID': ['ID', 'ID2', 'ID3']}) \ .sort_values('State', ascending=False) State Code ID 0 VA 733.0 RIC 2 VA 757.0 NPN 3 VA 787.0 FFX 1 NC 798.0 WIL 4 NC 698.0 GSB 5 NC 444.0 WSS </code></pre> <p>A more generic solution apart from @MaxU's would be:</p> <pre><code>code_list = [col for col in list(df) if col.startswith('Code')] id_list = [col for col in list(df) if col.startswith('ID')] pd.lreshape(df, {'Code': code_list, 'ID': id_list}).sort_values('State', ascending=False) </code></pre>
4
2016-08-29T13:55:17Z
[ "python", "pandas", "dataframe", "reshape" ]
Efficient way to make numpy object arrays intern strings
39,207,890
<p>Consider numpy arrays of the <code>object</code> dtype. I can shove anything I want in there.</p> <p>A common use case for me is to put strings in them. However, for very large arrays, this <em>may</em> use up a lot of memory, depending on how the array is constructed. For example, if you assign a long string (e.g. "1234567890123456789012345678901234567890") to a variable, and then assign that variable to each element in the array, everything is fine:</p> <pre><code>arr = np.zeros((100000,), dtype=object) arr[:] = "1234567890123456789012345678901234567890" </code></pre> <p>The interpreter now has one large string in memory, and an array full of pointers to this one object.</p> <p>However, we can also do it wrong:</p> <pre><code>arr2 = np.zeros((100000,), dtype=object) for idx in range(100000): arr2[idx] = str(1234567890123456789012345678901234567890) </code></pre> <p>Now, the interpreter has a hundred thousand copies of my long string in memory. Not so great. (Naturally, in the above example, the generation of a new string each time is stunted - in real life, imagine reading a string from each line in a file.)</p> <p>What I want to do is, instead of assigning each element to the string, first check if it's already in the array, and if it is, use the same object as the previous entry, rather than the new object.</p> <p>Something like:</p> <pre><code>arr = np.zeros((100000,), dtype=object) seen = [] for idx, string in enumerate(file): # Length of file is exactly 100000 if string in seen: arr[idx] = seen[seen.index(string)] else: arr[idx] = string seen.append(string) </code></pre> <p>(Apologies for not posting fully running code. Hopefully you get the idea.)</p> <p>Unfortunately this requires a large number of superfluous operations on the <code>seen</code> list. I can't figure out how to make it work with <code>set</code>s either.</p> <p>Suggestions?</p>
2
2016-08-29T13:46:44Z
39,208,145
<p>Here's one way to do it, using a dictionary whose values are equal to its keys:</p> <pre><code>seen = {} for idx, string in enumerate(file): arr[idx] = seen.setdefault(string, string) </code></pre>
2
2016-08-29T13:59:30Z
[ "python", "numpy" ]
If statement in python Pandas
39,207,921
<p>I've a dataframe called family in pandas that I've created following an sql code. I've done all of it except this line. The sql code is the following </p> <pre><code>SELECT IF(name Is Null, family.last_name, family.first_name) as family.NAME from family </code></pre> <p>I've tried the following </p> <pre><code>family['NAME']= np.where(family[family.name.isnull()],family.last_name, family.first_name) </code></pre> <p>But I'm not getting anywhere, any help is appreciated. The dataframe looks something like this </p> <pre><code>name: first_name: last_name: Peter Peter Smith NaN Phil McGrath Jack Jack Jones NAN Fred Hogan </code></pre> <p>I want it to get me a new column that would look like this </p> <pre><code>NAME: Peter McGrath Jack Hogan </code></pre>
1
2016-08-29T13:48:18Z
39,208,190
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow">numpy.where(condition[, x, y])</a> function expects <code>bool</code> values as a <code>condition</code> argument:</p> <blockquote> <p><strong>condition :</strong> array_like, bool</p> <p>When True, yield x, otherwise yield y.</p> </blockquote> <p>so you can do it this way:</p> <pre><code>np.where(family.name.isnull(),family.last_name, family.first_name) </code></pre>
2
2016-08-29T14:01:09Z
[ "python", "sql", "pandas" ]
If statement in python Pandas
39,207,921
<p>I've a dataframe called family in pandas that I've created following an sql code. I've done all of it except this line. The sql code is the following </p> <pre><code>SELECT IF(name Is Null, family.last_name, family.first_name) as family.NAME from family </code></pre> <p>I've tried the following </p> <pre><code>family['NAME']= np.where(family[family.name.isnull()],family.last_name, family.first_name) </code></pre> <p>But I'm not getting anywhere, any help is appreciated. The dataframe looks something like this </p> <pre><code>name: first_name: last_name: Peter Peter Smith NaN Phil McGrath Jack Jack Jones NAN Fred Hogan </code></pre> <p>I want it to get me a new column that would look like this </p> <pre><code>NAME: Peter McGrath Jack Hogan </code></pre>
1
2016-08-29T13:48:18Z
39,208,192
<p>As MAXU said </p> <pre><code>family['NAME'] = np.where(family.name.isnull(),family.last_name, family.first_name) </code></pre> <p>was the correct code</p>
0
2016-08-29T14:01:18Z
[ "python", "sql", "pandas" ]
Python UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3
39,207,994
<p>I'm reading a config file in python getting sections and creating new config files for each section.</p> <p>However.. I'm getting a decode error because one of the strings contains <code>Español=spain</code></p> <pre><code>self.output_file.write( what.replace( " = ", "=", 1 ) ) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128) </code></pre> <p>How would I adjust my code to allow for encoded characters such as these? I'm very new to this so please excuse me if this is something simple..</p> <pre><code>class EqualsSpaceRemover: output_file = None def __init__( self, new_output_file ): self.output_file = new_output_file def write( self, what ): self.output_file.write( what.replace( " = ", "=", 1 ) ) def get_sections(): configFilePath = 'C:\\test.ini' config = ConfigParser.ConfigParser() config.optionxform = str config.read(configFilePath) for section in config.sections(): configdata = {k:v for k,v in config.items(section)} confignew = ConfigParser.ConfigParser() cfgfile = open("C:\\" + section + ".ini", 'w') confignew.add_section(section) for x in configdata.items(): confignew.set(section,x[0],x[1]) confignew.write( EqualsSpaceRemover( cfgfile ) ) cfgfile.close() </code></pre>
0
2016-08-29T13:51:38Z
39,209,175
<p>If you use <code>python2</code> with <code>from __future__ import unicode_literals</code> then every string literal you write is an unicode literal, as if you would prefix every literal with <code>u"..."</code>, unless you explicityl write <code>b"..."</code>.</p> <p>This explains why you get an Unicode<i>Decode</i>Error on this line:</p> <pre><code>what.replace(" = ", "=", 1) </code></pre> <p>because what you actually do is</p> <pre><code>what.replace(u" = ",u"=",1 ) </code></pre> <p><code>ConfigParser</code> uses plain old <code>str</code> for its items when it reads a file using the <code>parser.read()</code> method, which means <code>what</code> will be a <code>str</code>. If you use unicode as arguments to <code>str.replace()</code>, then the string is converted (decoded) to unicode, the replacement applied and the result returned as unicode. But if <code>what</code> contains characters that can't be decoded to unicode using the default encoding, then you get an UnicodeDecodeError where you wouldn't expect one.</p> <p>So to make this work you can</p> <ul> <li>use explicit prefixes for byte strings: <code>what.replace(b" = ", b"=", 1)</code></li> <li>or remove the <code>unicode_litreals</code> future import.</li> </ul> <p>Generally you shouldn't mix <code>unicode</code> and <code>str</code> (python3 fixes this by making it an error in almost any case). You should be aware that <code>from __future__ import unicode_literals</code> changes every non prefixed literal to unicode and doesn't automatically change your code to work with unicode in all case. Quite the opposite in many cases.</p>
0
2016-08-29T14:51:59Z
[ "python", "parsing", "configparser", "python-config" ]
Pulling omniture data using API (fully processed) using Python giving error max_queue_checks reached
39,208,036
<p>I was trying to pull data from API (fully processed), Attaching the code snippet I used for the same:</p> <pre><code>from sitecat_py.pandas_api import SiteCatPandas report_description = { "reportSuiteID": "**********", "dateFrom": "2016-08-22", "dateTo": "2016-08-28", "dateGranularity": "day", "metrics": [{"id": "orders"},{"id": "revenue"}], "elements": [{"id": "product", "classification": "Base Item ID", "selected" : item_list}] } df = sc_pd.read_sc_api(report_description) </code></pre> <p>where, 'item_list' is a list containing 250 Base Item ID's</p> <p>This code is running fine, but occasionally the queue check crosses 20 and it throws this error in the console:</p> <pre><code>queue check 1 queue check 2 queue check 3 queue check 4 queue check 5 queue check 6 queue check 7 queue check 8 queue check 9 queue check 10 queue check 11 queue check 12 queue check 13 queue check 14 queue check 15 queue check 16 queue check 17 queue check 18 queue check 19 queue check 20 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "sitecat_py\pandas_api.py", line 65, in read_sc_api jdata = self.omni.get_report(**kwargs) File "sitecat_py\python_api.py", line 173, in get_report return self.make_queued_report_request(method, **kwargs) File "sitecat_py\python_api.py", line 82, in make_queued_report_request raise Exception('max_queue_checks reached!!') Exception: max_queue_checks reached!! </code></pre> <p>I tried to reduce the number of items in the list to 100, but I end up getting this error sometimes even with the reduced Item list (It worked the first time and gave the same error when I ran it the second time for the same item list)</p> <p>Is there any safe limit for the number of items for which I can safely pull the data for without it throwing this error since it seems to independent of number of rows ??</p> <p>Thanks in advance</p>
0
2016-08-29T13:54:06Z
39,247,392
<p>I posted the same question to this forum above, this answer was helpful</p> <p><a href="https://marketing.adobe.com/developer/forum/reporting/pulling-omniture-data-using-api-fully-processed-using-python-error-max-queue-checks-reached?page=1#comment_5281" rel="nofollow">https://marketing.adobe.com/developer/forum/reporting/pulling-omniture-data-using-api-fully-processed-using-python-error-max-queue-checks-reached?page=1#comment_5281</a></p> <p>By changing the value of 'max_queue_checks' in the 'pandas_api.py' to some higher value will allow the program to check if the data has been pulled for a longer duration, you can change it a larger number as per your requirements</p> <p>However don't make the value very large as it will allow inefficient data fetch request to run for a longer duration which will slow down the service. </p>
0
2016-08-31T10:41:01Z
[ "python", "adobe", "adobe-analytics" ]
django.db.utils.IntegrityError: (1048, "Column 'create_timestamp' cannot be null")
39,208,218
<p>This is the full output after execute script this error is present when run script on python I use django 1.10 python 2.7</p> <pre><code>File "/usr/bin/snort-sig-parser.py", line 213, in &lt;module&gt; main() File "/usr/bin/snort-sig-parser.py", line 205, in main sig_parse(sig_line, 0,options.branch,options.revision) File "/usr/bin/snort-sig-parser.py", line 173, in sig_parse sig_obj.save() File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", line 796, in save force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", line 824, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", line 908, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", line 947, in _do_insert using=using, raw=raw) File "/usr/local/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 1043, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1054, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 117, in execute six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 112, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute self.errorhandler(self, exc, value) File "/usr/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue django.db.utils.IntegrityError: (1048, "Column 'create_timestamp' cannot be null") </code></pre> <p>this script not write on mysql database.</p> <p>This is part of code on models.</p> <pre><code>class SignatureUpdateSet(models.Model): create_timestamp = models.DateTimeField() branch = models.CharField(max_length=80) revision = models.IntegerField() new_signatures = models.ManyToManyField(Signature,related_name='new_signatures') updated_signatures = models.ManyToManyField(Signature,related_name='updated_signatures') deleted_signatures = models.ManyToManyField(Signature,related_name='deleted_signatures') #blogpost_id = models.IntegerField(blank=True, null=True) blogpost = models.ForeignKey(BlogPost,null=True) class Meta: managed = False db_table = 'content_app_signatureupdateset' </code></pre>
1
2016-08-29T14:02:31Z
39,209,571
<p>Add <code>auto_now=True</code> in your <code>create_timestamp</code> field if you want to add Time Stamp automatically, else if you want to add anything other than current time stamp, you can add<code>blank=True</code> and add any custom time stamp if you like before saving. </p> <pre><code>create_timestamp = DateTimeField(auto_now=True) # To save current datetime create_timestamp = DateTimeField(blank=True) # To save any custom date time </code></pre>
0
2016-08-29T15:11:11Z
[ "python", "django" ]
Sort django queryset using a Python list
39,208,266
<p>I have a</p> <pre><code>Model Car(self.Models) # a bunch of features here </code></pre> <p>then in my views.py, I get all the cars and compute a score for them:</p> <pre><code>allCars = Car.object.all() # so you get [A, B, C, D] scoreList = someComputation(allCars) # returns [3,1,2,4] </code></pre> <p>then in my template I iterate through allCars to display them; using the ordering the query returned with I get primary key ordering, so</p> <ol> <li>A</li> <li>B</li> <li>C</li> <li>D</li> </ol> <p>However I would like to know if there is a way to order the queryset using the list I computed in the view, which would yield</p> <ol> <li>B</li> <li>C</li> <li>A</li> <li>D</li> </ol> <p>so doing something like</p> <pre><code>allCars.order_by(scoreList) </code></pre>
0
2016-08-29T14:05:04Z
39,208,427
<p>First off, to answer your question, you can't use ORM/sql to sort something that's derived from the records with complex logic, unless it's just pure math, which database can do to some extent. </p> <p>Your next option is to use python built in sorting. However, you can't sort items by a function that "take all in" and "spit all out", meaning your current function is taking a whole list and computed scores and return all scores, because you lost track of what score corresponds to which car.</p> <p>I would use a function on the model to compute the score, then sort the records accordingly:</p> <pre><code>class Car(models.Model): @property def compute_score(self): return a_score_based_on_current_car cars = Car.objects.all() cars = sorted(cars, key=lambda car: car.compute_score) </code></pre>
2
2016-08-29T14:13:47Z
[ "python", "sql", "django" ]
Pandas: how to create a year-week variable?
39,208,305
<p>I have a dataframe with datetimes</p> <pre><code>dates = pd.date_range('9/25/2010', periods=10, freq='D') df = pd.DataFrame({'col':dates}) df['col']=pd.to_datetime(df['col']) df['dow'] = df.col.dt.dayofweek df['week'] = df.col.dt.to_period('W') df['week_alt']=df.col.dt.year.astype(str) + '-w' + df.col.dt.week.astype(str) df Out[21]: col dow week week_alt 0 2010-09-25 5 2010-09-20/2010-09-26 2010-w38 1 2010-09-26 6 2010-09-20/2010-09-26 2010-w38 2 2010-09-27 0 2010-09-27/2010-10-03 2010-w39 3 2010-09-28 1 2010-09-27/2010-10-03 2010-w39 4 2010-09-29 2 2010-09-27/2010-10-03 2010-w39 5 2010-09-30 3 2010-09-27/2010-10-03 2010-w39 6 2010-10-01 4 2010-09-27/2010-10-03 2010-w39 7 2010-10-02 5 2010-09-27/2010-10-03 2010-w39 8 2010-10-03 6 2010-09-27/2010-10-03 2010-w39 9 2010-10-04 0 2010-10-04/2010-10-10 2010-w40 </code></pre> <p>Here you can see that a week starts on <code>Monday</code> and ends on <code>Sunday</code>. </p> <p>I would like to have control over when a week starts. For instance, if weeks now start on Sunday instead, then <code>2010-09-26</code> would be <code>2010-w39</code> and <code>2010-10-03</code> be <code>2010-w40</code>. </p> <p>How can I do that in Pandas?</p>
1
2016-08-29T14:07:12Z
39,208,375
<p><strong>UPDATE:</strong> you can choose between these three UNIX modifiers: <code>%U</code>,<code>%V</code>,<code>%W</code>:</p> <blockquote> <p><strong>%U</strong> week number of year, with Sunday as first day of week (00..53).</p> <p><strong>%V</strong> ISO week number, with Monday as first day of week (01..53). </p> <p><strong>%W</strong> week number of year, with Monday as first day of week (00..53).</p> </blockquote> <pre><code>In [189]: df.col.dt.strftime('%U-%V-%W') Out[189]: 0 38-38-38 1 39-38-38 2 39-39-39 3 39-39-39 4 39-39-39 5 39-39-39 6 39-39-39 7 39-39-39 8 40-39-39 9 40-40-40 Name: col, dtype: object </code></pre> <p><code>%U</code> week number of year, with Sunday as first day of week (00..53).</p> <pre><code>In [190]: df.col.dt.strftime('%Y-w%U') Out[190]: 0 2010-w38 1 2010-w39 2 2010-w39 3 2010-w39 4 2010-w39 5 2010-w39 6 2010-w39 7 2010-w39 8 2010-w40 9 2010-w40 Name: col, dtype: object </code></pre> <p><code>%V</code> ISO week number, with Monday as first day of week (01..53). </p> <pre><code>In [191]: df.col.dt.strftime('%Y-w%V') Out[191]: 0 2010-w38 1 2010-w38 2 2010-w39 3 2010-w39 4 2010-w39 5 2010-w39 6 2010-w39 7 2010-w39 8 2010-w39 9 2010-w40 Name: col, dtype: object </code></pre> <p><strong>OLD answer:</strong></p> <p>is that what you want?</p> <pre><code>In [73]: df['week'] = df.date.dt.year.astype(str) + '-w' + df.date.dt.week.astype(str) In [74]: df Out[74]: date week 0 2012-01-01 2012-w52 1 2012-01-02 2012-w1 2 2012-02-01 2012-w5 </code></pre>
2
2016-08-29T14:11:29Z
[ "python", "pandas", "dataframe" ]
dictionary python with a csv file
39,208,352
<p>I'm new at all this coding but have lots of motivation even when things don't work.</p> <p>I'm trying to work on a dictionary with a CSV file. I get to open and edit a new file but I think I'm missing something when trying to read from the csv file. I'm getting errors in rows 39-41 i'm probably doing something wrong but what is it? Here is the code:</p> <pre><code>import csv import os import os.path phonebook = {} def print_menu(): print('1. Print phone book') print('2. add phone book') print('3. look for number using first name only') print('4. look by last name') print('5. exit') print() menu_selection = 0 while menu_selection != 5: if os.path.isfile('my_phonebook.csv') == True: csv_file = open('my_phonebook.csv', 'a', newline = '') writer = csv.writer(csv_file) else: csv_file = open('my_phonebook.csv', 'w', newline = '') writer = csv.writer(csv_file) headers = ['first_name','last_name','phone_number'] writer.writerow(headers) print_menu() menu_selection = int(input('type menu selection number')) if menu_selection == 2: #add list in phone book first_name = input("enter first name: ") last_name = input("enter last name: ") phone_number = input("enter phone number: ") writer.writerow([first_name,last_name,phone_number]) csv_file.close() elif menu_selection == 1: #print phone book print("phone book:") listGen = csv.reader(csv_file, delimiter=' ', quotechar='|') #error starts here and in the next two rows... for row in csv_file: print(row) elif menu_selection == 3: #look for number using first name only print('look up number') first_name = input('first name:') if first_name in phonebook: print('the number is', phonebook[phone_number]) else: print('name not found') elif menu_selection == 4: #print all details of last name entered print('search by last name') last_name = input('please enter last name: ') for row in csv_file: print(row) </code></pre>
-2
2016-08-29T14:10:18Z
39,208,438
<p>Does the file have any contents? Looks like you're trying to loop over an empty iterator of lines. Try something like...</p> <pre><code>for row in csv_file: print(row) else: print('no phone numbers') </code></pre> <p>And see what you get.</p>
1
2016-08-29T14:14:15Z
[ "python", "csv", "dictionary" ]
dictionary python with a csv file
39,208,352
<p>I'm new at all this coding but have lots of motivation even when things don't work.</p> <p>I'm trying to work on a dictionary with a CSV file. I get to open and edit a new file but I think I'm missing something when trying to read from the csv file. I'm getting errors in rows 39-41 i'm probably doing something wrong but what is it? Here is the code:</p> <pre><code>import csv import os import os.path phonebook = {} def print_menu(): print('1. Print phone book') print('2. add phone book') print('3. look for number using first name only') print('4. look by last name') print('5. exit') print() menu_selection = 0 while menu_selection != 5: if os.path.isfile('my_phonebook.csv') == True: csv_file = open('my_phonebook.csv', 'a', newline = '') writer = csv.writer(csv_file) else: csv_file = open('my_phonebook.csv', 'w', newline = '') writer = csv.writer(csv_file) headers = ['first_name','last_name','phone_number'] writer.writerow(headers) print_menu() menu_selection = int(input('type menu selection number')) if menu_selection == 2: #add list in phone book first_name = input("enter first name: ") last_name = input("enter last name: ") phone_number = input("enter phone number: ") writer.writerow([first_name,last_name,phone_number]) csv_file.close() elif menu_selection == 1: #print phone book print("phone book:") listGen = csv.reader(csv_file, delimiter=' ', quotechar='|') #error starts here and in the next two rows... for row in csv_file: print(row) elif menu_selection == 3: #look for number using first name only print('look up number') first_name = input('first name:') if first_name in phonebook: print('the number is', phonebook[phone_number]) else: print('name not found') elif menu_selection == 4: #print all details of last name entered print('search by last name') last_name = input('please enter last name: ') for row in csv_file: print(row) </code></pre>
-2
2016-08-29T14:10:18Z
39,209,417
<p>Please check the below code. There were some other errors also which I tried to fix.Did couple of changes for the same.</p> <p>For reading csv, I didn't use csv reader module.</p> <p>If you want to use that, please replace the code in search() function.</p> <pre><code>import csv import os import os.path phonebook = {} def print_menu(): print('1. Print phone book') print('2. add phone book') print('3. look for number using first name only') print('4. look by last name') print('5. exit') print() def search(name): phonebook = open('my_phonebook.csv','r') name_found = True for line in phonebook: if name in line: fname,lname,num = line.split(',') print "First Name is ",fname.strip() print "Last Name is ",lname.strip() print 'the number is', num.strip() name_found = True if not name_found: print('name not found') return menu_selection = 0 while menu_selection != 5: print_menu() menu_selection = int(input('type menu selection number - ')) if menu_selection == 2: #add list in phone book if os.path.isfile('my_phonebook.csv') == True: csv_file = open('my_phonebook.csv', 'a') writer = csv.writer(csv_file) else: csv_file = open('my_phonebook.csv', 'w') writer = csv.writer(csv_file) headers = ['first_name','last_name','phone_number'] writer.writerow(headers) first_name = input("enter first name: ") last_name = input("enter last name: ") phone_number = input("enter phone number: ") writer.writerow([first_name,last_name,phone_number]) csv_file.close() elif menu_selection == 1: #print phone book print("phone book:") if os.path.isfile('my_phonebook.csv') == True: csv_file=open('my_phonebook.csv','r') for row in csv_file: print(row) csv_file.close() else: print "Phone book file not created. First create it to read it" elif menu_selection == 3: #look for number using first name only print('look up number') first_name = input('first name:') search(first_name) elif menu_selection == 4: #print all details of last name entered print('search by last name') last_name = input('please enter last name: ') search(last_name) </code></pre> <p>Output:</p> <pre><code>C:\Users\dinesh_pundkar\Desktop&gt;python b.py 1. Print phone book 2. add phone book 3. look for number using first name only 4. look by last name 5. exit () type menu selection number - 1 phone book: Phone book file not created. First create it to read it 1. Print phone book 2. add phone book 3. look for number using first name only 4. look by last name 5. exit () type menu selection number - 2 enter first name: "Dinesh" enter last name: "Pundkar" enter phone number: "12345" 1. Print phone book 2. add phone book 3. look for number using first name only 4. look by last name 5. exit () type menu selection number - 1 phone book: first_name,last_name,phone_number Dinesh,Pundkar,12345 1. Print phone book 2. add phone book 3. look for number using first name only 4. look by last name 5. exit () type menu selection number - 3 look up number first name:"Dinesh" First Name is Dinesh Last Name is Pundkar the number is 12345 1. Print phone book 2. add phone book 3. look for number using first name only 4. look by last name 5. exit () type menu selection number - 4 search by last name please enter last name: "Pundkar" First Name is Dinesh Last Name is Pundkar the number is 12345 1. Print phone book 2. add phone book 3. look for number using first name only 4. look by last name 5. exit () type menu selection number - 5 C:\Users\dinesh_pundkar\Desktop&gt; </code></pre>
0
2016-08-29T15:03:13Z
[ "python", "csv", "dictionary" ]
Is a dictionary the right data structure for this?
39,208,453
<p>I would like to use a data structure that would allow me to store my data like this:</p> <pre><code>data[1][a] data[1][b] data[1][c] data[1][d] data[2][a] data[2][b] </code></pre> <p>... With the labels a, b, c, d known from the beginning, while i iter over the 1, 2, ... from a list.</p> <p>I thought about using a dictionary:</p> <pre><code>dict={} #How to initialize the dictionary ? mylist=(1, 2, ...) for i in mylist: dict[i][a]=something dict[i][b]=something_else etc </code></pre> <p>1) Is it the best data structure to use ? Else what would you use ? 2) If using the dictionary structure how to initialize the dictionary with the labels a, b, c &amp; d ?</p>
1
2016-08-29T14:14:49Z
39,208,822
<p>I suggest a list of dictionaries. And I suggest that you replace your suggested iteration:</p> <pre><code>for i in mylist: dict[i][a]=something </code></pre> <p>With this:</p> <pre><code>for elem in list_of_dicts: elem[a] = something </code></pre> <p>If for some reason, you really need the list index, you can do the following:</p> <pre><code>for i, elem in enumerate(list_of_dicts): elem[a] = something # or list_of_dicts[i][a] = something </code></pre> <p>Regarding your question about initializing.</p> <pre><code>list_of_dicts = list() list_of_dicts.append( { a : b, c : d } ) list_of_dicts.append( { e : f, g : h } ) </code></pre>
0
2016-08-29T14:34:32Z
[ "python", "dictionary", "data-structures", "label" ]
Is a dictionary the right data structure for this?
39,208,453
<p>I would like to use a data structure that would allow me to store my data like this:</p> <pre><code>data[1][a] data[1][b] data[1][c] data[1][d] data[2][a] data[2][b] </code></pre> <p>... With the labels a, b, c, d known from the beginning, while i iter over the 1, 2, ... from a list.</p> <p>I thought about using a dictionary:</p> <pre><code>dict={} #How to initialize the dictionary ? mylist=(1, 2, ...) for i in mylist: dict[i][a]=something dict[i][b]=something_else etc </code></pre> <p>1) Is it the best data structure to use ? Else what would you use ? 2) If using the dictionary structure how to initialize the dictionary with the labels a, b, c &amp; d ?</p>
1
2016-08-29T14:14:49Z
39,209,800
<p>If you want to have data[1][a] using dict. You could have a dict of dicts and initialize like so.</p> <pre><code>dict={} mylist=(1, 2, 3) labels = ('a','b','c','d') something = 'foo' for i in mylist: for l in labels: if(i in dict): dict[i].update({l:something}) else: dict[i] = {l:something} </code></pre>
1
2016-08-29T15:23:56Z
[ "python", "dictionary", "data-structures", "label" ]
removing words from a list after splitting the words :Python
39,208,488
<p>I have a list </p> <pre><code>List = ['iamcool', 'Noyouarenot'] stopwords=['iamcool'] </code></pre> <p>What I want to do is to remove stowprds from my list. I am trying to acheive this with following script </p> <pre><code>query1=List.split() resultwords = [word for word in query1 if word not in stopwords] result = ' '.join(resultwords) return result </code></pre> <p>So my result should be </p> <pre><code>result =['Noyouarenot'] </code></pre> <p>I am receiving an error </p> <pre><code>AttributeError: 'list' object has no attribute 'split' </code></pre> <p>which is right also, what small thing I am missing, please help. I appreciate every help. </p>
0
2016-08-29T14:17:04Z
39,208,542
<p>A list comprehension with a condition checking for membership in <code>stopwords</code>.</p> <pre><code>print [item for item in List if item not in stopwords] </code></pre> <p>or <code>filter</code></p> <pre><code>print filter(lambda item: item not in stopwords, List) </code></pre> <p>or <code>set</code> operations, you can refer to my answer on speed differences <a href="http://stackoverflow.com/a/38977964/6320655">here</a>.</p> <pre><code>print list(set(List) - set(stopwords)) </code></pre> <p><strong>Output -></strong> <code>['Noyouarenot']</code></p>
4
2016-08-29T14:19:18Z
[ "python", "list" ]
removing words from a list after splitting the words :Python
39,208,488
<p>I have a list </p> <pre><code>List = ['iamcool', 'Noyouarenot'] stopwords=['iamcool'] </code></pre> <p>What I want to do is to remove stowprds from my list. I am trying to acheive this with following script </p> <pre><code>query1=List.split() resultwords = [word for word in query1 if word not in stopwords] result = ' '.join(resultwords) return result </code></pre> <p>So my result should be </p> <pre><code>result =['Noyouarenot'] </code></pre> <p>I am receiving an error </p> <pre><code>AttributeError: 'list' object has no attribute 'split' </code></pre> <p>which is right also, what small thing I am missing, please help. I appreciate every help. </p>
0
2016-08-29T14:17:04Z
39,208,576
<p>It should be <code>result=[i for i in Mylist if i not in stopword]</code></p> <p>I think you should read the document like <a href="https://docs.python.org/2/tutorial/datastructures.html" rel="nofollow">this</a>.It will help you learn Python.</p> <p>By the way,I know something about NLP.<br> I think the input should be a sentence,like </p> <pre><code>input="I am Jack" </code></pre> <p>And you can use the <code>split</code> method ,<code>input.split()</code> you will get <code>["I","am","Jack"]</code>. Then use loop to determine whether it is a stopword.</p> <pre><code>stopword=["am","which"] result=[i for i in input.split() if i not in stopword] </code></pre> <p><a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow">str.split()</a></p> <p>Hope this helps.</p>
0
2016-08-29T14:21:32Z
[ "python", "list" ]
removing words from a list after splitting the words :Python
39,208,488
<p>I have a list </p> <pre><code>List = ['iamcool', 'Noyouarenot'] stopwords=['iamcool'] </code></pre> <p>What I want to do is to remove stowprds from my list. I am trying to acheive this with following script </p> <pre><code>query1=List.split() resultwords = [word for word in query1 if word not in stopwords] result = ' '.join(resultwords) return result </code></pre> <p>So my result should be </p> <pre><code>result =['Noyouarenot'] </code></pre> <p>I am receiving an error </p> <pre><code>AttributeError: 'list' object has no attribute 'split' </code></pre> <p>which is right also, what small thing I am missing, please help. I appreciate every help. </p>
0
2016-08-29T14:17:04Z
39,208,633
<p>Here's the snippet fixing your error:</p> <pre><code>lst = ['iamcool', 'Noyouarenot'] stopwords = ['iamcool'] resultwords = [word for word in lst if word not in stopwords] result = ' '.join(resultwords) print result </code></pre> <p>Another possible solution assuming your input list and stopwords list don't care about order and duplicates:</p> <pre><code>print " ".join(list(set(lst)-set(stopwords))) </code></pre>
1
2016-08-29T14:24:50Z
[ "python", "list" ]
Why my code is not encrypting the password if i inherit django user?
39,208,585
<p>Im learning about django, and i need create a customized user, called Person. I use inherit from contrib.auth.models User, but in my django administrator the form for add a new Teacher dont show the field confirm password and the password is not encrypted in the table user</p> <pre><code>from django.db import models from django.contrib.auth.models import User, UserManager # Create your models here. class Person (User): date_of_birth = models.DateField(blank=False, null=False) class Meta: abstract = True class ClassRoom (models.Model): classroom = models.CharField(max_length=3, blank=False, null=False) def __unicode__(self): return self.classroom class Teacher(Person): phone = models.PositiveIntegerField(max_length=15, blank=False, null=False) classroom = models.ManyToManyField(ClassRoom) </code></pre> <p>You can see in this photo as the first and second users is saved encripting the password(this users was added as normal user in the django administrator), but the last(creadted as Teacher in the django administrator) dont encrypt the pass.</p> <p>¿Someone can help me? <a href="http://i.stack.imgur.com/zN9jU.png" rel="nofollow">database photo user table</a></p>
1
2016-08-29T14:21:57Z
39,211,961
<p>In order to encrypt a password, you need to set it through User's <code>set_password</code> method. for example, </p> <pre><code>user = User( email=email, is_staff=False, is_active=True, is_superuser=False, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) </code></pre>
0
2016-08-29T17:33:48Z
[ "python", "django", "django-models", "django-views" ]
Basic Bar Chart with plotly
39,208,680
<p>I try to do a bar charts, with this code </p> <pre><code>import plotly.plotly as py import plotly.graph_objs as go data = [go.Bar( x=['giraffes', 'orangutans', 'monkeys'], y=[20, 14, 23] )] py.iplot(data, filename='basic-bar') </code></pre> <p>But I got this error : </p> <blockquote> <pre><code>PlotlyLocalCredentialsError Traceback (most recent call last) &lt;ipython-input-42-9eae40f28f37&gt; in &lt;module&gt;() 3 y=[20, 14, 23] 4 )] ----&gt; 5 py.iplot(data, filename='basic-bar') C:\Users\Demonstrator\Anaconda3\lib\site-packages\plotly\plotly\plotly.py </code></pre> <p>in iplot(figure_or_data, **plot_options) 149 if 'auto_open' not in plot_options: 150 plot_options['auto_open'] = False --> 151 url = plot(figure_or_data, **plot_options) 152 153 if isinstance(figure_or_data, dict):</p> <pre><code>C:\Users\Demonstrator\Anaconda3\lib\site-packages\plotly\plotly\plotly.py </code></pre> <p>in plot(figure_or_data, validate, **plot_options) 239 240 plot_options = _plot_option_logic(plot_options) --> 241 res = _send_to_plotly(figure, **plot_options) 242 if res['error'] == '': 243 if plot_options['auto_open']:</p> <pre><code>C:\Users\Demonstrator\Anaconda3\lib\site-packages\plotly\plotly\plotly.py </code></pre> <p>in _send_to_plotly(figure, **plot_options) 1401 cls=utils.PlotlyJSONEncoder) 1402 credentials = get_credentials() -> 1403 validate_credentials(credentials) 1404 username = credentials['username'] 1405 api_key = credentials['api_key']</p> <pre><code>C:\Users\Demonstrator\Anaconda3\lib\site-packages\plotly\plotly\plotly.py </code></pre> <p>in validate_credentials(credentials) 1350 api_key = credentials.get('api_key') 1351 if not username or not api_key: -> 1352 raise exceptions.PlotlyLocalCredentialsError() 1353 1354 </p> <pre><code>PlotlyLocalCredentialsError: Couldn't find a 'username', 'api-key' pair for you on your local machine. To sign in temporarily (until you stop running Python), run: &gt;&gt;&gt; import plotly.plotly as py &gt;&gt;&gt; py.sign_in('username', 'api_key') Even better, save your credentials permanently using the 'tools' module: &gt;&gt;&gt; import plotly.tools as tls &gt;&gt;&gt; tls.set_credentials_file(username='username', api_key='api-key') For more help, see https://plot.ly/python. </code></pre> </blockquote> <p>Any idea to help me please?</p> <p>Thank you</p>
0
2016-08-29T14:27:13Z
39,208,868
<p>You need to pay attention to the traceback in the error. In this case, it's even more helpful than usual. The solution is given to you here:</p> <pre><code>PlotlyLocalCredentialsError: Couldn't find a 'username', 'api-key' pair for you on your local machine. To sign in temporarily (until you stop running Python), run: &gt;&gt;&gt; import plotly.plotly as py &gt;&gt;&gt; py.sign_in('username', 'api_key') Even better, save your credentials permanently using the 'tools' module: &gt;&gt;&gt; import plotly.tools as tls &gt;&gt;&gt; tls.set_credentials_file(username='username', api_key='api-key') For more help, see https://plot.ly/python. </code></pre> <p>So, enter your credentials used when you signed up to the site before you attempt to make a plot. You may have to sign in in a web browser and request for an API key to be generated, it is not the same as your password.</p>
1
2016-08-29T14:37:06Z
[ "python", "plot", "plotly" ]
Python list of dictionaries: Get last item of each day
39,208,735
<p>I have a list of dictionaries, ordered by the key <code>date</code>:</p> <pre><code>d = [{'date': datetime.strptime('2016-01-01 07:00', "%Y-%m-%d %H:%M"), 'val': 1}, {'date': datetime.strptime('2016-01-01 23:00', "%Y-%m-%d %H:%M"), 'val': 3}, {'date': datetime.strptime('2016-01-02 07:00', "%Y-%m-%d %H:%M"), 'val': 5}, {'date': datetime.strptime('2016-01-02 22:13', "%Y-%m-%d %H:%M"), 'val': 7}, {'date': datetime.strptime('2016-01-02 23:00', "%Y-%m-%d %H:%M"), 'val': 9}, {'date': datetime.strptime('2016-01-03 00:10', "%Y-%m-%d %H:%M"), 'val': 17}, {'date': datetime.strptime('2016-01-03 09:12', "%Y-%m-%d %H:%M"), 'val': 25}, {'date': datetime.strptime('2016-01-03 21:52', "%Y-%m-%d %H:%M"), 'val': 37}] </code></pre> <p>And i want to get the last(latest) item of each day, so in this case it would be:</p> <pre><code>{'date': datetime.strptime('2016-01-01 23:00', "%Y-%m-%d %H:%M"), 'val': 3}, {'date': datetime.strptime('2016-01-02 23:00', "%Y-%m-%d %H:%M"), 'val': 9}, {'date': datetime.strptime('2016-01-03 21:52', "%Y-%m-%d %H:%M"), 'val': 37}, </code></pre> <p>I have the following piece of code which does the trick:</p> <pre><code>previous_item = None wanted_data = [] for index, entry in enumerate(d): if not previous_item: previous_item = entry continue if entry['date'].date() != previous_item['date'].date(): wanted_data.append(previous_item) previous_item = entry #Add as well the last item if index + 1 == len(d): wanted_data.append(entry) </code></pre> <p>But i believe there are better and faster ways to do it... Besides, thats pretty ugly.</p> <p>Is there a more pythonish way to achieve this?</p> <p>Thanks!</p>
1
2016-08-29T14:30:19Z
39,208,951
<p>Assuming that the data is already sorted by <code>'date'</code> (it seems to be in your case), you can use <a href="https://docs.python.org/3.5/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> to group by the <code>date()</code>, and then get the last item from each group.</p> <pre><code>&gt;&gt;&gt; d = sorted(d, key=lambda x: x["date"]) # only if not already sorted &gt;&gt;&gt; groups = itertools.groupby(d, lambda x: x["date"].date()) &gt;&gt;&gt; wanted_data = [list(grp)[-1] for key, grp in groups] &gt;&gt;&gt; wanted_data [{'date': datetime.datetime(2016, 1, 1, 23, 0), 'val': 3}, {'date': datetime.datetime(2016, 1, 2, 23, 0), 'val': 9}, {'date': datetime.datetime(2016, 1, 3, 21, 52), 'val': 37}] </code></pre> <p>Note that this will expand each of the groups into a <code>list</code>. If this is too expensive, because there are very many entries for each date, you could create a function to get the last entry from an iterator, e.g. using <code>reduce</code> (or <code>functools.reduce</code> in Python 3):</p> <pre><code>&gt;&gt;&gt; last = lambda x: functools.reduce(lambda x, y: y, x) &gt;&gt;&gt; wanted_data = [last(grp) for key, grp in groups] </code></pre>
3
2016-08-29T14:41:09Z
[ "python" ]
Solution for storing digital asset management metadata and dependencies in Python
39,208,751
<p>I'm planning to write some sort of digital management system to help users to deal with files in VCS (SVN, Perforce...) easily. The main premise is, that all files custom metadata and dependencies are stored alongside real files in VCS and not on separate database server. But when querying the metadata it would be super slow to load everything from VCS on demand, so I would like to cache all metadata and dependencies locally and just update them incrementally when needed. I need to write the whole system in Python, since it have to run in several environments that are embedding python. Theoretically my needs will be fulfilled by <strong>nosql embedded graph database with multiprocess access</strong>, but sadly I can find anything to match this criteria:</p> <ul> <li>every file can have different metadata structure, so I can't use schemas, thus no SQL db</li> <li>I need to store dependencies</li> <li>ability to search metadata and dependencies</li> <li>several processes need to be able to read the database at once</li> <li>serverless solution (only local machine will use it)</li> <li>Python support</li> <li>Optionally a way to inform connected processes about database update</li> </ul> <p>I would really appreciate if someone more experienced could point me to the right direction. I'm not looking exclusively for one silver-bullet software that would fulfill my needs, it can also be an combination of several solutions. I just don't like reinventing the well, so I would like to use 3rd party solution rather than writing something on my own.</p> <p>Thank you</p>
-2
2016-08-29T14:31:10Z
39,209,674
<p><a href="https://pypi.python.org/pypi/ZODB" rel="nofollow">ZODB</a> satisfies most of your criteria:</p> <ul> <li>support for arbitrary python constructs</li> <li>usable mostly like having everything in memory as normal objects</li> <li>if opened in read-only mode multiple processes can read at the same time (i think)</li> <li>if using with <a href="https://pypi.python.org/pypi/ZEO" rel="nofollow">ZEO</a> (server) many clients can access at the same time with automatic notification on changes. See sample application in <a href="http://www.zodb.org/en/latest/documentation/guide/zeo.html" rel="nofollow">ZEO guide</a></li> </ul> <p>You can load the same database with ZEO or ZODB so you can switch.</p> <p>There is some tutorial stuff and general info at <a href="http://www.zodb.org" rel="nofollow">http://www.zodb.org</a></p>
0
2016-08-29T15:16:31Z
[ "python", "database", "search", "nosql" ]
I'm trying to write a loop that raises the mathematical constant of pi to its powers until the result is greater than 10000
39,208,771
<pre><code> math.pi = 3.14 while math.pi &gt; 10000 print math.pi </code></pre> <p>I'm trying to write a loop that raises the mathematical constant of pi to its powers until the result is greater than 10000</p>
-4
2016-08-29T14:32:23Z
39,209,003
<p>Do you want something like this? I tried to provide an example with as similar format to what you provided. </p> <pre><code>import math exponent = 0 num = math.pi while num ** exponent &lt; 10000: print num ** exponent exponent += 1 </code></pre> <p>If we take a look at the code that you posted, you're never changing the value of pi. The loop will never start, because the value of pi will never be greater than 10,000. Also, your condition should be <code>while num ** exponent &lt; 10000:</code> because you want the while loop to execute while the result is less than 10,000. When the value is greater than 10,000, the loop will stop and no longer execute.</p>
0
2016-08-29T14:43:53Z
[ "python" ]
I'm trying to write a loop that raises the mathematical constant of pi to its powers until the result is greater than 10000
39,208,771
<pre><code> math.pi = 3.14 while math.pi &gt; 10000 print math.pi </code></pre> <p>I'm trying to write a loop that raises the mathematical constant of pi to its powers until the result is greater than 10000</p>
-4
2016-08-29T14:32:23Z
39,209,046
<p>It looks like you forgot to actually assign pi to a variable and increase it's value</p> <pre><code>p = math.pi while p &lt; 10000: p *= math.pi </code></pre> <p>or using a bit of math you can get the same result:</p> <pre><code>p = math.pi ** (math.ceil(math.log(10000) / math.log(math.pi))) </code></pre>
0
2016-08-29T14:45:41Z
[ "python" ]
How to set an GTK Entry as an default active element in Python GTK2
39,208,829
<p>How can I set a GTK entry as default activated element / widget on start so I can insert my text without click into the entry widget first?</p> <p>For example, when I start this script I want to insert into entry2 by default:</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import gtk window = gtk.Window(gtk.WINDOW_TOPLEVEL) mainbox = gtk.VBox() window.add(mainbox) mainbox.pack_start(gtk.Label("Label 1")) entry1 = gtk.Entry() mainbox.pack_start(entry1) mainbox.pack_start(gtk.Label("Label 2")) entry2 = gtk.Entry() mainbox.pack_start(entry2) window.show_all() gtk.main() </code></pre> <p>I could not find an option:</p> <ul> <li><a href="http://www.pygtk.org/pygtk2reference/class-gtkentry.html" rel="nofollow">http://www.pygtk.org/pygtk2reference/class-gtkentry.html</a></li> <li><a href="http://www.pygtk.org/pygtk2reference/class-gtkwidget.html" rel="nofollow">http://www.pygtk.org/pygtk2reference/class-gtkwidget.html</a></li> </ul>
1
2016-08-29T14:35:04Z
39,209,140
<p>Just found:</p> <p><strong>5.10. How do I focus a widget? How do I focus it before its toplevel window is shown?</strong></p> <p><a href="http://faq.pygtk.org/index.py?file=faq05.010.htp&amp;req=show" rel="nofollow">http://faq.pygtk.org/index.py?file=faq05.010.htp&amp;req=show</a></p> <pre><code>entry2.grab_focus() </code></pre> <p>.</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import gtk window = gtk.Window(gtk.WINDOW_TOPLEVEL) mainbox = gtk.VBox() window.add(mainbox) mainbox.pack_start(gtk.Label("Label 1")) entry1 = gtk.Entry() mainbox.pack_start(entry1) mainbox.pack_start(gtk.Label("Label 2")) entry2 = gtk.Entry() mainbox.pack_start(entry2) entry2.grab_focus() window.show_all() gtk.main() </code></pre>
2
2016-08-29T14:50:35Z
[ "python", "gtk2" ]
Python - Select latest file with a specific start string and extension
39,208,881
<p>Newbie: I have the following code that fetches the latest Excel file from the downloads folder, based on the Modification time:</p> <pre><code>import os import glob latest_Excel = max(glob.iglob('C:\Users\Aditya\Downloads/*.xlsx'), key=os.path.getmtime) </code></pre> <p>Now, all excel files have either <strong>'Local'</strong> or <strong>'Global'</strong> as their start name. </p> <p>For eg. Local_20160808.xlsx, Local_20160809.xlsx, Global_20160810.xlsx, Global_20160811.xlsx, etc</p> <p>So, how can we get the names of 2 files: the latest Excel file with 'Local' as the start name and the latest Excel file with 'Global' as the start name, from the same folder?</p> <p>Thanks</p>
0
2016-08-29T14:37:37Z
39,208,982
<pre><code>latest_local_Excel = max(glob.iglob('C:\Users\Aditya\Downloads/Local*.xlsx'), key=os.path.getmtime) latest_gloabl_Excel = max(glob.iglob('C:\Users\Aditya\Downloads/Global*.xlsx'), key=os.path.getmtime) </code></pre>
2
2016-08-29T14:42:57Z
[ "python", "excel" ]
Python, pandas, cumulative sum in new column on matching groups
39,208,948
<p>If I have these columns in a dataframe:</p> <pre><code>a b 1 5 1 7 2 3 1,2 3 2 5 </code></pre> <p>How do I create column <code>c</code> where column <code>b</code> is summed using groupings of column <code>a</code> (string), keeping the existing dataframe. Some rows can belong to more than one group.</p> <pre><code>a b c 1 5 15 1 7 15 2 3 11 1,2 3 26 2 5 11 </code></pre> <p>Is there an easy and efficient solution as the dataframe I have is very large.</p>
2
2016-08-29T14:41:02Z
39,209,284
<p>You can first need split column <code>a</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" rel="nofollow"><code>join</code></a> it to original <code>DataFrame</code>:</p> <pre><code>print (df.a.str.split(',', expand=True) .stack() .reset_index(level=1, drop=True) .rename('a')) 0 1 1 1 2 2 3 1 3 2 4 2 Name: a, dtype: object df1 = df.drop('a', axis=1) .join(df.a.str.split(',', expand=True) .stack() .reset_index(level=1, drop=True) .rename('a')) print (df1) b a 0 5 1 1 7 1 2 3 2 3 3 1 3 3 2 4 5 2 </code></pre> <p>Then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow"><code>transform</code></a> for <code>sum</code> without aggragation.</p> <pre><code>df1['c'] = df1.groupby(['a'])['b'].transform(sum) #cast for aggreagation join working with strings df1['a'] = df1.a.astype(str) print (df1) b a c 0 5 1 15 1 7 1 15 2 3 2 11 3 3 1 15 3 3 2 11 4 5 2 11 </code></pre> <p>Last <code>groupby</code> by index and aggregate columns by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow"><code>agg</code></a>:</p> <pre><code>print (df1.groupby(level=0) .agg({'a':','.join,'b':'first' ,'c':sum}) [['a','b','c']] ) a b c 0 1 5 15 1 1 7 15 2 2 3 11 3 1,2 3 26 4 2 5 11 </code></pre>
2
2016-08-29T14:56:38Z
[ "python", "pandas", "dataframe", "group-by", "sum" ]
Data Migrations on Django getting previous Model versions
39,208,967
<p>Im working on a data migrations which needs to change a Foreign key to a different model and alter all the existing instances foreign keys to the new Model pk. I think this can be achieved with data migrations on Django. My question is:</p> <p>¿How can I access previous versions of my models in order to perform the data migration?</p> <p>I would like to do something like this:</p> <pre><code>MyPreviousModel = previousModels.MyModel ModelAfterMigration = afterMigrations.MyModel all_previous = MyPreviousModel.objects.all() for element in all_previous: element.previous_fk = new_foreignKey ModelAfterMigrations.create(element) </code></pre>
1
2016-08-29T14:42:09Z
39,211,896
<p>Use the versioned app registry to get the model, rather than an import statement.</p> <pre><code>def my_migration(apps, schema_editor): MyModel = apps.get_model("my_app", "MyModel") </code></pre> <p>The first argument passed to your migration worker function is an app registry that has the historical versions of all your models loaded into it to match where in your history the migration sits.</p>
1
2016-08-29T17:29:19Z
[ "python", "django" ]
Python lxml objectify: Strange behaviour when changing an elements value
39,209,062
<p>I´m new to stack overflow, so "hi" to everbody and I hope someone can help me with my question...</p> <p>Recently I start to play around a bit with lxml.objectify and stumble over the following behavior, which I found to be strange. If I just create a little xml string like this:</p> <pre><code>from lxml import objectify objroot = objectify.fromstring("&lt;root&gt;somerootvalue&lt;child1/&gt;&lt;child2/&gt;&lt;child3/&gt;&lt;child4&gt;&lt;subchild1/&gt;&lt;subchild2/&gt;&lt;/child4&gt;&lt;child5&gt;&lt;subchild1/&gt;&lt;subchild2/&gt;&lt;/child5&gt;&lt;/root&gt;") objroot.child4 = True objroot.child4.subchild1 = "Foo" objroot.child4.subchild2 = "Bar" print(objroot.child4.subchild1,objroot.child4.subchild2,objroot.child4) </code></pre> <p>The output is just: Foo Bar true</p> <p>If I change the value/text of the elements then by:</p> <pre><code>from lxml import objectify objroot = objectify.fromstring("&lt;root&gt;somerootvalue&lt;child1/&gt;&lt;child2/&gt;&lt;child3/&gt;&lt;child4&gt;&lt;subchild1/&gt;&lt;subchild2/&gt;&lt;/child4&gt;&lt;child5&gt;&lt;subchild1/&gt;&lt;subchild2/&gt;&lt;/child5&gt;&lt;/root&gt;") objroot.child4 = True objroot.child4.subchild1 = "Foo" objroot.child4.subchild2 = "Bar" print(objroot.child4.subchild1,objroot.child4.subchild2,objroot.child4) objroot.child4 = False objroot.child4.subchild1 = "Foo" objroot.child4.subchild2 = "Bar" print(objroot.child4.subchild1,objroot.child4.subchild2,objroot.child4) </code></pre> <p>The output is as expected: Foo Bar true, Foo Baz false</p> <p>But if I just change the value of objroot.child4 and call the print statement, I´ve got the following error:</p> <pre><code>from lxml import objectify objroot = objectify.fromstring("&lt;root&gt;somerootvalue&lt;child1/&gt;&lt;child2/&gt;&lt;child3/&gt;&lt;child4&gt;&lt;subchild1/&gt;&lt;subchild2/&gt;&lt;/child4&gt;&lt;child5&gt;&lt;subchild1/&gt;&lt;subchild2/&gt;&lt;/child5&gt;&lt;/root&gt;") objroot.child4 = True objroot.child4.subchild1 = "Foo" objroot.child4.subchild2 = "Bar" print(objroot.child4.subchild1,objroot.child4.subchild2,objroot.child4) objroot.child4 = False objroot.child4.subchild1 = "Foo" objroot.child4.subchild2 = "Bar" print(objroot.child4.subchild1,objroot.child4.subchild2,objroot.child4) objroot.child4 = True print(objroot.child4.subchild1,objroot.child4.subchild2,objroot.child4) File "src\lxml\lxml.objectify.pyx", line 450, in lxml.objectify._lookupChildOrRaise (src\lxml\lxml.objectify.c:6586) AttributeError: no such child: subchild1 </code></pre> <p>While I expect the last output to be "Foo Bar true", I´ve got the "no such child error". So it seems that the remaining part of the tree behind child4 has been cut of? Is tha a desired behavior and if yes how can I change the text of an element in the middle of the tree without cutting the rest of?</p> <p>Thank you for your help!</p>
1
2016-08-29T14:46:25Z
39,211,468
<p>It is actually not that strange of behavior once we dig into it a bit. Using <code>root.element.subelement....</code> is not performing as you might assume it is. We can use <code>etree</code> to print out the state of the xml tree and check the structure.</p> <pre><code>from lxml import objectify, etree objroot = objectify.fromstring("&lt;root&gt;somerootvalue&lt;child1/&gt;&lt;child2/&gt;&lt;child3/&gt;&lt;child4&gt;&lt;subchild1/&gt;&lt;subchild2/&gt;&lt;/child4&gt;&lt;child5&gt;&lt;subchild1/&gt;&lt;subchild2/&gt;&lt;/child5&gt;&lt;/root&gt;") print(etree.tostring(objroot, pretty_print=True) #output: &lt;root&gt;somerootvalue &lt;child1/&gt; &lt;child2/&gt; &lt;child3/&gt; &lt;child4&gt;&lt;subchild1/&gt;&lt;subchild2/&gt;&lt;/child4&gt; &lt;child5&gt;&lt;subchild1/&gt;&lt;subchild2/&gt;&lt;/child5&gt; &lt;/root&gt; </code></pre> <p>This looks correct. So what happens when we call <code>objroot.child4 = True</code>? The API allows you to do this, but it does not just add the text. Rather, it replaces everything that was under <code>child4</code> with the text. So the subelements get dropped. We can check using:</p> <pre><code>objroot.child4 = True print(etree.tostring(objroot, pretty_print=True) #output: &lt;root&gt;somerootvalue &lt;child1/&gt; &lt;child2/&gt; &lt;child3/&gt; &lt;child4 xmlns:py="..." py:pytype="bool"&gt;true&lt;/child4&gt; &lt;child5&gt;&lt;subchild1/&gt;&lt;subchild2/&gt;&lt;/child5&gt; &lt;/root&gt; </code></pre> <p>So it has set the value of <code>child4</code> to <code>True</code>, but it has dropped the subelements. After that, when you set the values of the subelements using:</p> <pre><code>objroot.child4.subchild1 = "Foo" objroot.child4.subchild2 = "Bar" </code></pre> <p>It actually creates each subelement under <code>child4</code> and then sets the value on the fly. </p>
1
2016-08-29T17:02:31Z
[ "python", "python-3.x", "attributeerror", "lxml.objectify" ]
Running a package as a script: executing __main__.py without importing __init__.py
39,209,065
<p>My package directory is as follow:</p> <pre><code>foo/ __init__.py __main__.py setup.py </code></pre> <p>If that matters, I installed it using setuptools.</p> <p>Now, if I have a Python code with the line <code>import foo</code>, then <code>__init__.py</code> is executed and <code>__main__.py</code> is not executed. This is fine.</p> <p>But if I run the command <code>python -m foo</code>, both <code>__init__.py</code> and <code>__main__.py</code> are executed. I would like <code>__main__.py</code> to be executed without <code>__init__.py</code>.</p> <p><strong>How can I achieve that?</strong></p> <p>I have the desired behavior if I run <code>python foo</code> when <code>foo</code> is in my working directory. However, this does not work anymore when I run the command from some other directory (I have the error <code>No such file or directory</code>, as expected).</p> <hr> <p>The motivation behind that is that <code>foo</code> is a library that relies on some shared C library (call it <code>c_foo</code>). You cannot import <code>foo</code> if <code>c_foo</code> doesn't exist on your system (it throws an exception). I do not want to install automatically <code>c_foo</code> with setup.py since it may be shared or the user may want to have a custom installation. However, I want to embed an installation script in <code>foo</code> to help the user to install <code>c_foo</code> if needed. So I would like <code>python -m foo</code> to be the entry point of the installation script.</p>
0
2016-08-29T14:46:31Z
39,209,109
<p>You can't. <code>__init__</code> is the <em>core</em> of the package and will <strong>always</strong> be imported for anything from the package.</p> <p>You'll have to move the code from <code>__main__.py</code> to live outside the package, or move the code you don't want executed from <code>__init__.py</code> to another module.</p>
0
2016-08-29T14:48:43Z
[ "python", "package" ]
How to know more about built-in modules
39,209,131
<p><strong>OVERVIEW</strong></p> <p>Once you've imported a package you can query the source path using the <code>__path__</code> attribute and from there most of the time you can read the Python source code directly. The problem comes when the module in question is similar to winreg. If I do</p> <pre><code>import winreg print winreg.__path__ </code></pre> <p>I'll get the path <code>['d:\\virtual_envs\\py2711\\lib\\site-packages\\winreg']</code>, and from there I can take a look to its source code, where I can see the <code>__init__.py</code> is doing:</p> <pre><code>from __future__ import absolute_import from future.utils import PY3 if PY3: from winreg import * else: __future_module__ = True from _winreg import * </code></pre> <p>Now, because I'm a very curious person I'd like to know more about the <code>_winreg</code> implementation so I try to do:</p> <pre><code>import _winreg print winreg print dir(_winreg) </code></pre> <p>And I get <code>_winreg</code> is <code>&lt;module '_winreg' (built-in)&gt;</code>.</p> <p>Is there a <em>standard</em> way to know in which part of the source code is implemented some built-in package like this so I'll be able to read and debug it?</p>
1
2016-08-29T14:49:56Z
39,209,264
<p>For Python's modules written in C, you can always check CPython's source code over at GitHub: <a href="https://github.com/python/cpython" rel="nofollow">https://github.com/python/cpython</a></p> <p>Usually you can find them in the <code>Modules</code> folder but the <code>winreg</code> one is special, here it is: <a href="https://github.com/python/cpython/blob/master/PC/winreg.c" rel="nofollow">https://github.com/python/cpython/blob/master/PC/winreg.c</a></p>
2
2016-08-29T14:55:33Z
[ "python", "built-in" ]
Python order of conditions
39,209,145
<p>When I enter this code, the program never throws an error, even if I enter a non-number:</p> <pre><code>user_input = input("Enter a number.") if user_input.isdigit() and 0 &lt;= float(user_input) &lt;= 10: print("A number between 0 and 10.") else: print("Not a number between 0 and 10.") </code></pre> <p>But, if I enter this code, the program throws an error if I enter a non-number:</p> <pre><code>user_input = input("Enter a number.") if 0 &lt;= float(user_input) &lt;= 10 and user_input.isdigit(): print("A number between 0 and 10.") else: print("Not a number between 0 and 10.") </code></pre> <p>Does anyone know why? Does it really make a difference in which order I type conditions?</p>
0
2016-08-29T14:50:38Z
39,209,229
<p>Of course it matters.</p> <pre><code>if 0 &lt;= float(user_input) &lt;= 10 and user_input.isdigit(): </code></pre> <p>First tries to evaluate <code>float(user_input)</code>. If <code>user_input</code> is a non-number string it would raise a <code>ValueError</code>.</p> <p><br/></p> <pre><code>if user_input.isdigit() and 0 &lt;= float(user_input) &lt;= 10: </code></pre> <p>First tries to evaluate <code>user_input.isdigit()</code>. If it returns <code>False</code> then <code>0 &lt;= float(user_input) &lt;= 10</code> isn't evaluated at all.</p> <p>This behavior is called "short-circuiting". In the predicate <code>A AND B</code>, <code>B</code> will be evaluated only if <code>A</code> is <code>True</code>. Likewise, in the predicate <code>A OR B</code>, <code>B</code> will be evaluated only if <code>A</code> is <code>False</code>.</p>
2
2016-08-29T14:53:56Z
[ "python", "condition" ]
Python order of conditions
39,209,145
<p>When I enter this code, the program never throws an error, even if I enter a non-number:</p> <pre><code>user_input = input("Enter a number.") if user_input.isdigit() and 0 &lt;= float(user_input) &lt;= 10: print("A number between 0 and 10.") else: print("Not a number between 0 and 10.") </code></pre> <p>But, if I enter this code, the program throws an error if I enter a non-number:</p> <pre><code>user_input = input("Enter a number.") if 0 &lt;= float(user_input) &lt;= 10 and user_input.isdigit(): print("A number between 0 and 10.") else: print("Not a number between 0 and 10.") </code></pre> <p>Does anyone know why? Does it really make a difference in which order I type conditions?</p>
0
2016-08-29T14:50:38Z
39,209,230
<p>In the first case, the <code>isdigit()</code> method is false, so the next condition is not checked. In the second case, the <code>float()</code> is attempted and raises and exception:</p> <pre><code>... float('bob') Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; ValueError: could not convert string to float: bob &gt;&gt;&gt; </code></pre>
0
2016-08-29T14:54:04Z
[ "python", "condition" ]
How to change multiple Pandas DF columns to categorical without a loop
39,209,240
<p>I have a DataFrame where I want to change several columns from type 'object' to 'category'.</p> <p>I can change several columns at the same time for float, </p> <pre><code>dftest[['col3', 'col4', 'col5', 'col6']] = \ dftest[['col3', 'col4', 'col5', 'col6']].astype(float) </code></pre> <p>For 'category' I can not do it the same, I need to do one by one (or in a loop like <a href="http://stackoverflow.com/a/28910914/427129">here</a>).</p> <pre><code>for col in ['col1', 'col2']: dftest[col] = dftest[col].astype('category') </code></pre> <p>Question: Is there any way of doing the change for all wanted columns at once like in the 'float' example?</p> <p>If I try to do several columns at the same time I have:</p> <pre><code>dftest[['col1','col2']] = dftest[['col1','col2']].astype('category') ## NotImplementedError: &gt; 1 ndim Categorical are not supported at this time </code></pre> <p>My current working test code: </p> <pre><code>import numpy as np import pandas as pd factors= np.array([ ['a', 'xx'], ['a', 'xx'], ['ab', 'xx'], ['ab', 'xx'], ['ab', 'yy'], ['cc', 'yy'], ['cc', 'zz'], ['d', 'zz'], ['d', 'zz'], ['g', 'zz'] ]) values = np.random.randn(10,4).round(2) dftest = pd.DataFrame(np.hstack([factors,values]), columns = ['col1', 'col2', 'col3', 'col4', 'col5', 'col6']) #dftest[['col1','col2']] = dftest[['col1','col2']].astype('category') ## NotImplementedError: &gt; 1 ndim Categorical are not supported at this time ## it works with individual astype #dftest['col2'] = dftest['col2'].astype('category') #dftest['col1'] = dftest['col1'].astype('category') print(dftest) ## doing a loop for col in ['col1', 'col2']: dftest[col] = dftest[col].astype('category') dftest[['col3', 'col4', 'col5', 'col6']] = \ dftest[['col3', 'col4', 'col5', 'col6']].astype(float) dftest.dtypes </code></pre> <hr> <p>output:</p> <pre><code>col1 category col2 category col3 float64 col4 float64 col5 float64 col6 float64 dtype: object </code></pre> <p>== [update] ==</p> <p>I don't have a problem using the loop now that I know the trick, but I asked the question because I wanted to learn/understand WHY I need to do a loop for 'category' and not for float, if there is no other way of doing it.</p>
3
2016-08-29T14:54:32Z
39,209,586
<p>you can do it this way:</p> <pre><code>In [99]: pd.concat([dftest[['col1', 'col2']].apply(lambda x: x.astype('category')), dftest.ix[:, 'col3':].astype('float')], axis=1) Out[99]: col1 col2 col3 col4 col5 col6 0 a xx 0.30 2.28 0.84 0.31 1 a xx -0.13 2.04 2.62 0.49 2 ab xx -0.34 -0.32 -1.87 1.49 3 ab xx -1.18 -0.57 -0.57 0.87 4 ab yy 0.66 0.65 0.96 0.07 5 cc yy 0.88 2.43 0.76 1.93 6 cc zz 1.81 -1.40 -2.29 -0.13 7 d zz -0.05 0.60 -0.78 -0.28 8 d zz -0.36 0.98 0.23 -0.17 9 g zz -1.31 -0.84 0.02 0.47 In [100]: pd.concat([dftest[['col1', 'col2']].apply(lambda x: x.astype('category')), dftest.ix[:, 'col3':].astype('float')], axis=1).dtypes Out[100]: col1 category col2 category col3 float64 col4 float64 col5 float64 col6 float64 dtype: object </code></pre> <p>but it won't be <strong>much</strong> faster, as <code>apply()</code> method uses looping under the hood</p>
1
2016-08-29T15:11:55Z
[ "python", "pandas", "numpy", "dataframe", "categorization" ]
How to change multiple Pandas DF columns to categorical without a loop
39,209,240
<p>I have a DataFrame where I want to change several columns from type 'object' to 'category'.</p> <p>I can change several columns at the same time for float, </p> <pre><code>dftest[['col3', 'col4', 'col5', 'col6']] = \ dftest[['col3', 'col4', 'col5', 'col6']].astype(float) </code></pre> <p>For 'category' I can not do it the same, I need to do one by one (or in a loop like <a href="http://stackoverflow.com/a/28910914/427129">here</a>).</p> <pre><code>for col in ['col1', 'col2']: dftest[col] = dftest[col].astype('category') </code></pre> <p>Question: Is there any way of doing the change for all wanted columns at once like in the 'float' example?</p> <p>If I try to do several columns at the same time I have:</p> <pre><code>dftest[['col1','col2']] = dftest[['col1','col2']].astype('category') ## NotImplementedError: &gt; 1 ndim Categorical are not supported at this time </code></pre> <p>My current working test code: </p> <pre><code>import numpy as np import pandas as pd factors= np.array([ ['a', 'xx'], ['a', 'xx'], ['ab', 'xx'], ['ab', 'xx'], ['ab', 'yy'], ['cc', 'yy'], ['cc', 'zz'], ['d', 'zz'], ['d', 'zz'], ['g', 'zz'] ]) values = np.random.randn(10,4).round(2) dftest = pd.DataFrame(np.hstack([factors,values]), columns = ['col1', 'col2', 'col3', 'col4', 'col5', 'col6']) #dftest[['col1','col2']] = dftest[['col1','col2']].astype('category') ## NotImplementedError: &gt; 1 ndim Categorical are not supported at this time ## it works with individual astype #dftest['col2'] = dftest['col2'].astype('category') #dftest['col1'] = dftest['col1'].astype('category') print(dftest) ## doing a loop for col in ['col1', 'col2']: dftest[col] = dftest[col].astype('category') dftest[['col3', 'col4', 'col5', 'col6']] = \ dftest[['col3', 'col4', 'col5', 'col6']].astype(float) dftest.dtypes </code></pre> <hr> <p>output:</p> <pre><code>col1 category col2 category col3 float64 col4 float64 col5 float64 col6 float64 dtype: object </code></pre> <p>== [update] ==</p> <p>I don't have a problem using the loop now that I know the trick, but I asked the question because I wanted to learn/understand WHY I need to do a loop for 'category' and not for float, if there is no other way of doing it.</p>
3
2016-08-29T14:54:32Z
39,232,578
<p>It's not immediately clear what the result of <code>dftest[['col1','col2']].astype('category')</code> should be, i.e. whether the resulting columns should share the same categories or not.</p> <p>Looping over columns make each column have a separate set of categories. (I believe this is a desired result in your example.) </p> <p>On the other hand, <code>.astype(float)</code> works differently: it ravels the underlying values to a 1d array, casts it to floats, and then reshape it back to the original shape. This way it may be faster than just iterating over columns. You can emulate this behaviour for <code>category</code> with higher level functions:</p> <pre><code>result = dftest[['col1', 'col2']].stack().astype('category').unstack() </code></pre> <p>But then you get a single set of categories shared by the both columns:</p> <pre><code>result['col1'] Out[36]: 0 a 1 a 2 ab 3 ab 4 ab 5 cc 6 cc 7 d 8 d 9 g Name: col1, dtype: category Categories (8, object): [a &lt; ab &lt; cc &lt; d &lt; g &lt; xx &lt; yy &lt; zz] </code></pre>
1
2016-08-30T16:21:44Z
[ "python", "pandas", "numpy", "dataframe", "categorization" ]
Error in parsing json in python
39,209,261
<p>Trying to parse this json in python</p> <pre><code>'''[{"accountName":"London\"Paris\"Geneva","accountId":"1664800781","isActive":true,"timeZone":"Asia/Jerusalem","currency":"ILS"}]''' </code></pre> <p>gives this error</p> <pre><code>Traceback (most recent call last): File "unicode_test.py", line 5, in &lt;module&gt; parsed_json = json.loads(json3) File "/usr/lib/python2.7/json/__init__.py", line 338, in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/json/decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode obj, end = self.scan_once(s, idx) ValueError: Expecting , delimiter: line 1 column 25 (char 24) </code></pre> <p>whereas this json parses fine(adding extra '\')</p> <pre><code>'''[{"accountName":"London\\"Paris\\"Geneva","accountId":"1664800781","isActive":true,"timeZone":"Asia/Jerusalem","currency":"ILS"}]''' </code></pre> <p>with this code:</p> <pre><code>import json json3 = '''[{"accountName":"London\\"Paris\\"Geneva","accountId":"1664800781","isActive":true,"timeZone":"Asia/Jerusalem","currency":"ILS"}]''' parsed_json = json.loads(json3) print json.dumps(parsed_json) print parsed_json[0]['accountName'] </code></pre> <p>But the output has me confused, json.dumps() output</p> <pre><code>[{"currency": "ILS", "timeZone": "Asia/Jerusalem", "accountId": "1664800781", "isActive": true, "accountName": "London\"Paris\"Geneva"}] </code></pre> <p>actual accountName string</p> <pre><code>London"Paris"Geneva </code></pre> <p>How can I get <code>London"Paris"Geneva</code> in the json string?</p>
0
2016-08-29T14:55:27Z
39,209,392
<p>The issue you are facing is called <a href="https://docs.python.org/2/reference/lexical_analysis.html#string-literals" rel="nofollow">character escaping</a>. The parser is indeed working as intended; this is a common topic across most programming languages.</p> <p>In your particular example, you are trying to use double quotes <code>"</code> within a value, which itself is enclosed within double quotes, like this:</p> <pre><code>'accountName': "London'Paris'Geneva", </code></pre> <p>To parse the string you expected, I would do something like this:</p> <pre><code>import json json3 = '''[{"accountName": "London\'Paris\'Geneva", "accountId": "1664800781", "isActive": "true", "timeZone": "Asia/Jerusalem", "currency": "ILS"}]''' parsed_json = json.loads(json3) print (json.dumps(parsed_json)) print (parsed_json[0]['accountName']) </code></pre> <p>which produces the following output:</p> <pre><code>[{"currency": "ILS", "timeZone": "Asia/Jerusalem", "accountId": "1664800781", "isActive": "true", "accountName": "London'Paris'Geneva"}] London'Paris'Geneva </code></pre>
0
2016-08-29T15:01:47Z
[ "python", "json" ]
Error in parsing json in python
39,209,261
<p>Trying to parse this json in python</p> <pre><code>'''[{"accountName":"London\"Paris\"Geneva","accountId":"1664800781","isActive":true,"timeZone":"Asia/Jerusalem","currency":"ILS"}]''' </code></pre> <p>gives this error</p> <pre><code>Traceback (most recent call last): File "unicode_test.py", line 5, in &lt;module&gt; parsed_json = json.loads(json3) File "/usr/lib/python2.7/json/__init__.py", line 338, in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/json/decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode obj, end = self.scan_once(s, idx) ValueError: Expecting , delimiter: line 1 column 25 (char 24) </code></pre> <p>whereas this json parses fine(adding extra '\')</p> <pre><code>'''[{"accountName":"London\\"Paris\\"Geneva","accountId":"1664800781","isActive":true,"timeZone":"Asia/Jerusalem","currency":"ILS"}]''' </code></pre> <p>with this code:</p> <pre><code>import json json3 = '''[{"accountName":"London\\"Paris\\"Geneva","accountId":"1664800781","isActive":true,"timeZone":"Asia/Jerusalem","currency":"ILS"}]''' parsed_json = json.loads(json3) print json.dumps(parsed_json) print parsed_json[0]['accountName'] </code></pre> <p>But the output has me confused, json.dumps() output</p> <pre><code>[{"currency": "ILS", "timeZone": "Asia/Jerusalem", "accountId": "1664800781", "isActive": true, "accountName": "London\"Paris\"Geneva"}] </code></pre> <p>actual accountName string</p> <pre><code>London"Paris"Geneva </code></pre> <p>How can I get <code>London"Paris"Geneva</code> in the json string?</p>
0
2016-08-29T14:55:27Z
39,210,716
<p>Preceding quotes with a <code>\</code> in a string literal is called escaping it, and tells the parser that you actually mean the string contains a quote, not to end the string there. Python has two other options for that: Use a different type of quote to wrap the string, or put <code>r</code> before the string which means roughly "assume that all quotes and backslashes are already escaped."</p> <p>What's happening here is that the <code>json</code> module is re-escaping things in the output for consistency - if you load some <code>json</code>, dump it, and then load what you dump, it shouldn't change. <code>json</code> will then read that string, so you need the double-backslash so that the quotes get escaped again then. If <code>json</code> loads a string-literal containing a double-quote, the string-literal will need to have the quote preceded by <code>\\\</code>, be wrapped with single-quotes and have the quote preceded by <code>\\</code>, or else be a raw string.</p> <p>Simplifying your example, three things would work:</p> <pre><code>test = "{\"accountName\": \"London\\\"Paris\\\"Geneva\"}" </code></pre> <p>(escape all internal quotes, and also escape the backslashes around "Paris" for later re-escaping)</p> <p>and</p> <pre><code>test = '{"accountName": "London\\"Paris\\"Geneva"}' </code></pre> <p>(Using single-quotes means you don't need to escape the double-quotes, but you still need to escape the backslashes because you <em>can</em> escape things even when you don't <em>need</em> to, and you don't actually want to in this case.)</p> <p>and</p> <pre><code>test = r'{"accountName": "London\"Paris\"Geneva"}' </code></pre> <p>(Using a raw string means you're telling it nothing is escaped, so you can use backslashes safely, but you still need to use single quotes to wrap it so that the double-quotes don't end it)</p> <p>All three of which actually represent a string containing <code>"</code> around the key and value, with <code>\</code> before the <code>"</code> in the middle of the value: <code>'{"accountName": "London\"Paris\"Geneva"}'</code> but which will generally be printed as <code>\\</code> instead of <code>\</code> so that you know it's a literal <code>\</code>rather than an escape on the following character. That is to say:</p> <pre><code>&gt;&gt;&gt; print test '{"accountName": "London\\"Paris\\"Geneva"}' &gt;&gt;&gt; print test[23] '\\' </code></pre> <p>The <code>\\</code> is a representation on screen that takes two characters of space, but represents internally a single <code>\</code> character.</p> <p>The output of <code>json.loads(test)</code>, then, is a <code>dict</code>:</p> <pre><code>{'accountName': 'London"Paris"Geneva'} </code></pre> <p>And <code>json.dumps(json.loads(test)) == test</code></p> <p>If you want <code>json</code> to dump that again, it needs to re-escape those quotes to keep things readable - if it didn't put the backslashes back in, trying to re-load that would result in an error when it hit an un-escaped quote too early. You won't be able to get <code>json</code> to dump a string that includes unescaped quotes in the middle of a string, because it is required to always dump readable JSON text which can be loaded to result in the same structure it was told to dump. If you must have the actual string contain double-quotes, your options are either:</p> <ol> <li>Dump it with <code>json</code>, then process it afterwards to remove the backslashes. If the output string there is still <code>test</code>, you'd run <code>test.replace(r'\"', r'"')</code></li> <li>Process your object in some way other than by <code>json.dumps()</code>, in which case you can do it more or less however you like.</li> </ol> <p>Either way, though, you won't be able to read the result as JSON again without adding those back in.</p>
0
2016-08-29T16:14:57Z
[ "python", "json" ]
Joining hundreds of columns and column indexes into a string
39,209,287
<p>I've got what I hope is a unique/interesting problem for my first question on Stack Overflow!</p> <p>I have data on skills assessments, currently in a very large pandas dataframe. Each row represents a student, and each column contains their scores for a particular skills assessment. There are about 200 skill assessments in total, with each student having a score in only a small subset of these assessments (1 - 20 scores is typical, but some students have more).</p> <p>Example dataframe structure:</p> <pre><code>id skill1 skill2 skill3 skill4 skill5 .... 1 10 50 NaN 3 NaN 2 Nan 10 2 70 NaN 3 23 NaN 45 NaN 5 </code></pre> <p>I am attempting to get this data transformed into a space-delimited string for each student, in the following format, so that we can import it into a different datastore: </p> <pre><code>skill1:10 skill2:50 skill4:3 skill2:10 skill3:2 skill4:70 </code></pre> <p>(notice how skills without assessments scores don't get added to the list)</p> <p>I've created a lambda function to join all of these skill values with their column labels:</p> <pre><code>skillmerge = lambda row: ' '.join([str(row.index[i])+':'+str(row[i]) for i in range(0,len(row)) if row[i]!=np.nan]) </code></pre> <p>When I created a single series (1 student) to test on, the lambda function takes less than a second to create the output string in my desired format. However, when I create a dataframe with just 2 rows (again for testing purposes), the function takes several minutes just to complete those 2 rows:</p> <pre><code>testing_df['combined_skills'] = testing_df.apply(skillmerge, axis=1) </code></pre> <p>Seeing as how I have a couple million students in this dataset, I am looking for way to make this process reliably work faster. Any thoughts on where I can fix this?</p> <p>Thanks in advance for helping with my first SO question! :D</p>
2
2016-08-29T14:56:42Z
39,210,508
<p>Using <code>to_json</code> then fixing it</p> <pre><code>def to_str(x): return x.dropna().to_json(double_precision=0) \ .replace('"', '').replace(',', ' ').strip("{}") df.T.apply(to_str) </code></pre> <p>Or using list comprehension and <code>join</code></p> <pre><code>def to_str(x): return " ".join(["{}:{}".format(k, int(v)) for k, v in x.dropna().iteritems()]) df.T.apply(to_str) </code></pre> <p>Both give</p> <pre><code>id 1 skill1:10 skill2:50 skill4:3 2 skill2:10 skill3:2 skill4:70 3 skill1:23 skill3:45 skill5:5 dtype: object </code></pre> <hr> <p><strong><em>Making your solution work</em></strong></p> <pre><code>skillmerge = lambda row: ' '.join([str(row.index[i])+':'+str(row[i]) for i in range(len(row)) if not np.isnan(row[i])]) df.T.apply(skillmerge) </code></pre> <p>Notice that <code>np.nan == np.nan</code> evaluates to <code>False</code>. In order to test for <code>np.nan</code> use <code>np.isnan</code> or <code>pd.isnull</code> or <code>pd.notnull</code>. This fact was throwing off your solution. I replaced it with <code>not np.isnan</code> and it works.</p> <p>I took the opportunity to do what I'd do because I like it better.</p>
1
2016-08-29T16:02:18Z
[ "python", "pandas", "dataframe" ]
Joining hundreds of columns and column indexes into a string
39,209,287
<p>I've got what I hope is a unique/interesting problem for my first question on Stack Overflow!</p> <p>I have data on skills assessments, currently in a very large pandas dataframe. Each row represents a student, and each column contains their scores for a particular skills assessment. There are about 200 skill assessments in total, with each student having a score in only a small subset of these assessments (1 - 20 scores is typical, but some students have more).</p> <p>Example dataframe structure:</p> <pre><code>id skill1 skill2 skill3 skill4 skill5 .... 1 10 50 NaN 3 NaN 2 Nan 10 2 70 NaN 3 23 NaN 45 NaN 5 </code></pre> <p>I am attempting to get this data transformed into a space-delimited string for each student, in the following format, so that we can import it into a different datastore: </p> <pre><code>skill1:10 skill2:50 skill4:3 skill2:10 skill3:2 skill4:70 </code></pre> <p>(notice how skills without assessments scores don't get added to the list)</p> <p>I've created a lambda function to join all of these skill values with their column labels:</p> <pre><code>skillmerge = lambda row: ' '.join([str(row.index[i])+':'+str(row[i]) for i in range(0,len(row)) if row[i]!=np.nan]) </code></pre> <p>When I created a single series (1 student) to test on, the lambda function takes less than a second to create the output string in my desired format. However, when I create a dataframe with just 2 rows (again for testing purposes), the function takes several minutes just to complete those 2 rows:</p> <pre><code>testing_df['combined_skills'] = testing_df.apply(skillmerge, axis=1) </code></pre> <p>Seeing as how I have a couple million students in this dataset, I am looking for way to make this process reliably work faster. Any thoughts on where I can fix this?</p> <p>Thanks in advance for helping with my first SO question! :D</p>
2
2016-08-29T14:56:42Z
39,210,931
<p>Try this: </p> <pre><code>ld = df.set_index('id').fillna("").to_dict(orient='records') ll = [' '.join([ k +":"+ str(v) for k,v in x.iteritems() if v != "" ]) for x in ld ] ll ['skill2:50.0 skill1:10.0 skill4:3.0', 'skill3:2.0 skill2:10.0 skill4:70.0', 'skill3:45.0 skill1:23.0 skill5:5.0'] </code></pre>
0
2016-08-29T16:29:18Z
[ "python", "pandas", "dataframe" ]
Using different font (Gentium) for Matplotlib plots
39,209,465
<p>I'm trying to use Gentium Plus as the main font in matplotlib, especially for the numbers. The following works in order to use Palatino for everything, which is fine for the math font.</p> <pre><code>import matplotlib.pyplot as plt font = {'family': 'serif', 'serif': ['Palatino'], 'size': 10} plt.rc('font', **font) plt.rc('text', usetex=True) </code></pre> <p>But I would like to have Gentium Plus for the text font and numbers. Is this possible?</p>
1
2016-08-29T15:05:29Z
39,209,740
<p>You can check the available fonts in matplotlib by the following..</p> <pre><code>import matplotlib.font_manager list = matplotlib.font_manager.get_fontconfig_fonts() names = [matplotlib.font_manager.FontProperties(fname=fname).get_name() for fname in list] print names </code></pre> <p>To check for more options you can check the <a href="http://matplotlib.org/api/font_manager_api.html" rel="nofollow">documentation</a></p>
1
2016-08-29T15:20:01Z
[ "python", "matplotlib", "fonts" ]
Using different font (Gentium) for Matplotlib plots
39,209,465
<p>I'm trying to use Gentium Plus as the main font in matplotlib, especially for the numbers. The following works in order to use Palatino for everything, which is fine for the math font.</p> <pre><code>import matplotlib.pyplot as plt font = {'family': 'serif', 'serif': ['Palatino'], 'size': 10} plt.rc('font', **font) plt.rc('text', usetex=True) </code></pre> <p>But I would like to have Gentium Plus for the text font and numbers. Is this possible?</p>
1
2016-08-29T15:05:29Z
39,223,009
<p>Thanks to Denduluri I found the name for Gentium</p> <pre><code>import matplotlib import matplotlib.pyplot as plt font = {'family': 'serif', 'serif': ['Gentium Basic'], 'size': 10} plt.rc('font', **font) matplotlib.rcParams['mathtext.fontset'] = 'custom' matplotlib.rcParams['mathtext.rm'] = 'Gentium Basic' matplotlib.rcParams['mathtext.it'] = 'Gentium Basic:italic' matplotlib.rcParams['mathtext.bf'] = 'Gentium Basic:bold' </code></pre> <p>However, if you're using TeX for math formulas you probably need to use a different font than Gentium and in order to have the same style for the numbers you need to redefine them.</p> <pre><code>from matplotlib.backends.backend_pgf import FigureCanvasPgf matplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf) pgf_with_custom_preamble = { "font.family": "serif", # use serif/main font for text elements "text.usetex": True, # use inline math for ticks "pgf.preamble": [ "\\usepackage{mathpazo}", "\\usepackage{gentium}", "\\DeclareSymbolFont{sfnumbers}{T1}{gentium}{m}{n}", "\\SetSymbolFont{sfnumbers}{bold}{T1}{gentium}{bx}{n}", "\\DeclareMathSymbol{0}\mathalpha{sfnumbers}{\"30}", "\\DeclareMathSymbol{1}\mathalpha{sfnumbers}{\"31}", "\\DeclareMathSymbol{2}\mathalpha{sfnumbers}{\"32}", "\\DeclareMathSymbol{3}\mathalpha{sfnumbers}{\"33}", "\\DeclareMathSymbol{4}\mathalpha{sfnumbers}{\"34}", "\\DeclareMathSymbol{5}\mathalpha{sfnumbers}{\"35}", "\\DeclareMathSymbol{6}\mathalpha{sfnumbers}{\"36}", "\\DeclareMathSymbol{7}\mathalpha{sfnumbers}{\"37}", "\\DeclareMathSymbol{8}\mathalpha{sfnumbers}{\"38}", "\\DeclareMathSymbol{9}\mathalpha{sfnumbers}{\"39}", "\\DeclareMathSymbol{,}\mathalpha{sfnumbers}{\"2C}" ] } matplotlib.rcParams.update(pgf_with_custom_preamble) </code></pre>
0
2016-08-30T08:58:49Z
[ "python", "matplotlib", "fonts" ]
Using an '&' in a string in python
39,209,626
<p>What is the purpose of the '&amp;' in the string in this line?</p> <pre><code>exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&amp;Exit', self) </code></pre> <p>Likewise here:</p> <pre><code>fileMenu = menubar.addMenu('&amp;File') </code></pre>
0
2016-08-29T15:13:32Z
39,209,764
<p>The <code>&amp;</code> character has a special purpose if you use it in the text of a <code>QAction</code> object: If the QAction object is used in a tool button, the character directly after the <code>&amp;</code> symbol can be used as a keyboard shortcut for that button (in combination with the alt-key).</p> <p>See <a href="http://doc.qt.io/qt-5/qaction.html" rel="nofollow">http://doc.qt.io/qt-5/qaction.html</a> (resp. <a href="http://doc.qt.io/qt-5/qaction.html#QAction-2" rel="nofollow">http://doc.qt.io/qt-5/qaction.html#QAction-2</a>).</p>
2
2016-08-29T15:21:27Z
[ "python", "qt", "pyqt", "pyside" ]
Assertion error when comparing two float tensors
39,209,633
<p>I'm using tensorflow-10.0 with gpu support, and I want to compare if 2 equations return the the same thing (which they actually should). I simplified the second equation up to the point where both equations are equal, but the assert returns that they are not.</p> <p>In the following code snippet b,c,d are float32 tensors and calculated above.</p> <pre><code>a1 = tf.reduce_sum(-1/2 - 1/2*b + 1/2*tf.exp(c) + 1/2*tf.square(d), 1) a2 = tf.reduce_sum(-1/2 - 1/2*b + 1/2*tf.exp(c) + 1/2*tf.square(d), 1) a1 = control_flow_ops.with_dependencies([tf.assert_equal(a1, a2)], a1) </code></pre> <blockquote> <p>tensorflow.python.framework.errors.InvalidArgumentError: assertion failed: [Condition x == y did not hold element-wise: x = ] [../Sum:0] [0.038984224 0.047407709 0.043144785...] [y = ] [../Sum_1:0] [0.038984239 0.047407985 0.043144524...]</p> </blockquote> <p>Is there a reason, why comparing two float32 vectors lead to an assertion error (even the equation is deterministic, and handling the same values)? Rounding errors should be occur for both equations the same way, or am I wrong?</p> <p>Thanks in advance!</p>
0
2016-08-29T15:13:52Z
39,209,918
<p>The <a href="https://www.tensorflow.org/versions/r0.10/api_docs/index.html" rel="nofollow"><code>tf.reduce_sum()</code></a> operator&mdash;in common with most of TensorFlow's <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/math_ops.html#reduction" rel="nofollow">reduction operators</a>&mdash;is implemented using multiple threads to perform the reduction in parallel. However, since floating-point addition is not <a href="http://www.walkingrandomly.com/?p=5380" rel="nofollow"><strong>associative</strong></a>, and the threads may complete in a non-deterministic order, the results of aggregating the same tensor multiple times can be different. The error can be particularly large when the numbers being aggregated have a large dynamic range.</p>
2
2016-08-29T15:28:58Z
[ "python", "tensorflow" ]
Concatenating filter requests with a loop in django
39,209,634
<p>I have a list of strings that I need to determine if they are present in my model names. Currently I am using a series of if and elif statements to determine how many strings are in my list of strings then execute a filter request to my database like this (this works but is extremely inefficient as I am constantly repeating myself):</p> <pre><code>#example if my list contained only 2 strings if len(listOfStrings) == 2: queryResults = MyModel.objects.filter(Q(name__contains=listOfStrings[0])|Q(name__contains=listOfStrings[1])) </code></pre> <p>Then I notify the client based on the result of these queries. If I test the strings against my models each individually I might get the same models (because some model names contain all three or two strings) then notify the client twice. So I would think to solve this problem using a for loop like so</p> <pre><code>listOfStrings = {"string1","string2","string3"} queryResults = "" for string in listOfStrings: queryResults += MyModel.objects.filter(name__contains=string) </code></pre> <p>I understand that the <code>filter()</code> method is lazy and doesn't execute right away and that this python logic is most likely wrong. But how do I concatenate filter requests in order to avoid duplicate model results.</p>
0
2016-08-29T15:13:58Z
39,209,807
<p>You probably want to use the <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct" rel="nofollow">distinct</a> filter.</p>
1
2016-08-29T15:24:07Z
[ "python", "django" ]
python google app engine stripe integration
39,209,770
<p>I am working on a project in which i want to integrate stripe for payments. I am following their documentation to integrate it in python <a href="https://stripe.com/docs/charges" rel="nofollow">Stripe Documentation</a>. In documentation they downloaded the stripe library to use it. The code to download it was:</p> <pre><code>pip install --upgrade stripe </code></pre> <p>I followed the same steps. But i am getting this error. When i try to import it in my project.</p> <pre><code>import stripe ImportError: No module named stripe </code></pre>
1
2016-08-29T15:21:53Z
39,210,327
<p>When you pip installed stripe, it installed it in your local system. But GAE does not have that package, so you cannot simply import it in production. You need to download the package, and add it inside your app. For example, in a "libs" directory. Then, it will upload with the rest of your app when you deploy, and be available to the app. Then, you import it like this:</p> <pre><code>from libs import stripe </code></pre> <p>Assuming your app structure looks like this:</p> <pre><code>- myapp - app.yaml - otherstuff.py - libs - stripe </code></pre>
0
2016-08-29T15:51:36Z
[ "python", "google-app-engine", "stripe-payments" ]
python google app engine stripe integration
39,209,770
<p>I am working on a project in which i want to integrate stripe for payments. I am following their documentation to integrate it in python <a href="https://stripe.com/docs/charges" rel="nofollow">Stripe Documentation</a>. In documentation they downloaded the stripe library to use it. The code to download it was:</p> <pre><code>pip install --upgrade stripe </code></pre> <p>I followed the same steps. But i am getting this error. When i try to import it in my project.</p> <pre><code>import stripe ImportError: No module named stripe </code></pre>
1
2016-08-29T15:21:53Z
39,210,899
<p>The proper way to install a 3rd party library into your GAE application is described in <a href="https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27?hl=en#installing_a_library" rel="nofollow">Installing a library</a>:</p> <blockquote> <p>The easiest way to manage this is with a ./lib directory:</p> <ol> <li><p>Use pip to install the library and the vendor module to enable importing packages from the third-party library directory.</p></li> <li><p>Create a directory named lib in your application root directory:</p> <pre><code>mkdir lib </code></pre></li> <li><p>To tell your app how to find libraries in this directory, create or modify a file named appengine_config.py in the root of your project, then add these lines:</p> <pre><code>from google.appengine.ext import vendor # Add any libraries installed in the "lib" folder. vendor.add('lib') </code></pre></li> <li><p>Use pip with the -t lib flag to install libraries in this directory:</p> <pre><code>pip install -t lib gcloud </code></pre></li> </ol> </blockquote> <p><strong>Notes</strong>: </p> <ul> <li><p>When going through the mentioned doc page pay attention as it also contains instructions for requesting and using GAE-provided <em>built-in</em> libraries - different than those for <em>installed/vendored-in</em> libraries.</p></li> <li><p>if your app is a multi-module one you'll need an <code>appengine_config.py</code> for each module using the library at step#3, located beside the module's <code>.yaml</code> file. It can be symlinked for DRY reasons if you prefer (see <a href="http://stackoverflow.com/a/34291789/4495081">http://stackoverflow.com/a/34291789/4495081</a>).</p></li> <li><p>step #4's goal is to just bring the content of the stripe library in a subdirectory of the <code>lib</code> dir. You can do that manually if the pip way fails for whatever reason.</p></li> </ul>
3
2016-08-29T16:27:05Z
[ "python", "google-app-engine", "stripe-payments" ]
PyCharm wrong notification: no module named cx_Oracle
39,209,776
<p>I've installed cx_Oracle 5.2.1 for Python 2.7.10, and it works (running Win). My problem is though; PyCharm notifies me that the module name does not exists, which is not a problem in runtime. But because of this PyCharm is unable to assist me on the modules different function etc.</p> <p>Can anyone clarify please?</p> <p>I already looked into this <a href="http://stackoverflow.com/questions/36870935/pycharm-pythons-standard-libs-names-and-functions-are-underlined-as-no-modul">PyCharm: Python&#39;s standard lib&#39;s names and functions are underlined as &quot;No module named such&quot;</a> and I though it might be related. I don't see any solution though.</p> <p>EDIT 1:</p> <p>I read that it might fix the problem to delete cx-Oracle from the <code>Project Interpreter</code> and add it again. Problem is though that I get an error trying to install cx_Oracle: <code>error: command 'C:\\Program Files (x86)\\Common Files\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\link.exe' failed with exit status 1120</code>. I use PyCharm through a proxy.</p> <p>EDIT 2:</p> <p>As mentioned in a comment</p> <pre><code>import cx_Oracle print cx_Oracle.__file__ </code></pre> <p>yields <code>C:\Python27\lib\site-packages\cx_Oracle.pyd</code>, and you can see the <a href="http://i.stack.imgur.com/K0bXX.png" rel="nofollow">Project Interpreter Paths</a> here.</p>
0
2016-08-29T15:22:22Z
39,210,017
<p>Go to <code>File &gt; Invalidate Caches &gt; Invalidate</code> and Restart or Invalidate and check. </p> <p>If you want to check the library inside pyCharm go to <code>File &gt; Settings &gt; Project &gt; Project Interpreter</code>. Select the interpreter and check the library is listed.</p> <p>If you want to check the path where the said module is installed.</p> <pre><code>import cx_Oracle print cx_Oracle.__file__ </code></pre>
0
2016-08-29T15:34:17Z
[ "python", "pycharm", "cx-oracle" ]
Clustering text documents and obtaining duplicate top terms
39,209,820
<p>I found the code in <a href="http://stackoverflow.com/questions/27889873/clustering-text-documents-using-scikit-learn-kmeans-in-python?rq=1">this post</a> to be very helpful. (I would add a comment to that post but I need 50 reputation points.)</p> <p>I used the same code in the post above but added a test document I have been using for debugging my own clustering code. For some reason a word in 1 document appears in both clusters. </p> <p>The code is:</p> <p>Update: I added "Unique sentence" to the documents below. </p> <pre><code>documents = ["I ran yesterday.", "The sun was hot.", "I ran yesterday in the hot and humid sun.", "Yesterday the sun was hot.", "Yesterday I ran in the hot sun.", "Unique sentence." ] vectorizer = TfidfVectorizer(stop_words='english') X = vectorizer.fit_transform(documents) #cluster documents true_k = 2 model = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1) model.fit(X) #print top terms per cluster clusters print("Top terms per cluster:") order_centroids = model.cluster_centers_.argsort()[:, ::-1] terms = vectorizer.get_feature_names() for i in range(true_k): print ("Cluster %d:" % i,) for ind in order_centroids[i, :10]: print(' %s' % terms[ind]) print </code></pre> <p>The output I receive is:</p> <p>UPDATE: I updated the output below to reflect the "unique sentence" above. </p> <p>Cluster 0: sun hot yesterday ran humid unique sentence Cluster 1: unique sentence yesterday sun ran humid hot</p> <p>You'll note that "humid" appears as a top term in both clusters even though it's in just 1 line of the documents above. I would expect a unique word, like "humid" in this case, to be a top term in just 1 of the clusters. </p> <p>Thanks! </p>
0
2016-08-29T15:24:39Z
39,210,359
<p>Not necessarily. The code you are using creates vector space of the bag of words (excluding stop words) of your corpus (I am ignoring the tf-idf weighting.). Looking at your documents, your vector space is of size 5, with the a word array like (ignoring the order):</p> <pre><code>word_vec_space = [yesterday, ran, sun, hot, humid] </code></pre> <p>Each document is assigned a numeric vector of whether it contains the words in 'word_vec_space'. </p> <pre><code>"I ran yesterday." -&gt; [1,1,0,0,0] "The sun was hot." -&gt; [0,0,1,1,0] ... </code></pre> <p>When performing k-mean clustering, you pick k starting points in the vector-space and allow the points to move around to optimize the clusters. You ended up with both cluster centroids containing the a non-zero value for <code>'humid'</code>. This is due to the one sentence that contains <code>'humid'</code> also had <code>'sun'</code>, <code>'hot'</code>, and <code>'yesterday'</code>. </p>
1
2016-08-29T15:53:13Z
[ "python", "scikit-learn", "cluster-analysis", "k-means" ]
Clustering text documents and obtaining duplicate top terms
39,209,820
<p>I found the code in <a href="http://stackoverflow.com/questions/27889873/clustering-text-documents-using-scikit-learn-kmeans-in-python?rq=1">this post</a> to be very helpful. (I would add a comment to that post but I need 50 reputation points.)</p> <p>I used the same code in the post above but added a test document I have been using for debugging my own clustering code. For some reason a word in 1 document appears in both clusters. </p> <p>The code is:</p> <p>Update: I added "Unique sentence" to the documents below. </p> <pre><code>documents = ["I ran yesterday.", "The sun was hot.", "I ran yesterday in the hot and humid sun.", "Yesterday the sun was hot.", "Yesterday I ran in the hot sun.", "Unique sentence." ] vectorizer = TfidfVectorizer(stop_words='english') X = vectorizer.fit_transform(documents) #cluster documents true_k = 2 model = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1) model.fit(X) #print top terms per cluster clusters print("Top terms per cluster:") order_centroids = model.cluster_centers_.argsort()[:, ::-1] terms = vectorizer.get_feature_names() for i in range(true_k): print ("Cluster %d:" % i,) for ind in order_centroids[i, :10]: print(' %s' % terms[ind]) print </code></pre> <p>The output I receive is:</p> <p>UPDATE: I updated the output below to reflect the "unique sentence" above. </p> <p>Cluster 0: sun hot yesterday ran humid unique sentence Cluster 1: unique sentence yesterday sun ran humid hot</p> <p>You'll note that "humid" appears as a top term in both clusters even though it's in just 1 line of the documents above. I would expect a unique word, like "humid" in this case, to be a top term in just 1 of the clusters. </p> <p>Thanks! </p>
0
2016-08-29T15:24:39Z
39,212,759
<p>TF*IDF tells you the representativeness of a word (in this case the column) for a specific document (and in this case the row). By representative I mean: a word occurs frequently in one document but not frequently in other documents. The higher the TF*IDF value, the more this word represents a specific document. </p> <p>Now let's start to understand the values you actually work with. From sklearn's kmeans you use the return variable <em>cluster_centers</em>. This gives you the coordinates of each cluster, which are an array of TF*IDF weights, for each word one. It is important to note that these are just some abstract form of word frequency and do no longer relate back to a specific document. Next, numpy.argsort() gives you the indices that would sort an array, starting with the index for the lowest TF*IDF value. So after that you reverse its order with [:, ::-1]. Now you have the index of the most representative words for that cluster center at the beginning.</p> <p>Now, let's talk a bit more about k-means. k-means initialises it's k-cluster centers randomly. Then the each document is assigned to a center and then the cluster centers are recomputed. This is repeated until the optimization criterion to minimize the sum of sqaured distances between documents and their closest center is met. What this means for you is that each cluster dimension most likely doesn't have the TF*IDF value 0 because of the random initialisation. Furthermore, k-means stops as soon as the optimization criterion is met. Thus, TF*IDF values of a center mean just that the TF*IDF of the documents that were assigned to the other clusters are closer to this center than to the other cluster centers.</p> <p>One additional bit is that with <em>order_centroids[i, :10]</em>, the 10 most representative words for each cluster are printed, but since you have only 5 words in total, all words will be printed either way just in a different order.</p> <p>I hope this helped. By the way k-means does not guarantee you to find the global optimum and might get stuck in a local optimum, that's why it is usually run multiple times with different random starting points. </p>
1
2016-08-29T18:26:23Z
[ "python", "scikit-learn", "cluster-analysis", "k-means" ]
Clustering text documents and obtaining duplicate top terms
39,209,820
<p>I found the code in <a href="http://stackoverflow.com/questions/27889873/clustering-text-documents-using-scikit-learn-kmeans-in-python?rq=1">this post</a> to be very helpful. (I would add a comment to that post but I need 50 reputation points.)</p> <p>I used the same code in the post above but added a test document I have been using for debugging my own clustering code. For some reason a word in 1 document appears in both clusters. </p> <p>The code is:</p> <p>Update: I added "Unique sentence" to the documents below. </p> <pre><code>documents = ["I ran yesterday.", "The sun was hot.", "I ran yesterday in the hot and humid sun.", "Yesterday the sun was hot.", "Yesterday I ran in the hot sun.", "Unique sentence." ] vectorizer = TfidfVectorizer(stop_words='english') X = vectorizer.fit_transform(documents) #cluster documents true_k = 2 model = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1) model.fit(X) #print top terms per cluster clusters print("Top terms per cluster:") order_centroids = model.cluster_centers_.argsort()[:, ::-1] terms = vectorizer.get_feature_names() for i in range(true_k): print ("Cluster %d:" % i,) for ind in order_centroids[i, :10]: print(' %s' % terms[ind]) print </code></pre> <p>The output I receive is:</p> <p>UPDATE: I updated the output below to reflect the "unique sentence" above. </p> <p>Cluster 0: sun hot yesterday ran humid unique sentence Cluster 1: unique sentence yesterday sun ran humid hot</p> <p>You'll note that "humid" appears as a top term in both clusters even though it's in just 1 line of the documents above. I would expect a unique word, like "humid" in this case, to be a top term in just 1 of the clusters. </p> <p>Thanks! </p>
0
2016-08-29T15:24:39Z
39,280,446
<p>Why would clusters have distinct top terms?</p> <p>Consider the clustering worked (very often it doesn't - beware), would you consider these clusters to be bad or good:</p> <ul> <li>banana fruit</li> <li>apple fruit</li> <li>apple computer</li> <li>windows computer</li> <li>window blinds</li> </ul> <p>If I would ever get such clusters, I wouldmbe happy (iknfact, I would believe I am seeing an error, because these are much too god results. Text clustering is always borderline to non-working).</p> <p><strong>With text clusters, it's a lot about word combinations, not just single words</strong>. Apple fruit and apple computer are not the same.</p>
1
2016-09-01T20:34:25Z
[ "python", "scikit-learn", "cluster-analysis", "k-means" ]
Decode Base64 string to byte array
39,209,872
<p>I would create a python script that decode a Base64 string to an array of byte (or array of Hex values).</p> <p>The embedded side of my project is a micro controller that creates a base64 string starting from raw byte. The string contains some no-printable characters (for this reason I choose base64 encoding).</p> <p>On the Pc side I need to decode the the base64 string and recover the original raw bytes.</p> <p>My script uses python 2.7 and the base64 library:</p> <pre><code>base64Packet = raw_input('Base64 stream:') packet = base64.b64decode(base64Packet ) sys.stdout.write("Decoded packet: %s"%packet) </code></pre> <p>The resulting string is a characters string that contains some not printable char.</p> <p>Is there a way to decode base64 string to byte (or hex) values?</p> <p>Thanks in advance!</p>
-1
2016-08-29T15:26:56Z
39,210,134
<p>You can use <a href="https://docs.python.org/2/library/functions.html#bytearray" rel="nofollow">bytearray</a> for exactly this. Possibly the <a href="https://docs.python.org/2/library/binascii.html" rel="nofollow">binascii</a> module and <a href="https://docs.python.org/2/library/struct.html" rel="nofollow">struct</a> can be helpful, too.</p> <pre><code>import binascii import struct binstr=b"thisisunreadablebytes" encoded=binascii.b2a_base64(binstr) print encoded print binascii.a2b_base64(encoded) ba=bytearray(binstr) print list(ba) print binascii.b2a_hex(binstr) print struct.unpack("21B",binstr) </code></pre>
1
2016-08-29T15:40:45Z
[ "python", "string", "embedded", "base64", "decode" ]
collect some specific classes in python module
39,209,891
<p>I have a packages contains classes <code>C1, C2, CInvalid3, C4</code>, which are defined in different sub modules.</p> <pre><code>my_package/ __init__.py sub_package1/ __init__.py sub_module1.py # contains C1, C2 sub_package2/ __init__.py sub_module2.py # contains CInvalid3, C4 </code></pre> <p>Given a string containing some class's name, I want to initialize the corresponding class. For example,</p> <pre><code>some_valid_class_name = 'C1' some_valid_class = all_valid_classes[some_valid_class_name]() </code></pre> <p>Currently I create a module <code>all_classes.py</code> under <code>my_package</code>, which contains</p> <pre><code>all_valid_classes = {} # I want the dict contain C1, C2 and C4 def this_is_a_valid_class(cls): all_valid_classes[cls.__name__] = cls return cls </code></pre> <p>And in <code>sub_module1.py</code> and <code>sub_module2.py</code>, I use</p> <pre><code>from my_package.all_classes import this_is_a_valid_class @this_is_a_valid_class class C1(object): pass </code></pre> <p>and add</p> <pre><code>from .sub_package1 import sub_module1 from .sub_package2 import sub_module2 </code></pre> <p>to <code>my_package/__init__.py</code>.</p> <p>Is there any better way to handle this? I import all things in <code>my_package/__init__.py</code>. When I add new <code>sub_package3.sub_module3.C99</code>, I need to remember to add <code>from .sub_package3 import sub_module3</code> to <code>my_package/__init__.py</code>. I don't think these are good ideas.</p>
1
2016-08-29T15:27:27Z
39,213,082
<p>To get what you're looking for, what you can do is to <em>mark</em> valid classes with a class attribute:</p> <pre><code>class C1(object): _valid = True </code></pre> <p>And then dynamically import all modules in your package, storing valid classes separately in your <code>all_valid_classes</code> dictionary during the process.</p> <p>The key thing is that you have to import the modules of all the classes you want to use no matter what, so you can do it manually (as you're doing now) or dynamically (finding the filenames of the modules within the package and importing them).</p> <p>This snippet shows the concept (please note that it is really ugly and <strong>only intended as a proof-of-concept</strong>, I assembled it in a rush!). It would go in your <code>my_module/__init__.py</code> file:</p> <pre><code>import os import fnmatch from importlib import import_module from types import TypeType # dictionary with all valid classes all_valid_classes = {} # walk directory and load modules dynamically this_path = os.path.dirname(__file__) modules = [] for root, dirnames, filenames in os.walk(this_path): for filename in fnmatch.filter(filenames, '*.py'): # avoid this file importing itself full_path = os.path.join(root, filename) if full_path == os.path.join(this_path, '__init__.py'): continue # convert the filename to the module name trimmed_path = full_path[len(this_path) + 1:-3] module_name = trimmed_path.replace('/', '.') # import the module module = import_module('%s.%s' % (__name__, module_name)) # find valid classes (classes with a '_valid = True' attribute for item_name in dir(module): item = getattr(module, item_name) if type(item) == TypeType: try: valid_attr = getattr(item, '_valid') if valid_attr is True: all_valid_classes[item_name] = item except AttributeError: pass </code></pre> <p>After importing <code>my_module</code>, <code>all_valid_classes</code> will contain <code>C1</code>, <code>C2</code> and <code>C4</code> (provided that they are marked with <code>_valid = True</code>).</p> <p>ps. Note, however, that I would personally do the imports manually as you're doing already, it is more pythonic and clean in my opinion.</p>
1
2016-08-29T18:44:44Z
[ "python", "python-2.7", "python-3.x", "oop", "python-3.4" ]
Text got cut off when strange chars inside when trying to save into TEXT field
39,209,898
<p>Having a text like that in a file. I want to insert that text in my database (UTF8 encoding by the way).</p> <pre><code>OK: "Spanning op P4V2 (TP2)" : 4.00 V DC &lt;= 4.20 V DC OK: "Spanning op P1V8_EHSX_BGS2 (TP1030)" : 1.81 V DC &gt;= 1.71 V DC OK: "Spanning op P1V8_EHSX_BGS2 (TP1030)" : 1.81 V DC &lt;= 1.89 V DC LOG: Waiting for barebox command prompt LOG: ^@^@Starting Bootlets... LOG: LOG: Configured for DCDC_BATT only power source. LOG: Initialized 1 ram bank(s) LOG: Starting secondary bootloader </code></pre> <p>The table has a field "results" with type "TEXT". However the file get cut off when finds the "^@" characters. Everything after that is not saved in my database.</p> <p>I have tried many things like:</p> <pre><code>results = results.encode('utf-8') self.db.set_client_encoding('UTF8') c.execute("INSERT INTO ats2_testrun (serial_number_id, test_system_id, date, status_ok, results, author, svn_url, svn_revision_number, service_report_id) + "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s);",(sid, tsid, tstamp, ok, results, author, svn_url, svn_revision_number, service_report_id)) </code></pre> <p>But it doesn't work. Somebody told me to transform that field into a binary one, but if there is a way to save that into a TEXT field. I don't care the strange chars "^@" so they can be removed.</p>
0
2016-08-29T15:27:48Z
39,210,042
<p><code>0x00</code> (<code>^@</code>) is a string terminator. It is the only character you can not save in a 0x00-terminated field (which TEXT is).</p> <p>Replace the chars and you will be just fine.</p>
1
2016-08-29T15:35:49Z
[ "python", "postgresql", "unicode", "utf-8", "psycopg2" ]
NLTK can't find the Stanford POS tagger model file
39,210,008
<p>I am trying to use StanfordPOSTagger from the NLTK. I downloaded Stanford POS full tagger. I have set </p> <pre><code>CLASSPATH=/home/waheeb/Stanford_Tools/stanford-postagger-full-2015-12-09 /stanford-postagger.jar STANFORD_MODELS=home/waheeb/Stanford_Tools/stanford-postagger-full-2015-12-09/models </code></pre> <p>When I type the following in python:</p> <pre><code>&gt;&gt;&gt; from nltk.tag import StanfordPOSTagger &gt;&gt;&gt; st = StanfordPOSTagger('english-bidirectional-distsim.tagger') </code></pre> <p>I get the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/waheeb/anaconda2/lib/python2.7/site-packages/nltk/tag /stanford.py", line 136, in __init__ super(StanfordPOSTagger, self).__init__(*args, **kwargs) File "/home/waheeb/anaconda2/lib/python2.7/site-packages/nltk/tag/stanford.py", line 56, in __init__ env_vars=('STANFORD_MODELS',), verbose=verbose) File "/home/waheeb/anaconda2/lib/python2.7/site-packages /nltk/internals.py", line 573, in find_file file_names, url, verbose)) File "/home/waheeb/anaconda2/lib/python2.7/site-packages/nltk/internals.py", line 567, in find_file_iter raise LookupError('\n\n%s\n%s\n%s' % (div, msg, div)) </code></pre> <p>LookupError: </p> <pre><code>========================================================================= NLTK was unable to find the english-bidirectional-distsim.tagger file! Use software specific configuration paramaters or set the TANFORD_MODELS environment variable. ========================================================================== </code></pre> <p>Why is that?? </p>
0
2016-08-29T15:33:41Z
39,210,557
<p>You forgot to use <code>export</code> in the command line before calling your python script. I.e. </p> <pre><code>alvas@ubi:~$ export STANFORDTOOLSDIR=$HOME alvas@ubi:~$ export CLASSPATH=$STANFORDTOOLSDIR/stanford-postagger-full-2015-12-09/stanford-postagger.jar alvas@ubi:~$ export STANFORD_MODELS=$STANFORDTOOLSDIR/stanford-postagger-full-2015-12-09/models alvas@ubi:~$ python </code></pre> <p>For more details see <a href="https://gist.github.com/alvations/e1df0ba227e542955a8a" rel="nofollow">https://gist.github.com/alvations/e1df0ba227e542955a8a</a></p> <hr> <p>Similar problems includes:</p> <ul> <li><a href="http://stackoverflow.com/questions/34037094/setting-nltk-with-stanford-nlp-both-stanfordnertagger-and-stanfordpostagger-fo">Setting NLTK with Stanford NLP (both StanfordNERTagger and StanfordPOSTagger) for Spanish</a></li> <li><a href="http://stackoverflow.com/questions/22930328/error-using-stanford-pos-tagger-in-nltk-python">Error using Stanford POS Tagger in NLTK Python</a></li> <li><a href="http://stackoverflow.com/questions/34692987/cant-make-stanford-pos-tagger-working-in-nltk">Can&#39;t make Stanford POS tagger working in nltk</a></li> <li><a href="http://stackoverflow.com/questions/7344916/trouble-importing-stanford-pos-tagger-into-nltk">trouble importing stanford pos tagger into nltk</a></li> <li><a href="http://stackoverflow.com/questions/13883277/stanford-parser-and-nltk">Stanford Parser and NLTK</a></li> </ul>
0
2016-08-29T16:05:03Z
[ "python", "nlp", "nltk", "stanford-nlp", "pos-tagger" ]
Pandas: set a default datetime for None values
39,210,033
<p>I have a Pandas dataframe with columns that contain dates as strings (in SQL-like format). However, many cells contain <code>None</code> values. I'm trying to convert these columns to Pandas dates using <code>to_datetime</code> and set a "default" value for cells that contain the <code>None</code> value. Example code below:</p> <pre><code>import pandas as pd &gt;&gt;&gt; d = {'a': [1,2,3], 'd1': ['2016-01-01','2015-10-02',None], 'd2': [None,'2016-04-03',None]} &gt;&gt;&gt; df = pd.DataFrame(d) &gt;&gt;&gt; print df a d1 d2 0 1 2016-01-01 None 1 2 2015-10-02 2016-04-03 2 3 None None &gt;&gt;&gt; date_cols = ['d1','d2'] &gt;&gt;&gt; df[date_cols] = df[date_cols].apply(pd.to_datetime) &gt;&gt;&gt; print df a d1 d2 0 1 2016-01-01 NaT 1 2 2015-10-02 2016-04-03 2 3 NaT NaT </code></pre> <p>It's simple enough to convert the valid strings to a date, I just want to replace the <code>NaT</code> with the <code>default_date</code>. This is what I'd like the final dataframe to look like:</p> <pre><code>&gt;&gt;&gt; default_date = '2015-01-01' &gt;&gt;&gt; print df a d1 d2 0 1 2016-01-01 2015-01-01 1 2 2015-10-02 2016-04-03 2 3 2015-01-01 2015-01-01 </code></pre>
1
2016-08-29T15:34:51Z
39,210,098
<p>use <code>fillna</code></p> <pre><code>df[date_cols] = df[date_cols].fillna(pd.to_datetime('2015-01-01')) df </code></pre> <p><a href="http://i.stack.imgur.com/EPTWy.png" rel="nofollow"><img src="http://i.stack.imgur.com/EPTWy.png" alt="enter image description here"></a></p>
2
2016-08-29T15:38:18Z
[ "python", "datetime", "pandas" ]
How can I write each element of a list to each line of a text file?
39,210,073
<p>Using python, I've got the following list:</p> <pre><code>data = ['element0', 'element1', 'element2', 'element3'] </code></pre> <p>And I want to write each element, into a new line of "myfile.txt", so I've been trying this:</p> <pre><code>for x in data: open("myfile.txt", "w").write(x + "\n") </code></pre> <p>Which gives me this (inside "myfile.txt"):</p> <pre><code>element3 </code></pre> <p>I looks like each time it goes through the loop, it writes the element on top of the last.</p> <p>Desired result (inside "myfile.txt"):</p> <pre><code>element0 element1 element2 element3 </code></pre>
0
2016-08-29T15:37:02Z
39,210,102
<p>Just open the file object <strong>once</strong>:</p> <pre><code>with open("myfile.txt", "w") as fobj: for x in data: fobj.write(x + "\n") </code></pre> <p>I'm using the file as a <em>context manager</em> by passing it to the <code>with</code> statement; this ensures that the file is closed again after the block of code finishes.</p> <p>Each time you open the file object with the <code>'w'</code> (write) mode, the file is <em>truncated</em>, emptied out. You'd have to use the <code>'a'</code> (append) mode to prevent the file being truncated.</p> <p>However, opening the file just once is much more efficient.</p>
4
2016-08-29T15:38:27Z
[ "python", "list", "file" ]
Change the width of the Basic Bar Chart
39,210,160
<p>I create a Bar Chart with matplotlib with : </p> <pre><code>import matplotlib.pyplot as plt; plt.rcdefaults() import numpy as np import matplotlib.pyplot as plt objects = ('ETA_PRG_P2REF_RM', 'ETA_PRG_VDES_RM', 'ETA_PRG_P3REF_RM', 'Python', 'C++', 'Java', 'Perl', 'Scala', 'Lisp') y_pos = np.arange(len(objects)) performance = [220010, 234690, 235100, 21220, 83410, 119770, 210990, 190430, 888994] plt.bar(y_pos, performance, align='center', alpha=0.5) plt.xticks(y_pos, objects) plt.ylabel('Usage') plt.title('Programming language usage') plt.show() </code></pre> <p>Look at the attached Image <a href="http://i.stack.imgur.com/MAUfd.png" rel="nofollow"><img src="http://i.stack.imgur.com/MAUfd.png" alt="enter image description here"></a></p> <p>But, As you can remark the width of the plot is smal, the name of object are not clear. Can you suggest me how to resolve this problem?</p> <p>Thank you</p>
1
2016-08-29T15:42:21Z
39,210,442
<p>You can add tick labels with a rotation:</p> <pre><code>pyplot.xticks(y_pos, objects, rotation=70) </code></pre> <p>In addition to an angle in degrees, you can specify a string:</p> <pre><code>pyplot.xticks(y_pos, objects, rotation='vertical') </code></pre> <p>You may also want to specify a horizontal alignment, especially is using an angle like 40. The default is to use the center, which makes the labels look weird:</p> <pre><code>pyplot.xticks(y_pos, objects, rotation=40, ha='right') </code></pre> <p>See the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks" rel="nofollow">docs</a> for a full list of options.</p>
1
2016-08-29T15:57:51Z
[ "python", "matplotlib", "bar-chart" ]
Trouble with Kivy ScreenManager
39,210,179
<p>Lately I have some problems with Kivy's Screenmanager. I can't use the <code>switch_to</code> method of the manager when accessing it from a <code>Screen</code> class. In a <code>Screen</code> class: <code>self.manager.switch_to</code> gives the error: <code>AttributeError: 'NoneType' object has no attribute 'switch_to'</code>. I'm a bit desperate. Below simple app that produces the error. </p> <pre><code>import kivy kivy.require("1.9.1") from kivy.app import App from kivy.uix.label import Label from kivy.uix.screenmanager import ScreenManager, Screen screen1 = True class Screen1(Screen): def __init__(self, **kw): super(Screen1, self).__init__(**kw) self.add_widget(Label(text="Screen1")) class Screen2(Screen): def __init__(self, **kw): super(Screen2, self).__init__(**kw) self.add_widget(Label(text="Screen2")) class BlackMenu(Screen): def __init__(self, **kw): super(BlackMenu, self).__init__(**kw) if screen1: self.manager.switch_to(Screen1()) class MyApp(App): def build(self): mymanager = ScreenManager() mymanager.switch_to(BlackMenu(name="black")) return mymanager if __name__ == "__main__": MyApp().run() </code></pre>
0
2016-08-29T15:43:41Z
39,225,001
<p>try declaring your screen manager as a global variable below screen1</p> <pre><code>import kivy kivy.require("1.9.1") from kivy.app import App from kivy.uix.label import Label from kivy.uix.screenmanager import ScreenManager, Screen screen1 = True screen_manager = ScreenManager() </code></pre> <p>then in your build function add your screens just like:</p> <pre><code>def build(self): screen_manager.add_widget(Screen1(name='screen1')) screen_manager.add_widget(Screen2(name='screen2')) screen_manager.add_widget(BlackMenu(name='black_menu')) return screen_manager </code></pre> <p>then in your black screen you could do:</p> <pre><code>class BlackMenu(Screen): def __init__(self, **kw): super(BlackMenu, self).__init__(**kw) if screen_manager.current == 'screen1': screen_manager.switch_to(Screen1()) </code></pre> <p>but keep in mind that switching to a screen removes that screen from screen_manager childs so you have to manage adding it again. good luck</p>
0
2016-08-30T10:27:43Z
[ "python", "kivy" ]
Python classes: method has same name as property
39,210,250
<p>I'm constructing a class Heating. Every instance of this class has the property 'temperature'. It's mandatory that Heating also supports the method temperature() that prints the property 'temperature' as an integer.</p> <p>When I call the method temperature() I get the error 'int' object is not callable because self.temperature is already defined as an integer.</p> <p>How do I solve this?</p> <p>code:</p> <pre><code>class Heating: """ &gt;&gt;&gt; machine1 = Heating('radiator kitchen', temperature=20) &gt;&gt;&gt; machine2 = Heating('radiator living', minimum=15, temperature=18) &gt;&gt;&gt; machine3 = Heating('radiator bathroom', temperature=22, minimum=18, maximum=28) &gt;&gt;&gt; print(machine1) radiator kitchen: current temperature: 20.0; allowed min: 0.0; allowed max: 100.0 &gt;&gt;&gt; machine2 Heating('radiator living', 18.0, 15.0, 100.0) &gt;&gt;&gt; machine2.changeTemperature(8) &gt;&gt;&gt; machine2.temperature() 26.0 &gt;&gt;&gt; machine3.changeTemperature(-5) &gt;&gt;&gt; machine3 Heating('radiator bathroom', 18.0, 18.0, 28.0) """ def __init__(self, name, temperature = 10, minimum = 0, maximum = 100): self.name = name self.temperature = temperature self.minimum = minimum self.maximum = maximum def __str__(self): return '{0}: current temperature: {1:.1f}; allowed min: {2:.1f}; allowed max: {3:.1f}'.format(self.name, self.temperature, self.minimum, self.maximum) def __repr__(self): return 'Heating(\'{0}\', {1:.1f}, {2:.1f}, {3:.1f})'.format(self.name, self.temperature, self.minimum, self.maximum) def changeTemperature(self, increment): self.temperature += increment if self.temperature &lt; self.minimum: self.temperature = self.minimum if self.temperature &gt; self.maximum: self.temperature = self.maximum def temperature(self): return self.temperature # testen van het programma if __name__ == '__main__': import doctest doctest.testmod() </code></pre>
-2
2016-08-29T15:47:42Z
39,210,317
<p>You can't have both a method and an attribute with the same name. Methods are attributes too, albeit ones that you can call.</p> <p>Just rename the attribute to something else. You could use <code>_temperature</code>:</p> <pre><code>def __init__(self, name, temperature = 10, minimum = 0, maximum = 100): self.name = name self._temperature = temperature self.minimum = minimum self.maximum = maximum def __str__(self): return '{0}: current temperature: {1:.1f}; allowed min: {2:.1f}; allowed max: {3:.1f}'.format(self.name, self._temperature, self.minimum, self.maximum) def __repr__(self): return 'Heating(\'{0}\', {1:.1f}, {2:.1f}, {3:.1f})'.format(self.name, self._temperature, self.minimum, self.maximum) def changeTemperature(self, increment): self._temperature += increment if self.temperature &lt; self.minimum: self._temperature = self.minimum if self.temperature &gt; self.maximum: self._temperature = self.maximum def temperature(self): return self._temperature </code></pre> <p>Now your class has both <code>_temperature</code> (the integer) and <code>temperature()</code> (the method); the latter returns the former.</p>
2
2016-08-29T15:51:04Z
[ "python", "class" ]
Select text from either a DIV or an underlying container, if it exists
39,210,350
<p>I'm having a div table where each row has two cells/columns. The second cell/column sometimes has a clear text (<code>&lt;div class="something"&gt;Text&lt;/div&gt;</code>) while sometimes it's hidden within an "a" tag inside: <code>&lt;div class="something"&gt;&lt;a href="url"&gt;Text&lt;/a&gt;&lt;/div&gt;</code>.</p> <p>Now, I have no problem in getting everything but the linked text. I can also get the linked text separately, but I don't know how to get everything at once, so I get three columns of data: 1. first column text, 2. second column text no matter if it is linked or not, 3. link, if it exist</p> <p>The code that extracts everything not linked and works is:</p> <pre><code>times = scrapy.Selector(response).xpath('//div[contains(concat(" ", normalize-space(@class), " "), " time ")]/text()').extract() titles = scrapy.Selector(response).xpath('//div[contains(concat(" ", normalize-space(@class), " "), " name ")]/text()').extract() for time, title in zip(times, titles): print time.strip(), title.strip() </code></pre> <p>I can get the linked items only with</p> <pre><code>ltitles = scrapy.Selector(response).xpath('//div[contains(concat(" ", normalize-space(@class), " "), " name ")]/a/text()').extract() for ltitle in ltitles: print ltitle.strip() </code></pre> <p>But don't know how to combine the "query" to get everything together.</p> <p>Here's a sample HTML:</p> <pre><code>&lt;div class="programRow rowOdd"&gt; &lt;div class="time ColorVesti"&gt; 22:55 &lt;/div&gt; &lt;div class="name"&gt; Dnevnik &lt;/div&gt; &lt;/div&gt; &lt;div class="programRow rowEven"&gt; &lt;div class="time ColorOstalo"&gt; 23:15 &lt;/div&gt; &lt;div class="name"&gt; &lt;a class="recnik" href="/page/tv/sr/story/20/rts-1/2434373/kulturni-dnevnik.html" rel="/ajax/storyToolTip.jsp?id=2434373"&gt;Kulturni dnevnik&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Sample output (one I cannot get):</p> <pre><code>22:55, Dnevnik, [] 23:15, Kulturni dnevnik, /page/tv/sr/story/20/rts-1/2434373/kulturni-dnevnik.html </code></pre> <p>I either get the first two columns (without the linked text) or just the linked text with the code samples above.</p>
0
2016-08-29T15:52:53Z
39,212,148
<p>If I understand you correctly then you should probably just iterate through program nodes and create item for every cycle. Also there's xpath shortcut <code>//text()</code> which captures all text under the node and it's childrem</p> <p>Try something like:</p> <pre><code>programs = response.xpath("//div[contains(@class,'programRow')]") for program in programs: item = dict() item['name'] = program.xpath(".//div[contains(@class,'name')]//text()").extract_first() item['link'] = program.xpath(".//div[contains(@class,'name')]/a/@href").extract_first() item['title'] = program.xpath(".//div[contains(@class,'title')]//text()").extract_first() return item </code></pre>
0
2016-08-29T17:45:57Z
[ "python", "scrapy" ]
Function within while loop not running more than once
39,210,360
<p>I am writing a small game as a way to try and learn python. At the bottom of my code, there is a while loop which asks for user input. If that user input is yes, it is supposed to update a variable, encounter_prob. If encounter_prob is above 20, it is supposed to call the function. I can get this behavior to happen, but only once. It seems to not be going through the if statement again.</p> <pre><code>import random def def_monster_attack(): monster_attack = random.randrange(1,6) return monster_attack def def_player_attack(): player_attack = random.randrange(1,7) return player_attack def def_encounter_prob(): encounter_prob = random.randrange(1,100) return encounter_prob def def_action(): action = raw_input("Move forward? Yes or No") return action player = { 'hp': 100, 'mp': 100, 'xp': 0, 'str': 7 } monster = { 'hp': 45, 'mp': 10, 'str': 6 } def encounter(): while player['hp'] &gt; 0 and monster['hp'] &gt; 0: keep_fighting = raw_input("Attack, Spell, Gaurd, or Run?") if keep_fighting.startswith('a') == True: player_attack = def_player_attack() monster['hp'] = monster['hp'] - player_attack monster_attack = def_monster_attack() player['hp'] = player['hp'] - monster_attack print "player's hp is", player['hp'] print "monster's hp is", monster['hp'] while player['hp'] &gt; 0: action = def_action() if action.startswith('y') == True: encounter_prob = def_encounter_prob() if encounter_prob &gt; 20: encounter() </code></pre>
0
2016-08-29T15:53:16Z
39,210,650
<p>It's actually calling the function <code>encounter</code> twice but the first time ends up killing the monster by decreasing its <code>hp</code> to 0 or below, while the second time the function exits without entering the <code>while</code> loop because the <code>monster['hp'] &gt; 0</code> comparison evaluates to <code>False</code>. The monster's <code>hp</code> aren't reset at each new encounter.</p> <p>If you're having difficulties debugging your code, do not hesitate to put some <code>print</code> statements in different places to examine the value of your data. This should help you pinpointing what's going on.</p>
2
2016-08-29T16:10:37Z
[ "python", "python-2.7" ]
Function within while loop not running more than once
39,210,360
<p>I am writing a small game as a way to try and learn python. At the bottom of my code, there is a while loop which asks for user input. If that user input is yes, it is supposed to update a variable, encounter_prob. If encounter_prob is above 20, it is supposed to call the function. I can get this behavior to happen, but only once. It seems to not be going through the if statement again.</p> <pre><code>import random def def_monster_attack(): monster_attack = random.randrange(1,6) return monster_attack def def_player_attack(): player_attack = random.randrange(1,7) return player_attack def def_encounter_prob(): encounter_prob = random.randrange(1,100) return encounter_prob def def_action(): action = raw_input("Move forward? Yes or No") return action player = { 'hp': 100, 'mp': 100, 'xp': 0, 'str': 7 } monster = { 'hp': 45, 'mp': 10, 'str': 6 } def encounter(): while player['hp'] &gt; 0 and monster['hp'] &gt; 0: keep_fighting = raw_input("Attack, Spell, Gaurd, or Run?") if keep_fighting.startswith('a') == True: player_attack = def_player_attack() monster['hp'] = monster['hp'] - player_attack monster_attack = def_monster_attack() player['hp'] = player['hp'] - monster_attack print "player's hp is", player['hp'] print "monster's hp is", monster['hp'] while player['hp'] &gt; 0: action = def_action() if action.startswith('y') == True: encounter_prob = def_encounter_prob() if encounter_prob &gt; 20: encounter() </code></pre>
0
2016-08-29T15:53:16Z
39,211,378
<p>Your code with a couple of print commands to show you how they can let you see what is going on, when you haven't finished all of your coding.<br> Oh! and I evened things up a bit, can't have you with an unfair advantage :)</p> <pre><code>import random def def_monster_attack(): monster_attack = random.randrange(1,7) return monster_attack def def_player_attack(): player_attack = random.randrange(1,7) return player_attack def def_encounter_prob(): encounter_prob = random.randrange(1,100) return encounter_prob def def_action(): action = raw_input("Move forward? Yes or No") return action player = { 'hp': 45, 'mp': 100, 'xp': 0, 'str': 7 } monster = { 'hp': 45, 'mp': 10, 'str': 6 } def encounter(): while player['hp'] &gt; 0 and monster['hp'] &gt; 0: keep_fighting = raw_input("Attack, Spell, Guard, or Run?") if keep_fighting.startswith('a') == True: player_attack = def_player_attack() monster['hp'] = monster['hp'] - player_attack monster_attack = def_monster_attack() player['hp'] = player['hp'] - monster_attack print "It's a carve up! Your health", player['hp']," the monster's ", monster['hp'] else: print "Try attacking!" while player['hp'] &gt; 0 and monster['hp'] &gt; 0: action = def_action() if action.startswith('y') == True: encounter_prob = def_encounter_prob() if encounter_prob &gt; 20: encounter() else: print "Nothing happened all seems well" else: print "What are you going to stand there all day" if player['hp'] &lt; 1: print "Oops! You're dead!" if monster['hp'] &lt; 1: print "Hurrah! The monster's dead" </code></pre>
0
2016-08-29T16:57:51Z
[ "python", "python-2.7" ]
Defining Python function with input
39,210,459
<p>I have Postgres table called Records with several appIds. I am writing a function to pull out the data for one <code>AppId</code> (ABC0123) and want to store this result in dataframe <code>df</code>. I have created a variable AppId1 to store my AppId(ABC0123) and passed it to the query. The script got executed, but it did not create the dataframe.</p> <pre><code>def fun(AppId): AppId1=pd.read_sql_query(""" select "AppId" from "Records" where "AppId"='%s'""" %AppId,con=engine ) query = """" SELECT AppId from "Records" where AppId='%s' """ % AppId1 df=pd.read_sql_query(query,con=engine) return fun fun('ABC0123') </code></pre>
1
2016-08-29T15:59:08Z
39,210,549
<ul> <li>Change % AppId1 to % AppId only.</li> <li>return df</li> </ul> <p></p> <pre><code>def fun(AppId): AppId1=pd.read_sql_query(""" select 'AppId' from 'Records' where 'AppId'='%s'""" %AppId,con=engine ) query = """ SELECT 'AppId' from 'Records' where AppId='%s' """ %AppId df=pd.read_sql_query(query,con=engine) return df </code></pre>
0
2016-08-29T16:04:21Z
[ "python", "postgresql", "function" ]
Flurry Login Requests.Session() Python 3
39,210,484
<p>So I had this question answered before <a href="http://stackoverflow.com/questions/38670599/flurry-scraping-using-python3-requests-session">here</a>. However, something on the Flurry website has changed and the answer no longer works.</p> <pre><code>from bs4 import BeautifulSoup import requests loginurl = "https://dev.flurry.com/secure/loginAction.do" csvurl = "https://dev.flurry.com/eventdata/.../..." #URL to get CSV data = {'loginEmail': 'user', 'loginPassword': 'pass'} with requests.Session() as session: session.headers.update({ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36"}) soup = BeautifulSoup(session.get(loginurl).content) name = soup.select_one("input[name=struts.token.name]")["value"] data["struts.token.name"] = name data[name] = soup.select_one("input[name={}]".format(name))["value"] login = session.post(loginurl, data=data) getcsv = session.get(csvurl) </code></pre> <p>The code above worked great for the last month and then it stopped working last week. For the life of me, I can't figure out what on the website has changed. ID Names and tokens all look correct, username and pass hasnt changed. Im at a loss.</p> <p>If I login manually, I can download the csv just fine using the <code>csvurl</code>.</p> <p><code>login.histroy</code> shows:</p> <pre><code>[&lt;Response [302]&gt;, &lt;Response [302]&gt;, &lt;Response [302]&gt;, &lt;Response [302]&gt;, &lt;Response [303]&gt;] </code></pre> <p>If anyone could take a look and figure out where I am going wrong, I would greatly appreciate it.</p> <p>Thanks.</p> <p><strong>UPDATE</strong></p> <p>So from the new login address, I see the post needs to be in this format:</p> <pre><code>{"data":{"type":"session","id":"bd7d8dc1-4a86-4aed-a618-0b2765b03fb7","attributes":{"scopes":"","email":"myemail","password":"mypass","remember":"false"}}} </code></pre> <p>What I can't figure out though is how they generated the id. Can anyone take a look? </p>
5
2016-08-29T16:00:18Z
39,217,281
<p>They now have a new design and a <a href="https://login.flurry.com/home" rel="nofollow">new login page</a> to which they redirect you too - that's why you see 302 and 303 status codes. The login process and logic behind it, the URLs, links to CSV files - everything is now different and you have to "reimplement"/"remimic" it. </p>
1
2016-08-30T00:50:36Z
[ "python", "python-3.x", "session", "beautifulsoup", "flurry" ]
Flurry Login Requests.Session() Python 3
39,210,484
<p>So I had this question answered before <a href="http://stackoverflow.com/questions/38670599/flurry-scraping-using-python3-requests-session">here</a>. However, something on the Flurry website has changed and the answer no longer works.</p> <pre><code>from bs4 import BeautifulSoup import requests loginurl = "https://dev.flurry.com/secure/loginAction.do" csvurl = "https://dev.flurry.com/eventdata/.../..." #URL to get CSV data = {'loginEmail': 'user', 'loginPassword': 'pass'} with requests.Session() as session: session.headers.update({ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36"}) soup = BeautifulSoup(session.get(loginurl).content) name = soup.select_one("input[name=struts.token.name]")["value"] data["struts.token.name"] = name data[name] = soup.select_one("input[name={}]".format(name))["value"] login = session.post(loginurl, data=data) getcsv = session.get(csvurl) </code></pre> <p>The code above worked great for the last month and then it stopped working last week. For the life of me, I can't figure out what on the website has changed. ID Names and tokens all look correct, username and pass hasnt changed. Im at a loss.</p> <p>If I login manually, I can download the csv just fine using the <code>csvurl</code>.</p> <p><code>login.histroy</code> shows:</p> <pre><code>[&lt;Response [302]&gt;, &lt;Response [302]&gt;, &lt;Response [302]&gt;, &lt;Response [302]&gt;, &lt;Response [303]&gt;] </code></pre> <p>If anyone could take a look and figure out where I am going wrong, I would greatly appreciate it.</p> <p>Thanks.</p> <p><strong>UPDATE</strong></p> <p>So from the new login address, I see the post needs to be in this format:</p> <pre><code>{"data":{"type":"session","id":"bd7d8dc1-4a86-4aed-a618-0b2765b03fb7","attributes":{"scopes":"","email":"myemail","password":"mypass","remember":"false"}}} </code></pre> <p>What I can't figure out though is how they generated the id. Can anyone take a look? </p>
5
2016-08-29T16:00:18Z
39,301,685
<p>You can offer up a dummy session id and it will log you in with a new one. <a href="https://www.getpostman.com/docs/" rel="nofollow">Postman</a> interceptor helped with the redirects.</p> <pre><code>import requests import json def login(email, password, session, session_id=None): """ Authenticate with flurry.com, start a fresh session if no session id is provided. """ auth_url = 'https://auth.flurry.com/auth/v1/session' login_url = 'https://login.flurry.com' auth_method = 'application/vnd.api+json' if session_id is None: session_id = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' response = session.request('OPTIONS', auth_url, data='') headers = response.headers headers.update({'origin': login_url, 'referer': login_url, 'accept': auth_method, 'content-type': auth_method}) data = {'data': {'type': 'session', 'id': session_id, 'attributes': { 'scopes': '', 'email': email, 'password': password, 'remember': 'false'}}} payload = json.dumps(data) response = session.request('POST', auth_url, data=payload, headers=headers) return response email, password = 'your-email', 'your-password' session = requests.Session() response = login(email, password, session) # session_id = response.json()['data']['id'] </code></pre> <p>And then you can grab your csv data after hitting the old site:</p> <pre><code>response = session.request('GET', 'https://dev.flurry.com/home.do') data = session.request('GET', your_csv_url).text </code></pre>
1
2016-09-02T23:02:33Z
[ "python", "python-3.x", "session", "beautifulsoup", "flurry" ]
Flurry Login Requests.Session() Python 3
39,210,484
<p>So I had this question answered before <a href="http://stackoverflow.com/questions/38670599/flurry-scraping-using-python3-requests-session">here</a>. However, something on the Flurry website has changed and the answer no longer works.</p> <pre><code>from bs4 import BeautifulSoup import requests loginurl = "https://dev.flurry.com/secure/loginAction.do" csvurl = "https://dev.flurry.com/eventdata/.../..." #URL to get CSV data = {'loginEmail': 'user', 'loginPassword': 'pass'} with requests.Session() as session: session.headers.update({ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36"}) soup = BeautifulSoup(session.get(loginurl).content) name = soup.select_one("input[name=struts.token.name]")["value"] data["struts.token.name"] = name data[name] = soup.select_one("input[name={}]".format(name))["value"] login = session.post(loginurl, data=data) getcsv = session.get(csvurl) </code></pre> <p>The code above worked great for the last month and then it stopped working last week. For the life of me, I can't figure out what on the website has changed. ID Names and tokens all look correct, username and pass hasnt changed. Im at a loss.</p> <p>If I login manually, I can download the csv just fine using the <code>csvurl</code>.</p> <p><code>login.histroy</code> shows:</p> <pre><code>[&lt;Response [302]&gt;, &lt;Response [302]&gt;, &lt;Response [302]&gt;, &lt;Response [302]&gt;, &lt;Response [303]&gt;] </code></pre> <p>If anyone could take a look and figure out where I am going wrong, I would greatly appreciate it.</p> <p>Thanks.</p> <p><strong>UPDATE</strong></p> <p>So from the new login address, I see the post needs to be in this format:</p> <pre><code>{"data":{"type":"session","id":"bd7d8dc1-4a86-4aed-a618-0b2765b03fb7","attributes":{"scopes":"","email":"myemail","password":"mypass","remember":"false"}}} </code></pre> <p>What I can't figure out though is how they generated the id. Can anyone take a look? </p>
5
2016-08-29T16:00:18Z
39,337,666
<p>you can use uuid lib to generate an uuid for the session id, in order to use the old interface you'll need to perform a request to <a href="https://dev.flurry.com/home.do?isFirstPostLogin=true" rel="nofollow">https://dev.flurry.com/home.do?isFirstPostLogin=true</a>, now you can get the csv. (url_get variable)</p> <pre><code>id = uuid.uuid4() payload = {"data": {"type":"session", "id": str(id), "attributes":{ "scopes":"", "email": username, "password": password, "remember":"false"} } } with session() as api: headers = { 'Origin': 'https://login.flurry.com', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36', 'Content-Type': 'application/vnd.api+json', 'Accept': 'application/vnd.api+json', 'Connection': 'keep-alive', } req = api.post('https://auth.flurry.com/auth/v1/session', data=json.dumps(payload), headers=headers) if req.status_code == 201: api.get('https://dev.flurry.com/home.do?isFirstPostLogin=true') return api.get(url_get).content.encode('ascii', 'ignore') else: raise Exception('Login failed') </code></pre>
0
2016-09-05T21:02:46Z
[ "python", "python-3.x", "session", "beautifulsoup", "flurry" ]
Call a __init__ function from another function
39,210,531
<p>I need some help form all of you, so i have something like this</p> <pre><code>class LoginFrame(Frame): def __init__(self, master): super().__init__(master) ... ... ... def _login_btn_clickked(self): ... ... result = messagebox.askyesno("Wrong username or password.", "Do you want to try again?") if result == True: self.__init__(self) </code></pre> <p>So if the user select the option to try again i need the whole program start again, and show the login box. But when i execute the program the process fail. </p>
1
2016-08-29T16:03:22Z
39,210,631
<blockquote> <p>But when i execute the program the process fail. </p> </blockquote> <p>Actually it should. <code>__init__</code> method is normally called once an instance is created. You need to redesign this to either recreate an instance (first call <code>pack_forget</code> on that frame and then make new one and pack on that place), or do it using methods, like <code>show_loginbox</code> etc</p> <p>Usually, loginboxes are made using <code>Toplevel</code> with <code>Entry</code> as fields and some buttons to post a result. If done so, on error you could simply erase login or/and passwords entry box and show an error What I mean is:</p> <p><a href="http://i.stack.imgur.com/XRBRR.png" rel="nofollow"><img src="http://i.stack.imgur.com/XRBRR.png" alt="first"></a> <a href="http://i.stack.imgur.com/qhwxs.png" rel="nofollow"><img src="http://i.stack.imgur.com/qhwxs.png" alt="next"></a></p> <p>reference implementation of above is <a href="https://gist.github.com/thodnev/8cd74504a776933bcf110574c7bb7c76" rel="nofollow">here</a></p>
0
2016-08-29T16:09:51Z
[ "python", "recursion" ]
Call a __init__ function from another function
39,210,531
<p>I need some help form all of you, so i have something like this</p> <pre><code>class LoginFrame(Frame): def __init__(self, master): super().__init__(master) ... ... ... def _login_btn_clickked(self): ... ... result = messagebox.askyesno("Wrong username or password.", "Do you want to try again?") if result == True: self.__init__(self) </code></pre> <p>So if the user select the option to try again i need the whole program start again, and show the login box. But when i execute the program the process fail. </p>
1
2016-08-29T16:03:22Z
39,210,634
<p>Are you using tkinter.Frame?</p> <p>I should think that it wouldn't like being reconstructed through the use of super().<strong>init</strong>() While already being packed into a root window (I'm adsuming that is the setup you have).</p>
0
2016-08-29T16:09:56Z
[ "python", "recursion" ]
PyQt Qwizardpage : Cut up url after Question mark letter, and add groupbox to each found
39,210,556
<p>This is a double question</p> <p>Questions</p> <p><s>1) split url after question marks</s></p> <p>2) when split up, count how many questions marks , and add a groupbox to each found </p> <p>I making a Qwizardpage which have two pages.</p> <p>PyQt4 Qwizardpage app info.</p> <p>On page one i have a textboxEdit where i fill in a url.</p> <p>Lets use this example url</p> <p><code>url2 ="http://example.com/over/example?sender=senderexample&amp;password=passwxample&amp;recipients=recipientsexample&amp;sId=idexample&amp;content=contentexample"</code></p> <p>On page 2 i wanna count in the url, how many question marks there is in the url, and add a groupbox to each question marks found. This is cause i wanna work with many urls.</p> <p>so the output will be displayed like this, so i can use it for each groupbox.</p> <pre><code>senderexample=and a groupbox passwxample=and groupbox recipientsexample=and groupbox idexample=and a groupbox contentexample=and a groupbox </code></pre> <p>here is the PyQt4 Qwizardpage code</p> <pre><code>from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Wizard(object): def setupUi(self, Wizard): Wizard.setObjectName(_fromUtf8("Wizard")) Wizard.resize(523, 386) Wizard.setWizardStyle(QtGui.QWizard.AeroStyle) Wizard.setOptions(QtGui.QWizard.HaveHelpButton) Wizard.setTitleFormat(QtCore.Qt.AutoText) self.wizardPage1 = QtGui.QWizardPage() self.wizardPage1.setObjectName(_fromUtf8("wizardPage1")) self.textEditsms = QtGui.QTextEdit(self.wizardPage1) self.textEditsms.setGeometry(QtCore.QRect(70, 90, 391, 231)) self.textEditsms.setObjectName(_fromUtf8("textEditsms")) self.textEditprovider = QtGui.QTextEdit(self.wizardPage1) self.textEditprovider.setGeometry(QtCore.QRect(70, 30, 391, 31)) self.textEditprovider.setObjectName(_fromUtf8("textEditprovider")) self.label = QtGui.QLabel(self.wizardPage1) self.label.setGeometry(QtCore.QRect(200, 0, 101, 31)) font = QtGui.QFont() font.setPointSize(11) self.label.setFont(font) self.label.setObjectName(_fromUtf8("label")) self.label_2 = QtGui.QLabel(self.wizardPage1) self.label_2.setGeometry(QtCore.QRect(220, 70, 61, 21)) font = QtGui.QFont() font.setPointSize(11) self.label_2.setFont(font) self.label_2.setObjectName(_fromUtf8("label_2")) Wizard.addPage(self.wizardPage1) self.wizardPage2 = QtGui.QWizardPage() self.wizardPage2.setObjectName(_fromUtf8("wizardPage2")) Wizard.addPage(self.wizardPage2) self.retranslateUi(Wizard) QtCore.QMetaObject.connectSlotsByName(Wizard) def retranslateUi(self, Wizard): Wizard.setWindowTitle(_translate("Wizard", "Wizard", None)) Wizard.setWhatsThis(_translate("Wizard", "&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;br/&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;", None)) self.label.setText(_translate("Wizard", "Provider name", None)) self.label_2.setText(_translate("Wizard", "Sms Url:", None)) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) Wizard = QtGui.QWizard() ui = Ui_Wizard() ui.setupUi(Wizard) Wizard.show() sys.exit(app.exec_()) </code></pre> <p>Now i have tried to split url up in different ways but none did output correct. i tried with urlparse, re.split and also <a href="https://docs.python.org/2/library/urlparse.html#results-of-urlparse-and-urlsplit" rel="nofollow">urlsplit()</a></p> <pre><code>from urlparse import parse_qs, urlparse, parse_qsl, urlsplit import re url2 ="http://example.com/over/example?sender=senderexample&amp;password=passwxample&amp;recipients=recipientsexample&amp;sId=idexample&amp;content=contentexample" print parse_qs(urlparse(url2).query, 1) print dict(parse_qsl(url2)) bob = re.split('[?.]', url2) print bob text = url2 dup = filter(None, re.split("[,=?:]+", text)) print dup print url2.rsplit('?') </code></pre> <p>output</p> <pre><code>{'content': ['contentexample'], 'password': ['passwxample'], 'sender': ['senderexample'], 'recipients': ['recipientsexample'], 'sId': ['idexample']} {'content': 'contentexample', 'password': 'passwxample', 'http://example.com/over/example?sender': 'senderexample', 'recipients': 'recipientsexample', 'sId': 'idexample'} ['http://example', 'com/over/example', 'sender=senderexample&amp;password=passwxample&amp;recipients=recipientsexample&amp;sId=idexample&amp;content=contentexample'] ['http', '//example.com/over/example', 'sender', 'senderexample&amp;password', 'passwxample&amp;recipients', 'recipientsexample&amp;sId', 'idexample&amp;content', 'contentexample'] ['http://example.com/over/example', 'sender=senderexample&amp;password=passwxample&amp;recipients=recipientsexample&amp;sId=idexample&amp;content=contentexample'] </code></pre> <p>None have the right order or desired output.</p> <p>Update ! added answer one by @Mr. eXoDia</p> <p>okay so what i want is </p> <pre><code>url ="http://example.com/over/example? sender=senderexample&amp;password=passwxample&amp;recipients=recipientsexample&amp;sId=idexample&amp;content=contentexample" for key_value in url.split("?")[1].split("&amp;"): tsplit = key_value.split("=") key = tsplit[0] value = tsplit[1] print (value)` </code></pre> <p>output</p> <pre><code>senderexample passwxample recipientsexample idexample contentexample </code></pre>
0
2016-08-29T16:05:01Z
39,211,151
<p>You can use some string splitting in your case:</p> <pre><code>url ="http://example.com/over/example?sender=senderexample&amp;password=passwxample&amp;recipients=recipientsexample&amp;sId=idexample&amp;content=contentexample" for key_value in url.split("?")[1].split("&amp;"): tsplit = key_value.split("=") key = tsplit[0] value = tsplit[1] print "key: \"%s\", value: \"%s\"" % (key, value) </code></pre> <p>This will output:</p> <pre><code>key: "sender", value: "senderexample" key: "password", value: "passwxample" key: "recipients", value: "recipientsexample" key: "sId", value: "idexample" key: "content", value: "contentexample" </code></pre> <p>Basically you first split over the initial separator (?), take the right part and split that over the separator for key value pairs (&amp;). These give you strings separated by (=) on which you split the key value pairs.</p>
0
2016-08-29T16:42:38Z
[ "python", "split", "pyqt4", "groupbox" ]
How can I get values from dictionary for particular key using python
39,210,569
<p>In this code, I wanted to identify a member with his ID. If the ID exist in the dictionary, I would like to print the fullname of this member</p> <pre><code>iin = input('Enter your ID :') dict = {'id' : ['aa', 'bb', 'cc'], 'Firstname' : ['Mark', 'Jamal', 'Van'], 'Lastname' : ['Roch', 'borh', 'nilsa']} for d in dict: if inn in d: print('Hello,', dict[inn]) else : print('Sorry, you are not a member') </code></pre> <p>The desired result</p> <pre><code>Enter your ID : aa Hello, Mark Roch </code></pre> <p>Thank you for the help</p>
2
2016-08-29T16:05:37Z
39,210,723
<p>The working version of the code should be:</p> <pre><code>my_dict = {'id' : ['aa', 'bb', 'cc'], 'Firstname' : ['Mark', 'Jamal', 'Van'], 'Lastname' : ['Roch', 'borh', 'nilsa']} iin = input('Enter your ID :') # Enter your ID :"bb" try: my_id = my_dict['id'].index(iin) print my_dict['Firstname'][my_id], ', ', my_dict['Lastname'][my_id] except ValueError: print 'Sorry, you are not a member' # Jamal , borh </code></pre> <p><strong>Exlaination/Issues with your code:</strong></p> <ol> <li><code>for d in dict</code> means <code>for d in dict.keys()</code> which will return <code>['id', 'FirstName', 'LastName'</code>. In order to iterate over id, you should be doing <code>for d in dict['id']</code>. In fact, iterating over the list itself is not required. To get <code>index</code> of element in ;list, you may simply use <code>list.index(element)</code> function</li> <li><code>dict</code> is the <code>built-in</code> class in <code>python</code>. You should never use the keywords</li> <li><p>You dictionary structure is itself not correct. By definition, <code>dict means collections of objects</code> and object means similar entities. In this case, Person. Since id is supposed by unique, in am making nested dict with key as <code>id</code> (you may also use list of dict):</p> <pre><code>{'aa': {'Firstname' : 'Mark', 'Lastname' : 'Roch'}, 'bb': {'Firstname' : 'Jamal', 'Lastname' : 'borh'}, 'cc': {'Firstname' : 'Van', 'Lastname' : 'nilsa'}, } </code></pre></li> </ol>
0
2016-08-29T16:15:20Z
[ "python", "for-loop", "dictionary", "input", "output" ]
How can I get values from dictionary for particular key using python
39,210,569
<p>In this code, I wanted to identify a member with his ID. If the ID exist in the dictionary, I would like to print the fullname of this member</p> <pre><code>iin = input('Enter your ID :') dict = {'id' : ['aa', 'bb', 'cc'], 'Firstname' : ['Mark', 'Jamal', 'Van'], 'Lastname' : ['Roch', 'borh', 'nilsa']} for d in dict: if inn in d: print('Hello,', dict[inn]) else : print('Sorry, you are not a member') </code></pre> <p>The desired result</p> <pre><code>Enter your ID : aa Hello, Mark Roch </code></pre> <p>Thank you for the help</p>
2
2016-08-29T16:05:37Z
39,210,735
<p>There's no need to loop over all the items in the dictionary; it would be silly to look for an id in the <code>Firstname</code> and <code>Lastname</code> fields. (And this could produce incorrect results if the entered id happens to be a substring of someone's name.)</p> <p>What you want is to check if the given id is present in the id list, and if so, use that list position to print the corresponding first and last names:</p> <pre><code>if iin in dict['id']: index = dict['id'].index(iin) print('Hello, %s %s' % (dict['Firstname'][index], dict['Lastname'][index])) else : print('Sorry, you are not a member') </code></pre> <p>Some suggestions:</p> <p>It might be easier if you arranged your data as a list of dicts each containing a single member, like so:</p> <pre><code>members = [ {'id': 'aa', 'Firstname': 'Mark', 'Lastname': 'Roch'}, {'id': 'bb', 'Firstname': 'Jamal', 'Lastname': 'borh'}, {'id': 'cc', 'Firstname': 'Van', 'Lastname': 'nilsa'}, ] </code></pre> <p>Don't name your dictionary <code>dict</code>, as that conflicts with a built-in function name.</p>
3
2016-08-29T16:15:53Z
[ "python", "for-loop", "dictionary", "input", "output" ]
How can I get values from dictionary for particular key using python
39,210,569
<p>In this code, I wanted to identify a member with his ID. If the ID exist in the dictionary, I would like to print the fullname of this member</p> <pre><code>iin = input('Enter your ID :') dict = {'id' : ['aa', 'bb', 'cc'], 'Firstname' : ['Mark', 'Jamal', 'Van'], 'Lastname' : ['Roch', 'borh', 'nilsa']} for d in dict: if inn in d: print('Hello,', dict[inn]) else : print('Sorry, you are not a member') </code></pre> <p>The desired result</p> <pre><code>Enter your ID : aa Hello, Mark Roch </code></pre> <p>Thank you for the help</p>
2
2016-08-29T16:05:37Z
39,210,764
<p>Building on <a href="http://stackoverflow.com/questions/176918/finding-the-index-of-an-item-given-a-list-containing-it-in-python">previous posts</a></p> <pre><code>iin = input('Enter your ID :') dict = {'id' : ['aa', 'bb', 'cc'], 'Firstname' : ['Mark', 'Jamal', 'Van'], 'Lastname' : ['Roch', 'borh', 'nilsa']} try: i = dict['id'].index(iin) print('Hello {0} {1}'.format(dict['Firstname'][i], dict['Lastname'][i]) except ValueError: print('Sorry, you are not a member') </code></pre> <p><strong>NOTE</strong>: you cannot name a dictionary <code>dict</code> because it conflicts with a keyword.</p>
-1
2016-08-29T16:17:56Z
[ "python", "for-loop", "dictionary", "input", "output" ]
How can I get values from dictionary for particular key using python
39,210,569
<p>In this code, I wanted to identify a member with his ID. If the ID exist in the dictionary, I would like to print the fullname of this member</p> <pre><code>iin = input('Enter your ID :') dict = {'id' : ['aa', 'bb', 'cc'], 'Firstname' : ['Mark', 'Jamal', 'Van'], 'Lastname' : ['Roch', 'borh', 'nilsa']} for d in dict: if inn in d: print('Hello,', dict[inn]) else : print('Sorry, you are not a member') </code></pre> <p>The desired result</p> <pre><code>Enter your ID : aa Hello, Mark Roch </code></pre> <p>Thank you for the help</p>
2
2016-08-29T16:05:37Z
39,210,781
<p>Please check the below code with comments inline.</p> <pre><code>iin = input('Enter your ID :') d = {'id' : ['aa', 'bb', 'cc'], 'Firstname' : ['Mark', 'Jamal', 'Van'], 'Lastname' : ['Roch', 'borh', 'nilsa']} #Get list of IDs id_list = d['id'] #Check input in list if iin in id_list: #Get index of input from ID list index = id_list.index(iin) #Get rest of info fname = d['Firstname'][index] lname = d['Lastname'][index] msg = "Hello, " + fname + " " + lname print msg else: print 'Sorry, you are not a member' </code></pre> <p>Output :</p> <pre><code>C:\Users\dinesh_pundkar\Desktop&gt;python b.py Enter your ID :"aa" Hello, Mark Roch C:\Users\dinesh_pundkar\Desktop&gt;python b.py Enter your ID :"asd" Sorry, you are not a member C:\Users\dinesh_pundkar\Desktop&gt; </code></pre>
3
2016-08-29T16:19:15Z
[ "python", "for-loop", "dictionary", "input", "output" ]
How can I get values from dictionary for particular key using python
39,210,569
<p>In this code, I wanted to identify a member with his ID. If the ID exist in the dictionary, I would like to print the fullname of this member</p> <pre><code>iin = input('Enter your ID :') dict = {'id' : ['aa', 'bb', 'cc'], 'Firstname' : ['Mark', 'Jamal', 'Van'], 'Lastname' : ['Roch', 'borh', 'nilsa']} for d in dict: if inn in d: print('Hello,', dict[inn]) else : print('Sorry, you are not a member') </code></pre> <p>The desired result</p> <pre><code>Enter your ID : aa Hello, Mark Roch </code></pre> <p>Thank you for the help</p>
2
2016-08-29T16:05:37Z
39,210,891
<p>Using .items() will allow for a loop on a dictionary.</p> <pre><code>iin = input('Enter your ID :') dict = {'id' : ['aa', 'bb', 'cc'], 'Firstname' : ['Mark', 'Jamal', 'Van'], 'Lastname' : ['Roch', 'borh', 'nilsa']} for k, v in dict.items(): if k == 'id': loc = v.index(iin) print("Hello, {} {}".format(dict['Firstname'][loc], dict['Lastname'][loc])) else: print('Sorry, you are not a member') </code></pre>
-1
2016-08-29T16:26:26Z
[ "python", "for-loop", "dictionary", "input", "output" ]
Python PDF module and Visual Studio
39,210,636
<p>I'm teaching myself Python thanks to a book and nice people i find every day in SO. Thanks all of you.</p> <p>The question is that i been using VS, because i find it easy, but idk how/where to write commands like "python pythonprogram.py" and make use of the optparse module as i do on a Linux console.</p> <p>The program i'm working on extracts the metadata from a pdf and it's the code below. </p> <pre><code>import PyPDF2 import optparse def printMeta(fileName): pdfFile = pdfFileReader(file(fileName, 'rb')) docInfo = pdfFile.getDocumentInfo() print('[*] PDF Metadata For: ' + str(fileName)) for metaItem in docInfo: print('[+]' + metaItem + ':' + docInfo[metaItem]) def main(): parser = optparse.OptionParser('usage %prog' + '-F &lt;PDF File Name&gt;') parser.add_option('-F', dest='fileName', type='string', help='specify PDF file Name') (options, args) = parser.parse_args() fileName = options.fileName if fileName == None: print(parser.usage) exit(0) else: printMeta(fileName) if __name__ == '__main__': fileName = 'pdftest.pdf' main() </code></pre> <p>This is a double question, one about VS proper use and the other to ask if my code works. I want to say that the pdftest.pdf is in the python program folder so i don't need a direction if i'm right. Thanks </p>
0
2016-08-29T16:09:58Z
39,216,108
<p>To make sure where your relative path starts, you might want to use <code>os.chdir</code></p> <pre><code>from os import chdir chdir("path/to/my/python/file") </code></pre> <p>then, you'll be able to import files in the same directory even if you're running the script from another folder.</p> <p>Hope that helps</p>
0
2016-08-29T22:25:43Z
[ "python", "visual-studio", "python-3.x", "pdf" ]
Change name of the "Authentication and Authorization" menu in Django/python
39,210,668
<p>I'm learning python/Django and setting up my first project. All is going well but I've been searching like crazy on something very simple.</p> <p>There is a default menu item "Authentication and Authorization" and I want to change the name. I've searched in the template if I need to extend something, I've searched if there's a <code>.po</code> file or what not but I can't find it nor a hint on which parameter I should overwrite in <code>admin.py</code> to set it.</p> <p>I'm not trying to install multi language or some advanced localization, just want to change the name of that one menu item :)</p> <p>Any ideas?</p>
0
2016-08-29T16:11:29Z
39,212,494
<p>This can't be done at least cleanly via templates..</p> <p>You can put the auth app verbose name "authentication and authorization" in your own .po file (&amp; follow Django docs on translation) This way Django will normally use your name. </p>
0
2016-08-29T18:08:11Z
[ "python", "django", "admin" ]
Change name of the "Authentication and Authorization" menu in Django/python
39,210,668
<p>I'm learning python/Django and setting up my first project. All is going well but I've been searching like crazy on something very simple.</p> <p>There is a default menu item "Authentication and Authorization" and I want to change the name. I've searched in the template if I need to extend something, I've searched if there's a <code>.po</code> file or what not but I can't find it nor a hint on which parameter I should overwrite in <code>admin.py</code> to set it.</p> <p>I'm not trying to install multi language or some advanced localization, just want to change the name of that one menu item :)</p> <p>Any ideas?</p>
0
2016-08-29T16:11:29Z
39,213,750
<p>Create a custom <code>AppConfig</code> pointing to original <code>django.auth</code> module and override <code>verbose_name</code>. Then use your custom <code>AppConfig</code> in <code>INSTALLED_APPS</code> instead of original <code>auth</code> app.</p> <p><a href="https://docs.djangoproject.com/en/1.10/ref/applications/#configuring-applications" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/applications/#configuring-applications</a></p>
0
2016-08-29T19:28:40Z
[ "python", "django", "admin" ]
plot data points on map
39,210,706
<p>While trying to plot gps coordinates on a map from a CSV file named test_gps.csv and i am getting the error:</p> <pre><code>ValueError: Some errors were detected ! Line #1 (got 2 columns instead of 2) Line #2 (got 2 columns instead of 2) ... </code></pre> <p>My code is:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap airports = np.genfromtxt("test_gps.csv", delimiter=';', dtype=[('lat', np.float32), ('lon', np.float32)], usecols=(1, 2)) fig = plt.figure() themap = Basemap(projection='gall', llcrnrlon = -15, llcrnrlat = 28, urcrnrlon = 45, urcrnrlat = 73, resolution = 'l', area_thresh = 100000.0, ) themap.drawcoastlines() themap.drawcountries() themap.fillcontinents(color = 'gainsboro') themap.drawmapboundary(fill_color='steelblue') x, y = themap(airports['lon'], airports['lat']) themap.plot(x, y, 'o', color='Indigo', markersize=4 ) plt.show() </code></pre> <p>The CSV has the format:</p> <pre><code>-344.586.792;-585.306.702 -314.071.598;-641.856.689 -3.435.215;-587.938.194 -346.999.893;-583.838.615 -517.951.889;-594.954.567 -517.951.889;-594.954.567 474.808.006;97.561.398 </code></pre> <p>I tried to change the data format to other extensions and the delimiter but i still get the same error.Any idea what can I be doing wrong?! Thanks</p>
1
2016-08-29T16:14:02Z
39,211,375
<p>It is because the index in usecols starts from 0 not 1. And the code was expecting another column to read the data and throwing the error.</p> <p>This change in the code is able to read the values.</p> <pre><code>airports = np.genfromtxt("test_gps.csv", delimiter=';', dtype=[('lat', np.float32), ('lon', np.float32)], usecols=(0, 1)) </code></pre> <p>Also please try to change the values in the .csv file to have just one decimal point since the values are being read as <code>nan</code>, if it has two decimal points.</p>
1
2016-08-29T16:57:41Z
[ "python", "matplotlib-basemap" ]
Selenium Python - Finding div containing two specific elements
39,210,743
<p>I'm building a python script using selenium, and have ran into a quite confusing problem.</p> <p>The website lists products using a name, which is not unique, and a color, which is not unique either. The color and name elements have the same parent.</p> <p>My script gets user input on which product he wants the script to buy for him, and which color.</p> <p><strong>The problem:</strong> I can't for the life of me figure out how to select the right product using the two variables productName and productColor. </p> <p><strong>DOM:</strong></p> <pre><code>&lt;div class="inner-article"&gt; &lt;h1&gt; &lt;a class="product-name"&gt;Silk Shirt&lt;/a&gt; &lt;/h1&gt; &lt;p&gt; &lt;a class="product-color"&gt;Black&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; </code></pre> <p><strong>What i've tried so far:</strong> Obviously, selecting the first product named Silk Shirt on the page is quite easy. I considered selecting the first product, then selecting that products parent, selecting that elements parent, then selecting that parents second child, checking if it was black, and proceeding, but CSS doesn't have a parent selector. </p> <p>How would i go about doing this?</p>
0
2016-08-29T16:16:30Z
39,211,028
<p>Create a main loop that selects each <code>div class="inner-article"</code> element.</p> <p>In the loop, look for elements that have an <code>h1</code> child element and an <code>a class=product-name</code> grandchild element with text of "Silk Shirt", and a <code>p</code> child element and a <code>a class=product-color</code> grandchild element with text of "Black".</p>
1
2016-08-29T16:35:09Z
[ "python", "css", "selenium", "selection" ]
Selenium Python - Finding div containing two specific elements
39,210,743
<p>I'm building a python script using selenium, and have ran into a quite confusing problem.</p> <p>The website lists products using a name, which is not unique, and a color, which is not unique either. The color and name elements have the same parent.</p> <p>My script gets user input on which product he wants the script to buy for him, and which color.</p> <p><strong>The problem:</strong> I can't for the life of me figure out how to select the right product using the two variables productName and productColor. </p> <p><strong>DOM:</strong></p> <pre><code>&lt;div class="inner-article"&gt; &lt;h1&gt; &lt;a class="product-name"&gt;Silk Shirt&lt;/a&gt; &lt;/h1&gt; &lt;p&gt; &lt;a class="product-color"&gt;Black&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; </code></pre> <p><strong>What i've tried so far:</strong> Obviously, selecting the first product named Silk Shirt on the page is quite easy. I considered selecting the first product, then selecting that products parent, selecting that elements parent, then selecting that parents second child, checking if it was black, and proceeding, but CSS doesn't have a parent selector. </p> <p>How would i go about doing this?</p>
0
2016-08-29T16:16:30Z
39,254,483
<p>Perhaps try searching using xpath. The xpath below will return the div element that contains the product and color you desire.</p> <pre><code>driver.find_element_by_xpath('//div[@class="inner-article"][.//a[@class="product-name"][.="Silk Shirt"]][.//a[@class="product-color"][.="Black"]]') </code></pre> <p>To make it reusable:</p> <pre><code>def select_product(name, color): return driver.find_element_by_xpath('//div[@class="inner-article"][.//a[@class="product-name"][.="{product_name}"]][.//a[@class="product-color"][.="{product_color}"]]'.format(product_name=name, product_color=color)) </code></pre>
0
2016-08-31T16:16:57Z
[ "python", "css", "selenium", "selection" ]
Randomly distribute files into train/test given a ratio
39,210,765
<p>I am at the moment trying make a setup script, capable of setting up a workspace up for me, such that I don't need to do it manually. I started doing this in bash, but quickly realized that would not work that well. </p> <p>My next idea was to do it using python, but can't seem to do it a proper way.. My idea was to make a list (a list being a .txt files with the paths for all the datafiles), shuffle this list, and then move each file to either my train dir or test dir, given the ratio.... </p> <p>But this is python, isn't there a more simpler way to do it, it seems like I am doing an unessesary workaround just to split the files. </p> <p>Bash Code: </p> <pre><code># Partition data randomly into train and test. cd ${PATH_TO_DATASET} SPLIT=0.5 #train/test split NUMBER_OF_FILES=$(ls ${PATH_TO_DATASET} | wc -l) ## number of directories in the dataset even=1 echo ${NUMBER_OF_FILES} if [ `echo "${NUMBER_OF_FILES} % 2" | bc` -eq 0 ] then even=1 echo "Even is true" else even=0 echo "Even is false" fi echo -e "${BLUE}Seperating files in to train and test set!${NC}" for ((i=1; i&lt;=${NUMBER_OF_FILES}; i++)) do ran=$(python -c "import random;print(random.uniform(0.0, 1.0))") if [[ ${ran} &lt; ${SPLIT} ]] then ##echo "test ${ran}" cp -R $(ls -d */|sed "${i}q;d") ${WORKSPACE_SETUP_ROOT}/../${WORKSPACE}/data/test/ else ##echo "train ${ran}" cp -R $(ls -d */|sed "${i}q;d") ${WORKSPACE_SETUP_ROOT}/../${WORKSPACE}/data/train/ fi ##echo $(ls -d */|sed "${i}q;d") done cd ${WORKSPACE_SETUP_ROOT}/../${WORKSPACE}/data NUMBER_TRAIN_FILES=$(ls train/ | wc -l) NUMBER_TEST_FILES=$(ls test/ | wc -l) echo "${NUMBER_TRAIN_FILES} and ${NUMBER_TEST_FILES}..." echo $(calc ${NUMBER_TRAIN_FILES}/${NUMBER_OF_FILES}) if [[ ${even} = 1 ]] &amp;&amp; [[ ${NUMBER_TRAIN_FILES}/${NUMBER_OF_FILES} != ${SPLIT} ]] then echo "Something need to be fixed!" if [[ $(calc ${NUMBER_TRAIN_FILES}/${NUMBER_OF_FILES}) &gt; ${SPLIT} ]] then echo "Too many files in the TRAIN set move some to TEST" cd train echo $(pwd) while [[ ${NUMBER_TRAIN_FILES}/${NUMBER_TEST_FILES} != ${SPLIT} ]] do mv $(ls -d */|sed "1q;d") ../test/ echo $(calc ${NUMBER_TRAIN_FILES}/${NUMBER_OF_FILES}) done else echo "Too many files in the TEST set move some to TRAIN" cd test while [[ ${NUMBER_TRAIN_FILES}/${NUMBER_TEST_FILES} != ${SPLIT} ]] do mv $(ls -d */|sed "1q;d") ../train/ echo $(calc ${NUMBER_TRAIN_FILES}/${NUMBER_OF_FILES}) done fi fi </code></pre> <p>My problem were the last part. Since i picking the numbers by random, I would not be sure that the data would be partitioned as hoped, which my last if statement were to check whether the partition was done right, and if not then fix it.. This was not possible since i am checking floating points, and the solution in general became more like a quick fix. </p>
0
2016-08-29T16:17:58Z
39,210,813
<p><code>scikit-learn</code> comes to the rescue =)</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from sklearn.cross_validation import train_test_split &gt;&gt;&gt; X, y = np.arange(10).reshape((5, 2)), range(5) &gt;&gt;&gt; X array([[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]) &gt;&gt;&gt; y [0, 1, 2, 3, 4] # If i want 1/4 of the data for testing # and i set a random seed of 42. &gt;&gt;&gt; X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42) &gt;&gt;&gt; X_train array([[4, 5], [0, 1], [6, 7]]) &gt;&gt;&gt; X_test array([[2, 3], [8, 9]]) &gt;&gt;&gt; y_train [2, 0, 3] &gt;&gt;&gt; y_test [1, 4] </code></pre> <p>See <a href="http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.train_test_split.html" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.train_test_split.html</a></p> <hr> <p>To demonstrate:</p> <pre><code>alvas@ubi:~$ mkdir splitfileproblem alvas@ubi:~$ cd splitfileproblem/ alvas@ubi:~/splitfileproblem$ mkdir original alvas@ubi:~/splitfileproblem$ mkdir train alvas@ubi:~/splitfileproblem$ mkdir test alvas@ubi:~/splitfileproblem$ ls original train test alvas@ubi:~/splitfileproblem$ cd original/ alvas@ubi:~/splitfileproblem/original$ ls alvas@ubi:~/splitfileproblem/original$ echo 'abc' &gt; a.txt alvas@ubi:~/splitfileproblem/original$ echo 'def\nghi' &gt; b.txt alvas@ubi:~/splitfileproblem/original$ cat a.txt abc alvas@ubi:~/splitfileproblem/original$ echo -e 'def\nghi' &gt; b.txt alvas@ubi:~/splitfileproblem/original$ cat b.txt def ghi alvas@ubi:~/splitfileproblem/original$ echo -e 'jkl' &gt; c.txt alvas@ubi:~/splitfileproblem/original$ echo -e 'mno' &gt; d.txt alvas@ubi:~/splitfileproblem/original$ ls a.txt b.txt c.txt d.txt </code></pre> <p>In Python:</p> <pre><code>alvas@ubi:~/splitfileproblem$ ls original test train alvas@ubi:~/splitfileproblem$ python Python 2.7.12 (default, Jul 1 2016, 15:12:24) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; from sklearn.cross_validation import train_test_split &gt;&gt;&gt; os.listdir('original') ['b.txt', 'd.txt', 'c.txt', 'a.txt'] &gt;&gt;&gt; X = y= os.listdir('original') &gt;&gt;&gt; X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0) &gt;&gt;&gt; X_train ['a.txt', 'd.txt', 'b.txt'] &gt;&gt;&gt; X_test ['c.txt'] </code></pre> <p>Now move the files:</p> <pre><code>&gt;&gt;&gt; for x in X_train: ... os.rename('original/'+x , 'train/'+x) ... &gt;&gt;&gt; for x in X_test: ... os.rename('original/'+x , 'test/'+x) ... &gt;&gt;&gt; os.listdir('test') ['c.txt'] &gt;&gt;&gt; os.listdir('train') ['b.txt', 'd.txt', 'a.txt'] &gt;&gt;&gt; os.listdir('original') [] </code></pre> <p>See also: <a href="http://stackoverflow.com/questions/8858008/how-to-move-a-file-in-python">How to move a file in Python</a></p>
2
2016-08-29T16:21:30Z
[ "python", "bash", "text-files", "file-handling", "train-test-split" ]
Randomly distribute files into train/test given a ratio
39,210,765
<p>I am at the moment trying make a setup script, capable of setting up a workspace up for me, such that I don't need to do it manually. I started doing this in bash, but quickly realized that would not work that well. </p> <p>My next idea was to do it using python, but can't seem to do it a proper way.. My idea was to make a list (a list being a .txt files with the paths for all the datafiles), shuffle this list, and then move each file to either my train dir or test dir, given the ratio.... </p> <p>But this is python, isn't there a more simpler way to do it, it seems like I am doing an unessesary workaround just to split the files. </p> <p>Bash Code: </p> <pre><code># Partition data randomly into train and test. cd ${PATH_TO_DATASET} SPLIT=0.5 #train/test split NUMBER_OF_FILES=$(ls ${PATH_TO_DATASET} | wc -l) ## number of directories in the dataset even=1 echo ${NUMBER_OF_FILES} if [ `echo "${NUMBER_OF_FILES} % 2" | bc` -eq 0 ] then even=1 echo "Even is true" else even=0 echo "Even is false" fi echo -e "${BLUE}Seperating files in to train and test set!${NC}" for ((i=1; i&lt;=${NUMBER_OF_FILES}; i++)) do ran=$(python -c "import random;print(random.uniform(0.0, 1.0))") if [[ ${ran} &lt; ${SPLIT} ]] then ##echo "test ${ran}" cp -R $(ls -d */|sed "${i}q;d") ${WORKSPACE_SETUP_ROOT}/../${WORKSPACE}/data/test/ else ##echo "train ${ran}" cp -R $(ls -d */|sed "${i}q;d") ${WORKSPACE_SETUP_ROOT}/../${WORKSPACE}/data/train/ fi ##echo $(ls -d */|sed "${i}q;d") done cd ${WORKSPACE_SETUP_ROOT}/../${WORKSPACE}/data NUMBER_TRAIN_FILES=$(ls train/ | wc -l) NUMBER_TEST_FILES=$(ls test/ | wc -l) echo "${NUMBER_TRAIN_FILES} and ${NUMBER_TEST_FILES}..." echo $(calc ${NUMBER_TRAIN_FILES}/${NUMBER_OF_FILES}) if [[ ${even} = 1 ]] &amp;&amp; [[ ${NUMBER_TRAIN_FILES}/${NUMBER_OF_FILES} != ${SPLIT} ]] then echo "Something need to be fixed!" if [[ $(calc ${NUMBER_TRAIN_FILES}/${NUMBER_OF_FILES}) &gt; ${SPLIT} ]] then echo "Too many files in the TRAIN set move some to TEST" cd train echo $(pwd) while [[ ${NUMBER_TRAIN_FILES}/${NUMBER_TEST_FILES} != ${SPLIT} ]] do mv $(ls -d */|sed "1q;d") ../test/ echo $(calc ${NUMBER_TRAIN_FILES}/${NUMBER_OF_FILES}) done else echo "Too many files in the TEST set move some to TRAIN" cd test while [[ ${NUMBER_TRAIN_FILES}/${NUMBER_TEST_FILES} != ${SPLIT} ]] do mv $(ls -d */|sed "1q;d") ../train/ echo $(calc ${NUMBER_TRAIN_FILES}/${NUMBER_OF_FILES}) done fi fi </code></pre> <p>My problem were the last part. Since i picking the numbers by random, I would not be sure that the data would be partitioned as hoped, which my last if statement were to check whether the partition was done right, and if not then fix it.. This was not possible since i am checking floating points, and the solution in general became more like a quick fix. </p>
0
2016-08-29T16:17:58Z
39,211,194
<p>Here's first dry-cut solution, pure Python:</p> <pre><code>import sys, random, os def splitdirs(files, dir1, dir2, ratio): shuffled = files[:] random.shuffle(shuffled) num = round(len(shuffled) * ratio) to_dir1, to_dir2 = shuffled[:num], shuffled[num:] for d in dir1, dir2: if not os.path.exists(d): os.mkdir(d) for file in to_dir1: os.symlink(file, os.path.join(dir1, os.path.basename(file))) for file in to_dir2: os.symlink(file, os.path.join(dir2, os.path.basename(file))) if __name__ == '__main__': if len(sys.argv) != 5: sys.exit('Usage: {} files.txt dir1 dir2 ratio'.format(sys.argv[0])) else: files, dir1, dir2, ratio = sys.argv[1:] ratio = float(ratio) files = open(files).read().splitlines() splitdirs(files, dir1, dir2, ratio) </code></pre> <p><code>[thd@aspire ~]$ python ./test.py ./files.txt dev tst 0.4</code> Here 40% of listed in files.txt goes to dev dir, and 60% -- to tst</p> <p>It makes symliks instead of copy, if you need true files, change <code>os.symlink</code> to <code>shutil.copy2</code></p>
1
2016-08-29T16:45:12Z
[ "python", "bash", "text-files", "file-handling", "train-test-split" ]
Randomly distribute files into train/test given a ratio
39,210,765
<p>I am at the moment trying make a setup script, capable of setting up a workspace up for me, such that I don't need to do it manually. I started doing this in bash, but quickly realized that would not work that well. </p> <p>My next idea was to do it using python, but can't seem to do it a proper way.. My idea was to make a list (a list being a .txt files with the paths for all the datafiles), shuffle this list, and then move each file to either my train dir or test dir, given the ratio.... </p> <p>But this is python, isn't there a more simpler way to do it, it seems like I am doing an unessesary workaround just to split the files. </p> <p>Bash Code: </p> <pre><code># Partition data randomly into train and test. cd ${PATH_TO_DATASET} SPLIT=0.5 #train/test split NUMBER_OF_FILES=$(ls ${PATH_TO_DATASET} | wc -l) ## number of directories in the dataset even=1 echo ${NUMBER_OF_FILES} if [ `echo "${NUMBER_OF_FILES} % 2" | bc` -eq 0 ] then even=1 echo "Even is true" else even=0 echo "Even is false" fi echo -e "${BLUE}Seperating files in to train and test set!${NC}" for ((i=1; i&lt;=${NUMBER_OF_FILES}; i++)) do ran=$(python -c "import random;print(random.uniform(0.0, 1.0))") if [[ ${ran} &lt; ${SPLIT} ]] then ##echo "test ${ran}" cp -R $(ls -d */|sed "${i}q;d") ${WORKSPACE_SETUP_ROOT}/../${WORKSPACE}/data/test/ else ##echo "train ${ran}" cp -R $(ls -d */|sed "${i}q;d") ${WORKSPACE_SETUP_ROOT}/../${WORKSPACE}/data/train/ fi ##echo $(ls -d */|sed "${i}q;d") done cd ${WORKSPACE_SETUP_ROOT}/../${WORKSPACE}/data NUMBER_TRAIN_FILES=$(ls train/ | wc -l) NUMBER_TEST_FILES=$(ls test/ | wc -l) echo "${NUMBER_TRAIN_FILES} and ${NUMBER_TEST_FILES}..." echo $(calc ${NUMBER_TRAIN_FILES}/${NUMBER_OF_FILES}) if [[ ${even} = 1 ]] &amp;&amp; [[ ${NUMBER_TRAIN_FILES}/${NUMBER_OF_FILES} != ${SPLIT} ]] then echo "Something need to be fixed!" if [[ $(calc ${NUMBER_TRAIN_FILES}/${NUMBER_OF_FILES}) &gt; ${SPLIT} ]] then echo "Too many files in the TRAIN set move some to TEST" cd train echo $(pwd) while [[ ${NUMBER_TRAIN_FILES}/${NUMBER_TEST_FILES} != ${SPLIT} ]] do mv $(ls -d */|sed "1q;d") ../test/ echo $(calc ${NUMBER_TRAIN_FILES}/${NUMBER_OF_FILES}) done else echo "Too many files in the TEST set move some to TRAIN" cd test while [[ ${NUMBER_TRAIN_FILES}/${NUMBER_TEST_FILES} != ${SPLIT} ]] do mv $(ls -d */|sed "1q;d") ../train/ echo $(calc ${NUMBER_TRAIN_FILES}/${NUMBER_OF_FILES}) done fi fi </code></pre> <p>My problem were the last part. Since i picking the numbers by random, I would not be sure that the data would be partitioned as hoped, which my last if statement were to check whether the partition was done right, and if not then fix it.. This was not possible since i am checking floating points, and the solution in general became more like a quick fix. </p>
0
2016-08-29T16:17:58Z
39,254,279
<p>Here's a simple example that uses bash's <code>$RANDOM</code> to move things to one of two target directories.</p> <pre><code>$ touch {1..10} $ mkdir red blue $ a=(*/) $ RANDOM=$$ $ for f in [0-9]*; do mv -v "$f" "${a[$((RANDOM/(32768/${#a[@]})))]}"; done 1 -&gt; red/1 10 -&gt; red/10 2 -&gt; blue/2 3 -&gt; red/3 4 -&gt; red/4 5 -&gt; red/5 6 -&gt; red/6 7 -&gt; blue/7 8 -&gt; blue/8 9 -&gt; blue/9 </code></pre> <p>This example starts with the creation of 10 files and two target directories. It sets an array to <code>*/</code> which expands to "all the directories within the current directory". It then runs a for loop with what looks like line noise in it. I'll break it apart for ya.</p> <p><code>"${a[$((RANDOM/(32768/${#a[@]})+1))]}"</code> is:</p> <ul> <li><code>${a[</code> ... the array "a",</li> <li><code>$((...))</code> ... whose subscript is an integer math function.</li> <li><code>$RANDOM</code> is a bash variable that generates a ramdom(ish) number from 0 to 32767, and our formula divides the denominator of that ratio by:</li> <li><code>${#a[@]}</code>, effectively multiplying <code>RANDOM/32768</code> by the number of elements in the array "a".</li> </ul> <p>The result of all this is that we pick a random array element, a.k.a. a random directory.</p> <p>If you really want to work from your "list of files", and assuming you leave your list of potential targets in the array "a", you could replace the for loop with a while loop:</p> <pre><code>while read f; do mv -v "$f" "${a[$((RANDOM/(32768/${#a[@]})))]}" done &lt; /dir/file.txt </code></pre> <p>Now ... these solutions split results "evenly". That's what happens when you multiply the denominator. And because they're random, there's no way to insure that your <a href="http://dilbert.com/strip/2001-10-25" rel="nofollow">random numbers won't put all your files into a single directory</a>. So to get a split, you need to be more creative.</p> <p>Let's assume we're dealing with only two targets (since I think that's what you're doing). If you're looking for a 25/75 split, slice up the random number range accordingly.</p> <pre><code>$ declare -a b=([0]="red/" [8192]="blue/") $ for f in {1..10}; do n=$RANDOM; for i in "${!b[@]}"; do [ $i -gt $n ] &amp;&amp; break; o="${b[i]}"; done; mv -v "$f" "$o"; done </code></pre> <p>Broken out for easier reading, here's what we've got, with comments:</p> <pre><code>declare -a b=([0]="red/" [8192]="blue/") for f in {1..10}; do # Step through our files... n=$RANDOM # Pick a random number, 0-32767 for i in "${!b[@]}"; do # Step through the indices of the array of targets [ $i -gt $n ] &amp;&amp; break # If the current index is &gt; than the random number, stop. o="${b[i]}" # If we haven't stopped, name this as our target, done mv -v "$f" "$o" # and move the file there. done </code></pre> <p>We define our split using the index of an array. 8192 is 25% of 32767, the max value of $RANDOM. You could split things however you like within this range, including amongst more than 2.</p> <p>If you want to test the results of this method, counting results in an array is a way to do it. Let's build a shell function to help with testing.</p> <pre><code>$ tester() { declare -A c=(); for f in {1..10000}; do n=$RANDOM; for i in "${!b[@]}"; do [ $i -gt $n ] &amp;&amp; break; o="${b[i]}"; done; ((c[$o]++)); done; declare -p c; } $ declare -a b='([0]="red/" [8192]="blue/")' $ tester declare -A c='([blue/]="7540" [red/]="2460" )' $ b=([0]="red/" [10992]="blue/") $ tester declare -A c='([blue/]="6633" [red/]="3367" )' </code></pre> <p>On the first line, we define our function. Second line sets the "b" array with a 25/75 split, then we run the function, whose output is the the counter array. Then we redefine the "b" array with a 33/67 split (or so), and run the function again to demonstrate results.</p> <p>So... While you certainly <em>could</em> use python for this, you can almost certainly achieve what you need with bash and a little math.</p>
1
2016-08-31T16:04:27Z
[ "python", "bash", "text-files", "file-handling", "train-test-split" ]
Python figure crashing and is unresponsive
39,210,995
<p>I'm trying to make a script where it'll go to each point and save a figure of the plot if the point is good or not. But the figure is just unresponsive/blank. Any ideas?</p> <pre><code>import matplotlib.pyplot as plt A = range(-3, 3, 1) for moving in range(len(A)): parsedFile = 'TEST/data_%d' % (moving) plt.figure(1) plt.plot(A) plt.plot(A[moving],"rx") plt.show(block=False) plotChoice = raw_input("Is this a good value? (y/n): ") if plotChoice == 'y': plt.savefig(parsedFile + '.jpg', pdi=1000) plt.clf() plt.close() else: plt.clf() plt.close() </code></pre> <p>Ran using PyCharm</p>
1
2016-08-29T16:33:14Z
39,214,930
<p>In non-interactive mode <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.show" rel="nofollow">plt.show()</a> will block until the figure is closed. The <code>block</code> argument is experimental according to the documentation, and it seems to me that it won't work in your case. Well, at least it doesn't work for me.</p> <p>To interact with the user of the plot you can use a <a href="http://matplotlib.org/api/widgets_api.html#matplotlib.widgets.Button" rel="nofollow">Button</a> widget. Two buttons 'Yes' and 'No' can be placed directly to the plot. Here you can find an example: <a href="http://matplotlib.org/examples/widgets/buttons.html" rel="nofollow">http://matplotlib.org/examples/widgets/buttons.html</a></p> <p>Button placement is not straightforward, so to simplifiy things a little bit I used plot title for the question and added buttons alongside. May seem ugly, feel free to adjust to your needs:</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.widgets import Button ax = plt.subplot() plt.title('Is this a good value?') A = range(-3, 3, 1) for moving in range(len(A)): parsedFile = 'TEST/data_%d' % moving ax.plot(A) ax.plot(A[moving], 'rx') def yes(event): plt.savefig(parsedFile + '.jpg', pdi=1000) plt.clf() plt.close() def no(event): plt.clf() plt.close() yes_axes = plt.axes([0.69, 0.91, 0.1, 0.075]) yes_button = Button(yes_axes, 'Yes') yes_button.on_clicked(yes) no_axes = plt.axes([0.80, 0.91, 0.1, 0.075]) no_button = Button(no_axes, 'No') no_button.on_clicked(no) plt.show() </code></pre>
0
2016-08-29T20:47:42Z
[ "python", "debugging", "figure" ]
Operation of Python's LRU cache
39,211,095
<p>I've got the following code:</p> <pre><code>def sharpe(self): return (self.weighted_returns()/self.weighted_returns().std())*np.sqrt(252) </code></pre> <p>Where <code>self.weighted_returns()</code> has a <code>@lru_cache(maxsize=None)</code> decorator.</p> <p>Will <code>self.weighted_returns()</code> be calculated once or twice?</p>
0
2016-08-29T16:38:43Z
39,211,532
<p>You could use <code>functools.lru_cache</code> for this. But if you're only caching the calculations for <code>self</code> and the function does not use an argument, it is an overkill. </p> <p>Rather, I'd steal the lazy <a href="http://docs.pylonsproject.org/projects/pyramid/en/latest/api/decorator.html#pyramid.decorator.reify" rel="nofollow"><code>reify</code></a> decorator from Pyramid:</p> <pre><code>class reify(object): def __init__(self, wrapped): self.wrapped = wrapped update_wrapper(self, wrapped) def __get__(self, inst, objtype=None): if inst is None: return self val = self.wrapped(inst) setattr(inst, self.wrapped.__name__, val) return val </code></pre> <p>And use it on <code>weighted_returns</code>, turning it into a lazily calculated attribute:</p> <pre><code>@reify def weighted_returns(self): # calculate the returns using self normally return returns </code></pre> <p>Then your calculation would be </p> <pre><code>self.weighted_returns / self.weighted_returns.std() * np.sqrt(252) </code></pre> <p>(notice the lack of parentheses). </p> <p>Unlike <code>functools.lru_cache(maxsize=None)</code> which will keep a dictionary of unlimited size (it is going to increase in size until you kill the program), the <code>reify</code> decorator caches the calculation result on the instance itself. If the instance is garbage-collected, then so are its cached weighted returns. </p>
0
2016-08-29T17:06:50Z
[ "python", "python-3.x" ]
Prime code not working
39,211,186
<p>I am trying to learn some code, and found python. I'm only a beginner but intrested in a programming language.</p> <p>I have some trouble writing my first program. I am trying to make a program that ask the user for a number, then checks if the number is a prime number, if it is, it will add it to the prime number list.</p> <p>here is my code.</p> <pre><code>prime = [2,3,5,7] get = int(input("what number do you want to check ? ")) a = 0 while a &lt; len(prime): print("Test " + str(a+1)) test = (get / prime[a]) if isinstance(test, int): print(str(get) + " is not a prime number" ) break else: a += 1 else: prime.extend(get) print(str(get) + " is a prime number, prime number added to list" </code></pre>
0
2016-08-29T16:44:37Z
39,211,354
<pre><code>prime.extend(get) </code></pre> <p><code>extend</code> is used to add a list to a list. If you only want to add a single value, use <code>append</code>.</p> <pre><code>prime.append(get) </code></pre>
2
2016-08-29T16:56:20Z
[ "python", "primes" ]
Prime code not working
39,211,186
<p>I am trying to learn some code, and found python. I'm only a beginner but intrested in a programming language.</p> <p>I have some trouble writing my first program. I am trying to make a program that ask the user for a number, then checks if the number is a prime number, if it is, it will add it to the prime number list.</p> <p>here is my code.</p> <pre><code>prime = [2,3,5,7] get = int(input("what number do you want to check ? ")) a = 0 while a &lt; len(prime): print("Test " + str(a+1)) test = (get / prime[a]) if isinstance(test, int): print(str(get) + " is not a prime number" ) break else: a += 1 else: prime.extend(get) print(str(get) + " is a prime number, prime number added to list" </code></pre>
0
2016-08-29T16:44:37Z
39,211,505
<p>Given the way you set it up, you would get that 26 is a prime. Since it is only divisible by 13, and 13 is not yet in the table, it will fall through the while. You need to find all primes less than the number that you ask for to populate your table, or set the program find the first n primes.</p> <p>I notice that the else on the if is in the wrong indentation. </p> <p>You should use the modulo operator on the if and not division as you my be getting integer division and not floating point. </p> <p>I put the fix in the code below.</p> <p>Note that the problem is that you are using extend when you should be using append.</p> <p><a href="http://stackoverflow.com/questions/252703/append-vs-extend">append vs. extend</a></p> <p><a href="https://docs.python.org/2/library/array.html?#array.array.append" rel="nofollow"><code>append</code></a>: Appends object at end.</p> <pre><code>x = [1, 2, 3] x.append([4, 5]) print (x) </code></pre> <p>gives you: <code>[1, 2, 3, [4, 5]]</code></p> <hr> <p><a href="https://docs.python.org/2/library/array.html?#array.array.extend" rel="nofollow"><code>extend</code></a>: Extends list by appending elements from the iterable.</p> <pre><code>x = [1, 2, 3] x.extend([4, 5]) print (x) </code></pre> <p>gives you: <code>[1, 2, 3, 4, 5]</code></p> <p>Here is the code set up using modulo for the test rather than division. This shows the correct situation. Note that when doing division and getting a floating point result isinstance() may not give the correct answer. There are a number of sources that recommend not using that as a test.</p> <p>If you are using Python 3.0, then you would be getting a floating point response rather than an int answer. See <a href="http://stackoverflow.com/questions/1282945/python-integer-division-yields-float">Python integer division yields float</a></p> <pre><code>prime = [2,3,5,7] get = int(input("what number do you want to check ? ")) a = 0 while a &lt; len(prime): print("Test " + str(a+1)) if (get % prime[a]) == 0: # Number was evenly divisible by a prime number print(str(get) + " is not a prime number" ) break else: a += 1 else: # Number was not evenly divisible by primes already in table prime.append(get) print(str(get) + " is a prime number, prime number added to list" </code></pre>
1
2016-08-29T17:05:15Z
[ "python", "primes" ]
A pythonic way to use Lxml to find all elements of a certain type
39,211,236
<p>I'm not very good with Lxml but thought a few of you might know how one can quickly get through the following task. See below... Specifically, I need to parse the XML to get the value of the name attribute in all of the category elements. For example:</p> <pre><code>&lt;categories&gt; &lt;category name="Test"&gt; &lt;p&gt;test_1&lt;/p&gt; &lt;/category&gt; &lt;category name="Acme"&gt; &lt;p&gt;acme_1&lt;/p&gt; &lt;/category&gt; &lt;/categories </code></pre> <p>So for the above case, the results would be the following category names as a result:</p> <pre><code>Test Acme </code></pre>
-1
2016-08-29T16:48:38Z
39,211,335
<pre><code>names = root_el.xpath('//category/@name') </code></pre>
1
2016-08-29T16:54:53Z
[ "python", "xml", "lxml" ]
Failure to load image with AsyncImage in kivy
39,211,301
<p>i have a code that loads an image online with the AsyncImage module in kivy. i wrote the code in python3 which runs well on the pc but doesnt work on a packaged apk. i think this is because i packaged it using python2.7 buildozer. thanks <a href="http://i.stack.imgur.com/I5f0V.png" rel="nofollow">an image showing the error in logcat</a></p> <p>this is the code</p> <pre><code>class Gallery(Screen,GridLayout): scroller = ObjectProperty(None) grid = ObjectProperty(None) def __init__ (self,**kwargs): super(Gallery, self).__init__(**kwargs) if len(self.ids.grid.children) == 0: for i in range(13): src = "http://placehold.it/480x270.png&amp;text=slide-%d&amp;.png" % i image = MyTile(source=src, allow_stretch=True) self.ids.grid.add_widget(image) </code></pre>
2
2016-08-29T16:52:51Z
39,221,882
<p>It seems that your APK is missing ssl support (the URL is redirecting you to an https site...)</p> <p>try adding:</p> <pre><code> requirements = kivy,OTHER_STUFF_YOU_NEED,openssl </code></pre> <p>to your buildozer spec.</p>
1
2016-08-30T07:57:18Z
[ "python", "kivy" ]
multiprocessing - calling function with different input files
39,211,309
<p>I have a function which reads in a file, compares a record in that file to a record in another file and depending on a rule, appends a record from the file to one of two lists. </p> <p>I have an empty list for adding matched results to:</p> <pre><code>match = [] </code></pre> <p>I have a list <code>restrictions</code> that I want to compare records in a series of files with.</p> <p>I have a function for reading in the file I wish to see if contains any matches. If there is a match, I append the record to the <code>match</code> list.</p> <pre><code>def link_match(file): links = json.load(file) for link in links: found = False try: for other_link in other_links: if link['data'] == other_link['data']: match.append(link) found = True else: pass else: print "not found" </code></pre> <p>I have numerous files that I wish to compare and I thus wish to use the multiprocessing library. </p> <p>I create a list of file names to act as function arguments:</p> <pre><code>list_files=[] for file in glob.glob("/path/*.json"): list_files.append(file) </code></pre> <p>I then use the <code>map</code> feature to call the function with the different input files:</p> <pre><code>if __name__ == '__main__': pool = multiprocessing.Pool(processes=6) pool.map(link_match,list_files) pool.close() pool.join() </code></pre> <p>CPU use goes through the roof and by adding in a print line to the function loop I can see that matches are being found and the function is behaving correctly. </p> <p>However, the <code>match</code> results list remains empty. What am I doing wrong?</p>
1
2016-08-29T16:53:15Z
39,211,384
<p>Multiprocessing creates multiple processes. The context of your "match" variable will now be in that child process, not the parent Python process that kicked the processing off.</p> <p>Try writing the list results out to a file in your function to see what I mean.</p>
1
2016-08-29T16:58:20Z
[ "python", "multiprocessing" ]
multiprocessing - calling function with different input files
39,211,309
<p>I have a function which reads in a file, compares a record in that file to a record in another file and depending on a rule, appends a record from the file to one of two lists. </p> <p>I have an empty list for adding matched results to:</p> <pre><code>match = [] </code></pre> <p>I have a list <code>restrictions</code> that I want to compare records in a series of files with.</p> <p>I have a function for reading in the file I wish to see if contains any matches. If there is a match, I append the record to the <code>match</code> list.</p> <pre><code>def link_match(file): links = json.load(file) for link in links: found = False try: for other_link in other_links: if link['data'] == other_link['data']: match.append(link) found = True else: pass else: print "not found" </code></pre> <p>I have numerous files that I wish to compare and I thus wish to use the multiprocessing library. </p> <p>I create a list of file names to act as function arguments:</p> <pre><code>list_files=[] for file in glob.glob("/path/*.json"): list_files.append(file) </code></pre> <p>I then use the <code>map</code> feature to call the function with the different input files:</p> <pre><code>if __name__ == '__main__': pool = multiprocessing.Pool(processes=6) pool.map(link_match,list_files) pool.close() pool.join() </code></pre> <p>CPU use goes through the roof and by adding in a print line to the function loop I can see that matches are being found and the function is behaving correctly. </p> <p>However, the <code>match</code> results list remains empty. What am I doing wrong?</p>
1
2016-08-29T16:53:15Z
39,211,579
<p>To expand cthrall's answer, you need to return something from your function in order to pass the info back to your main thread, e.g.</p> <pre><code>def link_match(file): [put all the code here] return match [main thread] all_matches = pool.map(link_match,list_files) </code></pre> <p>the list <code>match</code> will be returned from each single thread and <code>map</code> will return a list of lists in this case. You can then <a href="http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python">flatten</a> it again to get the final output.</p> <hr> <p>Alternatively you can use a <a href="https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing.managers" rel="nofollow">shared list</a> but this will just add more headache in my opinion.</p>
1
2016-08-29T17:09:33Z
[ "python", "multiprocessing" ]
multiprocessing - calling function with different input files
39,211,309
<p>I have a function which reads in a file, compares a record in that file to a record in another file and depending on a rule, appends a record from the file to one of two lists. </p> <p>I have an empty list for adding matched results to:</p> <pre><code>match = [] </code></pre> <p>I have a list <code>restrictions</code> that I want to compare records in a series of files with.</p> <p>I have a function for reading in the file I wish to see if contains any matches. If there is a match, I append the record to the <code>match</code> list.</p> <pre><code>def link_match(file): links = json.load(file) for link in links: found = False try: for other_link in other_links: if link['data'] == other_link['data']: match.append(link) found = True else: pass else: print "not found" </code></pre> <p>I have numerous files that I wish to compare and I thus wish to use the multiprocessing library. </p> <p>I create a list of file names to act as function arguments:</p> <pre><code>list_files=[] for file in glob.glob("/path/*.json"): list_files.append(file) </code></pre> <p>I then use the <code>map</code> feature to call the function with the different input files:</p> <pre><code>if __name__ == '__main__': pool = multiprocessing.Pool(processes=6) pool.map(link_match,list_files) pool.close() pool.join() </code></pre> <p>CPU use goes through the roof and by adding in a print line to the function loop I can see that matches are being found and the function is behaving correctly. </p> <p>However, the <code>match</code> results list remains empty. What am I doing wrong?</p>
1
2016-08-29T16:53:15Z
39,211,781
<p><code>multiprocessing</code> runs a new instance of Python for each process in the pool - the context is empty (if you use <code>spawn</code> as a start method) or copied (if you use <code>fork</code>), plus copies of any arguments you pass in (either way), and from there they're all separate. If you want to pass data between branches, there's a few other ways to do it.</p> <ol> <li>Instead of writing to an internal list, write to a file and read from it later when you're done. The largest potential problem here is that only one thing can write to a file at a time, so either you make a lot of separate files (and have to read all of them afterwards) or they all block each other.</li> <li>Continue with <code>multiprocessing</code>, but use a <a href="https://docs.python.org/3.5/library/multiprocessing.html#multiprocessing.Queue" rel="nofollow"><code>multiprocessing.Queue</code></a> instead of a list. This is an object provided specifically for your current use-case: Using multiple processes and needing to pass data between them. Assuming that you should indeed be using <code>multiprocessing</code> (that your situation wouldn't be better for <code>threading</code>, see below), this is probably your best option.</li> <li>Instead of <code>multiprocessing</code>, use <a href="https://docs.python.org/3/library/threading.html#module-threading" rel="nofollow"><code>threading</code></a>. Separate threads all share a single environment. The biggest problems here are that Python only lets one thread actually run Python code at a time, per process. This is called the Global Interpreter Lock (GIL). <code>threading</code> is thus useful when the threads will be waiting on external processes (other programs, user input, reading or writing files), but if most of the time is spent in Python code, it actually takes longer (because it takes a little time to switch threads, and you're not doing anything to save time). This has its own <a href="https://docs.python.org/3/library/queue.html#module-queue" rel="nofollow"><code>queue</code></a>. You should probably use that rather than a plain list, if you use <code>threading</code> - otherwise there's the potential that two threads accessing the list at the same time interfere with each other, if it switches threads at the wrong time.</li> </ol> <p>Oh, by the way: If you do use threading, Python 3.2 and later has an improved implementation of the GIL, which seems like it at least has a good chance of helping. A lot of stuff for threading performance is very dependent on your hardware (number of CPU cores) and the exact tasks you're doing, though - probably best to try several ways and see what works for you.</p>
1
2016-08-29T17:22:33Z
[ "python", "multiprocessing" ]
multiprocessing - calling function with different input files
39,211,309
<p>I have a function which reads in a file, compares a record in that file to a record in another file and depending on a rule, appends a record from the file to one of two lists. </p> <p>I have an empty list for adding matched results to:</p> <pre><code>match = [] </code></pre> <p>I have a list <code>restrictions</code> that I want to compare records in a series of files with.</p> <p>I have a function for reading in the file I wish to see if contains any matches. If there is a match, I append the record to the <code>match</code> list.</p> <pre><code>def link_match(file): links = json.load(file) for link in links: found = False try: for other_link in other_links: if link['data'] == other_link['data']: match.append(link) found = True else: pass else: print "not found" </code></pre> <p>I have numerous files that I wish to compare and I thus wish to use the multiprocessing library. </p> <p>I create a list of file names to act as function arguments:</p> <pre><code>list_files=[] for file in glob.glob("/path/*.json"): list_files.append(file) </code></pre> <p>I then use the <code>map</code> feature to call the function with the different input files:</p> <pre><code>if __name__ == '__main__': pool = multiprocessing.Pool(processes=6) pool.map(link_match,list_files) pool.close() pool.join() </code></pre> <p>CPU use goes through the roof and by adding in a print line to the function loop I can see that matches are being found and the function is behaving correctly. </p> <p>However, the <code>match</code> results list remains empty. What am I doing wrong?</p>
1
2016-08-29T16:53:15Z
39,211,994
<p>When multiprocessing, each subprocess gets its own copy of any global variables in the main module defined before the <code>if __name__ == '__main__':</code> statement. This means that the <code>link_match()</code> function in each one of the processes will be accessing a <em>different</em> <code>match</code> list in your code.</p> <p>One workaround is to use a shared list, which in turn requires a <a href="https://docs.python.org/2/library/multiprocessing.html#multiprocessing.managers.SyncManager" rel="nofollow">SyncManager</a> to synchronize access to the shared resource among the processes (which is created by calling <code>multiprocessing.Manager()</code>). This is then used to create the list to store the results (which I have named <code>matches</code> instead of <code>match</code>) in the code below.</p> <p>I also had to use <code>functools.partial()</code> to create a single argument callable out of the revised <code>link_match</code> function which now takes two arguments, not one (which is the kind of function <code>pool.map()</code> expects).</p> <pre><code>from functools import partial import glob import multiprocessing def link_match(matches, file): # note: added results list argument links = json.load(file) for link in links: try: for other_link in other_links: if link['data'] == other_link['data']: matches.append(link) else: pass else: print "not found" if __name__ == '__main__': manager = multiprocessing.Manager() # create SyncManager matches = manager.list() # create a shared list here link_matches = partial(link_match, matches) # create one arg callable to # pass to pool.map() pool = multiprocessing.Pool(processes=6) list_files = glob.glob("/path/*.json") # only used here pool.map(link_matches, list_files) # apply partial to files list pool.close() pool.join() print(matches) </code></pre>
1
2016-08-29T17:35:38Z
[ "python", "multiprocessing" ]
Custom initializer for get_variable
39,211,332
<p>How can one specify a custom initializer as the third argument for <code>tf.get_variable()</code>? Specifically, I have a variable <code>y</code> which I want to initialize using another (already initialized) variable <code>x</code>. </p> <p>This is easy to do using <code>tf.Variable()</code>, just say, <code>y = tf.Variable(x.initialized_value())</code>. But I couldn't find an analog in the documentation for <code>tf.get_variable()</code>.</p>
2
2016-08-29T16:54:32Z
39,211,524
<p>You can use <code>x.initialized_value()</code> as well. For example:</p> <pre><code>import tensorflow as tf x = tf.Variable(1.0) y = tf.get_variable('y', initializer=x.initialized_value()) with tf.Session() as sess: sess.run(tf.initialize_all_variables()) print(sess.run(y)) # prints 1.0 </code></pre>
1
2016-08-29T17:06:27Z
[ "python", "tensorflow" ]