prefix
stringclasses
1 value
input_text
stringlengths
10
172
target_text
stringlengths
18
33.9k
QA:
Exponentional values in Python Pandas
<pre><code>&gt;&gt;&gt; float(4.536115e+07) 45361150.0 </code></pre> <p>or</p> <pre><code>&gt;&gt;&gt; f = 4.536115e+07 &gt;&gt;&gt; "%.16f" % f '45361150.0000000000000000' </code></pre>
QA:
Celery (Redis) results backend not working
<p>Adding <code>CELERY_STORE_ERRORS_EVEN_IF_IGNORED = True</code> to my settings resolved this problem for me.</p>
QA:
What is the difference between installing python from the website and using brew?
<blockquote> <p>it is possible to brew install python 3.5.1?</p> </blockquote> <p>Yes it is. See <a href="http://stackoverflow.com/a/4158763/735926">this StackOverflow answer</a>.</p> <blockquote> <p>If not, what will it mean to install 3.5.1 via .pkg file?</p> </blockquote> <p>The most noticeable change will be that you won’t be able to upgrade your Python installation without downloading the new version and installing it by hand (compared to <code>brew upgrade python3</code>). It’ll also be <a href="http://stackoverflow.com/a/3819829/735926">slightly more complicated to remove</a> compared to <code>brew rm python3</code>.</p> <p>Other than these minor differences you should have the same experience with both installations. Be sure that the <code>python</code> installed from <code>python-3.5.1-macosx10.6.pkg</code> is before Homebrew’s in your <code>PATH</code> or use its full path.</p>
QA:
Call a Python function with arguments based on user input
<p>Instead of using eval, you can parse it yourself. This way, you have control over how each function should parse/deserialize the user input's arguments.</p> <pre class="lang-python prettyprint-override"><code>import sys, re def custom_print(value): print value def custom_add(addends): print sum(addends) def deserialize_print(args): # just print it as is custom_print(args) def deserialize_add(args): # remove all whitespace, split on commas, parse as floats addends = [float(x) for x in re.sub(r"\s", "", args).split(",")] # send to custom_add function custom_add(addends) def get_command(): cmd_input = raw_input("Command: ") # -- check that the command is formatted properly # and capture command groups match = re.match(r"^([a-zA-Z0-9]+)(\(.*\))?$", cmd_input) if match: # extract matched groups to separate variables (cmd, argstring) = match.groups() # strip parenthesis off of argstring if argstring: args = argstring[1:-1] # send the whole argument string to its corresponding function if cmd == "print": deserialize_print(args) elif cmd == "add": deserialize_add(args) elif cmd == "exit": sys.exit() else: print "Command doesn't exist." else: print "Invalid command." # recurse until exit get_command() # -- begin fetching commands get_command() </code></pre> <hr> <p>This is a pretty rough setup, although you can get by with some more error checking and improving the deserializing functions and modularizing function additions.</p> <p>If the decoupled deserialize functions seem too much, you can also just move the deserialization into the custom functions themselves.</p>
QA:
read data in specific column and row of a text file
<p>make '=' to '==' at line 3 of your code </p> <pre><code>with open('my_file', 'r') as f: for x, line in enumerate(f): if x == 1000: print float(line.split()[1]) </code></pre>
QA:
Exponentional values in Python Pandas
<p>You could change the pandas options as such:</p> <pre><code>&gt;&gt;&gt; data = np.array([4.536115e+07, 3.889124e+07, 2.757327e+07]) &gt;&gt;&gt; pd.set_option('display.float_format', lambda x: '%.f' % x) &gt;&gt;&gt; pd.DataFrame(data, columns=['trades']) trades 0 45361150 1 38891240 2 27573270 </code></pre>
QA:
Django: authenticate the user
<p>Your code seems to be correct. </p> <p>The problem might be in the way the params are being passed to your <code>create_user</code> view (Param passing in <code>get_entry</code> view highly unlikely to be a problem since the params <code>username</code> and <code>password</code> are hard-coded).</p> <p>Try printing out <code>username</code> and <code>password</code> before passing them to <code>User.objects.create_user()</code>, since it's possible that the <code>password</code> field is not being saved properly and/or empty <code>password</code> is being passed, and Django might be creating a hash for the empty password.</p> <p>P.S.: This is just a speculation, need your response over this for further diagnosis of the issue.</p>
QA:
read data in specific column and row of a text file
<pre><code>import re with open('my_file', 'r') as f: for x, line in enumerate(f): if x == 1000: array = re.split('(\d+)',line) # array=['AAAA','123'] if line='AAAA123' print array[1] # your required second row. </code></pre>
QA:
Learn Python the Hard way ex25 - Want to check my understanding
<blockquote> <p>that the argument label doesn't matter</p> </blockquote> <p>It matters in the sense that it's used "locally" within the function definition. Basically think of it as another local variable you define in the function definition but the values of the arguments are given to the function.</p> <p>Keeping this in mind, your next question is easy to answer:</p> <blockquote> <p>what does the 'words' returned from 'break_words' have to do with the variable 'words' defined as a part of 'sort_sentence'?</p> </blockquote> <p>Nothing. As stated previously, <code>words</code> is a local variable of <code>sort_sentence</code> and so is basically trashed when you leave the function ("falls out of scope" is the lingo). Of course, you can use <code>words</code> as the name of variables elsewhere, such as in another function definition, and that's what's happening here.</p>
QA:
Having troubles with pip and importing
<p>Launch python 2.7 and type </p> <p><code>&gt;&gt;&gt;import tweepy</code></p> <p>Than launch python 3.5 and type </p> <pre><code>&gt;&gt;&gt;import tweepy </code></pre> <p>Whichever one does not work means that is probably not your default Python installation.</p> <p>One of your Python installations doesn't have this installed since pip does not install in both versions of Python only the default one found on your path. </p>
QA:
draw horizontal bars on the same line
<p>Actually, I'm gonna cheat and post you something straight from the <a href="http://matplotlib.org/users/event_handling.html#draggable-rectangle-exercise" rel="nofollow">Matplotlib Documentation</a>. This should get you started with draggable objects in mpl. you'll have to come up with your own dynamic object creation code...</p> <p>full credit to the guys over at mpl:</p> <pre><code># draggable rectangle with the animation blit techniques; see # http://www.scipy.org/Cookbook/Matplotlib/Animations import numpy as np import matplotlib.pyplot as plt class DraggableRectangle: lock = None # only one can be animated at a time def __init__(self, rect): self.rect = rect self.press = None self.background = None def connect(self): 'connect to all the events we need' self.cidpress = self.rect.figure.canvas.mpl_connect( 'button_press_event', self.on_press) self.cidrelease = self.rect.figure.canvas.mpl_connect( 'button_release_event', self.on_release) self.cidmotion = self.rect.figure.canvas.mpl_connect( 'motion_notify_event', self.on_motion) def on_press(self, event): 'on button press we will see if the mouse is over us and store some data' if event.inaxes != self.rect.axes: return if DraggableRectangle.lock is not None: return contains, attrd = self.rect.contains(event) if not contains: return print('event contains', self.rect.xy) x0, y0 = self.rect.xy self.press = x0, y0, event.xdata, event.ydata DraggableRectangle.lock = self # draw everything but the selected rectangle and store the pixel buffer canvas = self.rect.figure.canvas axes = self.rect.axes self.rect.set_animated(True) canvas.draw() self.background = canvas.copy_from_bbox(self.rect.axes.bbox) # now redraw just the rectangle axes.draw_artist(self.rect) # and blit just the redrawn area canvas.blit(axes.bbox) def on_motion(self, event): 'on motion we will move the rect if the mouse is over us' if DraggableRectangle.lock is not self: return if event.inaxes != self.rect.axes: return x0, y0, xpress, ypress = self.press dx = event.xdata - xpress dy = event.ydata - ypress self.rect.set_x(x0+dx) self.rect.set_y(y0+dy) canvas = self.rect.figure.canvas axes = self.rect.axes # restore the background region canvas.restore_region(self.background) # redraw just the current rectangle axes.draw_artist(self.rect) # blit just the redrawn area canvas.blit(axes.bbox) def on_release(self, event): 'on release we reset the press data' if DraggableRectangle.lock is not self: return self.press = None DraggableRectangle.lock = None # turn off the rect animation property and reset the background self.rect.set_animated(False) self.background = None # redraw the full figure self.rect.figure.canvas.draw() def disconnect(self): 'disconnect all the stored connection ids' self.rect.figure.canvas.mpl_disconnect(self.cidpress) self.rect.figure.canvas.mpl_disconnect(self.cidrelease) self.rect.figure.canvas.mpl_disconnect(self.cidmotion) fig = plt.figure() ax = fig.add_subplot(111) rects = ax.bar(range(10), 20*np.random.rand(10)) drs = [] for rect in rects: dr = DraggableRectangle(rect) dr.connect() drs.append(dr) plt.show() </code></pre>
QA:
Why is hash() slower under python3.4 vs python2.7
<p>There are two changes in <code>hash()</code> function between Python 2.7 and Python 3.4</p> <ol> <li>Adoptions of <em>SipHash</em></li> <li>Default enabling of <em>Hash randomization</em></li> </ol> <hr> <p><em>References:</em></p> <ul> <li>Since from Python 3.4, it uses <a href="https://131002.net/siphash/" rel="nofollow">SipHash</a> for it's hashing function. Read: <a href="https://lwn.net/Articles/574761/" rel="nofollow">Python adopts SipHash</a></li> <li>Since Python 3.3 <em>Hash randomization is enabled by default.</em> Reference: <a href="https://docs.python.org/3/reference/datamodel.html#object.__hash__" rel="nofollow"><code>object.__hash__</code></a> (last line of this section). Specifying <a href="https://docs.python.org/3/using/cmdline.html#envvar-PYTHONHASHSEED" rel="nofollow"><code>PYTHONHASHSEED</code></a> the value 0 will disable hash randomization.</li> </ul>
QA:
Identify drive letter of USB composite device using Python
<p>I don't have an SD card attached to a USB port. To get you started, you could <em>try</em> this on Windows. Install <a href="http://timgolden.me.uk/python/wmi/index.html" rel="nofollow">Golden's WMI</a>. I found that the Windows .zip wouldn't install but the pip version works fine, or at least it does on Win7. Then you can list logical disks with code like this.</p> <pre><code>&gt;&gt;&gt; import wmi &gt;&gt;&gt; c=wmi.WMI() ... &gt;&gt;&gt; for disk in c.Win32_LogicalDisk(): ... print(disk) </code></pre> <p>This code provided a listing that included mention of a NAS which is why I have hopes for your SD card. Various refinements are possible.</p>
QA:
Gmail SMTP rejecting my login
<p>The solution to this ended up being changing my gmail password. I never did figure out which special characters were throwing everything off, but I just generated a new password and had no problems with this after that.</p>
QA:
how does pickle know which to pick?
<p>wow I did not even know you could do this ... and I have been using python for a very long time... so thats totally awesome in my book, however you really should not do this it will be very hard to work with later(especially if it isnt you working on it)</p> <p>I would recommend just doing </p> <pre><code>pickle.dump({"X":X_scalar,"Y":Y_scalar},output) ... data = pickle.load(fp) print "Y_scalar:",data['Y'] print "X_scalar:",data['X'] </code></pre> <p>unless you have a <strong>very</strong> compelling reason to save and load the data like you were in your question ...</p> <h1>edit to answer the actual question...</h1> <p>it loads from the start of the file to the end (ie it loads them in the same order they were dumped)</p>
QA:
How to find the longest sub-array within a threshold?
<p>Here's a vectorized approach using <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> -</p> <pre><code>def longest_thresh_subarray(sorted_array,thresh): diffs = (sorted_array[:,None] - sorted_array) r = np.arange(sorted_array.size) valid_mask = r[:,None] &gt; r mask = (diffs &lt;= thresh) &amp; valid_mask bestcolID = (mask).sum(0).argmax() idx = np.nonzero(mask[:,bestcolID])[0] if len(idx)==0: out = (0,0) else: out = idx[0]-1, idx[-1] return out </code></pre> <p>Sample runs -</p> <pre><code>In [137]: sorted_array = np.array([0, 0.7, 1, 2, 2.5]) In [138]: longest_thresh_subarray(sorted_array,0.2) Out[138]: (0, 0) In [139]: longest_thresh_subarray(sorted_array,0.4) Out[139]: (1, 2) In [140]: longest_thresh_subarray(sorted_array,0.8) Out[140]: (0, 1) In [141]: longest_thresh_subarray(sorted_array,1) Out[141]: (0, 2) In [142]: longest_thresh_subarray(sorted_array,1.9) Out[142]: (1, 4) In [143]: longest_thresh_subarray(sorted_array,2) Out[143]: (0, 3) In [144]: longest_thresh_subarray(sorted_array,2.6) Out[144]: (0, 4) </code></pre>
QA:
webdriver + reset Chrome
<pre><code>driver = webdriver.Chrome() main_window_handle = None while not main_window_handle: main_window_handle = driver.current_window_handle popup_handle = None while not popup_handle: for handle in driver.window_handles: if handle != main_window_handle: popup_handle = handle break driver.switch_to.window(popup_handle) driver.find_element_by_xpath(u'XPATH OF RESET BUTTON').click() driver.switch_to.window(main_window_handle) </code></pre> <p>I think <code>switch_to.window(handle)</code> is deprecated lately, so instead of that, use:</p> <pre><code>switch_to_window(handle) </code></pre>
QA:
how does pickle know which to pick?
<p>Yes, pickle pick objects in order of saving.</p> <p>Intuitively, pickle append to the end when it write (dump) to a file, and read (load) sequentially the content from a file.</p> <p>Consequently, order is preserved, allowing you to retrieve your data in the exact order you serialize it.</p>
QA:
Upload file to MS SharePoint using Python OneDrive SDK
<p>I finally found a solution, with the help of (<em>SO user</em>) sytech.</p> <p>The answer to my original question is that using the original <strong><a href="https://github.com/OneDrive/onedrive-sdk-python" rel="nofollow">Python OneDrive SDK</a></strong>, it's <strong>not possible</strong> to upload a file to the <code>Shared Documents</code> folder of a <code>SharePoint Online</code> site (at the moment of writing this): when the SDK queries the <a href="https://dev.onedrive.com/auth/aad_oauth.htm#step-3-discover-the-onedrive-for-business-resource-uri" rel="nofollow"><strong>resource discovery service</strong></a>, it drops all services whose <code>service_api_version</code> is not <code>v2.0</code>. However, I get the SharePoint service with <code>v1.0</code>, so it's dropped, although it could be accessed using API v2.0 too.</p> <p><strong>However</strong>, by extending the <code>ResourceDiscoveryRequest</code> class (in the OneDrive SDK), we can create a workaround for this. I managed to <strong>upload a file</strong> this way:</p> <pre><code>import json import re import onedrivesdk import requests from onedrivesdk.helpers.resource_discovery import ResourceDiscoveryRequest, \ ServiceInfo # our domain (not the original) redirect_uri = 'https://example.ourdomain.net/' # our client id (not the original) client_id = "a1234567-1ab2-1234-a123-ab1234abc123" # our client secret (not the original) client_secret = 'ABCaDEFGbHcd0e1I2fghJijkL3mn4M5NO67P8Qopq+r=' resource = 'https://api.office.com/discovery/' auth_server_url = 'https://login.microsoftonline.com/common/oauth2/authorize' auth_token_url = 'https://login.microsoftonline.com/common/oauth2/token' # our sharepoint URL (not the original) sharepoint_base_url = 'https://{tenant}.sharepoint.com/' # our site URL (not the original) sharepoint_site_url = sharepoint_base_url + 'sites/{site}' file_to_upload = 'C:/test.xlsx' target_filename = 'test.xlsx' class AnyVersionResourceDiscoveryRequest(ResourceDiscoveryRequest): def get_all_service_info(self, access_token, sharepoint_base_url): headers = {'Authorization': 'Bearer ' + access_token} response = json.loads(requests.get(self._discovery_service_url, headers=headers).text) service_info_list = [ServiceInfo(x) for x in response['value']] # Get all services, not just the ones with service_api_version 'v2.0' # Filter only on service_resource_id sharepoint_services = \ [si for si in service_info_list if si.service_resource_id == sharepoint_base_url] return sharepoint_services http = onedrivesdk.HttpProvider() auth = onedrivesdk.AuthProvider(http_provider=http, client_id=client_id, auth_server_url=auth_server_url, auth_token_url=auth_token_url) should_authenticate_via_browser = False try: # Look for a saved session. If not found, we'll have to # authenticate by opening the browser. auth.load_session() auth.refresh_token() except FileNotFoundError as e: should_authenticate_via_browser = True pass if should_authenticate_via_browser: auth_url = auth.get_auth_url(redirect_uri) code = '' while not re.match(r'[a-zA-Z0-9_-]+', code): # Ask for the code print('Paste this URL into your browser, approve the app\'s access.') print('Copy the resulting URL and paste it below.') print(auth_url) code = input('Paste code here: ') # Parse code from URL if necessary if re.match(r'.*?code=([a-zA-Z0-9_-]+).*', code): code = re.sub(r'.*?code=([a-zA-Z0-9_-]*).*', r'\1', code) auth.authenticate(code, redirect_uri, client_secret, resource=resource) service_info = AnyVersionResourceDiscoveryRequest().\ get_all_service_info(auth.access_token, sharepoint_base_url)[0] auth.redeem_refresh_token(service_info.service_resource_id) auth.save_session() client = onedrivesdk.OneDriveClient(sharepoint_site_url + '/_api/v2.0/', auth, http) # Get the drive ID of the Documents folder. documents_drive_id = [x['id'] for x in client.drives.get()._prop_list if x['name'] == 'Documents'][0] items = client.item(drive=documents_drive_id, id='root') # Upload file uploaded_file_info = items.children[target_filename].upload(file_to_upload) </code></pre> <p>Authenticating for a different service gives you a different token.</p>
QA:
Finding the length of first half of a string using string slicing in Python?
<pre><code>first_half = phrase[:len(phrase)//2] or phrase[:int(len(phrase)/2)] </code></pre>
QA:
how does pickle know which to pick?
<p>What you have is fine. It's a <a href="https://docs.python.org/2/library/pickle.html#pickle.Pickler" rel="nofollow">documented feature</a> of pickle:</p> <blockquote> <p>It is possible to make multiple calls to the dump() method of the same Pickler instance. These must then be matched to the same number of calls to the load() method of the corresponding Unpickler instance. </p> </blockquote> <p>There is no magic here, pickle is a really simple stack-based language that serializes python objects into bytestrings. The pickle format knows about object boundaries: by design, <code>pickle.dumps('x') + pickle.dumps('y')</code> is not the same bytestring as <code>pickle.dumps('xy')</code>. </p> <p>If you're interested to learn some background on the implementation, <a href="http://peadrop.com/blog/2007/06/18/pickle-an-interesting-stack-language/" rel="nofollow">this article</a> is an easy read to shed some light on the python pickler.</p>
QA:
using a Python script w 2nd Order Runge Kutta method to solve the equation of a pendulum, how do I add a calculation of the KE, PE, and TE?
<p>You are missing a factor 1/2 in both theta updates. The formulas for the midpoint method apply uniformly to all components of the first order system.</p> <p>The potential energy should contain the integral of <code>sin(x)</code>, <code>C-cos(x)</code>. For instance, </p> <pre><code>Pe[i+1] = m*g*L*(1-np.cos(theta[i+1])) </code></pre> <p>The formulas for the energies at time point <code>i+1</code> also apply at time point <code>0</code>.</p> <p>And finally, the indicated exact solution is for the small angle approximation, there is no finitely expressible exact solution for the general physical pendulum. For the given amplitude of <code>theta0=0.01</code>, the small angle approximation should be good enough, but be aware of this for larger swings.</p>
QA:
Using subprocess for accessing HBase
<p>If you need to access HBase from Python I strongly suggest you looks at the <strong>happybase</strong> modules.</p> <p>I have been using them in production for the past 4 years - and they have simplified our ETL tasks.</p> <p>Out of the box they are Python 2.X, but with a few minutes work - you can upgrade them to Python 3 (useful if you data is UTF-8)</p>
QA:
Python: Pandas, dealing with spaced column names
<p>This is the way I'm mentioning in the comment: it uses a file object to skip the custom dirty data you need to skip at the beginning. You land the file offset at the appropriate location in the file where <code>read_fwf</code> simply does the job:</p> <pre><code>with open(rawfile, 'r') as data_file: while(data_file.read(1)=='#'): last_pound_pos = data_file.tell() data_file.readline() data_file.seek(last_pound_pos) df = pd.read_fwf(data_file) df Out[88]: i mult stat (+/-) syst (+/-) Q2 x x.1 Php 0 0 0.322541 0.018731 0.026681 1.250269 0.037525 0.148981 0.104192 1 1 0.667686 0.023593 0.033163 1.250269 0.037525 0.150414 0.211203 2 2 0.766044 0.022712 0.037836 1.250269 0.037525 0.149641 0.316589 3 3 0.668402 0.024219 0.031938 1.250269 0.037525 0.148027 0.415451 4 4 0.423496 0.020548 0.018001 1.250269 0.037525 0.154227 0.557743 5 5 0.237175 0.023561 0.007481 1.250269 0.037525 0.159904 0.750544 </code></pre>
QA:
Writing rows in a csv using dictionaries in a loop (python 3)
<p>My solution was:</p> <pre><code>fieldnames = ['id', 'variable1', 'variable2'] f= open('file.csv', 'w', newline='') my_writer = csv.DictWriter(f, fieldnames) my_writer.writeheader() for i in something: something where I get data for mydict writer.writerow(mydict) f.close() </code></pre>
QA:
Python user input inside infinite loop too slow, easily confused
<p>After much experimenting based on helpful advice from users @tomalak, @rolf-of-saxony and @hevlastka my conclusion is that <strong>yes, this <em>is</em> an inevitability that I just have to live with.</strong> </p> <p>Even if you strip the example down to the basics by removing the database write process and making it a simple <em>parrot</em> script that just repeats back inputs (See <a href="http://stackoverflow.com/questions/40156905/python-on-raspberry-pi-user-input-inside-infinite-loop-misses-inputs-when-hit-wi">Python on Raspberry Pi user input inside infinite loop misses inputs when hit with many</a>), it is still possible to scan items so fast that inputs get missed/skipped/ignored. The Raspberry Pi simply cannot keep up. </p> <p>So my approach will now be to add an audio feedback feature such as a beep sound to indicate to the user when the device is ready to receive the next input. A route I didn't want to go down but it seems my code is the most efficient it can be and we're still able to hit the limits. Responsibility is with the user to not go at breakneck speed and the best we can do a responsible product builders is give them good feedback. </p>
QA:
Call a Python function with arguments based on user input
<p>You should investigate the <a href="https://docs.python.org/2/library/cmd.html?highlight=cmd#module-cmd" rel="nofollow">cmd</a> module. This allows you to parse input similar to shell commands, but I believe you can get tricky and change the delimiters if the parentheses are an important part of the specification.</p>
QA:
Sort a List of a Tuple.. of a list. Case insensitive
<p>Right now, your sort is only taking into account the first word in the list. In order to make it sort lexicographically based on <em>all</em> the words in the list, your sort key should return a <em>list</em> of lower-cased words (one lower-cased word for each word in the input list)</p> <pre><code>def sort_key(t): word_list, integer = t return [word.lower() for word in word_list] Final_Array.sort(key=sort_key) </code></pre> <p><sup>Due to the complexity of the sort, I'd prefer to avoid the lambda in this case, but not everyone necessarily agrees with that opinion :-)</sup></p>
QA:
AttributeError when creating tkinter.PhotoImage object with PIL.ImageTk
<p><code>ImageTk.PhotoImage</code> as in <code>PIL.ImageTk.PhotoImage</code> is not the same class as <code>tk.PhotoImage</code> (<code>tkinter.PhotoImage</code>) they just have the same name</p> <p>here is ImageTk.PhotoImage docs: <a href="http://pillow.readthedocs.io/en/3.1.x/reference/ImageTk.html#PIL.ImageTk.PhotoImage" rel="nofollow">http://pillow.readthedocs.io/en/3.1.x/reference/ImageTk.html#PIL.ImageTk.PhotoImage</a> as you can see there is no put method in it.</p> <p>but <code>ImageTk.PhotoImage</code> do have it: <a href="http://epydoc.sourceforge.net/stdlib/Tkinter.PhotoImage-class.html" rel="nofollow">http://epydoc.sourceforge.net/stdlib/Tkinter.PhotoImage-class.html</a></p>
QA:
Sort a List of a Tuple.. of a list. Case insensitive
<pre><code>Final_Array.sort(key=lambda x: list(map(str.lower, x[0]))) </code></pre>
QA:
Drawing on python and pycharm
<p>You need to call the function so it will start:</p> <pre><code>import turtle def drawSquare(t, size): for i in range(4): t.forward(size) t.left(90) turtle.mainloop() drawSquare(turtle.Turtle(), 100) </code></pre>
QA:
Installing bsddb package - python
<p>@bamdan 's answer uses an older version of Berkeley DB, if you still want to use the latest, Berkeley DB,</p> <ul> <li><p>First, install the latest Berkeley DB</p> <pre><code>pip install berkeley-db </code></pre></li> <li><p>Second, set an environment variable <code>YES_I_HAVE_THE_RIGHT_TO_USE_THIS_BERKELEY_DB_VERSION</code> to indicate that you have the license</p> <pre><code>BERKELEYDB_DIR=$(brew --cellar)/berkeley-db4/6.1.26 YES_I_HAVE_THE_RIGHT_TO_USE_THIS_BERKELEY_DB_VERSION=yes pip install bsddb3 </code></pre></li> </ul>
QA:
Work with a row in a pandas dataframe without incurring chain indexing (not coping just indexing)
<p>This should work:</p> <pre><code>row_of_interest = df.loc['R2', :] row_of_interest.is_copy = False row_of_interest['Col2'] = row_of_interest['Col2'] + 1000 </code></pre> <p>Setting <code>.is_copy = False</code> is the trick</p> <p>Edit 2:</p> <pre><code>import pandas as pd import numpy as np data = {'Col1' : [4,5,6,7], 'Col2' : [10,20,30,40], 'Col3' : [100,50,-30,-50], 'Col4' : ['AAA', 'BBB', 'AAA', 'CCC']} df = pd.DataFrame(data=data, index = ['R1','R2','R3','R4']) row_of_interest = df.loc['R2'] row_of_interest.is_copy = False new_cell_value = row_of_interest['Col2'] + 1000 row_of_interest['Col2'] = new_cell_value print row_of_interest df.loc['R2'] = row_of_interest print df </code></pre> <p>df:</p> <pre><code> Col1 Col2 Col3 Col4 R1 4 10 100 AAA R2 5 1020 50 BBB R3 6 30 -30 AAA R4 7 40 -50 CCC </code></pre>
QA:
Work with a row in a pandas dataframe without incurring chain indexing (not coping just indexing)
<p>most straight forward way to do this</p> <pre><code>df.loc['R2', 'Col2'] += 1000 df </code></pre> <p><a href="https://i.stack.imgur.com/5m2KA.png" rel="nofollow"><img src="https://i.stack.imgur.com/5m2KA.png" alt="enter image description here"></a></p>
QA:
problems dealing with pandas read csv
<p>In your message, you said that you're a running:</p> <pre><code>df = pd.read_csv('SHL1_TAQ_600000_201201.txt',usecols=fields) </code></pre> <p>Which did not throw an error for me and @Anil_M. But from your traceback, it is possible to see that the command used is another one:</p> <pre><code>df = pd.read_csv('SHL1_TAQ_600000_201201.txt',usecols=fields, header=1) </code></pre> <p>which includes a <code>header=1</code> and it throws the error mentioned.</p> <p>So, I would guess that the error comes from some confusion on your code.</p>
QA:
Ipython cv2.imwrite() not saving image
<p>As Jean suggested, the error is due to the \ being interpretted as an escape sequence. It is hence always safer to use <code>os.path.join()</code> as it is more cross platform and you need not worry about the escape sequence problem. For instance, in your case, you further need not worry about the first few arguments, as that is your home directory</p> <pre><code>import os cv2.imwrite(os.path.join(os.path.expanduser('~'),'Desktop','tropical_image_sig5.bmp'), img2) </code></pre> <p><code>os.path.expanduser('~')</code> will directly return your home directory.</p>
QA:
How can I create a mesh that can be changed without invalidating native sets in Abaqus?
<p>As usual, there is more than one way. </p> <p>One technique, if you know the coordinates of some point on or near the edge(s) of interest, is to use the EdgeArray.findAt() method, followed with the Edge.getNodes() method to return the Node objects, and then defining a new set from them. You can use the following code for inspiration for other more complex methods you might dream up:</p> <pre><code># Tested on Abaqus/CAE 6.12 # Assumes access from the Part-level (Assembly-level is similar): p = mdb.models['Model-1'].parts['Part-1'] # the Part object e = p.edges # an EdgeArray of Edge objects in the Part # Look for your edge at the specified coords, then get the nodes: e1 = e.findAt( coordinates = (0.5, 0.0, 0.0) ) # the Edge object of interest e1_nodes = e1.getNodes() # A list of Node objects # Specify the new node set: e1_nset = p.SetFromNodeLabels( name='Nset-1', nodeLabels=[node.label for node in e1_nodes] ) </code></pre>
QA:
How to limit number of concurrent threads in Python?
<p>I'm very knowledgeable on how good this method is but I did it this way a few times:</p> <pre><code>import threading def process_something(): something = list(get_something) def worker(): while something: obj = something.pop() # do something with obj threads = [Thread(target=worker) for i in range(4)] [t.start() for t in threads] [t.join() for t in threads] </code></pre>
QA:
Issue when imoporting GDAL : ImportError, Library not loaded, Image not found
<p>I found a solution to my problem <a href="https://github.com/conda-forge/gdal-feedstock/issues/111" rel="nofollow">here</a>.</p> <p>Thank you for the clear explanation of "ocefpaf":</p> <blockquote> <p>You problem seems like the usuall mismatch between conda-forge and defaults. Can you try the following instructions (if you do want to use conda-forge's gdal of course):</p> <ol> <li><p>Make sure you have the latest conda to take advantage of the channel preference feature. You can do that by issuing conda update conda in the root env of your conda installation.</p></li> <li><p>Edit your .condarc file and place the conda-forge on top of defaults. The .condarc usually lives in your home directory. See mine below. (Note that the more channels you have you are more likely to face issues. I recommend having only defaults and conda-forge.)</p></li> <li><p>Issue the following commands to check if you will get the correct installation:</p></li> </ol> </blockquote> <pre><code>conda create --yes -n TEST_GDAL python=3.5 gdal source activate TEST_GDAL python -c "from osgeo import gdal; print(gdal.__version__)" </code></pre> <blockquote> <p>If you get 2.1.1 you got a successful installation of the latest version from conda-forge. We always recommend users to work with envs as the the example above. But you do not need to use Python 3.5 (conda-forge has 3.4 and 2.7 also) and you do not need to name the env TEST_GDAL.</p> <p>And here is my .condarc file.</p> </blockquote> <pre><code>&gt; cat .condarc channels: - conda-forge - defaults show_channel_urls: true </code></pre>
QA:
Work with a row in a pandas dataframe without incurring chain indexing (not coping just indexing)
<p>You can remove the warning by creating a series with the slice you want to work on:</p> <pre><code>from pandas import Series row_of_interest = Series(data=df.loc['R2', :]) row_of_interest.loc['Col2'] += 1000 print(row_of_interest) </code></pre> <p>Results in:</p> <pre><code>Col1 5 Col2 1020 Col3 50 Col4 BBB Name: R2, dtype: object </code></pre>
QA:
Python: How to develop a between_time similar method when on pandas 0.9.0?
<p><strong>UPDATE:</strong></p> <p>try to use:</p> <pre><code>df.ix[df.index.indexer_between_time('08:00','09:50')] </code></pre> <p><strong>OLD answer:</strong></p> <p>I'm not sure that it'll work on Pandas 0.9.0, but it's worth to try it:</p> <pre><code>df[(df.index.hour &gt;= 8) &amp; (df.index.hour &lt;= 9)] </code></pre> <p>PS please be aware - it's not the same as <code>between_time</code> as it checks only hours and <code>between_time</code> is able to check <strong>time</strong> like <code>df.between_time('08:01:15','09:13:28')</code></p> <p><strong>Hint</strong>: download a source code for a newer version of Pandas and take a look at the definition of <code>indexer_between_time()</code> function in <code>pandas/tseries/index.py</code> - you can clone it for your needs</p>
QA:
Why is my Python script not running via command line?
<p>Without seeing your error message it's hard to say exactly what the problem is, but a few things jump out:</p> <ul> <li>No indentation after if __name__ == "__main__":</li> <li>you're only passing one argument into the hello function and it requires two.</li> <li>the sys module is not visible in the scope outside the hello function.</li> </ul> <p>probably more, but again, need the error output.</p> <p>Here's what you might want:</p> <pre><code>import sys def hello(a,b): print "hello and that's your sum:" sum=a+b print sum if __name__ == "__main__": hello(int(sys.argv[1]), int(sys.argv[2])) </code></pre>
QA:
Why is my Python script not running via command line?
<ul> <li>Import <code>sys</code> in <strong>global scope</strong>, not in the end of the function.</li> <li>Send <strong>two arguments</strong> into <code>hello</code>, one is not enough. </li> <li>Convert these arguments to <strong>floats</strong>, so they can be added as numbers.</li> <li><strong>Indent</strong> properly. In python indentation <em>does</em> matter.</li> </ul> <p>That should result in:</p> <pre><code>import sys def hello(a, b): sum = a + b print "hello and that's your sum:", sum if __name__ == "__main__": hello(float(sys.argv[1]), float(sys.argv[2])) </code></pre>
QA:
How to find the longest sub-array within a threshold?
<p>Most likely, the OP's own answer is the best possible algorithm, as it is O(n). However, the pure-python overhead makes it very slow. However, this overhead can easily be reduced by compiling the algorithm using <a href="http://numba.pydata.org/" rel="nofollow" title="numba">numba</a>, with the current version (0.28.1 as of this writing), there is no need for any manual typing, simply decorating your function with <code>@numba.njit()</code> is enough.</p> <p>However, if you do not want to depend on <a href="http://numba.pydata.org/" rel="nofollow" title="numba">numba</a>, there is a numpy algorithm in O(n log n):</p> <pre><code>def algo_burnpanck(sorted_array,thresh): limit = np.searchsorted(sorted_array,sorted_array+thresh,'right') distance = limit - np.arange(limit.size) best = np.argmax(distance) return best, limit[best]-1 </code></pre> <p>I did run a quick profiling on my own machine of the two previous answers (OP's and Divakar's), as well as my numpy algorithm and the numba version of the OP's algorithm.</p> <pre><code>thresh = 1 for n in [100, 10000]: sorted_array = np.sort(np.random.randn(n,)) for f in [algo_user1475412,algo_Divakar,algo_burnpanck,algo_user1475412_numba]: a,b = f(sorted_array, thresh) d = b-a diff = sorted_array[b]-sorted_array[a] closestlonger = np.min(sorted_array[d+1:]-sorted_array[:-d-1]) assert sorted_array[b]-sorted_array[a]&lt;=thresh assert closestlonger&gt;thresh print('f=%s, n=%d thresh=%s:'%(f.__name__,n,thresh))#,d,a,b,diff,closestlonger) %timeit f(sorted_array, thresh) </code></pre> <p>Here are the results:</p> <pre><code>f=algo_user1475412, n=100 thresh=1: 10000 loops, best of 3: 111 µs per loop f=algo_Divakar, n=100 thresh=1: 10000 loops, best of 3: 74.6 µs per loop f=algo_burnpanck, n=100 thresh=1: 100000 loops, best of 3: 9.38 µs per loop f=algo_user1475412_numba, n=100 thresh=1: 1000000 loops, best of 3: 764 ns per loop f=algo_user1475412, n=10000 thresh=1: 100 loops, best of 3: 12.1 ms per loop f=algo_Divakar, n=10000 thresh=1: 1 loop, best of 3: 1.76 s per loop f=algo_burnpanck, n=10000 thresh=1: 1000 loops, best of 3: 308 µs per loop f=algo_user1475412_numba, n=10000 thresh=1: 10000 loops, best of 3: 82.9 µs per loop </code></pre> <p>At 100 numbers, O(n^2) solution using numpy just barely beats the O(n) python solution, but quickly after, the scaling makes that algorithm useless. The O(n log n) keeps up even at 10000 numbers, but the numba approach is unbeaten everywhere.</p>
QA:
Python find and replace dialog from Rapid GUI Programming error
<p>The code in question can be found here - <a href="https://github.com/suzp1984/pyqt5-book-code/blob/master/chap07/ui_findandreplacedlg.py" rel="nofollow">https://github.com/suzp1984/pyqt5-book-code/blob/master/chap07/ui_findandreplacedlg.py</a>. If that file is in the same directory as the code you're trying to run, just do </p> <pre><code>import ui_findandreplacedlg </code></pre>
QA:
Database Connect Error: Centos 6 / Apache 2.4 / Postgres 9.4 / Django 1.9 / mod_wsgi 3.5 / python 2.7
<p>MySQL and PostgreSQL both do not come along with a user called 'leechprotect'. But a google search points out, that this username <a href="https://confluence2.cpanel.net/display/1152Docs/Leech+Protect" rel="nofollow">is related to cPanel</a> - might be worth reading that to understand whats going on. Afterwards you might consider deactivating it for you project directory.</p>
QA:
Sort matrix based on its diagonal entries
<p>Here I simplify a straightforward solution that has been stated before but is hard to get your heads around.</p> <p>This is useful if you want to sort a table (e.g. confusion matrix by its diagonal magnitude and arrange rows and columns accordingly.</p> <pre><code>&gt;&gt;&gt; A=np.array([[5,1,4],[7,2,9],[8,0,3]]) &gt;&gt;&gt; A array([[5, 1, 4], [7, 2, 9], [8, 0, 3]]) &gt;&gt;&gt; diag = np.diag(A) &gt;&gt;&gt; diag array([5, 2, 3]) &gt;&gt;&gt; idx=np.argsort(diag) # get the order of items that are in diagon &gt;&gt;&gt; A[idx,:][:,idx] # reorder rows and arrows based on the order of items on diagon array([[2, 9, 7], [0, 3, 8], [1, 4, 5]]) </code></pre> <p>if you want to sort in descending order just add <code>idx = idx[::-1] # reverse order</code></p>
QA:
Python - reduce complexity using sets
<p>This is what I see, not knowing much about spotify:</p> <pre><code>for id_ in track_ids: # this runs N times, where N = len(track_ids) ... tids.add(track_id) # tids contains all track_ids processed until now # in the end: len(tids) == N ... features = sp.audio_features(tids) # features contains features of all tracks processed until now # in the end, I guess: len(features) == N * num_features_per_track urls = {x['analysis_url'] for x in features if x} # very probably: len(urls) == len(features) for url in urls: # for the first track, this processes features of the first track only # for the seconds track, this processes features of 1st and 2nd # etc. # in the end, this loop repeats N * N * num_features_per_track times </code></pre> <p>You should not any url twice. And you do, because you keep all tracks in <code>tids</code> and then for each track you process everything in <code>tids</code>, which turns the complexity of this into O(n<sup>2</sup>).</p> <p>In general, always look for loops inside loops when trying to reduce complexity.</p> <p>I believe in this case this should work, if <code>audio_features</code> expects a set of ids:</p> <pre><code># replace this: features = sp.audio_features(tids) # with: features = sp.audio_features({track_id}) </code></pre>
QA:
shapely is_valid for polygons in 3D
<p>The problem is that <code>shapely</code> in fact ignores the z coordinate. So, as far as shapely can tell you are building a polygon with the points <code>[(1,0),(1,1), (1,1)]</code> that aren't enough to build a polygon.</p> <p>See this other SO question for more information: <a href="http://stackoverflow.com/questions/39317261/python-polygon-does-not-close-shapely/39347117#39347117">python-polygon-does-not-close-shapely</a>.</p> <p>IMHO, shapely shouldn't allow three dimension coordinates, because it brings this kind of confusions. </p>
QA:
Mark as unseen on Gmail (imaplib)
<p>It appears you've misunderstood flags on APPEND a bit.</p> <p>By doing <code>APPEND folder (-FLAGS \Seen) ...</code> you've actually created a message with two flags: The standard <code>\Seen</code> flag, and a nonstandard <code>-FLAGS</code> flag.</p> <p>To create a message without the \Seen flag, just use <code>()</code> as your flag list for <code>APPEND</code>.</p> <p><code>-FLAGS</code> is a subcommand to STORE, saying to remove these flags from the current list. Conversely, <code>+FLAGS</code> is add these flags to the current list. The plain <code>FLAGS</code> overwrites the current list.</p> <p>Also, if you do remove the <code>\Seen</code> flag over an IMAP connection, it can take sometime to show up in the GMail WebUI. You may need to refresh or switch folders to get the changes to render.</p> <p>NB: You are not protecting your backslashes. <code>\S</code> is not a legal escape sequence, so will be passed through, but you should either use a double backslash (<code>'\\Seen'</code>) or a raw string (<code>r'\Seen'</code>)</p>
QA:
Reading Database Queries into a Specific format in Python
<p>In this code the commented lines at the top indicate what's needed to access the sqlite database. Since I didn't want to build and populate such a database I created the object <strong>C</strong> to emulate its approximate behaviour. I used <strong>defaultdict</strong> because I don't know how many possible combinations of id's and tasks are involved. However, this means that only non-zero occurrences are represented in the final dictionary.</p> <pre><code>#~ import sqlite3 #~ conn = sqlite3 . connect ( some database ) #~ c = conn . cursor ( ) #~ c . execute ( 'Select id, task from aTable' ) class C: def __init__(self,iterated): self.iterated=iterated def fetchone (self): for _ in iter(list(self.iterated)): yield _ c=C( [ ['1','1'], ['2','1'], ['3','2'], ['4','2'] ] ) from collections import defaultdict counts = defaultdict(int) for row in c.fetchone(): print (row) id, task = row counts [(id,task)]+=1 print (counts) </code></pre> <p>Here's the output.</p> <pre><code>['1', '1'] ['2', '1'] ['3', '2'] ['4', '2'] defaultdict(&lt;class 'int'&gt;, {('4', '2'): 1, ('2', '1'): 1, ('1', '1'): 1, ('3', '2'): 1}) </code></pre>
QA:
How to return JSON from Python REST API
<p>You will first need to get the mysql query to return a dict object instead of a list. If your library is MySQLdb then this answer: <a href="http://stackoverflow.com/questions/4147707/python-mysqldb-sqlite-result-as-dictionary">Python - mysqlDB, sqlite result as dictionary</a> is what you need.</p> <p>Here is a link to the docs for MySQLdb: <a href="http://www.mikusa.com/python-mysql-docs/docs/MySQLdb.connections.html" rel="nofollow">http://www.mikusa.com/python-mysql-docs/docs/MySQLdb.connections.html</a></p> <p>I think if you pass in the cursor class you want to use when you create your cursor the result of fetchone will be a dictionary. </p> <pre><code>with self.connection.cursor(MySQLdb.cursors.DictCursor) as cursor: </code></pre> <p>Running json.dumps(result) on a dictionary will give the output you are looking for.</p>
QA:
Python - Return integer value for list enumeration
<p>Yes, use <code>list.index()</code>.</p> <pre><code>a = ['m', 'rt', 'paaq', 'panc'] id_list = a[a.index('rt')+1:] assert id_list == ['paaq', 'panc'] </code></pre> <p>Or, to minimally change your program:</p> <pre><code>a = ['m', 'rt', 'paaq', 'panc'] loc_int = a.index('rt') id_list = a[loc_int + 1:] print id_list </code></pre> <p>References:</p> <ul> <li><a href="https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange" rel="nofollow">https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange</a></li> <li><a href="https://docs.python.org/2/tutorial/datastructures.html#more-on-lists" rel="nofollow">https://docs.python.org/2/tutorial/datastructures.html#more-on-lists</a></li> </ul>
QA:
Concatenate string using .format
<p><code>''.join</code> is probably fast enough and efficient.</p> <pre><code>'-'.join((test_1,test_2)) </code></pre> <p>You can measure different methods using the <code>timeit</code> module. That can tell you which is fastest </p> <p>This is an example of how <code>timeit</code> can be used:-</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; timeit.timeit('"-".join(str(n) for n in range(100))', number=10000) 0.8187260627746582 </code></pre>
QA:
Python - Return integer value for list enumeration
<pre><code>a[a.index('rt') + 1:] </code></pre> <p>What this is doing is <a href="https://docs.python.org/2.3/whatsnew/section-slices.html" rel="nofollow">slicing</a> the array, starting at where <code>a.index('rt')</code>. not specifying an end <code>:]</code> means we want until the end of the list.</p>
QA:
Theano's function() reports that my `givens` value is not needed for the graph
<p>why you use "=" sign? I think, it made train_mode not readable, my code works well by writing: <code>givens = {train_mode:1}</code></p>
QA:
Running shell command from Python and capturing the output
<p><strong>I had a slightly different flavor of the same problem with the following requirements:</strong></p> <ol> <li>Capture and return STDOUT messages as they accumulate in the STDOUT buffer (i.e. in realtime). <ul> <li><em>@vartec solved this Pythonically with his use of generators and the 'yield'<br> keyword above</em></li> </ul></li> <li>Print all STDOUT lines (<em>even if process exits before STDOUT buffer can be fully read</em>)</li> <li>Don't waste CPU cycles polling the process at high-frequency</li> <li>Check the return code of the subprocess</li> <li>Print STDERR (separate from STDOUT) if we get a non-zero error return code.</li> </ol> <p><strong>I've combined and tweaked previous answers to come up with the following:</strong></p> <pre><code>def run_command(command): p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) # Read stdout from subprocess until the buffer is empty ! for line in iter(p.stdout.readline, b''): if line: # Don't print blank lines yield line # This ensures the process has completed, AND sets the 'returncode' attr while p.poll() is None: sleep(.1) #Don't waste CPU-cycles # Empty STDERR buffer err = p.stderr.read() if p.returncode != 0: # The run_command() function is responsible for logging STDERR print "Error: " + err </code></pre> <p><strong>This code would be executed the same as previous answers:</strong></p> <pre><code>for line in run_command(cmd): print line </code></pre>
QA:
How to get PyCharm to check PEP8 code style?
<p>OP asks for a way to highlight PEP8 errors on PyCharm, but there's another way (much clearer in my opinion) to see the violations (extracted from <a href="https://www.jetbrains.com/help/pycharm/2016.1/inspection-tool-window.html" rel="nofollow">PyCharm's docs</a>):</p> <blockquote> <p><strong>Inspection Tool Window</strong></p> <p>View | Tool Windows | Inspection:</p> <ul> <li>You can access the tool window this way only when it is already opened through Code | Inspect Code.</li> <li>After you deactivate the tool window manually by clicking the Close button, the tool window is again available only through Code | Inspect Code. The Inspection tool window displays inspection results on separate tabs</li> </ul> </blockquote> <p>Just tested it on a <em>PyCharm Community Edition</em> and it worked like a <em>charm</em> (no pun intended).</p>
QA:
Python: How to develop a between_time similar method when on pandas 0.9.0?
<p>Here is a NumPy-based way of doing it:</p> <pre><code>import pandas as pd import numpy as np import datetime dates = pd.date_range(start="08/01/2009",end="08/01/2012",freq="10min") df = pd.DataFrame(np.random.rand(len(dates), 1)*1500, index=dates, columns=['Power']) epoch = np.datetime64('1970-01-01') start = np.datetime64('1970-01-01 08:00:00') end = np.datetime64('1970-01-01 09:00:00') # convert the dates to a NumPy datetime64 array date_array = df.index.asi8.astype('&lt;M8[ns]') # replace the year/month/day with 1970-01-01 truncated = (date_array - date_array.astype('M8[D]')) + epoch # compare the hour/minute/seconds etc with `start` and `end` mask = (start &lt;= truncated) &amp; (truncated &lt;=end) print(df[mask]) </code></pre> <p>yields</p> <pre><code> Power 2009-08-01 08:00:00 1007.289466 2009-08-01 08:10:00 770.732422 2009-08-01 08:20:00 617.388909 2009-08-01 08:30:00 1348.384210 ... 2012-07-31 08:30:00 999.133350 2012-07-31 08:40:00 1451.500408 2012-07-31 08:50:00 1161.003167 2012-07-31 09:00:00 670.545371 </code></pre>
QA:
Concatinating multiple Data frames of different length
<p>The key is to make a <code>list</code> of different data-frames and then concatenate the list instead of individual concatenation.</p> <p>I created 10 <code>df</code> filled with random length data of one column and saved to <code>csv</code> files to simulate your data.</p> <pre><code>import pandas as pd import numpy as np from random import randint #generate 10 df and save to seperate csv files for i in range(1,11): dfi = pd.DataFrame({'a':np.arange(randint(2,11))}) csv_file = "file{0}.csv".format(i) dfi.to_csv(csv_file, sep='\t') print "saving file", csv_file </code></pre> <p>Then we read those 10 <code>csv</code> files into separate data-frames and save to a <code>list</code></p> <pre><code>#read previously saved csv files into 10 seperate df # and add to list frames = [] for x in range(1,10): csv_file = "file{0}.csv".format(x) newdf = pd.DataFrame.from_csv(csv_file, sep='\t') frames.append(newdf) </code></pre> <p>Finally, we concatenate the <code>list</code></p> <pre><code>#concatenate frames list result = pd.concat(frames, axis=1) print result </code></pre> <p>The result is 10 frames of variable length concatenated column wise into single <code>df</code>.</p> <pre><code>saving file file1.csv saving file file2.csv saving file file3.csv saving file file4.csv saving file file5.csv saving file file6.csv saving file file7.csv saving file file8.csv saving file file9.csv saving file file10.csv a a a a a a a a a 0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 0.0 1 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1 1.0 2 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2 2.0 3 3.0 3.0 3.0 3.0 3.0 NaN 3.0 3 NaN 4 4.0 4.0 4.0 4.0 4.0 NaN NaN 4 NaN 5 5.0 5.0 5.0 5.0 5.0 NaN NaN 5 NaN 6 6.0 6.0 6.0 6.0 6.0 NaN NaN 6 NaN 7 NaN 7.0 7.0 7.0 7.0 NaN NaN 7 NaN 8 NaN 8.0 NaN NaN 8.0 NaN NaN 8 NaN 9 NaN NaN NaN NaN 9.0 NaN NaN 9 NaN 10 NaN NaN NaN NaN NaN NaN NaN 10 NaN </code></pre> <p>Hope this is what you are looking for. A good example on merge, join and concatenate can be found <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow">here</a>.</p>
QA:
insert element in the start of the numpy array
<p>You can do the insert by ommiting the axis param:</p> <pre><code>x = np.array([0,0,0,0]) x = np.insert(x, 0, -1) x </code></pre> <p>That will give:</p> <pre><code>array([-1, 0, 0, 0, 0]) </code></pre>
QA:
Reformat JSON file?
<p>What about:</p> <pre><code>cat &lt;file&gt; | python -m json.tool </code></pre> <p>This will reformat the contents of the file into a uniform human readable format. If you really need to change the names of the fields you could use sed.</p> <pre><code>cat &lt;file&gt; | sed -e 's/"properties"/"attributes"/' </code></pre> <p>This may be sufficient for your use case. If you have something that requires more nuanced parsing, you'll have to read up on how to manage the JSON through an ORM library.</p>
QA:
Search for a combination in dataframe to change cell value
<p>You have all almost all your code, just create <code>dictionary</code> or <code>list</code> and iterate over it and you are done.</p> <pre><code>import pandas as pd combinations = [['key1', 'key2', 'msg']] combinations.append(['Texas 1', '222', 'triple two']) combinations.append(['Texas 1', '555', 'triple five']) df = pd.DataFrame([ ['Texas 1', '111', '222', '333'], ['Texas 1', '444', '555', '666'], ['Texas 2', '777','888','999'] ]) for c in combinations: df.ix[(df[0] == c[0]) &amp; (df[2] == c[1]), 1] = c[2] </code></pre> <p>Output:</p> <pre><code> 0 1 2 3 0 Texas 1 triple two 222 333 1 Texas 1 triple five 555 666 2 Texas 2 777 888 999 </code></pre>
QA:
Is it possible to pass a single user input (an int) into an argument to match 2 ints in python?
<p>I am not sure what exactly you want to do, but I guess there are multiple solutions to it. I will just give one possible solution:</p> <pre><code>def grid_maker(h,w=None): if w is None: w=h grid = [[" | " for _ in range(w)] for _ in range(h)] return grid </code></pre>
QA:
Python - dividing a user input to display a range of answers
<p><code>x % 13 == 0</code> by itself does nothing; it evaluates to True or False, but you then ignore that result. If you want to do something with it, you need to use it in an if condition.</p> <p>Note also that indentation is important - the else needs to be lined up with the if. There's no need for <code>while</code> at all because nothing can change within the loop.</p> <pre><code>if x % 13 == 0: print x else: print 'Your number us not divisible by 13' </code></pre>
QA:
Python - dividing a user input to display a range of answers
<p>Can do this:</p> <pre><code>x = int(input("Enter your number here: ")) def divide(x): for i in range(1,x): if i % 13 == 0: print (i) divide(x) </code></pre>
QA:
insert element in the start of the numpy array
<p>I'm not fully familiar with numpy, but it seems that the insert function does not affect the array you pass to it, but rather it returns a new array with the inserted value(s). You'll have to reassign to x if you really want x to change. </p> <pre><code>&gt;&gt;&gt; x= [-1, 0.30153836, 0.30376881, 0.29115761, 0.29074261, 0.28676876] &gt;&gt;&gt; np.insert(x,0,-1,axis=0) array([-1. , -1. , 0.30153836, 0.30376881, 0.29115761, 0.29074261, 0.28676876]) &gt;&gt;&gt; x [-1, 0.30153836, 0.30376881, 0.29115761, 0.29074261, 0.28676876] &gt;&gt;&gt; x = np.insert(x,0,-1,axis=0) &gt;&gt;&gt; x array([-1. , -1. , 0.30153836, 0.30376881, 0.29115761, 0.29074261, 0.28676876]) </code></pre>
QA:
iteration counter for GCD
<pre><code>def gcd(m, n): r = m % n counter = 0 while r != 0: m = n n = r r = m % n counter += 1 return n, counter </code></pre>
QA:
Python - dividing a user input to display a range of answers
<p>Instead you can do something like:</p> <pre><code>x = 27 / 13 print [13 * i for i in range(1,x+1)] </code></pre>
QA:
AttributeError: 'module' object has no attribute 'io' in caffe
<p><code>io</code> is a module in <code>caffe</code> package. Basically when you type <code>import caffe</code>, it will not automatically try to import all modules in <code>caffe</code> package including <code>io</code>. There are two solutions.</p> <p>First one: import caffe.io manually</p> <pre><code>import caffe import caffe.io </code></pre> <p>Second one: update to the latest caffe version, in which you should find a line in <code>__init__.py</code> under <code>python/caffe</code> directory:</p> <pre><code>from . import io </code></pre>
QA:
Python - dividing a user input to display a range of answers
<p>Borrow the back-ported print function Python 3:</p> <pre><code>from __future__ import print_function </code></pre> <p>The following will print all numbers in the range [1..x] inclusive</p> <pre><code>print([y for y in range(1,x+1,1) if y%13==0]) </code></pre>
QA:
Python - dividing a user input to display a range of answers
<p>I'd just show all multiples of 13 until x, dropping 0:</p> <pre><code>def divide(x): print range(0, x, 13)[1:] </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; divide(27) [13, 26] </code></pre>
QA:
Search for a combination in dataframe to change cell value
<h1>Great Use Case for <code>DataFrame.apply()</code>. Lamda functions all the way!!</h1> <pre><code>df = pd.DataFrame([ ['Texas 1', 111, 222, 333], ['Texas 1', 444, 555, 666], ['Texas 2', 777,888,999] ]) val_dict = {} # assumption # str_like_Success : [column_0 , column_1] val_dict["Success"] = ['Texas 1', 222] val_dict["Failure"] = ['Texas 2', 888] </code></pre> <p>The function <code>fill_values_from_dict</code> will be applied to each row, where <code>x</code> is the row (Series) and <code>val_dict</code> is the dictionary created above</p> <pre><code> def fill_values_from_dict(x,val_dict): for key,val in val_dict.items(): if x[0] == val[0] and x[2] == val[1]: x.set_value(1,key) return x return x </code></pre> <p>Apply <code>fill_values_from_dict</code> to each row </p> <pre><code>df1 = df.apply(lambda x : fill_values_from_dict(x,val_dict),axis=1) </code></pre> <p>Output: </p> <pre><code> print(df1) 0 1 2 3 0 Texas 1 Success 222 333 1 Texas 1 444 555 666 2 Texas 2 Failure 888 999 </code></pre>
QA:
Reformat JSON file?
<p>Manipulating JSON in Python is a good candidate for the <a href="https://en.wikipedia.org/wiki/IPO_model" rel="nofollow">input-process-output model</a> of programming.</p> <p>For input, you convert the external JSON file into a Python data structure, using <a href="https://docs.python.org/2/library/json.html#json.load" rel="nofollow"><code>json.load()</code></a>.</p> <p>For output, you convert the Python data structure into an external JSON file using <a href="https://docs.python.org/2/library/json.html#json.dump" rel="nofollow"><code>json.dump()</code></a>.</p> <p>For the processing or conversion step, do whatever it is that you need to do, using ordinary Python <code>dict</code> and <code>list</code> methods.</p> <p>This program might do what you want:</p> <pre><code>import json with open("b.json") as b: b = json.load(b) for feature in b["features"]: feature["attributes"] = feature["properties"] del feature["properties"] feature["geometry"]["paths"] = feature["geometry"]["coordinates"] del feature["geometry"]["coordinates"] del feature["geometry"]["type"] del feature["type"] with open("new-b.json", "w") as new_b: json.dump(b, new_b, indent=1, separators=(',', ': ')) </code></pre>
QA:
Python Arguments and Passing Floats in Arguments
<p><s>You didn't actually provide the code you're using (aside from incidentally in the traceback),</s>(<strong>Update:</strong> Code added later) but the answer is: Stop messing around with parsing <code>sys.argv</code> manually and use <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow">the <code>argparse</code> module</a> (or <code>docopt</code> or something that doesn't involve rolling your own switch parsing).</p> <pre><code>import argparse parser = argparse.ArgumentParser() parser.add_argument('-a', action='store_true') parser.add_argument('-b', metavar='INTERVAL', type=int, choices=range(11)) parser.add_argument('-c', action='store_true') parser.add_argument('-d', action='store_true') args = parser.parse_args() if args.a: print('Argument_A') if args.b is not None: print('The number provided is:', args.b) if args.c: print('Argument_C') if args.d: print('Argument_D') </code></pre> <p>If you want to accept <code>int</code> or <code>float</code>, the easiest solution is to just make <code>type=float</code> and use a consistent type (but the <code>range</code> check must be done outside the parsing step). If you must allow both, <code>ast.literal_eval</code> or a homegrown <code>argparse</code> type conversion function are options. Since you want a range check too (which <code>range</code> won't handle properly for <code>float</code> values that aren't equal to <code>int</code> values), roll a type checker:</p> <pre><code>def int_or_float(minval=None, maxval=None): def checker(val): try: val = int(val) except ValueError: val = float(val) if minval is not None and val &lt; minval: raise argparse.ArgumentTypeError('%r must be &gt;= %r' % (val, minval)) if maxval is not None and val &gt; maxval: raise argparse.ArgumentTypeError('%r must be &lt;= %r' % (val, maxval)) return val return checker </code></pre> <p>Then use it by replacing the definition for <code>-b</code> with:</p> <pre><code># Might want int_or_float(0, 10) depending on range exclusivity rules parser.add_argument('-b', metavar='INTERVAL', type=int_or_float(0, 11)) </code></pre>
QA:
How do I schedule a job in Django?
<p>Django is a web framework. It receives a request, does whatever processing is necessary and sends out a response. It doesn't have any persistent process that could keep track of time and run scheduled tasks, so there is no good way to do it using just Django.</p> <p>That said, Celery (<a href="http://www.celeryproject.org/" rel="nofollow">http://www.celeryproject.org/</a>) is a python framework specifically built to run tasks, both scheduled and on-demand. It also integrates with Django ORM with minimal configuration. I suggest you look into it.</p> <p>You could, of course, write your own external script that would use schedule module that you mentioned. You would need to implement a way to write shedule objects into the database and then you could have your script read and execute them. Is your "scheduledb" model already implemented?</p>
QA:
Keeping 'key' column when using groupby with transform in pandas
<p>that is bizzare!</p> <p>I tricked it like this</p> <pre><code>df.groupby(df.a.values).transform(lambda x: x) </code></pre> <p><a href="https://i.stack.imgur.com/XcYxq.png" rel="nofollow"><img src="https://i.stack.imgur.com/XcYxq.png" alt="enter image description here"></a></p>
QA:
python/pandas/sklearn: getting closest matches from pairwise_distances
<pre><code>from io import StringIO from sklearn import metrics stringdata = StringIO(u"""pid,ratio1,pct1,rsp 0,2.9,26.7,95.073615 1,11.6,29.6,96.963660 2,0.7,37.9,97.750412 3,2.7,27.9,102.750412 4,1.2,19.9,93.750412 5,0.2,22.1,96.750412 """) stats = ['ratio1','pct1','rsp'] df = pd.read_csv(stringdata) dist = metrics.pairwise.pairwise_distances(df[stats].as_matrix(), metric='mahalanobis') dist = pd.DataFrame(dist) ranks = np.argsort(dist, axis=1) df["rankcol"] = ranks.apply(lambda row: ','.join(map(str, row)), axis=1) df </code></pre>
QA:
Obey the Testing Goat - Traceback
<p>Found the error in my work. I was apparently missing an s in list.html</p> <pre><code>&lt;form method="POST" action="/lists/{{ list.id }}/add_item"&gt; </code></pre>
QA:
Django templates: why does __call__ magic method breaks the rendering of a non-model object?
<p>Because that's what the template language is designed to do. As <a href="https://docs.djangoproject.com/en/1.10/ref/templates/language/#variables" rel="nofollow">the docs state</a>:</p> <blockquote> <p>If the resulting value [of looking up a variable] is callable, it is called with no arguments. The result of the call becomes the template value.</p> </blockquote> <p>Without this, there would be no way of calling methods in templates, since the template syntax does not allow using parentheses.</p>
QA:
insert element in the start of the numpy array
<p>From the <code>np.insert</code> documentation:</p> <pre><code>Returns out : ndarray A copy of `arr` with `values` inserted. Note that `insert` does not occur in-place: a new array is returned. </code></pre> <p>You can do the same with <code>concatenate</code>, joining the new value to the main value. <code>hstack</code>, <code>append</code> etc use <code>concatenate</code>; insert is more general, allowing insertion in the middle (for any axis), so it does its own indexing and new array creation.</p> <p>In any case, the key point is that it does not operate in-place. You can't change the size of an array.</p> <pre><code>In [788]: x= np.array([0.30153836, 0.30376881, 0.29115761, 0.29074261, 0.28 ...: 676876]) In [789]: y=np.insert(x,0,-1,axis=0) In [790]: y Out[790]: array([-1. , 0.30153836, 0.30376881, 0.29115761, 0.29074261, 0.28676876]) In [791]: x Out[791]: array([ 0.30153836, 0.30376881, 0.29115761, 0.29074261, 0.28676876]) </code></pre> <p>Same action with concatenate; note that I had to add <code>[]</code>, short for <code>np.array([-1])</code>, so both inputs are 1d arrays. Expanding the scalar to array is all that <code>insert</code> is doing special.</p> <pre><code>In [793]: np.concatenate([[-1],x]) Out[793]: array([-1. , 0.30153836, 0.30376881, 0.29115761, 0.29074261, 0.28676876]) </code></pre>
QA:
Import error installing tlslite
<p>Assuming you installed tlslite correctly, try this:</p> <pre><code>&gt;&gt;&gt; from tlslite.checker import Checker </code></pre> <p>If that doesn't work, check that tlslite is in your site packages</p>
QA:
Percentage data from .csv to excel
<pre><code>for row in ws.iter_rows(row_offset=0): for i in reader: ws.append(float(i[2:-1])) code here </code></pre> <p>Float the value before you append it</p>
QA:
Python read dedicated rows from csv file
<p>Thanks for the answers. I defined a class and want to fill every value to the dedicated function:</p> <pre><code>class Class(object): def __init__(self, name, years, age, town): self.name = name self.years = years self.age = age self.town = town def GetName(self): return self.name def GetYears(self): return self.years def GetAge(self): return self.age def GetTown(self): return self.town def __str__(self): return "%s is a %s" % (self.name, self.years, self.age, self.town) </code></pre> <p>So my file reader should load the file read a line and fill the dedicated values into the function as shown below. I am just not sure how to call the reader for the first row based on A and the fill the function:</p> <pre><code>import csv with open('C:/0001.txt', newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=';') for row in spamreader: FirstRow = row[0] if FirstRow == 'A': **Fill Maria into GetName Fill 1.5 into GetYears Fill 20.0 into GetAge Fill FFM into GetTown** </code></pre>
QA:
Import error installing tlslite
<p>To work with <a href="https://pypi.python.org/pypi/tlslite/0.4.6" rel="nofollow">tlslite</a> I recommend to use a virtualenv and install TlsLite inside:</p> <pre><code>cd ~/virtualenv/ # &lt;- all my virtualenv are here virtualenv myvenv source ~/virtualenv/myvenv/bin/activate pip install -q -U pip setuptools # ensure last version pip install tlslite </code></pre> <p>With that in hand, you can use the <code>Checker</code>:</p> <pre><code>$ python &gt;&gt;&gt; from tlslite.checker import Checker &gt;&gt;&gt; </code></pre> <p>Et voilà !</p>
QA:
How do I return a nonflat numpy array selecting elements given a set of conditions?
<p>Let's define you variables:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.array([(1,2,3),(4,5,6),(7,8,9),(10,11,12)]) &gt;&gt;&gt; conditions = [True, False, False, True] </code></pre> <p>Now, let's select the elements that you want:</p> <pre><code>&gt;&gt;&gt; a[np.array(conditions)] array([[ 1, 2, 3], [10, 11, 12]]) </code></pre> <h3>Aside</h3> <p>Note that the simpler <code>a[conditions]</code> has some ambiguity:</p> <pre><code>&gt;&gt;&gt; a[conditions] -c:1: FutureWarning: in the future, boolean array-likes will be handled as a boolean array index array([[4, 5, 6], [1, 2, 3], [1, 2, 3], [4, 5, 6]]) </code></pre> <p>As you can see, <code>conditions</code> are treated here as (integer-like) index values which is not what we wanted.</p>
QA:
AWS Lambda sending HTTP request
<p>If you've deployed your Lambda function inside your VPC, it does not obtain a public IP address, even if it's deployed into a subnet with a route to an Internet Gateway. It only obtains a private IP address, and thus can not communicate to the public Internet by itself.</p> <p>To communicate to the public Internet, Lambda functions deployed inside your VPC need to be done so in a private subnet which has a <a href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Route_Tables.html#route-tables-nat" rel="nofollow">route</a> to either a <a href="https://aws.amazon.com/blogs/aws/new-managed-nat-network-address-translation-gateway-for-aws/" rel="nofollow">NAT Gateway</a> or a self-managed <a href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html" rel="nofollow">NAT instance</a>.</p>
QA:
How do I return a nonflat numpy array selecting elements given a set of conditions?
<p>you can use simple list slicing and <code>np.where</code> It's more or less made specifically for this situation..</p> <pre><code>&gt;&gt;&gt; a[np.where(conditions)] array([[[ 1, 2, 3], [10, 11, 12]]]) </code></pre>
QA:
Is there a way to refer two attributes of an object in a list?
<p>Reread your question. The answer is still yes. Use the <code>format</code> method of strings:</p> <pre><code>print("The taller athlete is {0.name} with {0.height} meters.".format(max(athletes_list, key=lambda a: a.height))) </code></pre>
QA:
Attribute error for PersonalInfoForm
<p>Your traceback is showing that you haven't used the view above at all, but the form. Presumably you've assigned the wrong thing in urls.py.</p> <p><strong>Edit</strong> Actually the problem is that your post method, when the form is not valid, returns the form itself and not an HttpResponse.</p> <p>However you should <strong>not</strong> be defining any of these methods. You are just replicating what the class-based views are already supposed to be doing for you. Make your view actually inherit from CreateView and remove all those method definitions completely.</p>
QA:
Is there a way to refer two attributes of an object in a list?
<p>Use <code>max</code> over both values (with height first):</p> <pre><code>from future_builtins import map # Only on Py2, to get generator based map from operator import attrgetter # Ties on height will go to first name alphabetically maxheight, name = max(map(attrgetter('height', 'name'), athletes)) print("The taller athlete is", name, "with", maxheight, "meters.") </code></pre> <p>Or so ties are resolved by order of appearance, not name:</p> <pre><code>maxheight, name = attrgetter('height', 'name')(max(athletes, key=attrgetter('height'))) </code></pre>
QA:
Setting Image background for a line plot in matplotlib
<p>You're creating two separate figures in your code. The first one with <code>fig, ax = plt.subplots(1)</code> and the second with <code>plt.figure(2)</code></p> <p>If you delete that second figure, you should be getting closer to your goal</p>
QA:
How do I unload (reload) a Python module?
<p>If <code>foo</code> is given an alias then reload the alias as <code>reload(foo)</code> raises an exception.</p> <pre><code>import foo as bar # Do things reload(bar) </code></pre>
QA:
'DataFrame' object is not callable
<p>You are reading a csv file but it has no header, the delimiter is a space not a comma, and there are a variable number of columns. So that is three mistakes in your first line.</p> <p>And data1 is a DataFrame, freqMap is a dictionary that is completely unrelated. So it makes no sense to do data1[freqMap].</p> <p>I suggest you step through this line by line in jupyter or a python interpreter. Then you can see what each line actually does and experiment.</p>
QA:
How to tag friends on Facebook using python
<p><a href="http://docs.seleniumhq.org/" rel="nofollow">Selenium</a> package might be helpful. <a href="https://pythonicways.wordpress.com/2016/10/04/invite-friends-to-your-facebook-page-with-python-selenium/" rel="nofollow">This example</a> (Invite friends to your facebook page with python) gives you more than you need to get you started. You can adjust it and use it to automate other actions on facebook. </p>
QA:
Python- request.post login credentials for website
<p>That is what your dict should look like</p> <pre><code>values = {'username': 'username','password': 'somepass'} </code></pre>
QA:
Pulling specific string with lxml?
<p>I ended up using <code>//div/@title[0]</code> which pulls the desired text.</p>
QA:
Is it possible to use FillBetweenItem to fill between two PlotCurveItem's in pyqtgraph?
<p>This fixed it. </p> <pre><code> phigh = pg.PlotCurveItem(x, y, pen = 'k') plow = pg.PlotCurveItem(x, yy, pen = 'k') pfill = pg.FillBetweenItem(ph, plow, brush = br) self.p2.addItem(ph) self.p2.addItem(plow) self.p2.addItem(pfill) </code></pre>
QA:
PyBrain - out = fnn.activateOnDataset(griddata)
<p>I believe it has to do with the dimensions of your initial data set not aligning with the dimensions of your griddata.</p> <p><code>alldata = ClassificationDataSet(3,1,nb_classes=10)</code> <code>griddata = ClassificationDataSet(2,1, nb_classes=4)</code></p> <p>They should both be 3, 1. However, when I adjust this my code fails at a later stage so I am also curious about this.</p>
QA:
Try and Except (TypeError)
<p>Try.</p> <pre><code>choice = input("enter v for validate, or enter g for generate").lower() if (choice == "v") or (choice == "g"): #do something else : print("Not a valid choice! Try again") restartCode() #pre-defined function, d/w about this* </code></pre> <p>However, if you really want to stick with try/except you can store the desired inputs, and compare against them. The error will be a KeyError instead of a TypeError. </p> <pre><code>choice = input("enter v for validate, or enter g for generate").lower() valid_choices = {'v':1, 'g':1} try: valid_choices[choice] #do something except: KeyError print("Not a valid choice! Try again") restartCode() #pre-defined function, d/w about this </code></pre>