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
sequence
Django exclude field in admin if creator of this object is request user
39,974,962
<p>How can I exclude a field from the Django admin if the creator of this object is current user. Is there any way to customise my model in <code>admin.py</code>?</p> <pre><code>class Toys(BaseModel): name = models.CharField(max_length=255) tags = models.ManyToManyField(Tag, related_name='Item_tags') price = models.CharField(max_length=255) status = models.BooleanField(default=False) </code></pre>
0
2016-10-11T10:09:32Z
39,977,581
<p>First, you need to add a field to your model to store the creator.</p> <pre><code>class Toys(BaseModel): creator = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) tags = models.ManyToManyField(Tag, related_name='Item_tags') price = models.CharField(max_length=255) status = models.BooleanField(default=False) </code></pre> <p>The override the <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_fields" rel="nofollow"><code>get_fields</code></a> method of your model admin.</p> <pre><code>class ToyAdmin(admin.ModelAdmin): def get_fields(self, request, obj=None): fields = super(ToyAdmin, self).get_fields(request, obj) if obj is not None and request.user.is_authenticated(): # In Django 1.10+ use request.user.is_authenticated if obj.creator == request.user: fields = [f for f in fields if f != 'status'] return fields </code></pre> <p>In Django 1.11+, you can use <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_exclude" rel="nofollow"><code>get_exclude</code></a> instead.</p> <pre><code>class ToyAdmin(admin.ModelAdmin): def get_exclude(self, request, obj=None): if obj is not None and request.user.is_authenticated(): # In Django 1.10+ use request.user.is_authenticated if obj.creator == request.user: return ['status'] else: return [] </code></pre>
1
2016-10-11T12:46:06Z
[ "python", "django", "django-admin" ]
How to convert a list of strings into a list of integers - many things dont seem to work
39,974,985
<p>I have a problem. I would like to convert a list of strings with 594 elements, among them many empty, to a list of integers. I already looked up many answers here, but neither list comprehensions, neither map function seems to work. My command prompt simply says int argument must be a string or a number, not a list.</p> <p>Here is my code:</p> <pre><code>fname = raw_input("Enter file name: ") if len(fname) &lt; 1 : fname = "regex_sum_317625.txt" fh = open(fname) import re numlist = list() for line in fh: line = line.rstrip() numbers = re.findall('[0-9]+', line) numlist.append(numbers) print numlist listlength = len(numlist) print listlength intlist = [int(nums) for nums in numlist] print intlist </code></pre> <p>I tried many ways, but the problem always is that I try to do an operation on a list which is not allowed. Could you please help me, what should I do?</p>
0
2016-10-11T10:10:56Z
39,975,035
<p>The approaches you mentioned should work, but you're not building your data correctly; you don't have a list of strings but a list of lists - <code>re.findall</code> <em>returns</em> a list:</p> <pre><code>numbers = re.findall('[0-9]+', line) numlist.append(numbers) # appending a list to numlist </code></pre> <p>You should instead <em>extend</em> <code>numlist</code> with the results of <code>re.findall</code> using the <code>extend</code> method of the list:</p> <pre><code>numlist.extend(numbers) </code></pre> <p>The <code>list.extend</code> method will</p> <blockquote> <p><em>extend</em> the list by appending all the items in the given list.</p> </blockquote> <hr> <p>Since you're already familiar with comprehensions, you might as well use a comprehension in place of the <code>for</code> loop:</p> <pre><code>with open(fname) as fh: int_list = [int(item) for line in fh for item in re.findall('[0-9]+', line)] </code></pre> <p>I noticed, you did not call the <code>close</code> method of your file object <code>fh</code>. You can let Python do the cleanup for you by opening the file <em>with</em> a context manager, using the <code>with</code> statement.</p> <p>See <a href="http://stackoverflow.com/questions/9282967/how-to-open-a-file-using-the-open-with-statement">How to open a file using the open with statement</a> to learn more about this.</p>
3
2016-10-11T10:13:19Z
[ "python", "list" ]
Escape backslash in Python parameterized MySQL query
39,975,020
<p>I am working on excel files and database storaging, precisely I am storaging excel data to MySQL database. At some point I am executing this query:</p> <pre><code>query_for_id = ''' SELECT id FROM attivita WHERE attivita = '{0}' '''.format(attivita) </code></pre> <p>And when I print the query result I get this:</p> <p>' SELECT id FROM attivita WHERE attivita = \\'Manutenzione\\' '</p> <p>When it tries to match 'attivita' with the right value, taken from the excel, I got errors because of the '\\'.</p> <p>I tried changing the triple quotes from " " " to ' ' ', as well as using <code>connection.escape_string()</code>, but I didn't solve the problem. Can anyone help me figuring out the problem? Thank you in advance.</p>
0
2016-10-11T10:12:36Z
39,975,299
<p>I think that in your case better to use arguments to execute</p> <pre><code>query_for_id = ''' SELECT id FROM attivita WHERE attivita = %(attivita)s ''' cursor.execute(query_for_id, { 'attivita': attivita }) </code></pre> <p><a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html" rel="nofollow">https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html</a></p>
1
2016-10-11T10:29:29Z
[ "python", "mysql", "sql" ]
Ordered list of text and element data of an html element with beautifulsoup
39,975,101
<p>I would like to parse the content of the following div element with BeautifulSoup (bs4):</p> <pre><code>&lt;div&gt;&lt;!--block--&gt;&amp;nbsp; &amp;nbsp; Some text is here&amp;nbsp;&lt;br&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; - Another text&amp;nbsp;&lt;br&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; - More text&amp;nbsp;&lt;br&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/div&gt; </code></pre> <p>I need an ordered list of the content. The list shall contain the following items for this case:</p> <pre><code>- non-breaking space - non-breaking space - text data - br - non-breaking space ... - non-breaking space </code></pre> <p>Using tag.find_all() I can get a list of tags like "br" but all other data such as non-breaking space or text data is not returned by tag.find_all().</p>
1
2016-10-11T09:10:06Z
39,975,864
<p>tag.contents is what I was looking for.</p>
0
2016-10-11T11:06:57Z
[ "python", "html", "screen-scraping" ]
Subprocess calls the wrong version of 'time'
39,975,103
<p>I'm trying to call the shell keyword version of 'time' via </p> <pre><code>subprocess.check_output('time ls',stderr=subprocess.STDOUT,shell=True) </code></pre> <p>this is giving me the output (which is /usr/bin/time output):</p> <pre><code>0.00user 0.00system 0:00.00elapsed ?%CPU (0avgtext+0avgdata 1992maxresident)k 0inputs+0outputs (0major+85minor)pagefaults 0swaps </code></pre> <p>rather than the shell keyword output:</p> <pre><code>real 0m0.001s user 0m0.000s sys 0m0.000s </code></pre> <p>For some reason subprocess.check_output is using the /usr/bin/time version of time.</p> <p>Could someone tell me what is happening here? Thank you.</p>
0
2016-10-11T10:16:48Z
39,999,562
<p>It is because <code>time</code> is a also a built in function in Bash. So you need to specify that you want to use Bash as your shell:</p> <pre><code>print subprocess.check_output('time ls', stderr=subprocess.STDOUT,\ shell=True, executable='/bin/bash') </code></pre>
2
2016-10-12T13:14:50Z
[ "python", "linux", "shell", "time", "subprocess" ]
deleting printed line from screen
39,975,187
<p>I have code that runs for various lengths of time, during which a thread runs and displays a spinning cursor. When the code finishes it's task it prints some output, sets an event and the cursor stops. However this leaves the last character that was printed on the screen. I would like this to be removed.</p> <pre><code>def spinning_cursor(event): for j in itertools.cycle('/-\|'): if not event.is_set(): sys.stdout.write(j) sys.stdout.flush() time.sleep(0.1) sys.stdout.write('\b') else: #sys.stdout.write('\b') return </code></pre> <p>What I see on screen looks like this:</p> <pre><code>paul# Writing file... / info: file has been written paul# </code></pre> <p>I want the <code>/</code> to disappear when the event is set. I have tried <code>sys.stdout.write('\b')</code> before returning (uncommenting the line above) but this code seems to run after the subsequent prints in the main thread have, and it deletes nothing. Why is this? A more obvious example where I use <code>sys.stdout.write('TEST')</code> before returning in the <code>else</code>.</p> <pre><code>paul# Writing file... / info: file has been written TESTpaul# </code></pre> <p>I have found a solution via moving up one line before prints in the main thread but as there are many code paths it is messy:</p> <pre><code>CURSOR_UP_ONE = '\x1b[1A' sys.stdout.write(CURSOR_UP_ONE) </code></pre> <p>Here is how the spinning cursor is called. Any ideas?</p> <pre><code>def copy(): processing_flag = Event() Thread(target = spinning_cursor, kwargs = {'event': processing_flag}).start() try: ... except: ... finally: processing_flag.set() </code></pre>
2
2016-10-11T10:21:48Z
39,997,927
<p>The problem is that the main thread does not wait for the <em>spinning_cursor</em> one. So here is what happens (I could reproduce it):</p> <pre><code>main | spinning --------------------------------------------------------------------------- starts spinning thread | starts works | displays a *spinning* cursor ends working | == sets event | waits for running time continues and writes to stdout (*) | may be still waiting ... ... | writes its last backspace and exits (*) </code></pre> <p>(*) I could prove that the main thread begun writing on stdout even with a <code>write</code> occuring after the <code>finaly</code> block <strong>before</strong> the spinning thread can write its last backspace by writing a printable character at the end of the thread. That character was printed too late.</p> <p>How to fix: simply <code>join</code> the <em>spinning_cursor</em> thread:</p> <pre><code>def copy(): processing_flag = Event() t = Thread(target = spinning_cursor, kwargs = {'event': processing_flag}) t.start() try: ... except: ... finally: processing_flag.set() t.join() # waits for the thread to output its last backspace </code></pre>
1
2016-10-12T11:52:17Z
[ "python", "multithreading" ]
How to access the value of a ctypes.LP_c_char pointer?
39,975,430
<p>I have defined a struct : </p> <pre><code>class FILE_HANDLE(Structure): _fields_ = [ ("handle_bytes", c_uint), ("handle_type", c_int), ("f_handle", POINTER(c_char)) ] </code></pre> <p>The struct is initialised :</p> <pre><code>buf = create_string_buffer(f_handle.handle_bytes) fh = FILE_HANDLE(c_uint(8), c_int(0), buf) </code></pre> <p>I am passing it by reference to a function that populates it.</p> <pre><code>ret = libc.name_to_handle_at(dirfd, pathname, byref(fh), byref(mount_id), flags) </code></pre> <p>I can check with strace that the call works, but I have not been able to figure out how to access the value of fh.f_handle</p> <p>fh.f_handle type is <code>&lt;ctypes.LP_c_char object at 0x7f1a7ca17560&gt;</code><br> fh.f_handle.contents type is <code>&lt;ctypes.LP_c_char object at 0x7f1a7ca17560&gt;</code> but I get a SIGSEGV if I try to access its value.<br> How could I get 8 bytes from f_handle into a string or array ?</p>
0
2016-10-11T10:38:32Z
40,028,465
<p>fh.f_handle is shown as LP_c_char because you defined the struct that way.</p> <pre><code>buf = create_string_buffer(8) print type(buf) fh = FILE_HANDLE(c_uint(8), c_int(0), buf) print type(fh.f_handle) </code></pre> <p>Will output</p> <pre><code>&lt;class 'ctypes.c_char_Array_8'&gt; &lt;class 'ctypes.LP_c_char'&gt; </code></pre> <p>You have defined your struct to accept a pointer to a c_char. So when you try to access fh.f_handle it will expect the value to be a memory address containing the address to the actual single c_char.</p> <p>But by trying to input a c_char * 8 from the string buffer it will convert the first part of your buffer to a pointer.</p> <p>Python tries to dereference your char[0] which means that it will look for a memory address with the value of the character you have defined in char[0]. That memory address is not valid, so your interpreter will signal a SIGSEGV.</p> <p>Now to create a class which properly handles a variable length buffer is quite difficult. An easier option is to pass the buffer as an opaque handle, to access it afterwards you need to cast it back to a char array.</p> <p>Example:</p> <pre><code>class FILE_HANDLE(Structure): _fields_ = [ ("handle_bytes", c_uint), ("handle_type", c_int), ("f_handle", c_void_p) ] buf = create_string_buffer(8) buf = cast(buf, c_void_p) fh = FILE_HANDLE(c_uint(8), c_int(0), buf) f_handle_value = (c_char * fh.handle_bytes).from_address(fh.f_handle) </code></pre>
0
2016-10-13T18:33:08Z
[ "python", "ctypes" ]
How to access the value of a ctypes.LP_c_char pointer?
39,975,430
<p>I have defined a struct : </p> <pre><code>class FILE_HANDLE(Structure): _fields_ = [ ("handle_bytes", c_uint), ("handle_type", c_int), ("f_handle", POINTER(c_char)) ] </code></pre> <p>The struct is initialised :</p> <pre><code>buf = create_string_buffer(f_handle.handle_bytes) fh = FILE_HANDLE(c_uint(8), c_int(0), buf) </code></pre> <p>I am passing it by reference to a function that populates it.</p> <pre><code>ret = libc.name_to_handle_at(dirfd, pathname, byref(fh), byref(mount_id), flags) </code></pre> <p>I can check with strace that the call works, but I have not been able to figure out how to access the value of fh.f_handle</p> <p>fh.f_handle type is <code>&lt;ctypes.LP_c_char object at 0x7f1a7ca17560&gt;</code><br> fh.f_handle.contents type is <code>&lt;ctypes.LP_c_char object at 0x7f1a7ca17560&gt;</code> but I get a SIGSEGV if I try to access its value.<br> How could I get 8 bytes from f_handle into a string or array ?</p>
0
2016-10-11T10:38:32Z
40,048,004
<p>Everything actually looks right for what you've shown, but without seeing the explicit C definition of the structure and function you are calling it is difficult to see the problem.</p> <p>Here's an example that works with what you have shown. I inferred what the C definitions <em>should</em> be from what you have declared in Python, but most likely your definition is different if you get a segfault.</p> <h3>C Code (Windows)</h3> <pre><code>struct FILE_HANDLE { unsigned int handle_bytes; int handle_type; char* f_handle; }; __declspec(dllexport) int name_to_handle_at(int dirfd, char* pathname, struct FILE_HANDLE* fh, int* mount_id, int flags) { unsigned int i; printf("dirfd=%d pathname=%s fh-&gt;handle_bytes=%u fh-&gt;handle_type=%d flags=%d\n", dirfd, pathname, fh-&gt;handle_bytes, fh-&gt;handle_type, flags); for(i = 0; i &lt; fh-&gt;handle_bytes; ++i) fh-&gt;f_handle[i] = 'A' + i; *mount_id = 123; return 1; } </code></pre> <h3>Python code (Works in Python 2 and 3):</h3> <pre><code>from __future__ import print_function from ctypes import * class FILE_HANDLE(Structure): _fields_ = [("handle_bytes", c_uint), ("handle_type", c_int), ("f_handle", POINTER(c_char))] buf = create_string_buffer(8); fh = FILE_HANDLE(8,0,buf) libc = CDLL('test.dll') mount_id = c_int(0) ret = libc.name_to_handle_at(1,b'abc',byref(fh),byref(mount_id),7) print('mount_id =',mount_id.value) print('fh.f_handle =',fh.f_handle[:fh.handle_bytes]) </code></pre> <h3>Output</h3> <pre><code>dirfd=1 pathname=abc fh-&gt;handle_bytes=8 fh-&gt;handle_type=0 flags=7 mount_id = 123 fh.f_handle = b'ABCDEFGH' </code></pre> <p>Note that since the structure is declared as a pointer to a single character, printing <code>fh.f_handle.contents</code> would only print <code>b'A'</code>. Using slicing, I've instructed Python to index the pointer up to the length allocated.</p> <p>If this doesn't work for you, provide a <a href="http://stackoverflow.com/help/mcve">Minimal, Complete, and Verifiable example</a> (as I have) to reproduce your error exactly.</p>
0
2016-10-14T16:33:51Z
[ "python", "ctypes" ]
How to determine number of function/builtin/callable parameters programmatically?
39,975,486
<p>I want to be able to classify an unknown function/builtin/callable based on its number of arguments.</p> <p>I may write a piece of code like that:</p> <pre><code>if numberOfParameters(f) == 0: noParameters.append(f) elif numberOfParameters(f) == 1: oneParameter.append(f) else: manyParameters.append(f) </code></pre> <p>but I have no idea how to implement <code>numberOfParameters()</code>. <code>inspect.getargspec</code> does not work with builtins. I can not use exceptions, since it is potentially expensive to call the function.</p> <p>It would be great if the solution work with both Python 2.7 and Python 3.3+</p>
1
2016-10-11T10:41:18Z
39,975,814
<p>From Python 3.3</p> <blockquote> <p>New in version 3.3.</p> </blockquote> <p><a href="https://docs.python.org/3/library/inspect.html#introspecting-callables-with-the-signature-object" rel="nofollow"><strong>Introspecting callables with the Signature object</strong></a></p> <pre><code>&gt;&gt;&gt; import inspect &gt;&gt;&gt; inspect.signature(sorted).parameters mappingproxy(OrderedDict([('iterable', &lt;Parameter "iterable"&gt;), ('key', &lt;Parameter "key=None"&gt;), ('reverse', &lt;Parameter "reverse=False"&gt;)])) </code></pre> <p>And then you can count them, and do whatever you like.</p>
1
2016-10-11T11:03:41Z
[ "python", "python-2.7", "function", "python-3.x", "callable" ]
How to determine number of function/builtin/callable parameters programmatically?
39,975,486
<p>I want to be able to classify an unknown function/builtin/callable based on its number of arguments.</p> <p>I may write a piece of code like that:</p> <pre><code>if numberOfParameters(f) == 0: noParameters.append(f) elif numberOfParameters(f) == 1: oneParameter.append(f) else: manyParameters.append(f) </code></pre> <p>but I have no idea how to implement <code>numberOfParameters()</code>. <code>inspect.getargspec</code> does not work with builtins. I can not use exceptions, since it is potentially expensive to call the function.</p> <p>It would be great if the solution work with both Python 2.7 and Python 3.3+</p>
1
2016-10-11T10:41:18Z
39,976,055
<p>You can somewhat do this, but only in Python 3. This is when <code>ArgumentClinic</code> made information about the signature of objects available.</p> <p>Take note, not all built-ins are actually available as of right now, currently:</p> <pre><code>__import__ vars max print dir __build_class__ min iter round getattr next </code></pre> <p>do not expose information about their signature. For the rest <code>getargspec</code> (a thin wrapper around <code>getfullargspec</code>) and <code>Signature</code> would do.</p> <p>In Python 2, you only have the option of <code>getargspec</code> which doesn't do the trick for built-ins and probably never will. So, there's no solution that spans across python versions. For the most compatible solution, I'd use <code>getargspec</code> as of right now.</p> <p>As for the most simplistic way to check, just count the <code>args</code> from the <code>NamedTuple</code> returned:</p> <pre><code>def NumberOfParameters(f): try: r = getargspec(f) return len(r.args) # if it has kwargs, what do you do? except TypeError as e: print("Function {0} cannot be inspected".format(f.__name__)) </code></pre>
0
2016-10-11T11:17:59Z
[ "python", "python-2.7", "function", "python-3.x", "callable" ]
Dynamically select from a dataframe using the values of another
39,975,528
<p>Using Pandas.py, I have csv of this format, which is dynamically created:</p> <pre><code>time,name,status 2016-10-09 00:15:50,10.0.0.24,REJECTED 2016-10-09 00:15:50,10.0.0.24,REJECTED 2016-10-09 00:15:54,10.0.0.24,accepted 2016-10-09 00:15:57,10.0.0.24,accepted 2016-10-09 00:15:58,10.0.0.103,accepted 2016-10-09 00:15:59,10.0.0.24,accepted 2016-10-09 00:16:08,10.0.0.24,accepted </code></pre> <p>This is a raw log file of events from numerous IP addresses.</p> <p>I then group the data with groupby and make the following dataframes (here in csv format). </p> <p>An event count grouped by time (here 20 mins):</p> <pre><code>time,10.0.0.103,10.0.0.24 2016-10-09 00:00:00,36,44 2016-10-09 00:20:00,143,199 2016-10-09 00:40:00,195,182 2016-10-09 01:00:00,174,200 2016-10-09 01:20:00,176,212 2016-10-09 01:40:00,165,186 2016-10-09 02:00:00,167,218 2016-10-09 02:20:00,171,222 2016-10-09 02:40:00,189,221 </code></pre> <p>And a summary table:</p> <pre><code>name,count,numReject,numAccept,percentAccept 10.0.0.103,9476,1,9475,99 10.0.0.24,12030,0,12030,100 </code></pre> <p>I need a column in the summary table which defines when a given IP last had an event. A 'last seen' column. Desired output:</p> <pre><code>name,count,numReject,numAccept,percentAccept, lastSeen 10.0.0.103,9476,1,9475,99,2016-10-09 00:15:58 10.0.0.24,12030,0,12030,100,2016-10-09 00:16:08 </code></pre> <p>I have tried loops, but I feel like that is entirely the wrong way to go about things here. I can do it statically with a boolean iloc mask given a known IP value, but with an unknown number of IP addresses I cannot figure out where to begin!</p>
1
2016-10-11T10:43:54Z
39,979,180
<p><strong><em>assumed imports</em></strong></p> <pre><code>import pandas as pd import numpy as np </code></pre> <p><strong><em>general solution</em></strong><br> for more than 2 types of status</p> <pre><code>g = df.groupby('name') pd.concat([ g.status.size().rename(''), g.time.last().rename(''), g.status.value_counts().unstack(fill_value=0), g.status.value_counts(normalize=True).unstack(fill_value=0) ], axis=1, keys=['Count', 'Last', 'status_counts', 'status_frequency']) \ .rename_axis([None, None], axis=1) \ .rename_axis([None]) </code></pre> <p><a href="https://i.stack.imgur.com/b6vjA.png" rel="nofollow"><img src="https://i.stack.imgur.com/b6vjA.png" alt="enter image description here"></a></p> <p><strong><em>tailored solution</em></strong><br> assuming just <code>accepted</code> and <code>REJECTED</code></p> <pre><code>df['status_bool'] = df.status.eq('accepted') * 1 summary = df.groupby('name').agg( dict(status=dict(Count='count'), status_bool=dict(Accepted='sum', Freq=lambda x: np.sum(x) * 1. / np.size(x)), time=dict(Last='last') )) summary.columns = summary.columns.droplevel(0) summary </code></pre> <p><a href="https://i.stack.imgur.com/YCwGi.png" rel="nofollow"><img src="https://i.stack.imgur.com/YCwGi.png" alt="enter image description here"></a></p>
0
2016-10-11T14:08:32Z
[ "python", "csv", "pandas" ]
How get a fragment of the code from External HTML (web site) with python
39,975,555
<p>i want to get a fragment from a HTML website with pithon.</p> <p>for example from the url <a href="http://steven-universe.wikia.com/wiki/Steven_Universe_Wiki" rel="nofollow">http://steven-universe.wikia.com/wiki/Steven_Universe_Wiki</a> i want to get the text in the box "next Episode", as a string , how can i get it?</p>
-3
2016-10-11T10:45:04Z
39,976,110
<p>First of all download BeautifulSoup latest version from <a href="https://pypi.python.org/pypi/beautifulsoup4" rel="nofollow">here</a> and requests from <a href="http://docs.python-requests.org/en/master/" rel="nofollow">here</a> </p> <pre><code>from bs4 import BeautifulSoup import requests con = requests.get(url).content soup = BeautifulSoup(con) text = soup.find_all("a",href="/wiki/Gem_Harvest").text; print(link) </code></pre>
0
2016-10-11T11:21:08Z
[ "python", "html" ]
Python 27: How to fix/store a value to a method to preserve its interface?
39,975,659
<p>If everything is an object in python then why does the following not work?</p> <pre><code>class Hello(object): def hello(self): print(x) h = Hello() h.hello.x = "hello world" </code></pre> <p>When doing this I get:</p> <pre><code>AttributeError: 'instancemethod' object has no attribute 'value' </code></pre> <p>A way which I can achieve this is by using partial however I am not sure what the effects of that would be on an object. Is there another way to achieve this?</p> <pre><code>from functools import partial class Hello(object): def hello(self, x): print(x) h = Hello() newMethod = partial(h.hello, "helloworld") newMethod() </code></pre> <p>Okay, from the comments below, people want a "real" scenario one example which can be considered as the following:</p> <pre><code>file.txt contains the following list ["ItemID1", "ItemID2", "ItemID3", "ItemID4"] def BindMethods(self): # ["ItemID1", "ItemID2", "ItemID3", "ItemID4"] items = readFromFile("file.txt") self.bind(AN_EVENT, GenericMethod) def GenericMethod(self, i, event): # The person calling this method knows that the method # only accepts a single argument, not two. # I am attempting to preserve the interface which I do not have control over data = generateDataFromID(i) table[i] = data </code></pre> <p>The idea here being that you bind a method to an event whereby the caller is expecting the method of a specific signature i.e. a single input argument.</p> <p>But at the point of binding you want to pass in some extra information down to the handler. You don't know how much information you want to pass down since it is variable.</p> <p>A expanded/compile time version of the same thing would be something like this:</p> <pre><code>file.txt contains the following list ["ItemID1", "ItemID2", "ItemID3", "ItemID4"] def BindMethods(self): # ["ItemID1", "ItemID2", "ItemID3", "ItemID4"] items = readFromFile("file.txt") self.bind(AN_EVENT, self.Item1Method) self.bind(AN_EVENT, self.Item2Method) self.bind(AN_EVENT, self.Item3Method) ...... def Item1Method(self, event): data = generateDataFromID("Item1") table["Item1ID"] = data def Item2Method(self, event): data = generateDataFromID("Item2") table["Item2ID"] = data </code></pre>
0
2016-10-11T10:52:37Z
39,975,790
<p>The <code>x</code> in the first version is not defined: the way you write the code, it should be a global variable; the way you use it, it should be an attribute of the object. You want to do something like</p> <pre><code>class Hello(object): def __init__(self, x): self.x = x def hello(self): print(self.x) h = Hello("Hello World") </code></pre>
-1
2016-10-11T11:01:38Z
[ "python", "python-2.7" ]
Python 27: How to fix/store a value to a method to preserve its interface?
39,975,659
<p>If everything is an object in python then why does the following not work?</p> <pre><code>class Hello(object): def hello(self): print(x) h = Hello() h.hello.x = "hello world" </code></pre> <p>When doing this I get:</p> <pre><code>AttributeError: 'instancemethod' object has no attribute 'value' </code></pre> <p>A way which I can achieve this is by using partial however I am not sure what the effects of that would be on an object. Is there another way to achieve this?</p> <pre><code>from functools import partial class Hello(object): def hello(self, x): print(x) h = Hello() newMethod = partial(h.hello, "helloworld") newMethod() </code></pre> <p>Okay, from the comments below, people want a "real" scenario one example which can be considered as the following:</p> <pre><code>file.txt contains the following list ["ItemID1", "ItemID2", "ItemID3", "ItemID4"] def BindMethods(self): # ["ItemID1", "ItemID2", "ItemID3", "ItemID4"] items = readFromFile("file.txt") self.bind(AN_EVENT, GenericMethod) def GenericMethod(self, i, event): # The person calling this method knows that the method # only accepts a single argument, not two. # I am attempting to preserve the interface which I do not have control over data = generateDataFromID(i) table[i] = data </code></pre> <p>The idea here being that you bind a method to an event whereby the caller is expecting the method of a specific signature i.e. a single input argument.</p> <p>But at the point of binding you want to pass in some extra information down to the handler. You don't know how much information you want to pass down since it is variable.</p> <p>A expanded/compile time version of the same thing would be something like this:</p> <pre><code>file.txt contains the following list ["ItemID1", "ItemID2", "ItemID3", "ItemID4"] def BindMethods(self): # ["ItemID1", "ItemID2", "ItemID3", "ItemID4"] items = readFromFile("file.txt") self.bind(AN_EVENT, self.Item1Method) self.bind(AN_EVENT, self.Item2Method) self.bind(AN_EVENT, self.Item3Method) ...... def Item1Method(self, event): data = generateDataFromID("Item1") table["Item1ID"] = data def Item2Method(self, event): data = generateDataFromID("Item2") table["Item2ID"] = data </code></pre>
0
2016-10-11T10:52:37Z
39,975,900
<p><strong>This answer was referring to the question before it was editet; it might not be appropriate anymore.</strong></p> <p>Actually, there is a solution to this question. In python 3, you can directly assign attributes to bound methods, whereas in python 2.7 it is not that straightforward.</p> <p>Look at a class definition like this:</p> <pre><code>class Hello(object): def hello(self): print(self.hello.x) </code></pre> <p>In regular use (instantiate and subsequently call the instance method <code>hello()</code>), the implementation would fail due to the missing attribute <code>x</code>:</p> <pre><code>h = Hello() h.hello() &gt;&gt;&gt; AttributeError: 'function' object has no attribute 'x' </code></pre> <p>Changing the code a bit (<strong>Warning:</strong> Hack.) to something like this:</p> <pre><code>class Hello(object): def hello(self): if not hasattr(self.hello, 'x'): self.hello.__dict__['x'] = 0 print(self.hello.x) </code></pre> <p>Would let you use the class implementation just as usual:</p> <pre><code>h = Hello() h.hello() &gt;&gt;&gt; 0 print(h.hello.x) &gt;&gt;&gt; 0 </code></pre> <p>Thus, you <em>can</em> bind attributes to bound methods, but the way you tried it only works in python 3.</p> <p><strong>Whatever this is good for, you may want to ask yourself whether it is the best way to achieve the desired behavior.</strong></p>
4
2016-10-11T11:09:23Z
[ "python", "python-2.7" ]
Python 27: How to fix/store a value to a method to preserve its interface?
39,975,659
<p>If everything is an object in python then why does the following not work?</p> <pre><code>class Hello(object): def hello(self): print(x) h = Hello() h.hello.x = "hello world" </code></pre> <p>When doing this I get:</p> <pre><code>AttributeError: 'instancemethod' object has no attribute 'value' </code></pre> <p>A way which I can achieve this is by using partial however I am not sure what the effects of that would be on an object. Is there another way to achieve this?</p> <pre><code>from functools import partial class Hello(object): def hello(self, x): print(x) h = Hello() newMethod = partial(h.hello, "helloworld") newMethod() </code></pre> <p>Okay, from the comments below, people want a "real" scenario one example which can be considered as the following:</p> <pre><code>file.txt contains the following list ["ItemID1", "ItemID2", "ItemID3", "ItemID4"] def BindMethods(self): # ["ItemID1", "ItemID2", "ItemID3", "ItemID4"] items = readFromFile("file.txt") self.bind(AN_EVENT, GenericMethod) def GenericMethod(self, i, event): # The person calling this method knows that the method # only accepts a single argument, not two. # I am attempting to preserve the interface which I do not have control over data = generateDataFromID(i) table[i] = data </code></pre> <p>The idea here being that you bind a method to an event whereby the caller is expecting the method of a specific signature i.e. a single input argument.</p> <p>But at the point of binding you want to pass in some extra information down to the handler. You don't know how much information you want to pass down since it is variable.</p> <p>A expanded/compile time version of the same thing would be something like this:</p> <pre><code>file.txt contains the following list ["ItemID1", "ItemID2", "ItemID3", "ItemID4"] def BindMethods(self): # ["ItemID1", "ItemID2", "ItemID3", "ItemID4"] items = readFromFile("file.txt") self.bind(AN_EVENT, self.Item1Method) self.bind(AN_EVENT, self.Item2Method) self.bind(AN_EVENT, self.Item3Method) ...... def Item1Method(self, event): data = generateDataFromID("Item1") table["Item1ID"] = data def Item2Method(self, event): data = generateDataFromID("Item2") table["Item2ID"] = data </code></pre>
0
2016-10-11T10:52:37Z
39,976,593
<p>After your edit, this seems to me as if you seek a possibility to <em>route</em> certain events to certain functions, right?</p> <p>Instead of binding new attributes to existing <em>instance methods</em>, you should think about setting up a clean and extendable event routing system.</p> <h2>A Basic Routing Core</h2> <p>While usually application of the <code>singleton</code> pattern always is a good point to ask oneself whether one is following the right concept, it totally makes sense here. The core of your routing is something similar to this:</p> <pre><code>def singleton(cls): instance = cls() instance.__call__ = lambda: instance return instance @singleton class EventRouter(object): def __init__(self): self._routes = dict() def bind(self, key, func): self._routes[key] = func def route(self, key): if key in self._routes.keys(): return self._routes[key]() else: raise KeyError('Unbound routing key: {}'.format(key)) </code></pre> <p>The <code>EventRouter</code> is a singleton class that can bind functions to certain keys and is furthermore able to route occurring events to their desired destination functions.<br> You now kan bind an event to a desired function during runtime:</p> <pre><code>def my_event_function(): print('An event was handled.') EventRouter.bind('E_MYEVT', my_event_function) # If you are iterating over events (for example drawn from a file), # you can direct them to their functions: for e in ['E_MYEVT', 'E_WHATEVT', 'E_NOEVT']: EventRouter.route(e) </code></pre> <h2>A Routing Decorator</h2> <p>If required, you can set up another decorator that can be used to directly bind methods to a certain event type:</p> <pre><code>def eventroute(key): def register_method(call): EventRouter.bind(key, call) return register_method @eventroute('E_MYEVT') def handle_myevt(): print('Handling event: E_MYEVT') @eventroute('E_WHATEVT') def handle_whatevt(): print('Handling event: E_WHATEVT') if __name__ == '__main__': for e in ['E_MYEVT', 'E_WHATEVT']: EventRouter.route(e) &gt;&gt;&gt; Handling event: E_MYEVT &gt;&gt;&gt; Handling event: E_WHATEVT </code></pre> <h2>Passing Arguments to the Route Endpoints</h2> <p>If you want to pass arguments to the endpoints, just extend the calls by optional keyword arguments <code>**kwargs</code> when forwarding the call:</p> <p>In <code>EventRouter</code> class, change <code>route</code> method to:</p> <pre><code>def route(self, key, **kwargs): if key in self._routes.keys(): return self._routes[key](**kwargs) else: raise KeyError('Unbound routing key: {}'.format(key)) </code></pre> <p>For your endpoints, set the desired arguments. In this example, I use the argument <code>filename</code>:</p> <pre><code>@eventroute(...) def handle_...(filename): print('Handling event: ...') print(filename) </code></pre> <p>And when dispatching your events, provide the required argument as kwarg:</p> <pre><code>events = ['E_MYEVT', 'E_WHATEVT'] for e in events: EventRouter.route(e, filename='whatever.jpg') &gt;&gt;&gt; Handling event: E_MYEVT &gt;&gt;&gt; whatever.jpg &gt;&gt;&gt; Handling event: E_WHATEVT &gt;&gt;&gt; whatever.jpg </code></pre> <h2>Where to go</h2> <p>This is a brief overview of just a very basic setup.<br> You can extend your <code>EventRouter</code> to be arbitrarily complex, e.g. add routing keys in a multi-layered hierarchy, or the like. Furthermore, you can add more arguments to your methods. You can even think about extending the <code>eventroute</code> decorator to define the <code>kwargs</code> that shall be passed to the endpoint function to keep the function signatures as generic as possible.</p> <p>Might seem like overkill, but structures like these are pretty neat and can be extended by anyone who imports your library/script and wants to add her own endpoints for individual events.</p>
2
2016-10-11T11:49:04Z
[ "python", "python-2.7" ]
Competitive Programming Python: Repeated sum of digits Error
39,975,692
<p>Don't know It's right place to ask this or not. But I was feeling completely stuck. Couldn't find better way to solve it.</p> <p>I am newbie in competitive Programming. I was solving <code>Repeated sum of digits problem</code> Here is The Question.</p> <p><code>Given an integer N, recursively sum digits of N until we get a single digit.</code></p> <p>Example:-</p> <pre><code>Input: 2 123 9999 Output:- 6 9 </code></pre> <p>Here is my code:-</p> <pre><code>def sum(inp): if type(inp) == int: if len(str(inp)) &lt;= 1: return inp else: a = list(str(inp)) while len(a) &gt; 1: b = 0 for i in a: b+= int(i) a = list(str(b)) return b t = int(raw_input()) for i in range(0,t): print sum(i) </code></pre> <p>While submitting it gave My following error:-</p> <pre><code>Wrong !! The first test case where your code failed: Input: 42 Its Correct output is: 6 And Your Output is: 0 </code></pre> <p>However When I tested my code personally using <code>42</code> It's perfectly gives me correct Output <code>6</code>. </p> <p>Here is the link of question:- <a href="http://www.practice.geeksforgeeks.org/problem-page.php?pid=1398" rel="nofollow">Repeated sum of digits Error</a></p>
2
2016-10-11T10:54:47Z
39,976,109
<p>You have not implemented the code properly. You are iterating over <code>i</code> from <code>0</code> to <code>t</code>. Why?? The methodology goes as follows:</p> <p><code>N = 12345</code></p> <p>Calculate the sum of digits(1+2+3+4+5 = 15).</p> <p>Check if it is less than 10. If so, then the current sum is the answer.. If not.. follow the same procedure by setting <code>N = 15</code></p> <p>Here is the code:</p> <pre><code>def sum(inp): while inp &gt; 9: num = inp s = 0 while num &gt; 0: s = s + num%10 num = num/10 inp = s return inp t = int(raw_input()) for i in range(t): n = int(raw_input()) print sum(n) </code></pre> <p><strong>Edit</strong>: I think you are iterating till <code>t</code> because you have considered <code>t</code> to be the number of testcases. So, inside the <code>for</code> loop, you should take another input for <code>N</code> for each of the testcase. [This is based on the <code>input</code> and <code>output</code> that you have provided in the question]</p> <p><strong>Edit-2</strong>: I have changed the code a bit. The question asks us to find the repeated sum of <code>t</code> numbers. For that, I have added a loop where we input a number <code>n</code> corresponding to each testcase and find its repeated sum.</p>
2
2016-10-11T11:21:08Z
[ "python" ]
undefined symbol: PyOS_mystrnicmp
39,975,712
<p>I tried installing <code>pysqlite</code>, but I'm having some trouble using it.</p> <pre><code>&gt;&gt;&gt; import pysqlite2.dbapi2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/data/.pyenv/versions/2.7.5/lib/python2.7/site-packages/pysqlite2/dbapi2.py", line 28, in &lt;module&gt; from pysqlite2._sqlite import * ImportError: /data/.pyenv/versions/2.7.5/lib/python2.7/site-packages/pysqlite2/_sqlite.so: undefined symbol: PyOS_mystrnicmp </code></pre> <p>I think I might be missing some Python headers. Where do I find them? I'm using CentOS with CPython 2.7.5.</p>
0
2016-10-11T10:56:08Z
39,995,741
<p>As <a href="https://groups.google.com/forum/#!topic/python-sqlite/04Ocf7aP1so" rel="nofollow">https://groups.google.com/forum/#!topic/python-sqlite/04Ocf7aP1so</a> points out, a <a href="http://bugs.python.org/issue18603" rel="nofollow">bug</a> was reported that appears to be fixed in newer versions of Python. Upgrading to a later version of Python 2.7 did the trick for me.</p>
0
2016-10-12T09:57:25Z
[ "python", "cpython" ]
pandas ewm and rolling methods to not fill in NAs
39,975,812
<p>Is there a parameter for ewm and rolling methods to not fill in the NAs?</p> <pre><code>&gt;&gt;&gt; A = pd.Series([1,2,3,4,np.nan,5,6]) &gt;&gt;&gt; A 0 1.0 1 2.0 2 3.0 3 4.0 4 NaN 5 5.0 6 6.0 dtype: float64 &gt;&gt;&gt; eA = A.ewm(alpha = 0.5, ignore_na=True).mean() &gt;&gt;&gt; eA 0 1.000000 1 1.666667 2 2.428571 3 3.266667 4 3.266667 # I want this to be NA, don't fill in 5 4.161290 6 5.095238 dtype: float64 </code></pre> <p>Of course this is easily solved by </p> <pre><code>eA[A.isnull()] = np.nan </code></pre> <p>But this takes some unnecessary running time, and the need to think of a variable name for every rolling function is bothersome when you have more than a few.</p>
1
2016-10-11T11:03:35Z
39,977,211
<p>Unfortunately this currently isn't supported in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.ewm.html#pandas.Series.ewm" rel="nofollow"><code>ewm</code></a>, you'd have to overwrite with <code>NaN</code> using your proposed method or filter our the <code>NaN</code> rows so that <code>ewm</code> produces a <code>Series</code> preserving the original index, you can then either use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.combine_first.html" rel="nofollow"><code>combine_first</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.reindex.html" rel="nofollow"><code>reindex</code></a> to re-insert the <code>NaN</code> rows:</p> <pre><code>In [32]: A = pd.Series([1,2,3,4,np.nan,5,6]) eA = A[A.notnull()].ewm(alpha = 0.5, ignore_na=True).mean() eA.combine_first(A) Out[32]: 0 1.000000 1 1.666667 2 2.428571 3 3.266667 4 NaN 5 4.161290 6 5.095238 dtype: float64 In [33]: eA.reindex(A.index) Out[33]: 0 1.000000 1 1.666667 2 2.428571 3 3.266667 4 NaN 5 4.161290 6 5.095238 dtype: float64 </code></pre>
1
2016-10-11T12:25:54Z
[ "python", "pandas" ]
Handling accents in Oracle from Python
39,975,885
<p>I have the following code:</p> <pre><code> #!/usr/bin/python # coding=UTF-8 import cx_Oracle def oracle_connection(user, passwd, host, port, service): oracle_con_details = user+'/'+passwd+'@'+host+':'+port+'/'+service try: oracle_connection = cx_Oracle.connect(oracle_con_details) except cx_Oracle.DatabaseError as e: error, = e.args if error.code == 1017: log.warning('Please check your credentials.') else: log.error('Database connection error: ') log.error(e) return oracle_connection user_oracle = "user" passw_oracle = "pass" host_oracle = "host" port_oracle = "port" service_oracle = "service" con_oracle = oracle_connection(user_oracle, passw_oracle, host_oracle, port_oracle, service_oracle) query = """ SELECT COUNT(*) FROM TABLE WHERE MYDATA = 'REUNIÓN'""" cursor_oracle = con_oracle.cursor() cursor_oracle.execute(query) data_tuple = cursor_oracle.fetchall() </code></pre> <p>Of course, Oracle credentials and query are just examples. Notice the query has 'Ó' character. This is the one giving me the following error:</p> <blockquote> <p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xd3' in position 49: ordinal not in range(128)</p> </blockquote> <p>I've tried the solutions from some other questions here:</p> <pre><code>query.decode('utf-8') query.encode('utf-8') query.decode('unicode') query.encode('unicode') </code></pre> <p>I understand my string (query) is encoded in unicode but I just don't understand why decoding it in utf-8 doesn't work. </p> <p>Because of this my query doesn't get to Oracle how it should.</p> <p><strong>ADDITIONAL INFO:</strong></p> <p>Based on <a href="http://So%20your%20variable%20either%20contains%20a%20unicode%20string%20or%20a%20byte%20string.%20If%20it%20is%20a%20unicode%20string%20you%20can%20just%20do%20appName.encode(%22utf-8%22).">this</a> answer I thought mystring.encode('utf-8) would work.</p> <p>I cheked the type of my string with <a href="http://stackoverflow.com/questions/4987327/how-do-i-check-if-a-string-is-unicode-or-ascii">this</a> method just in case and the result is 'ordinary string'.</p>
1
2016-10-11T11:08:20Z
40,016,537
<p>Adding this to my python code solved it. </p> <pre><code>import os os.environ["NLS_LANG"] = "SPANISH_SPAIN.UTF8" </code></pre>
1
2016-10-13T08:58:45Z
[ "python", "oracle", "unicode", "ascii" ]
Error ValueError: cannot reindex from a duplicate axis because of concatenating dataframes
39,975,957
<p>I implemented experimental environment in my project. </p> <p>This component is based on Scikit learn. </p> <p>In this compnent I read the given CSV into pandas dataframe. After that I selected the best features and reduced the dimensions of the given dataframe from 100 to 5. After that I added to this reduced dataframe the removed ID column for future use. This coloumn was dropped by the dimension reduction process. </p> <p>Everything works fine until I changed my code to read all CSV files and return one union dataframe:</p> <p>Please look on the next code: Reading all CSV:</p> <pre><code>dataframes = [] from os import listdir from os.path import isfile, join files_names = [f for f in listdir(full_path_directory_files) if isfile(join(full_path_directory_files, f))] for file_name in files_names: full_path_file = full_path_directory_files + file_name data_frame = pd.read_csv(full_path_file, index_col=None, compression="infer") dataframes.append(dataframe) </code></pre> <p>After that I made concatenation between the dataframes</p> <pre><code>features_dataframe = pd.concat(dataframes, axis=0) </code></pre> <p>I also checked it. I created two different dataframes with shape = (200, 100) and after concatenating it turned to (400, 100)</p> <p>After that the dataframe was sent into the following method:</p> <pre><code> def _reduce_dimensions_by_num_of_features(self, features_dataframe, truth_dataframe, num_of_features): print("Create dataframe with the {0} best features".format(num_of_features)) ## In those functions I got the ids and their class ids, id_series = self._create_ids_by_dataframe(features_dataframe) features_dataframe_truth_class = self._extract_truth_class_by_truth_dataframe(truth_dataframe, ids) k_best_classifier = SelectKBest(score_func=f_classif, k=num_of_features) k_best_features = k_best_classifier.fit_transform(features_dataframe, features_dataframe_truth_class) reduced_dataframe_column_names = self._get_k_best_feature_names(k_best_classifier, features_dataframe) reduced_dataframe = pd.DataFrame(k_best_features, columns=reduced_dataframe_column_names) </code></pre> <p>Now I retrieved the ID column:</p> <pre><code> reduced_dataframe["Id"] = id_series </code></pre> <p>The software it failed on the message:</p> <pre><code>ValueError: cannot reindex from a duplicate axis </code></pre> <p>This is occurred only after the concation of the dataframes.</p> <p>How can I add the column of the IDs into the dataframe without getting error??</p>
1
2016-10-11T11:12:11Z
40,014,731
<p>I found the problem:</p> <p>After the concatenation of the dataframes, the index is changed and when we add the row :</p> <pre><code>reduced_dataframe["Id"] = id_series </code></pre> <p>We got an error.</p> <p>The solution is to reset the index : </p> <pre><code>features_dataframe = pd.concat(dataframes, axis=0) features_dataframe.reset_index(drop=True, inplace=True) </code></pre>
0
2016-10-13T07:23:58Z
[ "python", "csv", "scikit-learn" ]
Django Migrations - what benefits do they bring?
39,975,996
<p>I am pretty sure that <a href="https://docs.djangoproject.com/en/1.10/topics/migrations/" rel="nofollow">Django Migrations</a> bring many benefits to the Django platform. I am just having a hard time identifying those benefits.</p> <p>Maybe someone could explain to me in what circumstances Django Migrations can be beneficial. In what way does it benefit the work of a software developer?</p> <p>I could not find that kind of information in the documentation. Maybe it is so obvious that there is no need.</p> <p>Anyway, thanks in advance for any hint.</p> <p><strong>Edit:</strong> My apologies for not being accurate enough. The way I wrote above I appear to imply that Django Migrations do not do anything valuable, which is not what I intended.</p> <p>I know that Django Migrations are meant to keep the database in sync with my Models. What I find annoying is that, sometimes, things go wrong and I have to reset the migrations manually. Still, after your replies I believe I have a better understanding why the Django Migrations are the way they are.</p>
-3
2016-10-11T11:14:22Z
39,976,115
<p>The migrations make it easy to maintain database updates.</p> <p>You control the database through Django models. E.g. Add a field to one of the models.</p> <p>Then you can make migrations and migrate and these changes will be replicated in your SQL database by the addition of this field.</p>
1
2016-10-11T11:21:19Z
[ "python", "django" ]
Django Migrations - what benefits do they bring?
39,975,996
<p>I am pretty sure that <a href="https://docs.djangoproject.com/en/1.10/topics/migrations/" rel="nofollow">Django Migrations</a> bring many benefits to the Django platform. I am just having a hard time identifying those benefits.</p> <p>Maybe someone could explain to me in what circumstances Django Migrations can be beneficial. In what way does it benefit the work of a software developer?</p> <p>I could not find that kind of information in the documentation. Maybe it is so obvious that there is no need.</p> <p>Anyway, thanks in advance for any hint.</p> <p><strong>Edit:</strong> My apologies for not being accurate enough. The way I wrote above I appear to imply that Django Migrations do not do anything valuable, which is not what I intended.</p> <p>I know that Django Migrations are meant to keep the database in sync with my Models. What I find annoying is that, sometimes, things go wrong and I have to reset the migrations manually. Still, after your replies I believe I have a better understanding why the Django Migrations are the way they are.</p>
-3
2016-10-11T11:14:22Z
39,976,321
<p>Just as your code changes over time, so does your database layout. Models get new fields, your App gets new models etc.</p> <p>Your code can be changed and uploaded to your server, replacing old files.</p> <p>Your database however needs to persistent. You cannot just overwrite your database with a different one and ask 10.000 users to sign up again if you decide your user model needs a new field. Also, every developer in your team has their own database on their machine. The schema of these databases need to be in sync.</p> <p>Migrations allow you to change your database in a controlled way: Any change you make to your database will be represented in a migration and may be "played back" on a different machine. Some migration systems also support both up and down migrations, allowing migrations to be played forward and backwards (order matters!).</p> <p>The fact that migrations are part of your codebase makes it easy for them to version tracked and shipped using your usual code deployment method.</p> <p>Before migrations Django allowed to "sync" your model with your database. This enabled some non-destructive changes in your database. However more complex scenarios in which certain operations need to be done during sync could not be achieved.</p> <p>Migrations, being Python code, on the other hand allow for custom code to be run during a migration. This allows much more flexible and finely controlled changes in your database.</p>
2
2016-10-11T11:32:50Z
[ "python", "django" ]
Django Migrations - what benefits do they bring?
39,975,996
<p>I am pretty sure that <a href="https://docs.djangoproject.com/en/1.10/topics/migrations/" rel="nofollow">Django Migrations</a> bring many benefits to the Django platform. I am just having a hard time identifying those benefits.</p> <p>Maybe someone could explain to me in what circumstances Django Migrations can be beneficial. In what way does it benefit the work of a software developer?</p> <p>I could not find that kind of information in the documentation. Maybe it is so obvious that there is no need.</p> <p>Anyway, thanks in advance for any hint.</p> <p><strong>Edit:</strong> My apologies for not being accurate enough. The way I wrote above I appear to imply that Django Migrations do not do anything valuable, which is not what I intended.</p> <p>I know that Django Migrations are meant to keep the database in sync with my Models. What I find annoying is that, sometimes, things go wrong and I have to reset the migrations manually. Still, after your replies I believe I have a better understanding why the Django Migrations are the way they are.</p>
-3
2016-10-11T11:14:22Z
39,977,761
<p>You make some changes to your database, you:</p> <ul> <li>Change the default value of a field</li> <li>You update all user entries so that their "name" field begins with a capital letter</li> <li>You remove a model altogether</li> </ul> <p>So now you need to modify your database schema, get to it!</p> <p>Chances are you haven't bothered to learn how to write SQL yet so you need to do that first... oh and then its sensitive data you're dealing with so you need to make sure you don't make any mistakes when your deleting that table (Bobby tables much?).. </p> <p>This doesn't sound fun at all, and its error prone. Especially as you hire new people and then you need to make sure they don't delete EvilCorps data by mistake.</p> <p>So, instead you opt for the framework that abstracts all these operations into a language that you write anyway, that you store within your source control, tagged to the developer that committed them.</p> <p>So whats the benefit to the developer? Time and abstraction - the benefits of which I hope are obvious.</p>
0
2016-10-11T12:55:48Z
[ "python", "django" ]
Python Pillow: Make gradient for transparency
39,976,028
<p>I have code which add gradient on image.</p> <pre><code>def st(path, gradient_magnitude=2.): im = Image.open(path) if im.mode != 'RGBA': im = im.convert('RGBA') width, height = im.size gradient = Image.new('L', (width, 1), color=0xFF) for x in range(width): gradient.putpixel((x, 0), int(255 * (1 - gradient_magnitude * float(x) / width))) alpha = gradient.resize(im.size) black_im = Image.new('RGBA', (width, height), color=0x000000) black_im.putalpha(alpha) gradient_im = Image.alpha_composite(im, black_im) gradient_im.save('out.jpg', 'JPEG') </code></pre> <p>After run I get this image <a href="http://i.stack.imgur.com/oDUcD.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/oDUcD.jpg" alt="enter image description here"></a></p> <p>How can I make gradient more transparency?</p>
1
2016-10-11T11:16:03Z
39,980,957
<p>Try this. Initial opacity values of 0.9 or 0.95 should give you what you want. I also restructured the code a bit because it was a mess before. Whoever wrote the <a href="http://stackoverflow.com/questions/39842286/python-pillow-add-transparent-gradient-to-an-image/39857434?noredirect=1#comment67230721_39857434">previous version</a> should be told off and kept away from a computer. ;-)</p> <pre><code>from PIL import Image def apply_black_gradient(path_in, path_out='out.png', gradient=1., initial_opacity=1.): """ Applies a black gradient to the image, going from left to right. Arguments: --------- path_in: string path to image to apply gradient to path_out: string (default 'out.png') path to save result to gradient: float (default 1.) gradient of the gradient; should be non-negative; if gradient = 0., the image is black; if gradient = 1., the gradient smoothly varies over the full width; if gradient &gt; 1., the gradient terminates before the end of the width; initial_opacity: float (default 1.) scales the initial opacity of the gradient (i.e. on the far left of the image); should be between 0. and 1.; values between 0.9-1. give good results """ # get image to operate on input_im = Image.open(path_in) if input_im.mode != 'RGBA': input_im = input_im.convert('RGBA') width, height = input_im.size # create a gradient that # starts at full opacity * initial_value # decrements opacity by gradient * x / width alpha_gradient = Image.new('L', (width, 1), color=0xFF) for x in range(width): a = int((initial_opacity * 255.) * (1. - gradient * float(x)/width)) if a &gt; 0: alpha_gradient.putpixel((x, 0), a) else: alpha_gradient.putpixel((x, 0), 0) # print '{}, {:.2f}, {}'.format(x, float(x) / width, a) alpha = alpha_gradient.resize(input_im.size) # create black image, apply gradient black_im = Image.new('RGBA', (width, height), color=0) # i.e. black black_im.putalpha(alpha) # make composite with original image output_im = Image.alpha_composite(input_im, black_im) output_im.save(path_out, 'PNG') return </code></pre>
1
2016-10-11T15:26:43Z
[ "python", "python-imaging-library", "pillow" ]
python continuing a loop from a specific index
39,976,073
<p>I wrote some code that uses enumerate to loop through a list.</p> <pre><code>for index, item in enumerate(list[start_idx:end_idx]) print('index [%d] item [%s]'%(str(index), item)) </code></pre> <p>the item in the list are just strings. Sometimes I do not want to enumerate for the whole list, sometimes I'll slice up the list do do different things.</p> <p>The part that I am having trouble with is python's enumerate function.</p> <p>The docs say you can do:</p> <pre><code>for index, item in enumerate(list, start_index): print(str(index)) </code></pre> <p>the above code doesn't do what I expected. I though enumerate would start at the start position and stop at the end, but it doesn't.</p> <p>I wrote a small program and it does indeed act wonky.</p> <pre><code>&gt;&gt;&gt; for i, x in enumerate(range(0,20),start=4): ... print(str(i)+'\t'+str(x)) ... 4 0 5 1 6 2 7 3 8 4 9 5 10 6 11 7 12 8 13 9 14 10 15 11 16 12 17 13 18 14 19 15 20 16 21 17 22 18 23 19 </code></pre> <p>I would expect enumerate to start at index 4 and loop to the end. So it would get the range of 4-19 but it seems to just start the index but still iterates from 0-19..</p> <p>Question, is there a way to do a iteration loop starting at a specific index in python?</p> <p>My expected outcome would be</p> <pre><code>&gt;&gt;&gt; for i, x in enumerate(range(0,20),start=4): ... print(str(i)+'\t'+str(x)) ... 4 0 # skip 5 1 # until 6 2 # this 7 3 # item 8 4 9 5 10 6 11 7 12 8 13 9 14 10 15 11 16 12 17 13 18 14 19 15 20 16 21 17 22 18 23 19 </code></pre> <p>instead of starting the index at the start position provide.</p>
2
2016-10-11T11:19:09Z
39,976,119
<p>You can do:</p> <pre><code>for index, item in enumerate(list[4:]): print(str(index)) </code></pre>
0
2016-10-11T11:21:25Z
[ "python", "loops", "enumerate" ]
python continuing a loop from a specific index
39,976,073
<p>I wrote some code that uses enumerate to loop through a list.</p> <pre><code>for index, item in enumerate(list[start_idx:end_idx]) print('index [%d] item [%s]'%(str(index), item)) </code></pre> <p>the item in the list are just strings. Sometimes I do not want to enumerate for the whole list, sometimes I'll slice up the list do do different things.</p> <p>The part that I am having trouble with is python's enumerate function.</p> <p>The docs say you can do:</p> <pre><code>for index, item in enumerate(list, start_index): print(str(index)) </code></pre> <p>the above code doesn't do what I expected. I though enumerate would start at the start position and stop at the end, but it doesn't.</p> <p>I wrote a small program and it does indeed act wonky.</p> <pre><code>&gt;&gt;&gt; for i, x in enumerate(range(0,20),start=4): ... print(str(i)+'\t'+str(x)) ... 4 0 5 1 6 2 7 3 8 4 9 5 10 6 11 7 12 8 13 9 14 10 15 11 16 12 17 13 18 14 19 15 20 16 21 17 22 18 23 19 </code></pre> <p>I would expect enumerate to start at index 4 and loop to the end. So it would get the range of 4-19 but it seems to just start the index but still iterates from 0-19..</p> <p>Question, is there a way to do a iteration loop starting at a specific index in python?</p> <p>My expected outcome would be</p> <pre><code>&gt;&gt;&gt; for i, x in enumerate(range(0,20),start=4): ... print(str(i)+'\t'+str(x)) ... 4 0 # skip 5 1 # until 6 2 # this 7 3 # item 8 4 9 5 10 6 11 7 12 8 13 9 14 10 15 11 16 12 17 13 18 14 19 15 20 16 21 17 22 18 23 19 </code></pre> <p>instead of starting the index at the start position provide.</p>
2
2016-10-11T11:19:09Z
39,976,147
<p>The <code>start</code> parameter of <code>enumerate</code> doesn't have anything to do with what elements of the iterable get selected. It just tells enumerate what number to start with.</p> <pre><code>&gt;&gt;&gt; list(enumerate(range(3))) [(0, 0), (1, 1), (2, 2)] &gt;&gt;&gt; list(enumerate(range(3), 1)) [(1, 0), (2, 1), (3, 2)] </code></pre> <p>If you want to start at a specific index, you need to provide the start argument <em>and</em> a <a href="https://docs.python.org/dev/library/functions.html#slice" rel="nofollow">slice</a>:</p> <pre><code>for i, v in enumerate(alist[4:], 4): ... </code></pre>
1
2016-10-11T11:23:03Z
[ "python", "loops", "enumerate" ]
python continuing a loop from a specific index
39,976,073
<p>I wrote some code that uses enumerate to loop through a list.</p> <pre><code>for index, item in enumerate(list[start_idx:end_idx]) print('index [%d] item [%s]'%(str(index), item)) </code></pre> <p>the item in the list are just strings. Sometimes I do not want to enumerate for the whole list, sometimes I'll slice up the list do do different things.</p> <p>The part that I am having trouble with is python's enumerate function.</p> <p>The docs say you can do:</p> <pre><code>for index, item in enumerate(list, start_index): print(str(index)) </code></pre> <p>the above code doesn't do what I expected. I though enumerate would start at the start position and stop at the end, but it doesn't.</p> <p>I wrote a small program and it does indeed act wonky.</p> <pre><code>&gt;&gt;&gt; for i, x in enumerate(range(0,20),start=4): ... print(str(i)+'\t'+str(x)) ... 4 0 5 1 6 2 7 3 8 4 9 5 10 6 11 7 12 8 13 9 14 10 15 11 16 12 17 13 18 14 19 15 20 16 21 17 22 18 23 19 </code></pre> <p>I would expect enumerate to start at index 4 and loop to the end. So it would get the range of 4-19 but it seems to just start the index but still iterates from 0-19..</p> <p>Question, is there a way to do a iteration loop starting at a specific index in python?</p> <p>My expected outcome would be</p> <pre><code>&gt;&gt;&gt; for i, x in enumerate(range(0,20),start=4): ... print(str(i)+'\t'+str(x)) ... 4 0 # skip 5 1 # until 6 2 # this 7 3 # item 8 4 9 5 10 6 11 7 12 8 13 9 14 10 15 11 16 12 17 13 18 14 19 15 20 16 21 17 22 18 23 19 </code></pre> <p>instead of starting the index at the start position provide.</p>
2
2016-10-11T11:19:09Z
39,976,254
<p>Actually if you got <code>range</code> object it's not a big deal to make a slice from it, because <code>range(n)[:4]</code> is still <code>range</code> object(<em>as @MosesKoledoye mentioned it's Python 3 feature</em>). But if you got a list, for the sake of not creating new list you can choose <a href="https://docs.python.org/3/library/itertools.html#itertools.islice" rel="nofollow"><code>itertools.islice</code></a>, it will return iterator.</p> <pre><code>from itertools import islice for index, item in enumerate(islice(range(20), 4, None)): print(index, item) </code></pre> <p>Output</p> <pre><code>0 4 1 5 2 6 3 7 4 8 ... </code></pre>
2
2016-10-11T11:28:54Z
[ "python", "loops", "enumerate" ]
How do you retrieve the cell row of a changed QComboBox as a QCellWidget of a QTableWidget?
39,976,078
<p>I am trying to get the row and column of a changed combobox in a QTableWidget. Here is how my table is set up. Look at the bottom to see what I am trying to do.</p> <pre><code>def click_btn_mailouts(self): self.cur.execute("""SELECT s.StudentID, s.FullName, m.PreviouslyMailed, m.nextMail, m.learnersDate, m.RestrictedDate, m.DefensiveDate FROM StudentProfile s LEFT JOIN Mailouts m ON s.studentID=m.studentID""") self.all_data = self.cur.fetchall() self.table.setRowCount(len(self.all_data)) self.tableFields = ["Check","Full name","Previously mailed?","Next mail","learners date","Restricted date","Defensive driving date"] self.columnList = ["StudentID","FullName","PreviouslyMailed","NextMail","learnersDate","RestrictedDate","DefensiveDate"] self.table.setColumnCount(len(self.tableFields)) self.table.setHorizontalHeaderLabels(self.tableFields) self.checkbox_list = [] for i, item in enumerate(self.all_data): FullName = QtGui.QTableWidgetItem(str(item[1])) PreviouslyMailed = QtGui.QComboBox() PreviouslyMailed.addItem("Yes") PreviouslyMailed.addItem("No") LearnersDate = QtGui.QTableWidgetItem(str(item[3])) RestrictedDate = QtGui.QTableWidgetItem(str(item[4])) DefensiveDate = QtGui.QTableWidgetItem(str(item[5])) NextMail = QtGui.QTableWidgetItem(str(item[6])) self.table.setItem(i, 1, FullName) self.table.setCellWidget(i, 2, PreviouslyMailed) self.table.setItem(i, 3, LearnersDate) self.table.setItem(i, 4, RestrictedDate) self.table.setItem(i, 5, DefensiveDate) self.table.setItem(i, 6, NextMail) chkBoxItem = QtGui.QTableWidgetItem() chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled) chkBoxItem.setCheckState(QtCore.Qt.Unchecked) self.checkbox_list.append(chkBoxItem) self.table.setItem(i, 0, self.checkbox_list[i]) FullName.setFlags(FullName.flags() &amp; ~Qt.ItemIsEditable) NextMail.setFlags(NextMail.flags() &amp; ~Qt.ItemIsEditable) """Heres what I am trying to do:""" PreviouslyMailed.currentIndexChanged.connect(self.comboBox_change(self.table.cellWidget(row,1).currentText())) """I want 'row' to be the row that has the combobox that has been changed.""" </code></pre>
1
2016-10-11T11:19:23Z
39,987,228
<p>If I understand correctly, when attaching the signal <code>i</code> will be the value of the row that you want to send (or, maybe <code>i+1</code>?). You can easily send additional data with Qt signals, by using a wrapper function or <code>lambda</code> as follows:</p> <pre><code>for a in range(5): x = QComboBox() x.currentIndexChanged.connect( lambda i: my_other_function(i, another_var) ) </code></pre> <p>Here, we connect the <code>lambda</code> to the signal, and when it is called the internal function will in turn be called with the extra data. This is functionally equivalent to:</p> <pre><code>def my_wrapper(i): my_other_function(i, another_var) for a in range(5): x = QComboBox() x.currentIndexChanged.connect( my_wrapper ) </code></pre> <p>But, as you will discover if you try to do this, this doesn't always work. If you try and pass the variable <code>a</code> to the internal function, it will <em>always</em> be set to the value <code>a</code> was at the end of the loop. </p> <pre><code>for a in range(5): x = QComboBox() x.currentIndexChanged.connect( lambda i: my_other_function(i, a) ) # a will always be 4 </code></pre> <p>You can get around this by rebinding the value of <code>a</code> to a new variable each time — the easiest way being passing it in as a named parameter to the <code>lambda</code>. For example —</p> <pre><code>for a in range(5): x = QComboBox() x.currentIndexChanged.connect( lambda i, a=a: my_other_function(i, a) ) # Each combo will send the index, plus the value of a </code></pre> <p>You should be able to use the above to send the correct value for <code>row</code> for each <code>QComboBox</code> you create. </p>
0
2016-10-11T21:41:47Z
[ "python", "pyqt" ]
ssh connection in python
39,976,096
<p>I'm trying to read a text file from a server using ssh from python 3.5. I'm using paramiko to connect to the server but unfortunately, I'm having trouble actually connecting to the server.</p> <p>this is the code I'm using to connect to the server</p> <pre><code>import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('IP ADDRESS OF THE SERVER', key_filename="/home/user/.ssh/id_ecdsa" ,look_for_keys=True) </code></pre> <p>but every time I try to connect to the server I'm getting an authentication failed error message, can anyone see what I'm doing wrong here? Any advice would be appreciated</p> <p>This is the error I'm getting everytime i connect.</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.5/site-packages/paramiko/client.py", line 380, in connect look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host) File "/usr/local/lib/python3.5/site-packages/paramiko/client.py", line 603, in _auth raise saved_exception File "/usr/local/lib/python3.5/site-packages/paramiko/client.py", line 580, in _auth allowed_types = set(self._transport.auth_publickey(username, key)) File "/usr/local/lib/python3.5/site-packages/paramiko/transport.py", line 1331, in auth_publickey return self.auth_handler.wait_for_response(my_event) File "/usr/local/lib/python3.5/site-packages/paramiko/auth_handler.py", line 208, in wait_for_response raise e paramiko.ssh_exception.AuthenticationException: Authentication failed. </code></pre>
0
2016-10-11T11:20:02Z
39,976,380
<p>You should use your <strong>private</strong> key to connect to a remote server. Your <strong>public</strong> key must be already installed in the server side, i.e. it must be listed in <code>~/.ssh/authorized_keys</code>.</p> <p>Try first from the command line, and only then use Python/paramiko. Check the permissions of the files/directories if all that fails.</p>
2
2016-10-11T11:36:21Z
[ "python", "paramiko" ]
ssh connection in python
39,976,096
<p>I'm trying to read a text file from a server using ssh from python 3.5. I'm using paramiko to connect to the server but unfortunately, I'm having trouble actually connecting to the server.</p> <p>this is the code I'm using to connect to the server</p> <pre><code>import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('IP ADDRESS OF THE SERVER', key_filename="/home/user/.ssh/id_ecdsa" ,look_for_keys=True) </code></pre> <p>but every time I try to connect to the server I'm getting an authentication failed error message, can anyone see what I'm doing wrong here? Any advice would be appreciated</p> <p>This is the error I'm getting everytime i connect.</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.5/site-packages/paramiko/client.py", line 380, in connect look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host) File "/usr/local/lib/python3.5/site-packages/paramiko/client.py", line 603, in _auth raise saved_exception File "/usr/local/lib/python3.5/site-packages/paramiko/client.py", line 580, in _auth allowed_types = set(self._transport.auth_publickey(username, key)) File "/usr/local/lib/python3.5/site-packages/paramiko/transport.py", line 1331, in auth_publickey return self.auth_handler.wait_for_response(my_event) File "/usr/local/lib/python3.5/site-packages/paramiko/auth_handler.py", line 208, in wait_for_response raise e paramiko.ssh_exception.AuthenticationException: Authentication failed. </code></pre>
0
2016-10-11T11:20:02Z
39,977,142
<p>Turns out I simply just forgot to add in the username in the connection string. works perfectly now.</p>
0
2016-10-11T12:21:54Z
[ "python", "paramiko" ]
Find all occurences of inner text in an xml file with etree
39,976,302
<p>I am new to python and trees at all, and have encountered some problems.</p> <p>I have the following dataset structured as:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;graphml xmlns="http://graphml.graphdrawing.org/xmlns"&gt; &lt;node id="node1"&gt; &lt;data key="label"&gt;node1&lt;/data&gt; &lt;data key="degree"&gt;6&lt;/data&gt; &lt;/node&gt; &lt;node id="node2"&gt; &lt;data key="label"&gt;node2&lt;/data&gt; &lt;data key="degree"&gt;32&lt;/data&gt; &lt;/node&gt; &lt;node id="node3"&gt; &lt;data key="label"&gt;node3&lt;/data&gt; &lt;data key="degree"&gt;25&lt;/data&gt; &lt;/node&gt; &lt;/graphml&gt; </code></pre> <p>I wish to be able to reach and print all the inner text of the &lt; data key="label"> elements using etree. In other words get the following result:</p> <pre><code>"node1" "node2" "node3" </code></pre> <p>I have tried the itertext() with no luck (<a href="https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.itertext" rel="nofollow">https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.itertext</a>), as well as faulty xpath expressions.</p> <p>I'm sure there is a simple solution to this, hope you guys can help!</p>
1
2016-10-11T11:32:03Z
39,976,781
<p>You probably forget the namespace. Try something like this:</p> <pre><code>import xml.etree.ElementTree as ET root = ET.fromstring(countrydata) ns = {'graphml': 'http://graphml.graphdrawing.org/xmlns'} for element in root.findall(".//graphml:node[@id]",ns): print(element.attrib['id']) </code></pre>
0
2016-10-11T12:00:57Z
[ "python", "xml", "xpath", "tree", "elementtree" ]
Find all occurences of inner text in an xml file with etree
39,976,302
<p>I am new to python and trees at all, and have encountered some problems.</p> <p>I have the following dataset structured as:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;graphml xmlns="http://graphml.graphdrawing.org/xmlns"&gt; &lt;node id="node1"&gt; &lt;data key="label"&gt;node1&lt;/data&gt; &lt;data key="degree"&gt;6&lt;/data&gt; &lt;/node&gt; &lt;node id="node2"&gt; &lt;data key="label"&gt;node2&lt;/data&gt; &lt;data key="degree"&gt;32&lt;/data&gt; &lt;/node&gt; &lt;node id="node3"&gt; &lt;data key="label"&gt;node3&lt;/data&gt; &lt;data key="degree"&gt;25&lt;/data&gt; &lt;/node&gt; &lt;/graphml&gt; </code></pre> <p>I wish to be able to reach and print all the inner text of the &lt; data key="label"> elements using etree. In other words get the following result:</p> <pre><code>"node1" "node2" "node3" </code></pre> <p>I have tried the itertext() with no luck (<a href="https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.itertext" rel="nofollow">https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.itertext</a>), as well as faulty xpath expressions.</p> <p>I'm sure there is a simple solution to this, hope you guys can help!</p>
1
2016-10-11T11:32:03Z
39,976,806
<p>This does the job on python 2.7 :</p> <pre><code>import xml.etree.ElementTree as ET root = ET.fromstring(data) elts = root.findall('.//*[@key="label"]') for e in elts: print(e.text) </code></pre>
0
2016-10-11T12:02:14Z
[ "python", "xml", "xpath", "tree", "elementtree" ]
Pandas Slow. Want first occurrence in DataFrame
39,976,348
<p>I have a DataFrame of <code>people</code>. One of the columns in this DataFrame is a <code>place_id</code>. I also have a DataFrame of places, where one of the columns is <code>place_id</code> and another is <code>weather</code>. For every person, I am trying to find the corresponding weather. Importantly, many people have the same <code>place_id</code>s. </p> <p>Currently, my setup is this:</p> <pre><code>def place_id_to_weather(pid): return place_df[place_df['place_id'] == pid]['weather'].item() person_df['weather'] = person_df['place_id'].map(place_id_to_weather)` </code></pre> <p>But this is untenably slow. I would like to speed this up. I suspect that I could achieve a speedup like this:</p> <p>Instead of returning <code>place_df[...].item()</code>, which does a search for <code>place_id == pid</code> for that entire column and returns a series, and then grabbing the first item in that series, I really just want to curtail the search in <code>place_df</code> after the first match <code>place_df['place_id']==pid</code> has been found. After that, I don't need to search any further. How do I limit the search to first occurrences only?</p> <p>Are there other methods I could use to achieve a speedup here? Some kind of join-type method?</p>
4
2016-10-11T11:34:07Z
39,976,539
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow"><code>drop_duplicates</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>, if there is only common columns <code>place_id</code> and <code>weather</code> in both <code>DataFrames</code>, you can omit parameter <code>on</code> (it depends of data, maybe <code>on='place_id'</code> is necessary):</p> <pre><code>df1 = place_df.drop_duplicates(['place_id']) print (df1) print (pd.merge(person_df, df1)) </code></pre> <p>Sample data:</p> <pre><code>person_df = pd.DataFrame({'place_id':['s','d','f','s','d','f'], 'A':[4,5,6,7,8,9]}) print (person_df) A place_id 0 4 s 1 5 d 2 6 f 3 7 s 4 8 d 5 9 f place_df = pd.DataFrame({'place_id':['s','d','f', 's','d','f'], 'weather':['y','e','r', 'h','u','i']}) print (place_df) place_id weather 0 s y 1 d e 2 f r 3 s h 4 d u 5 f i </code></pre> <pre><code>def place_id_to_weather(pid): #for first occurence add iloc[0] return place_df[place_df['place_id'] == pid]['weather'].iloc[0] person_df['weather'] = person_df['place_id'].map(place_id_to_weather) print (person_df) A place_id weather 0 4 s y 1 5 d e 2 6 f r 3 7 s y 4 8 d e 5 9 f r </code></pre> <hr> <pre><code>#keep='first' is by default, so can be omit print (place_df.drop_duplicates(['place_id'])) place_id weather 0 s y 1 d e 2 f r print (pd.merge(person_df, place_df.drop_duplicates(['place_id']))) A place_id weather 0 4 s y 1 7 s y 2 5 d e 3 8 d e 4 6 f r 5 9 f r </code></pre>
2
2016-10-11T11:45:50Z
[ "python", "pandas" ]
Pandas Slow. Want first occurrence in DataFrame
39,976,348
<p>I have a DataFrame of <code>people</code>. One of the columns in this DataFrame is a <code>place_id</code>. I also have a DataFrame of places, where one of the columns is <code>place_id</code> and another is <code>weather</code>. For every person, I am trying to find the corresponding weather. Importantly, many people have the same <code>place_id</code>s. </p> <p>Currently, my setup is this:</p> <pre><code>def place_id_to_weather(pid): return place_df[place_df['place_id'] == pid]['weather'].item() person_df['weather'] = person_df['place_id'].map(place_id_to_weather)` </code></pre> <p>But this is untenably slow. I would like to speed this up. I suspect that I could achieve a speedup like this:</p> <p>Instead of returning <code>place_df[...].item()</code>, which does a search for <code>place_id == pid</code> for that entire column and returns a series, and then grabbing the first item in that series, I really just want to curtail the search in <code>place_df</code> after the first match <code>place_df['place_id']==pid</code> has been found. After that, I don't need to search any further. How do I limit the search to first occurrences only?</p> <p>Are there other methods I could use to achieve a speedup here? Some kind of join-type method?</p>
4
2016-10-11T11:34:07Z
39,976,650
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow"><code>merge</code></a> to do the operation :</p> <pre><code>people = pd.DataFrame([['bob', 1], ['alice', 2], ['john', 3], ['paul', 2]], columns=['name', 'place']) # name place #0 bob 1 #1 alice 2 #2 john 3 #3 paul 2 weather = pd.DataFrame([[1, 'sun'], [2, 'rain'], [3, 'snow'], [1, 'rain']], columns=['place', 'weather']) # place weather #0 1 sun #1 2 rain #2 3 snow #3 1 rain pd.merge(people, weather, on='place') # name place weather #0 bob 1 sun #1 bob 1 rain #2 alice 2 rain #3 paul 2 rain #4 john 3 snow </code></pre> <p>In case you have several weather for the same place, you may want to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow"><code>drop_duplicates</code></a>, then you have the following result :</p> <pre><code>pd.merge(people, weather, on='place').drop_duplicates(subset=['name', 'place']) # name place weather #0 bob 1 sun #2 alice 2 rain #3 paul 2 rain #4 john 3 snow </code></pre>
0
2016-10-11T11:52:56Z
[ "python", "pandas" ]
Pandas Slow. Want first occurrence in DataFrame
39,976,348
<p>I have a DataFrame of <code>people</code>. One of the columns in this DataFrame is a <code>place_id</code>. I also have a DataFrame of places, where one of the columns is <code>place_id</code> and another is <code>weather</code>. For every person, I am trying to find the corresponding weather. Importantly, many people have the same <code>place_id</code>s. </p> <p>Currently, my setup is this:</p> <pre><code>def place_id_to_weather(pid): return place_df[place_df['place_id'] == pid]['weather'].item() person_df['weather'] = person_df['place_id'].map(place_id_to_weather)` </code></pre> <p>But this is untenably slow. I would like to speed this up. I suspect that I could achieve a speedup like this:</p> <p>Instead of returning <code>place_df[...].item()</code>, which does a search for <code>place_id == pid</code> for that entire column and returns a series, and then grabbing the first item in that series, I really just want to curtail the search in <code>place_df</code> after the first match <code>place_df['place_id']==pid</code> has been found. After that, I don't need to search any further. How do I limit the search to first occurrences only?</p> <p>Are there other methods I could use to achieve a speedup here? Some kind of join-type method?</p>
4
2016-10-11T11:34:07Z
39,984,155
<p>The map function is your quickest method, the purpose of which is to avoid calling an entire dataframe to run some function repeatedly. This is what you ended up doing in your function i.e. calling an entire dataframe which is fine but not good doing it repeatedly. To tweak your code just a little will significantly speed up your process and only call the place_df dataframe once:</p> <pre><code>person_df['weather'] = person_df['place_id'].map(dict(zip(place_df.place_id, place_df.weather))) </code></pre>
1
2016-10-11T18:26:06Z
[ "python", "pandas" ]
Django UpdateView create new object
39,976,361
<p>My problem: UpdateView create new object instead of updating previous, i think its happens because in class definition of my view i override get_object method like this:</p> <pre><code>def get_object(self, queryset=None): try: object_get = self.model.objects.get(pk=self.kwargs['pk']) except ObjectDoesNotExist: raise Http404("No object found matching this query") if self.request.user.is_authenticated(): if object_get.owner == self.request.user: return object_get </code></pre> <p>And so if current user is not owner of the object - this method return nothing - its what i wanted, but my form class instead create new object: </p> <pre><code>class ClientCreation(forms.ModelForm): class Meta: model = Client fields = ('name', 'loyal') </code></pre> <p>I think this is happened because form doesn't receive a self.instance and create new instead - what should i do in this situation? I don't want new object to be created, in case when owner of object is not the current user i want nothing to happend then sending such a post request. How should i correctly implement this?</p> <p>UPDATE views.py:</p> <pre><code>class Distinct(generic.UpdateView): def get_object(self, queryset=None): try: object_get = self.model.objects.get(pk=self.kwargs['pk']) except ObjectDoesNotExist: raise Http404("No object found matching this query") if self.request.user.is_authenticated(): if object_get.owner == self.request.user: return object_get def get_form_kwargs(self): kwargs = super(Distinct, self).get_form_kwargs() if self.request.user.is_authenticated(): kwargs.update({'user': self.request.user}) return kwargs def post(self, request, *args, **kwargs): if request.POST.get('action', '') == 'Delete': object_get = self.get_object() request.session['deleted_data'] = str(object_get) object_get.delete() return redirect(reverse('crm:main')) else: return super(Distinct, self).post(request, *args, **kwargs) def get_success_url(self): return reverse('crm:{}'.format(self.distinct_template), kwargs={'pk': self.kwargs['pk']}) class DistinctClient(Distinct): form_class = ClientCreation model = Client template_name = 'crm/client_detail.html' all_template = 'clients' distinct_template = 'client' def get_form_kwargs(self): return generic.UpdateView.get_form_kwargs(self) </code></pre>
1
2016-10-11T11:35:13Z
39,976,485
<p>In <code>UpdateView</code>, if <code>get_object</code> returns <code>None</code> django will create a new object.So instead of return <code>None</code> do whatever you want.</p> <pre><code>def get_object(self, queryset=None): try: object_get = self.model.objects.get(pk=self.kwargs['pk']) except ObjectDoesNotExist: raise Http404("No object found matching this query") if self.request.user.is_authenticated(): if object_get.owner == self.request.user: return object_get raise My #do something here. </code></pre> <p><strong>UPDATE</strong></p> <pre><code>class My(Exception): pass class DistinctClient(Distinct): form_class = ClientCreation model = Client template_name = 'crm/client_detail.html' all_template = 'clients' distinct_template = 'client' def dispatch(self, *args, **kwargs): try: return super(DistinctClient, self).dispatch(*args, **kwargs) except My: return redirect #to do or (return render(self.request, 'mytemplate.html', {})) </code></pre>
3
2016-10-11T11:43:28Z
[ "python", "django", "django-class-based-views" ]
Trying to iterate through XML : can't get subnode's values
39,976,405
<p>I need to process a huge file with many nodes structured likes this</p> <pre><code>&lt;category name="28931778o.rjpf"&gt; &lt;name&gt;RequestedName&lt;/name&gt; &lt;root&gt;0&lt;/root&gt; &lt;online&gt;1&lt;/online&gt; &lt;description xml:lang="pt-PT"&gt;mydescription &lt;/description&gt; &lt;category-links/&gt; &lt;template/&gt; &lt;parent name="PTW-0092"/&gt; &lt;custom-attributes&gt; &lt;custom-attribute name="sortkey" dt:dt="string"&gt;RequestedValue&lt;/custom-attribute&gt; &lt;custom-attribute name="ShortLink" dt:dt="string" xml:lang="pt-PT"&gt;/Requested_Url.html&lt;/custom-attribute&gt; &lt;custom-attribute name="ShortLinkActivate" dt:dt="string" xml:lang="pt-PT"&gt;true&lt;/custom-attribute&gt; ... &lt;/category&gt; </code></pre> <p>I need to get back for each category the 3 requested Values. I use Python .27 and etree. when running</p> <pre><code>for elem in tree.iterfind('{http://www.cc.com/a}category'): requestedName = elem.find('{http://www.cc.com/a}name').text print requestedName </code></pre> <p>It works fine</p> <p>when running </p> <pre><code>for elem in tree.iterfind('{http://www.cc.com/a}category/{http://www.cc.com/a}custom-attributes/{http://www.cc.com/a}custom-attribute[@name="sortkey"]'): print elem.text </code></pre> <p>it works fine also Problem comes when I want to retreive all three values. I try to find a "category" node and inside it to find the 2 requested values</p> <pre><code>for elem in tree.iterfind('{http://www.cc.com/a}category'): requestedName = elem.find('{http://www.cc.com/a}name').text print requestedName Requestedsortkey = elem.find('./{http://www.cc.com/a}custom-attributes/{http://www.cc.com/a}custom-attribute[@name="sortkey"]') print Requestedsortkey.text RequestedUrl = elem.find('./{http://www.cc.com/a}custom-attributes/{http://www.cc.com/a}custom-attribute[@name="ShortLink"]') print RequestedUrl.text </code></pre> <p>Program crashes with his error message AttributeError: 'NoneType' object has no attribute 'text'</p> <p>Who can help?</p>
2
2016-10-11T11:38:23Z
39,982,812
<p>You are right Dopstar ! Many thanks</p> <pre><code>for elem in tree.iterfind('{http://www.cc.com/a}category'): requestedName = elem.find('{http://www.cc.com/a}name').text print requestedName Requestedsortkey = elem.find('{http://www.cc.com/a}custom-attributes/{http://www.cc.com/a}custom-attribute[@name="sortkey"]') if Requestedsortkey &lt;&gt; None: print Requestedsortkey.text RequestedUrl = elem.find('{http://www.cc.com/a}custom-attributes/{http://www.cc.com/a}custom-attribute[@name="ShortLink"]') if RequestedUrl &lt;&gt; None : print RequestedUrl.text </code></pre>
0
2016-10-11T17:07:14Z
[ "python", "xml-parsing", "lxml", "elementtree" ]
Python Kivy language color property
39,976,475
<p>Does Kivy language support hex color values such as </p> <blockquote> <p><strong>#F05F40</strong></p> </blockquote> <p>Thanks very much in advance! </p>
0
2016-10-11T11:42:46Z
39,977,810
<p>Kivy has <code>utils</code> module with <a href="https://kivy.org/docs/api-kivy.utils.html#kivy.utils.get_color_from_hex" rel="nofollow">get_color_from_hex</a> function that do job:</p> <pre><code>#:import utils kivy.utils &lt;Widget&gt;: canvas.before: Color: rgb: utils.get_color_from_hex('#F05F40') Rectangle: pos: self.pos size: self.size </code></pre> <p>Note, that you should <a href="https://kivy.org/docs/guide/lang.html#special-syntaxes" rel="nofollow">import</a> module in kvlang.</p>
0
2016-10-11T12:58:27Z
[ "python", "kivy" ]
random circles using SimpleGraphics
39,976,596
<p>I need to make a circle by adjusting conditions on the heights, this program using a lot of random circles but I am unsure where to go from here? I am trying to use the following equation d = (sqrt)((x1 –x2)^2 +(y1 – y2)^2). Right now the program draws many random circles, so adjusting the formula i should be able to manipulate it so that certain circles are red in the centre (like the japan flag).</p> <pre><code># using the SimpleGraphics library from SimpleGraphics import * # use the random library to generate random numbers import random diameter = 15 ## # returns a valid colour based on the input coordinates # # @param x is an x-coordinate # @param y is a y-coordinate # @return a colour based on the input x,y values for the given flag ## def define_colour(x,y): ## if y &lt; (((2.5 - 0)**2) + ((-0.5 - 0)**2)**(1/2)): c = 'red' else: c = 'white' return c return None # repeat until window is closed while not closed(): # generate random x and y values x = random.randint(0, getWidth()) y = random.randint(0, getHeight()) # set colour for current circle setFill( define_colour(x,y) ) # draw the current circle ellipse(x, y, diameter, diameter) </code></pre>
2
2016-10-11T11:49:14Z
39,977,483
<p>Here's some code that endlessly draws circles. Circles that are close to the centre of the screen will be drawn in red, all other circles will be drawn in white. Eventually, this will create an image similar to the flag of Japan, although the edge of the inner red "circle" will not be smooth.</p> <p>I have not tested this code because I don't have the <code>SimpleGraphics</code> module, and I'm not having much success locating it via Google or pip.</p> <pre><code>from SimpleGraphics import * import random diameter = 15 width, height = getWidth(), getHeight() cx, cy = width // 2, height // 2 # Adjust the multiplier (10) to control the size of the central red portion min_dist_squared = (10 * diameter) ** 2 def define_colour(x, y): #Calculate distance squared from screen centre r2 = (x - cx) ** 2 + (y - cy) ** 2 if r2 &lt;= min_dist_squared: return 'red' else: return 'white' # repeat until window is closed while not closed(): # generate random x and y values x = random.randrange(0, width) y = random.randrange(0, height) # set colour for current circle setFill(define_colour(x, y)) # draw the current circle ellipse(x, y, diameter, diameter) </code></pre>
0
2016-10-11T12:41:14Z
[ "python", "python-3.x", "graphics" ]
Python 3.5.2 logger configuration and usage
39,976,715
<p>I'm new to python and trying to setup a logger in my simple app.</p> <p>This is the app structure:</p> <pre><code> - checker - checking - proxy_checker.py - custom_threading - __init__.py - executor_my.py - long_task.py - tests - __init__.py - logging_config.ini - main.py </code></pre> <p>i'm trying to setup the file configured logger in the main module's <code>checker/__init__.py</code><strong>:</strong></p> <pre><code>from logging.config import fileConfig fileConfig('logging_config.ini') </code></pre> <p><strong>logging_config.ini</strong></p> <pre><code>[loggers] keys=root [handlers] keys=stream_handler [formatters] keys=formatter [logger_root] level=DEBUG handlers=stream_handler [handler_stream_handler] class=StreamHandler level=DEBUG formatter=formatter args=(sys.stderr,) [formatter_formatter] format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s </code></pre> <p>and the use it in the <code>/checker/custom_threading/exector_my.py</code>:</p> <pre><code>import concurrent.futures import logging from custom_threading.long_task import LongTask class MyExecutor(object): logger = logging.getLogger(__name__) _executor = concurrent.futures.ThreadPoolExecutor(max_workers=500) def __init__(self, thread_count, task): self._thread_count = thread_count self._task = LongTask(task) pass def start(self): self.logger.debug("Launching with thread count: " + str(self._thread_count)) *more irrelevant code* </code></pre> <p>tried to use logger.info / logger.debug. for both options <strong>i don't get any error and nothing is logged in console</strong>. What do i do wrong?</p> <p>P.S. maybe also useful that i run it on Win 10 x64</p>
4
2016-10-11T11:57:16Z
39,978,648
<p>My (possibly wrong :-) guess is that you start the script by something like <code>python checker/main.py</code>, thus the logging configuration in <code>__init__.py</code> is not executed.</p> <p>Please, take a look at this answer: <a href="http://stackoverflow.com/questions/7533480/why-is-init-py-not-being-called">Why is __init__.py not being called?</a></p> <p>Moreover, you need to ensure that <code>fileConfig()</code> is called before <code>getLogger()</code> (class body is executed at the time of import). A working setup would be to load the configuration somewhere at the beginning of <code>main.py</code> and instantiate the logger in <code>MyExecutor.__init__()</code>.</p>
1
2016-10-11T13:41:04Z
[ "python", "python-3.x", "logging" ]
Deep autoencoder in Keras converting one dimension to another i
39,976,718
<p>I am doing an image captioning task using vectors for representing both images and captions. </p> <p>The caption vectors have a legth/dimension of size 128. The image vectors have a length/dimension of size 2048.</p> <p>What I want to do is to train an autoencoder, to get an encoder which is able to convert text vector into a image vector. And a decoder which is able to convert an image vector into a text vector. </p> <p>Encoder: 128 -> 2048.</p> <p>Decoder: 2048 -> 128.</p> <p>I followed <a href="https://blog.keras.io/building-autoencoders-in-keras.html" rel="nofollow">this</a> tutorial to implement a shallow network doing what I wanted.</p> <p>But I cant figure out how to create a deep network, following the same tutorial. </p> <pre class="lang-py prettyprint-override"><code>x_dim = 128 y_dim = 2048 x_dim_shape = Input(shape=(x_dim,)) encoded = Dense(512, activation='relu')(x_dim_shape) encoded = Dense(1024, activation='relu')(encoded) encoded = Dense(y_dim, activation='relu')(encoded) decoded = Dense(1024, activation='relu')(encoded) decoded = Dense(512, activation='relu')(decoded) decoded = Dense(x_dim, activation='sigmoid')(decoded) # this model maps an input to its reconstruction autoencoder = Model(input=x_dim_shape, output=decoded) # this model maps an input to its encoded representation encoder = Model(input=x_dim_shape, output=encoded) encoded_input = Input(shape=(y_dim,)) decoder_layer1 = autoencoder.layers[-3] decoder_layer2 = autoencoder.layers[-2] decoder_layer3 = autoencoder.layers[-1] # create the decoder model decoder = Model(input=encoded_input, output=decoder_layer3(decoder_layer2(decoder_layer1(encoded_input)))) autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy') autoencoder.fit(training_data_x, training_data_y, nb_epoch=50, batch_size=256, shuffle=True, validation_data=(test_data_x, test_data_y)) </code></pre> <p>The training_data_x and test_data_x have 128 dimensions. The training_data_y and test_data_y have 2048 dimensions.</p> <p>The error I receive while trying to run this is the following:</p> <blockquote> <p>Exception: Error when checking model target: expected dense_6 to have shape (None, 128) but got array with shape (32360, 2048)</p> </blockquote> <p>dense_6 is the last decoded variable. </p>
1
2016-10-11T11:57:36Z
39,998,476
<h1>Autoencoders</h1> <p>If you want is to be able to call the <code>encoder</code> and <code>decoder</code> separately, what you need to do is train the whole autoencoder exactly as per the tutorial, with <code>input_shape == output_shape</code> (<code>== 128</code> in your case), and only then can you call a subset of the layers:</p> <pre><code>x_dim = 128 y_dim = 2048 x_dim_shape = Input(shape=(x_dim,)) encoded = Dense(512, activation='relu')(x_dim_shape) encoded = Dense(1024, activation='relu')(encoded) encoded = Dense(y_dim, activation='relu')(encoded) decoded = Dense(1024, activation='relu')(encoded) decoded = Dense(512, activation='relu')(decoded) decoded = Dense(x_dim, activation='sigmoid')(decoded) # this model maps an input to its reconstruction autoencoder = Model(input=x_dim_shape, output=decoded) autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy') autoencoder.fit(training_data_x, training_data_x, nb_epoch=50, batch_size=256, shuffle=True, validation_data=(test_data_x, test_data_y)) # test the decoder model encoded_input = Input(shape=(y_dim,)) decoder_layer1 = autoencoder.layers[-3] decoder_layer2 = autoencoder.layers[-2] decoder_layer3 = autoencoder.layers[-1] decoder = Model(input=encoded_input, output=decoder_layer3(decoder_layer2(decoder_layer1(encoded_input)))) decoder.compile(optimizer='adadelta', loss='binary_crossentropy') eval = decoder.evaluate(test_data_y, test_data_x) print('Decoder evaluation: {:.2f}'.format(eval)) </code></pre> <p>Notice that, when calling <code>autoencoder.fit()</code>, <code>x == y</code> in the arguments. This is how the auto-encoder would (normally) have to optimize the bottleneck representation (that you call <code>y</code> in your own code) to best fit the original image with less dimensions.</p> <p>But, as a transition to the second part of this answer, notice that in your case, <code>x_dim &lt; y_dim</code>. You are actually training a model to <em>increase</em> the data dimensionality, which doesn't make much sense, AFAICT.</p> <h2>Your problem</h2> <p>Now reading your question again, I don't think autoencoders are any good for what you want to achieve. They are designed to <strong>reduce</strong> the dimensionality of the data, with a minimum of casualties.</p> <p>What you are trying to do is:</p> <ol> <li><strong>Render</strong> a text to an image (what you call <code>encode</code>)</li> <li><strong>Read</strong> a text from an image (what you call <code>decode</code>)</li> </ol> <p>In my understanding, while <code>2.</code> might indeed require some machine learning, <code>1.</code> definitely doesn't: there are plenty of libraries to write text on images out there.</p>
1
2016-10-12T12:20:33Z
[ "python", "vector", "neural-network", "keras", "autoencoder" ]
In Python, what's the difference between deepcopy and [each[:] for each in List]
39,976,742
<p>Below is the example code:</p> <pre><code>from copy import deepcopy List = [range(3), range(3), range(3)] a = deepcopy(List) b = [each[:] for each in List] </code></pre> <p>I know the time required to initialize a is slower than b's time, but why does this happen? What's the difference between deepcopy and [each[:] for each in List]? Why is deepcopy so slow?</p>
0
2016-10-11T11:58:42Z
39,976,760
<p><code>each[:]</code> creates a <em>shallow</em> copy of each nested list. <code>copy.deepcopy()</code> would make a <em>deep</em> copy.</p> <p>In this specific case, where your nested lists contain immutable integers, this difference doesn't actually matter; <code>deepcopy()</code> returns the integer unchanged when copying. But if there were <em>mutable</em> objects in the nested lists, then <code>deepcopy()</code> would continue to create copies of those, while your list comprehension would not.</p> <p>For example, you'd see a difference when copying a list containing lists with with dictionaries:</p> <pre><code>&gt;&gt;&gt; from copy import deepcopy &gt;&gt;&gt; sample = [[{'foo': 'bar'}, {'ham': 'spam'}], [{'monty': 'python'}, {'eric': 'idle'}]] &gt;&gt;&gt; shallow = [each[:] for each in sample] &gt;&gt;&gt; deep = deepcopy(sample) &gt;&gt;&gt; sample[-1][-1]['john'] = 'cleese' &gt;&gt;&gt; sample [[{'foo': 'bar'}, {'ham': 'spam'}], [{'monty': 'python'}, {'eric': 'idle', 'john': 'cleese'}]] &gt;&gt;&gt; shallow [[{'foo': 'bar'}, {'ham': 'spam'}], [{'monty': 'python'}, {'eric': 'idle', 'john': 'cleese'}]] &gt;&gt;&gt; deep [[{'foo': 'bar'}, {'ham': 'spam'}], [{'monty': 'python'}, {'eric': 'idle'}]] </code></pre> <p>Because the <code>deepcopy()</code> operation has to test each element in the nested lists, it is also slower; the list comprehension is the better option if you know that you don't need to produce a 'deeper' copy.</p>
6
2016-10-11T12:00:03Z
[ "python", "list", "copy", "deep-copy" ]
In Python, what's the difference between deepcopy and [each[:] for each in List]
39,976,742
<p>Below is the example code:</p> <pre><code>from copy import deepcopy List = [range(3), range(3), range(3)] a = deepcopy(List) b = [each[:] for each in List] </code></pre> <p>I know the time required to initialize a is slower than b's time, but why does this happen? What's the difference between deepcopy and [each[:] for each in List]? Why is deepcopy so slow?</p>
0
2016-10-11T11:58:42Z
39,980,594
<p>As Martijn Pieters said each[:] will perform by creating a shallow copy of each nested list. If your list elements are immutable objects then you can use this, otherwise you have to use deepcopy from copy module.</p> <p>It's possible to completely copy shallow list structures with the slice operator without having any of the side effects, have a look to the following snapshot:</p> <pre><code>LIST_1 = ['A','B',['AB','BA']] print LIST_1 &gt;&gt;&gt; ['A', 'B', ['AB', 'BA']] LIST_2= LIST_1[:] print id(LIST_1) &gt;&gt;&gt; 40427648 print id(LIST_2) &gt;&gt;&gt; 50932872 LIST_2[2][1] = "D" LIST_2[2][0] = "C"; print LIST_2 &gt;&gt;&gt; ['A', 'B', ['C', 'D']] print LIST_1 &gt;&gt;&gt; ['A', 'B', ['C', 'D']] </code></pre> <p>However in deepcopy method:</p> <p>A solution to the described problems is to use the module "copy". This module provides the method "copy", which allows a complete copy of a arbitrary list, i.e. shallow and other lists. so you use <code>copy.deepcopy(...)</code> for deep copying a list:</p> <pre><code>deepcopy(x, memo=None, _nil=[]) </code></pre> <p>The following script uses our example above and this method: </p> <pre><code>from copy import deepcopy LIST_1 = ['A','B',['AB','BA']] LIST_2= deepcopy(LIST_1) LIST_2[2][1] = "D" LIST_2[0] = "C"; print LIST_2 &gt;&gt;&gt;['C', 'B', ['AB', 'D']] print LIST_1 &gt;&gt;&gt;['A', 'B', ['AB', 'BA']] </code></pre> <p><a href="https://i.stack.imgur.com/wPphj.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/wPphj.jpg" alt="enter image description here"></a></p> <p>Therefore, a shallow copy of each nested list does not recursively makes copies of the inner objects. It only makes a copy of the outermost list, while still referencing the inner lists from the previous variable and that's why deepcopy is slower.</p>
1
2016-10-11T15:11:04Z
[ "python", "list", "copy", "deep-copy" ]
How do I shorten this if possible?
39,976,778
<p>Well, here's my code</p> <pre><code>import time import random Dice = input("Would you like to roll the dice?(y/n)") if Dice == "y": roll = random.randint(1,6) print("You have rolled a", roll) again = input("Would you like to roll again?(y/n)") while again == "y": roll2 = random.randint(1,6) print("You have rolled a", roll2) again = input("Roll again?(y/n)") if again == "n": time.sleep(1) print("Goodbye") else: time.sleep(1) print("Goodbye") </code></pre> <p>If you could help, that'd be great!</p>
-4
2016-10-11T12:00:41Z
39,976,904
<p>I feel like doing someones homework. But here you go, a shortened version of your code (untested).</p> <pre><code>import time import random dice = input("Would you like to roll the dice?(y/n)") while dice == "y": print( "You have rolled a %s" % (random.randint(1,6))) dice = input("would you like to roll again?(y/n)") time.sleep(1) print("Goodbye") </code></pre>
2
2016-10-11T12:08:11Z
[ "python", "python-3.x" ]
How do I shorten this if possible?
39,976,778
<p>Well, here's my code</p> <pre><code>import time import random Dice = input("Would you like to roll the dice?(y/n)") if Dice == "y": roll = random.randint(1,6) print("You have rolled a", roll) again = input("Would you like to roll again?(y/n)") while again == "y": roll2 = random.randint(1,6) print("You have rolled a", roll2) again = input("Roll again?(y/n)") if again == "n": time.sleep(1) print("Goodbye") else: time.sleep(1) print("Goodbye") </code></pre> <p>If you could help, that'd be great!</p>
-4
2016-10-11T12:00:41Z
39,976,968
<pre><code>import random while input('RTD? (y/n) ') == 'y': print('Rolled {}.'.format(random.randint(1, 6))) </code></pre>
4
2016-10-11T12:11:45Z
[ "python", "python-3.x" ]
How do I shorten this if possible?
39,976,778
<p>Well, here's my code</p> <pre><code>import time import random Dice = input("Would you like to roll the dice?(y/n)") if Dice == "y": roll = random.randint(1,6) print("You have rolled a", roll) again = input("Would you like to roll again?(y/n)") while again == "y": roll2 = random.randint(1,6) print("You have rolled a", roll2) again = input("Roll again?(y/n)") if again == "n": time.sleep(1) print("Goodbye") else: time.sleep(1) print("Goodbye") </code></pre> <p>If you could help, that'd be great!</p>
-4
2016-10-11T12:00:41Z
39,976,981
<pre><code>import time import random while input("Would you like to roll the dice? (y/n) ") == 'y': roll = random.randint(1,6) print("You have rolled a", roll) print("Goodbye") time.sleep(1) </code></pre>
0
2016-10-11T12:12:23Z
[ "python", "python-3.x" ]
How do I shorten this if possible?
39,976,778
<p>Well, here's my code</p> <pre><code>import time import random Dice = input("Would you like to roll the dice?(y/n)") if Dice == "y": roll = random.randint(1,6) print("You have rolled a", roll) again = input("Would you like to roll again?(y/n)") while again == "y": roll2 = random.randint(1,6) print("You have rolled a", roll2) again = input("Roll again?(y/n)") if again == "n": time.sleep(1) print("Goodbye") else: time.sleep(1) print("Goodbye") </code></pre> <p>If you could help, that'd be great!</p>
-4
2016-10-11T12:00:41Z
39,976,997
<p>Use while loop:</p> <pre><code>import time import random Dice = raw_input("Would you like to roll the dice?(y/n)") while Dice.lower() == "y": roll = random.randint(1, 6) print("You have rolled a ", roll) Dice = raw_input("Would you like to roll again?(y/n)") time.sleep(1) print("Goodbye") </code></pre>
0
2016-10-11T12:13:01Z
[ "python", "python-3.x" ]
Python Selenium IE - Clicking on an anchor does not change the URL
39,976,869
<h2>As Short As Possible</h2> <p>I am trying to do test automation using Python with py.test and Selenium.</p> <p>I have tried two approaches to change the URL by clicking an anchor <code>&lt;a&gt;</code> element, neither of the approaches seems to work - the URL does not change.</p> <p>There are no errors reported, other than the incorrect assertion result.</p> <p>The element I want to click on is:</p> <pre><code>&lt;li class="ng-scope" ng-repeat="crumb in bcCtrl.data"&gt; &lt;!-- ngIf: !$last --&gt; &lt;a class="ng-binding ng-scope" ng-if="!$last" ng-href="#/accounts/8" href="#/accounts/8"&gt;RC München&lt;/a&gt; &lt;!-- end ngIf: !$last --&gt; &lt;!-- ngIf: $last --&gt; &lt;/li&gt; &lt;!-- end ngRepeat: crumb in bcCtrl.data --&gt; </code></pre> <h3>What I have checked so far</h3> <ul> <li>I can find the anchor,</li> <li>The anchor found is the correct one (has the correct text, and href)</li> <li>(using JScript) That doing .click() on the anchor indeed causes the page to load the new URL just like the user action would</li> </ul> <h3>First approach</h3> <p>The first approach was to use:</p> <pre><code>pre_last_breadcrumb_element = self.find_elements_by_locator(locators['breadcrumb_elements'])[-1] pre_last_breadcrumb_element.click() </code></pre> <p>but this seems not to have done anything.</p> <h3>Second approach</h3> <p>The second approach was to use:</p> <pre><code>actions = ActionChains(self.driver) el = self.find_elements_by_locator(locators['breadcrumb_elements'])[-1] actions.move_to_element(el).click(el).perform() </code></pre> <p>But still no desired result.</p> <p>What am I doing wrong? Please help...</p> <hr> <h2>More details</h2> <p>The code that I've used is:</p> <pre><code>pre_last_breadcrumb_element = self.find_elements_by_locator(locators['breadcrumb_elements'])[-1] # this will click the pre-last element in the breadcrumb print("PreLast = {0}".format(pre_last_breadcrumb_element.text)) print("BEFORE CLICK get_current_url='{0}'".format(self.driver.get_current_url)) # APPROACH 1 actions = ActionChains(self.driver) el = self.find_elements_by_locator(locators['breadcrumb_elements'])[-1] actions.move_to_element(el).click(el).perform() # FIXME: The click on the anchor does not work... # APPROACH 2 # pre_last_breadcrumb_element.click() # FIXME: The click on the anchor does not work... print("AFTER CLICK get_current_url='{0}'".format(self.driver.get_current_url)) # checking if the pre-last element changed due to the click print("PreLast = {0}".format(pre_last_breadcrumb_element.text)) print("Changing between URLs\nFROM:'{0}'\n TO:'{1}'".format(self.get_url, pre_last_breadcrumb_element.get_attribute("href"))) # this will reload the page class at the newer URL self.open_at_current_location() print("Current URL:'{0}'".format(self.get_url)) assert last_breadcrumb_element.text is pre_last_breadcrumb_element.text </code></pre> <p>This is the result:</p> <pre><code>PreLast = RC München BEFORE CLICK get_current_url='http://fct:8080/fct/#/accounts/9' AFTER CLICK get_current_url='http://fct:8080/fct/#/accounts/9' PreLast = RC München Changing between URLs FROM:'http://fct:8080/fct/#/accounts/9' TO:'http://fct:8080/fct/#/accounts/8' get_current_url='http://fct:8080/fct/#/accounts/9' Current URL:'http://fct:8080/fct/#/accounts/9' </code></pre>
2
2016-10-11T12:06:00Z
39,980,754
<p>If you've tried all but nothing get success, you can try using <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.execute_script" rel="nofollow"><code>WebDriver#execute_script()</code></a> as an alternate solution where you can execute some piece of <code>JavaScript</code> code on the desired element to perform <code>click</code> as below :-</p> <pre><code>element = self.driver.find_element_by_link_text("RC München") #now click on this element using JavaScript self.driver.execute_script("arguments[0].click()", element) </code></pre> <p><strong>Warning</strong> :- The <code>JavaScript</code> injection <code>HTMLElement.click()</code> shouldn't be used in a testing context. It defeats the purpose of the test. First because it doesn't generate all the events like a real <code>click (focus, blur, mousedown, mouseup...)</code> and second because it doesn't guarantee that a real user can interact with the element. </p> <p>But some time due to designing or other issues this is to be only solution, so you can consider it as an alternate solution.</p>
-1
2016-10-11T15:18:14Z
[ "python", "internet-explorer", "selenium-webdriver", "automated-tests", "anchor" ]
Unable to reliabily Match Base 64 encrypted String from strings stored in a Website: Python Program
39,977,069
<p>I am Rishabh and am a beginner in Python Programming Language.. I have attempted to write a sort of an Authentication Program using Python. </p> <p><strong>Here's What I am doing in my Program:</strong></p> <ol> <li>I get the Username and Password</li> <li>I concatenate the two strings like : ###Username:::Password</li> <li>Then I encrypt the above concatenated string using a base64 encoding program that I saw online.(I am unfamiliar with base64 encoding and I a beginner in all the tools I have used in the below Python Program)</li> <li>Now you get an encrypted String.</li> <li>I have the same encrypted string hidden within the html of the blog that I created for this purpose : <strong><a href="https://pastarchive.blogspot.in" rel="nofollow">https://pastarchive.blogspot.in</a></strong></li> </ol> <p><strong>The Encrypted Strings are stored as hidden text in the html code of the page:</strong></p> <pre><code>&lt;span style="background-color: white; display: none;"&gt;HELLO !! POST&lt;/span&gt;&lt;br /&gt; &lt;span style="background-color: white; display: none;"&gt;HELLO !! POST&lt;/span&gt;&lt;br /&gt; &lt;span style="background-color: white; display: none;"&gt;HELLO !! POST&lt;/span&gt;&lt;br /&gt; &lt;span style="background-color: white; display: none;"&gt;HELLO !! POST&lt;/span&gt;&lt;br /&gt; &lt;span style="background-color: white; display: none;"&gt;HELLO !! POST&lt;/span&gt;&lt;br /&gt; &lt;span style="background-color: white; display: none;"&gt;IIKTxK6FBJC+or4JPyQqSI0BrAevMJix//LSgGyoiETg=&lt;/span&gt;&lt;br /&gt; &lt;span style="background-color: white; display: none;"&gt;4M3CXPZGRKUsQRqbaOPd/gajp6XD9irrM2pQ8N9MHyM=&lt;/span&gt;&lt;br /&gt; &lt;span style="background-color: white; display: none;"&gt;F5uxniPOSEiU2h/v1QreAx1+hXzW7GRRcJS15kYE/EM=&lt;/span&gt;&lt;br /&gt; &lt;span style="background-color: white; display: none;"&gt;mAHuxBo7URh0QcRswXTccxq/sMTUNfbqmSaiopZxzuA=&lt;/span&gt;&lt;br /&gt; </code></pre> <p><strong>The random characters you see in the above html code is from the website:</strong> </p> <ol start="6"> <li>So What I do is.. I make an encrypted string in the program as said before and I just check if the exact string exists in the website. If it is, I just display the "Successfully Logged in message" and if not I just display "Login Failed."</li> </ol> <p><strong>The Problem:</strong></p> <p>The problem I have is that, This method strangely works only for a few users and the rest don't succeed in finding the exact string from the website source code even though the exact encrypted string is present in the website. </p> <p>Please Download the Code and run it so that you can Understand</p> <p><strong>1. The Account which Sucessfully Logs in:</strong></p> <p><strong>Username is</strong> : USER</p> <p><strong>Password is</strong> : TEMPPASS</p> <p>This account works perfectly as I thought</p> <p><strong>2. The Accounts which strangely doesn't work:</strong> </p> <p><strong>Username is</strong> : user2</p> <p><strong>Password is</strong> : CLR</p> <p>Can someone tell me why the first account works perfectly fine and the later fails ? And how do I Fix this issue ? Please guide me to fix this issue as I am a beginner.</p> <p>Don't get confused by the Administrator Account.. Its just a Locally verified Account..</p> <p><strong>The Code:</strong></p> <pre><code>import requests from getpass import getpass from bs4 import BeautifulSoup import re import csv import time from Crypto.Cipher import AES import base64 counter =1 counter2=1 import requests import urllib2 from bs4 import BeautifulSoup import re print("\nPlease Authenticate Yourself:") #print("Welcome to Mantis\n") user = raw_input("\nEnter Username:") password= getpass("\nEnter Password:") print "\n...................................................................." matchstring="###"+user+":::"+password matches="" chkstr=matchstring print chkstr ###Encryption msg_text = chkstr.rjust(32) secret_key = '1234567890123456' cipher = AES.new(secret_key,AES.MODE_ECB) encoded = base64.b64encode(cipher.encrypt(msg_text)) #encoded = encoded.encode('string-escape') print "Encrypted Text: \n"+encoded ##print matchstring #data sent for Authentication if encoded == "OiKUr4N8ZT7V7hZlwvnXP2d0F1I4xtktNbZSpNotJh0=": print "\nHello Rishabh !! Is the Login Portal Locked ?" print "\n\nAdministrator Access Granted" counter2=2 if counter2==1: ###https://pastarchive.blogspot.in ###https://pastarchive.wordpress.com/2016/10/08/hello/ html_content = urllib2.urlopen('https://pastarchive.blogspot.in').read() rematchstring=re.compile(encoded) matches = re.findall(encoded, html_content); if len(matches) != 0 or counter2==2: print 'Sucessfully Logged in\n' print 'Hello '+user.upper()+" !\n" if user.upper()!="ADMINISTRATOR": print "Thanks in Advance for using Eagle, the Advanced Data Parsing Algorithm." print "\nCreator - Rishabh Raghunath, Electrical Engineering Student, MVIT\n" time.sleep(1) print "Let's Start !\n" print ".....................................................................\n" if len(matches) == 0: print '\nUserName or Password is Incorrect\n' print "Please Check Your mail in case your Password has been Changed" print "Log in failed.\n" time.sleep(5) </code></pre> <p>Please Try to help me out with this Strange Problem.. I don't have a clue how to solve this.. Thanks.</p>
3
2016-10-11T12:17:31Z
39,979,998
<p>The problem is because you use <code>re</code> and you have <code>+</code> in <code>encodec</code>. <code>re</code> treats <code>+</code> in special way so ie. <code>1+2</code> is searching <code>12 or 112 or 1112 etc.</code></p> <p>Use <code>html_content.find(encoded)</code> which returns position of <code>encodec</code> in <code>html_content</code> or <code>-1</code></p> <p>Now you will have to use <code>if matched != -1 or counter2 = 2</code> and <code>if matched == -1:</code></p> <hr> <p><strong>BTW:</strong> you have mess in code. It could look like this.</p> <pre><code>from getpass import getpass from Crypto.Cipher import AES import base64 import urllib2 import time # --- constants --- SECRET_KEY = '1234567890123456' # --- classes --- # empty # --- functions --- # empty # --- main --- loggedin = False # ------ input print("\nPlease Authenticate Yourself:") #print("Welcome to Mantis\n") user = raw_input("\nEnter Username:") password = getpass("\nEnter Password:") print "\n...................................................................." # ------ encrypting matchstring = "###{}:::{}".format(user, password) cipher = AES.new(SECRET_KEY, AES.MODE_ECB) encoded = base64.b64encode(cipher.encrypt(matchstring.rjust(32))) print "Encrypted Text: \n", encoded # ------ checking # print matchstring #data sent for Authentication if encoded == "eiKUr3N8ZT7V7RZlwvnXW2F0F1I4xtktNZZSpNotDh0=": print "\nHello Rishabh !! Is the Login Portal Locked ?" print "\n\nAdministrator Access Granted" loggedin = True else: html = urllib2.urlopen('https://passarchive.blogspot.in').read() loggedin = (html.find(encoded) != 1) # True or False # ------ info if loggedin: user = user.upper() print 'Sucessfully Logged in\n' print 'Hello', user, "!\n" if user != "ADMINISTRATOR": print "Thanks in Advance for using Eagle, the Advanced Data Parsing Algorithm." print "\nCreator - Rishabh Raghunath, Electrical Engineering Student, MVIT\n" time.sleep(1) print "Let's Start !\n" print ".....................................................................\n" else: print '\nUserName or Password is Incorrect\n' print "Please Check Your mail in case your Password has been Changed" print "Log in failed.\n" time.sleep(5) # ------ end </code></pre>
1
2016-10-11T14:45:18Z
[ "python", "regex", "encryption", "beautifulsoup", "base64" ]
Split and Merge data in a bunch of csv-files in a directory
39,977,119
<p>I have many .csv files in a directory, coming from an energy measurement device that stores its files every two seconds. Each file looks similar to that:</p> <pre><code>Position,Date,Time,V12,Unit,V23,Unit,V31,Unit,A1,Unit,A2,Unit,A3,Unit,P(SUM),Unit,S(SUM),Unit,Q(SUM),Unit,PF(SUM),Unit,PFH,Unit,WH,Unit,SH,Unit,QH,Unit,FREQ,Unit 0,7/21/2016,23:59:56,392.5, ACV,394, ACV,393.2, ACV,1.053, ACA,1.045, ACA,0, ACA,0.367,KW ,0.432,KVA ,0.229,KVAR,0.84,,0.85,,854.6,KWH ,1,MVAH ,516.8,KVARH ,50,Hz 0,7/21/2016,23:59:58,392.6, ACV,394.1, ACV,392.9, ACV,1.053, ACA,1.048, ACA,0, ACA,0.368,KW ,0.433,KVA ,0.229,KVAR,0.84,,0.85,,854.6,KWH ,1,MVAH ,516.8,KVARH ,50,Hz 0,7/22/2016,0:00:00,392.5, ACV,394, ACV,392.5, ACV,1.049, ACA,1.042, ACA,0, ACA,0.366,KW ,0.431,KVA ,0.228,KVAR,0.84,,0.85,,854.6,KWH ,1,MVAH ,516.8,KVARH ,49.9,Hz 0,7/22/2016,0:00:02,392.1, ACV,393.5, ACV,392.1, ACV,1.047, ACA,1.039, ACA,0, ACA,0.363,KW ,0.428,KVA ,0.226,KVAR,0.84,,0.85,,854.6,KWH ,1,MVAH ,516.8,KVARH ,50,Hz </code></pre> <p>Sometimes there is just one day in a file, sometimes two or more days (if the measurement stopped). Sometimes there is a headline between the data (when the measurement stopped and started again). Each file consists of 30000 rows, the data is sorted in ascending order.</p> <p>I want to make one file for each day that is named via the date. In this example it would be <code>2016-07-21.csv</code> (you can find the date in the second column). The file should start with the headline row you find above.</p> <p>Sample files can be found here: <a href="http://jmp.sh/TefuAek" rel="nofollow">Sample files</a></p> <p>Is there a script to get the job done?</p>
-1
2016-10-11T12:20:10Z
39,977,534
<p>The following approach should get you started:</p> <pre><code>from datetime import datetime from collections import defaultdict import csv import glob days = defaultdict(list) for filename in glob.glob('*.csv'): with open(filename, 'rb') as f_input: csv_input = csv.reader(f_input) header = next(csv_input) for row in csv_input: if row[0] != "Position": day = datetime.strptime('{} {}'.format(row[1], row[2]), '%m/%d/%Y %H:%M:%S') days[row[1]].append([day, row]) for day in sorted(days.keys()): with open('/myoutputfolder/{}.csv'.format(days[day][0][0].strftime('%Y-%m-%d')), 'wb') as f_output: csv_output = csv.writer(f_output) csv_output.writerow(header) csv_output.writerows(row for dt, row in sorted(days[day], key=lambda x: x[0])) </code></pre> <p>This reads all of the csv files, sorts the entries, and writes each day out into a separate csv file. It uses a Python <code>defaultdict</code> to keep a list of entries for each day. It also converts the date and time columns into a Python <code>datetime</code> so that the entries can all be correctly sorted before before written to the output files. The <code>glob</code> library is used to just return a list of <code>.csv</code> files for a given folder. If sub-folders are needed, this would need to be converted to use <code>os.walk()</code>. The <code>csv</code> library is used to automatically read the csv files into lists.</p> <p>Tested using Python 2.7.12</p>
2
2016-10-11T12:43:46Z
[ "python", "windows", "csv", "scripting" ]
Implement Bhattacharyya loss function using python layer Caffe
39,977,133
<p>Trying to implement my custom loss layer using python layer,caffe. I've used this <a href="https://github.com/BVLC/caffe/blob/master/examples/pycaffe/layers/pyloss.py" rel="nofollow">example</a> as the guide and have wrote the <code>forward</code> function as follow:</p> <pre><code> def forward(self,bottom,top): score = 0; self.mult[...] = np.multiply(bottom[0].data,bottom[1].data) self.multAndsqrt[...] = np.sqrt(self.mult) top[0].data[...] = -math.log(np.sum(self.multAndsqrt)) </code></pre> <p>However, the second task, that is implementing the <code>backward</code> function is kinda much difficult for me as I'm totally unfamiliar with python. So please help me with coding the backward section. Here is the cost function and its derivative for stocashtic gradient decent to be implemented:</p> <p><a href="https://i.stack.imgur.com/GXgGA.png" rel="nofollow"><img src="https://i.stack.imgur.com/GXgGA.png" alt="enter image description here"></a> Thanks in advance.</p> <p>Note that p[i] in the table indicates the <em>ith</em> output neuron value. </p>
0
2016-10-11T12:21:00Z
40,137,336
<p>Lets say bottom[0].data is p, bottom[1].data is q and Db(p,q) denotes the Bhattacharyya Distance between p and q.</p> <p>The only thing you need to do in your backward function is to compute the partial derivatives of Db with respect to its inputs (p and q) and store them in the respective bottom diff blobs:</p> <p><a href="https://i.stack.imgur.com/Q3ckj.gif" rel="nofollow">diff_p = dDb(p,q)/dp</a><br> <a href="https://i.stack.imgur.com/6s5Jl.gif" rel="nofollow">diff_q = dDb(p,q)/dq</a></p> <p>so your backward function would look something like:</p> <pre><code>def backward(self, top, propagate_down, bottom): if propagate_down[0]: bottom[0].diff[...] = # calculate dDb(p,q)/dp if propagate_down[1]: bottom[1].diff[...] = # calculate dDb(p,q)/dq </code></pre> <p>Note that you normally use the average (instad of the total) error of your batch. Then you would end up with something like this:</p> <pre><code>def forward(self,bottom,top): self.mult[...] = np.multiply(bottom[0].data,bottom[1].data) self.multAndsqrt[...] = np.sqrt(self.mult) top[0].data[...] = -math.log(np.sum(self.multAndsqrt)) / bottom[0].num def backward(self, top, propagate_down, bottom): if propagate_down[0]: bottom[0].diff[...] = # calculate dDb(p,q)/dp / bottom[0].num if propagate_down[1]: bottom[1].diff[...] = # calculate dDb(p,q)/dq / bottom[1].num </code></pre> <p>Once you calculated the partial derivatives of Db, you can insert them in the templates above as you did for the function of the forward pass.</p>
0
2016-10-19T16:52:48Z
[ "python", "python-2.7", "caffe", "pycaffe" ]
How to read from an excel sheet using pythons xlrd module
39,977,141
<p>I have the following code. What am I trying to do is screenscrape a website and then write the data to an excel worksheet. I can't read the existing data from excel file.</p> <pre><code>import xlwt import xlrd from xlutils.copy import copy from datetime import datetime import urllib.request from bs4 import BeautifulSoup import re import time import os links= open('links.txt', encoding='utf-8') #excel workbook if os.path.isfile('./TestSheet.xls'): rbook=xlrd.open_workbook('TestSheet.xls',formatting_info=True) book=copy(rbook) else: book = xlwt.Workbook() try: book.add_sheet("wayanad") except: print("sheet exists") sheet=book.get_sheet(1) for line in links: print("Currently Scanning\n","\n=================\n",line.rstrip()) url=str(line.rstrip()) req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) html = urllib.request.urlopen(req) soup = BeautifulSoup(html,"html.parser") #print(soup.prettify()) title=soup.find('h1').get_text() data=[] for i in soup.find_all('p'): data.append(i.get_text()) quick_descr=data[1].strip() category=data[2].strip() tags=data[3].strip() owner=data[4].strip() website=data[6].strip() full_description=data[7] address=re.sub('\s+', ' ', soup.find('h3').get_text()).strip() city=soup.find(attrs={"itemprop": "addressRegion"}).get_text().strip() postcode=soup.find(attrs={"itemprop": "postalCode"}).get_text().strip() phone=[] result=soup.findAll('h4') for h in result: if h.has_attr('itemprop'): phone.append(re.sub("\D", "", h.get_text())) #writing data to excel row=sheet.last_used_row column_count=sheet.ncols() book.save("Testsheet.xls") time.sleep(2) </code></pre> <p><strong>The code explained</strong></p> <ul> <li>I have a links file there are many links line by line. So pick a line(URL) and go that URL and scrape the data.</li> <li>Open an excel workbook and switch to a sheet for writing data.</li> <li>append the data to excel sheet.->></li> </ul> <p>Screenshot of execl sheet structure <a href="http://i.stack.imgur.com/QEUOi.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/QEUOi.jpg" alt="enter image description here"></a></p> <p>Currently the list is empty. But i want to continue from the last row. I coudn't read data from the cell. The <a href="https://xlrd.readthedocs.io/en/latest/" rel="nofollow">documentation says</a> there is <code>sheet.ncols</code> is avilable to count the columns. But it throws an error</p> <pre><code>&gt;&gt;&gt;column_count=sheet.ncols() &gt;&gt;&gt;AttributeError: 'Worksheet' object has no attribute 'ncols' </code></pre> <p>What i wanted is a way to count rows and columns, and read the data from cell. Many turials are old. Now i am using python 3.4. I've already gone through this links and many other. But no luck</p> <p><a href="http://stackoverflow.com/questions/10747385/attributeerror-module-object-has-no-attribute-open-openwork">Stack overflow</a></p> <p><a href="http://stackoverflow.com/questions/23088864/python-open-existing-excel-file-and-count-rows-in-sheet">Stackoverdlow</a></p>
0
2016-10-11T12:21:48Z
39,977,418
<p>Is that what you are looking for ? Going through all col.?</p> <pre><code>xl_workbook = xlrd.open_workbook num_cols = xl_sheet.ncols for row_idx in range(0, xl_sheet.nrows): </code></pre>
0
2016-10-11T12:38:03Z
[ "python", "excel", "xlrd", "xlwt" ]
Python: Confusing example of Functions as Objects
39,977,166
<p>When I was reasearching a bit about decorators, I stumbled upon some rather confusing code that i found perplexing in the way that it passes varibles and functions.</p> <pre><code>def get_text(name): return "lorem ipsum, {0} dolor sit amet".format(name) def p_decorate(func): def func_wrapper(name): return "&lt;p&gt;{0}&lt;/p&gt;".format(func(name)) return func_wrapper my_get_text = p_decorate(get_text) print my_get_text("John") # &lt;p&gt;Outputs lorem ipsum, John dolor sit amet&lt;/p&gt; </code></pre> <p>I understand the concept of passing functions as variables (which is cool) however the way that it was passed multiple times confused me. <code>my_get_text</code> has already been assigned to a function with an argument (another function). However, just after that we reference this new variable and pass arguments to it ("John"). The way that "John" gets transferred in <code>func_wrapper()</code> is also perplexing. </p> <p>How is <code>my_get_text</code> able to receive more arguments and how is it passed to the inside functions?</p> <p>Thank you</p>
0
2016-10-11T12:23:03Z
39,977,329
<p>This is a demonstration of how decorators work: They basically wrap the decorated function into another internal function and return its reference.</p> <ol> <li>In your example, the call <code>my_get_text = p_decorate(get_text)</code> calls the function <code>p_decorate</code> with the wrappable function as a parameter (<code>get_text</code>).</li> <li>The return value is a reference to a newly defined function which takes exactly one parameter <code>name</code>. This return value is assigned to your variable name <code>my_get_text</code></li> <li><code>my_get_text</code> is now <em>callable</em>, because it's a function reference.</li> <li>If you call <code>my_get_text</code>, it calls the function that was created by the decorator and hands over your parameter <code>name</code> (in your case <code>'John'</code>).</li> <li>The function creates <code>&lt;p&gt;</code>-Tags and pushes a string between them. This string is obtained from the function call that you provided the decorator in step 1: It is the return value of the call that has been <em>decorated</em>.</li> </ol> <p>By the way, because the function <code>func_wrapper</code> is re-defined each time a function is decorated (see <em>closure</em>), the return value is a function reference that points to an entirely new function.<br> Compare the memory addresses:</p> <pre><code>a = p_decorate(get_text) b = p_decorate(get_text) print(a == b) print(a) print(b) &gt;&gt;&gt; False &gt;&gt;&gt; &lt;function func_wrapper at 0x02ADFF30&gt; &gt;&gt;&gt; &lt;function func_wrapper at 0x02ADFF70&gt; </code></pre> <p>The functions are defined with the very same call, but since they are <em>closures</em>, the function pointer refers to another memory address (i.e. a different function).</p>
2
2016-10-11T12:32:34Z
[ "python", "function", "variables", "python-decorators" ]
What function is func here? Where did it come from?
39,977,187
<p>This is my code:</p> <pre><code>def testit(func, *nkwargs, **kwargs): try: retval = func(*nkwargs, **kwargs) result = (True, retval) except Exception, diag: result = (False, str(diag)) return result def test(): funcs = (int, long, float) vals = (1234, 12.34, '1234', '12.34') for eachFunc in funcs: print '-' * 20 for eachVal in vals: retval = testit(eachFunc, eachVal) if retval[0]: print '%s(%s) =' % \ (eachFunc.__name__, `eachVal`), retval[1] else: print '%s(%s) = FAILED:' % \ (eachFunc.__name__, `eachVal`), retval[1] if __name__ == '__main__': test() </code></pre> <p>What is the function of the <code>func</code> in the third line. I think it is a variable. How did it become a function name?</p>
-2
2016-10-11T12:24:19Z
39,977,260
<p>Python functions are first-class objects. This means you can assign such an object to a variable and pass it to another function. The very act of executing a <code>def functionname(): ...</code> statement assigns such an object to a name (<code>functionname</code> here):</p> <pre><code>&gt;&gt;&gt; def foo(): return 42 ... &gt;&gt;&gt; foo &lt;function foo at 0x107e9f0d0&gt; &gt;&gt;&gt; bar = foo &gt;&gt;&gt; bar &lt;function foo at 0x107e9f0d0&gt; &gt;&gt;&gt; bar() 42 </code></pre> <p>So the expression</p> <pre><code>funcs = (int, long, float) </code></pre> <p>takes 3 built-in functions and puts those into a tuple. <code>funcs[0]('10')</code> would return the integer object <code>10</code>, because <code>funcs[0]</code> is another reference to the <code>int()</code> function, so <code>funcs[0]('10')</code> would give you the exact same outcome as <code>int('10')</code>.</p> <p>Those function objects are passed to the <code>testit()</code> function in a loop with:</p> <pre><code> for eachFunc in funcs: print '-' * 20 for eachVal in vals: retval = testit(eachFunc, eachVal) </code></pre> <p>So <code>eachFunc</code> is bound to the function objects that the <code>funcs</code> tuple references, one by one.</p> <p><code>testit()</code> takes that function object as the <code>func</code> parameter, then calls it:</p> <pre><code>def testit(func, *nkwargs, **kwargs): try: retval = func(*nkwargs, **kwargs) </code></pre> <p>so this calls <code>int()</code>, <code>long()</code> and <code>float()</code> on various test values, from the <code>values</code> tuple.</p>
0
2016-10-11T12:28:34Z
[ "python", "function" ]
Why doesn't warp function in Python get executed when I call it?
39,977,254
<p>I have this simple code.</p> <pre><code>def decor(func): def wrap(): print("============") func() print("============") return wrap def print_text(): print("Hello world!") decor(print_text()) </code></pre> <p>Why does this only print "Hello world!" and not the two wrappers? </p>
0
2016-10-11T12:28:19Z
39,977,342
<p>Here you are evaluating <code>print_text</code> (thus printing "Hello World!"), and passing the result to <code>decor</code>:</p> <pre><code>decor(print_text()) </code></pre> <p>Here we are passing <code>print_text</code> to <code>decor</code>, and calling the resulting function which it returns, which is <code>wrap</code>::</p> <pre><code>decor(print_text)() </code></pre> <p>Notice that the first case will NOT call the function returned from <code>decor</code>. Try to call it and see what happens:</p> <pre><code>decor(print_text())() </code></pre> <blockquote> <p>TypeError: 'NoneType' object is not callable</p> </blockquote> <p>because <code>func</code> is now <code>None</code>.</p>
0
2016-10-11T12:33:07Z
[ "python", "wrap" ]
Why doesn't warp function in Python get executed when I call it?
39,977,254
<p>I have this simple code.</p> <pre><code>def decor(func): def wrap(): print("============") func() print("============") return wrap def print_text(): print("Hello world!") decor(print_text()) </code></pre> <p>Why does this only print "Hello world!" and not the two wrappers? </p>
0
2016-10-11T12:28:19Z
39,977,379
<p>That is because you only return the function wrap - It is not called. If you do call it, either by assigning the result to a variable, or by using <code>decor(print_text)()</code> directly. Note that you should use <code>print_text</code> and not <code>print_text()</code>, as the latter will give the result of the function to decor, rather than the function itself. The working version would be:</p> <pre><code>def decor(func): def wrap(): print("============") func() print("============") return wrap def print_text(): print "Hello world!" wrapped_function = decor(print_text) wrapped_function() </code></pre>
0
2016-10-11T12:35:22Z
[ "python", "wrap" ]
Why doesn't warp function in Python get executed when I call it?
39,977,254
<p>I have this simple code.</p> <pre><code>def decor(func): def wrap(): print("============") func() print("============") return wrap def print_text(): print("Hello world!") decor(print_text()) </code></pre> <p>Why does this only print "Hello world!" and not the two wrappers? </p>
0
2016-10-11T12:28:19Z
39,977,387
<p>You are calling <code>decor</code> with a single argument. That argument is whatever <code>print_text()</code> returns. Well, <code>print_text()</code> prints something and then returns None. So far, your output is just <code>Hello world!</code>. None is now passed to <code>decor</code>, and it returns the <code>wrap()</code> function. Nowhere is <code>wrap()</code> actually called, and your final output is just <code>Hello world!</code>.</p> <p>You are misunderstanding the use of decorators. The correct syntax is this:</p> <pre><code>@decor def print_text(): print("Hello world!") </code></pre> <p>That is a shortcut for this:</p> <pre><code>def print_text(): print("Hello world!") print_text = decor(print_text) </code></pre> <p>Now you can see that it is the returns of <code>decor(print_text)</code> (the <code>wrap()</code> function) that is being called, and everything is printed.</p>
0
2016-10-11T12:35:55Z
[ "python", "wrap" ]
Change value property of Circular gauge
39,977,266
<p>Hi I know this is a old and easy question, but I really dont get it. How can I change the value property of my circular gauge dynamicly from python to the qml file? I tried alot but standing again at the beginning. Because I am very new to QT and Python can somebody explain me how to do? I copied the qml and the empty python file here:</p> <p>Python:</p> <pre><code>import sys from PyQt5.QtCore import QObject, QUrl, Qt from PyQt5.QtWidgets import QApplication from PyQt5.QtQml import QQmlApplicationEngine from PyQt5 import QtCore, QtGui if __name__ == "__main__": app = QApplication(sys.argv) engine = QQmlApplicationEngine() engine.load('dashboard.qml') win = engine.rootObjects()[0] win.textUpdated.connect(show) win.show() sys.exit(app.exec_()) </code></pre> <p>And the QML:</p> <pre><code> CircularGauge { value: 66 **(Thats the value I want to change from Python)** maximumValue: 1 width: parent.width height: parent.height * 0.7 y: parent.height / 2 + container.height * 0.01 style: IconGaugeStyle { id: tempGaugeStyle icon: "qrc:/images/temperature-icon.png" maxWarningColor: Qt.rgba(0.5, 0, 0, 1) tickmarkLabel: Text { color: "white" visible: styleData.value === 0 || styleData.value === 1 font.pixelSize: tempGaugeStyle.toPixels(0.225) text: styleData.value === 0 ? "C" : (styleData.value === 1 ? "H" : "") } </code></pre> <p>Thanks a lot for helping a noob :)</p> <p>Actually having this python:</p> <pre><code>class Celsius(QObject): def __init__(self, temperature = 0.6): self._temperature = temperature @property def temperature(self): print("Getting value") return self._temperature @temperature.setter def temperature(self, value): if value &lt; -273: raise ValueError("Temperature below -273 is not possible") print("Setting value") self._temperature = value rotatevalue = Celsius() print(rotatevalue.temperature) if __name__ == "__main__": app = QApplication(sys.argv) engine = QQmlApplicationEngine() engine.load('dashboard.qml') view = QQuickView() root_context = view.rootContext().setContextProperty("valuepy", Celsius()) win = engine.rootObjects()[0] win.textUpdated.connect(show) win.show() sys.exit(app.exec_()) </code></pre> <p>QML is the same. If I print rotatevalue.temperature, I have the right value in this variable but the connection to the qml is still a problem. Python says on running following:</p> <p>root_context = view.rootContext().setContextProperty("valuepy", Celsius()) RuntimeError: super-class <strong>init</strong>() of type Celsius was never called.</p> <p>And the value is not in my gauge. Any ideas?</p>
1
2016-10-11T12:28:50Z
40,047,920
<p>I am unfortunately not able to help you with the Python syntax but this is how that would look in C++</p> <pre><code>class Celsius : public QObject { Q_OBJECT Q_PROPERTY(double temperature READ temperature WRITE setTemperature NOTIFY temperatureChanged) public: explicit Celsius(double temperature = 0.6, QObject *parent = 0) : QObject(parent), m_temperature(temperature) {} double temperature() const { return m_temperature; } void setTemperature(double temperature) { if (temperature == m_temperature) return; if (temperature &lt; -273) return; m_temperature = temperature; emit temperatureChanged(); } signals: void temperatureChanged(); }; </code></pre> <p>Maybe someone with PytQt know-how can propose an edit or base their own answer on that.</p>
0
2016-10-14T16:27:29Z
[ "python", "qt", "pyqt5", "circular", "gauge" ]
Change value property of Circular gauge
39,977,266
<p>Hi I know this is a old and easy question, but I really dont get it. How can I change the value property of my circular gauge dynamicly from python to the qml file? I tried alot but standing again at the beginning. Because I am very new to QT and Python can somebody explain me how to do? I copied the qml and the empty python file here:</p> <p>Python:</p> <pre><code>import sys from PyQt5.QtCore import QObject, QUrl, Qt from PyQt5.QtWidgets import QApplication from PyQt5.QtQml import QQmlApplicationEngine from PyQt5 import QtCore, QtGui if __name__ == "__main__": app = QApplication(sys.argv) engine = QQmlApplicationEngine() engine.load('dashboard.qml') win = engine.rootObjects()[0] win.textUpdated.connect(show) win.show() sys.exit(app.exec_()) </code></pre> <p>And the QML:</p> <pre><code> CircularGauge { value: 66 **(Thats the value I want to change from Python)** maximumValue: 1 width: parent.width height: parent.height * 0.7 y: parent.height / 2 + container.height * 0.01 style: IconGaugeStyle { id: tempGaugeStyle icon: "qrc:/images/temperature-icon.png" maxWarningColor: Qt.rgba(0.5, 0, 0, 1) tickmarkLabel: Text { color: "white" visible: styleData.value === 0 || styleData.value === 1 font.pixelSize: tempGaugeStyle.toPixels(0.225) text: styleData.value === 0 ? "C" : (styleData.value === 1 ? "H" : "") } </code></pre> <p>Thanks a lot for helping a noob :)</p> <p>Actually having this python:</p> <pre><code>class Celsius(QObject): def __init__(self, temperature = 0.6): self._temperature = temperature @property def temperature(self): print("Getting value") return self._temperature @temperature.setter def temperature(self, value): if value &lt; -273: raise ValueError("Temperature below -273 is not possible") print("Setting value") self._temperature = value rotatevalue = Celsius() print(rotatevalue.temperature) if __name__ == "__main__": app = QApplication(sys.argv) engine = QQmlApplicationEngine() engine.load('dashboard.qml') view = QQuickView() root_context = view.rootContext().setContextProperty("valuepy", Celsius()) win = engine.rootObjects()[0] win.textUpdated.connect(show) win.show() sys.exit(app.exec_()) </code></pre> <p>QML is the same. If I print rotatevalue.temperature, I have the right value in this variable but the connection to the qml is still a problem. Python says on running following:</p> <p>root_context = view.rootContext().setContextProperty("valuepy", Celsius()) RuntimeError: super-class <strong>init</strong>() of type Celsius was never called.</p> <p>And the value is not in my gauge. Any ideas?</p>
1
2016-10-11T12:28:50Z
40,088,966
<p>For anybode having the same problem, I found out, here is the code which seems to go right, thanks a lot for all the helping:</p> <pre><code>class Celsius(QObject): def __init__(self, parent=None): super().__init__(parent) self.temperature = 0.3 @pyqtProperty(int) def temperature(self): return self._temperature # Define the setter of the 'temperature' property. @temperature.setter def temperature(self, temperature): self._temperature = temperature rotatevalue = Celsius() print(rotatevalue.temperature) rot = rotatevalue.temperature if __name__ == "__main__": app = QApplication(sys.argv) qmlRegisterType(Celsius, 'Celsius', 1, 0, 'Celsius') view = QQuickView() engine = QQmlApplicationEngine() engine.rootContext().setContextProperty('valuepy', rot) engine.load('dashboard.qml') win = engine.rootObjects()[0] win.show() sys.exit(app.exec_()) </code></pre>
0
2016-10-17T14:24:12Z
[ "python", "qt", "pyqt5", "circular", "gauge" ]
SQLAlchemy: How to properly use Relationship()?
39,977,367
<p>I went through the docs, and <strong>think</strong> I've structured everything correctly, but struggling to implement it. </p> <p>There's two pieces to this: The use case is when I look at a resume, each resume has multiple jobs. Then the sum of all of those jobs determines the value of the entire resume. </p> <p>I've set up two tables &amp; corresponding classes. </p> <pre><code>from sqlalchemy import Column, Integer, String from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import relationship from sqlalchemy import ForeignKey Base = declarative_base() engine = create_engine('sqlite:///candidate.db', echo=True) class Candidate_Evaluation(Base): __tablename__ = 'candidate_evaluation' id = Column(Integer, primary_key=True) label = Column(String) url = Column(String) string_of_job_evals = Column(String) job_evaluation_relationship = relationship("Job_Evaluation", back_populates="candidate_evalution") def __repr__(self): "&lt;Candidate(URL = '%s', label = '%s', job evaluations = '%s')&gt;" % (self.url, self.label, self.string_of_job_evals) class Job_Evaluation(Base): __tablename__ = 'job_evaluation' id = Column(Integer, primary_key=True) candidate_evaluation_id = Column(Integer, ForeignKey('candidate_evaluation.id')) # details = Column(String) label = Column(String) candidate_evaluation_relationship = relationship("Candidate_Evaluation", back_populates='job_evaluation') def __repr__(self): "&lt;Job(label = '%s', details = '%s')&gt;" %(self.label, self.details) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() job = Job_Evaluation(label = 'front_end', details = 'javascript jquery html css') session.add(job) session.commit() </code></pre> <p>However, I'm running into a problem when I try to add records to the <code>job_evaluation</code> table. I <strong>think</strong> it has to do with how I've set up the relationship between them.</p> <p>The goal is that I can add job evaluation to the database and then link it to the candidate evaluation. It's a Many to One relationship, but the Many comes first. Is that possible? </p> <p>I'm getting the error: </p> <p><code>sqlalchemy.exc.InvalidRequestError: Mapper 'Mapper|Job_Evaluation|job_evaluation' has no property 'candidate_evalution'</code></p> <p>What am I doing wrong?</p>
2
2016-10-11T12:34:47Z
39,977,944
<p>I struggled with this in my early days of using sqlalchemy.</p> <p>As stated in the docs:</p> <blockquote> <p>Takes a string name and has the same meaning as backref, except the complementing property is not created automatically, and instead must be configured explicitly on the other mapper. The complementing property should also indicate back_populates to this relationship to ensure proper functioning.</p> </blockquote> <pre><code>class Candidate_Evaluation(Base): __tablename__ = 'candidate_evaluation' id = Column(Integer, primary_key=True) label = Column(String) url = Column(String) string_of_job_evals = Column(String) job_evaluation_relationship = relationship("Job_Evaluation", backref ="candidate_evalution") def __repr__(self): "&lt;Candidate(URL = '%s', label = '%s', job evaluations = '%s')&gt;" % (self.url, self.label, self.string_of_job_evals) class Job_Evaluation(Base): __tablename__ = 'job_evaluation' id = Column(Integer, primary_key=True) candidate_evaluation_id = Column(Integer, ForeignKey('candidate_evaluation.id')) # details = Column(String) label = Column(String) candidate_evaluation_relationship = relationship("Candidate_Evaluation", backref = job_evaluation') def __repr__(self): "&lt;Job(label = '%s', details = '%s')&gt;" %(self.label, self.details) </code></pre> <p>Just replace <code>back_populates</code> with <code>backref</code>.</p>
0
2016-10-11T13:05:59Z
[ "python" ]
how to use for loop to create right angled triangle?
39,977,395
<pre><code>I want to print : 1 12 123 1234 </code></pre> <p>and i have tried:</p> <pre><code>num=int(input("number")) space=int(num) count=1 while count&lt;num: if count==1: print(" "*space,count) count=count+1 space=space-1 while count&gt;=2: for n in range(2,num): print(" "*space,list(range(1,n)) space=space-1 </code></pre> <p>But it doesn't work. How can i print the designated result ? Thanks</p>
-3
2016-10-11T12:36:32Z
39,978,230
<pre><code>print(" "*space,list(range(1,n)) </code></pre> <p>Count the parentheses on this line. One of them isn't closed, which it has to be to work as you intend. </p> <p>Also note that your <code>while</code> loop will never stop running.</p> <p>As a general rule of thumb, whenever you know exactly how many times you should do something, you should use a <code>for</code> loop instead of a <code>while</code> loop</p> <p>Let's try to rewrite you code using a <code>for</code> loop:</p> <pre><code>num=int(input("number")) output = "" for n in range(1,num+1): output = ''.join([output, str(n)]) space = ' ' * (num - len(output)) print(space, output, sep='') </code></pre> <p>The only real substantive change I made other than a <code>for</code> loop is treating the output as a string rather than a list of numbers. </p>
0
2016-10-11T13:19:52Z
[ "python" ]
List dictionaries in documentation with Sphinx
39,977,507
<p>I have a project with a few .py files that only contains a few dictionaries. Like this:</p> <pre><code># My file dictionary = {'key1': 'value1', 'key2: 'value2'} </code></pre> <p>But much larger and longer and I would like to document this with Sphinx but I can't get it to work properly. </p> <p>The files are found by Sphinx just fine and show up under Modules as folder.file but they are all empty? What am I doing wrong? Why won't the dictionaries show up?</p> <p>in the .rst file for the folder it shows: </p> <pre><code> folder.file module -------------------- .. automodule:: folder.file :members: :undoc-members: :show-inheritance: </code></pre> <p>Am I missing something? Thanks in advance!</p>
0
2016-10-11T12:42:33Z
39,977,606
<p>Sphinx does require extra docstrings for all members that are not classes or methods. You probably don't want to edit <code>autodoc</code> (even though this can come handy for individualization under certain conditions), you can overcome this issue by adding a docstring <strong>below</strong> the variable:</p> <pre><code># My file dictionary = {'key1': 'value1', 'key2': 'value2'} '''A dictionary containing secret values. Do not expose this dictionary's values to the public. By default, the keys 'key1' and 'key2' are available.''' </code></pre>
1
2016-10-11T12:47:34Z
[ "python", "dictionary", "documentation", "python-sphinx", "autodoc" ]
Python TCP socket.error with long messages
39,977,583
<p>I'm trying to send a basic message across my LAN network via TCP in Python. TCPClient.py:</p> <pre><code>import socket, sys, time TCP_IP = "10.0.0.10" TCP_PORT = 5005 BUFFER_SIZE = 1024 running = True while running == True: try: MESSAGE = raw_input("Message: ") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("Connecting...") s.connect((TCP_IP,TCP_PORT)) print("Connected!") s.send(MESSAGE) data = s.recv(BUFFER_SIZE) s.close() print("Sent data: %s" % MESSAGE) print("Recieved data: %s" % data) running = False time.sleep(20) except socket.error as e: print(e) time.sleep(1) except: print(sys.exc_info()[0]) time.sleep(1) </code></pre> <p>And TCPServer.py:</p> <pre><code>import socket, time, sys TCP_IP = "10.0.0.10" TCP_PORT = 5005 BUFFER_SIZE = 20 while True: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((TCP_IP,TCP_PORT)) print("Listening for connection...") s.listen(1) conn,addr = s.accept() while 1: data = conn.recv(BUFFER_SIZE) if not data: break print("Recieved data: %s" % data) conn.send(data.upper()) print("Sent data: %s" % data.upper()) conn.close() except TypeError as e: print(e) except ValueError as e: print(e) except socket.error as e: print(e) except: print(sys.exc_info()[0]) time.sleep(1) </code></pre> <p>It mostly works for small messages (like "hello world") but when I send a message more than ~10 characters it splits it into 2 sections and sometimes doesn't even send half of it. E.g:</p> <p><a href="https://i.stack.imgur.com/3Ccer.png" rel="nofollow"><img src="https://i.stack.imgur.com/3Ccer.png" alt="running both scripts"></a></p> <p>Thanks for any help in advanced! much appreciated.</p>
0
2016-10-11T12:46:11Z
39,978,067
<p>Here's what happened: </p> <ol> <li>your client sent long line</li> <li>your server got 20 characters of that long line (that's size of your buffer on server side)</li> <li>your server sent back data (20 characters of line) to client</li> <li>your client got data and disconnected from server, causing server to raise exception.</li> </ol>
0
2016-10-11T13:11:50Z
[ "python", "sockets", "tcp" ]
Apply a map to DataFrame rows which are NaN
39,977,656
<p>I want to apply a mapping to a Pandas DataFrame, where some rows in one specific column are <code>NaN</code>. These are left overs from a prior mapping.</p> <pre><code>mymap = defaultdict(str) mymap["a"] = "-1 test" mymap["b"] = "-2 test" mymap["c"] = "-3 test" df[ df["my_infos"].isnull() ] = df["something"].map(lambda ip: map_function(ip, mymap)) </code></pre> <p>Here is the function:</p> <pre><code>def map_function(ip, mymap): # do stuff for key, value in mymap.iteritems(): # do stuff return stuff return other_stuff </code></pre> <p>This terminates after it iterates over the whole column, but shows:</p> <blockquote> <p>File "/opt/anaconda2/lib/python2.7/site-packages/pandas/core/indexing.py", line 527, in _setitem_with_indexer raise ValueError('Must have equal len keys and value ' ValueError: Must have equal len keys and value when setting with an iterable</p> </blockquote> <p>Is this the correct way to select all rows in the <code>my_infos</code> column, which are NaN? I somehow sense... that's not the case.</p>
2
2016-10-11T12:50:34Z
39,977,771
<p>I think you can select <code>NaN</code> values to both sides and then <code>map</code>:</p> <pre><code>df[ df["my_infos"].isnull() ] = df.ix[ df["my_infos"].isnull(), "something"].map(lambda ip: map_function(ip, mymap)) </code></pre>
1
2016-10-11T12:56:05Z
[ "python", "pandas" ]
Twisted threading and Thread Pool Difference
39,977,750
<p>What is the difference between using</p> <pre><code>from twisted.internet import reactor, threads </code></pre> <p>and just using</p> <pre><code>import thread </code></pre> <p>using a thread pool?</p> <p>What is the twisted thing actually doing? Also, is it safe to use twisted threads?</p>
0
2016-10-11T12:55:11Z
39,982,780
<blockquote> <p>What is the difference</p> </blockquote> <p>With <code>twisted.internet.threads</code>, Twisted will manage the thread and a thread pool for you. This puts less of a burden on devs and allows devs to focus more on the business logic instead of dealing with the idiosyncrasies of threaded code. If you <code>import thread</code> yourself, then you have to manage threads, get the results from threads, ensure results are synchronized, make sure too many threads don't start up at once, fire a callback once the threads are complete, etc.</p> <blockquote> <p>What is the twisted thing actually doing?</p> </blockquote> <p>It depends on what "thing" you're talking about. Can you be more specific? Twisted has various thread functions you can leverage and each may function slightly different from each other.</p> <blockquote> <p>And is it safe to use twisted threads.</p> </blockquote> <p>It's absolutely safe! I'd say it's more safe than managing threads yourself. Take a look at all the functionality that Twisted's thread provides, then think about if you had to write this code yourself. If you've ever worked with threads, you'll know what it starts off simple enough, but as your application grows and if you didn't make good decisions about threads, then your application can become very complicated and messy. In general, Twisted will handle the threads in a uniform way and in a way that devs would expect a well behaved threaded app to behave.</p> <h1>References</h1> <ul> <li><a href="https://twistedmatrix.com/documents/current/core/howto/threading.html" rel="nofollow">https://twistedmatrix.com/documents/current/core/howto/threading.html</a></li> </ul>
0
2016-10-11T17:04:59Z
[ "python", "multithreading", "security", "threadpool", "twisted" ]
python: grab a specific line after a match
39,977,812
<p>I have have df full of text<br> I would like to define variable <strong>date</strong> which is always three lines after <strong>version</strong>. here is my code</p> <pre><code>with open(input_file1,'r') as f: for i, line in enumerate(f): if line.startswith('Version'): version = line.strip() date = line + 3 print(line,date) </code></pre> <p>but it does not work for the <strong>date</strong> variable and i receive the following error. Can anybody help?</p> <pre><code>TypeError: Can't convert 'int' object to str implicitly </code></pre>
0
2016-10-11T12:58:29Z
39,978,024
<p><code>line</code> is the string contents of the line in the file. <code>i</code> is the incrementally increasing index of the line being parsed. Therefore you want to read line number <code>i+3</code>. You can read three lines ahead easily if you read all the lines into memory with <code>.readlines()</code>.<br> <strong>NOTE</strong> this is not advisable if your files are very large!</p> <pre><code>with open(input_file1,'r') as f: lines = f.readlines() for i, line in enumerate(lines): if line.startswith('Version'): version = line.strip() date = lines[i + 3].strip() print(line,date) </code></pre>
1
2016-10-11T13:09:56Z
[ "python", "loops", "lines" ]
python: grab a specific line after a match
39,977,812
<p>I have have df full of text<br> I would like to define variable <strong>date</strong> which is always three lines after <strong>version</strong>. here is my code</p> <pre><code>with open(input_file1,'r') as f: for i, line in enumerate(f): if line.startswith('Version'): version = line.strip() date = line + 3 print(line,date) </code></pre> <p>but it does not work for the <strong>date</strong> variable and i receive the following error. Can anybody help?</p> <pre><code>TypeError: Can't convert 'int' object to str implicitly </code></pre>
0
2016-10-11T12:58:29Z
39,978,112
<p>What the error message is telling you is that you cannot add a number to a string.</p> <p>You first need to convert the string to a datetime object, to which you can then add anything you want.</p> <p>Check out the <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow">datetime documentation here</a>.</p> <p>In your case, you might want to try something like:</p> <pre><code>import datetime Date = datetime.datetime.strptime(line, "%m/%d/%Y") </code></pre> <p>Where the second set of arguments determine the format of the date you are feeding the datetime object via your line variable. You will have to change this bit ("%m/%d/%Y") to match your input.</p>
0
2016-10-11T13:14:13Z
[ "python", "loops", "lines" ]
Nuke Python list of objects order based on other list
39,977,832
<p>I got two lists. First one looks like this:</p> <pre><code>passOrder = [ 'direct_diffuse', 'direct_specular', 'direct_specular_2', 'indirect_diffuse', 'indirect_specular', 'indirect_specular_2', 'refraction', 'reflection', 'emission', 'sss' ] </code></pre> <p>and the other one is a list of objects - in this case Nuke nodes:</p> <pre><code>nodes = nuke.selectedNodes() </code></pre> <p>I'm trying to compare each node's name parameter with passOrder list and arrange them in the order given in passOrder. I tried to explicitly set up orderedNodes index but I guess it's not possible when the list is empty at start.</p> <pre><code>orderedNodes = [] for n in nodes: for index, p in enumerate(passOrder): if n['name'].value() == p: orderedNodes.insert(index, n) </code></pre> <p>I've also tried to zip both lists, and sort them - no luck here. Basically I have no idea how to iterate over <code>n['name'].value()</code> component when sorting.</p>
0
2016-10-11T12:59:46Z
39,977,897
<p>I don't know what your class/function definitions look like, so I'm using these stubs to illustrate my solution:</p> <pre><code>class Thing: def __init__(self, value): self.val = value def value(self): return self.val class Nuke: def __init__(self, name): self.n = {"name": Thing(name)} def __repr__(self): return "Node({})".format(repr(self.n["name".value())) def selectedNodes(): return [Nuke("refraction"), Nuke("direct_diffuse"), Nuke("emission")] </code></pre> <p>You could sort <code>nodes</code>, using <code>passOrder.index</code> for its key parameter:</p> <pre><code>passOrder = [ 'direct_diffuse', 'direct_specular', 'direct_specular_2', 'indirect_diffuse', 'indirect_specular', 'indirect_specular_2', 'refraction', 'reflection', 'emission', 'sss' ] nodes = selectedNodes() nodes.sort(key=lambda item: passOrder.index(item.n["name"].value())) print nodes </code></pre> <p>Result:</p> <pre><code>[Node('direct_diffuse'), Node('refraction'), Node('emission')] </code></pre>
2
2016-10-11T13:03:39Z
[ "python", "list", "sorting", "object", "nuke" ]
Nuke Python list of objects order based on other list
39,977,832
<p>I got two lists. First one looks like this:</p> <pre><code>passOrder = [ 'direct_diffuse', 'direct_specular', 'direct_specular_2', 'indirect_diffuse', 'indirect_specular', 'indirect_specular_2', 'refraction', 'reflection', 'emission', 'sss' ] </code></pre> <p>and the other one is a list of objects - in this case Nuke nodes:</p> <pre><code>nodes = nuke.selectedNodes() </code></pre> <p>I'm trying to compare each node's name parameter with passOrder list and arrange them in the order given in passOrder. I tried to explicitly set up orderedNodes index but I guess it's not possible when the list is empty at start.</p> <pre><code>orderedNodes = [] for n in nodes: for index, p in enumerate(passOrder): if n['name'].value() == p: orderedNodes.insert(index, n) </code></pre> <p>I've also tried to zip both lists, and sort them - no luck here. Basically I have no idea how to iterate over <code>n['name'].value()</code> component when sorting.</p>
0
2016-10-11T12:59:46Z
39,978,014
<p>You can construct a dictionary mapping node names to nodes like this</p> <pre><code>nodes_by_name = {n['name'].value(): n for n in nodes} </code></pre> <p>With this dictionary, it's trivial to retrieve the nodes in the desired order:</p> <pre><code>ordered_nodes = [nodes_by_name[name] for name in passOrder] </code></pre> <p>If there might be names in <code>passOrder</code> without corresponding nodes, you can simply skip them:</p> <pre><code>ordered_nodes = [nodes_by_name[name] for name in passOrder if name in nodes_by_name] </code></pre> <p>This approach is simpler and more efficient than trying to use sorting.</p>
0
2016-10-11T13:09:23Z
[ "python", "list", "sorting", "object", "nuke" ]
Nuke Python list of objects order based on other list
39,977,832
<p>I got two lists. First one looks like this:</p> <pre><code>passOrder = [ 'direct_diffuse', 'direct_specular', 'direct_specular_2', 'indirect_diffuse', 'indirect_specular', 'indirect_specular_2', 'refraction', 'reflection', 'emission', 'sss' ] </code></pre> <p>and the other one is a list of objects - in this case Nuke nodes:</p> <pre><code>nodes = nuke.selectedNodes() </code></pre> <p>I'm trying to compare each node's name parameter with passOrder list and arrange them in the order given in passOrder. I tried to explicitly set up orderedNodes index but I guess it's not possible when the list is empty at start.</p> <pre><code>orderedNodes = [] for n in nodes: for index, p in enumerate(passOrder): if n['name'].value() == p: orderedNodes.insert(index, n) </code></pre> <p>I've also tried to zip both lists, and sort them - no luck here. Basically I have no idea how to iterate over <code>n['name'].value()</code> component when sorting.</p>
0
2016-10-11T12:59:46Z
39,978,016
<p>You don't have to code the sort yourself.</p> <pre><code>ordered_nodes = sorted(nodes, key=lambda n: passOrder.index(n["name"].value()) if n["name"].value() in passOrder else len(passOrder)) </code></pre>
1
2016-10-11T13:09:42Z
[ "python", "list", "sorting", "object", "nuke" ]
gcloud.exceptions.Forbidden: 403 Missing or insufficient permissions
39,978,077
<p>I am a new to Google Cloud Platform. I have setup a Google VM Instance. I am facing an authentication issue on Local Machine while running the command:</p> <p><code>python manage.py makemigrations</code></p> <p>Can you please suggest some tips/steps to resolve the same ? </p> <p><strong>Error Trace</strong></p> <pre><code> File "/constants.py", line 18, in &lt;module&gt; table_data = datastore_fetch(project_id, entity_kind) File "/datastore_helper.py", line 23, in datastore_fetch results = list(query.fetch()) File "/venv/local/lib/python2.7/site-packages/gcloud/datastore/query.py", line 463, in __iter__ self.next_page() File "/venv/local/lib/python2.7/site-packages/gcloud/datastore/query.py", line 434, in next_page transaction_id=transaction and transaction.id, File "/venv/local/lib/python2.7/site-packages/gcloud/datastore/connection.py", line 286, in run_query _datastore_pb2.RunQueryResponse) File "/venv/local/lib/python2.7/site-packages/gcloud/datastore/connection.py", line 124, in _rpc data=request_pb.SerializeToString()) File "/venv/local/lib/python2.7/site-packages/gcloud/datastore/connection.py", line 98, in _request raise make_exception(headers, error_status.message, use_json=False) gcloud.exceptions.Forbidden: 403 Missing or insufficient permissions. </code></pre> <p>Other Info:</p> <pre><code>gcloud auth list Credentialed Accounts: - [email protected] ACTIVE To set the active account, run: $ gcloud config set account `ACCOUNT` gcloud config list Your active configuration is: [default] [core] account = [email protected] disable_usage_reporting = True project = user_project </code></pre> <p><strong>Input:</strong> (Standalone Python Function)</p> <pre><code>from gcloud import datastore client = datastore.Client('user_project') print(vars(client.connection.credentials)) </code></pre> <p><strong>Output:</strong></p> <pre><code>{'scopes': set([]), 'revoke_uri': 'https://accounts.google.com/o/oauth2/revoke', 'access_token': None, 'token_uri': 'https://www.googleapis.com/oauth2/v4/token', 'token_info_uri': None, 'token_response': None, 'invalid': False, 'refresh_token': u'1/t-V_pZicXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'client_id': u'3XXXXXXXX9.apps.googleusercontent.com', 'id_token': None, 'client_secret': u'ZXXXXXXXXXXXXXXXXXXX2', 'token_expiry': None, 'store': None, 'user_agent': 'Python client library'} </code></pre> <p><strong>VM Details</strong></p> <pre><code>Firewalls Allow HTTP traffic Allow HTTPS traffic Availability policies Preemptibility Off (recommended) Automatic restart On (recommended) On host maintenance Migrate VM instance (recommended) Custom metadata None SSH Keys Block project-wide SSH keys None Service account service-account@user_project.iam.gserviceaccount.com Cloud API access scopes This instance has full API access to all Google Cloud services. </code></pre> <p>Thanks,</p>
1
2016-10-11T13:12:16Z
39,981,814
<p>Just ran these two commands:</p> <pre><code> 1. gcloud beta auth application-default login 2. export GOOGLE_APPLICATION_CREDENTIALS='/&lt;path_to_json&gt;/client_secrets.json' </code></pre> <p>from local machine and it started working.</p>
0
2016-10-11T16:08:50Z
[ "python", "django", "google-cloud-storage", "google-cloud-platform", "google-cloud-datastore" ]
gcloud.exceptions.Forbidden: 403 Missing or insufficient permissions
39,978,077
<p>I am a new to Google Cloud Platform. I have setup a Google VM Instance. I am facing an authentication issue on Local Machine while running the command:</p> <p><code>python manage.py makemigrations</code></p> <p>Can you please suggest some tips/steps to resolve the same ? </p> <p><strong>Error Trace</strong></p> <pre><code> File "/constants.py", line 18, in &lt;module&gt; table_data = datastore_fetch(project_id, entity_kind) File "/datastore_helper.py", line 23, in datastore_fetch results = list(query.fetch()) File "/venv/local/lib/python2.7/site-packages/gcloud/datastore/query.py", line 463, in __iter__ self.next_page() File "/venv/local/lib/python2.7/site-packages/gcloud/datastore/query.py", line 434, in next_page transaction_id=transaction and transaction.id, File "/venv/local/lib/python2.7/site-packages/gcloud/datastore/connection.py", line 286, in run_query _datastore_pb2.RunQueryResponse) File "/venv/local/lib/python2.7/site-packages/gcloud/datastore/connection.py", line 124, in _rpc data=request_pb.SerializeToString()) File "/venv/local/lib/python2.7/site-packages/gcloud/datastore/connection.py", line 98, in _request raise make_exception(headers, error_status.message, use_json=False) gcloud.exceptions.Forbidden: 403 Missing or insufficient permissions. </code></pre> <p>Other Info:</p> <pre><code>gcloud auth list Credentialed Accounts: - [email protected] ACTIVE To set the active account, run: $ gcloud config set account `ACCOUNT` gcloud config list Your active configuration is: [default] [core] account = [email protected] disable_usage_reporting = True project = user_project </code></pre> <p><strong>Input:</strong> (Standalone Python Function)</p> <pre><code>from gcloud import datastore client = datastore.Client('user_project') print(vars(client.connection.credentials)) </code></pre> <p><strong>Output:</strong></p> <pre><code>{'scopes': set([]), 'revoke_uri': 'https://accounts.google.com/o/oauth2/revoke', 'access_token': None, 'token_uri': 'https://www.googleapis.com/oauth2/v4/token', 'token_info_uri': None, 'token_response': None, 'invalid': False, 'refresh_token': u'1/t-V_pZicXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'client_id': u'3XXXXXXXX9.apps.googleusercontent.com', 'id_token': None, 'client_secret': u'ZXXXXXXXXXXXXXXXXXXX2', 'token_expiry': None, 'store': None, 'user_agent': 'Python client library'} </code></pre> <p><strong>VM Details</strong></p> <pre><code>Firewalls Allow HTTP traffic Allow HTTPS traffic Availability policies Preemptibility Off (recommended) Automatic restart On (recommended) On host maintenance Migrate VM instance (recommended) Custom metadata None SSH Keys Block project-wide SSH keys None Service account service-account@user_project.iam.gserviceaccount.com Cloud API access scopes This instance has full API access to all Google Cloud services. </code></pre> <p>Thanks,</p>
1
2016-10-11T13:12:16Z
39,987,101
<p>The behavior for application default credentials has <a href="https://cloud.google.com/sdk/release_notes#12800_20160928" rel="nofollow">changed</a> in <code>gcloud</code> since version 128.</p> <p>One should use</p> <pre><code>gcloud auth application-default login </code></pre> <p>instead. </p> <p>Note that changing credentials via <code>gcloud auth login</code> or <code>gcloud init</code> or <code>gcloud config set account MY_ACCOUNT</code> will NOT affect application default credentials, they managed separately from gcloud credentials.</p>
3
2016-10-11T21:32:10Z
[ "python", "django", "google-cloud-storage", "google-cloud-platform", "google-cloud-datastore" ]
Can read() and readline() be used together?
39,978,085
<p>Is it possible to use both read() and readline() on one text file in python?</p> <p>When I did that, it will only do the first reading function.</p> <pre><code>file = open(name, "r") inside = file.readline() inside2 = file.read() print(name) print(inside) print(inside2) </code></pre> <p>The result shows only the <code>inside</code> variable, not <code>inside2</code>.</p>
2
2016-10-11T13:12:30Z
39,978,203
<p>Yes you can.</p> <p><code>file.readline()</code> reads a line from the file (the first line in this case), and then <code>file.read()</code> reads the rest of the file starting from the <em>seek</em> position, in this case, where <code>file.readline()</code> left off.</p> <p>You are receiving an empty string with <code>f.read()</code> probably because you reached <em>EOF</em> - End of File immediately after reading the first line with <code>file.readline()</code> implying your file only contains one line.</p> <p>You can however return to the start of the file by moving the seek position to the start with <code>f.seek(0)</code>.</p>
1
2016-10-11T13:18:50Z
[ "python" ]
Can read() and readline() be used together?
39,978,085
<p>Is it possible to use both read() and readline() on one text file in python?</p> <p>When I did that, it will only do the first reading function.</p> <pre><code>file = open(name, "r") inside = file.readline() inside2 = file.read() print(name) print(inside) print(inside2) </code></pre> <p>The result shows only the <code>inside</code> variable, not <code>inside2</code>.</p>
2
2016-10-11T13:12:30Z
39,978,214
<p>Reading a file is like reading a book. When you say <code>.read()</code>, it reads through the book until the end. If you say <code>.read()</code> again, well you forgot one step. You can't read it again unless you flip back the pages until you're at the beginning. If you say <code>.readline()</code>, we can call that a page. It tells you the contents of the page and then turns the page. Now, saying <code>.read()</code> starts there and reads to the end. That first page isn't included. If you want to start at the beginning, you need to turn back the page. The way to do that is with the <code>.seek()</code> method. It is given a single argument: a character position to seek to:</p> <pre><code>with open(name, 'r') as file: inside = file.readline() file.seek(0) inside2 = file.read() </code></pre> <p>There is also another way to read information from the file. It is used under the hood when you use a <code>for</code> loop:</p> <pre><code>with open(name) as file: for line in file: ... </code></pre> <p>That way is <code>next(file)</code>, which gives you the next line. This way is a little special, though. If <code>file.readline()</code> or <code>file.read()</code> comes after <code>next(file)</code>, you will get an error that mixing iteration and read methods would lose data. (Credits to Sven Marnach for pointing this out.)</p>
3
2016-10-11T13:19:14Z
[ "python" ]
Python: print ALL argparse arguments including defaults
39,978,186
<p>I want to log the usage of a python program which uses the argparse module. Currently, the logger records the command line usage similar to the answer given in <a href="http://stackoverflow.com/questions/8542725/how-can-i-print-all-arguments-passed-to-a-python-script">this post</a>. However, that only gives the commandline arguments, and not including the defaults set later in argparse (which is the intended use, after all). Is there a simple way to print ALL the argparse options to create a nice, tidy <code>usage</code> log entry that includes the default values?</p> <p>It isn't difficult to go into the argparse namespace to fetch each argument by name, but I am hoping that someone has a concise way of extracting the needed info. </p> <p>Any direction is appreciated!</p>
0
2016-10-11T13:17:58Z
39,978,305
<p>I've done something similar in an application, hopefully the below snippets give you what you need. It is the call to vars that gave me a dictionary of all the arguments.</p> <pre><code>parser = argparse.ArgumentParser(description='Configure') .... args = parser.parse_args() ...... options = vars(args) </code></pre>
2
2016-10-11T13:24:09Z
[ "python", "logging", "namespaces", "argparse", "sys" ]
saltstack - execute a state inside a reactor written in python
39,978,293
<p>I am trying to create a reactor in Python + Jinja to react to some event. The documentation has fairly good examples on how to create reactors using the YAML format. However, the documentation for creating a reactor in Python is quite lacking. </p> <p>Here is what I got so far:</p> <pre><code>#!jinja|py """ reactors can be also complete Python programs instead of Jinja + YAML """ def run(): ''' I can have fairly complex logic here, but it is all executed on the master. ''' # I can define variable like this var = "{{ data['id'] }}" # this is the id of the minion that sent the signal # I can call a salt module like this: __salt__['pkg.install']('figlet') # this will install figlet on the master return {} </code></pre> <p>The documentation states </p> <blockquote> <p>The SLS file should contain a function called run which returns high state data.</p> </blockquote> <p>But so far I fail to see how I can target the desired minion from this dictionary. I know I can use the <a href="https://docs.saltstack.com/en/latest/ref/clients/index.html" rel="nofollow">salt API</a>, but I would like to avoid this at the moment.</p> <p>Can someone here give an example how you can call a state and target and a minion by returning the correct high state data?</p>
1
2016-10-11T13:23:25Z
40,038,252
<p>So, it turns out, my way of accessing the context data was wrong. There is no need to wrap the python script in Jinja. Unfortunately this is undocumented at the moment. If you write a state or a returner in Python everything that was inside</p> <pre><code>{{ data }} # in Jinja + YAML </code></pre> <p>Is now available with a global variable called (not suprisingly) <code>data</code>. This variable is a dictionary too. </p> <pre><code>#!py def run(): ''' ''' # I can define variable like this var = data['id'] # this is the id of the minion that sent the signal return {} </code></pre>
2
2016-10-14T08:15:09Z
[ "python", "salt-stack" ]
Making a String with literal r and variables Python
39,978,308
<p>I'm currently trying to make abstract methods for something like this:</p> <pre><code>preset_create("TaggingAgain", r'{"weight": 0, "precondition": "{\"_tags\":\"tagged\"}"}') </code></pre> <p>In my abstraction the User is able to make Precondition objects within a Preset object which then gets created.</p> <p>It's currently something like this:</p> <pre><code>data = str({"weight" : preset.weight, "precondition" : "{}"}) data = data.replace("\'", "\"") data = data.replace("}\"", "\"%(n)s\":\"%(v)s\"}" % {"n" : precondition.name,"v" : precondition.value}) </code></pre> <p>(shortened Version because I'll add being able to add multiple preconditions with a "for in" later)</p> <p>My problem is that the {\"_tags\":\"tagged\"} part needs to be in r'' to work and I don't know how to do that when there are variables in it.</p> <p>Other code that might help understanding:</p> <pre><code>class Precondition(object): def __init__(self, name, operator, value): self.name = name self.value = value class Preset(object): def __init__(self, name, weight, *preconditions): self.name = name self.weight = weight self.preconditions = preconditions precondition = Precondition("_tag", "", "tagged") createdPreset = Preset("TaggingAgain", "0", precondition) preset_create(createdPreset) </code></pre>
0
2016-10-11T13:24:17Z
40,000,949
<p>If anybody else needs this in the future, heres how I've done it (using json which gre_gor posted a link to in a comment to my question).</p> <p>Starting with the string:</p> <pre><code>precon = ("{\"%(n)s\":\"%(v)s\"}" % {"n" : precondition.name,"v" : precondition.value}) </code></pre> <p>Another way to get this would be to add this to Precondition:</p> <pre><code>def as_dict(self): return {self.name: self.value} </code></pre> <p>And then use it like this:</p> <pre><code>precons = str(precondition.as_dict()) precons = precons.replace("\'", "\"") </code></pre> <p>Both of these ways should leave you with a string like this:</p> <pre><code>{"_tag":"tagged"} </code></pre> <p>Then use json.dumps to do the same that r'' would do</p> <pre><code>precon = json.dumps(precon) </code></pre> <p>After that it should look like this:</p> <pre><code>"{\"_tag\":\"tagged\"}" </code></pre> <p>Since json.dumps adds " at the start and at the end, remember to get rid of them if you don't need them.</p>
0
2016-10-12T14:15:21Z
[ "python", "string-literals" ]
Requests lib works in Window and times out in Linux
39,978,321
<p>I have a simple python script to make a POST operation using requests lib. In windows, it works fine with no problem. In <strong>Linux</strong>, it's <strong>not</strong> working <strong><em>even though I can ping</em></strong>. The script gives me in Linux:</p> <pre><code>Traceback (most recent call last): File "temp.py", line 55, in &lt;module&gt; r = requests.post(urlPOST, json=payLoad, auth=('admin', 'pass'), verify=False) File "/opt/ute/python/lib/python2.7/site-packages/requests/api.py", line 109, in post return request('post', url, data=data, json=json, **kwargs) File "/opt/ute/python/lib/python2.7/site-packages/requests/api.py", line 50, in request response = session.request(method=method, url=url, **kwargs) File "/opt/ute/python/lib/python2.7/site-packages/requests/sessions.py", line 465, in request resp = self.send(prep, **send_kwargs) File "/opt/ute/python/lib/python2.7/site-packages/requests/sessions.py", line 573, in send r = adapter.send(request, **kwargs) File "/opt/ute/python/lib/python2.7/site-packages/requests/adapters.py", line 415, in send raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: ('Connection aborted.', error(110, 'Connection timed out')) </code></pre> <p>Again, <strong><em>I can ping</em></strong> the site <em>with no problems</em> in Linux. </p> <p><strong><em>Questions:</em></strong> <strong>1- What my be wrong?</strong> <strong>2- Is there another way to check connection rather than ping?</strong> I mean if it was a proxy problem, then I wouldn't be able to ping as well, right?</p>
0
2016-10-11T13:24:49Z
39,984,754
<p>My guess is, the website is not responding to your request, and that's why you are getting a time out error. I will try to solve this by changing the user agent in the header, because some websites might be trying to avoid bots. Maybe try something like this: </p> <pre><code>header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebK it/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'} r = requests.post(urlPOST, headers=header, json=payLoad, auth=('admin', 'pass'), verify=False) </code></pre>
0
2016-10-11T19:00:09Z
[ "python", "linux", "python-2.7", "proxy", "python-requests" ]
how to make a python module or fuction and use it while writing other programs?
39,978,375
<p>There where many instances where i have to write large line of code over and over again in multiple programs. so i was wondering if i could write just one program, save it and then call it in different programs like a function or a module.</p> <p>An elementary example :- I write a program to check if a number is palindromic or not. Then i want to write a program to check if a number is a palindromic a prime, could i just call the first program and do the rest of the code to check if it is prime or not.</p> <p>P.S I'm just a beginner at python or computer science for that matter and i use IDLE to do all my python programs.</p>
3
2016-10-11T13:27:25Z
39,978,523
<p>You should check out the python documentation. If you still have questions then come back.</p> <p><a href="https://docs.python.org/2/tutorial/modules.html" rel="nofollow">https://docs.python.org/2/tutorial/modules.html</a></p>
1
2016-10-11T13:35:31Z
[ "python", "function", "module" ]
how to make a python module or fuction and use it while writing other programs?
39,978,375
<p>There where many instances where i have to write large line of code over and over again in multiple programs. so i was wondering if i could write just one program, save it and then call it in different programs like a function or a module.</p> <p>An elementary example :- I write a program to check if a number is palindromic or not. Then i want to write a program to check if a number is a palindromic a prime, could i just call the first program and do the rest of the code to check if it is prime or not.</p> <p>P.S I'm just a beginner at python or computer science for that matter and i use IDLE to do all my python programs.</p>
3
2016-10-11T13:27:25Z
39,978,563
<p>Yes. Let's say you're writing code in a file called <code>palindrome.py</code>. Then in another file, or in the python shell you want to use that code. You would type</p> <pre><code>import palindrome </code></pre> <p>either at the top of the file or just into the shell as a command. Then you can access functions you've written in <code>palindrome.py</code> with statements like</p> <pre><code>palindrome.is_palindrome('abba') </code></pre> <p>It's important to note that to do this propery, the code in <code>palindrome.py</code> must be in functions. If you're not sure how to do that, I recommend the official Python tutorial: <a href="https://docs.python.org/3/tutorial/index.html" rel="nofollow">https://docs.python.org/3/tutorial/index.html</a></p>
0
2016-10-11T13:37:24Z
[ "python", "function", "module" ]
how to make a python module or fuction and use it while writing other programs?
39,978,375
<p>There where many instances where i have to write large line of code over and over again in multiple programs. so i was wondering if i could write just one program, save it and then call it in different programs like a function or a module.</p> <p>An elementary example :- I write a program to check if a number is palindromic or not. Then i want to write a program to check if a number is a palindromic a prime, could i just call the first program and do the rest of the code to check if it is prime or not.</p> <p>P.S I'm just a beginner at python or computer science for that matter and i use IDLE to do all my python programs.</p>
3
2016-10-11T13:27:25Z
39,978,902
<p>it's easy to write a function in python.</p> <p>first define a function is_palindromic,</p> <pre><code>def is_palindromic(num): #some code here return True </code></pre> <p>then define a function is_prime,</p> <pre><code>def is_prime(num): #some code here return True </code></pre> <p>at last, suppose you have a number 123321, you can call above function,</p> <pre><code>num = 123321 if is_palindromic(num): if is_prime(num): print 'this number is a prime!' </code></pre> <p>ps, maybe you could try to use some editors like vscode or sublime.</p>
0
2016-10-11T13:53:22Z
[ "python", "function", "module" ]
how to make a python module or fuction and use it while writing other programs?
39,978,375
<p>There where many instances where i have to write large line of code over and over again in multiple programs. so i was wondering if i could write just one program, save it and then call it in different programs like a function or a module.</p> <p>An elementary example :- I write a program to check if a number is palindromic or not. Then i want to write a program to check if a number is a palindromic a prime, could i just call the first program and do the rest of the code to check if it is prime or not.</p> <p>P.S I'm just a beginner at python or computer science for that matter and i use IDLE to do all my python programs.</p>
3
2016-10-11T13:27:25Z
39,979,991
<p>It is about writing reusable code. I can suggest you to write reusable code in specific function in separate python file and import that file and function too. For example you need function called sum in other function called "bodmas" then write function called sum in one python file say suppose "allimports.py":</p> <pre><code> def sum(a,b): return a+b </code></pre> <p>Now suppose your "bodmas" named function is some other python file then just import all the required functions and use is normally by calling it.</p> <pre><code> from allimports import sum def bodmas: print(sum(1,1)) </code></pre> <p>One important thing is be specific while import your module as it will effect performance of your code when length of your code is long. Suppose you want to use all functions then you can use two option like :</p> <pre><code> import allimports print(allimports.sum(1,1)) </code></pre> <p>other option is </p> <pre><code> from allimports import * print(sum(1,1)) </code></pre> <p>and for specific imports is as follows:</p> <pre><code> from allimports import sum print(sum(1,1)) </code></pre>
0
2016-10-11T14:45:07Z
[ "python", "function", "module" ]
String encode/decode issue - missing character from end
39,978,405
<p>I am having <code>NVARCHAR</code> type column in my database. I am unable to convert the content of this column to plain string in my code. (I am using <code>pyodbc</code> for the database connection).</p> <pre><code># This unicode string is returned by the database &gt;&gt;&gt; my_string = u'\u4157\u4347\u6e65\u6574\u2d72\u3430\u3931\u3530\u3731\u3539\u3533\u3631\u3630\u3530\u3330\u322d\u3130\u3036\u3036\u3135\u3432\u3538\u2d37\u3134\u3039\u352d' # prints something in chineese &gt;&gt;&gt; print my_string 䅗䍇湥整⵲㐰㤱㔰㜱㔹㔳㘱㘰㔰㌰㈭㄰〶〶ㄵ㐲㔸ⴷㄴ〹㔭 </code></pre> <p>The closest I have gone is via encoding it to <code>utf-16</code> as:</p> <pre><code>&gt;&gt;&gt; my_string.encode('utf-16') '\xff\xfeWAGCenter-04190517953516060503-20160605124857-4190-5' &gt;&gt;&gt; print my_string.encode('utf-16') ��WAGCenter-04190517953516060503-20160605124857-4190-5 </code></pre> <p>But the actual value that I need as per the value store in database is:</p> <pre><code>WAGCenter-04190517953516060503-20160605124857-4190-51 </code></pre> <p>I tried with encoding it to <code>utf-8</code>, <code>utf-16</code>, <code>ascii</code>, <code>utf-32</code> but nothing seemed to work.</p> <p>Does anyone have the idea regarding what I am missing? And how to get the desired result from the <code>my_string</code>.</p> <p><strong>Edit</strong>: <em>On converting it to <code>utf-16-le</code>, I am able to remove unwanted characters from start, but still one character is missing from end</em></p> <pre><code>&gt;&gt;&gt; print t.encode('utf-16-le') WAGCenter-04190517953516060503-20160605124857-4190-5 </code></pre> <p><em>On trying for some other columns, it is working. <strong>What might be the cause of this intermittent issue?</em></strong></p>
5
2016-10-11T13:29:13Z
39,981,171
<p>You have a major problem in your database definition, in the way you store values in it, or in the way you read values from it. I can only explain what you are seeing, but neither why nor how to fix it without:</p> <ul> <li>the type of the database</li> <li>the way you input values in it</li> <li>the way you extract values to obtain your <em>pseudo unicode</em> string</li> <li>the actual content if you use direct (<em>native</em>) database access</li> </ul> <p>What you get is an ASCII string, where the 8 bits characters are grouped by pair to build 16 bit unicode characters in little endian order. As the expected string has an odd numbers of characters, the last character was (irremediably) lost in translation, because the original string ends with <code>u'\352d'</code> where 0x2d is ASCII code for <code>'-'</code> and 0x35 for <code>'5'</code>. Demo:</p> <pre><code>def cvt(ustring): l = [] for uc in ustring: l.append(chr(ord(uc) &amp; 0xFF)) # low order byte l.append(chr((ord(uc) &gt;&gt; 8) &amp; 0xFF)) # high order byte return ''.join(l) cvt(my_string) 'WAGCenter-04190517953516060503-20160605124857-4190-5' </code></pre>
1
2016-10-11T15:37:19Z
[ "python", "python-2.7", "encode", "pyodbc", "nvarchar" ]
Is it the circular dependency?
39,978,423
<p>It's said that circular dependencies are bad and anti-patterns. So my question is what's wrong with the code below? Is it an example of circular dependency at all? The code is in python pseudocode but should be understood.</p> <pre><code>class Manager: _handlers = [] def on_config(self): # do something... # and notify about "event" for handler in self._handlers: handler() def add_change_handler(self, handler): self._handlers.append(handler) def get_value(self): return some_value class Consumer: def __init__(self, manager): self._manager = manager self._manager.add_change_handler(self._on_event) def _on_change(self): print('Got event') def do_something(self): self._manager.get_value() </code></pre> <p>So: Consumer gets manager to:</p> <ul> <li>get_value from it</li> <li>to register for litening on change event</li> </ul> <p>The argument from guys that are against that solution is that it's better to create other class, that will:</p> <ul> <li>know about manager and consumer</li> <li>listen on config event</li> <li>call consumer's on_change handler</li> <li>Consumer will use manager only to get_value</li> </ul>
0
2016-10-11T13:30:09Z
39,979,361
<p><a href="http://stackoverflow.com/questions/744373/circular-or-cyclic-imports-in-python">Circular (or cyclic) imports in Python</a>. This answer will help you know more about circular imports in python. </p> <p>This code is not about circular dependency. You can also regard this situation as a trade between bussinessmans.</p> <pre><code>#!/bin/python class Businessman: _trader_list = [] def __init__(self, name, goods): self.m_name = name self.m_goods = goods def on_get_goods(self): for trader in self._trader_list: trader.buy_some(self) def add_change_handler(self, handler): self._trader_list.append(handler) def del_change_handler(self, handler): self._trader_list.remove(handler) def buy_some(self, from_bussinessman): print "{0} will buy some {1}s from {2}".format( self.m_name, from_bussinessman.m_goods, from_bussinessman.m_name) def get_goods(self): print("{0} gets new {1}s.".format(self.m_name, self.m_goods)) self.on_get_goods() if __name__ == "__main__": bob = Businessman('Bob', 'apple') jack = Businessman('Jack', 'banana') cream = Businessman('Cream', 'rice') # Bob notifys Jack and Cream to buy apples when he gets some. seller1 = bob seller1.add_change_handler(jack) seller1.add_change_handler(cream) seller1.get_goods() </code></pre> <p>The result is</p> <pre><code>Bob gets new apples. Jack will buy some apples from Bob Cream will buy some apples from Bob </code></pre>
-1
2016-10-11T14:17:13Z
[ "python", "software-design" ]
How to translate a bson file to a json file with Python?
39,978,504
<p>I have some bson files (I don't have the database they came from, just the files, called file1.bson and file2.bson) and I would like to be able to translate them to json. My code is the following:</p> <pre><code>import json import bson to_convert = ["./file1", "./file2"] for i in to_convert: INPUTF = i + ".bson" OUTPUTF = i + ".json" input_file = open(INPUTF, 'r', encoding='utf-8') output_file = open(OUTPUTF, 'w', encoding='utf-8') reading = (input_file.read()).encode() #reading = (input_file.read()+'\0').encode() datas = bson.BSON.decode(reading) json.dump(datas, output_file) </code></pre> <p>It raises "bson.errors.InvalidBSON: bad eoo", which seems to indicate the NULL char at the end of a file is missing, but even when I add it manually (as in the commented part) the error persists.</p> <p>How can I fix this ?</p>
2
2016-10-11T13:34:42Z
39,978,874
<p>Actually <a href="http://stackoverflow.com/questions/34320177/python-convert-bson-output-of-mongodump-to-array-of-json-objects-dictionaries?rq=1">this</a> answered my question. Weird how poorly documented is the bson package.</p> <pre><code>import json import bson to_convert = ["./file1", "./file2"] for i in to_convert: INPUTF = i + ".bson" OUTPUTF = i + ".json" input_file = open(INPUTF, 'rb', encoding='utf-8') output_file = open(OUTPUTF, 'w', encoding='utf-8') raw = (input_file.read()) datas = bson.decode_all(raw) json.dump(datas, output_file) </code></pre>
0
2016-10-11T13:51:35Z
[ "python", "json", "bson" ]
Simulating UDAF on Pyspark for encapsulation
39,978,527
<p>I'm learning Spark with PySpark, and just hit a wall when trying to make things cleaner.</p> <p>Say a have a dataframe that looks like this. (of course, with way more columns and rows)</p> <pre><code>A | B | C --+---+------ a | 1 | 1.300 a | 2 | 2.500 a | 3 | 1.000 b | 1 | 120.0 b | 4 | 34.20 c | 2 | 3.442 </code></pre> <p>and I want to run a bunch of <code>groupby -&gt; agg</code> on it, using basic <code>pyspark.sql.functions</code> , like <code>count()</code> and <code>mean()</code>, like this:</p> <pre><code>df.groupby("A")\ .agg(mean("B").alias("B_mean"), sum("C").alias("C_sum"), (countDistinct("B")/avg("C")).alias("New_metric")) </code></pre> <p>It works fine, runs relatively fast, and gives me the desired results. </p> <p>But, eventually, slightly more complex functions will be needed, and, also, we want to make these easier to test. </p> <p>How can one encapsulate these functions? Using <code>lambda</code>? Some way around UDFs?</p> <p>I'm aware of UDAFs and that it's possible to write them in SCALA and import the code to PySpark, but, since all of our code base is already in Python, I would like to explore other options.</p> <p>P.S.: We are running Spark 1.6.0</p>
3
2016-10-11T13:35:46Z
39,978,829
<p>Function can be defined as a combination of <code>pyspark.sql.functions</code>:</p> <ul> <li><p>YES - go this way. For example:</p> <pre><code>def sum_of_squares(col): return sum(col * col) df.select(sum_of_squares(df["foo"]]) df.groupBy("foo").agg(sum_of_squares(df["bar"]]) </code></pre></li> <li><p>NO - use RDD.</p></li> </ul>
1
2016-10-11T13:49:44Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql", "spark-dataframe" ]
Python: list index out of range (Assigning a 2D list to another 2D list)
39,978,529
<p>I am processing a 2D list and want to store the processed 2D list in a new 2D list with same indexes. But, I am getting error "list index out of range"</p> <p>I have simplified my code to make it easy to understand:</p> <pre><code>a = [ ['a', 'b'], ['c', 'd'] ] print a b = [] for i in range(len(a)): for j in range(len(a[i])): if a[0][0] == 'a': a[0][0] = 'b' else: b[i][j] = a[i][j] #list index out of range </code></pre> <p>Thanks</p>
4
2016-10-11T13:35:52Z
39,978,691
<p>Simple, you initialised b to [], so any attempt to access it by index will be out of range. Lists in Python can increase in size dynamically, but this isn't how you do it. You need .append</p>
1
2016-10-11T13:42:43Z
[ "python", "arrays", "list" ]
Python: list index out of range (Assigning a 2D list to another 2D list)
39,978,529
<p>I am processing a 2D list and want to store the processed 2D list in a new 2D list with same indexes. But, I am getting error "list index out of range"</p> <p>I have simplified my code to make it easy to understand:</p> <pre><code>a = [ ['a', 'b'], ['c', 'd'] ] print a b = [] for i in range(len(a)): for j in range(len(a[i])): if a[0][0] == 'a': a[0][0] = 'b' else: b[i][j] = a[i][j] #list index out of range </code></pre> <p>Thanks</p>
4
2016-10-11T13:35:52Z
39,979,267
<p>I don't have any idea about your expected output. I just fixed the error. At first <code>append</code> an empty <code>list</code> to <code>b</code> then you can access <code>b[i]</code> and so on. </p> <p>Code:</p> <pre><code>a = [ ['a', 'b'], ['c', 'd'] ] print(a) b = [] for i in range(len(a)): b.append([]) #Append an empty list to `b` for j in range(len(a[i])): if a[0][0] == 'a': a[0][0] = 'b' else: b[i].append(a[i][j]) #No error now print(b) </code></pre>
2
2016-10-11T14:12:28Z
[ "python", "arrays", "list" ]
Python: list index out of range (Assigning a 2D list to another 2D list)
39,978,529
<p>I am processing a 2D list and want to store the processed 2D list in a new 2D list with same indexes. But, I am getting error "list index out of range"</p> <p>I have simplified my code to make it easy to understand:</p> <pre><code>a = [ ['a', 'b'], ['c', 'd'] ] print a b = [] for i in range(len(a)): for j in range(len(a[i])): if a[0][0] == 'a': a[0][0] = 'b' else: b[i][j] = a[i][j] #list index out of range </code></pre> <p>Thanks</p>
4
2016-10-11T13:35:52Z
39,979,814
<p>At <code>b[i][j]</code> you try to access the jth element of the ith element. However, b is just an empty list, so the ith element doesn't exist, let alone the jth element of that ith element. </p> <p>You can fix this by appending the elements to b. But first, a list (row) should be created (appended to b) for each list (row) in a.</p> <p>The following example makes use of the <code>enumerate</code> function. It returns the index and the element, so if you want you can still do stuff with i and j, but this will prevent you from gaining an <code>IndexError</code>. You can still safely use <code>a[i][j]</code>, because the indices are derived from <code>a</code>.</p> <pre><code>a = [ ['a', 'b'], ['c', 'd'] ] b = [] for i, row in enumerate(a): # loop over each list (row) in a b_row = [] # list (row) which will be added to b for j, element in enumerate(row): # loop over each element in each list (row) in a if a[0][0] == 'a': # Not sure why each the first element of a has to be checked each loop # Probably a simplification of the operations. a[0][0] = 'b' else: b_row.append(element) # append the element to the list(row) that will be added to b b.append(b_row) # When the row is filled, add it to b print(b) </code></pre> <p>One last comment: it is not recommended to change a list while looping over it in Python (like in the <code>if</code> statement). It is better to apply those changes to your output list, which is b. If it is jsut a simplification of the processessing, just ignore this remark.</p>
2
2016-10-11T14:37:06Z
[ "python", "arrays", "list" ]
Python databases
39,978,655
<p>I would like run a script that will ping some servers from a database and update a field in a database.</p> <p>My database is sqlite and the layout is:</p> <p><code>name IP last_poll status</code></p> <p>Typically the values will be:</p> <p><code>HQ 192.168.1.1 12:00 2016-01-01 online</code></p> <p>The idea is to have a loop to select the data from the database but how can I insert the result back into the same row?</p> <p>I have the basic setup where I can ping a single host:</p> <pre><code>import os hostname = "192.168.1.1" response = os.system("ping -c 1 " + hostname) if response == 0: print "online" </code></pre> <p>I could iterate through the tuple if I select the data but I don't know how I can insert it back into the rows.</p>
0
2016-10-11T13:41:16Z
40,022,866
<p>Thank you, I have a list of tuples now achieved with this: </p> <p><code>def read_from_db(): c.execute('SELECT ip FROM sites') data = c.fetchall() hostnames = tuple(sum(data, ()))</code></p> <p><code>for h in hostnames: responses = tuple(os.system('ping -c 1 ' + h) for h in hostnames)</code></p> <p><code>z = zip(hostnames, responses)</code></p> <p>That gives me a list of tuples:</p> <p><code>[(u'10.0.0.260', 512), (u'10.0.0.254', 0)]</code></p> <p>But how can that be used to update the database in a batch checking where the IP and updating the status with a code?</p>
0
2016-10-13T13:47:57Z
[ "python", "database", "sqlite" ]
How to make unpaired data in python
39,978,675
<p>My data is in this format</p> <pre><code>ID input_1 input_2 1 'hello' 'greeting' 2 'algorithm' 'computer science' . . . . . . </code></pre> <p>The input_1 and input_2 can be viewed as the pair data, is there a way or a library in python to shuffle them to make input_1 and input_2 are not paired? </p>
-2
2016-10-11T13:42:07Z
39,978,756
<p>You can use the random module - which funnily enough has a shuffle function!</p> <p>random.shuffle(input_1)</p> <p>(note that shuffle operates in place, yuck)</p>
0
2016-10-11T13:45:46Z
[ "python", "pandas" ]
How to make unpaired data in python
39,978,675
<p>My data is in this format</p> <pre><code>ID input_1 input_2 1 'hello' 'greeting' 2 'algorithm' 'computer science' . . . . . . </code></pre> <p>The input_1 and input_2 can be viewed as the pair data, is there a way or a library in python to shuffle them to make input_1 and input_2 are not paired? </p>
-2
2016-10-11T13:42:07Z
39,978,816
<p>I think you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.permutation.html" rel="nofollow"><code>numpy.random.permutation</code></a>:</p> <pre><code>df.input_1 = np.random.permutation(df.input_1) print (df) ID input_1 input_2 0 1 'algorithm' 'greeting' 1 2 'hello' 'computer science' </code></pre>
2
2016-10-11T13:49:12Z
[ "python", "pandas" ]
How to make unpaired data in python
39,978,675
<p>My data is in this format</p> <pre><code>ID input_1 input_2 1 'hello' 'greeting' 2 'algorithm' 'computer science' . . . . . . </code></pre> <p>The input_1 and input_2 can be viewed as the pair data, is there a way or a library in python to shuffle them to make input_1 and input_2 are not paired? </p>
-2
2016-10-11T13:42:07Z
39,978,846
<p>read the data in as a dataframe and then process it using it index <code>df.ix[row_number,column_number]</code> and fetch what ever you want to fetch and process accordingly.</p>
0
2016-10-11T13:50:30Z
[ "python", "pandas" ]
Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force NOT WORKING
39,978,810
<p>I'm trying to setup Node.js and Python on my work laptop.</p> <p>I've installed Node and Python successfully.</p> <p>When I'm trying to update my npm using this command in Windows PowerShell:</p> <pre><code>Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force npm install -g npm-windows-upgrade npm-windows-upgrade </code></pre> <p>While setting execution policy to unrestricted it throws the error in the image below and says "Cannot run scripts on this system".</p> <p><a href="https://i.stack.imgur.com/5xzTv.png" rel="nofollow"><img src="https://i.stack.imgur.com/5xzTv.png" alt="Please check image"></a></p> <p>I did run <code>Get-ExecutionPolicy -List</code>. It shows a table:</p> <pre> Scope ExecutionPolicy ----- --------------- MachinePolicy RemoteSigned UserPolicy Undefined Process Undefined CurrentUser Unrestricted LocalMachine Unrestricted</pre> <p>How do I make it run scripts?</p> <p>My OS: Windows 7 Enterprise 64 bit.</p>
0
2016-10-11T13:48:59Z
39,985,038
<p>The error message show the root of error:</p> <pre><code> Window powershell updated your execution policy suceffully, but the setting is overridden by a policy defined at a more specific scope. Due to the override, your shell will retain its current effective execution policy of remoteassigned. </code></pre> <p>So, there is a group policy setting for the current user assigned to remoteassigned and can't be changed by the command.</p> <p>Modify the setting in the group policy as in the given steps:</p> <pre><code> run: gpedit.msc </code></pre> <p>In the left tree, select:</p> <p>user configuration -> administrative templates-> windows components -> windows powershell</p> <p>turn on script execution -> enabled As in the figure: <a href="https://i.stack.imgur.com/YVGLB.png" rel="nofollow"><img src="https://i.stack.imgur.com/YVGLB.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/6EUqG.png" rel="nofollow"><img src="https://i.stack.imgur.com/6EUqG.png" alt="enter image description here"></a> If your machine is a member of domain and you log as a domain user, there may be a restriction for modification. </p> <p>In that case contact the Domain administrator to modify your group policy.</p>
0
2016-10-11T19:19:32Z
[ "python", "node.js", "powershell", "executionpolicy" ]
Why does zip change my lists?
39,978,853
<p>I noticed a (to me) very strange behavior, I don't understand: I got a list and an numpy array both with binary values and I want to check the true positives (both==1 at the same time).</p> <pre><code>import numpy as np a = [0,0,1,1] b = np.array([1,0,1,0]) for a,b in zip(a,b): if a==1 and b==1: print "cool" print a,b </code></pre> <p>Now the craziness begins. a and b are not longer a list or a numpy array but an integer and numpy float? How on earth did that happen? Thanks for your help!</p>
-1
2016-10-11T13:50:51Z
39,978,894
<p><code>zip</code> did not change your list. You lost the initial references to your lists when you assigned the name <code>a</code> and <code>b</code> to the loop variables in:</p> <pre><code>for a, b in zip(a,b): # ^ ^ </code></pre> <p>A simple fix is to change those names to say, <code>i</code> and <code>j</code>:</p> <pre><code>for i, j in zip(a,b): </code></pre> <p>One thing to bear in mind when using Python is that names are bound to objects, and therefore can be <em>unbound</em> or even <em>rebound</em>. No name is for keeps. Once you change the object a name is referencing like you did, the name starts to reference the new object.</p> <p>On another note, <code>for</code> loops assign the objects from the iterable to the name(s) provided, similar to a regular assignment, but with repetitions. So the values you get for <code>a</code> and <code>b</code> at the end of the <code>for</code> loop are those of the last assignment done in the last iteration.</p> <p>Do bear these in mind.</p>
11
2016-10-11T13:52:48Z
[ "python", "list", "python-2.7", "list-comprehension" ]
Why does zip change my lists?
39,978,853
<p>I noticed a (to me) very strange behavior, I don't understand: I got a list and an numpy array both with binary values and I want to check the true positives (both==1 at the same time).</p> <pre><code>import numpy as np a = [0,0,1,1] b = np.array([1,0,1,0]) for a,b in zip(a,b): if a==1 and b==1: print "cool" print a,b </code></pre> <p>Now the craziness begins. a and b are not longer a list or a numpy array but an integer and numpy float? How on earth did that happen? Thanks for your help!</p>
-1
2016-10-11T13:50:51Z
39,978,912
<p>Suppose <code>a</code> is a list, and you write <code>a = a[0]</code>. Now you'd expect <code>a</code> to be not a list, but the first value in the list.</p> <p>Similarly, when you write <code>for a,b in zip(a,b)</code> you re-assign <code>a</code> and <code>b</code> to hold the first element in each iterable. Try:</p> <pre><code>for x,y in zip(a,b): if x==1 and y==1: print "cool" print a,b </code></pre>
1
2016-10-11T13:53:44Z
[ "python", "list", "python-2.7", "list-comprehension" ]
"Error 21: Is a directory" when running a concatenate script
39,979,005
<p>I wrote a program to concatenate some csv files vertically. Here is the program.</p> <pre><code>import os import glob import pandas def concatenate(indir, outfile, colnames): os.chdir(indir) fileList=glob.glob('*.csv') dfList=[] for filename in fileList: print(filename) df=pandas.read_csv(filename,header=None) dfList.append(df) concatDf=pandas.concat(dfList,axis=0) concatDf.columns=colnames y=str(input("What do you want to name your file?")) concatDf.csv_path = y concatDf.to_csv(outfile,index=None) def main(): indir = str(input("What is the directory that you want to concatenate?" )) outfile = str(input("What is the directory that you want to export the merged file to?" )) string_input = input("What are the column names?: ") input_list = string_input.split() colnames = [str(x) for x in input_list] concatenate(indir, outfile, colnames) </code></pre> <p>However, when I test out my program, there is a small error. Here are my inputs.</p> <pre><code>main() What is the directory that you want to concatenate?/Users/hem/Desktop/Complete_Pilot_Copy/5555_1/DelayDiscounting What is the directory that you want to export the merged file to?/Users/hem/Desktop/DelayedDiscountingAnalyzed What are the column names?: Date SubjectID SessionID ProtocolID SiteID TaskID UserResponse LogDiscountRate LogDiscountRateStd QuestionRule NegativeDiscountFlag ZeroDiscountFlag BozoDiscountFlag gldomain ProposedValue1 ProposedDelay1 ProposedValue2 ProposedDelay2 ProposedValue3 ProposedDelay3 TrialStartTimeSec ResponseTimeSec DDT_5555_1_HUBS071501_BU_062016_135920.csv DDT_5555_1_HUBS071501_BU_062016_140010.csv DDT_5555_1_HUBS071501_BU_062016_140051.csv DelayedDiscounting_5555_1.csv What do you want to name your file?5555_1DelayDiscounting Traceback (most recent call last): File "&lt;ipython-input-2-58ca95c5b364&gt;", line 1, in &lt;module&gt; main() File "&lt;ipython-input-1-867fad0a7568&gt;", line 26, in main concatenate(indir, outfile, colnames) File "&lt;ipython-input-1-867fad0a7568&gt;", line 17, in concatenate concatDf.to_csv(outfile,index=None) File "/Users/hem/anaconda/lib/python3.5/site-packages/pandas/core/frame.py", line 1344, in to_csv formatter.save() File "/Users/hem/anaconda/lib/python3.5/site-packages/pandas/formats/format.py", line 1526, in save compression=self.compression) File "/Users/hem/anaconda/lib/python3.5/site-packages/pandas/io/common.py", line 424, in _get_handle f = open(path, mode, errors='replace') IsADirectoryError: [Errno 21] Is a directory: '/Users/hem/Desktop/DelayedDiscountingAnalyzed' </code></pre> <p>How would I fix this? I think it may be the way I entered the directory? Thanks</p>
-1
2016-10-11T13:58:54Z
39,979,094
<p>the error say pretty much everything <code>outfile</code> should be a path to a file, not directory. So instead of this</p> <pre><code>y=str(input("What do you want to name your file?")) concatDf.csv_path = y concatDf.to_csv(outfile,index=None) </code></pre> <p>Do this:</p> <pre><code>y=str(input("What do you want to name your file?")) concatDf.to_csv(os.path.join(outfile, y),index=None) </code></pre>
1
2016-10-11T14:03:46Z
[ "python", "csv", "concatenation" ]
sql update set ? = ? where ? = ? (python, sqlite3)
39,979,147
<p>Python, slite3</p> <pre><code>c.execute("UPDATE accounts SET ? = ? WHERE num=?", (db['choise'], db['data'], db['num'])) </code></pre> <p>so i don't know what is wrong with it</p> <p>db is shelve database</p>
0
2016-10-11T14:06:38Z
39,979,176
<p>The column (and table) names <em>cannot be parameterized</em>. Use string formatting for it and query parameterization for the rest of variables:</p> <pre><code>c.execute("UPDATE accounts SET {column} = ? WHERE num = ?".format(column=db['choise']), (db['data'], db['num'])) </code></pre> <p>That said, make sure you properly validate/sanitize/escape the <code>db['choise']</code> value or really trust the source of it (though don't trust anyone when it comes to database interactions).</p>
2
2016-10-11T14:08:20Z
[ "python", "sqlite3" ]
sql update set ? = ? where ? = ? (python, sqlite3)
39,979,147
<p>Python, slite3</p> <pre><code>c.execute("UPDATE accounts SET ? = ? WHERE num=?", (db['choise'], db['data'], db['num'])) </code></pre> <p>so i don't know what is wrong with it</p> <p>db is shelve database</p>
0
2016-10-11T14:06:38Z
39,979,464
<p>Column names cannot be given as arguments. You can try </p> <pre><code>c.execute("UPDATE accounts SET "+str(db['choise'])+" = ? WHERE num=?", (db['data'], db['num'])) </code></pre>
0
2016-10-11T14:21:55Z
[ "python", "sqlite3" ]
fabfile doesn't see remote environment variables
39,979,229
<p>My remote server (192.168.3.68) contains several environment variables set in my ~/.bashrc:</p> <pre><code># For instance export MY_DATABASE_HOST=127.0.0.1 </code></pre> <p>When I put <code>run('echo $MY_DATABASE_HOST')</code> in <code>fabfile.py</code>, it shows:</p> <pre><code>[192.168.3.68] run: echo $MY_DATABASE_HOST [192.168.3.68] output: Done Disconnecting from 192.168.3.68... done. </code></pre> <p>I've tried adding <code>run('source ~/.bashrc')</code> immediately before the echo but nothing changes.</p> <p>Why isn't the set environment variables in ~/.bashrc visible to fabfile?</p> <p>What do I do to fix that because fabfile must be able to read these variables?</p> <p><strong>UPDATE</strong></p> <pre><code>from fabric.context_managers import prefix # This didn't work with prefix('source /home/meandme/.bashrc'): run('echo $MY_DATABASE_HOST') # This didn't work either run('source /home/meandme/.bashrc &amp;&amp; echo $MY_DATABASE_HOST') </code></pre>
2
2016-10-11T14:10:40Z
39,979,563
<p>Each call of <code>run</code> will open up a new shell and any transient commands in the previous invocation of <code>run</code> are thus lost (e.g., such as setting an environment variable). To elide this issue, you can do two things:</p> <p>Write your shell commands thusly:</p> <pre><code>run('source /path/to/.bashrc &amp;&amp; echo $MY_DATABASE_HOST') </code></pre> <p>or Use the <code>prefix</code> context manager</p> <pre><code>from fabric.context_managers import prefix with prefix('source /path/to/.bashrc'): run('echo $MY_DATABASE_HOST') </code></pre>
0
2016-10-11T14:26:29Z
[ "python", "fabric" ]