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
numpy ndarray with more that 32 dimensions
39,325,930
<p>When I try to create an numpy array with more than 32 dimensions I get an error: </p> <pre><code>import numpy as np np.ndarray([1] * 33) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-2-78103e601d91&gt; in &lt;module&gt;() ----&gt; 1 np.ndarray([1] * 33) ValueError: sequence too large; cannot be greater than 32 </code></pre> <p>I found this: <a href="http://stackoverflow.com/questions/35192518/using-numpy-array-with-large-number-of-dimensions">Using numpy.array with large number of dimensions</a> to be related to this question but I want to do this without building my own version.</p> <p>My use case:<br> I am working with Joint Probability Distributions and I am trying to represent each variable on an axis so that computations on it (marginalize, reduce) is a single line operation. For example for a marginalize operation I can simply do a sum over the axis of that variable. For multiplication I can simply do a simple numpy multiplication (after checking if the axes are the same).</p> <p>Is there a possible workaround this?</p>
2
2016-09-05T07:46:13Z
39,334,404
<p>How about maintaining the data in a 1d, and selectively reshaping to focus on a given dimension</p> <p>To illustrate</p> <pre><code>In [252]: x=np.arange(2*3*4*5) </code></pre> <p>With full reshape</p> <pre><code>In [254]: x.reshape(2,3,4,5).sum(2) Out[254]: array([[[ 30, 34, 38, 42, 46], [110, 114, 118, 122, 126], [190, 194, 198, 202, 206]], [[270, 274, 278, 282, 286], [350, 354, 358, 362, 366], [430, 434, 438, 442, 446]]]) </code></pre> <p>With partial reshape - same numbers, different result shape</p> <pre><code>In [255]: x.reshape(6,4,5).sum(1) Out[255]: array([[ 30, 34, 38, 42, 46], [110, 114, 118, 122, 126], [190, 194, 198, 202, 206], [270, 274, 278, 282, 286], [350, 354, 358, 362, 366], [430, 434, 438, 442, 446]]) </code></pre> <p>I'm not going to test this on anything approaching 32+ dimensions. As was noted in the comment, if many of the dimensions are larger than 1 the overall array size will be excessively large.</p>
0
2016-09-05T16:17:41Z
[ "python", "python-3.x", "numpy", "multidimensional-array", "python-2.x" ]
How to copy os image cross IDC with softlayer API?
39,326,006
<p>I have a VM in IDC A, and I have captured this VM as my custom image_A. Now I want to copy image_A to IDC B. Does the softlayer API support this operation?</p>
0
2016-09-05T07:51:41Z
39,355,079
<h2>To copy image across datacenters:</h2> <p>You can use: </p> <ul> <li><a href="http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest_Block_Device_Template_Group/addLocations" rel="nofollow">SoftLayer_Virtual_Guest_Block_Device_Template_Group::addLocations</a></li> </ul> <p>Here an example using REST:</p> <pre><code>https://$user:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Virtual_Guest_Block_Device_Template_Group/$templateGroupId/addLocations Method: Post { "parameters":[ [ { "id":1441195 } ] ] } </code></pre> <p>Replace: <strong>$user</strong>, <strong>$apiKey</strong>, <strong>$templateGroupId</strong> (image) with your own information. <strong>1441195</strong> refers to <strong>Dallas 10</strong> datacenter's identifier (You need to replace this with the datacenter's id, in which you wish to copy your image).</p> <hr> <h2>To view your own block device template groups (images):</h2> <pre><code>https://$user:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Account/getPrivateBlockDeviceTemplateGroups Method: Get </code></pre> <p><strong>Method:</strong> <a href="http://sldn.softlayer.com/reference/services/SoftLayer_Account/getPrivateBlockDeviceTemplateGroups" rel="nofollow">SoftLayer_Account::getPrivateBlockDeviceTemplateGroups</a></p> <hr> <h2>To retrieve information from datacenters:</h2> <pre><code>https://$user:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Location/getDatacenters Method: Get </code></pre> <p><strong>Method:</strong> <a href="http://sldn.softlayer.com/reference/services/SoftLayer_Location/getDatacenters" rel="nofollow">SoftLayer_Location::getDatacenters</a></p> <hr> <blockquote> <p><strong>Updated</strong></p> </blockquote> <h2>To retrieve locations containing a copy of an image</h2> <p>Try this:</p> <pre><code>https://$user:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Virtual_Guest_Block_Device_Template_Group/$templateGroupId/getDatacenters Method: Get </code></pre> <p><strong>Method:</strong> <a href="http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest_Block_Device_Template_Group/getDatacenters" rel="nofollow">SoftLayer_Virtual_Guest_Block_Device_Template_Group::getDatacenters</a></p>
1
2016-09-06T17:52:45Z
[ "python", "api", "softlayer" ]
How to uninstall django-watson library clearly
39,326,089
<p>I want use search library in django</p> <p>So i decide to use django-watson(it tell me easy install, easy use)</p> <p>I command</p> <pre><code>git clone https://github.com/etianen/django-watson.git </code></pre> <p>in my django projects</p> <p>and insert <code>watson</code> in my <code>settings.py. INSTALLED_APPS</code></p> <p>when I command</p> <pre><code>python manage.py migrate </code></pre> <p>django can't find <code>watson</code> so I decide uninstall <code>django-watson</code> and reinstall</p> <p>I command</p> <pre><code>rm -rf django-watson </code></pre> <p>and command <code>migrate</code> (check about when i was uninstall library migrate has no problem)</p> <pre><code>python manage.py migrate </code></pre> <p>suddenly it show me error for me</p> <pre><code>Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/Users/hanminsoo/.pyenv/versions/study_alone/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/Users/hanminsoo/.pyenv/versions/study_alone/lib/python3.5/site-packages/django/core/management/__init__.py", line 327, in execute django.setup() File "/Users/hanminsoo/.pyenv/versions/study_alone/lib/python3.5/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/hanminsoo/.pyenv/versions/study_alone/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/hanminsoo/.pyenv/versions/study_alone/lib/python3.5/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/Users/hanminsoo/.pyenv/versions/3.5.1/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 944, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 956, in _find_and_load_unlocked ImportError: No module named 'django-watson' </code></pre> <p>I think it has installed in env but i can't find where is <code>django-watson</code> </p> <p>I want remove <code>django-watson</code> clearly </p> <p>please somebody help me</p>
1
2016-09-05T07:56:29Z
39,326,161
<p>Make sure you have removed it from INSTALLED_APPS in settings.py and that you have removed all imports related to it inside your project.</p>
1
2016-09-05T08:01:12Z
[ "python", "django", "environment-variables", "uninstall", "django-watson" ]
python3 global name 'SOL_SOCKET is not defined
39,326,220
<p>when I use <code>gevent</code>, I can not use <code>requests</code>, is my useage wrong?</p> <pre><code>from gevent import monkey; monkey.patch_all() import gevent, requests requests.get('https://haofly.net') </code></pre> <p>it raise the error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.3/site-packages/requests/api.py", line 70, in get return request('get', url, params=params, **kwargs) File "/usr/local/lib/python3.3/site-packages/requests/api.py", line 56, in request return session.request(method=method, url=url, **kwargs) File "/usr/local/lib/python3.3/site-packages/requests/sessions.py", line 475, in request resp = self.send(prep, **send_kwargs) File "/usr/local/lib/python3.3/site-packages/requests/sessions.py", line 596, in send r = adapter.send(request, **kwargs) File "/usr/local/lib/python3.3/site-packages/requests/adapters.py", line 423, in send timeout=timeout File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/connectionpool.py", line 595, in urlopen chunked=chunked) File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/connectionpool.py", line 352, in _make_request self._validate_conn(conn) File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/connectionpool.py", line 831, in _validate_conn conn.connect() File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/connection.py", line 289, in connect ssl_version=resolved_ssl_version) File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/util/ssl_.py", line 308, in ssl_wrap_socket return context.wrap_socket(sock, server_hostname=server_hostname) File "/usr/local/lib/python3.3/site-packages/gevent/_ssl3.py", line 60, in wrap_socket _context=self) File "/usr/local/lib/python3.3/site-packages/gevent/_ssl3.py", line 143, in __init__ if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM: NameError: global name 'SOL_SOCKET' is not defined </code></pre> <p>The version of my Python is 3.3</p> <p>If I add <code>ssl=False</code> to <code>monkey.patch_all()</code>, it returns:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.3/site-packages/requests/api.py", line 70, in get return request('get', url, params=params, **kwargs) File "/usr/local/lib/python3.3/site-packages/requests/api.py", line 56, in request return session.request(method=method, url=url, **kwargs) File "/usr/local/lib/python3.3/site-packages/requests/sessions.py", line 475, in request resp = self.send(prep, **send_kwargs) File "/usr/local/lib/python3.3/site-packages/requests/sessions.py", line 596, in send r = adapter.send(request, **kwargs) File "/usr/local/lib/python3.3/site-packages/requests/adapters.py", line 423, in send timeout=timeout File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/connectionpool.py", line 595, in urlopen chunked=chunked) File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/connectionpool.py", line 352, in _make_request self._validate_conn(conn) File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/connectionpool.py", line 831, in _validate_conn conn.connect() File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/connection.py", line 289, in connect ssl_version=resolved_ssl_version) File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/util/ssl_.py", line 308, in ssl_wrap_socket return context.wrap_socket(sock, server_hostname=server_hostname) File "/usr/local/lib/python3.3/ssl.py", line 245, in wrap_socket _context=self) File "/usr/local/lib/python3.3/ssl.py", line 335, in __init__ server_hostname) TypeError: _wrap_socket() argument 1 must be _socket.socket, not SSLSocket </code></pre>
0
2016-09-05T08:04:46Z
39,333,822
<p>Install the Python 3.5 version can fix this problem.</p>
0
2016-09-05T15:34:28Z
[ "python", "python-3.x", "python-3.3" ]
python3 global name 'SOL_SOCKET is not defined
39,326,220
<p>when I use <code>gevent</code>, I can not use <code>requests</code>, is my useage wrong?</p> <pre><code>from gevent import monkey; monkey.patch_all() import gevent, requests requests.get('https://haofly.net') </code></pre> <p>it raise the error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.3/site-packages/requests/api.py", line 70, in get return request('get', url, params=params, **kwargs) File "/usr/local/lib/python3.3/site-packages/requests/api.py", line 56, in request return session.request(method=method, url=url, **kwargs) File "/usr/local/lib/python3.3/site-packages/requests/sessions.py", line 475, in request resp = self.send(prep, **send_kwargs) File "/usr/local/lib/python3.3/site-packages/requests/sessions.py", line 596, in send r = adapter.send(request, **kwargs) File "/usr/local/lib/python3.3/site-packages/requests/adapters.py", line 423, in send timeout=timeout File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/connectionpool.py", line 595, in urlopen chunked=chunked) File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/connectionpool.py", line 352, in _make_request self._validate_conn(conn) File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/connectionpool.py", line 831, in _validate_conn conn.connect() File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/connection.py", line 289, in connect ssl_version=resolved_ssl_version) File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/util/ssl_.py", line 308, in ssl_wrap_socket return context.wrap_socket(sock, server_hostname=server_hostname) File "/usr/local/lib/python3.3/site-packages/gevent/_ssl3.py", line 60, in wrap_socket _context=self) File "/usr/local/lib/python3.3/site-packages/gevent/_ssl3.py", line 143, in __init__ if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM: NameError: global name 'SOL_SOCKET' is not defined </code></pre> <p>The version of my Python is 3.3</p> <p>If I add <code>ssl=False</code> to <code>monkey.patch_all()</code>, it returns:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.3/site-packages/requests/api.py", line 70, in get return request('get', url, params=params, **kwargs) File "/usr/local/lib/python3.3/site-packages/requests/api.py", line 56, in request return session.request(method=method, url=url, **kwargs) File "/usr/local/lib/python3.3/site-packages/requests/sessions.py", line 475, in request resp = self.send(prep, **send_kwargs) File "/usr/local/lib/python3.3/site-packages/requests/sessions.py", line 596, in send r = adapter.send(request, **kwargs) File "/usr/local/lib/python3.3/site-packages/requests/adapters.py", line 423, in send timeout=timeout File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/connectionpool.py", line 595, in urlopen chunked=chunked) File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/connectionpool.py", line 352, in _make_request self._validate_conn(conn) File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/connectionpool.py", line 831, in _validate_conn conn.connect() File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/connection.py", line 289, in connect ssl_version=resolved_ssl_version) File "/usr/local/lib/python3.3/site-packages/requests/packages/urllib3/util/ssl_.py", line 308, in ssl_wrap_socket return context.wrap_socket(sock, server_hostname=server_hostname) File "/usr/local/lib/python3.3/ssl.py", line 245, in wrap_socket _context=self) File "/usr/local/lib/python3.3/ssl.py", line 335, in __init__ server_hostname) TypeError: _wrap_socket() argument 1 must be _socket.socket, not SSLSocket </code></pre>
0
2016-09-05T08:04:46Z
39,335,677
<p>This is really a bug in gevent. It is trying to import a <a href="https://docs.python.org/3/library/socket.html#constants" rel="nofollow"><code>socket</code> constant</a> from the <code>ssl</code> library.</p> <p>That specific constant <em>happens</em> to be imported into the <code>ssl</code> library because that library makes use of it. But it is only there because a fix for <a href="http://bugs.python.org/issue19422" rel="nofollow">issue 19422</a> required it to be imported in to the <code>ssl</code> module. The fix for that bug was included in Python 3.3.4, and you have version 3.3.3 and you thus don't have that specific constant available in the <code>ssl</code> module as well.</p> <p>You could just fix it by adding <code>from socket import SOL_SOCKET, SO_TYPE</code> in <code>gevent/_ssl3.py</code> (located in the <code>/usr/local/lib/python3.3/site-packages</code> directory on your system). Or you can upgrade to Python 3.3.4 or newer. </p> <p>I've filed this as <a href="https://github.com/gevent/gevent/issues/856" rel="nofollow">issue #856</a> with the <code>gevent</code> project.</p>
1
2016-09-05T18:01:45Z
[ "python", "python-3.x", "python-3.3" ]
Append value to list with BeautifulSoup in Python
39,326,246
<pre><code>allname = [] alltel = [] allemail = [] for link in docdetail: name = soup.h1.contents[1] tel = soup.find('a', class_='tel').string email = soup.find('a', class_='email').string allname.append(name) alltel.append(tel) allemail.append(email) </code></pre> <p>I want to append name to allname, tel to alltel, email to allemail after every for loop. But it is possible that the returned value for name/tel/email is empty, then he order of attributes may mess up. I want to assign "NA" to the variable if the returned values are empty. How should I write a code for this precisely?</p>
-1
2016-09-05T08:06:24Z
39,326,331
<p>I recommend you use for loop, so whatever be the number of values it will be appended to array, if there's no value none will be appended : </p> <pre><code>for single_name in name: allname.append(single_name) for single_tel in tel: alltel.append(single_tel) for single_email in email: allemail.append(single_email) </code></pre>
0
2016-09-05T08:12:34Z
[ "python", "beautifulsoup", "append" ]
Append value to list with BeautifulSoup in Python
39,326,246
<pre><code>allname = [] alltel = [] allemail = [] for link in docdetail: name = soup.h1.contents[1] tel = soup.find('a', class_='tel').string email = soup.find('a', class_='email').string allname.append(name) alltel.append(tel) allemail.append(email) </code></pre> <p>I want to append name to allname, tel to alltel, email to allemail after every for loop. But it is possible that the returned value for name/tel/email is empty, then he order of attributes may mess up. I want to assign "NA" to the variable if the returned values are empty. How should I write a code for this precisely?</p>
-1
2016-09-05T08:06:24Z
39,326,735
<p>You can use a <code>try, except</code> to catch your exceptions as follows.</p> <pre><code>allname = [] alltel = [] allemail = [] for link in docdetail: name = soup.h1.contents[1] tel = soup.find('a', class_='tel').string email = soup.find('a', class_='email').string allname.append(name) try: alltel.append(tel) except: alltel.append('N/A') try: allemail.append(email) except: allemail.append('N/A') </code></pre> <p>Then you will have as much data in your fields as there is available. You can also use a <code>try, except</code> for the name if it not certain that it is there. This way will preserve your data in the same index - that is that entry <code>alltel[x]</code>, <code>allemail[x]</code> and <code>allname[x]</code> all refer to the same entity.</p>
0
2016-09-05T08:39:30Z
[ "python", "beautifulsoup", "append" ]
Append value to list with BeautifulSoup in Python
39,326,246
<pre><code>allname = [] alltel = [] allemail = [] for link in docdetail: name = soup.h1.contents[1] tel = soup.find('a', class_='tel').string email = soup.find('a', class_='email').string allname.append(name) alltel.append(tel) allemail.append(email) </code></pre> <p>I want to append name to allname, tel to alltel, email to allemail after every for loop. But it is possible that the returned value for name/tel/email is empty, then he order of attributes may mess up. I want to assign "NA" to the variable if the returned values are empty. How should I write a code for this precisely?</p>
-1
2016-09-05T08:06:24Z
39,326,985
<p>soup.find() returns a None value if there is no match. An attribute error occurs when applying the .string method to a None value. You can catch it this way:</p> <pre><code>allname = [] alltel = [] allemail = [] for link in docdetail: name = soup.h1.contents[1] tel = soup.find('a', class_='tel').string email = soup.find('a', class_='email').string try: allname.append(name) except AttributeError: allname.append(None) try: allemail.append(name) except AttributeError: allemail.append(None) try: allname.append(name) except AttributeError: allname.append(None) </code></pre>
-1
2016-09-05T08:55:25Z
[ "python", "beautifulsoup", "append" ]
Append value to list with BeautifulSoup in Python
39,326,246
<pre><code>allname = [] alltel = [] allemail = [] for link in docdetail: name = soup.h1.contents[1] tel = soup.find('a', class_='tel').string email = soup.find('a', class_='email').string allname.append(name) alltel.append(tel) allemail.append(email) </code></pre> <p>I want to append name to allname, tel to alltel, email to allemail after every for loop. But it is possible that the returned value for name/tel/email is empty, then he order of attributes may mess up. I want to assign "NA" to the variable if the returned values are empty. How should I write a code for this precisely?</p>
-1
2016-09-05T08:06:24Z
39,327,346
<p>You can write your own function to verify the attribute, See below example.</p> <pre><code>def validate_string(attr): if attr.strip() == '': return 'NA' else: return attr.strip() allname = [] alltel = [] allemail = [] for link in docdetail: name = soup.h1.contents[1] tel = soup.find('a', class_='tel').string email = soup.find('a', class_='email').string allname.append(validate_string(name)) alltel.append(validate_string(tel)) allemail.append(validate_string(email)) </code></pre>
0
2016-09-05T09:15:36Z
[ "python", "beautifulsoup", "append" ]
Django aggregate, use of AND/OR operators in when condition
39,326,289
<p>With the following queryset I would like to add and / or condition in the when clause, but I get syntax error. Is it possible to do it in a single queryset or should I split?</p> <pre><code>Game.objects.prefetch_related('schedule').filter(Q(team_home_id=625) | Q(team_away_id=625), schedule__date_time_start__lte=timezone.now()) .aggregate( wins=Sum(Case(When( score_home__gt=F('score_away') &amp; team_home_id=625 | score_away__gt=F('score_home') &amp; team_away_id=625, then=1), default=0, output_field=IntegerField() )), ) </code></pre>
0
2016-09-05T08:09:32Z
39,326,325
<p>According to the <a href="https://docs.djangoproject.com/en/1.10/ref/models/conditional-expressions/#when" rel="nofollow">docs</a> you have to use <code>Q</code> objects when using complex conditions (just like you did in <code>filter</code>). An example:</p> <pre><code>When(Q(name__startswith="John") | Q(name__startswith="Paul"), then='name') </code></pre>
1
2016-09-05T08:11:47Z
[ "python", "django", "aggregate", "django-queryset" ]
AccessToken matching query does not exist
39,326,356
<p>I am creating a an API for registering user based on oauth token. My app has functionality like registration and login, adding restaurant etc. I created user registration part but i get error while login. I want login based on token. </p> <p>I have used django-oauth-toolkit for this and DRF. </p> <p>What i have done is</p> <p><strong>Login based on token</strong></p> <pre><code>class UserCreateAPI(CreateAPIView): serializer_class = UserCreateSerializer queryset = User.objects.all() permission_classes = [AllowAny] class UserLoginAPI(APIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): access_token = AccessToken.objects.get(token=request.POST.get('access_token'), expires__gt=timezone.now()) # error is shown here data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) </code></pre> <p><strong>For creating user with a token</strong></p> <pre><code>class UserCreateSerializer(ModelSerializer): class Meta: model = User extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): username = validated_data['username'] first_name = validated_data['first_name'] last_name = validated_data['last_name'] email = validated_data['email'] password = validated_data['password'] confirm_password = validated_data['password'] user_obj = User( username = username, first_name = first_name, last_name = last_name, email = email ) user_obj.set_password(password) user_obj.save() if user_obj: expire_seconds = oauth2_settings.user_settings['ACCESS_TOKEN_EXPIRE_SECONDS'] scopes = oauth2_settings.user_settings['SCOPES'] application = Application.objects.get(name="Foodie") expires = datetime.now() + timedelta(seconds=expire_seconds) access_token = AccessToken.objects.create(user=user_obj, application=application, token = generate_token(), expires=expires, scope=scopes) return validated_data class UserLoginSerializer(ModelSerializer): # token = CharField(allow_blank=True, read_only=True) username = CharField() class Meta: model = User fields = [ 'username', 'password', # 'token', ] extra_kwargs = {"password": {"write_only": True} } </code></pre> <p>I have excluded fields part and validation part for shortening the code</p> <p>Am i doing the right way?</p>
0
2016-09-05T08:14:22Z
39,326,999
<p>Try to use request.data instead of request.post in order to get the access_token(<a href="http://www.django-rest-framework.org/tutorial/2-requests-and-responses/" rel="nofollow">http://www.django-rest-framework.org/tutorial/2-requests-and-responses/</a>):</p> <pre><code>access_token = AccessToken.objects.get(token=request.data.get('access_token'), expires__gt=timezone.now()) </code></pre> <p>use request.DATA if you are using the Version-2 of DRF. request.data is for version-3</p> <p>============UPDATE======================================== You should implement your own login procedure or modify the existing one; because when user log in, the access_token is not actually sent to the server.</p> <p>The login procedure should look like this :</p> <ol> <li><p>When the user enter his login and password, your app should send a post request to 127.0.0.1:8000/o/token asking for the token. The request should contains the username, password, client_id and client_secret.</p></li> <li><p>the server then receives the credentials and if they are valid it returns the access_token.</p></li> <li><p>The rest of the time you should query the server using that token. </p></li> </ol> <p>But, i'm not sure that it is what you are actually doing.</p>
0
2016-09-05T08:55:52Z
[ "python", "django", "python-3.x", "oauth", "django-rest-framework" ]
Run a module when module name is in a variable
39,326,482
<p>I'm trying to run modules from a directory. A simplified version of my project tree would be:</p> <pre><code>main.py modules/ |_ a/ | |_ a.py | |_ __init__.py |_ b/ | |_ b.py | |_ __init__.py |_ __init__.py </code></pre> <p>Each module in <code>modules/</code> has an empty <code>__init__.py</code> and a <code>run()</code> method that does some stuff in <code>&lt;module-name&gt;.py</code></p> <p>From <code>main.py</code> I would like to load all modules, and then run a module by passing it's name as parameter to a function. For example what I would like to do from <code>main.py</code>:</p> <pre><code>def runModule(module_name): # pseudo-codish from modules import "module_name" "module_name.run()" runModule(a) </code></pre> <p>I've googled a bit but can't seem to find a way this would work. Is this even possible? I'm working with Python3 but would welcome a Python2 solution for guidance even.</p>
0
2016-09-05T08:24:32Z
39,326,532
<p>You can do this with <a href="https://docs.python.org/3/library/importlib.html#importlib.import_module" rel="nofollow"><code>importlib</code></a>.</p> <pre><code>def run_module(module_name): mod = importlib.import_module(module_name) mod.run() </code></pre>
4
2016-09-05T08:27:51Z
[ "python" ]
Sort Multi-index pandas dataframe based on specific indexes
39,326,503
<p>I have the following dataframe:</p> <pre><code> x y a b c a b c kk ii jj kk jj ii kk jj ii ii jj kk jj kk ii kk ii jj 1 .1 .01 2 .5 .2 .4 .6 .01 .3 .5 .7 1. 1. 2 .3 .2 .01 .4 2 .5 .01 2 3 .1 4 .3 .1 .01 .02 2 1 5 .7 .3 2 4.5 2. 3 .01 .1 .4 .1 .5 .2 3 .6 1 3 .2 3 .2 1 1 .5 .2 1 </code></pre> <p>what I want is:</p> <pre><code> x y a b c a b c ii kk jj ii kk jj ii kk jj ii kk jj ii kk jj ii kk jj 1 .01 .1 2 .4 .5 .2 .3 .6 .01 .5 1 .7 .3 2 1. 0.01 .2 .4 2 0.1 .5 2 4 3 .1 .01 .3 .1 .02 1 2 .3 7 5 4.5 2 2 3 .1 .01 .4 .2 .1 .5 1 3 .6 3 3 .2 1 1 .2 .2 .5 1 </code></pre> <p>In fact, the aim is to sort the whole dataframe based on df['1']['x']['a'].</p> <p>I got the new index of sorting, but I do not know how can I reindex df based on new_idx?</p> <pre><code>df_sort = df.loc['1']['x']['a'].sort_values(axis=0) new_idx = df_sort.index --&gt; new_idx = (['ii','kk','jj']) </code></pre>
1
2016-09-05T08:26:05Z
39,326,606
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a>:</p> <pre><code>df = df.reindex(columns=['ii','kk','jj'], level=2) print (df) x y \ a b c a b ii kk jj ii kk jj ii kk jj ii kk jj ii kk 1 0.01 0.10 2.0 0.4 0.5 0.2 0.30 0.6 0.01 0.50 1.0 0.7 0.3 2.0 2 0.01 0.50 2.0 4.0 3.0 0.1 0.01 0.3 0.10 0.02 1.0 2.0 0.3 0.7 3 0.10 0.01 0.4 0.2 0.1 0.5 1.00 3.0 0.60 3.00 3.0 0.2 1.0 1.0 c jj ii kk jj 1 1.0 0.01 0.2 0.4 2 5.0 4.50 2.0 2.0 3 0.2 0.20 0.5 1.0 </code></pre>
2
2016-09-05T08:31:47Z
[ "python", "sorting", "pandas", "dataframe", "multi-index" ]
How do I reshape array of images obtained from .h5 file in python?
39,326,635
<p>I'm new to python and I apologize in advance if my question seems trivial.</p> <p>I have a .h5 file containing pairs of images in greyscale organized in match and non-match groups. For my final purpose I need to consider each pair of images as a single image of 2 channels (where each channel is in fact an image). </p> <p>To use my data I proceed like this:</p> <ol> <li><p>I read the .h5 file putting my data in numpy arrays (I read both groups match and non-match, both with shape (50000,4096)):</p> <pre><code> with h5py.File('supervised_64x64.h5','r') as hf: match = hf.get('/match') non_match = hf.get('/non-match') np_m = np.asarray(match) np_nm = np.asarray(non_match) hf.close() </code></pre></li> <li><p>Then I try to reshape the arrays:</p> <pre><code>reshaped_data_m = np_m.reshape(250000,2,4096) </code></pre></li> </ol> <p>Now, if I reshape the arrays as (250000,2,4096) and then I try to show the corresponding images what I get is actually right. But I need to reshape the arrays as (25000,64,64,2) and when I try to do this I get all black images. </p> <p>Can you help me? Thank you in advance!</p>
3
2016-09-05T08:33:36Z
39,326,779
<p>I bet you need to first transpose your input matrix from <code>250000x2x4096</code> to <code>250000x4096x2</code>, after which you can do the <code>reshape</code>.</p> <p>Luckly, numpy offers the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html" rel="nofollow">transpose</a> function which should do the trick. See <a href="http://stackoverflow.com/questions/23943379/swapping-the-dimensions-of-a-numpy-array">this question</a> for a bigger discussion around transposing.</p> <p>In your particular case, the invocation would be:</p> <pre><code>transposed_data_m = numpy.transpose(np_m, [1, 3, 2]) reshaped_data_m = tranposed_data_m.reshape(250000, 64, 64, 2) </code></pre>
2
2016-09-05T08:42:16Z
[ "python" ]
How can I use request.form in Flask/Python to get a variable textarea name?
39,326,729
<p>In my HTML template, I've added the following <code>&lt;textarea&gt;</code> into a flask for loop:</p> <pre><code>{% for message in messageList %} &lt;form action="/comment/{{ message['id'] }}" method='POST' id='createComment{{ message["id"] }}'&gt; &lt;textarea name='comment{{ message["id"] }}' id='comment{{ message["id"] }}' class='postComment'&gt;&lt;/textarea&gt; &lt;button form='createComment{{ message["id"] }}' formaction="/comment/{{ message['id'] }}" formmethod='post' type='submit' class="ui-button ui-corner-all ui-widget createCommentButton"&gt;Post a comment&lt;/button&gt; &lt;/form&gt; {% endfor %} </code></pre> <p>Using Flask with Python, I'm trying to grab the value of my dynamically generated <code>&lt;textarea&gt;</code></p> <p>(In the example above, if <code>id = 38</code>, name would read as <code>name="comment38"</code>)</p> <p>I'm having trouble properly using request form to get this data, can anyone help? </p> <p>Here's my Python code below which handles the route:</p> <pre><code>@app.route('/comment/&lt;id&gt;', methods=["POST"]) def createComment(id): query = 'INSERT INTO comments (message_id, user_id, comment, created_at, updated_at) VALUES (:message_id, :user_id, :comment, NOW(), NOW());' data = { 'message_id' : id, 'user_id' : session['loggedInUser'], 'comment' : request.form["comment" &amp; id] } mysql.query_db(query, data) flash('Comment has been created!') return redirect('/') </code></pre> <p>Does anyone know how I should appropriately format <code>request.form</code> in this scenario, as demonstrated above? Thank you!</p>
0
2016-09-05T08:39:09Z
39,357,714
<p>Should be <code>request.form["comment" + id]</code></p> <p>Better yet, to avoid a key error:</p> <p><code>request.form.get("comment" + id, 'oops, bad id')</code></p>
1
2016-09-06T20:57:00Z
[ "python", "html", "flask" ]
How can I use request.form in Flask/Python to get a variable textarea name?
39,326,729
<p>In my HTML template, I've added the following <code>&lt;textarea&gt;</code> into a flask for loop:</p> <pre><code>{% for message in messageList %} &lt;form action="/comment/{{ message['id'] }}" method='POST' id='createComment{{ message["id"] }}'&gt; &lt;textarea name='comment{{ message["id"] }}' id='comment{{ message["id"] }}' class='postComment'&gt;&lt;/textarea&gt; &lt;button form='createComment{{ message["id"] }}' formaction="/comment/{{ message['id'] }}" formmethod='post' type='submit' class="ui-button ui-corner-all ui-widget createCommentButton"&gt;Post a comment&lt;/button&gt; &lt;/form&gt; {% endfor %} </code></pre> <p>Using Flask with Python, I'm trying to grab the value of my dynamically generated <code>&lt;textarea&gt;</code></p> <p>(In the example above, if <code>id = 38</code>, name would read as <code>name="comment38"</code>)</p> <p>I'm having trouble properly using request form to get this data, can anyone help? </p> <p>Here's my Python code below which handles the route:</p> <pre><code>@app.route('/comment/&lt;id&gt;', methods=["POST"]) def createComment(id): query = 'INSERT INTO comments (message_id, user_id, comment, created_at, updated_at) VALUES (:message_id, :user_id, :comment, NOW(), NOW());' data = { 'message_id' : id, 'user_id' : session['loggedInUser'], 'comment' : request.form["comment" &amp; id] } mysql.query_db(query, data) flash('Comment has been created!') return redirect('/') </code></pre> <p>Does anyone know how I should appropriately format <code>request.form</code> in this scenario, as demonstrated above? Thank you!</p>
0
2016-09-05T08:39:09Z
39,554,079
<p>I solved this by creating a new variable:</p> <p><code>form = request.form</code></p> <p>and setting my dictionary value to:</p> <p><code>'comment' : form["comment" + id]</code></p> <p>[<em>EDIT</em>] I had sworn I'd tried <code>request.form['comment' + id]</code> as the @GAEfan noted, but I wasn't able to get it to work (I must have had something else going on, as this absolutely is working now!) Answer accepted!</p>
0
2016-09-18T04:23:38Z
[ "python", "html", "flask" ]
How to get the latest file in a folder using python
39,327,032
<p>i need to get the latest file of a folder using python. While using the code:</p> <pre><code>max(files, key = os.path.getctime) </code></pre> <p>I am getting the below error: </p> <blockquote> <p>FileNotFoundError: [WinError 2] The system cannot find the file specified: 'a'</p> </blockquote>
2
2016-09-05T08:58:23Z
39,327,078
<p>Try to sort items by creation time. Example below sorts files in a folder and gets first element which is latest.</p> <pre><code>import glob import os files_path = os.path.join(folder, '*') files = sorted( glob.iglob(files_path), key=os.path.getctime, reverse=True) print files[0] </code></pre>
1
2016-09-05T09:00:52Z
[ "python" ]
How to get the latest file in a folder using python
39,327,032
<p>i need to get the latest file of a folder using python. While using the code:</p> <pre><code>max(files, key = os.path.getctime) </code></pre> <p>I am getting the below error: </p> <blockquote> <p>FileNotFoundError: [WinError 2] The system cannot find the file specified: 'a'</p> </blockquote>
2
2016-09-05T08:58:23Z
39,327,156
<p>What ever assigned to your <code>files</code> variable is incorrect. Use the following code.</p> <pre><code>import glob import os list_of_files = glob.glob('/path/to/folder/*') # * means all if need specific format then *.csv latest_file = max(list_of_files, key=os.path.getctime) print latest_file </code></pre>
0
2016-09-05T09:04:49Z
[ "python" ]
How to get the latest file in a folder using python
39,327,032
<p>i need to get the latest file of a folder using python. While using the code:</p> <pre><code>max(files, key = os.path.getctime) </code></pre> <p>I am getting the below error: </p> <blockquote> <p>FileNotFoundError: [WinError 2] The system cannot find the file specified: 'a'</p> </blockquote>
2
2016-09-05T08:58:23Z
39,327,174
<p>(Edited to improve answer)</p> <p>First define a function get_latest_file</p> <pre><code>def get_latest_file(path, *paths): fullpath = os.path.join(path, paths) ... get_latest_file('example', 'files','randomtext011.*.txt') </code></pre> <p>You may also use a docstring !</p> <pre><code>def get_latest_file(path, *paths): """Returns the name of the latest (most recent) file of the joined path(s)""" fullpath = os.path.join(path, *paths) </code></pre> <p><strong>If you use Python 3</strong>, you can use <a href="https://docs.python.org/3/library/glob.html?highlight=glob.iglob#glob.iglob" rel="nofollow">iglob</a> instead.</p> <p><strong>Complete code to return the name of latest file:</strong></p> <pre><code>def get_latest_file(path, *paths): """Returns the name of the latest (most recent) file of the joined path(s)""" fullpath = os.path.join(path, *paths) files = glob.glob(fullpath) # You may use iglob in Python3 if not files: # I prefer using the negation return None # because it behaves like a shortcut latest_file = max(files, key=os.path.getctime) _, filename = os.path.split(latest_file) return filename </code></pre>
0
2016-09-05T09:05:39Z
[ "python" ]
How to get the latest file in a folder using python
39,327,032
<p>i need to get the latest file of a folder using python. While using the code:</p> <pre><code>max(files, key = os.path.getctime) </code></pre> <p>I am getting the below error: </p> <blockquote> <p>FileNotFoundError: [WinError 2] The system cannot find the file specified: 'a'</p> </blockquote>
2
2016-09-05T08:58:23Z
39,327,252
<pre><code>max(files, key = os.path.getctime) </code></pre> <p>is quite incomplete code. What is <code>files</code>? It probably is a list of file names, coming out of <code>os.listdir()</code>.</p> <p>But this list lists only the filename parts (a. k. a. "basenames"), because their path is common. In order to use it correctly, you have to combine it with the path leading to it (and used to obtain it).</p> <p>Such as (untested):</p> <pre><code>def newest(path): files = os.listdir(files) paths = [os.path.join(path, f) for f in files] return max(paths, key=os.path.getctime) </code></pre>
0
2016-09-05T09:09:55Z
[ "python" ]
Combining Characters using lambda in python
39,327,068
<p>I want to result using 'str += ' style in the lambda function </p> <p>example (with error) : </p> <pre><code>t=lambda text text : [c for c in text str += c.upper()] t(['h','e','l','l','o']) </code></pre> <p>I expect to result as :</p> <pre><code>HELLO </code></pre> <p>How can i fix above lambda function with state variable like 'str +=' style</p> <p>if 'str +=' style not possible, please explain in detail why the impossible. Do not just Short-Answer that wrong. </p>
-1
2016-09-05T09:00:24Z
39,327,112
<p>I think you mean this:</p> <pre><code>&gt;&gt;&gt; t = lambda text: ''.join(text).upper() &gt;&gt;&gt; t(['h','e','l','l','o']) 'HELLO' </code></pre> <p>Documentation: <a href="https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions" rel="nofollow">Lambda Expressions</a></p>
4
2016-09-05T09:02:32Z
[ "python", "lambda" ]
No visible text() when using matplotlib.pyplot
39,327,258
<p>matplotlib==1.5.2 pylab==0.1.3</p> <p>I am trying to reproduce a graph from the course <a href="http://cs224d.stanford.edu/syllabus.html" rel="nofollow">"CS224d Deep Learning for NLP"</a>, <a href="http://cs224d.stanford.edu/lectures/CS224d-Lecture2.pdf" rel="nofollow">Lecture 2</a>.</p> <p>It should look the following way:</p> <p><a href="http://i.stack.imgur.com/ykswK.png" rel="nofollow"><img src="http://i.stack.imgur.com/ykswK.png" alt="enter image description here"></a></p> <p>I am using the following code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt la = np.linalg words = ['I', 'like', 'enjoy', 'deep', 'learning', 'NLP', 'flying', '.'] X = np.array([[0,2,1,0,0,0,0,0], [2,0,0,1,0,1,0,0], [1,0,0,0,0,0,1,0], [0,1,0,0,1,0,0,0], [0,0,0,1,0,0,0,1], [0,1,0,0,0,0,0,1], [0,0,1,0,0,0,0,1], [0,0,0,0,1,1,1,0]]) U, s, Vh = la.svd(X, full_matrices=False) for i in xrange(len(words)): plt.text(U[i,0], U[i,1], words[i]) plt.autoscale() plt.show() </code></pre> <p>However, the words don't appear on the graph.</p> <p>If I remove the instruction </p> <pre><code>plt.autoscale() </code></pre> <ul> <li>I can see some text plotted in the corner, but the axis range is wrong.</li> </ul> <p>If I use this instruction, then I see no text at all, even if I call <em>text()</em> once again.</p> <p>I have seen solutions with using subplots and setting the exact ranges for <em>x</em> and <em>y</em> axis, but this seems to be unnecessarily complex.</p> <p>What else can I try? </p>
1
2016-09-05T09:10:16Z
39,327,699
<p>It shows the words when you set axis limits to show the text as per this answer below. </p> <pre><code>import numpy as np import matplotlib.pyplot as plt la = np.linalg words = ['I', 'like', 'enjoy', 'deep', 'learning', 'NLP', 'flying', '.'] X = np.array([[0,2,1,0,0,0,0,0], [2,0,0,1,0,1,0,0], [1,0,0,0,0,0,1,0], [0,1,0,0,1,0,0,0], [0,0,0,1,0,0,0,1], [0,1,0,0,0,0,0,1], [0,0,1,0,0,0,0,1], [0,0,0,0,1,1,1,0]]) U, s, Vh = la.svd(X, full_matrices=False) fig, ax = plt.subplots() for i in xrange(len(words)): ax.text(U[i,0], U[i,1], words[i]) ax.set_xlim([-0.8, 0.2]) ax.set_ylim([-0.8, 0.8]) plt.show() </code></pre>
1
2016-09-05T09:35:53Z
[ "python", "matplotlib" ]
Python PIL: How can set to a png image the background to white?
39,327,265
<p>I have a png image with transparent background and I want to resize it to another image, but with white background instead of transparent one. How can I do that with PIL?</p> <p><strong>Here is my code:</strong></p> <pre><code>basewidth = 200 img = Image.open("old.png") wpercent = (basewidth/float(img.size[0])) hsize = int((float(img.size[1]) * float(wpercent))) img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)hsize = int((float(img.size[1]) * float(wpercent))) img.save("new.png") </code></pre> <p><strong>Update</strong></p> <pre><code>import numpy as np import PIL from PIL import Image basewidth = 200 img = Image.open("old.png") wpercent = (basewidth/float(img.size[0])) hsize = int((float(img.size[1]) * float(wpercent))) data = np.array(img) alpha1 = 0 # Original value r2, g2, b2, alpha2 = 255, 255, 255,255 # Value that we want to replace it with red, green, blue,alpha = data[:,:,0], data[:,:,1], data[:,:,2], data[:,:,3] mask = (alpha==alpha1) data[:,:,:4][mask] = [r2, g2, b2, alpha2] img = Image.fromarray(data) img = img.resize((basewidth,hsize), PIL.Image.ANTIALIAS) img.save('new.png') </code></pre> <p>Here is the code provided by @khakishoiab and @Chachmu Thanks guys!</p>
1
2016-09-05T09:10:37Z
39,327,366
<pre><code> import Image f = Image.open('old.png') from resizeimage import resizeimage alpha1 = 0 # Original value r2, g2, b2, alpha2 = 255, 255, 255,255 # Value that we want to replace it with red, green, blue,alpha = data[:,:,0], data[:,:,1], data[:,:,2], data[:,:,3] mask = (alpha==alpha1) data[:,:,:3][mask] = [r2, g2, b2, alpha2] data = np.array(f) f = Image.fromarray(data) f = f.resize((basewidth,hsize), PIL.Image.ANTIALIAS) f.save('modified.png', image.format) </code></pre>
0
2016-09-05T09:16:42Z
[ "python", "python-imaging-library" ]
Python PIL: How can set to a png image the background to white?
39,327,265
<p>I have a png image with transparent background and I want to resize it to another image, but with white background instead of transparent one. How can I do that with PIL?</p> <p><strong>Here is my code:</strong></p> <pre><code>basewidth = 200 img = Image.open("old.png") wpercent = (basewidth/float(img.size[0])) hsize = int((float(img.size[1]) * float(wpercent))) img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)hsize = int((float(img.size[1]) * float(wpercent))) img.save("new.png") </code></pre> <p><strong>Update</strong></p> <pre><code>import numpy as np import PIL from PIL import Image basewidth = 200 img = Image.open("old.png") wpercent = (basewidth/float(img.size[0])) hsize = int((float(img.size[1]) * float(wpercent))) data = np.array(img) alpha1 = 0 # Original value r2, g2, b2, alpha2 = 255, 255, 255,255 # Value that we want to replace it with red, green, blue,alpha = data[:,:,0], data[:,:,1], data[:,:,2], data[:,:,3] mask = (alpha==alpha1) data[:,:,:4][mask] = [r2, g2, b2, alpha2] img = Image.fromarray(data) img = img.resize((basewidth,hsize), PIL.Image.ANTIALIAS) img.save('new.png') </code></pre> <p>Here is the code provided by @khakishoiab and @Chachmu Thanks guys!</p>
1
2016-09-05T09:10:37Z
39,327,595
<p>You can check whether the alpha channel is set to less than 255 on each pixel (which means that it is not opaque) and then set it to white and opaque.</p> <p>It might not be an ideal solution if you have transparency in other parts of your image, besides the background.</p> <pre><code>... pixels = img.load() for y in xrange(img.size[1]): for x in xrange(img.size[0]): if pixels[x,y][3] &lt; 255: # check alpha pixels[x,y] = (255, 255, 255, 255) img.save("new.png") </code></pre>
0
2016-09-05T09:29:29Z
[ "python", "python-imaging-library" ]
Python socket select.select. Using list of objects instead of connections
39,327,333
<p>Typically using <code>select.select()</code> will require a list of connection objects to work like this:</p> <p><code>read, write, error = select(self.all_connections, [], [], 0.1)</code></p> <p>Say I have the below object:</p> <pre><code>class remoteDevice(object) def __init___(self, connection): self.connection = connection </code></pre> <p>I will create a list of remoteDevices before using select after accepting the connections and append them to a list:</p> <pre><code>conn = socket.accept() newDevice = remoteDevice(conn) all_devices.append(newDevice) </code></pre> <p>Now <code>all_devices</code> will be alist of multiple devices, and their connection object is given to each remote device.</p> <p>Is there a way I can pass in <code>all_devices</code> into the select statement to iterate through the <code>connection</code> property of each <code>remoteDevice</code> object? Will I have to store the connection objects seperately just to use <code>select.select()</code>?</p>
0
2016-09-05T09:14:53Z
39,328,021
<p>According to the <a href="https://docs.python.org/3/library/select.html#select.select" rel="nofollow"><code>select.select()</code></a> documentation you can supply a sequence of objects that have a <code>fileno()</code> method. You can easily add that method to your class:</p> <pre><code>class RemoteDevice(object): def __init__(self, connection): self.connection = connection def fileno(self): return self.connection[0].fileno() </code></pre> <p>The <code>fileno()</code> method simply returns the file descriptor of the connection's socket object. Since you instantiate <code>RemoteDevice</code> with the return value of <code>socket.accept()</code>, this a tuple in which the first item is a <code>socket</code> object.</p>
3
2016-09-05T09:54:26Z
[ "python", "sockets", "python-3.x" ]
Is there a delay moving between libraries in Python?
39,327,361
<p>So recently I decided to write a program to draw the mandelbrot set using turtle, and it works very well, except for one thing; it's quite slow, and it slows down as it draws. The way it draws is, if I remember correctly, as follows:</p> <pre><code>def drawpoint(x,y,colour): t.color(colour) t.setpos(x,y) t.down() t.forward(1) t.up() </code></pre> <p>and the program in general calculates the point (using <code>math</code> (specifically its trigonometry) and its colour and then draws it.</p> <p>I can't work out why it's so slow, because it's not exactly an astonishing set of calculations. I'm fairly sure it's to do with <code>turtle</code>, and I was wondering if:</p> <p>a) Python is slowed down by moving between <code>math</code> and <code>turtle</code> <br /> b) Turtle slows down as you draw more points <br /> c) Something else entirely <br /></p> <p>Is it any of these, and if so, how can I speed it up?</p>
1
2016-09-05T09:16:15Z
40,081,059
<p>Since you didn't give a clock value to <strong><em>quite slow</em></strong>, I have to make assumptions. (And I don't disagree with PM 2Ring that turtle.py may not be your best choice for this purpose.) I wrote a mandelbrot program, using generic turtle operations, which took nearly an hour to draw the 320 x 240 image below. However, with a few turtle optimizations, I was able to get that down to just over a minute. And there may be room to do better (see further below.) Specific optimizations:</p> <ul> <li><p>Maximize the turtle drawing speed via <code>turtle.speed("fastest")</code></p></li> <li><p>Use <code>screen.tracer(0, 0)</code> and <code>screen.update()</code> to do the bulk of the drawing offscreen. In my code below, I update on each vertical slice of the image so you can see still its progress but don't delay for each individual pixel to be drawn.</p></li> <li><p>I found <em>stamping</em> my pixels to be more efficient than your <code>forward(1)</code> approach. This isn't intuitive as stamping keeps track of the stamps and does a bunch of polygon operations but it still times out better. This many be because it avoids the pen up and down operations.</p></li> <li><p>Make the turtle invisible either from creation using <code>turtle = Turtle(visible=False)</code> or later via <code>turtle.hideturtle()</code>. No need to waste time drawing the turtle itself for every pixel.</p></li> <li><p>Turn off <em>undo</em>. (In the case of stamping, you can't turn it off due to a bug in turtle.py, but) in general, if you're drawing lots and don't plan to undo you, can <code>turtle.setundobuffer(None)</code> to turn off this feature and not store every operation in a buffer.</p></li> <li><p>As with any speed optimized program, avoid doing anything at runtime that you can do ahead -- waste lots of space doing so if needed. Avoid doing things at runtime that are redundant. In my example below, I tried to minimize time spent on setting colors by precomputing the color values and avoiding <code>turtle.color(...)</code> if the pen color is already set to the correct color.</p></li> </ul> <p><a href="https://i.stack.imgur.com/npFgc.png" rel="nofollow"><img src="https://i.stack.imgur.com/npFgc.png" alt="enter image description here"></a></p> <pre><code>from turtle import Turtle, Screen COORDINATES = (-2.0, -1.0, 1.0, 1.0) WIDTH, HEIGHT = 320, 240 colors = {i: ((i &amp; 0b1111) &lt;&lt; 4, (i &amp; 0b111) &lt;&lt; 5, (i &amp; 0b11111) &lt;&lt; 3) for i in range(2 ** 5)} def mandelbrot(turtle, minimum_x, minimum_y, maximum_x, maximum_y, iterations, width, height): step_x, step_y = (maximum_x - minimum_x) / width, (maximum_y - minimum_y) / height real = minimum_x current_color = 0 while real &lt; maximum_x: imaginary = minimum_y while imaginary &lt; maximum_y: color = 0 c, z = complex(real, imaginary), 0j for i in range(iterations): if abs(z) &gt;= 4.0: color = i &amp; 31 break z = z * z + c if color != current_color: turtle.color(colors[color]) current_color = color turtle.setpos(real, imaginary) turtle.stamp() imaginary += step_y screen.update() real += step_x screen = Screen() screen.setup(WIDTH, HEIGHT) screen.setworldcoordinates(*COORDINATES) screen.colormode(255) screen.tracer(0, 0) turtle = Turtle(visible=False) turtle.speed("fastest") turtle.setundobuffer(1) # unfortunately setundobuffer(None|0) broken for turtle.stamp() turtle.begin_poly() # Yes, this is an empty polygon but produces a dot -- I don't know if this works on all platforms turtle.end_poly() screen.register_shape("pixel", turtle.get_poly()) turtle.shape("pixel") turtle.up() mandelbrot(turtle, *COORDINATES, 31, WIDTH, HEIGHT) screen.exitonclick() </code></pre> <p>An unresolved issue is, as you noted, it slows down as draws. It only takes 15 seconds to draw the first 2/3rds of the above image, the last third takes a minute. I tried to find a reason but nothing so far. An interesting twist is that the last 5% of the drawing speeds back up.</p>
0
2016-10-17T07:51:32Z
[ "python", "turtle-graphics" ]
Kivy canvas - fast drawing - polylines
39,327,575
<p>Tell me please, if drawing in Kivy Canvas fast, I get very acute, polylines figure, but if drawing very slow, then I get smooth lines.</p> <pre><code> ... def on_touch_down(self, touch): if Widget.on_touch_down(self, touch): return True print(touch.x, touch.y) with self.canvas.before: Color(*get_color_from_hex('#0080FF80')) Line(circle=(touch.x, touch.y, 2), width=2) touch.ud['current_line'] = Line(points=(touch.x, touch.y), width=2) def on_touch_move(self, touch): if 'current_line' in touch.ud: touch.ud['current_line'].points += (touch.x, touch.y) ... </code></pre> <p>This is my example:</p> <p><img src="http://i.stack.imgur.com/eAtKq.png" alt="this is my example!"></p> <p>Who knows how could I fixed it ? Could I drawing fast and smooth in Kivy ?</p>
1
2016-09-05T09:28:25Z
39,333,864
<p>i dont know why the lines dont look smooth when you draw fast in kivy, can you please test it on a different devices.</p>
0
2016-09-05T15:37:00Z
[ "android", "python", "canvas", "drawing", "kivy" ]
Kivy canvas - fast drawing - polylines
39,327,575
<p>Tell me please, if drawing in Kivy Canvas fast, I get very acute, polylines figure, but if drawing very slow, then I get smooth lines.</p> <pre><code> ... def on_touch_down(self, touch): if Widget.on_touch_down(self, touch): return True print(touch.x, touch.y) with self.canvas.before: Color(*get_color_from_hex('#0080FF80')) Line(circle=(touch.x, touch.y, 2), width=2) touch.ud['current_line'] = Line(points=(touch.x, touch.y), width=2) def on_touch_move(self, touch): if 'current_line' in touch.ud: touch.ud['current_line'].points += (touch.x, touch.y) ... </code></pre> <p>This is my example:</p> <p><img src="http://i.stack.imgur.com/eAtKq.png" alt="this is my example!"></p> <p>Who knows how could I fixed it ? Could I drawing fast and smooth in Kivy ?</p>
1
2016-09-05T09:28:25Z
39,340,288
<p>Actually I tested your code and couldn't produce the issue you are having. I mean it doesn't matter if I draw fast or slow in Kivy. Half of these 'e's I drew fast and half slow but no difference in output. I suggest you try <a href="https://kivy.org/docs/tutorials/firstwidget.html" rel="nofollow">https://kivy.org/docs/tutorials/firstwidget.html</a> . If this example's drawing output is acute while drawing fast, then probably there is something wrong with your environment because it works well in mine. elif it's smooth in fast drawing, then your project in hand must be having issues.</p> <p><a href="http://i.stack.imgur.com/J5d04.png" rel="nofollow"><img src="http://i.stack.imgur.com/J5d04.png" alt=""></a></p>
0
2016-09-06T03:39:20Z
[ "android", "python", "canvas", "drawing", "kivy" ]
Python: Problems in calling the function from the while loop
39,327,676
<p>I have a while loop which calls the function mainrt() on each iteration.</p> <pre><code>if __name__ == "__main__": inp = sys.stdin.read() inpList = inp.split('\n') inpList.pop() for n in inpList: i = 0 p = 0 n = int (n) while True: i += 1 p = n*i if n == 0: print "INSOMNIA" break else: res = True res = mainrt(p) if res == False: print p break </code></pre> <p>And the mainrt()</p> <pre><code>def mainrt(n): #print n while True: rem = n % 10 if rem in diMon: pass else: diMon.insert(rem,rem) if len(diMon) == 10: return False break n = n/10 if n == 0: return True break else: continue </code></pre> <p>The problem is as i take input from stdin.read() the first line of the input processed properly by the function, but the second line of the input get printed as it is. It is not being processed by the function example</p> <pre><code>INPUT 3 5 OUTPUT SHOLD BE 30 90 But instead I get 30 5 </code></pre> <p>Why the function not processing the input the second time??? There is no run time error so far.</p>
0
2016-09-05T09:34:42Z
39,327,915
<p>In your <code>mainrt</code> function I do not see that you declare <code>diMon</code> list, so it looks like it is a global variable and you do not clean that list. That mean your <code>mainrt</code> return <code>False</code> at the first check of <code>if len(diMon) == 10:</code> for the second input. You should declare <code>diMon</code> at the beginning od <code>mainrt</code> function or clear it at the end of while loop body.</p> <p><strong>EDIT:</strong> Now I checked your code one more time and I suggest you to declare diMon at the beginning of <code>for</code> loop</p> <pre><code>for n in inpList: diMon = [] i = 0 p = 0 n = int (n) </code></pre>
1
2016-09-05T09:48:17Z
[ "python", "python-2.7" ]
IndexError: string index out of range (enumerate)
39,327,737
<p>Okay so I have no idea what the problem is here. Everything I've read basically addresses the range not ending, thus the error, but that doesn't make sense to me since this is a fixed loop. </p> <p>I'm simply trying to take a string, and throw each letter into a list one at a time. What am I missing?</p> <pre><code>&gt;&gt;&gt; name = "Chris" &gt;&gt;&gt; &gt;&gt;&gt; my_list = [] &gt;&gt;&gt; &gt;&gt;&gt; for key, value in enumerate(name): ... my_list.append(value[key]) ... print (my_list) ... </code></pre> <p>The error I'm receiving:</p> <pre><code>['C'] Traceback (most recent call last): File "&lt;pyshell#7&gt;", line 2, in &lt;module&gt; my_list.append(value[key]) IndexError: string index out of range </code></pre>
-1
2016-09-05T09:37:51Z
39,327,816
<p>What you are missing is that <code>value</code> is a single element string. Indexing at positions <code>!= 0</code> will result in an <code>IndexError</code>; during your first iteration that's what happens.</p> <p>If you want to create it with your for loop, just append the value immediately:</p> <pre><code>for key, value in enumerate(name): my_list.append(value) </code></pre> <p>Of course, <code>enumerate</code> is by no means required here, this can be simplified by calling <code>list</code> and supplying the string in question; Python will then create a list containing the contents of the string for you:</p> <pre><code>my_list = list(name) </code></pre> <p>For <code>Python 3.x</code> you can also unpack in a <code>list</code> literal with <code>*</code>:</p> <pre><code>my_list = [*name] </code></pre> <p>In all supplied snippets, the result of the operations is <code>['C', 'h', 'r', 'i', 's']</code> as required.</p>
2
2016-09-05T09:42:19Z
[ "python", "python-3.x" ]
IndexError: string index out of range (enumerate)
39,327,737
<p>Okay so I have no idea what the problem is here. Everything I've read basically addresses the range not ending, thus the error, but that doesn't make sense to me since this is a fixed loop. </p> <p>I'm simply trying to take a string, and throw each letter into a list one at a time. What am I missing?</p> <pre><code>&gt;&gt;&gt; name = "Chris" &gt;&gt;&gt; &gt;&gt;&gt; my_list = [] &gt;&gt;&gt; &gt;&gt;&gt; for key, value in enumerate(name): ... my_list.append(value[key]) ... print (my_list) ... </code></pre> <p>The error I'm receiving:</p> <pre><code>['C'] Traceback (most recent call last): File "&lt;pyshell#7&gt;", line 2, in &lt;module&gt; my_list.append(value[key]) IndexError: string index out of range </code></pre>
-1
2016-09-05T09:37:51Z
39,327,823
<pre><code>name = 'Chris' my_list = list(name) print(my_list) </code></pre> <p>Input: ['C', 'h', 'r', 'i', 's']</p> <p>For one in each time:</p> <pre><code>for letter in name: print(letter) </code></pre>
0
2016-09-05T09:42:40Z
[ "python", "python-3.x" ]
IndexError: string index out of range (enumerate)
39,327,737
<p>Okay so I have no idea what the problem is here. Everything I've read basically addresses the range not ending, thus the error, but that doesn't make sense to me since this is a fixed loop. </p> <p>I'm simply trying to take a string, and throw each letter into a list one at a time. What am I missing?</p> <pre><code>&gt;&gt;&gt; name = "Chris" &gt;&gt;&gt; &gt;&gt;&gt; my_list = [] &gt;&gt;&gt; &gt;&gt;&gt; for key, value in enumerate(name): ... my_list.append(value[key]) ... print (my_list) ... </code></pre> <p>The error I'm receiving:</p> <pre><code>['C'] Traceback (most recent call last): File "&lt;pyshell#7&gt;", line 2, in &lt;module&gt; my_list.append(value[key]) IndexError: string index out of range </code></pre>
-1
2016-09-05T09:37:51Z
39,327,854
<p>You are enumerating over a string ("Chris") which means that key and value will hold the following values during the iteration:</p> <pre><code>0 "C" 1 "h" 2 "r" 3 "i" 4 "s" </code></pre> <p>value[key] in the first iteration is ok, it returns 'C'. </p> <p>In the second iteration, the index 1 is out of range for string "h".</p> <p>What you probably want to do is this:</p> <pre><code>for i, value in enumerate(name): my_list.append(value) print (my_list) </code></pre>
0
2016-09-05T09:44:40Z
[ "python", "python-3.x" ]
IndexError: string index out of range (enumerate)
39,327,737
<p>Okay so I have no idea what the problem is here. Everything I've read basically addresses the range not ending, thus the error, but that doesn't make sense to me since this is a fixed loop. </p> <p>I'm simply trying to take a string, and throw each letter into a list one at a time. What am I missing?</p> <pre><code>&gt;&gt;&gt; name = "Chris" &gt;&gt;&gt; &gt;&gt;&gt; my_list = [] &gt;&gt;&gt; &gt;&gt;&gt; for key, value in enumerate(name): ... my_list.append(value[key]) ... print (my_list) ... </code></pre> <p>The error I'm receiving:</p> <pre><code>['C'] Traceback (most recent call last): File "&lt;pyshell#7&gt;", line 2, in &lt;module&gt; my_list.append(value[key]) IndexError: string index out of range </code></pre>
-1
2016-09-05T09:37:51Z
39,327,861
<p>change my_list.append(value[key]) to my_list.append(value) in your code</p>
0
2016-09-05T09:45:21Z
[ "python", "python-3.x" ]
IndexError: string index out of range (enumerate)
39,327,737
<p>Okay so I have no idea what the problem is here. Everything I've read basically addresses the range not ending, thus the error, but that doesn't make sense to me since this is a fixed loop. </p> <p>I'm simply trying to take a string, and throw each letter into a list one at a time. What am I missing?</p> <pre><code>&gt;&gt;&gt; name = "Chris" &gt;&gt;&gt; &gt;&gt;&gt; my_list = [] &gt;&gt;&gt; &gt;&gt;&gt; for key, value in enumerate(name): ... my_list.append(value[key]) ... print (my_list) ... </code></pre> <p>The error I'm receiving:</p> <pre><code>['C'] Traceback (most recent call last): File "&lt;pyshell#7&gt;", line 2, in &lt;module&gt; my_list.append(value[key]) IndexError: string index out of range </code></pre>
-1
2016-09-05T09:37:51Z
39,327,964
<p>An alternative way, to reach your goal:</p> <pre><code>&gt;&gt;&gt;name ="Chris" &gt;&gt;&gt;list(name) ['C', 'h', 'r', 'i', 's'] </code></pre> <p>For your example: When iterating through a string in python, no enumeration is required.</p> <pre><code>&gt;&gt;&gt;name = "Chris" &gt;&gt;&gt;my_list = [] &gt;&gt;&gt;for i in name: ... my_list.append(i) &gt;&gt;&gt;my_list ['C', 'h', 'r', 'i', 's'] </code></pre>
0
2016-09-05T09:51:03Z
[ "python", "python-3.x" ]
I have two .py files. How can I get multi-lined output of one program into tkinter text of another program's GUI?
39,327,767
<p>GUI consists one Run Button which should run the first program as many times user wants &amp; display output in tkinter text.</p> <p>My code(2nd .py file):</p> <pre><code>from tkinter import* from tkinter import ttk import Random Game root = Tk() root.title("Random Game 1.0") quote = "Long \nRandom \nText \nGenerated \nBy \nRandom Function \nAnd \nControl Structures" frame = Frame(root) labelText = StringVar() label = Label(frame, textvariable=labelText).pack() button = Button(frame, text="Click to Run").pack() labelText.set("Random Game 1.0") Label(root, text ="") T = Text(root) frame.pack() T.pack() T.insert(END, quote) root.mainloop() </code></pre> <p>I want Output of 1st program which is random every time in "tkinter text of another (2nd program) instead of quote lines mentioned in above code.</p>
2
2016-09-05T09:39:15Z
39,337,367
<p>Output first program to txt file.</p> <p>Read from that txt file into the tkinter GUI by checking when it was last modified so as to avoid mutex issues.</p> <p>Therefore:</p> <pre><code># Prog 1: file = open("log.txt", "w") # code that writes there # Prog 2: file = open("log.txt", "r") # use data to show in the tkinter with its mainloop for example # in mainloop()... # ..... if other_prog_has_written_something_new : data = file.readlines() useDataInGUI(data) </code></pre>
1
2016-09-05T20:34:53Z
[ "python", "python-2.7", "python-3.x", "user-interface", "tkinter" ]
How to actively avoid duplicate rows from the angle of the code not database?
39,327,925
<p>I get a table called <code>tb_user_portrait</code> which saves customers' head portrait, its schema looks quite simple,</p> <pre><code>CREATE TABLE `tb_user_portrait` ( id BIGINT NOT NULL AUTO_INCREMENT COMMENT 'primary key', user_id BIGINT NOT NULL DEFAULT 0 COMMENT 'custormer id', portrait_hash CHAR(255) NOT NULL DEFAULT '' COMMENT 'portrait image hash', is_valid TINYINT NOT NULL DEFAULT 1 COMMENT 'validation flag of this row', primary key(id) ) </code></pre> <p>I don't set any unique key, because customers may upload head portraits several times. However each user is supposed to have only one valid portrait(i.e. each of them could have only one <code>is_valid=1</code> record).</p> <p>My code to deal with the uploading operation is simple too, </p> <pre><code>def upload(user_id, portrait_hash, is_valid=1): # find the last is_valid=1 records, and set invalid portrait = DBSession().query(UserPortrait).\ filter(UserPortrait.user_id == user_id).\ filter(UserPortrait.is_valid == 1).\ scalar() if portrait: portrait.is_valid = 0 DBSession().add(portrait) # create new valid portrait and save it to db new_portrait = UserPortrait( user_id=user_id, portrait_hash=portrait_hash, is_valid=is_valid) DBSession().add(new_portrait) DBSession().commit() </code></pre> <p>Although I firstly find out the valid record and set invalid, I always come across <code>MultipleRowsFound</code> and there're more than one records(<code>is_valid=1</code>) in the database.</p> <p>By the way, I use <strong>SQLAlchemy</strong> and turn the <code>session.autoflush</code> on.</p> <p>I'm wondering why it happens? Is there any best practice to avoid this?</p>
1
2016-09-05T09:48:48Z
39,328,089
<p>From SQLAlchemy:</p> <blockquote> <p>autoflush – When True, all query operations will issue a flush() call to this Session before proceeding. This is a convenience feature so that flush() need not be called repeatedly in order for database queries to retrieve results. It’s typical that autoflush is used in conjunction with autocommit=False. In this scenario, explicit calls to flush() are rarely needed; you usually only need to call commit() (which flushes) to finalize changes.</p> </blockquote> <p>So basically you don't commit your change to database, that's why it doesn't work and you have more than one record with <code>is_invalid = 1</code>.</p> <p>Instead of turning on <code>session.autoflush</code> try to do it manually, so here:</p> <pre><code>... if portrait: portrait.is_valid = 0 DBSession().add(portrait) DBSession().flush() # &lt;-- here new_portrait = UserPortrait( user_id=user_id, portrait_hash=portrait_hash, is_valid=is_valid) ... </code></pre> <p>And if it still doesn't work, instead of:</p> <pre><code> DBSession().flush() </code></pre> <p>just use:</p> <pre><code> DBSession().commit() </code></pre>
0
2016-09-05T09:58:00Z
[ "python", "mysql", "python-2.7", "sqlalchemy" ]
Python: listing variables from object
39,327,930
<p>So basically I need help with laziness.</p> <p>Is it possible in python to take an object, and then list off all it's variables</p> <p>For example</p> <pre><code>class some_object: def __init__(self): self.Name = None self.UUID = None </code></pre> <p>then call a magic function that lists all the variable names in the object</p> <p>and maybe return something that looks close to this:</p> <pre><code>[some_object.Name, some_object.UUID] </code></pre> <p>Keep in mind I DON'T NEED the values attached to the object, but rather the name of the variable, such as Name and UUID</p> <p>if anyone could help me, that'd be awesome.</p> <p>Edit: Thanks for everyone answering my question, the magic function I needed was vars (). I really appreciate everyone effort and input on the problem</p>
-3
2016-09-05T09:49:09Z
39,328,282
<p>You can use vars():</p> <pre><code>class about_me: def __init__(self): self.name = "Lyend Victorian" self.age = "25" self.height = "180" me = about_me() &gt;&gt;&gt; vars(me) {'age': '25', 'name': 'Lyend Victorian', 'height': '180'} </code></pre>
2
2016-09-05T10:08:43Z
[ "python" ]
Python: listing variables from object
39,327,930
<p>So basically I need help with laziness.</p> <p>Is it possible in python to take an object, and then list off all it's variables</p> <p>For example</p> <pre><code>class some_object: def __init__(self): self.Name = None self.UUID = None </code></pre> <p>then call a magic function that lists all the variable names in the object</p> <p>and maybe return something that looks close to this:</p> <pre><code>[some_object.Name, some_object.UUID] </code></pre> <p>Keep in mind I DON'T NEED the values attached to the object, but rather the name of the variable, such as Name and UUID</p> <p>if anyone could help me, that'd be awesome.</p> <p>Edit: Thanks for everyone answering my question, the magic function I needed was vars (). I really appreciate everyone effort and input on the problem</p>
-3
2016-09-05T09:49:09Z
39,328,340
<p>You can use the <a href="https://docs.python.org/3/library/functions.html#dir" rel="nofollow"><code>dir()</code></a> function to get a list of (some of) the attributes an object has, like so:</p> <pre><code>&gt;&gt;&gt; class Foo: ... def __init__(self): ... self.name = None ... self.uuid = None &gt;&gt;&gt; thing = Foo() &gt;&gt;&gt; dir(thing) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'uuid'] </code></pre> <p>Alternatively, the <a href="https://docs.python.org/3/library/functions.html#vars" rel="nofollow"><code>vars()</code></a> function can be used to get the <code>__dict__</code> attribute for an object:</p> <pre><code>&gt;&gt;&gt; class Foo: ... def __init__(self): ... self.name = None ... self.uuid = None &gt;&gt;&gt; thing = Foo() &gt;&gt;&gt; vars(thing) {'name': None, 'uuid': None} </code></pre> <p>However, as several commenters have pointed out, it's likely that there is a better way of accomplishing what you are trying to do. The <code>dir()</code> function will not necessarily return a complete list of all attributes an object has; from the docs:</p> <blockquote> <p>If the object does not provide <code>__dir__()</code>, the function tries its best to gather information from the object’s <code>__dict__</code> attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom <code>__getattr__()</code>.</p> <p>Because <code>dir()</code> is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.</p> </blockquote>
1
2016-09-05T10:11:40Z
[ "python" ]
How to install PythonMagick on Amazon Elastic Beanstalk
39,327,940
<p>Since PythonMagick is not available through PIP package manager, how can I install PythonMagick on Amazon Elastic Beanstalk?</p>
0
2016-09-05T09:49:38Z
39,328,898
<p>To install Python packages on Amazon Beanstalk, you have to run add a command in our .ebextension/*.config file. Amazon Linux AMIs in Beanstalk are not shipped with pip but easy_install.</p> <p>These commands run before the application and web server are set up and the application version file is extracted.</p> <pre><code>commands: 01_install_pythonmagick: command: 'easy_install PythonMagick' </code></pre> <p>or You can install it with the Debian package manager: </p> <pre><code>commands: install_packages: command: sudo apt-get install python-pythonmagick [Debian]* </code></pre> <p>or in Ubuntu:</p> <pre><code> command: sudo yum install python-pythonmagick [Ubuntu] </code></pre> <hr> <p>By other hand, the config files must be part of an .ebextensions directory added to your project sources.</p> <p>When deploying your code using the eb create / eb deploy command line, these commands are using the git archive commands to package your code and upload it to Elastic Beanstalk for deployment</p> <p>When your .ebextensions is not under git control (like being in .gitignore) for example, the directory and its config files are not packaged and not sent to Elastic Beanstalk.</p> <p>Be sure that you add and commit .ebextensions directory before tod deploy to Elastic Beanstalk.</p>
0
2016-09-05T10:43:24Z
[ "python", "pythonmagick" ]
Using PyMongo insert_many and empty/null values
39,328,142
<p>I'm in the process of populating a mongoDB database and and not sure what to do with null values when using the insert_many statement (I should state at this point that I'm new to both Python and MongoDB)</p> <p>The data I am inserting is two dimensional traditional SQL like data obtained from a text file, it looks something like this:</p> <pre><code>emp = [ [7839, 'KING', 'PRESIDENT', null], [7698, 'BLAKE', 'MANAGER', 7839], [7782, 'CLARK', 'MANAGER', 7839], [7566, 'JONES', 'MANAGER', 7839], [7788, 'SCOTT', 'ANALYST', 7566], [7902, 'FORD', 'ANALYST', 7566], [7369, 'SMITH', 'CLERK', 7902], [7499, 'ALLEN', 'SALESMAN', 7698], [7521, 'WARD', 'SALESMAN', 7698], [7654, 'MARTIN', 'SALESMAN', 7698], [7844, 'TURNER', 'SALESMAN', 7698], [7876, 'ADAMS', 'CLERK', 7788], [7900, 'JAMES', 'CLERK', 7698], [7934, 'MILLER', 'CLERK', 778] ] </code></pre> <p>And my database population looks like this</p> <pre><code>employee.insert_many([{ "_id" : emp[i,0], "Name": emp[i,1], "Role": emp[i,2], "Boss": emp[i,3] } for i in range(len(emp)) ],False) </code></pre> <p>Ideally I would like "KING", the president, to not have the "Boss" field but I'm not sure how to achieve this. Could anyone point me in the right direction?</p>
0
2016-09-05T10:01:12Z
39,329,760
<p>When you have a datafile like containing:</p> <pre><code>1,'Bob','Owner',null 2,'Joe','Worker','Bob' 3,'Sergiu','Eng','Bob' </code></pre> <p>insert_many it accepts an array (an iterable), in youre code you are using it wrong; python code can look like this:</p> <pre><code># 1 - create a list, read data and insert (computed) documents documents = [] with open("data.txt", "r") as data: for line in data: line = line.strip('\n') #Compute your documents doc_array = line.split(',') doc = {} doc['_id'] = int(doc_array[0]) doc['name'] = doc_array[1].strip('\'') doc['role'] = doc_array[2].strip('\'') boss = doc_array[3].strip('\'') if boss != 'null': doc['boss'] = boss documents.append(doc) #2 use the list for insert_many function db.test.insert_many(documents) </code></pre>
0
2016-09-05T11:36:39Z
[ "python", "mongodb", null, "pymongo", "bulkinsert" ]
Restful API - passing cookie to subsequent POST requests
39,328,197
<p>The application I want to query requires Json format. Supported method is POST. I seemingly cannot find a good example of how to get a cookie from 1 query and pass it to another query (or make subsequent queries use it as part of a <code>base package</code>. Could you advise what I'm doing wrong?</p> <pre><code>import json import requests headers = {'Content-type': 'application/json'} data = {"username":"user1", "password":"pass1"} login_info = json.dumps(data) session = requests.Session() login_url = 'https://ip/login' response = session.post(login_url, data=login_info, headers=headers, verify=False) print session.cookies.get_dict() #returns the following format- {'JSESSIONID': 'DE1EE0006D53EABFA4EE0C6A50D1386A'} query_url = 'https://ip/query' response = session.post(query_url, cookies=session.cookies.get_dict(), headers=headers, verify=False) print response.text #retuns +++++++++++++++ JSESSIONID is empty! +++++++++++++ </code></pre>
0
2016-09-05T10:04:15Z
39,337,266
<p>This link may have the solution to your problem : <a href="http://stackoverflow.com/questions/4166129/apache-httpclient-4-0-3-how-do-i-set-cookie-with-sessionid-for-post-request">Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request</a>. <strong>Have a look at the cookie path adjustment part ... you may need to do so before your second HTTP Post request.</strong></p> <p><em>Can you capture the HTTP request, response (as for example using Firebug or Chrome) while (1) manually trying the login and query pages and (2) doing the same with your script</em>, then sanitize those as required and post those here please? That will allow us to help you better. Thanks. </p> <p>Note/Extra Reading Materials: </p> <p>1)If you need help with using Firebug - here is one link: <a href="http://stackoverflow.com/questions/5374100/how-to-debug-the-http-response-headers-from-a-http-call">How to debug the http response headers from a HTTP call</a> </p> <p>2) Some extra info on jsessionID: </p> <p><a href="http://www.cs-repository.info/2014/07/understanding-jsessionid.html" rel="nofollow">http://www.cs-repository.info/2014/07/understanding-jsessionid.html</a> </p> <p>3) This link has an interesting explanation on cookie and context: <a href="http://www.cs-repository.info/2014/04/sharing-jsessionid-across-applications.html" rel="nofollow">http://www.cs-repository.info/2014/04/sharing-jsessionid-across-applications.html</a> It may be clarifying the real reason behind the problem that you are facing (though the server side solution is not applicable to you). Please search for the text "AppOne/one.jsp" and read from that point onward to be able to quickly finish reading.</p>
-1
2016-09-05T20:25:30Z
[ "python", "jsessionid" ]
NumPy structured / regular array from ctypes pointer to array of structs
39,328,205
<p>Say I have the following <code>C</code> function:</p> <pre><code>void getArrOfStructs(SomeStruct** ptr, int* numElements) </code></pre> <p>And the following <code>C</code> struct:</p> <pre><code>typedef struct SomeStruct { int x; int y; }; </code></pre> <p>I am able to successfully get a Python list:</p> <pre><code>class SomeStruct(Structure): _fields_ = [('x', c_int), ('y', c_int)] ptr, numElements = pointer(SomeStruct()), c_int() myDLL.getArrOfStructs(byref(ptr), byref(numElements))) </code></pre> <p>I want to get a NumPy structured / regular array. </p> <ol> <li>Structured vs Regular array: which one is preferable (in terms of terminology)?</li> <li>How can I do it? I'm looking for an efficient way (without copy each cell). I tried NumPy's <code>frombuffer()</code> functions, but was only able to use it with regular <code>C</code> arrays.</li> </ol>
0
2016-09-05T10:04:37Z
39,334,720
<p>Views of numpy arrays share a data buffer</p> <pre><code>In [267]: x=np.arange(6).reshape(3,2) In [268]: x.tostring() Out[268]: b'\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00' In [269]: x.view('i,i') Out[269]: array([[(0, 1)], [(2, 3)], [(4, 5)]], dtype=[('f0', '&lt;i4'), ('f1', '&lt;i4')]) </code></pre> <p>In this example the databuffer is a C array of 24 bytes, which can viewed in various ways - a flat array, 2 columns, or structured array with 2 fields.</p> <p>I haven't worked with <code>ctypes</code> but I'm sure there's something equivalent to <code>np.frombuffer</code> to construct an array from a byte buffer.</p> <pre><code>In [273]: np.frombuffer(x.tostring(),int) Out[273]: array([0, 1, 2, 3, 4, 5]) In [274]: np.frombuffer(x.tostring(),'i,i') Out[274]: array([(0, 1), (2, 3), (4, 5)], dtype=[('f0', '&lt;i4'), ('f1', '&lt;i4')]) </code></pre>
1
2016-09-05T16:42:01Z
[ "python", "numpy", "ctypes" ]
print cgi fieldstorage object to file instead of a html page python
39,328,254
<p>Thanks in advance. I have a dictionary that has been created from form post data. I want to print the contents of the dictionary to another file. I do not want to use it to output to a html page. </p> <pre><code>def cgiFieldStorageToDict( fieldStorage ): # Makes a dictionary from the http post data params = {} for key in fieldStorage.keys(): params[ key ] = fieldStorage[ key ].value return params my_dict = cgiFieldStorageToDict( cgi.FieldStorage() ) s = open('dict_read.py','w') z = str(my_dict) s.write(z) </code></pre> <p>When I open the dict_read.py file I am just seeing an empty dict:</p> <pre><code>{} </code></pre> <p>Where am I going wrong?</p>
0
2016-09-05T10:06:59Z
39,330,233
<p>I could not write to the file because it did not have the right permissions for all users to write to it. I chmod the file to 777 and some of the code and it now works the way I want it too. Here is the code:</p> <pre><code>form = cgi.FieldStorage() latitude = form.getvalue('latitude') s = open('any_read.py','w') s.write(str(latitude)) s.close() </code></pre>
0
2016-09-05T12:05:38Z
[ "python", "forms", "file", "post", "cgi" ]
Python shapely: .equals function does not always work:
39,328,327
<p>I am having a few issues with the shapely library. Now the equals function seem not to always work:</p> <pre><code>poly1 = Polygon(([220.0, 400, 500], [220.0, 20, 500], [220.0, 20, 0], [220.0, 400, 0], [220.0, 400, 500])) poly2 = Polygon(([220.0, 20, 500], [220.0, 400, 500], [220.0, 400, 0], [220.0, 20, 0], [220.0, 20, 500])) print (poly1.equals(poly2)) </code></pre> <p>Results with a false. Any idea why?</p>
1
2016-09-05T10:10:42Z
39,328,405
<p>From docs:</p> <blockquote> <p>The Polygon constructor takes two positional parameters. The first is an ordered sequence of (x, y[, z]) point tuples and is treated exactly as in the LinearRing case.</p> </blockquote> <p>So try to sort them first (tuples) before create <code>Polygon</code>:</p> <pre><code>&gt;&gt;&gt; pol1_coords = ([0, 1, 2], [3, 4, 5], [6, 7, 8]) &gt;&gt;&gt; pol2_coords = ([0, 1, 2], [6, 7, 8], [3, 4, 5]) &gt;&gt;&gt; Polygon(sorted(pol1_coords)) == Polygon(sorted(pol2_coords)) True </code></pre> <p>instead you'll still have this issue:</p> <pre><code>&gt;&gt;&gt; Polygon(pol1_coords) == Polygon(pol2_coords) False </code></pre>
2
2016-09-05T10:15:30Z
[ "python", "shapely" ]
Python shapely: .equals function does not always work:
39,328,327
<p>I am having a few issues with the shapely library. Now the equals function seem not to always work:</p> <pre><code>poly1 = Polygon(([220.0, 400, 500], [220.0, 20, 500], [220.0, 20, 0], [220.0, 400, 0], [220.0, 400, 500])) poly2 = Polygon(([220.0, 20, 500], [220.0, 400, 500], [220.0, 400, 0], [220.0, 20, 0], [220.0, 20, 500])) print (poly1.equals(poly2)) </code></pre> <p>Results with a false. Any idea why?</p>
1
2016-09-05T10:10:42Z
39,408,439
<p>As @ewcz says in the comments, this is because Shapely only really works with 2D geometry in the XY plane. It is ignoring the Z coordinate here. These are not valid Polygons when projected into the XY plane so Shapely is not prepared to agree that they are equal. It works fine if you remove the (unnecessary) x coordinate:</p> <pre><code>from shapely.geometry import Polygon poly1 = Polygon(([220.0, 400, 500], [220.0, 20, 500], [220.0, 20, 0], [220.0, 400, 0], [220.0, 400, 500])) poly2 = Polygon(([220.0, 20, 500], [220.0, 400, 500], [220.0, 400, 0], [220.0, 20, 0], [220.0, 20, 500])) print (poly1.equals(poly2)) # False print poly1.is_valid # False print poly2.is_valid # False poly1 = Polygon(([400, 500], [20, 500], [20, 0], [400, 0], [400, 500])) poly2 = Polygon(([20, 500], [400, 500], [400, 0], [20, 0], [20, 500])) print (poly1.equals(poly2)) # True print poly1.is_valid # True print poly2.is_valid # True poly1 = Polygon(([220.0, 400], [220.0, 20], [220.0, 20], [220.0, 400], [220.0, 400])) poly2 = Polygon(([220.0, 20], [220.0, 400], [220.0, 400], [220.0, 20], [220.0, 20])) print (poly1.equals(poly2)) # False print poly1.is_valid # False print poly2.is_valid # False </code></pre>
1
2016-09-09T09:37:07Z
[ "python", "shapely" ]
OR-tools consistently returns very sub-optimal TSP solution
39,328,358
<p>Generating some random Gaussian coordinates, I noticed the TSP-solver returns horrible solutions, however it also returns the same horrible solution over and over again for the same input.</p> <p>Given this code:</p> <pre><code>import numpy import math from ortools.constraint_solver import pywrapcp from ortools.constraint_solver import routing_enums_pb2 import matplotlib %matplotlib inline from matplotlib import pyplot, pylab pylab.rcParams['figure.figsize'] = 20, 10 n_points = 200 orders = numpy.random.randn(n_points, 2) coordinates = orders.tolist() class Distance: def __init__(self, coords): self.coords = coords def distance(self, x, y): return math.sqrt((x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2) def __call__(self, x, y): return self.distance(self.coords[x], self.coords[y]) distance = Distance(coordinates) search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters() search_parameters.first_solution_strategy = ( routing_enums_pb2.FirstSolutionStrategy.LOCAL_CHEAPEST_ARC) search_parameters.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.TABU_SEARCH routing = pywrapcp.RoutingModel(len(coordinates), 1) routing.SetArcCostEvaluatorOfAllVehicles(distance) routing.SetDepot(0) solver = routing.solver() routing.CloseModel() # the documentation is a bit unclear on whether this is needed assignment = routing.SolveWithParameters(search_parameters) nodes = [] index = routing.Start(0) while not routing.IsEnd(index): nodes.append(routing.IndexToNode(index)) index = assignment.Value(routing.NextVar(index)) nodes.append(0) for (a, b) in zip(nodes, nodes[1:]): a, b = coordinates[a], coordinates[b] pyplot.plot([a[0], b[0]], [a[1], b[1]], 'r' ) </code></pre> <p>For example, for 10 points I get a nice solution:</p> <p><a href="http://i.stack.imgur.com/uvfj6.png" rel="nofollow"><img src="http://i.stack.imgur.com/uvfj6.png" alt="enter image description here"></a></p> <p>For 20 It's worse, some obvious optimizations still exist (where one only would need to swap two points.</p> <p><a href="http://i.stack.imgur.com/E1x6b.png" rel="nofollow"><img src="http://i.stack.imgur.com/E1x6b.png" alt="enter image description here"></a></p> <p>And for 200 it's horrible:</p> <p><a href="http://i.stack.imgur.com/Reu6h.png" rel="nofollow"><img src="http://i.stack.imgur.com/Reu6h.png" alt="enter image description here"></a></p> <p>I'm wondering whether the code above actually does some LNS, or just returns the initial value, especially since most <code>first_solution_strategy</code> options suggest deterministic initialization.</p> <p>Why does the TSP-solver above return consistent solutions for the same data, even though tabu-search and simulated annealing and such are stochastic. And, why is the 200-point solution so bad?</p> <p>I played with several options in SearchParameters, especially enabling 'use_...' fields in <code>local_search_operators</code>. This had no effect, the same very sub-optimal solutions were returned.</p>
0
2016-09-05T10:12:45Z
39,329,754
<p>I think the problem is with the distance-measure :). I can remember a <code>kScalingFactor</code> in the C-code samples from or-tools, which was used to scale up distances, and then round (by casting) them to integers: or-tools expects distances to be integers.</p> <p>Or course, distances between standard Gaussian random coordinates typically lie between 0 and maybe 2, hence most point pairs have the same distances when mapped to integers: garbage in, garbage out.</p> <p>I fixed it by simply multiplying and casting to integers (just to be sure swig won't interpreter the floats as integers):</p> <pre class="lang-py prettyprint-override"><code># ... def distance(self, x, y): return int(10000 * math.sqrt((x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2)) # ... </code></pre> <p>Then the results make a lot more sense:</p> <p>10 points:</p> <p><a href="http://i.stack.imgur.com/9A41r.png" rel="nofollow"><img src="http://i.stack.imgur.com/9A41r.png" alt="10 points"></a></p> <p>20 points:</p> <p><a href="http://i.stack.imgur.com/fmm5m.png" rel="nofollow"><img src="http://i.stack.imgur.com/fmm5m.png" alt="20 points"></a></p> <p>200 points:</p> <p><a href="http://i.stack.imgur.com/43Ky3.png" rel="nofollow"><img src="http://i.stack.imgur.com/43Ky3.png" alt="200 points"></a></p>
0
2016-09-05T11:35:59Z
[ "python", "or-tools" ]
PUT Request fails on field rename
39,328,384
<p>Serializer.py</p> <pre><code>class CategorySerializer(serializers.ModelSerializer) : id = serializers.IntegerField(source='category_id') name = serializers.CharField(source='category_name') class Meta: model = Category fields = ['id', 'name'] </code></pre> <p>Above works fine for the GET but when i run PUT request it goes to fail block </p> <p>views.py for PUT </p> <pre><code>request.method == 'PUT': serializer = CategorySerializer(category, data=request.data) if serializer.is_valid(): serializer.save() response = { 'status': status.HTTP_200_OK, 'message' : "Category Updated", } return HttpResponse(json.dumps(response), content_type='application/json') else : response = { 'status': status.HTTP_400_BAD_REQUEST, 'message' : "Category not found", } return HttpResponse(json.dumps(response), content_type='application/json') </code></pre> <p>And i'm running following curl</p> <p>curl -X PUT <a href="http://localhost:8000/api/add-category/4/" rel="nofollow">http://localhost:8000/api/add-category/4/</a> -d "category_name=xyz"</p> <p>Response:</p> <pre><code>{"status": 400, "message": "Category not found"} </code></pre> <p>Each time it goes in else part. </p> <p>Experts please help</p>
4
2016-09-05T10:14:03Z
39,328,526
<p>I think problem with <code>id</code> field, it is required. But you sent only <code>name</code> field, try to use <code>partial</code> key. </p> <pre><code>serializer = CategorySerializer(category, data=request.data, partial=True) </code></pre>
0
2016-09-05T10:22:47Z
[ "python", "django", "django-rest-framework" ]
PUT Request fails on field rename
39,328,384
<p>Serializer.py</p> <pre><code>class CategorySerializer(serializers.ModelSerializer) : id = serializers.IntegerField(source='category_id') name = serializers.CharField(source='category_name') class Meta: model = Category fields = ['id', 'name'] </code></pre> <p>Above works fine for the GET but when i run PUT request it goes to fail block </p> <p>views.py for PUT </p> <pre><code>request.method == 'PUT': serializer = CategorySerializer(category, data=request.data) if serializer.is_valid(): serializer.save() response = { 'status': status.HTTP_200_OK, 'message' : "Category Updated", } return HttpResponse(json.dumps(response), content_type='application/json') else : response = { 'status': status.HTTP_400_BAD_REQUEST, 'message' : "Category not found", } return HttpResponse(json.dumps(response), content_type='application/json') </code></pre> <p>And i'm running following curl</p> <p>curl -X PUT <a href="http://localhost:8000/api/add-category/4/" rel="nofollow">http://localhost:8000/api/add-category/4/</a> -d "category_name=xyz"</p> <p>Response:</p> <pre><code>{"status": 400, "message": "Category not found"} </code></pre> <p>Each time it goes in else part. </p> <p>Experts please help</p>
4
2016-09-05T10:14:03Z
39,328,544
<p>You didn't attach your's serializer errors, but it looks like that you should set <code>partial</code> argument for <code>PUT</code> request method. Try </p> <pre><code>serializer = CategorySerializer(category, data=request.data, partial=True) </code></pre> <p>Documentation <a href="http://www.django-rest-framework.org/api-guide/serializers/#partial-updates" rel="nofollow">link</a></p>
2
2016-09-05T10:23:43Z
[ "python", "django", "django-rest-framework" ]
Locking in dask.multiprocessing.get and adding metadata to HDF
39,328,398
<p>Performing an ETL-task in pure Python, I would like to collect error metrics as well as metadata for each of the raw input files considered (error metrics are computed from error codes provided in the data section of the files while metadata is stored in headers). Here's pseudo-code for the whole procedure:</p> <pre><code>import pandas as pd import dask from dask import delayed from dask import dataframe as dd META_DATA = {} # shared resource ERRORS = {} # shared resource def read_file(file_name): global META_DATA, ERRORS # step 1: process headers headers = read_header(file_name) errors = {} data_bfr = [] # step 2: process data section for line in data_section: content_id, data = parse_line(line) if contains_errors(data): errors[content_id] = get_error_code(data) else: data_bfr.append(content_id, data) # ---- Part relevant for question 1 ---- # step 3: acquire lock for shared resource and write metadata with lock.acquire(): write_metadata(file_name, headers) # stores metadata in META_DATA[file_name] write_errors(file_name, errors) # stores error metrics in ERRORS[file_name] return pd.DataFrame(data=data_bfr,...) with set_options(get=dask.multiprocessing.get): df = dd.from_delayed([delayed(read_file)(file_name) \ for file_name in os.listdir(wd)]) # ---- Part relevant for question 2 ---- df.to_hdf('data.hdf', '/data', 'w', complevel=9, \ complib='blosc',..., metadata=(META_DATA, ERRORS)) </code></pre> <p>For each input file <code>read_file</code> returns a <code>pd.DataFrame</code>, further writing relevant metadata and error metrics to shared resources. I am using <code>dask</code>'s multiprocessing scheduler to compute a <code>dask.dataframe</code> from a list of delayed <code>read_file</code>-operations. </p> <ul> <li><strong>Question 1</strong>: Each of the <code>read_file</code>-operations writes to the shared resources <code>META_DATA</code> and <code>ERRORS</code>. What do I have to do to implement a proper locking strategy that works with <code>dask.multiprocessing.get</code>? Would it be sufficient to write the metadata and error information to the collections from within a <code>with locket.lock_file('.lock'):</code>-context? Does <code>multiprocessing.RLock</code> work? What do I have to do to initialize the lock to work with <code>dask</code>? More fundamentally, how can I declare <code>META_DATA</code> and <code>ERRORS</code> as shared resources in <code>dask</code>?</li> <li><strong>Question 2</strong>: If possible, I would like to annotate HDF-data with metadata and error metrics. From a <a href="http://stackoverflow.com/questions/35013926/collecting-attributes-from-dask-dataframe-providers">question on "Collecting attributes from dask dataframe providers"</a>, I learned that <code>dask</code> currently does not support adding metadata to dataframes, but is it possible for the information be written to HDF? If so, how to handle the access to the shared resources in this case?</li> </ul>
1
2016-09-05T10:15:19Z
39,330,077
<h3>Don't depend on Globals</h3> <p>Dask works best with <a href="http://toolz.readthedocs.io/en/latest/purity.html#function-purity" rel="nofollow">pure functions</a>. </p> <p>In particular, your case is a limitation in Python, in that it (correctly) doesn't share global data between processes. Instead, I recommend that you return data explicitly from functions:</p> <pre><code>def read_file(file_name): ... return df, metadata, errors values = [delayed(read_file)(fn) for fn in filenames] dfs = [v[0] for v in values] metadata = [v[1] for v in values] errors = [v[2] for v in values] df = dd.from_delayed(dfs) import toolz metadata = delayed(toolz.merge)(metadata) errors = delayed(toolz.merge)(errors) </code></pre>
1
2016-09-05T11:55:40Z
[ "python", "pandas", "locking", "metadata", "dask" ]
Python-Sphinx documentation: link source code
39,328,463
<p>I have a dictionary that represent a schema (JSON-Schema to be more precise).</p> <p>Sometimes the schema gets complex and in the documentation I need to link to it in order to give a better picture.</p> <p>I have the <code>viewcode</code> extension enabled, I tried the following with no luck:</p> <pre><code>.. data:: netjsonconfig.backends.openvpn.schema.schema .. automodule:: netjsonconfig.backends.openvpn.schema </code></pre> <p>The dictionary python path is <code>netjsonconfig.backends.openvpn.schema.schema</code>.</p> <p>Is it possible to achieve this? If yes how?</p>
1
2016-09-05T10:19:32Z
39,352,023
<p>Try this:</p> <pre><code>.. literalinclude:: your_json_filename.json :language: json </code></pre> <p>You can even select a part of this file to display by </p> <pre><code>.. literalinclude:: your_json_filename.json :language: json :lines: 18-43 </code></pre> <p>This displays the lines 18 to 43 of <em>your_json_filename.json</em>.</p>
0
2016-09-06T14:51:52Z
[ "python", "python-sphinx" ]
Colorbar for seaborn.kdeplot
39,328,551
<p>I want to create a Kernel-Density-Estimation with Seaborn.kdeplot with a colorbar on the side.</p> <pre><code>import matplotlib.pyplot as plt import seaborn as sns import numpy as np; np.random.seed(10) import seaborn as sns; sns.set(color_codes=True) mean, cov = [0, 2], [(1, .5), (.5, 1)] x, y = np.random.multivariate_normal(mean, cov, size=50).T sns.kdeplot(x,y,shade=True) plt.show() </code></pre> <p>While the Kernel-Density-Estimation is created, I do not have a clue how to create the colorbar. I tried using plt.colorbar() without success. </p>
0
2016-09-05T10:24:04Z
39,332,225
<p>You'll have to call the scipy KDE and matplotlib contour function directly, but it's just a bit of extra code:</p> <pre><code>import matplotlib.pyplot as plt import seaborn as sns import numpy as np; np.random.seed(10) import seaborn as sns; sns.set(color_codes=True) from scipy import stats mean, cov = [0, 2], [(1, .5), (.5, 1)] data = np.random.multivariate_normal(mean, cov, size=50).T kde = stats.gaussian_kde(data) xx, yy = np.mgrid[-3:3:.01, -1:4:.01] density = kde(np.c_[xx.flat, yy.flat].T).reshape(xx.shape) f, ax = plt.subplots() cset = ax.contourf(xx, yy, density, cmap="viridis") f.colorbar(cset) </code></pre> <p><a href="http://i.stack.imgur.com/3Zwqg.png" rel="nofollow"><img src="http://i.stack.imgur.com/3Zwqg.png" alt="enter image description here"></a></p>
1
2016-09-05T13:58:13Z
[ "python", "matplotlib", "seaborn", "colorbar", "kernel-density" ]
Reading defined Data from SQL
39,328,634
<p>I have a Problem with reading data with Pandas.read_sql (...):</p> <p>My code Looks like this:</p> <pre><code>import psycopg2 as pg import pandas as pd con = pg.connect(host='db123', database='data', user='ortm', password='***') db = pd.read_sql_query('select calculationtime, state from stateresult WHERE ID = A123', con) </code></pre> <p>I get the following Error Message: Execution failed on sql 'select calculationtime, state from stateresult WHERE ID = A123': FEHLER: Spalte „g351“ existiert nicht LINE 1: ...m stateresult WHERE ID = A123</p> <p>I tried this with another column which is a boolean or integer. I think it has sth. to do with the column being defined as character varying(250). I tried to get it to work with a CAST but that didnt work neither. [I'm using Python 2.7]</p>
0
2016-09-05T10:28:36Z
39,329,186
<p>Why don't you try this once and inform the response you got. If your connection with database is correct.But I am not aware about python.Once check it and revert to me if it gives error message. </p> <pre><code> db = pd.read_sql_query("select calculationtime, state from stateresult WHERE ID = 'A123'", con) </code></pre>
0
2016-09-05T11:00:40Z
[ "python", "sql", "pandas" ]
Run something only once in while loop without breaking the loop
39,328,690
<pre><code>import RPi.GPIO as g import time g.setmode(g.BOARD) g.setup(33, g.OUT) while True: tempfile = open("/sys/devices/w1_bus_master1/28-00152c2631ee/w1_slave") thetext = tempfile.read() tempfile.close() tempdata = thetext.split("\n") [1].split(" ")[9] temperature = float(tempdata[2:]) finaltemp = temperature / 1000 time.sleep(1) if finaltemp &gt; 22: g.output(33,g.LOW) time.sleep(0.3) g.output(33,g.HIGH) else: g.output(33,g.LOW) time.sleep(0.3) g.output(33,g.HIGH) </code></pre> <p>I have searched numerous sites including this one, but never found my solution.</p> <p>As you can see, the code currently grabs the temperature from the system file and stores the temperature in the variable "finaltemp". <br> The way I have my hardware setup is so that my relay switch is connected to the push button on AC remote control, which is why I have my GPIO set up to turn on and off very quickly (0.3 seconds), to mimic the push of the button on the remote. </p> <p>My goal is to 'blink' (push the button) the GPIO only once(!) when the temperature changes according to the condition. </p> <p><em>For example</em>:</p> <p>The temperature in room is 20 and the AC is off at the moment. Therefore, the temperature is slowly rising, and right when the temperature goes above 22, I want to run the 3 lines of code to run. What is happening however, is that it keeps checking it every time. Since the condition meets everytime the while loop starts over, it keeps running the code over and over, so essentially what's happening is that my AC keeps turning on and off and on and off. </p>
-1
2016-09-05T10:31:56Z
39,329,087
<p>What you're currently doing is just checking the temperature and using a condition to keep switching the AC on and off, which as you have already figured out will not work.</p> <p>This is because your condition statements only look at the temperature and not and the current state of the AC, for example if you want the AC to turn on when the temperature is above 22C you're if should be something along the lines of :</p> <pre><code>if temperature &gt; 22 &amp;&amp; AC == off // turn on AC </code></pre>
1
2016-09-05T10:54:27Z
[ "python" ]
Run something only once in while loop without breaking the loop
39,328,690
<pre><code>import RPi.GPIO as g import time g.setmode(g.BOARD) g.setup(33, g.OUT) while True: tempfile = open("/sys/devices/w1_bus_master1/28-00152c2631ee/w1_slave") thetext = tempfile.read() tempfile.close() tempdata = thetext.split("\n") [1].split(" ")[9] temperature = float(tempdata[2:]) finaltemp = temperature / 1000 time.sleep(1) if finaltemp &gt; 22: g.output(33,g.LOW) time.sleep(0.3) g.output(33,g.HIGH) else: g.output(33,g.LOW) time.sleep(0.3) g.output(33,g.HIGH) </code></pre> <p>I have searched numerous sites including this one, but never found my solution.</p> <p>As you can see, the code currently grabs the temperature from the system file and stores the temperature in the variable "finaltemp". <br> The way I have my hardware setup is so that my relay switch is connected to the push button on AC remote control, which is why I have my GPIO set up to turn on and off very quickly (0.3 seconds), to mimic the push of the button on the remote. </p> <p>My goal is to 'blink' (push the button) the GPIO only once(!) when the temperature changes according to the condition. </p> <p><em>For example</em>:</p> <p>The temperature in room is 20 and the AC is off at the moment. Therefore, the temperature is slowly rising, and right when the temperature goes above 22, I want to run the 3 lines of code to run. What is happening however, is that it keeps checking it every time. Since the condition meets everytime the while loop starts over, it keeps running the code over and over, so essentially what's happening is that my AC keeps turning on and off and on and off. </p>
-1
2016-09-05T10:31:56Z
39,329,272
<p>You need to add both <a href="https://en.wikipedia.org/wiki/Finite-state_machine" rel="nofollow">state</a> and <a href="https://en.wikipedia.org/wiki/Hysteresis#Control_systems" rel="nofollow">hysteresis</a>.</p> <p>Pseudo-code for the on/off logic:</p> <pre><code>LIMIT_LOW = 21.5 LIMIT_HIGH = 22.5 AC_running = False # False or True, you need to know exactly while True: temp = .... if temp &lt; LIMIT_LOW and AC_running: # turn AC off AC_running = False elif temp &gt; LIMIT_HIGH and not AC_running: # turn AC on AC_running = True sleep(...) </code></pre>
1
2016-09-05T11:06:04Z
[ "python" ]
Show html generated by using json2html at webpage [Django] [Python]?
39,328,784
<p>Following is my code in view: </p> <pre><code> RESULTS= {} for k in RESULTS_LIST[0].iterkeys(): RESULTS[k] = list(results[k] for results in RESULTS_LIST) RESULTS.pop('_id',None) html_table = json2html.convert(json=RESULTS) return render(request,'homepage.html',{'html_table':html_table}) </code></pre> <p>here I am arranging a data fetched from Mongo Db in a JSON named as RESULTS and by using JSON2HTML package, it is successfully generated html table for data given in JSON. To embedd the html table code in a blank division at html page, I am doing: </p> <pre><code>&lt;div&gt;{{html_table}}&lt;/div&gt; </code></pre> <p>But it failed to display the table on page. I have tried numerous ways to make it but didn't succeed. Please help me to resolve this issue. if any relevant example, you have done before , then please guide me in a right direction. </p> <p>JS code is: </p> <pre><code>angular.module("homeapp",[]) .controller("homecontroller",['$http','$scope',function($http,$scope){ $scope.search= { 'keyword': null, 'option': null, 'startDate':null, 'lastDate': null }; $scope.search_info=function(){ var search_req = { url:'/home', method:'POST', data:$scope.search } $http(search_req) //in case I dont want any response back or $http(search_req).success(function(response){ window.alert(response) }) //in case I need to check response } }]); </code></pre>
1
2016-09-05T10:36:52Z
39,330,777
<p>I have got solution to this problem in an easy way via using js, which is given below and it worked.</p> <pre><code> $http(search_req).success(function(response){ $(".search_results").append(response); }) </code></pre>
0
2016-09-05T12:36:33Z
[ "python", "json", "django" ]
Execute Gams in background on Python 2.7
39,328,807
<p>I need to call and run gams at background from a Python script.</p> <p>I'm using: </p> <pre><code>import subprocess subprocess.check_call([r"C:\GAMS\win64\24.4\gams.exe",r"F:\Otim\Interface\ElGr.gms"]) </code></pre> <p>And it gives me this error: </p> <blockquote> <p>Traceback (most recent call last): File "F:/Otim/Interface/tent_backgroundgams.py", line 91, in subprocess.check_call([r"C:\GAMS\win64\24.4\gams.exe",r"F:\Otim\Interface\ElGrs. gms"]) File "C:\Python27\ArcGIS10.2\lib\subprocess.py", line 511, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '['C:\GAMS\win64\24.4\gams.exe', 'F:\Otim\Interface\ElGr. gms']' returned non-zero exit status 6</p> </blockquote> <p>How can I solve it?</p>
0
2016-09-05T10:38:08Z
39,349,060
<p>Here is a list of the meanings of the different exit codes: <a href="https://www.gams.com/help/index.jsp?topic=%2Fgams.doc%2Fuserguides%2Fuserguide%2F_u_g__g_a_m_s_return_codes.html" rel="nofollow">https://www.gams.com/help/index.jsp?topic=%2Fgams.doc%2Fuserguides%2Fuserguide%2F_u_g__g_a_m_s_return_codes.html</a></p> <p>So, 6 means "there was a parameter error" (because the file specified could not be found with the extra whitespace). 3 means "there was an execution error". So, there was some error while GAMS runs you model. By default you should find an lst file (ElGrs.lst) in your working copy. If you search for "****" in that file, you should see what went wrong and where the error appears.</p>
0
2016-09-06T12:29:07Z
[ "python", "python-2.7", "subprocess", "gams-math" ]
Connecting to Google Cloud SQL from App Engine: access denied
39,328,869
<p>Trying to connect to Google Cloud SQL from App Engine. Getting an error 500 and the logs say: "Access denied for user 'root'@'cloudsqlproxy~' (using password: NO)"). The App Engine and cloud SQL are in the same project. The code I use to connect:</p> <pre><code>class MainPage(webapp2.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' env = os.getenv('SERVER_SOFTWARE') if (env and env.startswith('Google App Engine/')): # Connecting from App Engine db = MySQLdb.connect( unix_socket='/cloudsql/&lt;project-id&gt;:europe-west1:&lt;instance-name&gt;', user='root') cursor = db.cursor() cursor.execute('SELECT 1 + 1') self.response.write('pong') app = webapp2.WSGIApplication([ ('/', MainPage), ], debug=True) </code></pre> <p>As I understand, I am doing everything correctly. The code above I effectively copy-pasted a snippet that you can view in Google Dev Console. Everywhere on StackExchange it is said, that I should not pass the password, so I am not doing that either. I have changed root user password when I created the instance. I don't see why would database deny acess to App Engine, they are on the same project! Is there a way to check what are the permissions for the database? </p>
0
2016-09-05T10:42:02Z
39,329,306
<p>Okay, so turns out there is some misinformation happening. Adding a password parameter solved my issue. But for some reason, there is no mention of this in Google Documentation and many posts on StackOverflow actually directly tell you the oppposite, saying that Cloud SQL will throw an error if you pass it a password when logging in from AppEngine. Maybe some recent update is a cause of this, but in my case, passing a password solved the problem. Hope that helps!</p>
1
2016-09-05T11:08:41Z
[ "python", "google-app-engine", "google-cloud-sql" ]
Connecting to Google Cloud SQL from App Engine: access denied
39,328,869
<p>Trying to connect to Google Cloud SQL from App Engine. Getting an error 500 and the logs say: "Access denied for user 'root'@'cloudsqlproxy~' (using password: NO)"). The App Engine and cloud SQL are in the same project. The code I use to connect:</p> <pre><code>class MainPage(webapp2.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' env = os.getenv('SERVER_SOFTWARE') if (env and env.startswith('Google App Engine/')): # Connecting from App Engine db = MySQLdb.connect( unix_socket='/cloudsql/&lt;project-id&gt;:europe-west1:&lt;instance-name&gt;', user='root') cursor = db.cursor() cursor.execute('SELECT 1 + 1') self.response.write('pong') app = webapp2.WSGIApplication([ ('/', MainPage), ], debug=True) </code></pre> <p>As I understand, I am doing everything correctly. The code above I effectively copy-pasted a snippet that you can view in Google Dev Console. Everywhere on StackExchange it is said, that I should not pass the password, so I am not doing that either. I have changed root user password when I created the instance. I don't see why would database deny acess to App Engine, they are on the same project! Is there a way to check what are the permissions for the database? </p>
0
2016-09-05T10:42:02Z
39,489,787
<p>I would say this part is not well documented on <code>Google Developer Console</code>.</p> <p><code>Google Cloud SQL 2nd Gen</code> comes with a little modification required in the connection string which is not provided in your code.</p> <p>Please have a look at the original code after some modifications from my side:</p> <pre><code>class MainPage(webapp2.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' #db connection if (os.getenv('SERVER_SOFTWARE') and os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/')): db = MySQLdb.connect(unix_socket='/cloudsql/&lt;project-id&gt;:europe-west1&lt;instance-name&gt;, db = 'your-db', user= 'root', passwd='your-root-password') else: db = MySQLdb.connect(host = '10.10.0.1', port=3306, db = 'your-db', user='root', passwd='root-password') cursor = db.cursor() cursor.execute('SELECT 1 + 1') self.response.write('pong') app = webapp2.WSGIApplication([ ('/', MainPage), ], debug=True) </code></pre> <p>Regards.</p>
0
2016-09-14T11:53:04Z
[ "python", "google-app-engine", "google-cloud-sql" ]
Python fails to compile a regex
39,328,878
<p>I'm trying to detect all <code>set</code> from a cmake file using a python regex, fo the file below:</p> <pre><code># Library to include set(LIB_TO_INCLUDE a b c) # comon code (inclusion in source code) set(SHARED_TO_INCLUDE d e f) # Library to include set(THIRD_PARTY g h) </code></pre> <p>I'd like to retrieve:</p> <pre><code>LIB_TO_INCLUDE a b c SHARED_TO_INCLUDE d e f THIRD_PARTY g h </code></pre> <p>I tested the regex <code>set\((?s:[^)])*?\)</code> (get all but <code>)</code> items following <code>set(</code>) using regex101.com (see <a href="https://regex101.com/r/aB5tX2/1" rel="nofollow">https://regex101.com/r/aB5tX2/1</a>), it apparently does what I want.</p> <p>Now when I try to run <code>re.compile(r'set\((?s:[^)])*?\)')</code> from Python, I get the error:</p> <pre><code> File "private\python_scripts\convert.py", line 34, in create_sde_files pattern = re.compile(r'set\((?s:[^)])*?\)') File "b:\dev\vobs_ext_2015\tools_ext\python\Python34_light\lib\re.py", line 223, in compile return _compile(pattern, flags) File "b:\dev\vobs_ext_2015\tools_ext\python\Python34_light\lib\re.py", line 294, in _compile p = sre_compile.compile(pattern, flags) File "b:\dev\vobs_ext_2015\tools_ext\python\Python34_light\lib\sre_compile.py", line 568, in compile p = sre_parse.parse(p, flags) File "b:\dev\vobs_ext_2015\tools_ext\python\Python34_light\lib\sre_parse.py", line 760, in parse p = _parse_sub(source, pattern, 0) File "b:\dev\vobs_ext_2015\tools_ext\python\Python34_light\lib\sre_parse.py", line 370, in _parse_sub itemsappend(_parse(source, state)) File "b:\dev\vobs_ext_2015\tools_ext\python\Python34_light\lib\sre_parse.py", line 721, in _parse raise error("unknown extension") sre_constants.error: unknown extension </code></pre> <p>Is this kind of regex not supported by Python?</p>
0
2016-09-05T10:42:34Z
39,329,504
<p>This should do it: <code>set\(([^)]*?)\)</code></p> <p>The "single line" modifier is passed as an argument when you compile the regex:</p> <pre><code>&gt;&gt;&gt; t = """set(LIB_TO_INCLUDE ... a ... b ... c)""" &gt;&gt;&gt; &gt;&gt;&gt; pattern = r'set\(([^)]*?)\)' &gt;&gt;&gt; &gt;&gt;&gt; regex = re.compile(pattern, re.S) &gt;&gt;&gt; &gt;&gt;&gt; result = regex.search(t).groups()[0] &gt;&gt;&gt; result 'LIB_TO_INCLUDE \n a\n b\n c' </code></pre> <p>You can then eliminate the extra spacing and new lines:</p> <pre><code>&gt;&gt;&gt; ' '.join(x.strip() for x in result.split('\n')) 'LIB_TO_INCLUDE a b c' </code></pre> <p>Note than in your link, if you switch to "python" in the "Flavors" on the left you'll get the errors that your particular format was causing.</p> <p><strong>EDIT:</strong> to get all (3) matches you need to use <code>&lt;regex&gt;.findall(...)</code> instead of <code>search</code>.</p> <pre><code>&gt;&gt;&gt; tt = """# Library to include ... set(LIB_TO_INCLUDE ... a ... b ... c) ... ... # comon code (inclusion in source code) ... set(SHARED_TO_INCLUDE d e f) ... ... # Library to include ... set(THIRD_PARTY g h)""" &gt;&gt;&gt; &gt;&gt;&gt; result = regex.findall(tt) &gt;&gt;&gt; result ['LIB_TO_INCLUDE \n a\n b\n c', 'SHARED_TO_INCLUDE d e f', 'THIRD_PARTY g h'] </code></pre>
1
2016-09-05T11:21:06Z
[ "python", "regex" ]
In python why is the "object" class all in lower case instead of first letter in capitals?
39,328,881
<p>Before I ask this question please note that I've tried searching online for this question but because the word "object" is so common I get lots of unrelated results instead of what I'm looking for. I also looked through the official doc here: <a href="https://docs.python.org/3/tutorial/classes.html" rel="nofollow">https://docs.python.org/3/tutorial/classes.html</a> and didn't find any explanation for this. So please don't freak out when you read this question.</p> <p><strong>Question:</strong></p> <p>In python while declaring a new class we extend the object class. For ex:</p> <pre><code>class SomeClass(object): #eggs and ham etc </code></pre> <p>Here we notice that SomeClass has S capital because we are following the camel case. However, the class that we are inheriting from - "object" doesn't seem to follow this naming convention. Why is the object class in all lower case?</p>
1
2016-09-05T10:42:50Z
39,328,921
<p>All Python's built-in types have lower case: int, str, unicode, float, bool, etc. The object type is just another one of these.</p>
4
2016-09-05T10:44:53Z
[ "python", "class", "inheritance" ]
In python why is the "object" class all in lower case instead of first letter in capitals?
39,328,881
<p>Before I ask this question please note that I've tried searching online for this question but because the word "object" is so common I get lots of unrelated results instead of what I'm looking for. I also looked through the official doc here: <a href="https://docs.python.org/3/tutorial/classes.html" rel="nofollow">https://docs.python.org/3/tutorial/classes.html</a> and didn't find any explanation for this. So please don't freak out when you read this question.</p> <p><strong>Question:</strong></p> <p>In python while declaring a new class we extend the object class. For ex:</p> <pre><code>class SomeClass(object): #eggs and ham etc </code></pre> <p>Here we notice that SomeClass has S capital because we are following the camel case. However, the class that we are inheriting from - "object" doesn't seem to follow this naming convention. Why is the object class in all lower case?</p>
1
2016-09-05T10:42:50Z
39,328,945
<p>The short and basic answer is, class is just a keyword used by the python interpreter to know when some thing needs to be seen as a class , like how you have "def" for defining a function. Its a keyword to describe what follows is all.</p>
-3
2016-09-05T10:46:23Z
[ "python", "class", "inheritance" ]
In python why is the "object" class all in lower case instead of first letter in capitals?
39,328,881
<p>Before I ask this question please note that I've tried searching online for this question but because the word "object" is so common I get lots of unrelated results instead of what I'm looking for. I also looked through the official doc here: <a href="https://docs.python.org/3/tutorial/classes.html" rel="nofollow">https://docs.python.org/3/tutorial/classes.html</a> and didn't find any explanation for this. So please don't freak out when you read this question.</p> <p><strong>Question:</strong></p> <p>In python while declaring a new class we extend the object class. For ex:</p> <pre><code>class SomeClass(object): #eggs and ham etc </code></pre> <p>Here we notice that SomeClass has S capital because we are following the camel case. However, the class that we are inheriting from - "object" doesn't seem to follow this naming convention. Why is the object class in all lower case?</p>
1
2016-09-05T10:42:50Z
39,329,013
<p>If you go to the python interpreter and do this:</p> <pre><code>&gt;&gt;&gt; object &lt;type 'object'&gt; </code></pre> <p>You'll see object is a built-in type, the other built-in types in python are also lowercase <code>type, int, bool, float, str, list, tuple, dict, ...</code>. For instance:</p> <pre><code>&gt;&gt;&gt; type.__class__ &lt;type 'type'&gt; &gt;&gt;&gt; object.__class__ &lt;type 'type'&gt; &gt;&gt;&gt; int.__class__ &lt;type 'type'&gt; &gt;&gt;&gt; type.__class__ &lt;type 'type'&gt; &gt;&gt;&gt; int.__class__ &lt;type 'type'&gt; &gt;&gt;&gt; bool.__class__ &lt;type 'type'&gt; &gt;&gt;&gt; float.__class__ &lt;type 'type'&gt; &gt;&gt;&gt; str.__class__ &lt;type 'type'&gt; &gt;&gt;&gt; list.__class__ &lt;type 'type'&gt; &gt;&gt;&gt; tuple.__class__ &lt;type 'type'&gt; &gt;&gt;&gt; dict.__class__ &lt;type 'type'&gt; </code></pre> <p>So it makes sense they are not lowercase, that way is quite easy to distinguish them from the other type of classes</p>
0
2016-09-05T10:50:27Z
[ "python", "class", "inheritance" ]
Elasticsearch delete_by_query wrong usage
39,328,892
<p> I am using 2 similar ES methods to load and delete documents:</p> <pre><code>result = es.search(index='users_favourite_documents', doc_type='favourite_document', body={"query": {"match": {'user': user}}}) </code></pre> <p>And:</p> <pre><code>result = es.delete_by_query(index='users_favourite_documents', doc_type='favourite_document', body={"query": {"match": {'user': user}}}) </code></pre> <p>First one works ok and returns expected records.<br> Second one throws Exception:</p> <blockquote> <p>"TransportError(404,'{<br> \"found\":false,<br> \"_index\":\"users_favourite_documents\",<br> \"_type\":\"favourite_document\",<br> \"_id\":\"_query\", \"_version\":1,<br> \"_shards\":{\"total\":2,\"successful\":2, \"failed\":0}}')"</p> </blockquote> <p>What am I doing wrong?</p>
0
2016-09-05T10:43:10Z
39,329,398
<p>If you're running ES 2.x, you need to make sure that you have installed the <a href="https://www.elastic.co/guide/en/elasticsearch/plugins/2.4/plugins-delete-by-query.html" rel="nofollow">delete-by-query plugin</a> first:</p> <p>In your ES_HOME folder, run this:</p> <pre><code>bin/plugin install delete-by-query </code></pre> <p>Then restart ES and your <code>es.delete_by_query(...)</code> call will work.</p> <p>If you're running ES 1.x, then delete-by-query is part of the core and that should work out of the box.</p>
1
2016-09-05T11:14:26Z
[ "python", "elasticsearch", "elasticsearch-py" ]
regex that shouldn't work works
39,328,951
<p>im starting to learn regex and i tried to make a simple regex that doesn't make sense to match but it matched any way i tried in python</p> <pre><code>import re pattern = r'[a-z]+[a-z]' print re.findall(pattern,"adasdasad"); </code></pre> <p>it returned ['adasdasad'] where it shouldn't have worked because [a-z]+ should have consumed the whole string and the rest ([a-z]) won't find any thing to conusme why it evaluates ????</p>
1
2016-09-05T10:46:58Z
39,329,003
<p>The <code>+</code> is not a possessive quantifier and allows backtracking into the quantified subpattern.</p> <p>The <code>[a-z]+</code> matches <code>adasdasa</code> and <code>[a-z]</code> matches <code>d</code>, see <a href="https://regex101.com/r/fG5rS2/1">this demo</a>.</p> <p><a href="http://i.stack.imgur.com/YFsOf.png"><img src="http://i.stack.imgur.com/YFsOf.png" alt="enter image description here"></a></p> <p>BTW, if you used <code>[a-z]++[a-z]</code> with PCRE (a pattern with a possessive quantifier <code>++</code>), it would never match anything as it would require to match 1 or more letters and then another letter that would be already consumed with the first subpattern. So, that is the same as <code>(?!)</code> pattern.</p>
5
2016-09-05T10:49:57Z
[ "python", "regex" ]
How to identify unconnected siblings in a graph?
39,328,963
<p>I have a directed acyclic graph as shown in the figure below. <a href="http://i.stack.imgur.com/6NuA5.png" rel="nofollow"><img src="http://i.stack.imgur.com/6NuA5.png" alt="GRAPH WITH SIBLING NODES"></a></p> <p>I want to identify all such group of nodes in this graph that satisfy following conditions:</p> <ul> <li><p>None of the nodes in a group are connected to each other</p></li> <li><p>Nodes in a group have exactly same set of parent and children nodes</p></li> </ul> <p>For example, following group of nodes will be obtained from the above graph:</p> <p>Group 1: {3, 4, 5, 6, 7, 8}</p> <p>Group 2: {16, 17}</p> <p>Group 3: {19, 20}</p> <p>Group 4: {21, 22}</p> <p>I have thousands of such graphs (some with as large as 10k nodes). I'm looking for an efficient algorithm for doing this in Python using networkx.</p> <p>Thanks</p>
3
2016-09-05T10:47:47Z
39,338,249
<p>Note that first request is redundant because second request covers it. It is not possible to have same set of parents and children for two connected nodes. For connected nodes, one node has other node in parent set and vice verse in children set.</p> <p>So nodes in same group have same set of parent and children nodes. In python there is a simple solution implemented with dict indexing by pair of parent and children sets. I am not sure how efficient it is, but it is worth a try.</p> <pre><code>from collections import defaultdict children = { 1: [2, 3, 4, 5, 6, 7, 8], 2: [3, 4, 5, 6, 7, 8, 9], 3: [9, 10], 4: [9, 10], 5: [9, 10], 6: [9, 10], 7: [9, 10], 8: [9, 10], 9: [10], 10: [11, 12, 13], 11: [14, 15], 12: [13, 14, 15], 13: [16, 17], 14: [16, 17], 15: [16, 17], 16: [18], 17: [18], 18: [19, 20], 19: [21, 22], 20: [21, 22], 21: [], 22: [], } # Collect parents parents = defaultdict(list) for a, bs in children.iteritems(): for b in bs: parents[b].append(a) # Use default dict to collect nodes that have same parents and children store = defaultdict(list) for node in children.iterkeys(): store[(tuple(sorted(children[node])), tuple(sorted(parents[node])))].append(node) # Result for s in store.itervalues(): if len(s) &gt; 1: print s </code></pre> <p>From image, group {11, 12} is not a result. 11 is not connected to 13.</p>
2
2016-09-05T22:13:45Z
[ "python", "nodes", "graph-theory", "graph-algorithm", "networkx" ]
How to identify unconnected siblings in a graph?
39,328,963
<p>I have a directed acyclic graph as shown in the figure below. <a href="http://i.stack.imgur.com/6NuA5.png" rel="nofollow"><img src="http://i.stack.imgur.com/6NuA5.png" alt="GRAPH WITH SIBLING NODES"></a></p> <p>I want to identify all such group of nodes in this graph that satisfy following conditions:</p> <ul> <li><p>None of the nodes in a group are connected to each other</p></li> <li><p>Nodes in a group have exactly same set of parent and children nodes</p></li> </ul> <p>For example, following group of nodes will be obtained from the above graph:</p> <p>Group 1: {3, 4, 5, 6, 7, 8}</p> <p>Group 2: {16, 17}</p> <p>Group 3: {19, 20}</p> <p>Group 4: {21, 22}</p> <p>I have thousands of such graphs (some with as large as 10k nodes). I'm looking for an efficient algorithm for doing this in Python using networkx.</p> <p>Thanks</p>
3
2016-09-05T10:47:47Z
39,346,547
<p>Ante has provided an elegant solution to my question. I have modified his code a little to be used with networkx graphs in Python 3.5</p> <p>Given a directed acyclic graph <code>G</code>.</p> <pre><code>lineage = defaultdict(list) for node in G.nodes(): lineage[frozenset(G.predecessors(node)), frozenset(G.successors(node))].append(node) for i in lineage.values(): if len(i) &gt; 1: print (i) # a list containing the groups defined in the question </code></pre> <p>Thank you again Stack Overflow!</p>
0
2016-09-06T10:19:02Z
[ "python", "nodes", "graph-theory", "graph-algorithm", "networkx" ]
how to find the consecutive items in the list that are in a specific range in python
39,329,141
<p>Having the following python list [0.0, 5.0, 2.0, 0.0, 0.30000000000000004] I'd like to return the count of the longest consecutive sequence of items less than 0.5</p> <p>Expected result: [0.0, 5.0, 2.0, 0.0, 0.30000000000000004] should give an output of 2</p>
-2
2016-09-05T10:58:23Z
39,329,636
<p>You can find the working sample down here:</p> <pre><code>list = [0.0, 5.0, 2.0, 0.0, 0.30000000000000004] listDict = {} for idx, val in enumerate(list): for idx2, val2 in enumerate(list): if idx != idx2 and list[idx] != list[idx2] and abs(list[idx] - list[idx2]) &lt; 0.5: listDict[str(list[idx])] = True listDict[str(list[idx2])] = True print (len(listDict)) </code></pre> <p>And this is <a href="http://ideone.com/kX3DVL" rel="nofollow">the link</a> for the live sample.</p>
0
2016-09-05T11:29:14Z
[ "python", "python-3.x" ]
how to find the consecutive items in the list that are in a specific range in python
39,329,141
<p>Having the following python list [0.0, 5.0, 2.0, 0.0, 0.30000000000000004] I'd like to return the count of the longest consecutive sequence of items less than 0.5</p> <p>Expected result: [0.0, 5.0, 2.0, 0.0, 0.30000000000000004] should give an output of 2</p>
-2
2016-09-05T10:58:23Z
39,330,324
<p>Possible, but unstable approach:</p> <pre><code>def number_of_consecutive(data, min_threshold, max_threshold): sum_consec, max_value = 0,0 for element in data: if element &lt;= max_threshold and element &gt;= min_threshold: sum_consec += 1 if sum_consec &gt; max_value: max_value = sum_consec else: sum_consec = 0 return max_value </code></pre> <p>To find elements in range 0 to 0.5 for given list:</p> <pre><code>print number_of_consecutive([0.0, 5.0, 2.0, 0.0, 0.30000000000000004], 0.0, 0.5) "2" </code></pre>
0
2016-09-05T12:10:22Z
[ "python", "python-3.x" ]
How to upload image file from django admin panel ?
39,329,196
<p>I am making a personal website using django 1.10 I want to upload my website logo from admin for why I can edit this in future. So that I have wrote website app and the models of website is :</p> <p>from <strong>future</strong> import unicode_literals</p> <p>from django.db import models</p> <pre><code># Create your models here. class Website(models.Model): title = models.CharField(max_length=255) name = models.CharField(max_length=255) logo = models.ImageField(max_length=255, upload_to='images/') def __unicode__(self): return self.name def __str__(self): return self.name </code></pre> <p>Admin panel: <a href="http://i.stack.imgur.com/FdpvX.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/FdpvX.jpg" alt="enter image description here"></a></p> <p>But image is not uploaded in <code>media/images</code> folder. Please help me about this issue.</p>
2
2016-09-05T11:01:32Z
39,329,622
<p>It saves inside project folder if I change this in settings.py:</p> <p>Before:</p> <pre><code>MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn") </code></pre> <p>After:</p> <pre><code>MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(os.path.dirname(PROJECT_ROOT), "media_cdn") </code></pre>
0
2016-09-05T11:28:17Z
[ "python", "django", "file-upload", "django-models", "django-admin" ]
How to upload image file from django admin panel ?
39,329,196
<p>I am making a personal website using django 1.10 I want to upload my website logo from admin for why I can edit this in future. So that I have wrote website app and the models of website is :</p> <p>from <strong>future</strong> import unicode_literals</p> <p>from django.db import models</p> <pre><code># Create your models here. class Website(models.Model): title = models.CharField(max_length=255) name = models.CharField(max_length=255) logo = models.ImageField(max_length=255, upload_to='images/') def __unicode__(self): return self.name def __str__(self): return self.name </code></pre> <p>Admin panel: <a href="http://i.stack.imgur.com/FdpvX.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/FdpvX.jpg" alt="enter image description here"></a></p> <p>But image is not uploaded in <code>media/images</code> folder. Please help me about this issue.</p>
2
2016-09-05T11:01:32Z
39,330,088
<p>Finally, I solved this problem, I had to change urls.py as like:</p> <pre><code>from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin urlpatterns = [ url(r'^', include("website.urls", namespace='home')), url(r'^admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) </code></pre>
0
2016-09-05T11:56:16Z
[ "python", "django", "file-upload", "django-models", "django-admin" ]
How does index assignment to nodes work in Spark with mapPartitionsWithIndex()?
39,329,216
<p>I am trying to coordinate GPU execution on a Spark cluster. In order to achieve this I need each task/partition to only use a specific GPU slot per system. Each system has 4 GPUs, and the easiest way I have found to achieve this is by doing a mapPartitionsWithIndex() on the rdd with the data, and then using the index as the gpu slot.</p> <p>My question is if I can depend on the indexes to always be assigned in order to the worker nodes? Is there any documentation that refers to this?</p> <p>Quick example:</p> <pre><code>from pyspark import SparkContext from pyspark.sql import SQLContext sc = SparkContext(appName="sample") sqlContext = SQLContext(sc) def print_partition_info(idx, part): print "Index: {} - Partition data: {}".format(idx, part) for p in part: yield p data = [1,1,1,2,2,2, 20, 30, 40, 100] partitions = 4 rdd = sc.parallelize(data, partitions) # rdd = rdd.coalesce(len(partition_keys)) rdd2 = rdd.mapPartitionsWithIndex(print_partition_info) </code></pre> <p>Lets pretend the printed output of running an action on rdd2 is </p> <pre><code>Index: 0 - Partition data: [1,1] Index: 1 - Partition data: [1,2] Index: 2 - Partition data: [2,2] Index: 3 - Partition data: [20,30,40,100] </code></pre> <p>When these partitions get sent out to workers (say 2 workers), will they always be in order as in...<br> Worker 1 partitions = 1, 2<br> Worker 2 partitions = 3, 4 </p> <p>Expanding on that will the partitions always be ordered for say a cluster of 10 or 50 nodes?</p> <p>Finally here is a slide that seems to support this technique: </p> <p><a href="http://i.stack.imgur.com/VDyM1.png" rel="nofollow"><img src="http://i.stack.imgur.com/VDyM1.png" alt="enter image description here"></a> <a href="http://www.slideshare.net/continuumio/gpu-computing-with-apache-spark-and-python" rel="nofollow" title="Slides">slides - check #52</a></p>
1
2016-09-05T11:02:35Z
39,619,957
<p>Short answer: No. In a cluster, the RessourceManager (YARN most of the time) will use a worker if it is available, and it is not always the case when your system is multi-user, or if you have already started a job in a subset of your cluster. So you can't bind a worker with an index. </p> <p>Thus, I am pretty sure that index 0 will bind to the first partition in your data, and so on. An expert will correct me if I'm wrong.</p>
0
2016-09-21T14:54:04Z
[ "python", "apache-spark", "pyspark", "partitioning", "rdd" ]
Converting Python scripts to APIs
39,329,266
<p>I have a Python script that extracts certain consumer product aspects from customer reviews using LinearSVC, but I am trying to convert this script into some sort of API to use for new reviews. Is there an easy way to do this? I am very new to the whole concept of APIs.</p>
0
2016-09-05T11:05:40Z
39,329,314
<p>An API is just a library you import once it's reachable by the interpreter in your case. So any import in python is you calling on an library/API.</p> <p>So if you're script is called <em>foobar.py</em> for example, if it is in the same directory as other python files using</p> <pre><code>import foobar </code></pre> <p>at the top of your python file should allow you to reference any functions made in your original python script.</p>
1
2016-09-05T11:09:19Z
[ "python", "api", "python-textprocessing" ]
Insert data in specific columns in csv file
39,329,274
<p>I am trying to insert the data obtained from the date column. Columns headers are <code>date,day,month,year,pcp1,pcp2,pcp3,pcp4,pcp5,pcp6</code> in the csv file. The columns <code>day, month, year</code> are currently empty. </p> <p>I would like to insert the data obtained from the date by split method into these columns. How can l do that?</p> <p>Here is an example data in csv file:</p> <pre><code>date day month year pcp1 pcp2 pcp3 pcp4 pcp5 pcp6 1.01.1979 0.431 2.167 9.375 0.431 2.167 9.375 2.01.1979 1.216 2.583 9.162 1.216 2.583 9.162 3.01.1979 4.041 9.373 23.169 4.041 9.373 23.169 4.01.1979 1.799 3.866 8.286 1.799 3.866 8.286 5.01.1979 0.003 0.051 0.342 0.003 0.051 0.342 6.01.1979 2.345 3.777 7.483 2.345 3.777 7.483 7.01.1979 0.017 0.031 0.173 0.017 0.031 0.173 </code></pre> <p>Here is my code:</p> <pre><code>import csv dd=[] mm=[] yy=[] with open('output2.csv') as csvfile: reader = csv.DictReader(csvfile, fieldnames=("date","day","month","year","pcp1","pcp2","pcp3","pcp4","pcp5","pcp6"), delimiter=';', quotechar='|') next(reader) # skip header row x = [row['date'] for row in reader] for date_str in x: day, month, year = date_str.split('.') dd.append(day) mm.append(month) yy.append(year) csvfile.close() with open('output2.csv') as f: fieldnames = ["date","day","month","year","pcp1","pcp2","pcp3","pcp4","pcp5","pcp6"] writer = csv.DictWriter(f, fieldnames=fieldnames,delimiter=';', quotechar='|') for i in range(len(dd)): writer.writerow({'day':dd[i]}) for i in range(len(mm)): writer.writerow({'month':mm[i]}) for i in range(len(yy)): writer.writerow({'year':yy[i]}) f.close() </code></pre>
1
2016-09-05T11:06:11Z
39,329,605
<p>Use pandas. You will be able to use most of your code which is not too far from working </p> <pre><code>import pandas as pd filename = "test.csv" data = pd.read_excel(filename) x = data["date"] dd=[] mm=[] yy=[] for date_str in x: day, month, year = date_str.split('.') dd.append(day) mm.append(month) yy.append(year) data["day"] = dd data["month"] = mm data["year"] = yy data.to_csv("test2.csv") </code></pre> <p>In test2.csv the day month year is filled. If you do't want to have the index as first row ( I would not) use</p> <pre><code>data.to_csv("test2.csv",index = False) </code></pre> <p>as last lane</p>
0
2016-09-05T11:26:53Z
[ "python", "csv" ]
Insert data in specific columns in csv file
39,329,274
<p>I am trying to insert the data obtained from the date column. Columns headers are <code>date,day,month,year,pcp1,pcp2,pcp3,pcp4,pcp5,pcp6</code> in the csv file. The columns <code>day, month, year</code> are currently empty. </p> <p>I would like to insert the data obtained from the date by split method into these columns. How can l do that?</p> <p>Here is an example data in csv file:</p> <pre><code>date day month year pcp1 pcp2 pcp3 pcp4 pcp5 pcp6 1.01.1979 0.431 2.167 9.375 0.431 2.167 9.375 2.01.1979 1.216 2.583 9.162 1.216 2.583 9.162 3.01.1979 4.041 9.373 23.169 4.041 9.373 23.169 4.01.1979 1.799 3.866 8.286 1.799 3.866 8.286 5.01.1979 0.003 0.051 0.342 0.003 0.051 0.342 6.01.1979 2.345 3.777 7.483 2.345 3.777 7.483 7.01.1979 0.017 0.031 0.173 0.017 0.031 0.173 </code></pre> <p>Here is my code:</p> <pre><code>import csv dd=[] mm=[] yy=[] with open('output2.csv') as csvfile: reader = csv.DictReader(csvfile, fieldnames=("date","day","month","year","pcp1","pcp2","pcp3","pcp4","pcp5","pcp6"), delimiter=';', quotechar='|') next(reader) # skip header row x = [row['date'] for row in reader] for date_str in x: day, month, year = date_str.split('.') dd.append(day) mm.append(month) yy.append(year) csvfile.close() with open('output2.csv') as f: fieldnames = ["date","day","month","year","pcp1","pcp2","pcp3","pcp4","pcp5","pcp6"] writer = csv.DictWriter(f, fieldnames=fieldnames,delimiter=';', quotechar='|') for i in range(len(dd)): writer.writerow({'day':dd[i]}) for i in range(len(mm)): writer.writerow({'month':mm[i]}) for i in range(len(yy)): writer.writerow({'year':yy[i]}) f.close() </code></pre>
1
2016-09-05T11:06:11Z
39,330,080
<p>You could just parse the CSV as follows. This reads all of your rows into a list, and then inserts the date componants into the empty columns.</p> <pre><code>import csv with open('output2.csv', newline='') as f_input: csv_input = csv.reader(f_input, delimiter=';', quotechar='|') header = next(csv_input) rows = list(csv_input) with open('output2b.csv', 'w', newline='') as f_output: csv_output = csv.writer(f_output, delimiter=';', quotechar='|') csv_output.writerow(header) for row in rows: day, month, year = row[0].split('.') row[1:4] = [day, month, year] csv_output.writerow(row) </code></pre> <p>Giving you the following output:</p> <pre><code>date;day;month;year;pcp1;pcp2;pcp3;pcp4;pcp5;pcp6 1.01.1979;1;01;1979;0.431;2.167;9.375;0.431;2.167;9.375 2.01.1979;2;01;1979;1.216;2.583;9.162;1.216;2.583;9.162 3.01.1979;3;01;1979;4.041;9.373;23.169;4.041;9.373;23.169 4.01.1979;4;01;1979;1.799;3.866;8.286;1.799;3.866;8.286 5.01.1979;5;01;1979;0.003;0.051;0.342;0.003;0.051;0.342 6.01.1979;6;01;1979;2.345;3.777;7.483;2.345;3.777;7.483 7.01.1979;7;01;1979;0.017;0.031;0.173;0.017;0.031;0.173 </code></pre> <p>Tested using Python 3.5.2 </p>
2
2016-09-05T11:55:43Z
[ "python", "csv" ]
how to return object of matching subclass?
39,329,284
<p>I'm trying to write a method that is supposed to return me an object of a subclass depending on some input data. Let me try to explain</p> <pre><code>class Pet(): @classmethod def parse(cls,data): #return Pet() if all else fails pass class BigPet(Pet): size = "big" @classmethod def parse(cls,data): #return BigPet() if all subclass parsers fails pass class SmallPet(Pet): size = "small" @classmethod def parse(cls,data): #return SmallPet() if all subclass parsers fails pass class Cat(SmallPet): sound = "maw" @classmethod def parse(cls,data): #return Cat() if all criteria met pass class Dog(BigPet): sound = "woof" @classmethod def parse(cls,data): #return Dog() if all criteria met pass </code></pre> <p>Imagine that I would like to make a "parser", such as this:</p> <pre><code>Pet.parse(["big", "woof"]) &gt; returns object of class Dog Pet.parse(["small", "maw"]) &gt; returns object of class Cat Pet.parse(["small", "blup"]) &gt; returns object of class SmallPet </code></pre> <p>I have no idea of how to write this in a proper way. Any suggestions? Of course this is a bullshit example. I'd like to apply this on different packets of a communication protocol of some kind. </p> <p>If i am approaching this in a completely wrong way, please tell me :)</p>
1
2016-09-05T11:06:57Z
39,434,087
<p>Why not pass the exact class name, look for that in the <code>globals()</code> and instantiate that?</p> <pre><code>def parse_pet(class_name, data): # will raise a KeyError exception if class_name doesn't exist cls = globals()[class_name] return cls(data) cat = parse_pet('Cat', 'meow') big_pet = parse_pet('BigPet', 'woof') </code></pre>
0
2016-09-11T08:07:49Z
[ "python", "parsing", "design-patterns" ]
Write a script that runs a command for you
39,329,309
<p>So, here is my doubt:</p> <p>I have some VPS with Ubuntu 15.04 headless that run a python script 24.7</p> <p>I'd like to reboot the process every 8 hours without restarting the machine and giving it a 60 seconds delay between stop and start.</p> <p>This may seem simple, but i'm struggling a bit on how to do this.</p> <p>Thanks for your time.</p>
-4
2016-09-05T11:08:45Z
39,330,097
<p>I think it will be better (but not necessary) if you first daemonize your script so that it can be run as a service.</p> <p><a href="http://stackoverflow.com/questions/1603109/how-to-make-a-python-script-run-like-a-service-or-daemon-in-linux">How to make a Python script run like a service or daemon in Linux</a></p> <p>After that you should add two <a href="http://stackoverflow.com/questions/6423532/how-to-run-cron-job-every-2-hours">cron jobs</a>. Run your crontab editor</p> <pre><code>crontab -e </code></pre> <p>Write this in the editor:</p> <pre><code>0 */8 * * * python /home/username/script.sh stop # stop every 8 hours 1 */8 * * * python /home/username/script.sh start # start 1 minute after stopping </code></pre> <p>To make sure about the cron jobs timing check this <a href="http://crontab.guru" rel="nofollow">website</a>.</p>
0
2016-09-05T11:56:38Z
[ "python", "linux" ]
softlayer api: change root password and ssh-key operation
39,329,313
<p>I am a developer, my current work is writing a script to manage the softlayer VMs. The problems are about change Root Password and binding(remove binding) the SshKey. My questions are:</p> <ol> <li><p>I have a running softlayer vm, wihch softlayer api can help me to change the vm’s root password. </p></li> <li><p>I have a running softlayer vm which has not bind sshkey before. Does any softlayer api can help me to bind ssh-key with this vm?</p></li> <li><p>Contray to point 2, how can I unbind the sshkey by using softlayer api?</p></li> </ol>
1
2016-09-05T11:09:04Z
39,353,450
<p>Regarding to your <strong>first question</strong>, change root password from vm, follow these steps:</p> <p>Retrieves the password's identifier from the vm</p> <pre><code>https://$user:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Virtual_Guest/$vsiId/getSoftwareComponents?objectMask=mask[passwords] Method: Get </code></pre> <p>Replace <strong>$user</strong>, <strong>$apiKey</strong> and <strong>$vsiId</strong> with you own information</p> <p>You will get a result like this:</p> <pre><code>hardwareId": null "id": 345676755 "manufacturerLicenseInstance": "C412F72A-1BB1-4C07-9467-E55729234F8E" "passwords": [1] 0: { "createDate": "2016-06-09T11:10:28-03:00" "id": 122333 "modifyDate": "2016-09-06T11:19:18-03:00" "password": "Cochabamba" "port": null "softwareId": 11209641 "username": "Ruber" "software": null } } </code></pre> <p>Then you can update using the following call:</p> <pre><code>https://$user:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Software_Component_Password/$passwordId/editObject Method: Post { "parameters":[ { "username":"usernameTest", "password":"Password*-" } ] } </code></pre> <p>Replace: <strong>$user</strong>, <strong>$apiKey</strong> and <strong>$passwordId</strong> with you own information, in this case the <strong>$passwordId</strong> is: <strong>122333</strong></p> <p>Regarding to your <strong>second</strong> and <strong>third</strong> question, unfortunately it's not possible to do this through SoftLayer API, it is necessary to do an OS Reload</p>
1
2016-09-06T16:09:42Z
[ "python", "api", "softlayer" ]
softlayer api: change root password and ssh-key operation
39,329,313
<p>I am a developer, my current work is writing a script to manage the softlayer VMs. The problems are about change Root Password and binding(remove binding) the SshKey. My questions are:</p> <ol> <li><p>I have a running softlayer vm, wihch softlayer api can help me to change the vm’s root password. </p></li> <li><p>I have a running softlayer vm which has not bind sshkey before. Does any softlayer api can help me to bind ssh-key with this vm?</p></li> <li><p>Contray to point 2, how can I unbind the sshkey by using softlayer api?</p></li> </ol>
1
2016-09-05T11:09:04Z
39,355,839
<ol> <li>I have a running softlayer vm, wihch softlayer api can help me to change the vm’s root password.</li> </ol> <p>The answer Ruber Cuellar posted will change the password listed in the SoftLayer API, <strong><em>but will not change the password on your system</em></strong>, UNLESS you perform an OS reload. No API method will actually change anything on a running system. </p> <ol start="2"> <li>I have a running softlayer vm which has not bind sshkey before. Does any softlayer api can help me to bind ssh-key with this vm?</li> </ol> <p>No. You can add the key manually of course. <a href="https://help.ubuntu.com/community/SSH/OpenSSH/Keys" rel="nofollow">https://help.ubuntu.com/community/SSH/OpenSSH/Keys</a></p> <ol start="3"> <li>Contray to point 2, how can I unbind the sshkey by using softlayer api? No, but you can remove them manually as well. </li> </ol> <p>The following might also be useful in using SSH keys with the SoftLayer API</p> <p><a href="http://sldn.softlayer.com/reference/services/SoftLayer_Security_Ssh_Key" rel="nofollow">http://sldn.softlayer.com/reference/services/SoftLayer_Security_Ssh_Key</a></p> <p><a href="http://softlayer-api-python-client.readthedocs.io/en/latest/api/managers/sshkey/" rel="nofollow">http://softlayer-api-python-client.readthedocs.io/en/latest/api/managers/sshkey/</a></p>
1
2016-09-06T18:43:24Z
[ "python", "api", "softlayer" ]
Python list - string formatting as list indices
39,329,368
<p>Depending on a condition I need to get a value from one or another function. I'm trying to put it inside a simple <code>If ... Else</code> statement. I tried to use <code>%s</code> string formatting but it won't work. Below code, so it will become more clear what I try to do:</p> <pre><code>if condition: item = my_list['%s'] else: item = my_other_list['%s'] # now I do something with this value: print item % 3 </code></pre> <p>This way I tried to <code>print</code> 3rd value of one or other list if the <code>condition</code> was True of False. This returned an error about list indices being string. So I tried to put it inside <code>int()</code> what didn't help. </p> <p>How should I do it? The problem is I get the value <strong>later</strong> than I declare what <code>item</code> is.</p> <p><strong>EDIT</strong> I will add some more infos here:</p> <p>I have a <code>for</code> loop, that goes through ~1000 elements and processes them. If the <code>condition</code> is <code>True</code>, it calls one function or another if false. Now, I don't want to check the same condition 1000 times, because I know it won't change during the time and would like to check it once and apply the method to all of the elements. </p> <p>More code:</p> <pre><code>if self.dlg.comboBox_3.currentIndex == 0: item = QCustomTableWidgetItem(str(round((sum(values['%s'])/len(values['%s'])),2))) else: item = QCustomTableWidgetItem(str(round(sum(values['%s'],2)))) for row in range(len(groups)): group = QTableWidgetItem(str(groups[row])) qTable.setItem(row,0,group) qTable.setItem(row,1,item % row) </code></pre> <p>This is the actual code. Not the <code>'%s'</code> and '% row'. I used simplified before not to distract from the actual problem, but I think it's needed. I'm sorry if it wasn't a good decision.</p>
0
2016-09-05T11:12:30Z
39,329,399
<h3>Short answer:</h3> <p><code>'%s'</code> is a <em>string</em> by definition, while a list index should be an <em>integer</em> by definition. </p> <p>Use <code>int(string)</code> if you are sure the string can be an integer (if not, it will raise a <code>ValueError</code>)</p>
0
2016-09-05T11:14:39Z
[ "python", "list" ]
Python list - string formatting as list indices
39,329,368
<p>Depending on a condition I need to get a value from one or another function. I'm trying to put it inside a simple <code>If ... Else</code> statement. I tried to use <code>%s</code> string formatting but it won't work. Below code, so it will become more clear what I try to do:</p> <pre><code>if condition: item = my_list['%s'] else: item = my_other_list['%s'] # now I do something with this value: print item % 3 </code></pre> <p>This way I tried to <code>print</code> 3rd value of one or other list if the <code>condition</code> was True of False. This returned an error about list indices being string. So I tried to put it inside <code>int()</code> what didn't help. </p> <p>How should I do it? The problem is I get the value <strong>later</strong> than I declare what <code>item</code> is.</p> <p><strong>EDIT</strong> I will add some more infos here:</p> <p>I have a <code>for</code> loop, that goes through ~1000 elements and processes them. If the <code>condition</code> is <code>True</code>, it calls one function or another if false. Now, I don't want to check the same condition 1000 times, because I know it won't change during the time and would like to check it once and apply the method to all of the elements. </p> <p>More code:</p> <pre><code>if self.dlg.comboBox_3.currentIndex == 0: item = QCustomTableWidgetItem(str(round((sum(values['%s'])/len(values['%s'])),2))) else: item = QCustomTableWidgetItem(str(round(sum(values['%s'],2)))) for row in range(len(groups)): group = QTableWidgetItem(str(groups[row])) qTable.setItem(row,0,group) qTable.setItem(row,1,item % row) </code></pre> <p>This is the actual code. Not the <code>'%s'</code> and '% row'. I used simplified before not to distract from the actual problem, but I think it's needed. I'm sorry if it wasn't a good decision.</p>
0
2016-09-05T11:12:30Z
39,329,447
<p>A list is made up of multiple data values that are referenced by an indice. So if i defined my list like so :</p> <pre><code>my_list = [apples, orange, peaches] </code></pre> <p>If I want to reference something in the list I do it like this</p> <pre><code>print(my_list[0]) </code></pre> <p>The expected output for this line of code would be "apples". To actually add something new to a list you need to use an inbuilt method of the list object, which looks something like this :</p> <pre><code>my_list.append("foo") </code></pre> <p>The new list would then look like this </p> <pre><code>[apples, orange, peaches, foo] </code></pre> <p>I hope this helps.</p>
0
2016-09-05T11:17:27Z
[ "python", "list" ]
Python list - string formatting as list indices
39,329,368
<p>Depending on a condition I need to get a value from one or another function. I'm trying to put it inside a simple <code>If ... Else</code> statement. I tried to use <code>%s</code> string formatting but it won't work. Below code, so it will become more clear what I try to do:</p> <pre><code>if condition: item = my_list['%s'] else: item = my_other_list['%s'] # now I do something with this value: print item % 3 </code></pre> <p>This way I tried to <code>print</code> 3rd value of one or other list if the <code>condition</code> was True of False. This returned an error about list indices being string. So I tried to put it inside <code>int()</code> what didn't help. </p> <p>How should I do it? The problem is I get the value <strong>later</strong> than I declare what <code>item</code> is.</p> <p><strong>EDIT</strong> I will add some more infos here:</p> <p>I have a <code>for</code> loop, that goes through ~1000 elements and processes them. If the <code>condition</code> is <code>True</code>, it calls one function or another if false. Now, I don't want to check the same condition 1000 times, because I know it won't change during the time and would like to check it once and apply the method to all of the elements. </p> <p>More code:</p> <pre><code>if self.dlg.comboBox_3.currentIndex == 0: item = QCustomTableWidgetItem(str(round((sum(values['%s'])/len(values['%s'])),2))) else: item = QCustomTableWidgetItem(str(round(sum(values['%s'],2)))) for row in range(len(groups)): group = QTableWidgetItem(str(groups[row])) qTable.setItem(row,0,group) qTable.setItem(row,1,item % row) </code></pre> <p>This is the actual code. Not the <code>'%s'</code> and '% row'. I used simplified before not to distract from the actual problem, but I think it's needed. I'm sorry if it wasn't a good decision.</p>
0
2016-09-05T11:12:30Z
39,329,474
<p>I'd suggest wrapping around a function like this:</p> <pre><code>def get_item(index, list1, list2) if condition: return list1[index] else: return list2[index] print get_item(3) </code></pre>
0
2016-09-05T11:19:05Z
[ "python", "list" ]
Python list - string formatting as list indices
39,329,368
<p>Depending on a condition I need to get a value from one or another function. I'm trying to put it inside a simple <code>If ... Else</code> statement. I tried to use <code>%s</code> string formatting but it won't work. Below code, so it will become more clear what I try to do:</p> <pre><code>if condition: item = my_list['%s'] else: item = my_other_list['%s'] # now I do something with this value: print item % 3 </code></pre> <p>This way I tried to <code>print</code> 3rd value of one or other list if the <code>condition</code> was True of False. This returned an error about list indices being string. So I tried to put it inside <code>int()</code> what didn't help. </p> <p>How should I do it? The problem is I get the value <strong>later</strong> than I declare what <code>item</code> is.</p> <p><strong>EDIT</strong> I will add some more infos here:</p> <p>I have a <code>for</code> loop, that goes through ~1000 elements and processes them. If the <code>condition</code> is <code>True</code>, it calls one function or another if false. Now, I don't want to check the same condition 1000 times, because I know it won't change during the time and would like to check it once and apply the method to all of the elements. </p> <p>More code:</p> <pre><code>if self.dlg.comboBox_3.currentIndex == 0: item = QCustomTableWidgetItem(str(round((sum(values['%s'])/len(values['%s'])),2))) else: item = QCustomTableWidgetItem(str(round(sum(values['%s'],2)))) for row in range(len(groups)): group = QTableWidgetItem(str(groups[row])) qTable.setItem(row,0,group) qTable.setItem(row,1,item % row) </code></pre> <p>This is the actual code. Not the <code>'%s'</code> and '% row'. I used simplified before not to distract from the actual problem, but I think it's needed. I'm sorry if it wasn't a good decision.</p>
0
2016-09-05T11:12:30Z
39,329,584
<p>You have a reasonably large misconception about how list slicing works. It will always happen at the time you call it, so inside your if loop itself Python will be trying to slice either of the lists by the literal string <code>"%s"</code>, which can't possibly work.</p> <p>There is no need to do this. You can just assign <em>the list</em> as the output from the if statement, and then slice that directly:</p> <pre><code>if condition: list_to_slice = my_list else: list_to_slice = my_other_list # now I do something with this value: print list_to_slice[3] </code></pre>
2
2016-09-05T11:25:39Z
[ "python", "list" ]
Python list - string formatting as list indices
39,329,368
<p>Depending on a condition I need to get a value from one or another function. I'm trying to put it inside a simple <code>If ... Else</code> statement. I tried to use <code>%s</code> string formatting but it won't work. Below code, so it will become more clear what I try to do:</p> <pre><code>if condition: item = my_list['%s'] else: item = my_other_list['%s'] # now I do something with this value: print item % 3 </code></pre> <p>This way I tried to <code>print</code> 3rd value of one or other list if the <code>condition</code> was True of False. This returned an error about list indices being string. So I tried to put it inside <code>int()</code> what didn't help. </p> <p>How should I do it? The problem is I get the value <strong>later</strong> than I declare what <code>item</code> is.</p> <p><strong>EDIT</strong> I will add some more infos here:</p> <p>I have a <code>for</code> loop, that goes through ~1000 elements and processes them. If the <code>condition</code> is <code>True</code>, it calls one function or another if false. Now, I don't want to check the same condition 1000 times, because I know it won't change during the time and would like to check it once and apply the method to all of the elements. </p> <p>More code:</p> <pre><code>if self.dlg.comboBox_3.currentIndex == 0: item = QCustomTableWidgetItem(str(round((sum(values['%s'])/len(values['%s'])),2))) else: item = QCustomTableWidgetItem(str(round(sum(values['%s'],2)))) for row in range(len(groups)): group = QTableWidgetItem(str(groups[row])) qTable.setItem(row,0,group) qTable.setItem(row,1,item % row) </code></pre> <p>This is the actual code. Not the <code>'%s'</code> and '% row'. I used simplified before not to distract from the actual problem, but I think it's needed. I'm sorry if it wasn't a good decision.</p>
0
2016-09-05T11:12:30Z
39,329,643
<p>Here is a compact way to do it:</p> <pre><code>source = my_list if condition else my_other_list print(source[2]) </code></pre> <p>This binds a variable <code>source</code> to either <code>my_list</code> or <code>my_other_list</code> depending on the condition. Then the 3rd element of the selected list is accessed using an integer index. This method has the advantage that <code>source</code> is still bound to the list should you need to access other elements in the list.</p> <p>Another way, similar to yours, is to get the element directly:</p> <pre><code>index = 2 if condition: item = my_list[index] else: item = my_other_list[index] print(item) </code></pre>
0
2016-09-05T11:29:35Z
[ "python", "list" ]
Matplotlib, usetex: Colorbar's font does not match plot's font
39,329,429
<p>I have a matplotlib plot with a colorbar and can't seem to figure out how to match the fonts of the plot and the colorbar.</p> <p>I try to use usetex for text handling, but it seems like only the ticks of the plot are affected, not the ticks of the colorbar. Also, I have searched for solution quite a bit, so in the following code sample, there are a few different attempts included, but the result still is a bold font. Minimum failing code sample:</p> <pre><code>import matplotlib as mpl import matplotlib.pyplot as plt import sys import colorsys import numpy as np mpl.rc('text', usetex=True) plt.rcParams["font.family"] = "Times New Roman" plt.rcParams["font.weight"] = 100 plt.rcParams["axes.labelweight"] = 100 plt.rcParams["figure.titleweight"] = 100 def draw(): colors = [colorsys.hsv_to_rgb(0.33, step /15, 1) for step in [2, 5, 8, 11, 14]] mymap = mpl.colors.LinearSegmentedColormap.from_list('value',colors, N=5) Z = [[0,0],[0,0]] levels = range(2,15+4,3) CS3 = plt.contourf(Z, levels, cmap=mymap) plt.clf() plt.figure(figsize=(20, 15)) plt.gca().set_aspect('equal') cbar = plt.colorbar(CS3, ax=plt.gca(), shrink=0.5, fraction=0.5, aspect=30, pad=0.05, orientation="horizontal") cbar.set_ticks([1.5 + x for x in [2,5,8,11,14]]) # attempts to make the fonts look the same cbar.ax.set_xticklabels([1,2,3,4,5], weight="light", fontsize=16) cbar.set_label("value", weight="ultralight", fontsize=32) plt.setp(cbar.ax.xaxis.get_ticklabels(), weight='ultralight', fontsize=16) for l in cbar.ax.xaxis.get_ticklabels(): l.set_weight("light") plt.show() draw() </code></pre> <p>Unfortunately, the fonts don't look the same at all. Picture:</p> <p><a href="http://i.stack.imgur.com/3jNq4.png" rel="nofollow"><img src="http://i.stack.imgur.com/3jNq4.png" alt="plot font and colorbar font are different"></a></p> <p>I'm sure it's just a stupid misunderstanding of usetex on my part. Why does the usetex not seem to handle the colormap's font?</p> <p>Thanks!</p>
1
2016-09-05T11:16:44Z
39,334,140
<p>The issue here is that MPL wraps ticklabels in <code>$</code> when <code>usetex=True</code>. This causes them to have different sizes than text that is not wrapped in <code>$</code>. When you force your ticks to be labeled with <code>[1,2,3,4,5]</code> these values are not wrapped in <code>$</code>, and are therefore rendered differently. I don't know the details of <em>why</em> this is, but I've run into the problem before myself.</p> <p>I'd recommend wrapping your colorbar ticks in <code>$</code>, for example:</p> <pre><code>cbar.ax.set_xticklabels(['${}$'.format(tkval) for tkval in [1, 2, 3, 4, 5]]) </code></pre> <p>From there you should be able to figure out how to adjust font sizes/weights so that they match and you get what you want.</p>
1
2016-09-05T15:58:47Z
[ "python", "matplotlib", "fonts", "styles", "tex" ]
How to scattering a numpy array in python using comm.Scatterv
39,329,492
<p>I am tring to write a MPI-based code to do some calculation using python and MPI4py. However, following the example, I CANNOT scatter a numpy vector into cores. Here is the code and errors, is there anyone can help me? Thanks. </p> <pre><code>import numpy as np from mpi4py import MPI comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() n = 6 if rank == 0: d1 = np.arange(1, n+1) split = np.array_split(d1, size) split_size = [len(split[i]) for i in range(len(split))] split_disp = np.insert(np.cumsum(split_size), 0, 0)[0:-1] else: #Create variables on other cores d1 = None split = None split_size = None split_disp = None split_size = comm.bcast(split_size, root = 0) split_disp = comm.bcast(split_disp, root = 0) d1_local = np.zeros(split_size[rank]) comm.Scatterv([d1, split_size, split_disp, MPI.DOUBLE], d1_local, root=0) print('rank ', rank, ': ', d1_local) </code></pre> <p>And the error result is: </p> <pre><code>rank 2 : [ 2.47032823e-323] rank 3 : [ 2.96439388e-323] rank 0 : [ 4.94065646e-324 9.88131292e-324] rank 1 : [ 1.48219694e-323 1.97626258e-323] </code></pre> <p>Thanks. </p>
0
2016-09-05T11:20:14Z
39,345,364
<p>The data type is not correct. I should specify the type of the array:</p> <pre><code>d1 = np.arange(1, n+1, dtype='float64') </code></pre>
0
2016-09-06T09:25:11Z
[ "python", "numpy", "mpi", "mpi4py" ]
Stop counting time in django
39,329,649
<p>I've got a problem with take constant value from this function:</p> <pre><code>def get_time_left(self) now = timezone.now() time_left = self.deadline - now return time_left </code></pre> <p>self.deadline is value from model.</p> <p>For example I want to take time_left from 15.00 2.09.2016, save it and use this value in another function, but when I try to do this, the value is always changing...</p>
0
2016-09-05T11:29:44Z
39,329,875
<p>Maybe an easy workaround would be to have the value in the others function definition ? That way you are certain of what you send...</p> <p>Yet, if you set the result of get_time_left() in a variable, it should not change...</p> <p>More code would be helpfull indeed</p>
0
2016-09-05T11:42:59Z
[ "python", "django", "datetime", "timezone" ]
Unicode-encode issues while sending desktop notification using Python
39,329,709
<p>I am fetching latest football scores from a website and sending a notification on the desktop (OS X). I am using BeautifulSoup to scrape the data. I had issues with the unicode data which was generating this error</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 2: ordinal not in range(128). </code></pre> <p>So I inserted this at the beginning which solved the problem while outputting on the terminal.</p> <pre><code>import sys reload(sys) sys.setdefaultencoding('utf-8') </code></pre> <p>But the problem exists when I am sending notifications on the desktop. I use terminal-notifier to send desktop-notifications.</p> <pre><code>def notify (title, subtitle, message): t = '-title {!r}'.format(title) s = '-subtitle {!r}'.format(subtitle) m = '-message {!r}'.format(message) os.system('terminal-notifier {}'.format(' '.join((m, t, s)))) </code></pre> <p>The below images depict the output on the terminal Vs the desktop notification. </p> <p>Output on terminal.</p> <p><a href="http://i.stack.imgur.com/cFn41.png" rel="nofollow"><img src="http://i.stack.imgur.com/cFn41.png" alt="enter image description here"></a></p> <p>Desktop Notification</p> <p><a href="http://i.stack.imgur.com/MBIN1.png" rel="nofollow"><img src="http://i.stack.imgur.com/MBIN1.png" alt="Dektop Notification"></a></p> <p>Also, if I try to replace the comma in the string, I get the error,</p> <p><code>new_scorer = str(new_scorer[0].text).replace(",","")</code></p> <pre><code>File "live_football_bbc01.py", line 41, in get_score new_scorer = str(new_scorer[0].text).replace(",","") UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 2: ordinal not in range(128) </code></pre> <p>How do I get the output on the desktop notifications like the one on the terminal? Thanks!</p> <p><strong><em>Edit : Snapshot of the desktop notification. (Solved)</em></strong> </p> <p><a href="http://i.stack.imgur.com/OyxkI.png" rel="nofollow"><img src="http://i.stack.imgur.com/OyxkI.png" alt="enter image description here"></a></p>
1
2016-09-05T11:33:18Z
39,329,859
<p>Use: ˋsys.getfilesystemencoding` to get your encoding</p> <p>Encode your string with it, ignore or replace errors:</p> <pre><code>import sys encoding = sys.getfilesystemencoding() msg = new_scorer[0].text.replace(",", "") print(msg.encode(encoding, errons="replace")) </code></pre>
-1
2016-09-05T11:42:01Z
[ "python", "unicode", "utf-8", "ascii" ]
Unicode-encode issues while sending desktop notification using Python
39,329,709
<p>I am fetching latest football scores from a website and sending a notification on the desktop (OS X). I am using BeautifulSoup to scrape the data. I had issues with the unicode data which was generating this error</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 2: ordinal not in range(128). </code></pre> <p>So I inserted this at the beginning which solved the problem while outputting on the terminal.</p> <pre><code>import sys reload(sys) sys.setdefaultencoding('utf-8') </code></pre> <p>But the problem exists when I am sending notifications on the desktop. I use terminal-notifier to send desktop-notifications.</p> <pre><code>def notify (title, subtitle, message): t = '-title {!r}'.format(title) s = '-subtitle {!r}'.format(subtitle) m = '-message {!r}'.format(message) os.system('terminal-notifier {}'.format(' '.join((m, t, s)))) </code></pre> <p>The below images depict the output on the terminal Vs the desktop notification. </p> <p>Output on terminal.</p> <p><a href="http://i.stack.imgur.com/cFn41.png" rel="nofollow"><img src="http://i.stack.imgur.com/cFn41.png" alt="enter image description here"></a></p> <p>Desktop Notification</p> <p><a href="http://i.stack.imgur.com/MBIN1.png" rel="nofollow"><img src="http://i.stack.imgur.com/MBIN1.png" alt="Dektop Notification"></a></p> <p>Also, if I try to replace the comma in the string, I get the error,</p> <p><code>new_scorer = str(new_scorer[0].text).replace(",","")</code></p> <pre><code>File "live_football_bbc01.py", line 41, in get_score new_scorer = str(new_scorer[0].text).replace(",","") UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 2: ordinal not in range(128) </code></pre> <p>How do I get the output on the desktop notifications like the one on the terminal? Thanks!</p> <p><strong><em>Edit : Snapshot of the desktop notification. (Solved)</em></strong> </p> <p><a href="http://i.stack.imgur.com/OyxkI.png" rel="nofollow"><img src="http://i.stack.imgur.com/OyxkI.png" alt="enter image description here"></a></p>
1
2016-09-05T11:33:18Z
39,330,028
<p>You are formatting using <code>!r</code> which gives you the <em>repr</em> output, forget the terrible reload logic and either use unicode everywhere:</p> <pre><code>def notify (title, subtitle, message): t = u'-title {}'.format(title) s = u'-subtitle {}'.format(subtitle) m = u'-message {}'.format(message) os.system(u'terminal-notifier {}'.format(u' '.join((m, t, s)))) </code></pre> <p>or encode:</p> <pre><code>def notify (title, subtitle, message): t = '-title {}'.format(title.encode("utf-8")) s = '-subtitle {}'.format(subtitle.encode("utf-8")) m = '-message {}'.format(message.encode("utf-8")) os.system('terminal-notifier {}'.format(' '.join((m, t, s)))) </code></pre> <p>When you call <em>str(new_scorer[0].text).replace(",","")</em> you are trying to encode to <em>ascii</em>, you need to specify the encoding to use:</p> <pre><code>In [13]: s1=s2=s3= u'\xfc' In [14]: str(s1) # tries to encode to ascii --------------------------------------------------------------------------- UnicodeEncodeError Traceback (most recent call last) &lt;ipython-input-14-589849bdf059&gt; in &lt;module&gt;() ----&gt; 1 str(s1) UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 0: ordinal not in range(128) In [15]: "{}".format(s1) + "{}".format(s2) + "{}".format(s3) # tries to encode to ascii--------------------------------------------------------------------------- UnicodeEncodeError Traceback (most recent call last) &lt;ipython-input-15-7ca3746f9fba&gt; in &lt;module&gt;() ----&gt; 1 "{}".format(s1) + "{}".format(s2) + "{}".format(s3) UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 0: ordinal not in range(128) </code></pre> <p>You can encode straight away:</p> <pre><code>In [16]: "{}".format(s1.encode("utf-8")) + "{}".format(s2.encode("utf-8")) + "{}".format(s3.encode("utf-8")) Out[16]: '\xc3\xbc\xc3\xbc\xc3\xbc' </code></pre> <p>Or use use all unicode prepending a u to the format strings and encoding last:</p> <pre><code>In [17]: out = u"{}".format(s1) + u"{}".format(s2) + u"{}".format(s3) In [18]: out Out[18]: u'\xfc\xfc\xfc' In [19]: out.encode("utf-8") Out[19]: '\xc3\xbc\xc3\xbc\xc3\xbc' </code></pre> <p>If you use <code>!r</code> you are always going to the the bytes in the output:</p> <pre><code>In [30]: print "{}".format(s1.encode("utf-8")) ü In [31]: print "{!r}".format(s1).encode("utf-8") u'\xfc' </code></pre> <p>You can also pass the args using subprocess:</p> <pre><code>from subprocess import check_call def notify (title, subtitle, message): cheek_call(['terminal-notifier','-title',title.encode("utf-8"), '-subtitle',subtitle.encode("utf-8"), '-message'.message.encode("utf-8")]) </code></pre>
1
2016-09-05T11:51:44Z
[ "python", "unicode", "utf-8", "ascii" ]
Python: How to manage multiple user?
39,329,746
<p>I have a list of users IDs and each user ID has a lot of friends IDs. I want to write a program to send message to user's friend. So how to manage these information ? I think I should using 1 single file and write this Json format into file:</p> <pre><code>{'id_user':1, 'id_friend': 123} {'id_user':1, 'id_friend': 124} {'id_user':1, 'id_friend': 125} {'id_user':1, 'id_friend': 126} {'id_user':2, 'id_friend': 222} {'id_user':2, 'id_friend': 223} {'id_user':2, 'id_friend': 224} {'id_user':2, 'id_friend': 225} ... </code></pre> <p>If i use this way, after that, the file will have few dozen million rows. So, What is best way to manage these users ? What type of database I should use ? Thank you !</p>
-1
2016-09-05T11:35:25Z
39,331,219
<p>I hope my answer is not too biased...</p> <p>Depending on what else you want to accomplish, there are several options:</p> <ul> <li>In standard library you have <a href="https://docs.python.org/3/library/sqlite3.html" rel="nofollow">sqlite3</a> which is a relational database engine (which can handle large amounts of rows quite well)</li> <li>There are other relational database engines like mysql for which python libraries exist (most have better performance for huge datasets that sqlite)</li> <li>There is <a href="https://pypi.python.org/pypi/ZODB" rel="nofollow">ZODB</a> (tutorial on <a href="http://www.zodb.org/en/latest/" rel="nofollow">zodb.org</a>) which is an object-database engine (you can actually use it as an ORM, too)</li> <li>There are object-relational mappers (ORM) like <a href="http://www.sqlalchemy.org/" rel="nofollow">sqlalchemy</a> or the one included in <a href="https://www.djangoproject.com/" rel="nofollow">django</a> that can help you build databases.</li> </ul> <p>You should have a look at the <a href="https://wiki.python.org/moin/DatabaseProgramming/" rel="nofollow">Python Wiki</a> which providess deeper info about that</p>
1
2016-09-05T13:03:17Z
[ "python", "json", "database", "file", "dictionary" ]
How to find the maximum product of two elements in a list?
39,329,829
<p>I was trying out a problem on hackerrank contest for fun, and there came this question. I used itertools for this, here is the code:</p> <pre><code>import itertools l = [] for _ in range(int(input())): l.append(int(input())) max = l[0] * l[len(l)-1] for a,b in itertools.combinations(l,2): if max &lt; (a*b): max = (a*b) print(max) </code></pre> <p>Is their any other efficient way than this? As I am getting time out error on some test cases which I cant access (as its a small contest).</p>
2
2016-09-05T11:40:39Z
39,329,936
<p>Iterate over the list and find the following:</p> <p>Largest Positive number(a)</p> <p>Second Largest Positive number(b)</p> <p>Largest Negative number(c)</p> <p>Second Largest Negative number(d)</p> <p>Now, you will be able to figure out the maximum value upon multiplication, either <code>a*b</code> or <code>c*d</code></p>
13
2016-09-05T11:47:04Z
[ "python", "python-2.7", "python-3.x", "itertools" ]
How to find the maximum product of two elements in a list?
39,329,829
<p>I was trying out a problem on hackerrank contest for fun, and there came this question. I used itertools for this, here is the code:</p> <pre><code>import itertools l = [] for _ in range(int(input())): l.append(int(input())) max = l[0] * l[len(l)-1] for a,b in itertools.combinations(l,2): if max &lt; (a*b): max = (a*b) print(max) </code></pre> <p>Is their any other efficient way than this? As I am getting time out error on some test cases which I cant access (as its a small contest).</p>
2
2016-09-05T11:40:39Z
39,330,037
<p>Here is an implementation following @User_Targaryen's logic. <a href="https://docs.python.org/3.0/library/heapq.html" rel="nofollow"><code>heapq</code></a> returns the 2 largest and 2 smallest numbers in the list, <a href="https://docs.python.org/3/library/operator.html" rel="nofollow"><code>mul operator</code></a> returns the products of these 2 pairs of numbers, and <code>max</code> returns the largest of these 2 products.</p> <pre><code>&gt;&gt;&gt; import heapq &gt;&gt;&gt; from operator import mul &gt;&gt;&gt; l = [2,40,600,3,-89,-899] &gt;&gt;&gt; max(mul(*heapq.nsmallest(2,l)),mul(*heapq.nlargest(2,l))) 80011 # -899*-89 = 80011 </code></pre>
2
2016-09-05T11:52:42Z
[ "python", "python-2.7", "python-3.x", "itertools" ]
How to find the maximum product of two elements in a list?
39,329,829
<p>I was trying out a problem on hackerrank contest for fun, and there came this question. I used itertools for this, here is the code:</p> <pre><code>import itertools l = [] for _ in range(int(input())): l.append(int(input())) max = l[0] * l[len(l)-1] for a,b in itertools.combinations(l,2): if max &lt; (a*b): max = (a*b) print(max) </code></pre> <p>Is their any other efficient way than this? As I am getting time out error on some test cases which I cant access (as its a small contest).</p>
2
2016-09-05T11:40:39Z
39,330,487
<p>Just sort the list and select the largest of the products of the last 2 items in the list and the first 2 items in the list:</p> <pre><code>from operator import mul numbers = [10, 20, 1, -11, 100, -12] l = sorted(numbers) # or sort in place with numbers.sort() if you don't mind mutating the list max_product = max(mul(*l[:2]), mul(*l[-2:])) </code></pre> <p>This is a O(n log n) solution due to the sort. Someone else suggested a <code>heapq</code> solution which I found to be faster for lists longer than a few thousand random integers.</p>
2
2016-09-05T12:19:31Z
[ "python", "python-2.7", "python-3.x", "itertools" ]
Scikit Image Marching Cubes
39,329,954
<p>I'm using the Scikit Image implementation of the marching cubes algorithm to generate an isosurface. </p> <pre><code>verts, faces,normals,values = measure.marching_cubes(stack,0) </code></pre> <p>generates the following error: </p> <blockquote> <p>ValueError: need more than 2 values to unpack</p> </blockquote> <p>but </p> <pre><code> verts, faces = measure.marching_cubes(stack,0) </code></pre> <p>works fine so it seems the algorithm is simply not generating the values for <code>normals</code> and <code>values</code>. Has anyone had any experience with this type of issue?</p> <p>Furthermore, I don't understand the need for the <code>faces</code> output of the algorithm, as a set of 3 vertices for each triangle in the mesh should be sufficient to describe the isosurface?</p>
0
2016-09-05T11:48:20Z
39,330,245
<p>The <a href="http://scikit-image.org/docs/dev/api/skimage.measure.html#marching-cubes" rel="nofollow">docs</a> of <code>marching_cubes</code> on the development version of scikit-image show that it should return <code>normals</code> and <code>values</code> as well. However it has only been introduced recently. They were not returned in version 0.12, as can be seen in the <a href="http://scikit-image.org/docs/0.12.x/api/skimage.measure.html#marching-cubes" rel="nofollow">docs from that version</a>. To get them you'd have to update to the current development version. A guide on how to install the development version can be found <a href="http://scikit-image.org/docs/dev/install.html#running-the-development-version" rel="nofollow">here</a>.</p>
2
2016-09-05T12:06:03Z
[ "python", "mesh", "scikit-image", "marching-cubes" ]
Time and Space Complexity Trouble
39,330,093
<p>I've seen so many time complexity problems but none seem to aid in my understanding of it - like really get it.</p> <p>What I have taken from my readings and attempts at practices all seems to come down to what was mentioned here <a href="http://stackoverflow.com/questions/13467674/determining-complexity-for-recursive-functions-big-o-notation">Determining complexity for recursive functions (Big O notation)</a> in the answer coder gave - which in fact did help me understand a little more about what's going on for time complexity.</p> <p>What about a function that such as this:</p> <pre><code>def f(n): if n &lt; 3: return n if n &gt;= 3: return f(n-1) + 2*f(n-2) + 3*f(n-3) </code></pre> <p>Since the function calls the function 3 times, does that mean that the time complexity is O(3^n)?</p> <p>As for the space complexity, it seems to be linear hence I propose the complexity to be O(n).</p> <p>Am I wrong about this?</p>
0
2016-09-05T11:56:28Z
39,330,730
<blockquote> <p>Since the function calls the function 3 times</p> </blockquote> <p>This isn't really correct, but rather lets use examples that are more exact that your ad-hoc example.</p> <pre><code>def constant(n): return n*12301230 </code></pre> <p>This will always run in the same amount of time and is therefore O(1)</p> <pre><code>def linear(n): total = 0 for x in xrange(n): total+=1 return total </code></pre> <p>This has O(N) time </p> <pre><code>def quadratic(n): total = 0 for x in xrange(n): for y in xrange(n): total+=1 return total </code></pre> <p>This runs in quadratic time O(N^2) since the inner loop runs n times and the outer loop runs n times.</p> <p>There are also more specific examples for log(N), N*log(N), (2^N), etc but, going back to your question:</p> <blockquote> <blockquote> <p>Since the function calls the function 3 times, does that mean that the time complexity is O(3^n)?</p> </blockquote> </blockquote> <p>If the function is called 3 times, it will still be constant time for <code>constant(x)</code>, linear for <code>linear(x)</code> and quadratic for <code>quadratic(x)</code>. Importantly, O(3^n) is exponential time and is not the same as n^3. Then, we would not use a 3 as the base but a 2^n as a standard.</p> <p>So your function will have a constant time for x&lt;3. Best approximation to what your function gives, I'd run it through a timer but its recursive and difficult to compute. If you provide another, non-recursive example I'll be happy to tell you its complexity.</p> <p>Hope this helps a bit, the graph doesn't do justice to how much faster 2^n grows in comparison to n^2 but it's a good start.</p> <p><a href="http://i.stack.imgur.com/sCiCp.png" rel="nofollow"><img src="http://i.stack.imgur.com/sCiCp.png" alt="Time complexity"></a></p>
3
2016-09-05T12:33:48Z
[ "python", "recursion", "time-complexity" ]
recursively change file names in directories
39,330,127
<p>Starting with a source directory;</p> <p>&lt; C:/Users/Public/Env Defense/Projects/1_Earnings Calls/Quarterly Earnings Calls/1_IOUs by Quarter/2013 Q1/AAA Done/</p> <p>there are multiple subdirectories within the source directory; for example </p> <p>&lt; /Users/Public/Env Defense/Projects/1_Earnings Calls/Quarterly Earnings Calls/1_IOUs by Quarter/2013 Q1/AAA Done/AEP</p> <p>/Users/Public/Env Defense/Projects/1_Earnings Calls/Quarterly Earnings Calls/1_IOUs by Quarter/2013 Q1/AAA DONE/Allete</p> <p>Within each subdirectory are multiple files with common words in the names such as;</p> <p>*2013 Q1 AEP Earnings Call Transcript.txt</p> <p>*2013 Q1 AEP Earnings Call Transcript.txt</p> <p>*2013 Q1 ALLETE Earnings Call Transcript.docx</p> <p>*2013 Q1 AEP Earnings Call Presentation.pdf'</p> <p>I am writing a script to walk through the subdirectories and remove some of the common words. For example I want 2013 Q1 AEP Earnings Call Transcript.txt would become 2013 Q1 AEP.txt</p> <p>The script I wrote is; FileRename_V1.py</p> <pre><code>import os cwd = os.getcwd() print (' 1 Working Directory is %s' %cwd) print (' ') sourcedir = '/Users/Public/Env Defense/Projects/1_Earnings Calls/Quarterly Earnings Calls/1_IOUs by Quarter/2013 Q1/AAA Done' os.chdir (sourcedir) cwd = os.getcwd() print (' 2 Working Directory is %s' %cwd) print (' ') for dirPath, subdirNames, fileList in os.walk (sourcedir): for filename in fileList: filename = os.path.join (dirPath, filename) os.rename(filename,filename.replace("Earnings Call Transcript", '')) </code></pre> <p>The result is the following error message; </p> <p>Traceback (most recent call last): File "FileRename_V1.py", line 29, in os.rename(filename,filename.replace("Earnings Call Transcript", ''))</p> <p>FileNotFoundError: [WinError 2] The system cannot find the file specified: '/Users/Public/Env Defense/Projects/1_Earnings Calls/Quarterly Earnings Calls/1_IOUs by Quarter/2013 Q1/AAADONE\2013 Q1 AEP Earnings Call Presentation.pdf' -> </p> <p>'/Users/Public/Env Defense/Projects/1_Earnings Calls/Quarterly Earnings Calls/1_IOUs by Quarter/2013 Q1/AAA DONE\2013 Q1 AEP Earnings Call Presentation.pdf'</p> <p>I have researched code to recursively rename files and the code I wrote appears similar to examples that worked. Any suggestions as to what the problem is and how to correct the script will be much appreciated.</p> <p>Cheers, BobS</p>
-1
2016-09-05T11:59:08Z
39,337,649
<p>The WinError was caused by the file path exceeding 260 characters. I edited the directory names to reduce the number of characters and the script worked as intended. It is very helpful to be able to quickly edit the names as I am working with 20 directories each of which contains about 40 subdirectories and each subdirectory contains about 5 files. Fortunate that someone posted the issue with file path length !!</p>
1
2016-09-05T21:00:44Z
[ "python", "recursion" ]
How to iterate through every directory specified and run commands on files (Python)
39,330,146
<p>I have been working on a script that will check through every subdirectory in a directory and match files using regex and then use different commands based on what kind of a file it is. </p> <p>So what i have finished is the use of different commands based on regex matching. Right now it checks for either a .zip file, .rar file or .r00 file and uses different commands for each match. However i need help iterating through every directory and first check if there is a .mkv file in there, then it should just pass that directory and jump to the next, but if there is a match it should run the command and then when it's finished continue to the next directory.</p> <pre><code>import os import re rx = '(.*zip$)|(.*rar$)|(.*r00$)' path = "/mnt/externa/folder" for root, dirs, files in os.walk(path): for file in files: res = re.match(rx, file) if res: if res.group(1): print("Unzipping ",file, "...") os.system("unzip " + root + "/" + file + " -d " + root) elif res.group(2): os.system("unrar e " + root + "/" + file + " " + root) if res.group(3): print("Unraring ",file, "...") os.system("unrar e " + root + "/" + file + " " + root) </code></pre> <p>EDIT:</p> <p>Here is the code i have now:</p> <pre><code>import os import re from subprocess import check_call from os.path import join rx = '(.*zip$)|(.*rar$)|(.*r00$)' path = "/mnt/externa/Torrents/completed/test" for root, dirs, files in os.walk(path): if not any(f.endswith(".mkv") for f in files): found_r = False for file in files: pth = join(root, file) try: if file.endswith(".zip"): print("Unzipping ",file, "...") check_call(["unzip", pth, "-d", root]) found_zip = True elif not found_r and file.endswith((".rar",".r00")): check_call(["unrar","e","-o-", pth, root,]) found_r = True break except ValueError: print ("Oops! That did not work") </code></pre> <p>This script works mostly fine but sometimes i seem to run into issues when there are Subs in the folder, here is an error i message i get when i run the script:</p> <p>$ python unrarscript.py </p> <pre><code>UNRAR 5.30 beta 2 freeware Copyright (c) 1993-2015 Alexander Roshal Extracting from /mnt/externa/Torrents/completed/test/The.Conjuring.2013.1080p.BluRay.x264-ALLiANCE/Subs/the.conjuring.2013.1080p.bluray.x264-alliance.subs.rar No files to extract Traceback (most recent call last): File "unrarscript.py", line 19, in &lt;module&gt; check_call(["unrar","e","-o-", pth, root]) File "/usr/lib/python2.7/subprocess.py", line 541, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['unrar', 'e', '-o-', '/mnt/externa/Torrents/completed/test/The.Conjuring.2013.1080p.BluRay.x264-ALLiANCE/Subs/the.conjuring.2013.1080p.bluray.x264-alliance.subs.rar', '/mnt/externa/Torrents/completed/test/The.Conjuring.2013.1080p.BluRay.x264-ALLiANCE/Subs']' returned non-zero exit status 10 </code></pre> <p>I cannot really understand what is wrong about the code, so what im hoping is that some of you are willing to help me.</p>
3
2016-09-05T12:00:02Z
39,330,766
<p>The example below will work directly! As suggested by @Padraic I replaced os.system with the more suitable subprocess.</p> <p>What about joining all the files in a single string and look for *.mkv within the string? </p> <pre><code>import os import re from subprocess import check_call from os.path import join rx = '(.*zip$)|(.*rar$)|(.*r00$)' path = "/mnt/externa/folder" regex_mkv = re.compile('.*\.mkv\,') for root, dirs, files in os.walk(path): string_files = ','.join(files)+', ' if regex_mkv.match(string_files): continue for file in files: res = re.match(rx, file) if res: # use os.path.join pth = join(root, file) # it can only be res.group(1) or one of the other two so we only need if/else. if res.group(1): print("Unzipping ",file, "...") check_call(["unzip" , pth, "-d", root]) else: check_call(["unrar","e", pth, root]) </code></pre>
1
2016-09-05T12:36:08Z
[ "python", "loops" ]
How to iterate through every directory specified and run commands on files (Python)
39,330,146
<p>I have been working on a script that will check through every subdirectory in a directory and match files using regex and then use different commands based on what kind of a file it is. </p> <p>So what i have finished is the use of different commands based on regex matching. Right now it checks for either a .zip file, .rar file or .r00 file and uses different commands for each match. However i need help iterating through every directory and first check if there is a .mkv file in there, then it should just pass that directory and jump to the next, but if there is a match it should run the command and then when it's finished continue to the next directory.</p> <pre><code>import os import re rx = '(.*zip$)|(.*rar$)|(.*r00$)' path = "/mnt/externa/folder" for root, dirs, files in os.walk(path): for file in files: res = re.match(rx, file) if res: if res.group(1): print("Unzipping ",file, "...") os.system("unzip " + root + "/" + file + " -d " + root) elif res.group(2): os.system("unrar e " + root + "/" + file + " " + root) if res.group(3): print("Unraring ",file, "...") os.system("unrar e " + root + "/" + file + " " + root) </code></pre> <p>EDIT:</p> <p>Here is the code i have now:</p> <pre><code>import os import re from subprocess import check_call from os.path import join rx = '(.*zip$)|(.*rar$)|(.*r00$)' path = "/mnt/externa/Torrents/completed/test" for root, dirs, files in os.walk(path): if not any(f.endswith(".mkv") for f in files): found_r = False for file in files: pth = join(root, file) try: if file.endswith(".zip"): print("Unzipping ",file, "...") check_call(["unzip", pth, "-d", root]) found_zip = True elif not found_r and file.endswith((".rar",".r00")): check_call(["unrar","e","-o-", pth, root,]) found_r = True break except ValueError: print ("Oops! That did not work") </code></pre> <p>This script works mostly fine but sometimes i seem to run into issues when there are Subs in the folder, here is an error i message i get when i run the script:</p> <p>$ python unrarscript.py </p> <pre><code>UNRAR 5.30 beta 2 freeware Copyright (c) 1993-2015 Alexander Roshal Extracting from /mnt/externa/Torrents/completed/test/The.Conjuring.2013.1080p.BluRay.x264-ALLiANCE/Subs/the.conjuring.2013.1080p.bluray.x264-alliance.subs.rar No files to extract Traceback (most recent call last): File "unrarscript.py", line 19, in &lt;module&gt; check_call(["unrar","e","-o-", pth, root]) File "/usr/lib/python2.7/subprocess.py", line 541, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['unrar', 'e', '-o-', '/mnt/externa/Torrents/completed/test/The.Conjuring.2013.1080p.BluRay.x264-ALLiANCE/Subs/the.conjuring.2013.1080p.bluray.x264-alliance.subs.rar', '/mnt/externa/Torrents/completed/test/The.Conjuring.2013.1080p.BluRay.x264-ALLiANCE/Subs']' returned non-zero exit status 10 </code></pre> <p>I cannot really understand what is wrong about the code, so what im hoping is that some of you are willing to help me.</p>
3
2016-09-05T12:00:02Z
39,331,468
<pre><code>import os import re regex = re.complile(r'(.*zip$)|(.*rar$)|(.*r00$)') path = "/mnt/externa/folder" for root, dirs, files in os.walk(path): for file in files: res = regex.match(file) if res: if res.group(1): print("Unzipping ",file, "...") os.system("unzip " + root + "/" + file + " -d " + root) elif res.group(2): os.system("unrar e " + root + "/" + file + " " + root) else: print("Unraring ",file, "...") os.system("unrar e " + root + "/" + file + " " + root) </code></pre>
-2
2016-09-05T13:16:54Z
[ "python", "loops" ]
How to iterate through every directory specified and run commands on files (Python)
39,330,146
<p>I have been working on a script that will check through every subdirectory in a directory and match files using regex and then use different commands based on what kind of a file it is. </p> <p>So what i have finished is the use of different commands based on regex matching. Right now it checks for either a .zip file, .rar file or .r00 file and uses different commands for each match. However i need help iterating through every directory and first check if there is a .mkv file in there, then it should just pass that directory and jump to the next, but if there is a match it should run the command and then when it's finished continue to the next directory.</p> <pre><code>import os import re rx = '(.*zip$)|(.*rar$)|(.*r00$)' path = "/mnt/externa/folder" for root, dirs, files in os.walk(path): for file in files: res = re.match(rx, file) if res: if res.group(1): print("Unzipping ",file, "...") os.system("unzip " + root + "/" + file + " -d " + root) elif res.group(2): os.system("unrar e " + root + "/" + file + " " + root) if res.group(3): print("Unraring ",file, "...") os.system("unrar e " + root + "/" + file + " " + root) </code></pre> <p>EDIT:</p> <p>Here is the code i have now:</p> <pre><code>import os import re from subprocess import check_call from os.path import join rx = '(.*zip$)|(.*rar$)|(.*r00$)' path = "/mnt/externa/Torrents/completed/test" for root, dirs, files in os.walk(path): if not any(f.endswith(".mkv") for f in files): found_r = False for file in files: pth = join(root, file) try: if file.endswith(".zip"): print("Unzipping ",file, "...") check_call(["unzip", pth, "-d", root]) found_zip = True elif not found_r and file.endswith((".rar",".r00")): check_call(["unrar","e","-o-", pth, root,]) found_r = True break except ValueError: print ("Oops! That did not work") </code></pre> <p>This script works mostly fine but sometimes i seem to run into issues when there are Subs in the folder, here is an error i message i get when i run the script:</p> <p>$ python unrarscript.py </p> <pre><code>UNRAR 5.30 beta 2 freeware Copyright (c) 1993-2015 Alexander Roshal Extracting from /mnt/externa/Torrents/completed/test/The.Conjuring.2013.1080p.BluRay.x264-ALLiANCE/Subs/the.conjuring.2013.1080p.bluray.x264-alliance.subs.rar No files to extract Traceback (most recent call last): File "unrarscript.py", line 19, in &lt;module&gt; check_call(["unrar","e","-o-", pth, root]) File "/usr/lib/python2.7/subprocess.py", line 541, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['unrar', 'e', '-o-', '/mnt/externa/Torrents/completed/test/The.Conjuring.2013.1080p.BluRay.x264-ALLiANCE/Subs/the.conjuring.2013.1080p.bluray.x264-alliance.subs.rar', '/mnt/externa/Torrents/completed/test/The.Conjuring.2013.1080p.BluRay.x264-ALLiANCE/Subs']' returned non-zero exit status 10 </code></pre> <p>I cannot really understand what is wrong about the code, so what im hoping is that some of you are willing to help me.</p>
3
2016-09-05T12:00:02Z
39,331,551
<p>Just use <em>any</em> to see if any files end in <code>.mkv</code> before going any further, you can also simplify to an <em>if/else</em> as you do the same thing for the last two matches. Also using <a href="https://docs.python.org/2/library/subprocess.html#subprocess.check_call" rel="nofollow">subprocess.check_call</a> would be a better approach:</p> <pre><code>import os import re from subprocess import check_call from os.path import join rx = '(.*zip$)|(.*rar$)|(.*r00$)' path = "/mnt/externa/folder" for root, dirs, files in os.walk(path): if not any(f.endswith(".mkv") for f in files): for file in files: res = re.match(rx, file) if res: # use os.path.join pth = join(root, file) # it can only be res.group(1) or one of the other two so we only need if/else. if res.group(1): print("Unzipping ",file, "...") check_call(["unzip" , pth, "-d", root]) else: check_call(["unrar","e", pth, root]) </code></pre> <p>You could also forget the rex and just use an if/elif and str.endswith:</p> <pre><code>for root, dirs, files in os.walk(path): if not any(f.endswith(".mkv") for f in files): for file in files: pth = join(root, file) if file.endswith("zip"): print("Unzipping ",file, "...") check_call(["unzip" , pth, "-d", root]) elif file.endswith((".rar",".r00")): check_call(["unrar","e", pth, root]) </code></pre> <p>if you really care about not repeating steps and speed, you can filter as you iterate you can collect by extension by slicing as you do the check for the .mkv and use for/else logic:</p> <pre><code>good = {"rar", "zip", "r00"} for root, dirs, files in os.walk(path): if not any(f.endswith(".mkv") for f in files): tmp = {"rar": [], "zip": []} for file in files: ext = file[-4:] if ext == ".mkv": break elif ext in good: tmp[ext].append(join(root, file)) else: for p in tmp.get(".zip", []): print("Unzipping ", p, "...") check_call(["unzip", p, "-d", root]) for p in tmp.get(".rar", []): check_call(["unrar", "e", p, root]) </code></pre> <p>That will short circuit on any match for a <code>.mkv</code> or else only iterate over any matches for <code>.rar</code> or <code>.r00</code> but unless you really care about efficiency I would use the second logic. </p> <p>To avoid overwriting you can unrar/unzip each to a new subdirectory using a counter to help create a new dir name:</p> <pre><code>from itertools import count for root, dirs, files in os.walk(path): if not any(f.endswith(".mkv") for f in files): counter = count() for file in files: pth = join(root, file) if file.endswith("zip"): p = join(root, "sub_{}".format(next(counter))) os.mkdir(p) print("Unzipping ",file, "...") check_call(["unzip" , pth, "-d", p]) elif file.endswith((".rar",".r00")): p = join(root, "sub_{}".format(next(counter))) os.mkdir(p) check_call(["unrar","e", pth, p]) </code></pre> <p>Each will be unpacked into a new directory under root i.e <code>root_path/sub_1</code> etc..</p> <p>You probably would have been better adding an example to your question but if the real problem is you only want one of .rar or .r00 then you can set a flag when you find any match for the .rar or .r00 and only unpack if the flag is not set:</p> <pre><code>for root, dirs, files in os.walk(path): if not any(f.endswith(".mkv") for f in files): found_r = False for file in files: pth = join(root, file) if file.endswith("zip"): print("Unzipping ",file, "...") check_call(["unzip", pth, "-d", root]) found_zip = True elif not found_r and file.endswith((".rar",".r00")) check_call(["unrar","e", pth, root]) found_r = True </code></pre> <p>If there is also only one zip you can set two flags and leave the loop where both are set.</p>
2
2016-09-05T13:21:53Z
[ "python", "loops" ]
How to iterate through every directory specified and run commands on files (Python)
39,330,146
<p>I have been working on a script that will check through every subdirectory in a directory and match files using regex and then use different commands based on what kind of a file it is. </p> <p>So what i have finished is the use of different commands based on regex matching. Right now it checks for either a .zip file, .rar file or .r00 file and uses different commands for each match. However i need help iterating through every directory and first check if there is a .mkv file in there, then it should just pass that directory and jump to the next, but if there is a match it should run the command and then when it's finished continue to the next directory.</p> <pre><code>import os import re rx = '(.*zip$)|(.*rar$)|(.*r00$)' path = "/mnt/externa/folder" for root, dirs, files in os.walk(path): for file in files: res = re.match(rx, file) if res: if res.group(1): print("Unzipping ",file, "...") os.system("unzip " + root + "/" + file + " -d " + root) elif res.group(2): os.system("unrar e " + root + "/" + file + " " + root) if res.group(3): print("Unraring ",file, "...") os.system("unrar e " + root + "/" + file + " " + root) </code></pre> <p>EDIT:</p> <p>Here is the code i have now:</p> <pre><code>import os import re from subprocess import check_call from os.path import join rx = '(.*zip$)|(.*rar$)|(.*r00$)' path = "/mnt/externa/Torrents/completed/test" for root, dirs, files in os.walk(path): if not any(f.endswith(".mkv") for f in files): found_r = False for file in files: pth = join(root, file) try: if file.endswith(".zip"): print("Unzipping ",file, "...") check_call(["unzip", pth, "-d", root]) found_zip = True elif not found_r and file.endswith((".rar",".r00")): check_call(["unrar","e","-o-", pth, root,]) found_r = True break except ValueError: print ("Oops! That did not work") </code></pre> <p>This script works mostly fine but sometimes i seem to run into issues when there are Subs in the folder, here is an error i message i get when i run the script:</p> <p>$ python unrarscript.py </p> <pre><code>UNRAR 5.30 beta 2 freeware Copyright (c) 1993-2015 Alexander Roshal Extracting from /mnt/externa/Torrents/completed/test/The.Conjuring.2013.1080p.BluRay.x264-ALLiANCE/Subs/the.conjuring.2013.1080p.bluray.x264-alliance.subs.rar No files to extract Traceback (most recent call last): File "unrarscript.py", line 19, in &lt;module&gt; check_call(["unrar","e","-o-", pth, root]) File "/usr/lib/python2.7/subprocess.py", line 541, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['unrar', 'e', '-o-', '/mnt/externa/Torrents/completed/test/The.Conjuring.2013.1080p.BluRay.x264-ALLiANCE/Subs/the.conjuring.2013.1080p.bluray.x264-alliance.subs.rar', '/mnt/externa/Torrents/completed/test/The.Conjuring.2013.1080p.BluRay.x264-ALLiANCE/Subs']' returned non-zero exit status 10 </code></pre> <p>I cannot really understand what is wrong about the code, so what im hoping is that some of you are willing to help me.</p>
3
2016-09-05T12:00:02Z
39,331,776
<p><code>re</code> is overkill for something like this. There's a library function for extracting file extensions, <code>os.path.splitext</code>. In the following example, we build an extension-to-filenames map and we use it both for checking the presence of <code>.mkv</code> files in constant time and for mapping each filename to the appropriate command.</p> <p>Note that you can unzip files with <a href="https://docs.python.org/2/library/zipfile.html" rel="nofollow">zipfile</a> (standard lib) and third-party packages <a href="http://stackoverflow.com/questions/17614467">are available for <code>.rar</code> files</a>.</p> <pre><code>import os for root, dirs, files in os.walk(path): ext_map = {} for fn in files: ext_map.setdefault(os.path.splitext(fn)[1], []).append(fn) if '.mkv' not in ext_map: for ext, fnames in ext_map.iteritems(): for fn in fnames: if ext == ".zip": os.system("unzip %s -d %s" % (fn, root)) elif ext == ".rar" or ext == ".r00": os.system("unrar %s %s" % (fn, root)) </code></pre>
0
2016-09-05T13:33:03Z
[ "python", "loops" ]
how to avoid to being identified as spam when using smtplib in python
39,330,309
<pre><code>import smtplib smtp = smtplib.SMTP() smtp.connect('smtp.163.com', '25') from_addr = 'XXX@163.com' to_addr = 'XXX@qq.com' smtp.login(from_addr, 'XXXX') msg = ('From: %s\r\nTo: %s\r\n' % (from_addr, to_addr)) msg = msg + '''Subject: Test Hi, I just test this format!! Just python send mail test - -.''' smtp.sendmail(from_addr, to_addr, msg) smtp.quit() </code></pre> <p>I dont know why the message has been always classified as spam, I will appreciate for any advice for me.</p>
1
2016-09-05T12:09:38Z
39,330,501
<p>I had a similar issue and the work-around was to set a message ID:</p> <pre><code>from email.utils import make_msgid msg['Message-ID'] = make_msgid() </code></pre> <p>It is just a clue, I do not know if this fix will fit for you.</p>
0
2016-09-05T12:20:26Z
[ "python", "smtp", "spam" ]