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
Python - Creating a text file converting Fahrenheit to Degrees
40,092,290
<p>I'm new to Python and I've been given the task to create a program which uses a text file which contains figures in Fahrenheit, and then I need to change them into a text file which gives the figures in Degrees... Only problem is, I have no idea where to start. Any advice?</p>
0
2016-10-17T17:26:25Z
40,092,506
<p>I'd start making a python script file (a text file with *.py), and write an expression that <a href="https://docs.python.org/3/tutorial/inputoutput.html" rel="nofollow">opens</a> your text file. You'll need to do some operations on <a href="https://www.tutorialspoint.com/python/python_strings.htm" rel="nofollow">strings</a> to get your lines of characters into a usable data structure (possibly a <a href="https://www.codecademy.com/courses/python-beginner-nzzVa/0/1?curriculum_id=4f89dab3d788890003000096" rel="nofollow">list</a> of floats).</p> <p>Not required, but I also recommend you write a <a href="http://www.learnpython.org/en/Functions" rel="nofollow">function</a> that <a href="https://www.khanacademy.org/math/8th-engage-ny/engage-8th-module-4/8th-module-4-topic-d/v/converting-farenheit-to-celsius" rel="nofollow">converts</a> your units because it will make your code more readable.</p> <p>Finally, you'll want to convert your numbers back into strings that can be <a href="https://pythonprogramming.net/writing-file-python-3-basics/" rel="nofollow">written</a> to a file, and then of course <a href="https://learnpythonthehardway.org/book/ex16.html" rel="nofollow">write</a> those lines to a file.</p> <p>Check out the links I've provided as they take you to multiple learning materials for Python in general. You may find multiple answers to your problem under different tutorials, so explore!</p>
1
2016-10-17T17:39:56Z
[ "python" ]
FileNotFoundError When file exists (when created in current script)
40,092,293
<p>I am trying to create a secure (e.g., SSL/HTTPS) XML-RPC Client Server. The client-server part works perfectly when the required certificates are present on my system; however, when I try to <strong>create</strong> the certificates during execution, I receive a <strong>FileNotFoundError</strong> when opening the ssl-wrapped socket even though the certificates are clearly present (because the preceding function created them.) </p> <p>Why is the FileNotFoundError given when the files are present? (If I simply close and restart the python script no error is produced when opening the socket and everything works with no issue whatsoever.)</p> <p>I've searched elsewhere for solutions, but the best/closest answer I've found is, perhaps, "race conditions" between creating the certificates and opening them. However, I've tried adding "sleep" to alleviate the possibility of race conditions (as well as running each function individually via a user input menu) with the same error every time. </p> <p>What I am missing? </p> <p>Here is a snippet of my code:</p> <pre><code>import os import threading import ssl from xmlrpc.server import SimpleXMLRPCServer import certs.gencert as gencert # &lt;---- My python module for generating certs ... rootDomain = "mydomain" CERTFILE = "certs/mydomain.cert" KEYFILE = "certs/mydomain.key" ... def listenNow(ipAdd, portNum, serverCert, serverKey): # Create XMLRPC Server, based on ipAdd/port received server = SimpleXMLRPCServer((ipAdd, portNum)) # **THIS** is what causes the FileNotFoundError ONLY if # the certificates are created during THE SAME execution # of the program. server.socket = ssl.wrap_socket(server.socket, certfile=serverCert, keyfile=serverKey, do_handshake_on_connect=True, server_side=True) ... # Start server listening [forever] server.serve_forever() ... # Verify Certificates are present; if not present, # create new certificates def verifyCerts(): # If cert or key file not present, create new certs if not os.path.isfile(CERTFILE) or not os.path.isfile(KEYFILE): # NOTE: This [genert] will create certificates matching # the file names listed in CERTFILE and KEYFILE at the top gencert.gencert(rootDomain) print("Certfile(s) NOT present; new certs created.") else: print("Certfiles Verified Present") # Start a thread to run server connection as a daemon def startServer(hostIP, serverPort): # Verify certificates present prior to starting server verifyCerts() # Now, start thread t = threading.Thread(name="ServerDaemon", target=listenNow, args=(hostIP, serverPort, CERTFILE, KEYFILE ) ) t.daemon = True t.start() if __name__ == '__main__': startServer("127.0.0.1", 12345) time.sleep(60) # &lt;--To allow me to connect w/client before closing </code></pre> <p>When I run the above, with NO certificates present, this is the error I receive:</p> <pre><code>$ python3 test.py Certfile(s) NOT present; new certs created. Exception in thread ServerDaemon: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "test.py", line 41, in listenNow server_side=True) File "/usr/lib/python3.5/ssl.py", line 1069, in wrap_socket ciphers=ciphers) File "/usr/lib/python3.5/ssl.py", line 691, in __init__ self._context.load_cert_chain(certfile, keyfile) FileNotFoundError: [Errno 2] No such file or directory </code></pre> <p>When I simply re-run the script a second time (i.e., the cert files are already present when it starts, everything runs as expected with NO errors, and I can connect my client just fine. </p> <pre><code>$ python3 test.py Certfiles Verified Present </code></pre> <p>What is preventing the ssl.wrap_socket function from seeing/accessing the files that were just created (and thus producing the FileNotFoundError exception)? </p> <p>EDIT 1: Thanks for the comments John Gordon. Here is a copy of gencert.py, courtesy of Atul Varm, found here <a href="https://gist.github.com/toolness/3073310" rel="nofollow">https://gist.github.com/toolness/3073310</a></p> <pre><code>import os import sys import hashlib import subprocess import datetime OPENSSL_CONFIG_TEMPLATE = """ prompt = no distinguished_name = req_distinguished_name req_extensions = v3_req [ req_distinguished_name ] C = US ST = IL L = Chicago O = Toolness OU = Experimental Software Authority CN = %(domain)s emailAddress = [email protected] [ v3_req ] # Extensions to add to a certificate request basicConstraints = CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment subjectAltName = @alt_names [ alt_names ] DNS.1 = %(domain)s DNS.2 = *.%(domain)s """ MYDIR = os.path.abspath(os.path.dirname(__file__)) OPENSSL = '/usr/bin/openssl' KEY_SIZE = 1024 DAYS = 3650 CA_CERT = 'ca.cert' CA_KEY = 'ca.key' # Extra X509 args. Consider using e.g. ('-passin', 'pass:blah') if your # CA password is 'blah'. For more information, see: # # http://www.openssl.org/docs/apps/openssl.html#PASS_PHRASE_ARGUMENTS X509_EXTRA_ARGS = () def openssl(*args): cmdline = [OPENSSL] + list(args) subprocess.check_call(cmdline) def gencert(domain, rootdir=MYDIR, keysize=KEY_SIZE, days=DAYS, ca_cert=CA_CERT, ca_key=CA_KEY): def dfile(ext): return os.path.join('domains', '%s.%s' % (domain, ext)) os.chdir(rootdir) if not os.path.exists('domains'): os.mkdir('domains') if not os.path.exists(dfile('key')): openssl('genrsa', '-out', dfile('key'), str(keysize)) # EDIT 3: mydomain.key gets output here during execution config = open(dfile('config'), 'w') config.write(OPENSSL_CONFIG_TEMPLATE % {'domain': domain}) config.close() # EDIT 3: mydomain.config gets output here during execution openssl('req', '-new', '-key', dfile('key'), '-out', dfile('request'), '-config', dfile('config')) # EDIT 3: mydomain.request gets output here during execution openssl('x509', '-req', '-days', str(days), '-in', dfile('request'), '-CA', ca_cert, '-CAkey', ca_key, '-set_serial', '0x%s' % hashlib.md5(domain + str(datetime.datetime.now())).hexdigest(), '-out', dfile('cert'), '-extensions', 'v3_req', '-extfile', dfile('config'), *X509_EXTRA_ARGS) # EDIT 3: mydomain.cert gets output here during execution print "Done. The private key is at %s, the cert is at %s, and the " \ "CA cert is at %s." % (dfile('key'), dfile('cert'), ca_cert) if __name__ == "__main__": if len(sys.argv) &lt; 2: print "usage: %s &lt;domain-name&gt;" % sys.argv[0] sys.exit(1) gencert(sys.argv[1]) </code></pre> <p>EDIT 2: Regarding John's comment, <em>"this might mean that those files are being created, but not in the directory [I] expect"</em>: </p> <p>When I have the directory open in another window, I see the files pop up in the <strong>correct</strong> location during execution. In addition, when running the <code>test.py</code> script a second time with no changes, the files are identified as present in the correct (the same) location. This leads me to believe that file location is not the problem. Thanks for the suggestion. I'll keep looking. </p> <p>EDIT 3: I stepped through the gencert.py program, and each of the files are correctly output at the right time during execution. I indicated when exactly they were output within the above file, labeled with "EDIT 3" </p> <p>While gencert is paused awaiting my input (raw_input), I can open/view/edit the mentioned files in another program with no problem. </p> <p>In addition, with the first test.py instance running (paused, waiting for user input, just after mydomain.cert appears), I can run a second instance of test.py in another terminal and it sees/uses the files just fine. </p> <p>Within the first instance, however, if I continue the program it outputs "FileNotFoundError." </p>
0
2016-10-17T17:26:34Z
40,121,138
<p>The problem contained in the above stems from the use of <code>os.chdir(rootdir)</code> as suggested by John; however, the specifics are slightly different than the created files being in the wrong location. The problem is the current working directory (cwd) of the running program being changed by <code>gencert()</code>. Here are the specifics: </p> <ol> <li><p>The program is started with <code>test.py</code>, which calls <code>verifyCerts()</code>. At this point the program is running in the current directory of whichever folder <code>test.py</code> is running inside of. Use <code>os.getcwd()</code> to find the current directory at this point. In this case (as an example), it is running in:</p> <p><code>/home/name/testfolder/</code> </p></li> <li><p>Next, <code>os.path.isfile()</code> looks for the files "certs/mydomain.cert" and "certs/mydomain.key"; based on the file path above [e.g., the cwd], it is looking for the following files:</p> <p><code>/home/name/testfolder/certs/mydomain.cert</code><br> <code>/home/name/testfolder/certs/mydomain.key</code></p></li> <li><p>The above files are not present, so the program executes <code>gencert.gencert(rootDomain)</code> which <strong>correctly</strong> creates both files as expected in the exact locations mentioned above in number 2. </p></li> <li><p><strong>The problem</strong> is indeed the <code>os.chdir()</code> call: When <code>gencert()</code> executes, it uses <code>os.chdir()</code> to change the cwd to "rootdir," which is <code>os.path.abspath(os.path.dirname(__file__))</code>, which is the directory of the current file (gencert.py). Since this file is located a folder deeper, the new cwd becomes: </p> <p><code>/home/name/testfolder/certs/</code></p></li> <li><p>When <code>gencert()</code> finishes execution and the control returns to <code>test.py</code>, the cwd never changes again; the cwd remains as <code>/home/name/testfolder/certs/</code> even when execution returns to <code>test.py</code>.</p></li> <li><p>Later, when <code>ssl.wrap_socket()</code> tries to find the serverCert and serverKey, it looks for "certs/mydomain.cert" and "certs/mydomain.key" <strong>in the cwd</strong>, so here is the full path of what it is looking for:</p> <p><code>/home/name/testfolder/certs/certs/mydomain.cert</code> <code>/home/name/testfolder/certs/certs/mydomain.key</code> </p></li> <li><p>These two files are <strong>NOT</strong> present, so the program correctly returns "FileNotFoundError".</p></li> </ol> <p><strong>Solution</strong></p> <p>A) Move the "gencert.py" file to the same directory as "test.py"</p> <p>B) At the beginning of "gencert.py" add <code>cwd = os.getcwd()</code> to record the original cwd of the program; then, at the very end, add <code>os.chdir(cwd)</code> to change back to the original cwd before ending and giving control back to the calling program. </p> <p>I went with option 'B', and my program now works flawlessly. I appreciate the assistance from John Gordon to point me toward finding the source of my problem.</p>
0
2016-10-19T02:34:58Z
[ "python", "file-not-found" ]
Creating a matplotlib or seaborn histogram which uses percent rather than count?
40,092,294
<p>Specifically I'm dealing with the Kaggle Titanic dataset. I've plotted a stacked histogram which shows ages that survived and died upon the titanic. Code below.</p> <pre><code>figure = plt.figure(figsize=(15,8)) plt.hist([data[data['Survived']==1]['Age'], data[data['Survived']==0]['Age']], stacked=True, bins=30, label=['Survived','Dead']) plt.xlabel('Age') plt.ylabel('Number of passengers') plt.legend() </code></pre> <p>I would like to alter the chart to show a single chart per bin of the percentage in that age group that survived. E.g. if a bin contained the ages between 10-20 years of age and 60% of people aboard the titanic in that age group survived, then the height would line up 60% along the y-axis.</p> <p>Edit: I may have given a poor explanation to what I'm looking for. Rather than alter the y-axis values, I'm looking to change the actual shape of the bars based on the percentage that survived.</p> <p>The first bin on the graph shows roughly 65% survived in that age group. I would like this bin to line up against the y-axis at 65%. The following bins look to be 90%, 50%, 10% respectively, and so on.</p> <p><a href="https://i.stack.imgur.com/5OQiQ.png" rel="nofollow"><img src="https://i.stack.imgur.com/5OQiQ.png" alt=""></a></p> <p>The graph would end up actually looking something like this:</p> <p><a href="https://i.stack.imgur.com/qVQI3.png" rel="nofollow"><img src="https://i.stack.imgur.com/qVQI3.png" alt="enter image description here"></a></p>
2
2016-10-17T17:26:37Z
40,092,428
<p><code>pd.Series.hist</code> uses <code>np.histogram</code> underneath.</p> <p>Let's explore that</p> <pre><code>np.random.seed([3,1415]) s = pd.Series(np.random.randn(100)) d = np.histogram(s, normed=True) print('\nthese are the normalized counts\n') print(d[0]) print('\nthese are the bin values, or average of the bin edges\n') print(d[1]) these are the normalized counts [ 0.11552497 0.18483996 0.06931498 0.32346993 0.39278491 0.36967992 0.32346993 0.25415494 0.25415494 0.02310499] these are the bin edges [-2.25905503 -1.82624818 -1.39344133 -0.96063448 -0.52782764 -0.09502079 0.33778606 0.77059291 1.20339976 1.6362066 2.06901345] </code></pre> <p>We can plot these while calculating the mean bin edges</p> <pre><code>pd.Series(d[0], pd.Series(d[1]).rolling(2).mean().dropna().round(2).values).plot.bar() </code></pre> <p><a href="https://i.stack.imgur.com/fZxSi.png" rel="nofollow"><img src="https://i.stack.imgur.com/fZxSi.png" alt="enter image description here"></a></p> <p><strong><em>ACTUAL ANSWER</em></strong><br> OR</p> <p>We could have simply passed <code>normed=True</code> to the <code>pd.Series.hist</code> method. Which passes it along to <code>np.histogram</code></p> <pre><code>s.hist(normed=True) </code></pre> <p><a href="https://i.stack.imgur.com/aypHc.png" rel="nofollow"><img src="https://i.stack.imgur.com/aypHc.png" alt="enter image description here"></a></p>
2
2016-10-17T17:35:30Z
[ "python", "pandas", "matplotlib", "dataset", "histogram" ]
Creating a matplotlib or seaborn histogram which uses percent rather than count?
40,092,294
<p>Specifically I'm dealing with the Kaggle Titanic dataset. I've plotted a stacked histogram which shows ages that survived and died upon the titanic. Code below.</p> <pre><code>figure = plt.figure(figsize=(15,8)) plt.hist([data[data['Survived']==1]['Age'], data[data['Survived']==0]['Age']], stacked=True, bins=30, label=['Survived','Dead']) plt.xlabel('Age') plt.ylabel('Number of passengers') plt.legend() </code></pre> <p>I would like to alter the chart to show a single chart per bin of the percentage in that age group that survived. E.g. if a bin contained the ages between 10-20 years of age and 60% of people aboard the titanic in that age group survived, then the height would line up 60% along the y-axis.</p> <p>Edit: I may have given a poor explanation to what I'm looking for. Rather than alter the y-axis values, I'm looking to change the actual shape of the bars based on the percentage that survived.</p> <p>The first bin on the graph shows roughly 65% survived in that age group. I would like this bin to line up against the y-axis at 65%. The following bins look to be 90%, 50%, 10% respectively, and so on.</p> <p><a href="https://i.stack.imgur.com/5OQiQ.png" rel="nofollow"><img src="https://i.stack.imgur.com/5OQiQ.png" alt=""></a></p> <p>The graph would end up actually looking something like this:</p> <p><a href="https://i.stack.imgur.com/qVQI3.png" rel="nofollow"><img src="https://i.stack.imgur.com/qVQI3.png" alt="enter image description here"></a></p>
2
2016-10-17T17:26:37Z
40,101,292
<p>First of all it would be better if you create a function that splits your data in age groups</p> <pre><code># This function splits our data frame in predifined age groups def cutDF(df): return pd.cut( df,[0, 10, 20, 30, 40, 50, 60, 70, 80], labels=['0-10', '11-20', '21-30', '31-40', '41-50', '51-60', '61-70', '71-80']) data['AgeGroup'] = data[['Age']].apply(cutDF) </code></pre> <p>Then you can plot your graph as follows:</p> <pre><code>survival_per_age_group = data.groupby('AgeGroup')['Survived'].mean() # Creating the plot that will show survival % per age group and gender ax = survival_per_age_group.plot(kind='bar', color='green') ax.set_title("Survivors by Age Group", fontsize=14, fontweight='bold') ax.set_xlabel("Age Groups") ax.set_ylabel("Percentage") ax.tick_params(axis='x', top='off') ax.tick_params(axis='y', right='off') plt.xticks(rotation='horizontal') # Importing the relevant fuction to format the y axis from matplotlib.ticker import FuncFormatter ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: '{:.0%}'.format(y))) plt.show() </code></pre>
0
2016-10-18T06:45:07Z
[ "python", "pandas", "matplotlib", "dataset", "histogram" ]
Im trying to write a program that reverses the order of values in an input file using a stack and saves the result to a file
40,092,295
<pre><code>def main(): fname = input("Please input file name: ") # open input file fin = open(fname, "r") # open output file fout = open("output.txt", "w") for line in fin: token = Stack() if token: token.pop() fout.write(items) fout.write("\n") fin.close() fout.close() </code></pre> <p>Assuming the input file contains a single value per line. My error message reads: pop from empty list Im sure my problem is not getting the values from the input file and putting them in to a stack.</p>
-6
2016-10-17T17:26:37Z
40,093,000
<p>Instead of <code>if token:</code> try using <code>if !token.isEmpty():</code></p>
0
2016-10-17T18:11:55Z
[ "python", "python-3.x" ]
Python - Making text files
40,092,304
<p>I seem to be having various problems with my code. Firstly I cannot split the text that the user inputs. </p> <p>E.g. if they type <code>bob</code> for their name, <code>ha8 9qy</code> for their postcode and <code>17/03/10</code> for their date of birth, the program will return <code>"bobha8 9qy17/03/10"</code>. </p> <p>How should I separate the input? Secondly i cannot find the text file I supposedly make. Lastly, is there a way to return the information to the new display window created by Tkinter?</p> <pre><code>import tkinter as kt name=input("Enter your name") postcode=input("Enter your postcode") dob=input("Enter your date of birth") window=kt.Tk() window.title("File") window.geometry("300x150") def submit(): pythonfile = open("User details","w") pythonfile.write((name)) pythonfile.write((postcode)) pythonfile.write((dob)) pythonfile = open(("User details"),"r") print (pythonfile.read()) pythonfile.close() Btn = kt.Button(window, text="Submit", command=submit) Btn.pack() </code></pre>
-1
2016-10-17T17:27:19Z
40,140,759
<p>You have to add the <code>.txt</code> afther the filename. Also be sure that the file is in the same folder of the <code>.py</code> file. Pay attention to caps and spaces.</p> <p><code>pythonfile = open("User details.txt","w")</code></p> <p>If this does'nt work, try adding <code>os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))</code> afther the import, for me it fixed the problem.</p> <p>For the "spacing problem" try:</p> <p><code>pythonfile.write(name, '\n', postcode, '\n', dob)</code></p> <p>Also, when you create a alias for Tkinter use tk, and when you open a file try naming it file_it, or f_in, so it's more readable for other people ... When naming files don't use spaces, it's just going to make everything harder, try naming it like this: <code>userDetails.txt</code> or <code>user_details.txt</code></p>
0
2016-10-19T20:17:13Z
[ "python", "tkinter" ]
Python Tkinter Canvas Many create_window() Items Not Scrolling with Scrollbar
40,092,309
<p>Why doesn't the scrollbar initiate when <code>create_window</code> frame objects start to exceed the bottom <code>self.container</code> window?</p> <p>My understanding is that widgets are scrollable if they are embedded on the canvas using <code>create_window</code>. For context, I don't want to create a scrolling frame - put all your widget in a frame, use <code>create_window</code> to add that frame to the canvas - because I intend to move these frame objects around on the canvas and leverage a lot of canvas capabilities. According to <a href="http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.create_window-method" rel="nofollow">Effbot</a>, <em>You cannot draw other canvas items on top of a widget.</em>, so if I had a scrolling frame, I wouldn't be able to put widgets on top of that.</p> <p>So how do I scroll the canvas that contains many <code>create_window</code> objects, or, what am I doing wrong below?</p> <pre><code>import tkinter as tk class Canvas_Scrollbar_CreateWindow(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) self.parent = parent self.parent.columnconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.block_count = 0 self.button = tk.Button(self, text='Add', command=self.addblock) self.button.grid(row=0, column=0, columnspan=2, sticky='new') self.container = tk.Frame(self) self.container.grid(row=1, column=0, sticky='nsew') self.canvas = tk.Canvas(self.container, width=200, height=450) self.scrollbar = tk.Scrollbar(self.container, orient='vertical',command=self.canvas.yview) self.canvas.config(yscrollcommand=self.scrollbar.set) self.canvas.grid(row=0, column=0, sticky='nsew') self.scrollbar.grid(row=0, column=1, sticky='nse') self.container.bind('&lt;Configure&gt;', self.handle_scroll) def addblock(self): self.block = tk.Frame(self.canvas, bd=1, relief='solid') self.block.columnconfigure(0, weight=1) self.canvas.create_window((0, (self.block_count*25)), window=self.block, anchor="nw", width=200, height=24) self.block_count += 1 def handle_scroll(self, event): self.canvas.configure(scrollregion=self.canvas.bbox("all")) root = tk.Tk() app = Canvas_Scrollbar_CreateWindow(root) app.grid(row=0, column=0, sticky='ew') root.mainloop() </code></pre> <p><a href="https://i.stack.imgur.com/csTJE.png" rel="nofollow"><img src="https://i.stack.imgur.com/csTJE.png" alt="tkinter create_window scrollbar"></a></p>
0
2016-10-17T17:27:32Z
40,093,373
<p>You must re-configure <code>scrollregion</code> when you add items to the canvas.</p>
0
2016-10-17T18:36:17Z
[ "python", "tkinter", "scrollbar", "tkinter-canvas" ]
Updating transformer parameters after grid search on Pipeline
40,092,437
<p>I have a simple Pipeline for text analysis and classification consisting of a CountVectorizer, a TfidfTransformer, and finally a Multinomial Naive Bayes classifier. </p> <pre><code>from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import Pipeline text_clf = Pipeline([('vect', CountVectorizer()), ('tfidf', TfidfTransformer()), ('clf', MultinomialNB())]) </code></pre> <p>I now determine the best parameters using GridSearchCV (stop_words contains a previously loaded list of stop words):</p> <pre><code>from sklearn.model_selection import GridSearchCV parameters = {'vect__ngram_range': [(1,1), (1,2), (1,3)], 'vect__stop_words': [None, stop_words], 'tfidf__use_idf': [True, False], 'clf__alpha': np.arange(0.0, 1.05, 0.05) } grid_clf = GridSearchCV(text_clf, parameters, n_jobs = 1) _ = grid_clf.fit(X_train, y_train) </code></pre> <p>I can now see the best parameters of the model using <code>grid_clf.best_params_</code>:</p> <pre><code>{'clf__alpha': 0.050000000000000003, 'tfidf__use_idf': True, 'vect__ngram_range': (1, 3), 'vect__stop_words': None} </code></pre> <p>My question is: how can I get back an updated pipeline with the best parameters returned by grid search? I would like to be able to call the first two steps of the pipeline (CountVectorizer and TfidfTransformer) with the appropriate parameters.</p> <p>One workaround I have found is explicitly creating a new pipeline with the best parameters returned by grid search:</p> <pre><code>multinomial_clf = Pipeline([('vect', CountVectorizer(stop_words=None, ngram_range=(1,3))), ('tfidf', TfidfTransformer(use_idf = True)), ('clf', MultinomialNB(alpha=0.05))]) _ = multinomial_clf.fit(X_train, y_train) </code></pre> <p>I can now access the CountVectorizer and TfidfTransformer using <code>multinomial_clf.steps</code> but I am sure there must be an easier way.</p> <p>Thanks a lot for your help!</p>
0
2016-10-17T17:36:01Z
40,096,149
<p>The Pipeline with the best parameters can be found with <code>grid_clf.best_estimator_</code></p> <pre><code>grid_clf.best_estimator_ Pipeline(steps=[('vect', CountVectorizer(analyzer='word', binary=False, decode_error='strict', dtype=&lt;class 'numpy.int64'&gt;, encoding='utf-8', input='content', lowercase=True, max_df=1.0, max_features=None, min_df=1, ngram_range=(1, 3), preprocessor=None, stop_words=None, strip...near_tf=False, use_idf=True)), ('clf', MultinomialNB(alpha=0.02, class_prior=None, fit_prior=True))]) </code></pre> <p>However I am still confused as to how to transform using the transformers of the pipeline. The first two steps implement transform methods, whereas the last step does not. But if I try to call:</p> <pre><code>grid_clf.best_estimator_.transform(['ok computer']) </code></pre> <p>I get the following error:</p> <pre><code>AttributeError: 'MultinomialNB' object has no attribute 'transform' </code></pre> <p>Thanks for your help</p>
0
2016-10-17T21:42:00Z
[ "python", "scikit-learn", "pipeline", "grid-search" ]
What is the fastest way to get all pairwise combinations in an array in python?
40,092,474
<p>For example, if the array is [1,2,3,4] I want the output to be [1,2],[1,3],[1,4],[2,3],[2,4],[3,4] I want a solution which is better than the brute force method of using two for loops.</p>
0
2016-10-17T17:38:06Z
40,092,500
<pre><code>import itertools x = [1,2,3,4] for each in itertools.permutations(x,2): print(each) </code></pre> <p>Note that itertools is a generator object, meaning you need to iterate through it to get all you want. The '2' is optional, but it tells the function whats the number per combonation you want. </p> <p><a href="https://docs.python.org/3/library/itertools.html#itertools.permutations" rel="nofollow">You can read more here</a></p> <p>Edited:</p> <p>As ForceBru said in the comment, you can unpack the generator to print, skipping the for loop together But I would still iterate through it as you might not know how big the generated object will be:</p> <pre><code>print(*itertools.permutations(x, 2)) </code></pre>
4
2016-10-17T17:39:21Z
[ "python", "arrays" ]
What is the fastest way to get all pairwise combinations in an array in python?
40,092,474
<p>For example, if the array is [1,2,3,4] I want the output to be [1,2],[1,3],[1,4],[2,3],[2,4],[3,4] I want a solution which is better than the brute force method of using two for loops.</p>
0
2016-10-17T17:38:06Z
40,092,582
<p>Though the previous answer will give you all pairwise orderings, the example expected result seems to imply that you want all <em>unordered</em> pairs. </p> <p>This can be done with <code>itertools.combinations</code>:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; x = [1,2,3,4] &gt;&gt;&gt; list(itertools.combinations(x, 2)) [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] </code></pre> <p>Compare to the other result:</p> <pre><code>&gt;&gt;&gt; list(itertools.permutations(x, 2)) [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)] </code></pre>
3
2016-10-17T17:44:49Z
[ "python", "arrays" ]
Maintaining Data Associations in a Dictionary with Multiple Lines per Key
40,092,497
<p>I have a data set from a baseball team that I want to analyze in one of my first Python programming experiences (coming from C++). However, the dataset has a more complex structure than my previous simple examples that I'd like to know the best (most pythonic) way to capture. The main difficulty is that the each player can have multiple seasons, and I'd like all of those to be tied to the same key (the player's ID number) but to maintain their correlations with the seasons. An example player set in the database looks like:</p> <pre><code>ID year AB H 2B 3B HR JimBob01 2009 100 27 3 1 1 JimBob01 2010 154 37 6 2 5 JimBob01 2011 123 36 8 0 3 </code></pre> <p>I searched around SO and found that a dictionary is the way to go, since I have a hashable key name system. And it looks like I might want a list for each element in the dictionary? However, I'd like to be able to do something like:</p> <pre><code>print dict['JimBob01'][2009] </code></pre> <p>To see only the stats from 2009, as well as something like:</p> <pre><code>for year in dict['JimBob01']: total_ab += year['AB']` </code></pre> <p>and I think a list will not give me that flexibility. I apologize if this is an overly simplistic question, I'm trying to adapt to the data structures available in Python.</p>
0
2016-10-17T17:39:13Z
40,092,690
<p>Seems like you want a dictionary of dictionaries. Something like:</p> <pre><code>playerData = { 'JimBob01': { '2009': ... // player data here '2010': ... } } </code></pre> <p>You can then look up the data for a particular year as you want by doing <code>playerData['JimBob01']['2009']</code></p> <p>Depending on the size of your dataset and how often you need to run analysis, you might also want to look into a Sqlite database.</p>
1
2016-10-17T17:52:02Z
[ "python", "dictionary" ]
Unsupported operand type(s) for %: 'NoneType' and 'tuple'
40,092,556
<p>I am getting this error:</p> <blockquote> <p>TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'</p> </blockquote> <p>What do I need to change to fix this?</p> <pre><code>string_1 = "Sean"; string_2 = "beginner programmer"; print("Hi my name is %s, I\'m a %s.") % (string_1,string_2); </code></pre>
0
2016-10-17T17:43:23Z
40,092,584
<p><code>print</code> returns <code>None</code>, you must format the string <em>before</em> printing it</p> <pre><code>print("Hi my name is %s, I\'m a %s." % (string_1, string_2)) </code></pre>
3
2016-10-17T17:44:54Z
[ "python" ]
Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?
40,092,570
<p>so I'm on Python 3.5.2, I'm trying to install scrapy, it throws an error saying</p> <blockquote> <p>Failed building wheel for lxml <br> Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?</p> </blockquote> <p>So I try installing lxml, it throws the same error. I try installing it from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml" rel="nofollow">Here</a>, it says:</p> <blockquote> <p>Could not find a version that satisfies the requirement lxml-3.6.4-cp35-cp35m-win32 (from versions: ) No matching distribution found for lxml-3.6.4-cp35-cp35m-win32</p> </blockquote> <p>I can install almost nothing with pip. I'm on a Windows 10 machine. Note that it works flawlessly on my ubunto machine.</p>
1
2016-10-17T17:44:12Z
40,093,274
<p>try this first</p> <p>pip install lxml==3.6.0</p>
0
2016-10-17T18:30:04Z
[ "python", "scrapy" ]
String being mutated to a dictionary but can't figure out where
40,092,681
<p>I'm trying to implement a scrabble type game and the function playHand is returning an AttributeError: 'str' object has no attribute 'copy'. The error comes from updateHand Hand = Hand.copy(), but I've tested updateHand individually and works just fine on its ow. I've tried looking it up, but never really found anything. Apologies for the length! I can't help it. Thanks!</p> <pre><code>VOWELS = 'aeiou' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' HAND_SIZE = 7 SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } def getWordScore(word, n): """ Returns the score for a word. Assumes the word is a valid word. The score for a word is the sum of the points for letters in the word, multiplied by the length of the word, PLUS 50 points if all n letters are used on the first turn. Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES) word: string (lowercase letters) n: integer (HAND_SIZE; i.e., hand size required for additional points) returns: int &gt;= 0 """ score = 0 for letter in word: score += SCRABBLE_LETTER_VALUES[letter] return score * len(word) + 50 * (len(word) == n) def displayHand(hand): """ Displays the letters currently in the hand. For example: &gt;&gt;&gt; displayHand({'a':1, 'x':2, 'l':3, 'e':1}) Should print out something like: a x x l l l e The order of the letters is unimportant. hand: dictionary (string -&gt; int) """ for letter in hand.keys(): for j in range(hand[letter]): print(letter,end=" ") # print all on the same line print() # print an empty line def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. Has no side effects: does not modify hand. word: string hand: dictionary (string -&gt; int) returns: dictionary (string -&gt; int) """ Hand = hand.copy() for letter in word: Hand[letter] -= 1 return Hand def isValidWord(word, hand, wordList): """ Returns True if word is in the wordList and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or wordList. word: string hand: dictionary (string -&gt; int) wordList: list of lowercase strings """ Hand = hand.copy() if word not in wordList: return False for letter in word: if letter not in Hand: return(False) break else: Hand[letter] -= 1 if Hand[letter] &lt; 0: return False return True def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string int) returns: integer """ return sum(hand.values()) def printCurrentHand(hand): print('Current Hand: ', end = ' ') displayHand(hand) def printTotalScore(score): print('Total: ' + str(score) + ' points') def updateAndPrintScore(score, word, n): currentScore = getWordScore(word, n) score += currentScore print('" ' + word + ' "' + ' earned ' + str(currentScore) + ' points.', end = ' ') print(printTotalScore(score)) return score def playHand(hand, wordList, n): """ Allows the user to play the given hand, as follows: * The hand is displayed. * The user may input a word or a single period (the string ".") to indicate they're done playing * Invalid words are rejected, and a message is displayed asking the user to choose another word until they enter a valid word or "." * When a valid word is entered, it uses up letters from the hand. * After every valid word: the score for that word is displayed, the remaining letters in the hand are displayed, and the user is asked to input another word. * The sum of the word scores is displayed when the hand finishes. * The hand finishes when there are no more unused letters or the user inputs a "." hand: dictionary (string -&gt; int) wordList: list of lowercase strings n: integer (HAND_SIZE; i.e., hand size required for additional points) """ score = 0# Keep track of the total score hand_copy = hand.copy() while calculateHandlen(hand_copy) &gt; 0: printCurrentHand(hand_copy) word = input("Enter word, or a \".\" to indicate that you are finished: ") if word == '.': print("Goodbye!", end = ' ') break if isValidWord(word, hand_copy, wordList): score += updateAndPrintScore(score, word, n) hand_copy = updateHand(word, hand_copy) else: print('Invalid word!') print() if calculateHandlen(hand_copy) == 0: print("Run out of letters.", end = ' ') printTotalScore(score) playHand({'h':1, 'i':1, 'c':1, 'z':1, 'm':2, 'a':1},['him', 'cam'], 7) </code></pre> <p><em>Error code</em></p> <pre><code>runfile('C:/Users/.spyder2-py3/ProjectsMIT/temp.py', wdir='C:/Users/.spyder2-py3/ProjectsMIT') Current Hand: c a h i m m z Enter word, or a "." to indicate that you are finished: him " him " earned 24 points. Total: 24 points None Traceback (most recent call last): File "&lt;ipython-input-2-2e4e8585ae85&gt;", line 1, in &lt;module&gt; runfile('C:/Users/.spyder2-py3/ProjectsMIT/temp.py', wdir='C:/Users/.spyder2-py3/ProjectsMIT') File "C:\Users\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile execfile(filename, namespace) File "C:\Users\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile exec(compile(f.read(), filename, 'exec'), namespace) line 183, in &lt;module&gt; playHand({'h':1, 'i':1, 'c':1, 'z':1, 'm':2, 'a':1},['him', 'cam'], 7) line 172, in playHand hand_copy = updateHand(word, hand_copy) line 72, in updateHand Hand = hand.copy() AttributeError: 'str' object has no attribute 'copy' </code></pre>
1
2016-10-17T17:51:06Z
40,092,843
<p>Your passed-in arguments to <code>updateHand()</code> are reversed from the expected arguments:</p> <p>line 161:</p> <pre><code>hand_copy = updateHand(word, hand_copy) </code></pre> <p>Line 49:</p> <pre><code>def updateHand(hand, word): </code></pre> <p>Notice that <code>updateHand</code> expects a hand to be the first arg, but you pass a hand as the second arg.</p> <p>The fix is simple. Replace line 161 with:</p> <pre><code>hand_copy = updateHand(hand_copy, word) </code></pre>
2
2016-10-17T18:02:15Z
[ "python", "string", "dictionary", "semantics" ]
Slicing a range of elements in each sublist?
40,092,686
<p>I suspect there are more than one ways to do this in Python 2.7, but I'd like to be able to print the first three elements of each sublist in combos. Is there a way to do this without a loop? </p> <pre><code>combos = [ [1,2,3,.14], [5,6,7,.18], [9,10,11,.12], [1,2,3,.15] ] </code></pre> <p>such that the output of a print statement would read:</p> <pre><code>[ [1,2,3], [5,6,7], [9,10,11], [1,2,3] ] </code></pre> <p>***AFTER GETTING YOUR SUGGESTIONS: I was struggling to see how this would work inside of my code structure but list comprehension can be done as part of an if statement like so, which I failed to recognize:</p> <pre><code>p0combos = [ [1,2,3,.14], [5,6,7,.18], [9,10,11,.12], [1,2,3,.15] ] p0 = [1, 2, 3] if p0 not in [combo[:3] for combo in p0combos]: print combo[:3] print 'p0 not found' else: print 'p0 found' print combo[3:4] </code></pre> <p>The output:</p> <pre><code>p0 found [0.15] </code></pre> <p>Thanks all.</p>
0
2016-10-17T17:51:21Z
40,092,694
<pre><code>[sublist[:3] for sublist in combos] </code></pre>
2
2016-10-17T17:52:23Z
[ "python", "list", "list-comprehension", "slice" ]
Slicing a range of elements in each sublist?
40,092,686
<p>I suspect there are more than one ways to do this in Python 2.7, but I'd like to be able to print the first three elements of each sublist in combos. Is there a way to do this without a loop? </p> <pre><code>combos = [ [1,2,3,.14], [5,6,7,.18], [9,10,11,.12], [1,2,3,.15] ] </code></pre> <p>such that the output of a print statement would read:</p> <pre><code>[ [1,2,3], [5,6,7], [9,10,11], [1,2,3] ] </code></pre> <p>***AFTER GETTING YOUR SUGGESTIONS: I was struggling to see how this would work inside of my code structure but list comprehension can be done as part of an if statement like so, which I failed to recognize:</p> <pre><code>p0combos = [ [1,2,3,.14], [5,6,7,.18], [9,10,11,.12], [1,2,3,.15] ] p0 = [1, 2, 3] if p0 not in [combo[:3] for combo in p0combos]: print combo[:3] print 'p0 not found' else: print 'p0 found' print combo[3:4] </code></pre> <p>The output:</p> <pre><code>p0 found [0.15] </code></pre> <p>Thanks all.</p>
0
2016-10-17T17:51:21Z
40,092,698
<pre><code>print [temp_list[:3] for temp_list in combos] </code></pre>
2
2016-10-17T17:52:39Z
[ "python", "list", "list-comprehension", "slice" ]
Slicing a range of elements in each sublist?
40,092,686
<p>I suspect there are more than one ways to do this in Python 2.7, but I'd like to be able to print the first three elements of each sublist in combos. Is there a way to do this without a loop? </p> <pre><code>combos = [ [1,2,3,.14], [5,6,7,.18], [9,10,11,.12], [1,2,3,.15] ] </code></pre> <p>such that the output of a print statement would read:</p> <pre><code>[ [1,2,3], [5,6,7], [9,10,11], [1,2,3] ] </code></pre> <p>***AFTER GETTING YOUR SUGGESTIONS: I was struggling to see how this would work inside of my code structure but list comprehension can be done as part of an if statement like so, which I failed to recognize:</p> <pre><code>p0combos = [ [1,2,3,.14], [5,6,7,.18], [9,10,11,.12], [1,2,3,.15] ] p0 = [1, 2, 3] if p0 not in [combo[:3] for combo in p0combos]: print combo[:3] print 'p0 not found' else: print 'p0 found' print combo[3:4] </code></pre> <p>The output:</p> <pre><code>p0 found [0.15] </code></pre> <p>Thanks all.</p>
0
2016-10-17T17:51:21Z
40,093,354
<blockquote> <p>I suspect there are more than one ways to do this in Python 2.7</p> </blockquote> <p>Yes and you can be quite creative with it. This is another alternative</p> <pre><code>from operator import itemgetter map(itemgetter(slice(3)), combos) Out[192]: [[1, 2, 3], [5, 6, 7], [9, 10, 11], [1, 2, 3]] </code></pre>
0
2016-10-17T18:35:03Z
[ "python", "list", "list-comprehension", "slice" ]
How I order behavior IDublinCore in Dexterity Type?
40,092,789
<p>I'm writing a product using Python Dexterity Type, and I have <code>Title</code> and <code>Description</code>, this fields come from a behavior <code>plone.app.dexterity.behaviors.metadata.IDublinCore</code>, but I neeed reorder this fields with my fields.</p> <p>Example:</p> <p>My fields: document, collage, age, biography</p> <p>IDublinCore: Title, Description</p> <p>The order: collage, Title, document, age, biography, Description</p> <p>How I Do it?</p>
5
2016-10-17T17:58:45Z
40,110,683
<p>How about using Jquery? (Since the fieldsets are using Jquery anyway)</p> <p>For example to move Tags under Summary....</p> <pre><code>$('body.template-edit.portaltype-document #formfield-form-widgets-IDublinCore-subjects').insertAfter('#formfield-form-widgets-IDublinCore-description') </code></pre> <p>Note: This is a copy of my answer <a href="http://stackoverflow.com/a/31205979/3046069">here</a></p>
-1
2016-10-18T14:16:44Z
[ "python", "plone", "zope", "dexterity", "plone-4.x" ]
How I order behavior IDublinCore in Dexterity Type?
40,092,789
<p>I'm writing a product using Python Dexterity Type, and I have <code>Title</code> and <code>Description</code>, this fields come from a behavior <code>plone.app.dexterity.behaviors.metadata.IDublinCore</code>, but I neeed reorder this fields with my fields.</p> <p>Example:</p> <p>My fields: document, collage, age, biography</p> <p>IDublinCore: Title, Description</p> <p>The order: collage, Title, document, age, biography, Description</p> <p>How I Do it?</p>
5
2016-10-17T17:58:45Z
40,125,462
<p>Since you got your own Dexterity Type you can handle with <code>form directives</code> aka <code>setting taggedValues</code> on the interface.</p> <pre><code>from plone.autoform import directives class IYourSchema(model.Schema): directives.order_before(collage='IDublinCore.title') collage = schema.TextLine( title=u'Collage', ) </code></pre> <p>You find excellent documentation about this feature in the plone documentation <a href="http://docs.plone.org/external/plone.app.dexterity/docs/reference/form-schema-hints.html#appearance-related-directives" rel="nofollow">http://docs.plone.org/external/plone.app.dexterity/docs/reference/form-schema-hints.html#appearance-related-directives</a></p>
3
2016-10-19T08:00:35Z
[ "python", "plone", "zope", "dexterity", "plone-4.x" ]
How to clear dump (AndroidViewClient/Culebra) data from memory?
40,092,797
<p>I'm running an automated test script using AndroidViewClient. I do several dumps in the script. The script is used for a speed/response time test on an android device and the test is run for n>300. I get the following error at run #150.</p> <p><strong>raise ValueError("received does not contain valid XML: " + receivedXml) ValueError: received does not contain valid XML: Killed</strong></p> <p>After some digging and monitoring the memory using "memory_profiler", The dump data seems to be stacking up on the memory and slow down the test and influence the test results. </p> <p>1- Why do I get the error? 2- Where exactly the dump data is stored? 2- How to clear the memory every time I dump?</p>
0
2016-10-17T17:59:09Z
40,099,745
<p>What you describe seems like an issue with <code>uiautomator dump</code> (probably your device implementation) which is what <strong>AndroidViewClient</strong> uses as the default backend for API >= 19.</p> <p>However, to be absolutely sure you should remove AndroidViewClient from the picture and run the same command it is used as the backend.</p> <p><strong>AndroidViewClient 12.0.2</strong> supports some debug options specified in the command line, one it's very useful to determine the command being run.</p> <pre><code>$ dump --debug UI_AUTOMATOR:True &gt; /dev/null </code></pre> <p>this command will print something like</p> <pre><code>executing 'uiautomator dump --compressed /dev/tty &gt;/dev/null' </code></pre> <p>then this is the command you can run repeatedly to determine if the problem is in your device.</p> <p>For example, copying the command printed before you can use <code>bash</code> to run</p> <pre><code>for n in {0..299}; do echo $n; adb shell uiautomator dump --compressed /dev/tty \&gt;/dev/null &gt;/dev/null; done </code></pre> <p>and check if there's a memory leak or something fails on the device.</p> <p>Regarding your question and as you can see from the command, dump data is not stored anywhere and only copied to the socket. There are versions that require the data to be stored locally on the device but in such case the file used is overwritten every time.</p>
1
2016-10-18T04:49:22Z
[ "android", "python", "dump", "androidviewclient" ]
Compute sum of the elements in a chunk of a dask array
40,092,808
<p>I'd like to apply a function to each block and return a single element, for example, from a 10x10 matrix I'd like to sum each 2x2 block.</p> <p>I've tried some combinations of what you see below but I always get an <code>IndexError</code>.</p> <pre><code>m = da.from_array(np.ones((10,10)), chunks=(2,2)) def compute_block_sum(block): return np.array([np.sum(block)]) m.map_blocks(compute_block_sum, chunks=(1,1)).compute() </code></pre>
1
2016-10-17T18:00:01Z
40,092,963
<p>Using the default settings <code>map_blocks</code> assumes that the user-provided function returns a numpy array of the same number of dimensions as the input. So you can get your example above to work by adding in a second empty dimension to your <code>compute_block_sum</code> function using numpy slicing with <code>None</code>.</p> <pre><code>In [1]: import dask.array as da In [2]: import numpy as np In [3]: m = da.from_array(np.ones((10,10)), chunks=(2,2)) In [4]: def compute_block_sum(block): ...: return np.array([np.sum(block)])[:, None] In [5]: m.map_blocks(compute_block_sum, chunks=(1, 1)).compute() Out[5]: array([[ 4., 4., 4., 4., 4.], [ 4., 4., 4., 4., 4.], [ 4., 4., 4., 4., 4.], [ 4., 4., 4., 4., 4.], [ 4., 4., 4., 4., 4.]]) </code></pre>
1
2016-10-17T18:09:02Z
[ "python", "dask" ]
Python Ctypes memory allocation for c function
40,092,818
<p>I currently have a python callback function that calls a c function using ctypes library. The c function requires a pointer to a structure for example animal_info_s. I instantiate the structure and pass it as a pointer to the c function and it works. The issue I'm having is when I have multiple threads calling the callback, I'm finding the information being passed back is mixed up between the threads. </p> <pre><code>class animal_info_s(ctypes.Structure): _fields_ = [('dog_type', ctypes.c_uint16), ('cat_type', ctypes.c_uint16), ('bird_type', ctypes.c_uint16), ('epoch_time', ctypes.c_uint16), ('more_information', ctypes.c_uint16)] _mod = ctypes.cdll.LoadLibrary('bbuintflib.dll') animal_info_s = animal_info_s() get_animal_data = _mod.get_animal_data get_animal_data.argtypes = [ctypes.POINTER(animal_info_s)] get_animal_data.restype = ctypes.c_int # Python Callback def GetAnimalData(): animal_info_p = animal_info_s res = get_animal_data(animal_info_p) if (res != 0): print("Failed to get animal info") return print ("Receive Time - %d\nDog: %d\nCat: %d\nBird:%d" %(animal_info_p.epoch_time, animal_info_p.dog_type, animal_info_p.cat_type, animal_info_p.bird_type)) </code></pre> <p>I think what is happening is when I instantiate the structure, it is using the same memory location every time. How do I create a new memory location for each thread calling the callback?</p>
0
2016-10-17T18:00:46Z
40,098,908
<p>The following line should be removed. It redefines the name <code>animal_info_s</code> as a <code>class animal_info_s</code> instance, which then hides the class.</p> <pre><code>animal_info_s = animal_info_s() </code></pre> <p>The following line should be changed from:</p> <pre><code>animal_info_p = animal_info_s </code></pre> <p>to:</p> <pre><code>animal_info_p = animal_info_s() </code></pre> <p>The original line made another name for the <code>animal_info_s</code> name from the first error, which was the one-and-only instance used in the threads. the recommended line creates a new instance of the <code>animal_info_s</code> class each time the callback is called.</p>
2
2016-10-18T03:12:32Z
[ "python", "memory-management", "ctypes" ]
How do I make the combobox update?
40,092,890
<pre><code># IMPORT MODULES ----------------------------------------------------------- from tkinter import * from tkinter import Tk, StringVar, ttk #--------------------------------------------------------------------------- # LISTS </code></pre> <p><strong>Here are the lists which are used in the comboboxes</strong></p> <pre><code>BlankLines = ["------------"] CarBrandModel = ["------------","Audi", "BMW", "Mercedes"] AudiModels = ["------------", "A4", "A8", "Q7", "R8"] #---------------------------------------------------------------------------------- #FUNCTIONS def ModelSelectionFunction(): CarBrandModelSelected = Var1.get() print(CarBrandModelSelected) </code></pre> <p><strong>Here it gets the value from the combobox, but my problem is that it does not update when I select something else from the combobox</strong></p> <pre><code> if CarBrandModelSelected == "------------": CarModelBox["value"] = BlankLines CarModelBox.current(0) elif CarBrandModelSelected == "Audi": CarModelBox["value"] = AudiModels CarModelBox.current(0) # SET SCREEN --------------------------------------------------------------- root = Tk() root.geometry("1350x750") root.title("Car Showroom System") root.configure(bg="white") #-------------------------------------------------------------------------- # VAR Var1 = StringVar() Var2 = StringVar() </code></pre> <p><strong>Here the string variable are stored</strong></p> <p>#---------------------------------------------------------------------------</p> <pre><code># SELECTION SelectionFrame.grid_propagate(False) CarBrand = Label(SelectionFrame, text="Car :") CarBrand.grid(row=0, column=0) CarBrandBox = ttk.Combobox(SelectionFrame, textvariable=Var1, state="readonly") CarBrandBox.bind("&lt;&lt;ComboboxSelected&gt;&gt;") CarBrandBox["value"] = CarBrandModel CarBrandBox.current(0) CarBrandBox.grid(row=0, column=1) CarModel = Label(SelectionFrame, text="Model :") CarModel.grid(row=1, column=0) CarModelBox = ttk.Combobox(SelectionFrame, textvariable=Var2, state="readonly") CarModelBox.grid(row=1, column=1) ModelSelectionFunction() </code></pre> <p><strong>This calls the function in order to decide what to put into the combobox</strong></p> <pre><code> root.mainloop() </code></pre>
0
2016-10-17T18:04:35Z
40,100,458
<p>You have to add function name to bind</p> <pre><code>CarBrandBox.bind("&lt;&lt;ComboboxSelected&gt;&gt;", ModelSelectionFunction) </code></pre> <p>and tkinter executes it when you select in combobox.</p> <p>Because <code>tkinter</code> sends extra argument to binded function so you need to receive it in your function. I add <code>=None</code> so you can still execute it without arguments. </p> <pre><code>def ModelSelectionFunction(event=None) </code></pre> <hr> <p>BTW: this argument can give you selected value</p> <pre><code>if event: print(event.widget.get()) </code></pre>
0
2016-10-18T05:47:49Z
[ "python", "python-3.x", "user-interface", "tkinter", "combobox" ]
Adding a column which increment for every index which meets a criteria on another column
40,092,894
<p>I am trying to generate a column from a DataFrame to base my grouping on. I know that every NaN column under a non NaN one belong to the same group. So I wrote this loop (cf below) but I was wondering if there was a more pandas/pythonic way to write it with apply or a comprehension list.</p> <pre><code>import pandas &gt;&gt;&gt; DF = pandas.DataFrame([134, None, None, None, 129374, None, None, 12, None], columns=['Val']) &gt;&gt;&gt; a = [0] &gt;&gt;&gt; for i in DF['Val']: if i &gt; 1: a.append(a[-1] + 1) else: a.append(a[-1]) &gt;&gt;&gt; a.pop(0) # remove 1st 0 which does not correspond to any rows &gt;&gt;&gt; DF['Group'] = a &gt;&gt;&gt; DF Val Group 0 134.0 1 1 NaN 1 2 NaN 1 3 NaN 1 4 129374.0 2 5 NaN 2 6 NaN 2 7 12.0 3 8 NaN 3 </code></pre>
0
2016-10-17T18:04:49Z
40,092,932
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.notnull.html" rel="nofollow"><code>pd.notnull</code></a> to identify non-NaN values. Then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.cumsum.html" rel="nofollow"><code>cumsum</code></a> to create the <code>Group</code> column:</p> <pre><code>import pandas as pd df = pd.DataFrame([134, None, None, None, 129374, None, None, 12, None], columns=['Val']) df['Group'] = pd.notnull(df['Val']).cumsum() print(df) </code></pre> <p>yields</p> <pre><code> Val Group 0 134.0 1 1 NaN 1 2 NaN 1 3 NaN 1 4 129374.0 2 5 NaN 2 6 NaN 2 7 12.0 3 8 NaN 3 </code></pre>
2
2016-10-17T18:07:17Z
[ "python", "pandas" ]
AH00112: Warning - Centos 6 / Apache 2.4 / Django 1.9 / mod_wsgi 3.5 / python 2.7
40,092,913
<p>I have a dedicated server with GoDaddy. I seem to have successfully set up everything properly but I can't seem to figure out why I'm getting this issue:</p> <p>When I restart apache:</p> <pre><code>[root@sXXX-XXX-XXX-XXX /]# /scripts/restartsrv httpd </code></pre> <p>I get this:</p> <pre><code>AH00112: Warning: DocumentRoot [/usr/local/apache/var/www/&lt;my_django_project&gt;] does not exist AH00112: Warning: DocumentRoot [/usr/local/apache/var/www/&lt;my_django_project&gt;] does not exist AH00112: Warning: DocumentRoot [/usr/local/apache/var/www/&lt;my_django_project&gt;] does not exist </code></pre> <p>I never specified a path of <code>/usr/local/apache/var/www/&lt;my_django_project&gt;</code> ???</p> <p>It seems to just append my <code>var/www/&lt;my_django_project&gt;</code> to <code>/usr/local/apache</code> ... not sure why</p> <p>My httpd.conf file:</p> <pre><code>... a bunch of pre configured goDaddy stuff I'm guessing here ... LoadModule wsgi_module /usr/local/apache/extramodules/mod_wsgi.so AddHandler wsgi-script .wsgi &lt;VirtualHost XXX.XXX.XXX.X:80&gt; ServerName XXX.XXX.XXX.XXX ErrorLog /var/log/httpd/error.log # DocumentRoot /public_html/ ServerAdmin [email protected] Alias /favicon.ico /var/www/&lt;my_django_project&gt;/static/favicon.ico Alias /static /var/www/&lt;my_django_project&gt;/static &lt;Directory /var/www/&lt;my_django_project&gt;/static&gt; Require all granted &lt;/Directory&gt; Alias /media /var/www/&lt;my_django_project&gt;/media &lt;Directory /var/www/&lt;my_django_project&gt;/media&gt; Require all granted &lt;/Directory&gt; WSGIDaemonProcess &lt;my_django_project&gt; python-path= /var/www/&lt;my_django_project&gt;:/var/www/&lt;my_django_project&gt;/&lt;my_django_project&gt;:/var/www/&lt;my_django_project&gt;/&lt;my_django_project_site&gt;:/usr/local/lib/python2.7/site-packages WSGIProcessGroup &lt;my_django_project&gt; WSGIScriptAlias / /var/www/&lt;my_django_project&gt;/&lt;my_django_project&gt;/wsgi.py &lt;Directory /var/www/&lt;my_django_project&gt;/&lt;my_django_project&gt;&gt; &lt;Files wsgi.py&gt; Require all granted &lt;/Files&gt; &lt;/Directory&gt; &lt;/VirtualHost&gt; ... more stuff already in the conf file ... </code></pre> <p>When I go to <code>XXX-XXX-XXX-XXX:80</code> in my internet browser it told me it can't find .htaccess file. But now it's just redirecting me to <a href="http://XXX.XXX.XXX.XXX/cgi-sys/defaultwebpage.cgi" rel="nofollow">http://XXX.XXX.XXX.XXX/cgi-sys/defaultwebpage.cgi</a></p> <p>Any help would be much appreciated</p> <p>EDIT:</p> <p>It was pointed out that <code>AH00112: Warning: DocumentRoot [/usr/local/apache/var/www/&lt;my_django_project&gt;] does not exist</code> was due to not adding <code>/</code> in front of path.</p> <p>My browser now gives me:</p> <pre><code>Forbidden You don't have permission to access / on this server. Server unable to read htaccess file, denying access to be safe Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request. </code></pre>
0
2016-10-17T18:06:04Z
40,094,703
<p>This would indicate you have set <code>DocumentRoot</code> directive somewhere in your Apache configuration files to a path that does not have a leading slash. When that occurs Apache will append the path to the end of the <code>ServerRoot</code> directory which in your case is <code>/usr/local/apache</code>. Make sure that all your file system paths you set up are absolute path names with leading slash.</p>
0
2016-10-17T20:01:59Z
[ "python", "django", "apache", "python-2.7", "mod-wsgi" ]
Error when converting string to date object from command line in Python
40,093,046
<p>When I run the following code, I don't see any problems:</p> <pre><code>as_of_date = '10-16-17' today = datetime.datetime.strptime(as_of_date, '%m-%d-%y').date() type(today) print(today) Out: datetime.date Out: 2017-10-16 </code></pre> <p>However, when I run a script named <code>GetStats.py</code> that takes several arguments from the command line, I get an error.</p> <p>The command line consists of 5 arguments and looks as follows:</p> <pre><code>python GetStats.py Client_A.cfg 30 -d 10-16-17 </code></pre> <p>The last argument ("10-16-17") on the command line represents a date.</p> <p>The code in the GetStats.py script is as follows:</p> <pre><code>import sys from datetime import datetime, timedelta, time, date as_of_date = sys.argv[4] today = datetime.datetime.strptime(as_of_date, '%m-%d-%y').date() print (today) </code></pre> <p>The code doesn't hit the print statement and instead shows the following error:</p> <pre><code>type 'exceptions.AttributeError' </code></pre> <p>Does anyone see the mistake when I try to pass that date from the command line?</p> <p>Thanks!</p>
-1
2016-10-17T18:15:31Z
40,093,150
<p>The problem is with your import:</p> <p><code>from datetime import datetime</code> and then you try to call <code>datatime.datetime.strptime</code></p> <p>By doing this, you're trying to call the function <code>datetime.datetime.datetime.strptime</code> which doesn't exist.</p> <p>Therefore, to fix this change <code>datetime.datetime</code> to simply <code>datetime</code> in your code.</p>
2
2016-10-17T18:22:06Z
[ "python", "datetime" ]
How to write sumation in IBM CPLEX Python API
40,093,162
<p>I am new to Cplex Python APIs, but I worked with Cplex OPL, in OPL, you can easily write this objective function Max [sum C_ij*X_ij] as:</p> <p>Maximize sum(i in set1,j in set2) C_ij*X_ij</p> <p>if we want to use python API, we have to define it in vector format Max C*X, which C and X are both vectors of coefficients and variables respectively. So you need to make the vector format from C_ij matrix.</p> <p>Is there any way to write it in matrix format like what we do in OPL?</p>
0
2016-10-17T18:22:47Z
40,094,014
<p>The <a href="http://www.ibm.com/support/knowledgecenter/SSSA5P_12.6.3/ilog.odms.cplex.help/refpythoncplex/html/help.html?pos=2" rel="nofollow">CPLEX Python API</a> does not support this, but the <a href="https://developer.ibm.com/docloud/documentation/optimization-modeling/modeling-for-python/" rel="nofollow">DOcplex Modeling for Python API</a> is similar to OPL. For a quick start to the later see the <a href="https://cdn.rawgit.com/IBMDecisionOptimization/docplex-doc/master/docs/mp/creating_model.html" rel="nofollow">Creating a MP model in a nutshell</a> page, and <a href="https://cdn.rawgit.com/IBMDecisionOptimization/docplex-doc/master/docs/mp/docplex.mp.model.html#docplex.mp.model.Model.sum" rel="nofollow">Model.sum</a> in the reference manual.</p>
0
2016-10-17T19:17:00Z
[ "python", "cplex" ]
Updating missing letters in hangman game
40,093,203
<p>I'm making a hangman game and have found a problem with my methodology for updating the answer. I have a variable that adds underscores equal to the amount of letters in the word the player needs to guess. However I can't figure out how to effectively update that when the player guesses a correct letter.</p> <p>Here is my code</p> <pre><code>import random ''' HANGMAN IMAGE print(" _________ ") print("| | ") print("| 0 ") print("| /|\\ ") print("| / \\ ") print("| ") print("| ") ''' def game(): print('''Welcome to hangman, you must guess letters to fill in the word. Incorrect guesses will use up a turn, you have 7 turns before you lose.''') lines = open("wordBank.txt").read() line = lines[0:] words = line.split() myword = random.choice(words).lower() letters = len(myword) print("Your word has " + str(letters) + " letters.") underscores = "" for x in range(0, letters): underscores += "_ " print(underscores) print(myword) l = set(myword) turn = 0 guesses = [] def guess(): thisGuess = input("Type a letter and press Enter(Return) to guess: ") if thisGuess.lower() in l: else: print("Boo") guess() game() </code></pre>
0
2016-10-17T18:25:09Z
40,093,261
<p>You probably need to reword your question as it's not clear what you are asking. But you should look into string splicing. If they guessed the letter "a" and it goes in the third slot then you could do something like</p> <pre><code>underscores[:2] + 'a' + underscores[3:] </code></pre> <p>adapt for your code but that would replace the 3rd underscore with an "a".</p> <p>UPDATE: don't use a set, look up the index as you go. Try something like this</p> <pre><code>for index, letter in enumerate(my_word): if letter == guessed_letter: if not index == len(my_word) -1 underscores = underscores[:index] + letter + underscores[index+1:] else: underscores = undescores[:-1] + letter </code></pre>
2
2016-10-17T18:29:20Z
[ "python", "set" ]
Updating missing letters in hangman game
40,093,203
<p>I'm making a hangman game and have found a problem with my methodology for updating the answer. I have a variable that adds underscores equal to the amount of letters in the word the player needs to guess. However I can't figure out how to effectively update that when the player guesses a correct letter.</p> <p>Here is my code</p> <pre><code>import random ''' HANGMAN IMAGE print(" _________ ") print("| | ") print("| 0 ") print("| /|\\ ") print("| / \\ ") print("| ") print("| ") ''' def game(): print('''Welcome to hangman, you must guess letters to fill in the word. Incorrect guesses will use up a turn, you have 7 turns before you lose.''') lines = open("wordBank.txt").read() line = lines[0:] words = line.split() myword = random.choice(words).lower() letters = len(myword) print("Your word has " + str(letters) + " letters.") underscores = "" for x in range(0, letters): underscores += "_ " print(underscores) print(myword) l = set(myword) turn = 0 guesses = [] def guess(): thisGuess = input("Type a letter and press Enter(Return) to guess: ") if thisGuess.lower() in l: else: print("Boo") guess() game() </code></pre>
0
2016-10-17T18:25:09Z
40,093,719
<p>Another possible approach (in Python 2.7, see below for 3):</p> <pre><code>trueword = "shipping" guesses = "" def progress(): for i in range(len(trueword)): if trueword[i] in guesses: print trueword[i], else: print "-", print "" </code></pre> <p>This works by checking for each letter if it's been guessed <code>in guesses</code>, and printing that letter. If it hasn't been guessed, it prints <code>-</code>. When you put a comma at the end of a print (as in <code>print "-",</code>) it won't automatically print a newline, so you can continue printing on the same line. <code>print ""</code> prints a null string with a newline, finishing the line.</p> <p>Then guessing becomes:</p> <pre><code>guesses += guess </code></pre> <p>Output is:</p> <p>guesses = <code>''</code></p> <pre><code>- - - - - - - - </code></pre> <p>guesses = <code>'sip'</code></p> <pre><code>s - i p p i - - </code></pre> <hr> <p>In Python 3:</p> <pre><code>trueword = "shipping" guesses = "" def progress(): for i in range(len(trueword)): if trueword[i] in guesses: print(trueword[i], end='') else: print("-", end='') print('') </code></pre> <p>you add the <code>end=''</code> parameter to remove the newline, instead of the comma. If you want the spaces between them, you can add <code>sep=' '</code> as well to specify the separator.</p> <hr> <p>Also, because list comprehensions are awesome (and this works in 2.7 &amp; 3):</p> <pre><code>def progress(): ans = [word[x] if word[x] in guesses else '-' for x in range(len(word))] print(' '.join(ans)) </code></pre> <p>Does the same thing via <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">list comprehensions</a>... which are a very strong feature in python.</p>
1
2016-10-17T18:59:14Z
[ "python", "set" ]
Reading through a bunch of .gz files error: Error -3 while decompressing: invalid code lengths set
40,093,369
<p>I am trying to parse a bunch of .gz json files (the files are text files) by using the same function using multiprocessing in Python 2.7.10. However, almost at the very end of parsing each line in these files, it produces this error:</p> <p><code>error: Error -3 while decompressing: invalid code lengths set</code></p> <p>and stops the execution.</p> <p>This is my code:</p> <pre><code>import gzip import json from multiprocessing import Pool, cpu_count def build_list(file_name): count = 0 try: json_file = gzip.open(file_name, "r") except Exception as e: print e else: # Data parsing for line in json_file: try: row = json.loads(line) except Exception as e: print e else: count += 1 if __name__ == "__main__": files = ["h1.json.gz", "h2.json.gz", "h3.json.gz", "h4.json.gz", "h5.json.gz"] pool = Pool(processes=cpu_count()-1) pool.map(build_list, files) </code></pre> <p>It is important to clarify that the program starts running well and that the files are assigned at each processor when I check with <code>top</code>. I also check the integrity of the files with <code>gunzip -t</code> and they seems to be well formed. Also I did not see any exception raised before the error. Do you have any ideas on how can I fix it? Thanks in advance. </p>
0
2016-10-17T18:36:10Z
40,093,543
<p>Read in binary mode:</p> <pre><code>gzip.open(file_name, "rb") </code></pre> <p>Reading in text mode may mangle the data (as it is not text) on some platforms, and will cause odd errors such as this.</p>
0
2016-10-17T18:47:44Z
[ "python", "json", "python-2.7", "multiprocessing", "gzip" ]
Reading through a bunch of .gz files error: Error -3 while decompressing: invalid code lengths set
40,093,369
<p>I am trying to parse a bunch of .gz json files (the files are text files) by using the same function using multiprocessing in Python 2.7.10. However, almost at the very end of parsing each line in these files, it produces this error:</p> <p><code>error: Error -3 while decompressing: invalid code lengths set</code></p> <p>and stops the execution.</p> <p>This is my code:</p> <pre><code>import gzip import json from multiprocessing import Pool, cpu_count def build_list(file_name): count = 0 try: json_file = gzip.open(file_name, "r") except Exception as e: print e else: # Data parsing for line in json_file: try: row = json.loads(line) except Exception as e: print e else: count += 1 if __name__ == "__main__": files = ["h1.json.gz", "h2.json.gz", "h3.json.gz", "h4.json.gz", "h5.json.gz"] pool = Pool(processes=cpu_count()-1) pool.map(build_list, files) </code></pre> <p>It is important to clarify that the program starts running well and that the files are assigned at each processor when I check with <code>top</code>. I also check the integrity of the files with <code>gunzip -t</code> and they seems to be well formed. Also I did not see any exception raised before the error. Do you have any ideas on how can I fix it? Thanks in advance. </p>
0
2016-10-17T18:36:10Z
40,133,859
<p>I ended up using a try block that checks the integrity of every line in the pointer when reading. So the final code looks like this:</p> <pre><code>def build_list(file_name): count = 0 try: json_file = gzip.open(file_name, "r") except Exception as e: print e else: try: # Data parsing for line in json_file: try: row = json.loads(line) except Exception as e: print e else: count += 1 except Exception as e: print e </code></pre> <p>Thank you for all your comments. </p>
0
2016-10-19T14:12:19Z
[ "python", "json", "python-2.7", "multiprocessing", "gzip" ]
Python Script locked for debug in VS 2015
40,093,463
<p>I'm doing the nucleai courses. Exercises are based on python scripts and I'm using Visual Studio 2015. At some point, we have to use the library nltk. I was trying to debug some code I'm calling (I have the source) and something really weird happens: breakpoints work, but I can't use F10 to jump line to line. It just skips all the script. I can debug without any problem any of my scripts but not those within the library. So my question is: is there any option to "unlock" the script so I can debug line by line? I'm new with python and I can't find anything similar on google. I'm posting the code in case something is relevant. The function I want to debug is 'Respond'</p> <pre><code>from __future__ import print_function import re import random from nltk import compat reflections = { "i am" : "you are", "i was" : "you were", "i" : "you", "i'm" : "you are", "i'd" : "you would", "i've" : "you have", "i'll" : "you will", "my" : "your", "you are" : "I am", "you were" : "I was", "you've" : "I have", "you'll" : "I will", "your" : "my", "yours" : "mine", "you" : "me", "me" : "you" } class Chat(object): def __init__(self, pairs, reflections={}): self._pairs = [(re.compile(x, re.IGNORECASE),y) for (x,y) in pairs] self._reflections = reflections self._regex = self._compile_reflections() def _compile_reflections(self): sorted_refl = sorted(self._reflections.keys(), key=len, reverse=True) return re.compile(r"\b({0})\b".format("|".join(map(re.escape, sorted_refl))), re.IGNORECASE) def _substitute(self, str): return self._regex.sub(lambda mo: self._reflections[mo.string[mo.start():mo.end()]], str.lower()) def _wildcards(self, response, match): pos = response.find('%') while pos &gt;= 0: num = int(response[pos+1:pos+2]) response = response[:pos] + \ self._substitute(match.group(num)) + \ response[pos+2:] pos = response.find('%') return response def respond(self, str): # check each pattern for (pattern, response) in self._pairs: match = pattern.match(str) # did the pattern match? if match: resp = random.choice(response) # pick a random response resp = self._wildcards(resp, match) # process wildcards # fix munged punctuation at the end if resp[-2:] == '?.': resp = resp[:-2] + '.' if resp[-2:] == '??': resp = resp[:-2] + '?' return resp # Hold a conversation with a chatbot def converse(self, quit="quit"): input = "" while input != quit: input = quit try: input = compat.raw_input("&gt;") except EOFError: print(input) if input: while input[-1] in "!.": input = input[:-1] print(self.respond(input)) </code></pre> <p>Any help will be very much appreciated. Thanks.</p> <p>EDIT: I solved my problem but I haven't found a solution for the question. I'm using PyCharm (as suggested in the first comment) and it works like a charm. I can debug everything without any problem now. No file modification at all. I'm inclined to think that this is a bug in Python tools for Visual Studio. </p>
0
2016-10-17T18:42:45Z
40,120,240
<p>Other members also got the similar issue, my suggestion is that you can use the PyCharm instead of PTVS as a workaround. Of course, you could also start a discussion(Q AND A) from this site for PTVS tool:</p> <p><a href="https://visualstudiogallery.msdn.microsoft.com/9ea113de-a009-46cd-99f5-65ef0595f937" rel="nofollow">https://visualstudiogallery.msdn.microsoft.com/9ea113de-a009-46cd-99f5-65ef0595f937</a></p>
1
2016-10-19T00:40:50Z
[ "python", "python-3.x", "visual-studio-2015", "visual-studio-debugging" ]
Only show value of n*n matrix if value from another n*n has a certain value (Python)
40,093,475
<p>So I'm currently trying to calculate the Pearson's R and p-value for some data I have. This is done by this code:</p> <pre><code>import numpy as np from scipy.stats import pearsonr, betai from pandas import DataFrame import seaborn as sns import matplotlib.pyplot as plt def corrcoef(matrix): #function that calculates the Pearson's R and p-value r = np.corrcoef(matrix) rf = r[np.triu_indices(r.shape[0], 1)] df = matrix.shape[1] - 2 ts = rf * rf * (df / (1 - rf * rf)) pf = betai(0.5 * df, 0.5, df / (df + ts)) p = np.zeros(shape=r.shape) p[np.triu_indices(p.shape[0], 1)] = pf p[np.tril_indices(p.shape[0], -1)] = pf p[np.diag_indices(p.shape[0])] = np.ones(p.shape[0]) return r, p data = np.loadtxt('corr-data.txt') #data matrix loaded sig_lvl = 0.05 #significance level r_mat, p_mat = corrcoef(data) #use function on data and put the answers in two different matrices df_rmat = DataFrame(r_mat, columns=Index, index=Index) #make data readable for the seaborn package df_pmat = DataFrame(p_mat, columns=Index, index=Index) r_mat[abs(r_mat) &lt;= .90] = np.nan #if the R-value matrix elements are under 0.90, don't show them - make them NaN. p_mat[abs(p_mat) &gt;= sig_lvl] = np.nan #this is probably the issue. mask_pmat = np.zeros_like(p_mat) mask_pmat[np.tril_indices_from(mask_pmat)] = True #only showing the upper triangle of the values since it's symmetrical in the diagonal sns.plt.subplot(1,2,2) ax_pmat = sns.heatmap(np.around(df_pmat, decimals=2), annot=True, mask = mask_pmat) #subplot sequence for the p-value matrix only sns.plt.show() </code></pre> <p>It might not be the most optimal code, but as of now it works as intended. Using the seaborn package I get a heat/colormap of the different values if they are high enough (>= 0.95) or have the right significance level, and only the upper triangle. However, what I would actually like to do is to only show the p-value for those R-values that are represented in the first plot. Values that are smaller than 0.95 is just replaced by NaN and is no color in the heat map. So only values in the p-value matrix should be represented if values in the R-value matrix is represented.</p> <p>Can this be done, or...?</p> <p>And please let me know if something is unclear. Then I will try to further explain.</p> <p>Thanks in advance</p>
0
2016-10-17T18:43:39Z
40,093,665
<p>I think what you're saying is this:</p> <pre><code>p_mat[r_mat &lt; 0.95] = np.nan </code></pre> <p>This works because <code>p</code> and <code>r</code> are the same shape. It would go into your code instead of:</p> <pre><code>if r_mat[abs(r_mat) &lt;= .90] == np.nan: p_mat = np.nan </code></pre> <p>Note if you compare <code>NaN</code> to a value, the result is always false.</p>
2
2016-10-17T18:55:37Z
[ "python", "numpy", "matplotlib", "scipy", "seaborn" ]
find a number is between which range in a list of list
40,093,530
<p>Need some python help, I have a list: </p> <pre><code>[[sql1, 1, 10], [sql2, 12, 16]...] </code></pre> <p>I want to know if 15 is in the sql2, please let me know in python the easy way. </p> <p>I have tried in the loop. </p>
-2
2016-10-17T18:47:03Z
40,093,634
<p>You're going to have to give a few more details about your desired implementation, but this was too fun not to answer. </p> <p>My answer assumes:</p> <ol> <li>You want a list of the beginning strings (<code>index == 0</code>) of the sublists whose:</li> <li>2nd and 3rd elements contain <code>15</code> in the range of a (inclusive) and b (exclusive)</li> </ol> <p>This is in Python 3.</p> <pre> >>> x = [['sql1', 1, 10], ['sql2', 12, 16]] >>> [a for a, *b in x if 15 in range(*b)] ['sql2'] </pre> <p>This also works with multiple matches:</p> <pre><code>&gt;&gt;&gt; x = [['sql1', 1, 10], ['sql2', 12, 16], ['sql3', 15, 17]] &gt;&gt;&gt; [a for a, *b in x if 15 in range(*b)] ['sql2', 'sql3'] </code></pre> <p>If you want to accept <code>'sql2'</code> and <code>15</code> as input and return a boolean:</p> <pre><code>&gt;&gt;&gt; x = [['sql1', 1, 10], ['sql2', 12, 16]] &gt;&gt;&gt; check = 'sql2' &gt;&gt;&gt; n = 15 &gt;&gt;&gt; any(a == check and n in range(*b) for a, *b in x) True </code></pre>
2
2016-10-17T18:53:58Z
[ "python" ]
find a number is between which range in a list of list
40,093,530
<p>Need some python help, I have a list: </p> <pre><code>[[sql1, 1, 10], [sql2, 12, 16]...] </code></pre> <p>I want to know if 15 is in the sql2, please let me know in python the easy way. </p> <p>I have tried in the loop. </p>
-2
2016-10-17T18:47:03Z
40,093,638
<p>First, lest solve for the simplest solution and then look into making something generic out of it.</p> <pre><code>test_data = [['sql', 1, 10],['sql2', 12, 16, 15]] print(15 in test_data[1]) # True </code></pre> <p>We can even generalize it into a function </p> <pre><code>def in_data(data_sets, data, check_in): for data_set in data_sets: if data in data_set: if check_in in data_set: return True return False </code></pre> <p>@Robᵩ pointed out a more elegant/compact solution that allows us to write:</p> <pre><code>def in_data(data_sets, data, check_in): return any(check_in in data_set for data_set in data_sets) </code></pre>
1
2016-10-17T18:54:09Z
[ "python" ]
find a number is between which range in a list of list
40,093,530
<p>Need some python help, I have a list: </p> <pre><code>[[sql1, 1, 10], [sql2, 12, 16]...] </code></pre> <p>I want to know if 15 is in the sql2, please let me know in python the easy way. </p> <p>I have tried in the loop. </p>
-2
2016-10-17T18:47:03Z
40,093,658
<p>I have hard coded the data to meet the question requirements but the answer can be modified as required</p> <pre><code>my_list = [['sql1', 1, 10], ['sql2', 12, 16]] for i in range(len(my_list)): print(my_list[i]) if my_list[i][0] == 'sql1': if '15' in my_list[i][0]: print("found") else: print("not found") </code></pre>
1
2016-10-17T18:55:11Z
[ "python" ]
PyQt5 : how to Sort a QTableView when you click on the headers of a QHeaderView?
40,093,561
<p>I want to sort a QTableView when I click on the headers of my QHeaderView. I've found a several code sample on the internet like this one: <a href="http://stackoverflow.com/questions/28660287/sort-qtableview-in-pyqt5">Sort QTableView in pyqt5</a> but it doesn't work for me. I also look in the Rapid Gui programming Book from Summerfield but I could find something that was working either.</p> <p>In this quick example how could I sort the table by name or age?</p> <p>Here is my code :</p> <pre><code>from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * import pandas as pd import operator # This class was generated from the Qt Creator class Ui_tableView_ex(object): def setupUi(self, tableView_ex): tableView_ex.setObjectName("tableView_ex") tableView_ex.resize(800, 600) self.centralwidget = QWidget(tableView_ex) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.myTable = QTableView(self.centralwidget) self.myTable.setObjectName("monTablo") self.gridLayout.addWidget(self.myTable, 0, 0, 1, 1) tableView_ex.setCentralWidget(self.centralwidget) self.retranslateUi(tableView_ex) QMetaObject.connectSlotsByName(tableView_ex) def retranslateUi(self, tableView_ex): _translate = QCoreApplication.translate tableView_ex.setWindowTitle(_translate("tableView_ex", "MainWindow")) class TableTest(QMainWindow, Ui_tableView_ex): def __init__(self, parent=None): super(TableTest, self).__init__(parent) self.setupUi(self) self.model = TableModel() self.myTable.setModel(self.model) self.myTable.setShowGrid(False) self.hView = HeaderView(self.myTable) self.myTable.setHorizontalHeader(self.hView) self.myTable.verticalHeader().hide() # adding alternate colours self.myTable.setAlternatingRowColors(True) self.myTable.setStyleSheet("alternate-background-color: rgb(209, 209, 209)" "; background-color: rgb(244, 244, 244);") # self.myTable.setSortingEnabled(True) # self.myTable.sortByColumn(1, Qt.AscendingOrder) class HeaderView(QHeaderView): def __init__(self, parent): QHeaderView.__init__(self, Qt.Horizontal, parent) self.model = TableModel() self.setModel(self.model) # Setting font for headers only self.font = QFont("Helvetica", 12) self.setFont(self.font) # Changing section backgroud color. font color and font weight self.setStyleSheet("::section{background-color: pink; color: green; font-weight: bold}") self.setSectionResizeMode(1) self.setSectionsClickable(True) class TableModel(QAbstractTableModel): def __init__(self): QAbstractTableModel.__init__(self) super(TableModel, self).__init__() self.headers = ["Name", "Age", "Grades"] self.stocks = [["George", "26", "80%"], ["Bob", "16", "95%"], ["Martha", "22", "98%"]] self.data = pd.DataFrame(self.stocks, columns=self.headers) def update(self, in_data): self.data = in_data def rowCount(self, parent=None): return len(self.data.index) def columnCount(self, parent=None): return len(self.data.columns.values) def setData(self, index, value, role=None): if role == Qt.EditRole: row = index.row() col = index.column() column = self.data.columns.values[col] self.data.set_value(row, column, value) self.update(self.data) return True def data(self, index, role=None): if role == Qt.DisplayRole: row = index.row() col = index.column() value = self.data.iloc[row, col] return value def headerData(self, section, orientation, role=None): if role == Qt.DisplayRole: if orientation == Qt.Horizontal: return self.data.columns.values[section] # -----------------NOT WORKING!!!--------------- # ================================================= def sort(self, Ncol, order): """Sort table by given column number. """ self.layoutAboutToBeChanged.emit() self.data = sorted(self.data, key=operator.itemgetter(Ncol)) if order == Qt.DescendingOrder: self.data.reverse() self.layoutChanged.emit() # ================================================= if __name__ == '__main__': import sys app = QApplication(sys.argv) app.setStyle(QStyleFactory.create("Fusion")) main_window = TableTest() main_window.show() app.exec_() sys.exit() </code></pre> <p>I've try to modify a few things, but nothing worked out and when I uncomment the setSortingEnabled(True) line the window doesn't even open. So there is no way I can know if I'm closer to the solution or not! I would also like to change the text color depending on the grade(red under 50 an green over 50 for example). For that, I haven't search that much, so i will try it by myself before asking aquestion but if you have any hint It would be much appreciated!</p> <p>Thank you for your help!</p>
0
2016-10-17T18:48:44Z
40,104,722
<p>Your sort function is the problem, you are not using the pandas <code>DataFrame</code> sorting functions, and <code>self.data</code> become a python <code>list</code>, then other functions fail and the program crash.</p> <p>To correctly sort the <code>DataFrame</code> use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort.html" rel="nofollow"><code>sort_values</code></a> function like this:</p> <pre><code>def sort(self, Ncol, order): """Sort table by given column number.""" self.layoutAboutToBeChanged.emit() self.data = self.data.sort_values(self.headers[Ncol], ascending=order == Qt.AscendingOrder) self.layoutChanged.emit() </code></pre>
0
2016-10-18T09:38:42Z
[ "python", "sorting", "pyqt5", "qtableview", "qheaderview" ]
My program doesn't check if there's a duplicate inside a string correctly
40,093,614
<p>I have to do a program that check if there's a duplicate digit inside a 4 number string. The problem is that like 80% of the times the program classifies as not valid also number which aren't wrong.</p> <pre><code>import random def extraction(): random_number = str(random.randint(1000,9999)) print(random_number) for number in random_number: n = 0 print("number1 ",number) for number2 in random_number: print("number2 ",number2) if(number == number2): n = n + 1 print("n ",n) if(n == 2): print("The extracted number is not valid.\n") extraction() </code></pre>
-2
2016-10-17T18:52:44Z
40,093,708
<p>Why don't you make a <code>set()</code> out of the number string and evaluate the length of the set? If there are duplicate digits, only one entry will be stored in the set</p> <pre><code>if len(set(str(random_number))) == 4: pass #you have 4 unique digits </code></pre> <p>Example of working principle:</p> <pre>>>> set('1234') set(['1', '3', '2', '4']) >>> set('1123') set(['1', '3', '2'])</pre>
4
2016-10-17T18:58:34Z
[ "python" ]
My program doesn't check if there's a duplicate inside a string correctly
40,093,614
<p>I have to do a program that check if there's a duplicate digit inside a 4 number string. The problem is that like 80% of the times the program classifies as not valid also number which aren't wrong.</p> <pre><code>import random def extraction(): random_number = str(random.randint(1000,9999)) print(random_number) for number in random_number: n = 0 print("number1 ",number) for number2 in random_number: print("number2 ",number2) if(number == number2): n = n + 1 print("n ",n) if(n == 2): print("The extracted number is not valid.\n") extraction() </code></pre>
-2
2016-10-17T18:52:44Z
40,093,718
<p>Why not use the <code>str.count()</code> function?</p> <pre><code>def extraction(): random_number = str(random.randint(1000,9999)) print(random_number) if any([random_number.count(i)&gt;1 for i in random_number]): print("The extracted number is not valid.\n") extraction() </code></pre>
0
2016-10-17T18:59:05Z
[ "python" ]
Align image columns by max value
40,093,627
<p>I have an image where I would like to offset each column so that the maximum value of each column is vertically centered in the image. Here's some toy data:</p> <pre><code>unaligned = np.array([[0,0,1,2,3,2,1,0,0,0], [0,0,0,1,2,3,2,1,0,0], [0,1,2,3,4,3,2,1,0,0], [0,0,1,2,3,2,1,0,0,0], [0,0,0,1,2,3,2,1,0,0]]).T </code></pre> <p><a href="https://i.stack.imgur.com/KAHi9.png" rel="nofollow"><img src="https://i.stack.imgur.com/KAHi9.png" alt="enter image description here"></a></p> <p>Once aligned, it should look like</p> <pre><code>aligned = np.array([[0,0,0,1,2,3,2,1,0,0], [0,0,0,1,2,3,2,1,0,0], [0,0,1,2,3,4,3,2,1,0], [0,0,0,1,2,3,2,1,0,0], [0,0,0,1,2,3,2,1,0,0]]).T </code></pre> <p><a href="https://i.stack.imgur.com/Y568F.png" rel="nofollow"><img src="https://i.stack.imgur.com/Y568F.png" alt="enter image description here"></a></p> <p>I could go column by column, find the index of the maximum value, then rewrite the column to a new array with the maximum value at the midpoint. But is there a concise (and faster) way to do this, especially if I have images with thousands of columns? Perhaps even some image processing routine with the column max values used as control points?</p> <p>Thanks!</p>
0
2016-10-17T18:53:42Z
40,094,191
<p>Here's an approach using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> -</p> <pre><code>m,n = unaligned.shape col_shifts = m//2 - unaligned.argmax(0) row_idx = np.mod(np.arange(m)[:,None]-col_shifts,m) aligned_out = unaligned[row_idx,np.arange(n)] </code></pre> <p>If you are trying to fill the shifted in positions with zeros and the ends of the columns are zeros, we can alternatively get <code>row_idx</code> with <code>clipping</code>, like so -</p> <pre><code>row_idx = (np.arange(m)[:,None]-col_shifts).clip(min=0,max=m-1) </code></pre>
1
2016-10-17T19:28:40Z
[ "python", "numpy", "image-processing" ]
Python matplotlib: How can I draw an errorbar graph without lines and points?
40,093,641
<p>I am currently using the following code to plot errorbar graphs.</p> <pre><code>plt.errorbar(log_I_mean_, log_V2_mean_, xerr, yerr, '.') </code></pre> <p>However the end result shows a circular point in the centre of each errorbar intersection point. How can I plot just the errorbars without the central point, as is required in scientific work?</p>
0
2016-10-17T18:54:14Z
40,110,158
<p>use <code>'none'</code> instead of <code>'.'</code>:</p> <pre><code>import matplotlib.pyplot as plt x = np.arange(0.1, 4, 0.5) y = np.exp(-x) yerr = 0.1 + 0.2*np.sqrt(x) xerr = 0.1 + yerr plt.figure() plt.errorbar(x, y, 0.2, 0.4,'none') plt.title("Simplest errorbars, 0.2 in x, 0.4 in y") </code></pre> <p>result: </p> <p><a href="https://i.stack.imgur.com/xmb9p.png" rel="nofollow"><img src="https://i.stack.imgur.com/xmb9p.png" alt="enter image description here"></a></p> <p>P.S. this is slightly modified version of part of the example of pylab <a href="http://matplotlib.org/1.2.1/examples/pylab_examples/errorbar_demo.html" rel="nofollow">here</a></p>
2
2016-10-18T13:52:43Z
[ "python", "matplotlib" ]
Python split lines from read file and write them with another format in another file
40,093,696
<p>I read the lines from a file which containing two columns with values in that style:</p> <pre><code> 100.E-03 5.65581E-06 110.E-03 11.222E-06 120.E-03 18.3487E-06 130.E-03 15.6892E-06 </code></pre> <p>I need to write them in antoher file as:</p> <pre><code> 100.E-03 , 5.65581E-06 110.E-03 , 11.222E-06 120.E-03 , 18.3487E-06 130.E-03 , 15.6892E-06 </code></pre> <p>Can I do this with split? Can I define spaces, for example 5 spaces as the split variable? And when yes, how can I pick the splitted parts in order to write them in the way I want: My script looks like:</p> <pre><code>for k in files: print 'k =',k from abaqus import session print k with open("niffacc{k}.inp".format(k=k)) as f1: with open("niffacc_{k}.inp".format(k=k),"w") as f2: for line in itertools.islice(f1, 4, None): b = line.split(" ") #print "b:", b c = b[1] d = b[3] f2.write('%s'%c + "," + '%s'%d) #with open('VY_{k}'.format(k=k), 'a') as f1: #lines = f1.readlines() f2.close() f1.close() </code></pre> <p>I think the problem is in defining b, the splitted line. Is there any problem by defining as split character the spaces? Does python have a problem ti split because of the many spaces or it is handled as a groups of spaces? Is a better solution to convert the file in csv file and then back to txt file? </p>
-1
2016-10-17T18:57:21Z
40,093,820
<p><code>split</code> will automatically deal with any number of spaces. </p> <pre><code>' 100.E-03 5.65581E-06'.split() == ['100.E-03', '5.65581E-06'] </code></pre>
1
2016-10-17T19:04:47Z
[ "python", "csv", "split", "pick" ]
Python split lines from read file and write them with another format in another file
40,093,696
<p>I read the lines from a file which containing two columns with values in that style:</p> <pre><code> 100.E-03 5.65581E-06 110.E-03 11.222E-06 120.E-03 18.3487E-06 130.E-03 15.6892E-06 </code></pre> <p>I need to write them in antoher file as:</p> <pre><code> 100.E-03 , 5.65581E-06 110.E-03 , 11.222E-06 120.E-03 , 18.3487E-06 130.E-03 , 15.6892E-06 </code></pre> <p>Can I do this with split? Can I define spaces, for example 5 spaces as the split variable? And when yes, how can I pick the splitted parts in order to write them in the way I want: My script looks like:</p> <pre><code>for k in files: print 'k =',k from abaqus import session print k with open("niffacc{k}.inp".format(k=k)) as f1: with open("niffacc_{k}.inp".format(k=k),"w") as f2: for line in itertools.islice(f1, 4, None): b = line.split(" ") #print "b:", b c = b[1] d = b[3] f2.write('%s'%c + "," + '%s'%d) #with open('VY_{k}'.format(k=k), 'a') as f1: #lines = f1.readlines() f2.close() f1.close() </code></pre> <p>I think the problem is in defining b, the splitted line. Is there any problem by defining as split character the spaces? Does python have a problem ti split because of the many spaces or it is handled as a groups of spaces? Is a better solution to convert the file in csv file and then back to txt file? </p>
-1
2016-10-17T18:57:21Z
40,093,849
<p>I'm not sure why you want that many spaces between your columns but you can just split on whitespace:</p> <pre><code>with open('file1.txt') as f1, open('file2.txt', 'w') as f2: for line in f1: f2.write(line.split()[0] + ',' + line.split()[1] + '\n') </code></pre> <p>If you really want a bunch of spaces, then just use:</p> <pre><code>f2.write(line.split()[0] + ' , ' + line.split()[1] + '\n') </code></pre>
2
2016-10-17T19:06:41Z
[ "python", "csv", "split", "pick" ]
Python writing to terminal for no apparent reason?
40,093,816
<p>I have a fairly straightforward python (3.5.2) script, which reads from a file, and if the line meets certain criteria, then it copies the line into another one. The original file looks like this (this is one line, many more follow, in the same format but different numbers):</p> <blockquote> <p>2.9133 1 1 157.6578 170.4160 0.7081 3044.911 351.998 152.778 -1451.315 162.109</p> </blockquote> <p>And my script goes like:</p> <pre><code> inp = open("original.dat", "r") out = open("new.log", "w") for line in inp: if float(line.split()[5]) &lt; 5.0: out.write(line) </code></pre> <p>The program finishes the task well, I get the desired output. However, while running from the python terminal window, it spams my terminal with integers around 80 (so like 70-90) seemingly in a random fashion.</p> <p>I have no idea what might cause this undesired output, but it messes my workspace up hard. I hope some of you may have an idea to fix it.</p>
-1
2016-10-17T19:04:38Z
40,093,883
<p>This is a normal behavior when you do <code>.write</code> on a file like that. It's the number of bytes written to the file.</p> <pre><code>&gt;&gt;&gt; a = open("new.txt", 'w') &gt;&gt;&gt; a.write("hello") 5 </code></pre> <p>There's probably a more elegant solution, but you could suppress this by setting a variable to the output of <code>out.write</code></p> <pre><code>foo = out.write(line) </code></pre>
1
2016-10-17T19:09:11Z
[ "python" ]
Python Error: Not all arguments converted during string formatting
40,093,895
<pre><code>def process_cars(text_file): total_cmpg = 0 for line in text_file: if((line % 2) == 0): city_mpg = (line[52:54]) print(city_mpg) city_mpg = int(city_mpg) total_cmpg += city_mpg print ("Total miles per gallon in the city:", total_cmpg) </code></pre> <p>The error comes in the if((line % 2) == 0): I have searched on the other questions with the same error but none of them could solve the problem. The error is: Not all arguments converted during string formatting. I want to mod the position of the line. For example if it is the third line then, 2 % 2.</p>
0
2016-10-17T19:09:58Z
40,094,159
<pre><code>def process_cars(text_file): total_cmpg = 0 for file_line_number, line in enumerate(text_file): if((file_line_number % 2) == 0): city_mpg = (line[52:54]) print(city_mpg) city_mpg = int(city_mpg) total_cmpg += city_mpg print ("Total miles per gallon in the city:", total_cmpg) </code></pre> <p>Based on your comments, you want to only do the if statement every x amount of lines. Try what we have above, since we are using <code>enumerate()</code> which keeps a count of what ever is next in the object. In our case it keeps the count of the line number while still giving us what the line is. </p> <p><code>file_line_number</code> is the file number line currently and <code>line</code> is the content of the line.</p>
0
2016-10-17T19:26:55Z
[ "python", "python-3.x" ]
Basic Python functions. beginner
40,093,939
<p>This is all I have so far : </p> <pre><code>def anagram(str1, str2): print("String 1 : %s" %str1) print("String 2 : %s" %str2) s1 = sorted(str1.lower()) s2 = sorted(str2.lower()) if s1 == s2: print("This is an anagram") return True def test_anagram(): print( "\n** Testing example anagrams **\n") tests = [["dog", "cat"]] num_anagrams = 0 for test in tests: answer = anagram(test[0] , test[1]) print("For inputs " + test[0] + " and " + test[1] + " answer is: ", answer, end ="") if answer == test[0]: print("This test is correct") num_anagrams += 1 </code></pre> <p>I don't think this is close to right. I want it to compare the actual result to what the function previous gives out as a result, then output whether the result was the same, being 'correct' or not 'incorrect' then output how many tests worked correctly against the function. I cant get my head around the if statement</p> <p>Thanks for the help! </p>
-4
2016-10-17T19:12:28Z
40,093,992
<p>You're treating <code>str1</code> and <code>str2</code> like functions, when you're really just passing <code>str</code> objects, which, according to your error, are not callable (i.e. don't work as functions).</p> <p>Are you trying to accept input? If so, use <code>str1 = input("String 1 : ")</code> and so on.</p> <p>Otherwise, if you're trying to format output, use this:</p> <pre><code>print("String 1 : " % str1) </code></pre>
4
2016-10-17T19:15:05Z
[ "python", "function", "basic" ]
Basic Python functions. beginner
40,093,939
<p>This is all I have so far : </p> <pre><code>def anagram(str1, str2): print("String 1 : %s" %str1) print("String 2 : %s" %str2) s1 = sorted(str1.lower()) s2 = sorted(str2.lower()) if s1 == s2: print("This is an anagram") return True def test_anagram(): print( "\n** Testing example anagrams **\n") tests = [["dog", "cat"]] num_anagrams = 0 for test in tests: answer = anagram(test[0] , test[1]) print("For inputs " + test[0] + " and " + test[1] + " answer is: ", answer, end ="") if answer == test[0]: print("This test is correct") num_anagrams += 1 </code></pre> <p>I don't think this is close to right. I want it to compare the actual result to what the function previous gives out as a result, then output whether the result was the same, being 'correct' or not 'incorrect' then output how many tests worked correctly against the function. I cant get my head around the if statement</p> <p>Thanks for the help! </p>
-4
2016-10-17T19:12:28Z
40,094,067
<p>Fixed your code based on what I thought you wanted to do with some comments on what was changed and why:</p> <pre><code>def anagrams(str1, str2): print("String 1 : %s" %str1) #you wanted to print it right this is how you can format the string with variables print("String 2 : %s" %str2) #you wanted to print it right this is how you can format the string with variables s1 = sorted(str1.lower()) #lower function call to remove the capital letters since it matters s2 = sorted(str2.lower()) #lower function call to remove the capital letters since it matters if s1 == s2: print("This is an anagram") # you don't call a bool value with parameter. You use print functions instead and then return True return True #you wanted to return True here right? anagrams("Cat", "Tac") # no need to assign variables to match parameter names </code></pre> <p>This prints out:</p> <pre><code>String 1 : Cat String 2 : Tac This is an anagram </code></pre> <p>I think you were mistaking on how to print things out with variable assignment to the string, I vaguely remember a language that had that had a similar syntax with what you were doing. </p> <p>You error is basically trying to call a <code>str</code> object like a function. Since you took other programming language, I think you should know what's wrong with that statement</p> <p>Edited:</p> <pre><code>def anagram(str1, str2): print("String 1 : %s" %str1) print("String 2 : %s" %str2) s1 = sorted(str1.lower()) s2 = sorted(str2.lower()) if s1 == s2: print("This is an anagram") return True def test_anagram(): print( "\n** Testing example anagrams **\n") tests = [["dog", "cat"],["tac","cat"],["dog","god"]] num_anagrams = 0 for test in tests: answer = anagram(test[0] , test[1]) print("For inputs " + test[0] + " and " + test[1] + " answer is: " + str(answer)) if answer: print("This test is correct") num_anagrams += 1 print(num_anagrams) test_anagram() </code></pre>
3
2016-10-17T19:20:55Z
[ "python", "function", "basic" ]
Pandas DataFrame insert / fill missing rows from previous dates
40,093,971
<p>I have a <code>DataFrame</code> consisting of <code>date</code>s, other columns and a numerical value, where some value combinations in "other columns" could be missing, and I want to populate them from previous <code>date</code>s.</p> <p>Example. Say the <code>DataFrame</code> is like below. You can see on <code>2016-01-01</code>, we have data for <code>(LN, A)</code>, <code>(LN, B)</code>, <code>(NY, A)</code> and <code>(NY, B)</code> on columns <code>(location, band)</code>.</p> <pre> date location band value 0 2016-01-01 LN A 10.0 1 2016-01-01 LN B 5.0 2 2016-01-01 NY A 9.0 3 2016-01-01 NY B 6.0 4 2016-01-02 LN A 11.0 5 2016-01-02 NY B 7.0 6 2016-01-03 NY A 10.0 </pre> <p>Then you notice on <code>2016-01-02</code>, we only have <code>(LN, A)</code> and <code>(NY, B)</code>, but <code>(LN, B)</code> and <code>(NY, A)</code> are missing. Again, on <code>2016-01-03</code>, only <code>(NY, A)</code> is available; all other three combinations are missing.</p> <p>What I want to do is to populate the missing combinations of each date from its predecessor. Say for <code>2016-01-02</code>, I would like to add two more rows, "rolled over" from <code>2016-01-01</code>: <code>(LN, B, 5.0)</code> and <code>(NY, A, 9.0)</code> for columns <code>(location, band, value)</code>. Same for <code>2016-01-03</code>. So as to make the whole thing like below:</p> <pre> date location band value 0 2016-01-01 LN A 10.0 1 2016-01-01 LN B 5.0 2 2016-01-01 NY A 9.0 3 2016-01-01 NY B 6.0 4 2016-01-02 LN A 11.0 5 2016-01-02 NY B 7.0 6 2016-01-03 NY A 10.0 7 2016-01-02 LN B 5.0 8 2016-01-02 NY A 9.0 9 2016-01-03 LN A 11.0 10 2016-01-03 LN B 5.0 11 2016-01-03 NY B 7.0 </pre> <p>Note rows 7-11 are populated from rows 1, 2, 4, 7 and 5, respectively. The order is not really important as I can always sort afterwards if all the data I need is present.</p> <p>Anyone to help? Thanks a lot!</p>
0
2016-10-17T19:13:59Z
40,094,956
<p>You can use a <code>unstack</code>/<code>stack</code> method to get all missing values, followed by a forward fill:</p> <pre><code># Use unstack/stack to add missing locations. df = df.set_index(['date', 'location', 'band']) \ .unstack(level=['location', 'band']) \ .stack(level=['location', 'band'], dropna=False) # Forward fill NaN values within ['location', 'band'] groups. df = df.groupby(level=['location', 'band']).ffill().reset_index() </code></pre> <p>Or you can directly build a <code>MultiIndex</code> containing all combinations:</p> <pre><code># Build the full MultiIndex, set the partial MultiIndex, and reindex. levels = ['date', 'location', 'band'] full_idx = pd.MultiIndex.from_product([df[col].unique() for col in levels], names=levels) df = df.set_index(levels).reindex(full_idx) # Forward fill NaN values within ['location', 'band'] groups. df = df.groupby(level=['location', 'band']).ffill().reset_index() </code></pre> <p>The resulting output for either method:</p> <pre><code> date location band value 0 2016-01-01 LN A 10.0 1 2016-01-01 LN B 5.0 2 2016-01-01 NY A 9.0 3 2016-01-01 NY B 6.0 4 2016-01-02 LN A 11.0 5 2016-01-02 LN B 5.0 6 2016-01-02 NY A 9.0 7 2016-01-02 NY B 7.0 8 2016-01-03 LN A 11.0 9 2016-01-03 LN B 5.0 10 2016-01-03 NY A 10.0 11 2016-01-03 NY B 7.0 </code></pre>
0
2016-10-17T20:18:23Z
[ "python", "pandas", "dataframe" ]
Pandas DataFrame insert / fill missing rows from previous dates
40,093,971
<p>I have a <code>DataFrame</code> consisting of <code>date</code>s, other columns and a numerical value, where some value combinations in "other columns" could be missing, and I want to populate them from previous <code>date</code>s.</p> <p>Example. Say the <code>DataFrame</code> is like below. You can see on <code>2016-01-01</code>, we have data for <code>(LN, A)</code>, <code>(LN, B)</code>, <code>(NY, A)</code> and <code>(NY, B)</code> on columns <code>(location, band)</code>.</p> <pre> date location band value 0 2016-01-01 LN A 10.0 1 2016-01-01 LN B 5.0 2 2016-01-01 NY A 9.0 3 2016-01-01 NY B 6.0 4 2016-01-02 LN A 11.0 5 2016-01-02 NY B 7.0 6 2016-01-03 NY A 10.0 </pre> <p>Then you notice on <code>2016-01-02</code>, we only have <code>(LN, A)</code> and <code>(NY, B)</code>, but <code>(LN, B)</code> and <code>(NY, A)</code> are missing. Again, on <code>2016-01-03</code>, only <code>(NY, A)</code> is available; all other three combinations are missing.</p> <p>What I want to do is to populate the missing combinations of each date from its predecessor. Say for <code>2016-01-02</code>, I would like to add two more rows, "rolled over" from <code>2016-01-01</code>: <code>(LN, B, 5.0)</code> and <code>(NY, A, 9.0)</code> for columns <code>(location, band, value)</code>. Same for <code>2016-01-03</code>. So as to make the whole thing like below:</p> <pre> date location band value 0 2016-01-01 LN A 10.0 1 2016-01-01 LN B 5.0 2 2016-01-01 NY A 9.0 3 2016-01-01 NY B 6.0 4 2016-01-02 LN A 11.0 5 2016-01-02 NY B 7.0 6 2016-01-03 NY A 10.0 7 2016-01-02 LN B 5.0 8 2016-01-02 NY A 9.0 9 2016-01-03 LN A 11.0 10 2016-01-03 LN B 5.0 11 2016-01-03 NY B 7.0 </pre> <p>Note rows 7-11 are populated from rows 1, 2, 4, 7 and 5, respectively. The order is not really important as I can always sort afterwards if all the data I need is present.</p> <p>Anyone to help? Thanks a lot!</p>
0
2016-10-17T19:13:59Z
40,094,965
<p>My solution, in summary using the product operation to get all the combinations in a multi index, then some stacking and ffill().</p> <pre><code>df =pd.DataFrame({'date': {0: '2016-01-01', 1: '2016-01-01', 2: '2016-01-01', 3: '2016-01-01', 4: '2016-01-02', 5: '2016-01-02', 6: '2016-01-03'}, 'band': {0: 'A', 1: 'B', 2: 'A', 3: 'B', 4: 'A', 5: 'B', 6: 'A'}, 'location': {0: 'LN', 1: 'LN', 2: 'NY', 3: 'NY', 4: 'LN', 5: 'NY', 6: 'NY'}, 'value': {0: 10, 1: 5, 2: 9, 3: 6, 4: 11, 5: 7, 6: 10}}) unique_dates = df['date'].unique() df.set_index(['date','location','band'],inplace=True) idx = pd.MultiIndex.from_product([unique_dates,['LN','NY'],['A','B']]) df = df.reindex(idx) df = df.unstack(level=[2,1]) </code></pre> <p>which produces:</p> <pre><code> value A B A B LN LN NY NY 2016-01-01 10.0000 5.0000 9.0000 6.0000 2016-01-02 11.0000 nan nan 7.0000 2016-01-03 nan nan 10.0000 nan </code></pre> <p>and finally:</p> <pre><code>df = df.ffill() df = df.stack().stack() print df value 2016-01-01 LN A 10.0000 B 5.0000 NY A 9.0000 B 6.0000 2016-01-02 LN A 11.0000 B 5.0000 NY A 9.0000 B 7.0000 2016-01-03 LN A 11.0000 B 5.0000 NY A 10.0000 B 7.0000 </code></pre>
0
2016-10-17T20:19:04Z
[ "python", "pandas", "dataframe" ]
How do "de-embed" words in TensorFlow
40,094,097
<p>I am trying to follow the tutorial for <a href="https://www.tensorflow.org/versions/r0.11/tutorials/recurrent/index.html#language-modeling" rel="nofollow">Language Modeling</a> on the TensorFlow site. I see it runs and the cost goes down and it is working great, but I do not see any way to actually get the predictions from the model. I tried following the instructions at <a href="http://stackoverflow.com/questions/37179218/getting-word-from-id-at-tensorflow-rnn-sample">this answer</a> but the tensors returned from session.run are floating point values like 0.017842259, and the dictionary maps words to integers so that does not work.</p> <p>How can I get the predicted word from a tensorflow model? </p> <p>Edit: I found this <a href="https://github.com/tensorflow/tensorflow/issues/97" rel="nofollow">explanation</a> after searching around, I just am not sure what x and y would be in the context of this example. They don't seem to use the same conventions for this example as they do in the explanation.</p>
0
2016-10-17T19:22:37Z
40,094,226
<p>The tensor you are mentioning is the <code>loss</code>, which defines how the network is training. For prediction, you need to access the tensor <code>probabilities</code> which contain the probabilities for the next word. If this was classification problem, you'd just do <code>argmax</code> to get the top probability. But, to also give lower probability words a chance of being generated,some kind of sampling is often used.</p> <p>Edit: I assume the code you used is <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/rnn/ptb/ptb_word_lm.py" rel="nofollow">this</a>. In that case, if you look at line 148 (<code>logits</code>) which can be converted into probabilities by simply applying the <code>softmax</code> function to it -- like shown in the pseudocode in tensorflow website. Hope this helps.</p>
0
2016-10-17T19:31:19Z
[ "python", "tensorflow", "word2vec" ]
How do "de-embed" words in TensorFlow
40,094,097
<p>I am trying to follow the tutorial for <a href="https://www.tensorflow.org/versions/r0.11/tutorials/recurrent/index.html#language-modeling" rel="nofollow">Language Modeling</a> on the TensorFlow site. I see it runs and the cost goes down and it is working great, but I do not see any way to actually get the predictions from the model. I tried following the instructions at <a href="http://stackoverflow.com/questions/37179218/getting-word-from-id-at-tensorflow-rnn-sample">this answer</a> but the tensors returned from session.run are floating point values like 0.017842259, and the dictionary maps words to integers so that does not work.</p> <p>How can I get the predicted word from a tensorflow model? </p> <p>Edit: I found this <a href="https://github.com/tensorflow/tensorflow/issues/97" rel="nofollow">explanation</a> after searching around, I just am not sure what x and y would be in the context of this example. They don't seem to use the same conventions for this example as they do in the explanation.</p>
0
2016-10-17T19:22:37Z
40,114,823
<p>So after going through a bunch of other similar posts I figured this out. First, the code explained in the documentation is not the same as the code on the GitHub repository. The current code works by initializing models with data inside instead of passing data to the model as it goes along.</p> <p>So basically to accomplish what I was trying to do, I reverted my code to commit <a href="https://github.com/tensorflow/tensorflow/blob/9274f5aa478879386870bb0cb889e432d4aee330/tensorflow/models/rnn/ptb/ptb_word_lm.py" rel="nofollow">9274f5a</a> (also do the same for reader.py). Then I followed the steps taken in <a href="http://stackoverflow.com/questions/36286594/predicting-the-next-word-using-the-lstm-ptb-model-tensorflow-example?rq=1">this post</a> to get the <code>probabilities</code> tensor in my <code>run_epoch</code> function. Additionally, I followed <a href="http://stackoverflow.com/questions/37179218/getting-word-from-id-at-tensorflow-rnn-sample?noredirect=1&amp;lq=1">this answer</a> to pass the <code>vocabulary</code> to my <code>main</code> function. From there, I inverted the dict using <code>vocabulary = {v: k for k, v in vocabulary.items()}</code> and passed it to <code>run_epoch</code>.</p> <p>Finally, we can get the predicted word in <code>run_epoch</code> by running <code>current_word = vocabulary[np.argmax(prob, 1)]</code> where <code>prob</code> is the tensor returned from <code>session.run()</code></p> <p>Edit: Reverting the code as such should not be a permanent solution and I definitely recommend using @Prophecies answer above to get the <code>probabilities</code> tensor. However, if you want to get the word mapping, you will need to pass the vocabulary as I did here.</p>
0
2016-10-18T17:47:11Z
[ "python", "tensorflow", "word2vec" ]
I have a RSA public key exponent and modulus. How can I encrypt a string using Python?
40,094,108
<p>Given a public key exponent and modulus like the following, how can I encrypt a string and send it to a server as text?</p> <pre><code>publicKey: 10001, modulus: 'd0eeaf178015d0418170055351711be1e4ed1dbab956603ac04a6e7a0dca1179cf33f90294782e9db4dc24a2b1d1f2717c357f32373fb3d9fd7dce91c40b6602' </code></pre> <p>I am trying to replicate the functionality provided by the javascript rsa library <a href="http://www.ohdave.com/rsa/" rel="nofollow">http://www.ohdave.com/rsa/</a> in python. In javascript, it looks something like this:</p> <pre><code>setMaxDigits(67); //sets a max digits for bigInt var key = new RSAKeyPair('10001', '10001', 'd0eeaf178015d0418170055351711be1e4ed1dbab956603ac04a6e7a0dca1179cf33f90294782e9db4dc24a2b1d1f2717c357f32373fb3d9fd7dce91c40b6602'); var encrypted = encryptedString(key, 'message'); console.log(encrypted); //prints '88d58fec172269e5186592dd20446c594dbeb82c01edad41f841666500c9a530e24a282c6527ec66f4c826719f12478c6535bdc2baef86e4ff26906a26398413' </code></pre> <p>I imagine there is a way to do this with the PyCrypto library but I couldn't find any examples that use the exponent and modulus. </p> <h2>Edit 1:</h2> <p>Using the solution below, it appears to be working. Since I'm using python 2.7 I modified it to look like this: </p> <pre><code>from Crypto.PublicKey.RSA import construct from binascii import unhexlify from codecs import encode e = long(10001) n = int(encode('d0eeaf17801.....5d041817005535171', 'hex'), 16) key = construct((n, e)) a = key.encrypt('hello', None) print(a) ('.X?\xdc\x81\xfb\x9b(\x0b\xa1\xc6\xf7\xc0\xa3\xd7}U{Q?\xa6VR\xbdJ\xe9\xc5\x1f\x f9i+\xb2\xf7\xcc\x8c&amp;_\x9bD\x00\x86}V[z&amp;3\\]_\xde\xed\xdc~\xf2\xe1\xa9^\x96\xc3\ xd5R\xc2*\xcb\xd9\x1d\x88$\x98\xb0\x07\xfaG+&gt;G#\xf7cG\xd8\xa6\xf3y_ 4\x17\x0b\x0 3z\x0cvk7\xf7\xebPyo-\xa1\x81\xf5\x81\xec\x17\x9e\xfe3j\x98\xf2\xd5\x80\x1d\xdd\ xaf\xa4\xc8I\xeeB\xdaP\x85\xa7',) </code></pre> <p>Now I want to convert this encrypted text to a string to send via a post request. But this doesn't seem to work:</p> <pre><code>a.decode('utf-8') </code></pre>
0
2016-10-17T19:23:25Z
40,095,575
<p>With PyCrypto, you can use the <a href="https://www.dlitz.net/software/pycrypto/api/current/Crypto.PublicKey.RSA-module.html#construct" rel="nofollow">Crypto.PublicKey.RSA.construct()</a> function. You'll need to convert the modulus to an <code>int</code>. Here's an example (assuming big-endian):</p> <pre><code>from Crypto.PublicKey.RSA import construct e = int('10001', 16) n = int('d0eeaf...0b6602', 16) #snipped for brevity pubkey = construct((n, e)) </code></pre> <p>Then you can do the usual things (like <a href="https://www.dlitz.net/software/pycrypto/api/current/Crypto.PublicKey.RSA._RSAobj-class.html#encrypt" rel="nofollow">encrypt</a>) with the key:</p> <pre><code>pubkey.encrypt(b'abcde', None) </code></pre> <p><em>Edit: Note that your public exponent, 10001, is mostly likely hexadecimal. This would correspond to the common public exponent 65537. I've updated the above to reflect that.</em></p>
2
2016-10-17T21:01:21Z
[ "python", "public-key-encryption" ]
Python: [Errno 2] No such file or directory - weird issue
40,094,120
<p>I'm learning with a tutorial <a href="https://hackercollider.com/articles/2016/07/05/create-your-own-shell-in-python-part-1/" rel="nofollow">Create your own shell in Python</a> and I have some weird issue. I wrote following code:</p> <pre><code>import sys import shlex import os SHELL_STATUS_RUN = 1 SHELL_STATUS_STOP = 0 def shell_loop(): status = SHELL_STATUS_RUN while status == SHELL_STATUS_RUN: sys.stdout.write('&gt; ') #display a command prompt sys.stdout.flush() cmd = sys.stdin.readline() #read command input cmd_tokens = tokenize(cmd) #tokenize the command input status = execute(cmd_tokens) #execute the command and retrieve new status def main(): shell_loop() def tokenize(string): return shlex.split(string) def execute(cmd_tokens): #execute command os.execvp(cmd_tokens[0], cmd_tokens) #return status indicating to wait for the next command in shell_loop return SHELL_STATUS_RUN if __name__ == "__main__": main() </code></pre> <p>And now when I'm typing a "mkdir folder" command it returns error: <code>[Errno 2] No such file or directory</code>. BUT if I write previously "help" command which works correctly (displays me all available commands), command mkdir works correctly and it creating a folder. Please, guide me what's wrong with my code? I'm writing in Notepad++ on Windows 8.1 64x</p>
1
2016-10-17T19:24:18Z
40,094,312
<p>Copy-paste from comments in my link (thanks for <a href="http://stackoverflow.com/users/3009212/ari-gold">Ari Gold</a>)</p> <p>Hi tyh, it seems like you tried it on Windows. (I forgot to note that it works on Linux and Mac or Unix-like emulator like Cygwin only)</p> <p>For the first problem, it seems like it cannot find <code>mkdir</code> command on your system environment. You might find the directory that the <code>mkdir</code> binary resides in and use execvpe() to explicitly specify environment instead</p> <p>For the second problem, the <code>os</code> module on Windows has no fork() function. However, I suggest you to use Cygwin on Windows to emulate Unix like environment and two problems above should be gone.</p> <p>In Windows 10, there is Linux-Bash, which might work, but I never try.</p>
0
2016-10-17T19:37:22Z
[ "python", "python-3.x" ]
How can I find out the number of outputs in a loop?
40,094,153
<p>I am a beginner at python and I'm struggling with one of my (simple) college assignments. I have been given the following instructions:</p> <p><strong>A bank is offering a savings account where a yearly fee is charged. Write a program that lets the user enter</strong></p> <ol> <li><p>An initial investment.</p></li> <li><p>The yearly interest rate in percent.</p></li> <li><p>The yearly fee.</p></li> </ol> <p>the program should then calculate the time it takes for the investment to double. The interest is added on once per year.</p> <p>An example run of the program:</p> <p>Enter the investment: 1000</p> <p>Enter the interest rate: 10</p> <p>Enter the fee: 10</p> <p>The investment doubles after 7 years.</p> <p>I have formulated the following code but am receiving an error message with regards to t. I would really appreciate if I could get some help, thanks!:</p> <pre><code>t=0 p=float(input("Enter the investment:")) a=float(input("Enter the interest rate:")) m=float(input("Enter the fee:")) i=(float(a/100)) f=p while f&lt;=(2*p): f=(float(f*((1+i)**t)-m) t=t+1 print("The investment doubles after",t,"years") </code></pre>
-1
2016-10-17T19:26:25Z
40,096,285
<p>I tried to write this in a way that was very easy to follow and understand. I edited it with comments to explain what is happening line by line. I would recommend using more descriptive variables. t/p/a/m/f may make a lot of sense to you, but going back to this program 6 months from now, you may have issues trying to understand what you were trying to accomplish. <em>NOTE</em> You should use input instead of raw_input in my example if using Python 3+. I use 2.7 so I use raw_input.</p> <pre><code>#first we define our main function def main(): #investment is a variable equal to user input. it is converted to a float so that the user may enter numbers with decimal places for cents investment = float(raw_input("Starting Investment: ")) #interest is the variable for interest rate. it is entered as a percentage so 5.5 would equate to 5.5% interest = float(raw_input("Interest Rate as %, ex: 5.5 ")) #annual_fee is a variable that will hold the value for the annual fee. annual_fee = float(raw_input("Annual Fee: ")) #years is a variable that we will use with a while loop, adding 1 to each year (but we wait until within the loop to do this) years = 1 #we use a while loop as opposed to a for loop because we do not know how many times we will have to iterate through this loop to achieve a result. while true is always true, so this segment is going to run without conditions while True: #this is a variable that holds the value of our total money per year, this is equal to the initial investment + investment * interest percentage - our annual fee per year #I actually had to try a few different things to get this to work, a regular expression may have been more suited to achieve an interest % that would be easier to work with. do some research on regular expressions in python as you will sooner or later need it. total_per_year = investment + (years * (investment * (interest / 100))) - (annual_fee * years) #now we start adding 1 to our years variable, since this is a while loop, this will recalculate the value of total_per_year variable years += 1 #the conditional statement for when our total_per_year becomes equal to double our initial investment if total_per_year &gt;= 2 * investment: #print years value (at time condition is met, so it will be 5 if it takes 5 years) and the string ' Years to Double Investment' print years,' Years to Double Investment' #prints 'You will have $' string and then the value our variable total_per_year print 'You will have $', total_per_year #this will break our while loop so that it does not run endlessly break #here is error handling for if the fee is larger than investment + interest if (years * annual_fee) &gt;= (years * (investment * (interest / 100))): print('Annual Fee Exceeds Interest - Losing Money') break #initial call of our main function/begins loop main() </code></pre>
0
2016-10-17T21:53:45Z
[ "python", "loops", "while-loop" ]
URL query parameters are not processed in django rest
40,094,156
<p>Here is my <code>views.py</code>:</p> <pre><code>class my4appCompanyData(generics.ListAPIView): serializer_class = my4appSerializer def get_queryset(self,request): """Optionally restricts the returned data to ofa company, by filtering against a `id` query parameter in the URL. """ queryset = companies_csrhub.objects.all() #url_id = self.request.query_params.get('id', None) url_id = request.GET.get('id', None) if id is not None: queryset = queryset.filter(id=url_id) elif id is ALL: queryset = companies_csrhub.objects.all() else: queryset = "Error data not found" return queryset </code></pre> <p>And my <code>urls.py</code>:</p> <pre><code>router.register(r'api/my4app/company/$', views.my4appCompanyData.as_view(),base_name="company") </code></pre> <p>URL used for checking: <code>mywebsite/api/my4app/company/?id=100227</code></p> <p>Planning to add multiple filters with default values but not working. Please help.</p>
0
2016-10-17T19:26:36Z
40,097,324
<pre><code>class my4appCompanyData(generics.ListAPIView): serializer_class = my4appSerializer def get_queryset(self,request): """Optionally restricts the returned data to ofa company, by filtering against a `id` query parameter in the URL. """ queryset = companies_csrhub.objects.all() url_id = request.query_params.get('id', None) if id is not None: queryset = queryset.filter(id=url_id) elif id is ALL: queryset = companies_csrhub.objects.all() else: queryset = [] return queryset </code></pre> <p>Delete the return id since id is not a queryset, therefore it'd give an error. Also in the else part of if statement, you return string but you can't do that also since string is not a queryset.</p>
0
2016-10-17T23:41:35Z
[ "python", "django", "django-views", "django-rest-framework" ]
URL query parameters are not processed in django rest
40,094,156
<p>Here is my <code>views.py</code>:</p> <pre><code>class my4appCompanyData(generics.ListAPIView): serializer_class = my4appSerializer def get_queryset(self,request): """Optionally restricts the returned data to ofa company, by filtering against a `id` query parameter in the URL. """ queryset = companies_csrhub.objects.all() #url_id = self.request.query_params.get('id', None) url_id = request.GET.get('id', None) if id is not None: queryset = queryset.filter(id=url_id) elif id is ALL: queryset = companies_csrhub.objects.all() else: queryset = "Error data not found" return queryset </code></pre> <p>And my <code>urls.py</code>:</p> <pre><code>router.register(r'api/my4app/company/$', views.my4appCompanyData.as_view(),base_name="company") </code></pre> <p>URL used for checking: <code>mywebsite/api/my4app/company/?id=100227</code></p> <p>Planning to add multiple filters with default values but not working. Please help.</p>
0
2016-10-17T19:26:36Z
40,123,440
<p>According the official docs (<a href="http://www.django-rest-framework.org/api-guide/filtering/#filtering-against-query-parameters" rel="nofollow">http://www.django-rest-framework.org/api-guide/filtering/#filtering-against-query-parameters</a>)</p> <p>I think your code is not working because you are using:</p> <pre><code>url_id = request.query_params.get('id', None) </code></pre> <p>Instead of:</p> <pre><code>url_id = self.request.query_params.get('id', None) </code></pre> <p>In the documentation you can find that get_queryset function just receives <code>self</code> param, you must remove <code>request</code> param.</p>
0
2016-10-19T06:06:11Z
[ "python", "django", "django-views", "django-rest-framework" ]
Crontab: Using Python and sending email attachment
40,094,162
<p>I currently have a python file that is executed by the below crontab. It is currently working where it will run the Python file and it will email the output in the body of the email and also have an attachment with the same data. If I am trying to only have the attachment ( and not show the output of the data in the email), how can I modify my cronjob to do this?</p> <p>Python file: osversion_weekly.py</p> <pre><code>#! /usr/bin/python import commands, os, string import sys import fileinput output = os.system('uptime') output = os.system('df') output = os.system('top') output = os.system('ps') </code></pre> <p>Crontab Job: </p> <pre><code>04 19 17 10 2 /root/python/osversion_weekly.py | tee /root/python/osversion`date +\%Y-\%m-\%d-\%H:\%M`-cron.csv | mailx -s "Daily Report" -a "/root/python/osversion`date +\%Y-\%m-\%d-\%H:\%M`-cron.csv" [email protected] </code></pre>
0
2016-10-17T19:27:07Z
40,094,831
<p>I have a different version of <code>mailx</code> than you so I can't test this, but I suspect you'll get what you want if you replace the command with the following:</p> <pre><code>/root/python/osversion_weekly.py &gt; /root/python/osversion`date +\%Y-\%m-\%d-\%H:\%M`-cron.csv; echo "" | mailx -s "Daily Report" -a "/root/python/osversion`date +\%Y-\%m-\%d-\%H:\%M`-cron.csv" [email protected] </code></pre> <p>This writes the contents of the script to a file and then (hopefully) attaches it.</p>
0
2016-10-17T20:09:19Z
[ "python", "linux", "crontab" ]
git,curl,wget redirect to locahost
40,094,180
<p>Git gives me this error:</p> <pre class="lang-none prettyprint-override"><code>$ git clone How people build software · GitHub Cloning into 'xxxx'... fatal: unable to access 'xxx (Michael Dungan) · GitHub': Failed to connect to 127.0.0.1 port 443: Connection refused </code></pre> <p><code>curl</code> also gives the error:</p> <pre class="lang-none prettyprint-override"><code>$ curl http://baidu.com curl: (7) Failed to connect to 127.0.0.1 port 80: Connection refused </code></pre> <p><code>wget</code> also gives the error:</p> <pre class="lang-none prettyprint-override"><code>$ wget http://baidu.com Error parsing proxy URL “ http://127.0.0.1:8123 ”: Scheme missing. </code></pre> <p>But <code>ping</code> is okay:</p> <pre class="lang-none prettyprint-override"><code>ping http://baidu.com PING http://baidu.com (180.149.132.47): 56 data bytes 64 bytes from 180.149.132.47: icmp_seq=0 ttl=52 time=24.689 ms 64 bytes from 180.149.132.47: icmp_seq=1 ttl=52 time=23.770 ms 64 bytes from 180.149.132.47: icmp_seq=2 ttl=52 time=25.112 ms </code></pre> <p>And my browser is okay.</p> <p>I have restarted my Mac, closed my proxy, VPN, but the it never changes. This problem appears after I write this python code:</p> <pre class="lang-python prettyprint-override"><code>socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050) socket.socket = socks.socksocket socket.create_connection = create_connection socket.getaddrinfo = getaddrinfo </code></pre>
-1
2016-10-17T19:27:58Z
40,098,293
<p>i have solved this problem, i hava missed the http_proxy,https_proxy system environment variable in <code>/.bash_profile</code>. remove them, it is okay now.</p>
0
2016-10-18T01:51:39Z
[ "python", "sockets" ]
Parsing xml tree attributes (file has no elements)
40,094,201
<p>I have been trying to use minidom but have no real preference. For some reason lxml will not install on my machine. </p> <p>I would like to parse an xml file:</p> <pre><code>&lt;?xml version="1. -&lt;transfer frmt="1" vtl="0" serial_number="E5XX-0822" date="2016-10-03 16:34:53.000" style="startstop"&gt; -&lt;plateInfo&gt; &lt;plate barcode="E0122326" name="384plate" type="source"/&gt; &lt;plate barcode="A1234516" name="1536plateD" type="destination"/&gt; &lt;/plateInfo&gt; -&lt;printmap total="1387"&gt; &lt;w reason="" cf="13" aa="1.779" eo="299.798" tof="32.357" sv="1565.311" ct="1.627" ft="1.649" fc="88.226" memt="0.877" fldu="Percent" fld="DMSO" dy="0" dx="0" region="-1" tz="18989.481" gy="72468.649" gx="55070.768" avt="50" vt="50" vl="3.68" cvl="3.63" t="16:30:47.703" dc="0" dr="0" dn="A1" c="0" r="0" n="A1"/&gt; &lt;w reason="" cf="13" aa="1.779" eo="299.798" tof="32.357" sv="1565.311" ct="1.627" ft="1.649" fc="88.226" memt="0.877" fldu="Percent" fld="DMSO" dy="0" dx="0" region="-1" tz="18989.481" gy="72468.649" gx="55070.768" avt="50" vt="50" vl="3.68" cvl="3.63" t="16:30:47.703" dc="0" dr="0" dn="A1" c="1" r="0" n="A2"/&gt; &lt;/printmap&gt; &lt;/transfer&gt; </code></pre> <p>The files do not have any element details, as you can see. All the information is contained in the attributes. In trying to adapt another SO post, I have this - but it seems to be geared more toward elements. I am also failing at a good way to "browse" the xml information, i.e. I would like to say "dir(xml_file)" and have a list of all the methods I can carry out on my tree structure, or see all the attributes. I know this was a lot and potentially different directions, but thank you in advance!</p> <pre><code>def parse(files): for xml_file in files: xmldoc = minidom.parse(xml_file) transfer = xmldoc.getElementsByTagName('transfer')[0] plateInfo = transfer.getElementsByTagName('plateInfo')[0] </code></pre>
0
2016-10-17T19:29:15Z
40,095,571
<p>With minidom you can access the attributes of a particular element using the method attributes which can then be treated as dictionary; this example iterates and print the attributes of the element transfer[0]:</p> <pre><code>from xml.dom.minidom import parse, parseString xml_file='''&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;transfer frmt="1" vtl="0" serial_number="E5XX-0822" date="2016-10-03 16:34:53.000" style="startstop"&gt; &lt;plateInfo&gt; &lt;plate barcode="E0122326" name="384plate" type="source"/&gt; &lt;plate barcode="A1234516" name="1536plateD" type="destination"/&gt; &lt;/plateInfo&gt; &lt;printmap total="1387"&gt; &lt;w reason="" cf="13" aa="1.779" eo="299.798" tof="32.357" sv="1565.311" ct="1.627" ft="1.649" fc="88.226" memt="0.877" fldu="Percent" fld="DMSO" dy="0" dx="0" region="-1" tz="18989.481" gy="72468.649" gx="55070.768" avt="50" vt="50" vl="3.68" cvl="3.63" t="16:30:47.703" dc="0" dr="0" dn="A1" c="0" r="0" n="A1"/&gt; &lt;w reason="" cf="13" aa="1.779" eo="299.798" tof="32.357" sv="1565.311" ct="1.627" ft="1.649" fc="88.226" memt="0.877" fldu="Percent" fld="DMSO" dy="0" dx="0" region="-1" tz="18989.481" gy="72468.649" gx="55070.768" avt="50" vt="50" vl="3.68" cvl="3.63" t="16:30:47.703" dc="0" dr="0" dn="A1" c="1" r="0" n="A2"/&gt; &lt;/printmap&gt; &lt;/transfer&gt;''' xmldoc = parseString(xml_file) transfer = xmldoc.getElementsByTagName('transfer') attlist= transfer[0].attributes.keys() for a in attlist: print transfer[0].attributes[a].name,transfer[0].attributes[a].value </code></pre> <p>you can find more information here:</p> <p><a href="http://www.diveintopython.net/xml_processing/attributes.html" rel="nofollow">http://www.diveintopython.net/xml_processing/attributes.html</a></p>
0
2016-10-17T21:01:04Z
[ "python", "xml", "minidom" ]
What is a delimiter?
40,094,221
<p>I am new to making CSV files with Python, and I am doing it to work with LDA (Latent Dirichlet Allocation). It says in a tutorial video </p> <pre><code>with open('test.csv', 'w') as fp: a = csv.writer(fp,delimiter=',') </code></pre> <p>I know <code>fp</code> means file pointer, yet I don't know how that relates to <code>delimiter</code> or what a <code>delimiter</code> is.</p>
-12
2016-10-17T19:30:49Z
40,094,289
<p>A delimiter is what separates values from each other. So the csv writer will separate values using a comma since the delimiter keyword argument is set to a comma mark <code>delimiter=','</code>.</p>
3
2016-10-17T19:35:18Z
[ "python", "csv" ]
What is a delimiter?
40,094,221
<p>I am new to making CSV files with Python, and I am doing it to work with LDA (Latent Dirichlet Allocation). It says in a tutorial video </p> <pre><code>with open('test.csv', 'w') as fp: a = csv.writer(fp,delimiter=',') </code></pre> <p>I know <code>fp</code> means file pointer, yet I don't know how that relates to <code>delimiter</code> or what a <code>delimiter</code> is.</p>
-12
2016-10-17T19:30:49Z
40,094,310
<p>Let's say I have a csv file with lines like:</p> <pre><code>123ab,3748 jk89, 9ijkl </code></pre> <p>What are the values in this file? With delimiter <code>,</code></p> <pre><code>['123ab', '3748 jk89', ' 9ijkl'] </code></pre> <p>But with delimiter <code></code> (space character)</p> <pre><code>['123ab,3748', 'jk89,', '9ijkl'] </code></pre>
2
2016-10-17T19:37:03Z
[ "python", "csv" ]
Displaying unique name with total of column value in a group with additional variables in python
40,094,260
<p>I'm learning Python and thought working on a project might be the best way to learn it. I have about 200,000 rows of data in which the data shows list of medication for the patient. Here's a sample of the data. </p> <pre><code>PTID PTNAME MME DRNAME DRUGNAME SPLY STR QTY FACTOR 1 PATIENT, A 2700 DR, A OXYCODONE HCL 15 MG 30 15 120 1.5 1 PATIENT, A 2700 DR, B OXYCODONE HCL 15 MG 30 15 120 1.5 2 PATIENT, B 4050 DR, C MORPHINE SULFATE ER 15 MG 30 15 270 1 2 PATIENT, B 4050 DR, C MORPHINE SULFATE ER 15 MG 30 15 270 1 2 PATIENT, B 840 DR, A OXYCODONE-ACETAMINOPHE 10MG-32 14 10 56 1.5 2 PATIENT, B 1350 DR, C OXYCODONE-ACETAMINOPHE 5 MG-32 15 5 180 1.5 3 PATIENT, C 1350 DR, C OXYCODONE-ACETAMINOPHE 5 MG-32 15 5 180 1.5 3 PATIENT, C 1800 DR, D OXYCODONE-ACETAMINOPHE 10MG-32 30 10 120 1.5 </code></pre> <p>I've been thinking about this a lot and have tried many ways but none of the code produce any results or makes any sense. Honestly, I don't even know where to begin. A little help would be highly appreciated. </p> <p>So, what I want to do is consolidate the data for each patients and calculate the <code>Total MME</code> for each patient. The <code>DRUGNAME</code> should show the one that has higher MME. In other words, the dataframe should only have one row for each patient. </p> <p>One thing I did try is </p> <pre><code>groupby_ptname = semp.groupby('PTNAME').apply(lambda x: x.MME.sum()) </code></pre> <p>which shows unique patient names with total MME, but I'm not sure how to add other variables in this new dataframe. </p>
1
2016-10-17T19:33:28Z
40,094,536
<p>Have another look at the documentation for the <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">pandas groupby methods</a>. </p> <p>Here's something that could work for you:</p> <pre><code>#first get the total MME for each patient and drug combination total_mme=semp.groupby(['PTNAME','DRUGNAME'])['MME'].sum() #this will be a series object with index corresponding to PTNAME and DRUGNAME and values corresponding to the total MME #now get the indices corresponding to the drug with the max MME total max_drug_indices=total_mme.groupby(level='PTNAME').idxmax() #index the total MME with these indices out=total_mme[max_drug_indices] </code></pre>
1
2016-10-17T19:50:25Z
[ "python", "pandas" ]
Displaying unique name with total of column value in a group with additional variables in python
40,094,260
<p>I'm learning Python and thought working on a project might be the best way to learn it. I have about 200,000 rows of data in which the data shows list of medication for the patient. Here's a sample of the data. </p> <pre><code>PTID PTNAME MME DRNAME DRUGNAME SPLY STR QTY FACTOR 1 PATIENT, A 2700 DR, A OXYCODONE HCL 15 MG 30 15 120 1.5 1 PATIENT, A 2700 DR, B OXYCODONE HCL 15 MG 30 15 120 1.5 2 PATIENT, B 4050 DR, C MORPHINE SULFATE ER 15 MG 30 15 270 1 2 PATIENT, B 4050 DR, C MORPHINE SULFATE ER 15 MG 30 15 270 1 2 PATIENT, B 840 DR, A OXYCODONE-ACETAMINOPHE 10MG-32 14 10 56 1.5 2 PATIENT, B 1350 DR, C OXYCODONE-ACETAMINOPHE 5 MG-32 15 5 180 1.5 3 PATIENT, C 1350 DR, C OXYCODONE-ACETAMINOPHE 5 MG-32 15 5 180 1.5 3 PATIENT, C 1800 DR, D OXYCODONE-ACETAMINOPHE 10MG-32 30 10 120 1.5 </code></pre> <p>I've been thinking about this a lot and have tried many ways but none of the code produce any results or makes any sense. Honestly, I don't even know where to begin. A little help would be highly appreciated. </p> <p>So, what I want to do is consolidate the data for each patients and calculate the <code>Total MME</code> for each patient. The <code>DRUGNAME</code> should show the one that has higher MME. In other words, the dataframe should only have one row for each patient. </p> <p>One thing I did try is </p> <pre><code>groupby_ptname = semp.groupby('PTNAME').apply(lambda x: x.MME.sum()) </code></pre> <p>which shows unique patient names with total MME, but I'm not sure how to add other variables in this new dataframe. </p>
1
2016-10-17T19:33:28Z
40,095,388
<p>IIUC you can do it this way:</p> <pre><code>In [62]: df.sort_values('MME').groupby('PTNAME').agg({'MME':'sum', 'DRUGNAME':'last'}) Out[62]: DRUGNAME MME PTNAME PATIENT, A OXYCODONE HCL 15 MG 5400 PATIENT, B MORPHINE SULFATE ER 15 MG 10290 PATIENT, C OXYCODONE-ACETAMINOPHE 10MG-32 3150 </code></pre> <p>or with <code>.reset_index()</code>:</p> <pre><code>In [64]: df.sort_values('MME').groupby('PTNAME').agg({'MME':'sum', 'DRUGNAME':'last'}).reset_index() Out[64]: PTNAME DRUGNAME MME 0 PATIENT, A OXYCODONE HCL 15 MG 5400 1 PATIENT, B MORPHINE SULFATE ER 15 MG 10290 2 PATIENT, C OXYCODONE-ACETAMINOPHE 10MG-32 3150 </code></pre> <p><strong>UPDATE:</strong> more fun with <code>agg()</code> function</p> <pre><code>In [84]: agg_funcs = { ...: 'MME':{'MME_max':'last', ...: 'MME_total':'sum'}, ...: 'DRUGNAME':{'DRUGNAME_max_MME':'last'} ...: } ...: ...: rslt = (df.sort_values('MME') ...: .groupby('PTNAME') ...: .agg(agg_funcs) ...: .reset_index() ...: ) ...: rslt.columns = [tup[1] if tup[1] else tup[0] for tup in rslt.columns] ...: In [85]: rslt Out[85]: PTNAME MME_total MME_max DRUGNAME_max_MME 0 PATIENT, A 5400 2700 OXYCODONE HCL 15 MG 1 PATIENT, B 10290 4050 MORPHINE SULFATE ER 15 MG 2 PATIENT, C 3150 1800 OXYCODONE-ACETAMINOPHE 10MG-32 </code></pre>
1
2016-10-17T20:47:24Z
[ "python", "pandas" ]
Finding pointer arguments with GnuCParser?
40,094,339
<p>I'm trying to parse this fragment of C code:</p> <pre><code>void foo(const int *bar, int * const baz); </code></pre> <p>using <code>GnuCParser</code>, part of <a href="https://github.com/inducer/pycparserext" rel="nofollow">pycparserext</a>.</p> <p>Based on <a href="http://stackoverflow.com/a/21872138/28169">this answer</a> I expected to see some <code>PtrDecl</code>s, but here's what I get from <code>ast.show()</code> on the resulting parse tree:</p> <pre><code>FileAST: Decl: foo, [], [], [] FuncDecl: ParamList: Decl: bar, ['const'], [], [] TypeDeclExt: bar, ['const'] IdentifierType: ['int'] Decl: baz, [], [], [] TypeDeclExt: baz, [] IdentifierType: ['int'] TypeDecl: foo, [] IdentifierType: ['void'] </code></pre> <p>Notice how <code>baz</code>, a "const pointer to <code>int</code>", doesn't have a trace of <code>const</code> (or "pointeryness") in the data printed by <code>ast.show()</code>. Is this difference because of <code>GnuCParser</code>?</p> <p>How do I figure out the type of <code>baz</code> from the AST? My actual C code needs the GNU parser. I'm using pycparserext version 2016.1.</p> <p><em>UPDATE</em>: I've created a <a href="https://github.com/inducer/pycparserext/issues/21" rel="nofollow">pycparserext issue on GitHub</a>.</p>
0
2016-10-17T19:39:37Z
40,099,163
<p>I'm not sure what the issue with pycparserext here, but if I run it through the vanilla <a href="https://github.com/eliben/pycparser" rel="nofollow">pycparser</a> I get:</p> <pre><code>FileAST: Decl: foo, [], [], [] FuncDecl: ParamList: Decl: bar, ['const'], [], [] PtrDecl: [] TypeDecl: bar, ['const'] IdentifierType: ['int'] Decl: baz, [], [], [] PtrDecl: ['const'] TypeDecl: baz, [] IdentifierType: ['int'] TypeDecl: foo, [] IdentifierType: ['void'] </code></pre> <p>Which looks entirely reasonable for this input.</p>
0
2016-10-18T03:46:00Z
[ "python", "gcc", "pycparser" ]
Finding pointer arguments with GnuCParser?
40,094,339
<p>I'm trying to parse this fragment of C code:</p> <pre><code>void foo(const int *bar, int * const baz); </code></pre> <p>using <code>GnuCParser</code>, part of <a href="https://github.com/inducer/pycparserext" rel="nofollow">pycparserext</a>.</p> <p>Based on <a href="http://stackoverflow.com/a/21872138/28169">this answer</a> I expected to see some <code>PtrDecl</code>s, but here's what I get from <code>ast.show()</code> on the resulting parse tree:</p> <pre><code>FileAST: Decl: foo, [], [], [] FuncDecl: ParamList: Decl: bar, ['const'], [], [] TypeDeclExt: bar, ['const'] IdentifierType: ['int'] Decl: baz, [], [], [] TypeDeclExt: baz, [] IdentifierType: ['int'] TypeDecl: foo, [] IdentifierType: ['void'] </code></pre> <p>Notice how <code>baz</code>, a "const pointer to <code>int</code>", doesn't have a trace of <code>const</code> (or "pointeryness") in the data printed by <code>ast.show()</code>. Is this difference because of <code>GnuCParser</code>?</p> <p>How do I figure out the type of <code>baz</code> from the AST? My actual C code needs the GNU parser. I'm using pycparserext version 2016.1.</p> <p><em>UPDATE</em>: I've created a <a href="https://github.com/inducer/pycparserext/issues/21" rel="nofollow">pycparserext issue on GitHub</a>.</p>
0
2016-10-17T19:39:37Z
40,125,514
<p>This was due to a bug in pycparserext, it has been fixed now by the maintainer and the issue mentioned in the question has been closed. The fix is in release 2016.2.</p> <p>The output is now:</p> <pre><code>&gt;&gt;&gt; from pycparserext.ext_c_parser import GnuCParser &gt;&gt;&gt; p=GnuCParser() &gt;&gt;&gt; ast=p.parse("void foo(const int *bar, int * const baz);") &gt;&gt;&gt; ast.show() FileAST: Decl: foo, [], [], [] FuncDecl: ParamList: Decl: bar, ['const'], [], [] PtrDecl: [] TypeDecl: bar, ['const'] IdentifierType: ['int'] Decl: baz, [], [], [] PtrDecl: ['const'] TypeDecl: baz, [] IdentifierType: ['int'] TypeDecl: foo, [] IdentifierType: ['void'] </code></pre> <p>Clearly this contains more <code>Ptr</code> nodes, which is a very good sign. The pycparserext code has also had a test added to catch this in the future.</p> <p>Very impressive. :)</p>
0
2016-10-19T08:03:05Z
[ "python", "gcc", "pycparser" ]
How is it possible to use a while loop to print even numbers 2 through 100?
40,094,424
<p>I am a beginner and I am stuck on this problem, "Write a python code that uses a while loop to print even numbers from 2 through 100. Hint ConsecutiveEven differ by 2."</p> <p>Here is what I came up with so far: </p> <pre><code> while num in range(22,101,2): print(num) </code></pre>
-6
2016-10-17T19:44:08Z
40,094,469
<p>Here is how to use the while loop</p> <pre><code> while [condition]: logic here </code></pre> <p>using while in range is incorrect. </p> <pre><code>num = 0 while num &lt;=100: if num % 2 == 0: print(num) num += 1 </code></pre>
0
2016-10-17T19:47:07Z
[ "python", "loops", "while-loop" ]
How is it possible to use a while loop to print even numbers 2 through 100?
40,094,424
<p>I am a beginner and I am stuck on this problem, "Write a python code that uses a while loop to print even numbers from 2 through 100. Hint ConsecutiveEven differ by 2."</p> <p>Here is what I came up with so far: </p> <pre><code> while num in range(22,101,2): print(num) </code></pre>
-6
2016-10-17T19:44:08Z
40,094,508
<p>Use either <code>for</code> with <code>range()</code>, or use <code>while</code> and explicitly increment the number. For example:</p> <pre><code>&gt;&gt;&gt; i = 2 &gt;&gt;&gt; while i &lt;=10: # Using while ... print(i) ... i += 2 ... 2 4 6 8 10 &gt;&gt;&gt; for i in range(2, 11, 2): # Using for ... print(i) ... 2 4 6 8 10 </code></pre>
1
2016-10-17T19:49:01Z
[ "python", "loops", "while-loop" ]
How is it possible to use a while loop to print even numbers 2 through 100?
40,094,424
<p>I am a beginner and I am stuck on this problem, "Write a python code that uses a while loop to print even numbers from 2 through 100. Hint ConsecutiveEven differ by 2."</p> <p>Here is what I came up with so far: </p> <pre><code> while num in range(22,101,2): print(num) </code></pre>
-6
2016-10-17T19:44:08Z
40,094,527
<p>Your code has several problems:</p> <ul> <li>Substituting <code>while</code> for a statement with <code>for</code> syntax. <code>while</code> takes a bool, not an iterable.</li> <li>Using incorrect values for <code>range</code>: you will start at 22.</li> </ul> <p>With minimal changes, this should work:</p> <pre><code>for num in range(2, 101, 2): print(num) </code></pre> <p>Note that I used <code>101</code> for the upper limit of <code>range</code> because it is <em>exclusive</em>. If I put <code>100</code> it would stop at <code>98</code>.</p> <p>If you need to use a <code>while</code> loop:</p> <pre><code>n = 2 while n &lt;= 100: print (n) n += 2 </code></pre>
0
2016-10-17T19:49:41Z
[ "python", "loops", "while-loop" ]
Paramiko capturing command output
40,094,461
<p>I have an issue that has been giving me a headache for a few days. I am using the Paramiko module with Python 2.7.10 and I'd like to issue multiple commands to a Brocade router, but only return output from one of the given commands like so:</p> <pre><code>#!/usr/bin/env python import paramiko, time router = 'r1.test.example.com' password = 'password' username = 'testuser' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(router, username=username, password=password) print('Successfully connected to %s' % router) remote_conn = ssh.invoke_shell() output = remote_conn.recv(1000) # Disable paging on Brocade. remote_conn.send('terminal length 0\n') # Check interface status. remote_conn.send('show interfaces ethernet 0/1\n') # I only want output from this command. time.sleep(2) output = remote_conn.recv(5000) print(output) </code></pre> <p>If I were to print the full output it would contain everything issued to the router, but I only want to see output from the show <code>interfaces ethernet 0/1\n</code> command.</p> <p>Can anyone help with this issue?</p> <p>One final thing I would like to ask. I want to filter through the <code>output</code> variable and check for occurrences of strings like "up" or "down", but I can't seem to get it to work because everything in the output appears to be on new lines?</p> <p>For example:</p> <p>If I iterate over the <code>output</code> variable in a for loop I get all of the characters in the variable like so:</p> <pre><code>for line in output: print(line) </code></pre> <p>I get an output like this:</p> <p>t</p> <p>e</p> <p>r</p> <p>m</p> <p>i</p> <p>n</p> <p>a</p> <p>l</p> <p>l</p> <p>e</p> <p>n</p> <p>g</p> <p>t</p> <p>h</p> <p>0</p> <p>Any way around this?</p> <p>Again,</p> <p>Thanks in advance for any help.</p> <p>Best regards,</p> <p>Aaron C.</p>
-1
2016-10-17T19:46:46Z
40,095,024
<p>For your second question: Though I am not specialist of paramiko, I see that function recv, <a href="http://docs.paramiko.org/en/2.0/api/channel.html" rel="nofollow">according to the doc</a>, returns a string. If you apply a <strong>for</strong> loop on a string, you will get characters (and not lines as one might perhaps expect). The newline is caused by your use of the print function as explained <a href="http://www.pythonlearn.com/html-008/cfbook007.html" rel="nofollow">on this page, at paragraph 6.3</a>.</p> <p>I haven't studied what paramiko suggests to do. But why don't you treat the full string as a single entity? For example, you could check the presence of "up" as:</p> <pre><code>if "up" in output: </code></pre> <p>Or, if that suits your needs better, you could <a href="http://stackoverflow.com/questions/172439/how-do-i-split-a-multi-line-string-into-multiple-lines">split the string into lines</a> and then do whatever test you want to do:</p> <pre><code>for line in output.split('\n'): </code></pre>
1
2016-10-17T20:22:56Z
[ "python", "python-2.7", "ssh", "paramiko" ]
Paramiko capturing command output
40,094,461
<p>I have an issue that has been giving me a headache for a few days. I am using the Paramiko module with Python 2.7.10 and I'd like to issue multiple commands to a Brocade router, but only return output from one of the given commands like so:</p> <pre><code>#!/usr/bin/env python import paramiko, time router = 'r1.test.example.com' password = 'password' username = 'testuser' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(router, username=username, password=password) print('Successfully connected to %s' % router) remote_conn = ssh.invoke_shell() output = remote_conn.recv(1000) # Disable paging on Brocade. remote_conn.send('terminal length 0\n') # Check interface status. remote_conn.send('show interfaces ethernet 0/1\n') # I only want output from this command. time.sleep(2) output = remote_conn.recv(5000) print(output) </code></pre> <p>If I were to print the full output it would contain everything issued to the router, but I only want to see output from the show <code>interfaces ethernet 0/1\n</code> command.</p> <p>Can anyone help with this issue?</p> <p>One final thing I would like to ask. I want to filter through the <code>output</code> variable and check for occurrences of strings like "up" or "down", but I can't seem to get it to work because everything in the output appears to be on new lines?</p> <p>For example:</p> <p>If I iterate over the <code>output</code> variable in a for loop I get all of the characters in the variable like so:</p> <pre><code>for line in output: print(line) </code></pre> <p>I get an output like this:</p> <p>t</p> <p>e</p> <p>r</p> <p>m</p> <p>i</p> <p>n</p> <p>a</p> <p>l</p> <p>l</p> <p>e</p> <p>n</p> <p>g</p> <p>t</p> <p>h</p> <p>0</p> <p>Any way around this?</p> <p>Again,</p> <p>Thanks in advance for any help.</p> <p>Best regards,</p> <p>Aaron C.</p>
-1
2016-10-17T19:46:46Z
40,095,135
<p>If you can, the <code>exec_command()</code> call provides a simpler mechanism to invoke a command. I have seen Cisco switches abruptly drop connections that try <code>exec_command()</code>, so that may not be usable with Brocade devices.</p> <p>If you must go the <code>invoke_shell()</code> route, be sure to clear all pending output after connecting and after <code>send('terminal length 0\n')</code>, checking <code>recv_ready()</code> before calling <code>recv()</code> to avoid blocking on reading data that might not ever arrive. Since you are controlling an interactive shell, <code>sleep()</code> calls might be needed to allow the server adequate time to process and send data, or it might be necessary to poll the output string to confirm that your last command completed by recognizing the shell prompt string.</p>
0
2016-10-17T20:30:23Z
[ "python", "python-2.7", "ssh", "paramiko" ]
Paramiko capturing command output
40,094,461
<p>I have an issue that has been giving me a headache for a few days. I am using the Paramiko module with Python 2.7.10 and I'd like to issue multiple commands to a Brocade router, but only return output from one of the given commands like so:</p> <pre><code>#!/usr/bin/env python import paramiko, time router = 'r1.test.example.com' password = 'password' username = 'testuser' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(router, username=username, password=password) print('Successfully connected to %s' % router) remote_conn = ssh.invoke_shell() output = remote_conn.recv(1000) # Disable paging on Brocade. remote_conn.send('terminal length 0\n') # Check interface status. remote_conn.send('show interfaces ethernet 0/1\n') # I only want output from this command. time.sleep(2) output = remote_conn.recv(5000) print(output) </code></pre> <p>If I were to print the full output it would contain everything issued to the router, but I only want to see output from the show <code>interfaces ethernet 0/1\n</code> command.</p> <p>Can anyone help with this issue?</p> <p>One final thing I would like to ask. I want to filter through the <code>output</code> variable and check for occurrences of strings like "up" or "down", but I can't seem to get it to work because everything in the output appears to be on new lines?</p> <p>For example:</p> <p>If I iterate over the <code>output</code> variable in a for loop I get all of the characters in the variable like so:</p> <pre><code>for line in output: print(line) </code></pre> <p>I get an output like this:</p> <p>t</p> <p>e</p> <p>r</p> <p>m</p> <p>i</p> <p>n</p> <p>a</p> <p>l</p> <p>l</p> <p>e</p> <p>n</p> <p>g</p> <p>t</p> <p>h</p> <p>0</p> <p>Any way around this?</p> <p>Again,</p> <p>Thanks in advance for any help.</p> <p>Best regards,</p> <p>Aaron C.</p>
-1
2016-10-17T19:46:46Z
40,095,538
<p>After reading all of the comment I have made the following changes:</p> <pre><code>#!/usr/bin/env python import paramiko, time router = 'r2.test.example.com' password = 'password' username = 'testuser' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(router, username=username, password=password) print('Successfully connected to %s' % router) remote_conn = ssh.invoke_shell() output = remote_conn.recv(1000) # Disable paging on Brocade. remote_conn.send('terminal length 0\n') time.sleep(2) # Clearing output. if remote_conn.recv_ready(): output = remote_conn.recv(1000) # Check interface status. remote_conn.send('show interfaces ethernet 4/1\n') # I only want output from this command. time.sleep(2) # Getting output I want. if remote_conn.recv_ready(): output = remote_conn.recv(5000) print(output) # Test: Check if interface is up. for line in output.split('\n'): if 'line protocol is up' in line: print(line) </code></pre> <p>Everything works great now.</p> <p>Thank you for all the help.</p> <p>Best regards,</p> <p>Aaron C.</p>
0
2016-10-17T20:58:41Z
[ "python", "python-2.7", "ssh", "paramiko" ]
Why does adding parenthesis around a yield call in a generator allow it to compile/run?
40,094,470
<p>I have a method:</p> <pre><code>@gen.coroutine def my_func(x): return 2 * x </code></pre> <p>basically, a tornado coroutine.</p> <p>I am making a list such as:</p> <pre><code>my_funcs = [] for x in range(0, 10): f = yield my_func(x) my_funcs.append(x) </code></pre> <p>In trying to make this a list comprehension such as:</p> <pre><code>my_funcs = [yield my_func(i) for i in range(0,10)] </code></pre> <p>I realized this was invalid syntax. It <a href="http://chat.stackoverflow.com/transcript/message/33540588#33540588">turns out you can do this</a> using <code>()</code> around the yield:</p> <pre><code>my_funcs = [(yield my_func(i)) for i in range(0,10)] </code></pre> <ul> <li>Does this behavior (the syntax for wrapping a <code>yield foo()</code> call in () such as <code>(yield foo() )</code> in order to allow this above code to execute) have a specific type of name? <ul> <li>Is it some form of operator precedence with <code>yield</code>?</li> </ul></li> <li>Is this behavior with <code>yield</code> documented somewhere?</li> </ul> <p>Python 2.7.11 on OSX. This code does need to work in both Python2/3 which is why the above list comprehension is not a good idea (see <a href="http://stackoverflow.com/a/32139977/1048539">here</a> for why, the above list comp works in Python 2.7 but is broken in Python 3).</p>
5
2016-10-17T19:47:19Z
40,094,628
<p><code>yield</code> expressions must be parenthesized in any context except as an entire statement or as the right-hand side of an assignment:</p> <pre><code># If your code doesn't look like this, you need parentheses: yield x y = yield x </code></pre> <p>This is stated in the <a href="https://www.python.org/dev/peps/pep-0342/" rel="nofollow">PEP that introduced <code>yield</code> expressions</a> (as opposed to <code>yield</code> statements), and it's implied by the contexts in which <code>yield_expr</code> appears in the <a href="https://docs.python.org/2/reference/grammar.html" rel="nofollow">grammar</a>, although no one is expecting you to read the grammar:</p> <blockquote> <p>A yield-expression must always be parenthesized except when it occurs at the top-level expression on the right-hand side of an assignment.</p> </blockquote>
5
2016-10-17T19:57:18Z
[ "python", "python-2.7", "tornado", "coroutine" ]
Provisioning CoreOS with Ansible pip error
40,094,550
<p>I am trying to provision a coreOS box using Ansible. First a bootstapped the box using <a href="https://github.com/defunctzombie/ansible-coreos-bootstrap" rel="nofollow">https://github.com/defunctzombie/ansible-coreos-bootstrap</a></p> <p>This seems to work ad all but pip (located in /home/core/bin) is not added to the path. In a next step I am trying to run a task that installs docker-py:</p> <pre><code>- name: Install docker-py pip: name=docker-py </code></pre> <p>As pip's folder is not in path I did it using ansible:</p> <pre><code> environment: PATH: /home/core/bin:$PATH </code></pre> <p>If I am trying to execute this task I get the following error:</p> <p>fatal: [192.168.0.160]: FAILED! => {"changed": false, "cmd": "/home/core/bin/pip install docker-py", "failed": true, "msg": "\n:stderr: /home/core/bin/pip: line 2: basename: command not found\n/home/core/bin/pip: line 2: /root/pypy/bin/: No such file or directory\n"}</p> <p>what I ask is where does <code>/root/pypy/bin/</code> come from it seems this is the problem. Any idea?</p>
0
2016-10-17T19:51:27Z
40,096,277
<p>You can't use shell-style variable expansion when setting Ansible variables. In this statement...</p> <pre><code>environment: PATH: /home/core/bin:$PATH </code></pre> <p>...you are setting your <code>PATH</code> environment variable to the <em>literal</em> value <code>/home/core/bin:$PATH</code>. In other words, you are blowing away any existing value of <code>$PATH</code>, which is why you're getting "command not found" errors for basic things like <code>basename</code>.</p> <p>Consider installing <code>pip</code> somewhere in your existing <code>$PATH</code>, modifying <code>$PATH</code> <em>before</em> calling ansible, or calling <code>pip</code> from a shells cript:</p> <pre><code>- name: install something with pip shell: | PATH="/home/core/bin:$PATH" pip install some_module </code></pre>
1
2016-10-17T21:52:56Z
[ "python", "pip", "ansible", "ansible-playbook", "coreos" ]
Connection Refused When Connecting to Elasticsearch Remotely
40,094,586
<p>I'm trying to use elasticsearch-py to connect to my server, but I'm having some serious issues. For whatever reason, when I pass in the credentials through python my connection is being refused.</p> <p>Initially, I thought it could be a result of nginx configurations or bad certificates, but updating these did not improve the situation. I can log into the server from the browser, curl, or my phone using RFC-1738 formatted URLs (<a href="http://user:[email protected]/space" rel="nofollow">http://user:[email protected]/space</a>)</p> <p>What else can I try?</p>
1
2016-10-17T19:54:14Z
40,094,646
<p>In <code>config/elasticsearch.yml</code> put</p> <pre><code>network.host: 0.0.0.0 </code></pre> <p>to allow access from remote system. OR, replace <code>0.0.0.0</code> with the IP of the network/sub-network you would be using for accessing the Elastic Search.</p>
1
2016-10-17T19:58:24Z
[ "python", "elasticsearch", "connection" ]
How to get a list of matchable characters from a regex class
40,094,588
<p>Given a regex character class/set, how can i get a list of all matchable characters (in python 3). E.g.:</p> <pre><code>[\dA-C] </code></pre> <p>should give</p> <pre><code>['0','1','2','3','4','5','6','7','8','9','A','B','C'] </code></pre>
3
2016-10-17T19:54:32Z
40,094,676
<pre><code>import re x = '123456789ABCDE' pattern = r'[\dA-C]' print(re.findall(pattern,x)) #prints ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C'] </code></pre> <p>Is this what you are looking for? </p> <p>If you don't have <code>x</code> and just want to match ascii characters you can use :</p> <pre><code>import re import string x = string.ascii_uppercase + string.digits pattern = r'[\dA-C]' print(re.findall(pattern,x)) </code></pre> <p>If you want to take inputs for the pattern you can simply just do:</p> <pre><code> pattern = input() #with either one from above </code></pre>
2
2016-10-17T19:59:57Z
[ "python", "regex", "python-3.x" ]
How to get a list of matchable characters from a regex class
40,094,588
<p>Given a regex character class/set, how can i get a list of all matchable characters (in python 3). E.g.:</p> <pre><code>[\dA-C] </code></pre> <p>should give</p> <pre><code>['0','1','2','3','4','5','6','7','8','9','A','B','C'] </code></pre>
3
2016-10-17T19:54:32Z
40,094,825
<p>I think what you are looking for is <a href="https://docs.python.org/2/library/string.html#string.printable" rel="nofollow"><code>string.printable</code></a> which returns all the printable characters in Python. For example:</p> <pre><code>&gt;&gt;&gt; import string &gt;&gt;&gt; string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\\]^_`{|}~ \t\n\r\x0b\x0c' </code></pre> <p>Now to check content satisfied by your regex, you may do:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; x = string.printable &gt;&gt;&gt; pattern = r'[\dA-C]' &gt;&gt;&gt; print(re.findall(pattern, x)) ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C'] </code></pre> <p><code>string.printable</code> is a combination of <em>digits, letters, punctuation,</em> and <em>whitespace</em>. Also check <a href="https://docs.python.org/2/library/string.html#string-constants" rel="nofollow">String Constants</a> for complete list of constants available with <a href="https://docs.python.org/2/library/string.html" rel="nofollow">string</a> module.</p> <hr> <p><em>In case you need the list of all <code>unicode</code> characters</em>, you may do:</p> <pre><code>import sys unicode_list = [chr(i) for i in range(sys.maxunicode)] </code></pre> <p><strong>Note:</strong> It will be a huge list, and console might get stuck for a while to give the result as value of <code>sys.maxunicode</code> is:</p> <pre><code>&gt;&gt;&gt; sys.maxunicode 1114111 </code></pre> <p>In case you are dealing with some specific unicode formats, refer <a href="http://billposer.org/Linguistics/Computation/UnicodeRanges.html" rel="nofollow">Unicode Character Ranges</a> for limiting the ranges you are interested in.</p>
7
2016-10-17T20:08:55Z
[ "python", "regex", "python-3.x" ]
How to get a list of matchable characters from a regex class
40,094,588
<p>Given a regex character class/set, how can i get a list of all matchable characters (in python 3). E.g.:</p> <pre><code>[\dA-C] </code></pre> <p>should give</p> <pre><code>['0','1','2','3','4','5','6','7','8','9','A','B','C'] </code></pre>
3
2016-10-17T19:54:32Z
40,095,866
<p>You probably hoped to just extract them from the regexp itself, but it's not that easy: Consider specifications like <code>\S</code>, which doesn't match a contiguous range of characters, negated specifications like <code>[^abc\d]</code>, and of course goodies like <code>(?![aeiou])\w</code> (which matches any single letter <em>except</em> the five vowels given). So it's far simpler to just try out each candidate character against your regexp.</p> <p>But checking all Unicode codepoints is not very practical, both because of the large number of tests and because the result could be a very large list: A character class regexp might contain specifications like <code>\w</code>, which can match an enormous number of characters from all over the Unicode table. Or it could contain a negated specification like <code>[^abc\d]</code>, which matches even more. So let's assume that you can restrict your interest to a particular subset of the Unicode range. After consulting a <a href="https://en.wikipedia.org/wiki/Unicode_block#collapsibleTable0" rel="nofollow">table of Unicode ranges</a>, you might decide, for the sake of example, that you are interested in the ranges [0000-024F] (Basic and Extended Latin) and [0590-074F] (Hebrew and Arabic).</p> <p>You can then churn through each of these unicode codepoints, checking which ones are matched by your regexp:</p> <pre><code>import re myregexp = r"[\dA-C]" interest = [ (0x0000, 0x024F), (0x0590, 0x06FF) ] pattern = re.compile(myregexp) matched = [] for low, high in interest: matched.extend(chr(p) for p in range(low, high+1) if pattern.match(chr(p))) &gt;&gt;&gt; print("".join(matched)) 0123456789ABC٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹ </code></pre>
3
2016-10-17T21:22:36Z
[ "python", "regex", "python-3.x" ]
python dice rolling restart script
40,094,671
<p>i want to restart my script automatically i have a dice rolling script and i don't want to have to reset my script manually between each roll this is my script. </p> <pre><code>import random from random import randrange from random import randint r = randint min = 1 max = 6 rolls = int(float(input('how menny times do you want to roll:'))) for x in range(rolls): print ('Rolling the dices...') print ('The value is....') print (r(min, max)) </code></pre> <p>i have tried a few ways to do it but none of them worked</p>
-3
2016-10-17T19:59:43Z
40,096,792
<p>I'm not 100% sure what you were actually trying to do, but here is a program that I wrote that will roll 2 die at a time, and will generate however many rolls you would like to roll. -not the best practice to use recursive (main calls main from within itself), but it's not really an issue with something this basic.</p> <p>*replace raw_input with input if you are using Python 3+. I use 2.7 so I use raw_input</p> <pre><code>import time import random def roll_multiple(): #honestly this is all you need to do what you want to do, the rest just turns it into a game and allows multiple runs roll_number = int(raw_input("How Many Times Would You Like to Roll?\n")) for i in range(roll_number): print"You Rolled A ", random.randrange(1,6,1), " and a ", random.randrange(1,6,1) #that's it! if you do these 3 lines, it will ask for how many times, and for each item in range of roll_number (whatever you input) it will run the print below and generate new numbers for each roll. def main(): print("Welcome to Craps 2.0") playing = raw_input("Press Enter to Roll or Q to quit") if playing == 'q': print("Thanks for Playing") time.sleep(2) quit() elif playing != 'q': roll_multiple() main() main() </code></pre>
0
2016-10-17T22:42:06Z
[ "python" ]
Concating CSV files but Filtering Duplicates by 2 Columns
40,094,735
<p>I have a csv I want to update based on certain criteria. Example: </p> <pre><code>csv: Name UniqueID Status Apple 1121 Full Orange 1122 Eaten Apple 1123 Rotten </code></pre> <p>New values (also in a csv):</p> <pre><code>csv1: Apple 1121 Eaten orange 1122 Eaten Pear 1233 Wiggly </code></pre> <p>the updated csv would look like this:</p> <pre><code>Name UniqueID Status Apple 1121 Full Orange 1122 Eaten Apple 1123 Rotten Pear 1233 Wiggly Apple 1121 Eaten </code></pre> <p>So basically skip the entries that have the same <code>UniqueID</code> and <code>Status</code>. If it's a new <code>UniqueID</code> or an existing <code>UniqueID</code> and a different <code>Status</code> I want it included as a separate row. So from the above example <code>orange 1122 Eaten</code>, was excluded. </p> <p>I tried converting the csv to a DataFrame and using the <code>drop_duplicates</code>. </p> <p><code>data = pd.concat([pd.DataFrame.from_csv(csv, csv1)].drop_duplicates(subset=['Status', 'UniqueID'])</code></p> <p>But it predictably dropped all the duplicates. Which resulted in:</p> <pre><code> Name UniqueID Status Apple 1121 Full Orange 1122 Eaten Apple 1123 Rotten Pear 1233 Wiggly # Apple 1121 Eaten &lt;-- this result was excluded </code></pre>
0
2016-10-17T20:03:22Z
40,095,557
<pre> cat csv csv1 | awk '{if (!status[$2] || status[$2]!=$3) {print $0; status[$2]=$3} }' </pre> <p><strong>explanation</strong></p> <p>print these files in sequence and iterete line by line</p> <p><code>cat csv csv1 | awk '{</code> </p> <p>Keep second column (<code>unique id</code>) in an array key and the third one column as the value. Then check, if the array element doesn't exists (it means this is first occurence of that row) OR value is not equal to the third one (it means that value has changed)</p> <p><code>if (!status[$2] || status[$2]!=$3) {</code></p> <p>then simply print the row and set the array value</p> <p><code>print $0;</code> <code>status[$2]=$3</code></p> <p>if ends</p> <p><code>}</code></p> <p>awk ends <code>}'</code></p>
0
2016-10-17T20:59:47Z
[ "python", "csv", "pandas", "dataframe" ]
Concating CSV files but Filtering Duplicates by 2 Columns
40,094,735
<p>I have a csv I want to update based on certain criteria. Example: </p> <pre><code>csv: Name UniqueID Status Apple 1121 Full Orange 1122 Eaten Apple 1123 Rotten </code></pre> <p>New values (also in a csv):</p> <pre><code>csv1: Apple 1121 Eaten orange 1122 Eaten Pear 1233 Wiggly </code></pre> <p>the updated csv would look like this:</p> <pre><code>Name UniqueID Status Apple 1121 Full Orange 1122 Eaten Apple 1123 Rotten Pear 1233 Wiggly Apple 1121 Eaten </code></pre> <p>So basically skip the entries that have the same <code>UniqueID</code> and <code>Status</code>. If it's a new <code>UniqueID</code> or an existing <code>UniqueID</code> and a different <code>Status</code> I want it included as a separate row. So from the above example <code>orange 1122 Eaten</code>, was excluded. </p> <p>I tried converting the csv to a DataFrame and using the <code>drop_duplicates</code>. </p> <p><code>data = pd.concat([pd.DataFrame.from_csv(csv, csv1)].drop_duplicates(subset=['Status', 'UniqueID'])</code></p> <p>But it predictably dropped all the duplicates. Which resulted in:</p> <pre><code> Name UniqueID Status Apple 1121 Full Orange 1122 Eaten Apple 1123 Rotten Pear 1233 Wiggly # Apple 1121 Eaten &lt;-- this result was excluded </code></pre>
0
2016-10-17T20:03:22Z
40,096,924
<p><strong><em>setup</em></strong> </p> <pre><code>import pandas as pd from StringIO import StringIO csv = """Name UniqueID Status Apple 1121 Full Orange 1122 Eaten Apple 1123 Rotten""" csv1 = """Name UniqueID Status Apple 1121 Eaten Orange 1122 Eaten Pear 1233 Wiggly """ </code></pre> <p><strong><em>option 1</em></strong><br> <code>set_index</code> + <code>combine_first</code> + <code>reduce</code></p> <pre><code>def fruit_status1(f): return pd.read_csv(StringIO(f), delim_whitespace=True, index_col=['UniqueID', 'Status']) def update1(d1, d2): return d2.combine_first(d1) reduce(update1, [fruit_status1(f) for f in [csv, csv1]]) </code></pre> <p><a href="https://i.stack.imgur.com/TGIDG.png" rel="nofollow"><img src="https://i.stack.imgur.com/TGIDG.png" alt="enter image description here"></a></p> <p><strong><em>option 2</em></strong><br> <code>pd.concat</code> + <code>drop_duplicates</code></p> <pre><code>def fruit_status2(f): return pd.read_csv(StringIO(f), delim_whitespace=True) pd.concat([fruit_status2(f) for f in [csv, csv1]]) \ .drop_duplicates(subset=['UniqueID', 'Status']) </code></pre> <p><a href="https://i.stack.imgur.com/NoI8w.png" rel="nofollow"><img src="https://i.stack.imgur.com/NoI8w.png" alt="enter image description here"></a></p>
0
2016-10-17T22:56:11Z
[ "python", "csv", "pandas", "dataframe" ]
Python equivalent of Perl Digest::MD5 functions
40,094,746
<p>As part of a work project I am porting a Perl library to Python. I'm comfortable with Python, much (much) less so with Perl.</p> <p>The perl code uses <a href="https://metacpan.org/pod/Digest::MD5" rel="nofollow">Digest::MD5</a>. This module has three functions:</p> <ul> <li><code>md5($data)</code> takes in data and spits out md5 digest in <em>binary</em></li> <li><code>md5_hex($data)</code> takes in data and spits out md5 digest in <em>hex</em></li> <li><code>md5_base64($data)</code> takes in data and spits out md5 digest in base64 encoding</li> </ul> <p>I can replicate md5_hex with something like this:</p> <pre><code>import hashlib string = 'abcdefg' print(hashlib.md5(string.encode()).hexdigest()) </code></pre> <p>Which works fine (same inputs give same outputs at least). I can't seem to get anything to match for the other two functions. </p> <p>It doesn't help that string encodings are really not something I've done much with. I've been interpreting the perl functions as saying they take an md5 digest and then re-encode in binary or base64, something like this:</p> <pre><code>import hashlib import base64 string = 'abcdefg' md5_string = hashlib.md5(string.encode()).hexdigest() print(base64.b64encode(md5_string)) </code></pre> <p>but maybe that's wrong? I'm sure there's something fundamental I'm just missing. </p> <p>The Perl doc is here: <a href="https://metacpan.org/pod/Digest::MD5" rel="nofollow">https://metacpan.org/pod/Digest::MD5</a></p>
0
2016-10-17T20:03:41Z
40,094,887
<p>The first one would simply be calling <code>.digest</code> method on the <code>md5</code>:</p> <pre><code>&gt;&gt;&gt; from hashlib import md5 &gt;&gt;&gt; s = 'abcdefg' &gt;&gt;&gt; md5(s.encode()).digest() b'z\xc6l\x0f\x14\x8d\xe9Q\x9b\x8b\xd2d1,Md' </code></pre> <p>And <code>md5_base64</code> is the digest but base64-encoded:</p> <pre><code>&gt;&gt;&gt; base64.b64encode(md5(s.encode()).digest()) b'esZsDxSN6VGbi9JkMSxNZA==' </code></pre> <p>However, Perl doesn't return the hash padded, thus to be compatible, you'd strip the <code>=</code> padding characters:</p> <pre><code>&gt;&gt;&gt; base64.b64encode(md5(s.encode()).digest()).strip(b'=') b'esZsDxSN6VGbi9JkMSxNZA' </code></pre>
3
2016-10-17T20:13:37Z
[ "python", "string", "perl", "encoding", "md5" ]
Python equivalent of Perl Digest::MD5 functions
40,094,746
<p>As part of a work project I am porting a Perl library to Python. I'm comfortable with Python, much (much) less so with Perl.</p> <p>The perl code uses <a href="https://metacpan.org/pod/Digest::MD5" rel="nofollow">Digest::MD5</a>. This module has three functions:</p> <ul> <li><code>md5($data)</code> takes in data and spits out md5 digest in <em>binary</em></li> <li><code>md5_hex($data)</code> takes in data and spits out md5 digest in <em>hex</em></li> <li><code>md5_base64($data)</code> takes in data and spits out md5 digest in base64 encoding</li> </ul> <p>I can replicate md5_hex with something like this:</p> <pre><code>import hashlib string = 'abcdefg' print(hashlib.md5(string.encode()).hexdigest()) </code></pre> <p>Which works fine (same inputs give same outputs at least). I can't seem to get anything to match for the other two functions. </p> <p>It doesn't help that string encodings are really not something I've done much with. I've been interpreting the perl functions as saying they take an md5 digest and then re-encode in binary or base64, something like this:</p> <pre><code>import hashlib import base64 string = 'abcdefg' md5_string = hashlib.md5(string.encode()).hexdigest() print(base64.b64encode(md5_string)) </code></pre> <p>but maybe that's wrong? I'm sure there's something fundamental I'm just missing. </p> <p>The Perl doc is here: <a href="https://metacpan.org/pod/Digest::MD5" rel="nofollow">https://metacpan.org/pod/Digest::MD5</a></p>
0
2016-10-17T20:03:41Z
40,094,894
<p>First, note <a href="https://metacpan.org/pod/Digest::MD5" rel="nofollow">Digest::MD5</a> documentation:</p> <blockquote> <p>Note that the base64 encoded string returned is not padded to be a multiple of 4 bytes long. If you want interoperability with other base64 encoded md5 digests you might want to append the redundant string "==" to the result.</p> </blockquote> <p>Second, note that you want to Base64 encode the hash, not the hex representation of it:</p> <pre><code>print(base64.b64encode(hashlib.md5(string.encode()).digest())) </code></pre> <blockquote> <p><code>esZsDxSN6VGbi9JkMSxNZA==</code></p> </blockquote> <pre><code>perl -MDigest::MD5=md5_base64 -E 'say md5_base64($ARGV[0])' abcdefg </code></pre> <blockquote> <p><code>esZsDxSN6VGbi9JkMSxNZA</code></p> </blockquote>
0
2016-10-17T20:14:03Z
[ "python", "string", "perl", "encoding", "md5" ]
Matplotlib Add Space Betwen Lines and left and right axes
40,094,762
<p>Given the following line graph:</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.ticker import FuncFormatter, MaxNLocator fig = plt.figure() ax = fig.add_subplot(111) xs = range(26) ys = range(26) labels = list('abcdefghijklmnopqrstuvwxyz') def format_fn(tick_val, tick_pos): if int(tick_val) in xs: return labels[int(tick_val)] else: return '' ax.xaxis.set_major_formatter(FuncFormatter(format_fn)) ax.xaxis.set_major_locator(MaxNLocator(integer=True)) ax.plot(xs, ys) plt.show() </code></pre> <p>How can I add space between the left end of the line and the left y-axis and the same for the right side? For example, there should be space between the 0 on the bottom of the y-axis and the 'a' on the left side of the x-axis.</p> <p>Thanks in advance!</p>
0
2016-10-17T20:05:07Z
40,104,812
<p>I guess the easiest would be to add a <code>ax.margins(margin)</code> call, where <code>margin</code> is a float between <code>0</code> and <code>1</code> that multiplied by the plot dimensions (width and height) gives the margin size it will be added.</p> <p>Not sure how it fares with non trivial layouts (subplots, tight layout) but seems to work pretty well with your example.</p>
0
2016-10-18T09:42:50Z
[ "python", "matplotlib" ]
Error while trying to port a repo from github
40,094,800
<p>There is a github code I am trying to use that is located <a href="https://github.com/PX4/pyulog" rel="nofollow">here</a>.</p> <p>I am trying to run <code>params.py</code> which is a code that will take a binary file and converts it so that I can plot it (or so I think).</p> <p>I tried to run:</p> <pre><code>pip install git+https://github.com/PX4/pyulog.git </code></pre> <p>However, that gave me an error:</p> <pre><code>C:\Users\Mike\Documents&gt;pip install git+https://github.com/PX4/pyulog.git Collecting git+https://github.com/PX4/pyulog.git Cloning https://github.com/PX4/pyulog.git to c:\users\mike\appdata\local\temp\pip-t_vvh_b0-build Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Anaconda3\lib\tokenize.py", line 454, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Mike\\AppData\\Local\\Temp\\pip-t_vvh_b0-build\\setup.py' </code></pre>
0
2016-10-17T20:07:15Z
40,094,908
<p>Pip install tries to install the module from :</p> <ul> <li>PyPI (and other indexes) using requirement specifiers. </li> <li>VCS project urls. </li> <li>Local project directories. </li> <li>Local or remote source archives.</li> </ul> <p>When looking at the items to be installed, pip checks what type of item each is, in the following order:</p> <ul> <li>Project or archive URL.</li> <li>local directory (which must contain a <strong>setup.py</strong>, or pip will report an error).</li> <li>Local file (a sdist or wheel format archive, following the naming conventions for those formats).</li> <li>A requirement, as specified in PEP 440.</li> </ul> <p>In your case, git repo doesn't meet the requirement. It doesn't have setup.py that's why you get the error.<br> Instead try cloning the repo on your local machine.</p>
1
2016-10-17T20:15:13Z
[ "python" ]
Django Rest Framework invalid username/password
40,094,823
<p>Trying to do a simple '<strong>GET</strong>' wih admin credentials returns</p> <blockquote> <p>"detail": "Invalid username/password."</p> </blockquote> <p>I have a <em>custom user model</em> where I deleted the <strong>username</strong>, instead I use <strong>facebook_id</strong> :</p> <pre><code>USERNAME_FIELD = 'facebook_id' </code></pre> <hr> <p>I tried changing the <em>DEFAULT_PERMISSION_CLASSES</em>:</p> <pre><code>('rest_framework.permissions.IsAuthenticated',), -- doesn't work! ('rest_framework.permissions.IsAdminUser',), -- doesn't work! </code></pre> <p>The only one that works is:</p> <pre><code>('rest_framework.permissions.AllowAny',), </code></pre> <p>But I do not want that, since I'm building an API for a Mobile App</p> <p>I also declared a <em>CustomUserAdmin</em> model and <em>CustomUserCreationForm</em> , apparently this was not the problem</p> <hr> <p>Help me understand what needs to be done to fix this annoying problem, I'm guessing it might have something to do with <strong>Permissions/Authentication</strong> or the fact that I CustomUserModel..</p> <p>Also, let me know if there is a better way for a mobile app client to authenticate to the api</p>
2
2016-10-17T20:08:47Z
40,094,986
<p>You have the default, and then you have per view. You can set the default to <code>IsAuthenticated</code>, and then you override your view's particular <code>permission_classes</code>. e.g.</p> <pre><code>class ObtainJSONWebLogin(APIView): permission_classes = () </code></pre> <p>or </p> <pre><code>class Foo(viewsets.ModelViewSet): permission_classes = () </code></pre>
0
2016-10-17T20:20:19Z
[ "python", "django", "api", "django-rest-framework" ]
Find all cycles in directed and undirected graph
40,094,835
<p>I want to be able to find all cycles in a directed and an undirected graph. </p> <p>The below code returns True or False if a cycle exists or not in a directed graph:</p> <pre><code>def cycle_exists(G): color = { u : "white" for u in G } found_cycle = [False] for u in G: if color[u] == "white": dfs_visit(G, u, color, found_cycle) if found_cycle[0]: break return found_cycle[0] def dfs_visit(G, u, color, found_cycle): if found_cycle[0]: return color[u] = "gray" for v in G[u]: if color[v] == "gray": found_cycle[0] = True return if color[v] == "white": dfs_visit(G, v, color, found_cycle) color[u] = "black" </code></pre> <p>The below code returns True or False if a cycle exists or not in an undirected graph:</p> <pre><code>def cycle_exists(G): marked = { u : False for u in G } found_cycle = [False] for u in G: if not marked[u]: dfs_visit(G, u, found_cycle, u, marked) if found_cycle[0]: break return found_cycle[0] def dfs_visit(G, u, found_cycle, pred_node, marked): if found_cycle[0]: return marked[u] = True for v in G[u]: if marked[v] and v != pred_node: found_cycle[0] = True return if not marked[v]: dfs_visit(G, v, found_cycle, u, marked) graph_example = { 0 : [1], 1 : [0, 2, 3, 5], 2 : [1], 3 : [1, 4], 4 : [3, 5], 5 : [1, 4] } </code></pre> <p>How do I use these to find all the cycles that exist in a directed and undirected graph?</p>
0
2016-10-17T20:09:30Z
40,095,367
<p>If I understand well, your problem is to use one unique algorithm for directed and undirected graph. </p> <p>Why can't you use the algorithm to check for directed cycles on undirected graph? <strong>Non-directed graphs are a special case of directed graphs</strong>. You can just consider that a undirected edge is made from one forward and backward directed edge. </p> <p>But, this is not very efficient. Generally, the statement of your problem will indicate if the graph is or not directed. </p>
0
2016-10-17T20:45:07Z
[ "python", "graph", "graph-theory", "dfs" ]
Exception Value: object of type 'PolymorphicModelBase' has no len()
40,094,839
<p>I am converting existing models/admin over to django-polymorphic. I think I have the models and migrations done successfully (at least, it's working in the shell) but I can't get the admin to work. I'm finding the <a href="http://django-polymorphic.readthedocs.io/en/stable/admin.html#setup" rel="nofollow">documentation</a> a little fuzzy, but I think I've followed it correctly.</p> <pre><code>class LibraryItemAdmin(PolymorphicParentModelAdmin): base_model = LibraryItem child_models = (Whitepaper) class LibraryItemChildAdmin(PolymorphicChildModelAdmin): base_model = LibraryItem class WhitepaperAdmin(LibraryItemChildAdmin): form = LibraryForm base_model = Whitepaper </code></pre> <p>I don't understand the issue:</p> <pre><code>Traceback: File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 108. response = middleware_method(request) File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/middleware/common.py" in process_request 74. if (not urlresolvers.is_valid_path(request.path_info, urlconf) and File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in is_valid_path 646. resolve(path, urlconf) File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve 521. return get_resolver(urlconf).resolve(path) File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve 365. for pattern in self.url_patterns: File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in url_patterns 401. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in urlconf_module 395. self._urlconf_module = import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py" in import_module 37. __import__(name) File "/srv/www/urls.py" in &lt;module&gt; 349. url(r'^admin/', include(admin.site.urls), name='admin'), File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in urls 291. return self.get_urls(), 'admin', self.name File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in get_urls 275. url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)), File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in urls 631. return self.get_urls() File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/polymorphic/admin/parentadmin.py" in get_urls 283. self._lazy_setup() File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/polymorphic/admin/parentadmin.py" in _lazy_setup 92. self._compat_mode = len(child_models) and isinstance(child_models[0], (list, tuple)) Exception Type: TypeError at /admin/library Exception Value: object of type 'PolymorphicModelBase' has no len() </code></pre>
0
2016-10-17T20:09:46Z
40,095,187
<p>Documentation is out of date. Bad docs. Bad.</p> <p>child_models should be an iterable of (Model, ModelAdmin) tuples.</p> <p><a href="https://github.com/django-polymorphic/django-polymorphic/issues/227" rel="nofollow">https://github.com/django-polymorphic/django-polymorphic/issues/227</a></p>
0
2016-10-17T20:33:58Z
[ "python", "django", "django-polymorphic" ]
Numpy: how I can determine if all elements of numpy array are equal to a number
40,094,938
<p>I need to know if all the elements of an array of <code>numpy</code> are equal to a number</p> <p>It would be like:</p> <pre><code>numbers = np.zeros(5) # array[0,0,0,0,0] print numbers.allEqual(0) # return True because all elements are 0 </code></pre> <p>I can make an algorithm but, there is some method implemented in <code>numpy</code> library?</p>
0
2016-10-17T20:17:10Z
40,094,955
<p>You can break that down into <code>np.all()</code>, which takes a boolean array and checks it's all <code>True</code>, and an equality comparison:</p> <pre><code>np.all(numbers == 0) # or equivalently (numbers == 0).all() </code></pre>
5
2016-10-17T20:18:22Z
[ "python", "arrays", "numpy" ]
Categorical variables in pipeline
40,095,008
<p>I want to apply a pipeline with numeric &amp; categorical variables as below</p> <pre><code>import numpy as np import pandas as pd from sklearn import linear_model, pipeline, preprocessing from sklearn.feature_extraction import DictVectorizer df = pd.DataFrame({'a':range(12), 'b':[1,2,3,1,2,3,1,2,3,3,1,2], 'c':['a', 'b', 'c']*4, 'd': ['m', 'f']*6}) y = df['a'] X = df[['b', 'c', 'd']] </code></pre> <p>I create indices for numeric </p> <pre><code>numeric = ['b'] numeric_indices = np.array([(column in numeric) for column in X.columns], dtype = bool) </code></pre> <p>&amp; for categorical variables</p> <pre><code>categorical = ['c', 'd'] categorical_indices = np.array([(column in categorical) for column in X.columns], dtype = bool) </code></pre> <p>Then i create a pipeline</p> <pre><code>regressor = linear_model.SGDRegressor() encoder = DictVectorizer(sparse = False) estimator = pipeline.Pipeline(steps = [ ('feature_processing', pipeline.FeatureUnion(transformer_list = [ #numeric ('numeric_variables_processing', pipeline.Pipeline(steps = [ ('selecting', preprocessing.FunctionTransformer(lambda data: data[:, numeric_indices])), ('scaling', preprocessing.StandardScaler(with_mean = 0.)) ])), #categorical ('categorical_variables_processing', pipeline.Pipeline(steps = [ ('selecting', preprocessing.FunctionTransformer(lambda data: data[:, categorical_indices])), ('DictVectorizer', encoder ) ])), ])), ('model_fitting', regressor) ] ) </code></pre> <p>and i get </p> <pre><code>estimator.fit(X, y) ValueError: could not convert string to float: 'f' </code></pre> <p>I know i have to apply encoder.fit() in the pipeline but don't understand how to apply it Or we hate to use <strong>preprocessing.OneHotEncoder()</strong> but again we need convert string to float</p> <p>How to improve it?</p>
0
2016-10-17T20:21:34Z
40,116,881
<p>I see just this way</p> <pre><code>import numpy as np import pandas as pd from sklearn import linear_model, metrics, pipeline, preprocessing df = pd.DataFrame({'a':range(12), 'b':[1,2,3,1,2,3,1,2,3,3,1,2], 'c':['a', 'b', 'c']*4, 'd': ['m', 'f']*6}) y = df.a num = df[['b']] cat = df[['c', 'd']] from sklearn.feature_extraction import DictVectorizer enc = DictVectorizer(sparse = False) enc_data = enc.fit_transform(cat .T.to_dict().values()) crat = pd.DataFrame(enc_data, columns=enc.get_feature_names()) X = pd.concat([crat, num], axis=1) cat_columns = ['c=a', 'c=b', 'c=c', 'd=f', 'd=m'] cat_indices = np.array([(column in cat_columns) for column in X.columns], dtype = bool) numeric_col = ['b'] num_indices = np.array([(column in numeric_col) for column in X.columns], dtype = bool) reg = linear_model.SGDRegressor() estimator = pipeline.Pipeline(steps = [ ('feature_processing', pipeline.FeatureUnion(transformer_list = [ ('categorical', preprocessing.FunctionTransformer(lambda data: data[:, cat_indices])), #numeric ('numeric', pipeline.Pipeline(steps = [ ('select', preprocessing.FunctionTransformer(lambda data: data[:, num_indices])), ('scale', preprocessing.StandardScaler()) ])) ])), ('model', reg) ] ) estimator.fit(X, y) </code></pre>
0
2016-10-18T19:50:54Z
[ "python", "pipeline", "categorical-data", "dictvectorizer" ]
Asana SQL API Asana2sql missing followers data
40,095,013
<p>I am able to successfully create and synchronize to a sqlite db using asana2sql.py. All the tables are populated, including the followers table. However, the followers table has no data. </p> <p>I haven't seen any issues in the code. Has this happened to anyone else using the asana2sql api? What could be the issue?</p>
0
2016-10-17T20:21:49Z
40,116,218
<p>It looks like that didn't make it into the library initially. There's a pull request to add it which should be resolved soon. You can work off of that branch in the meantime.</p> <p><a href="https://github.com/Asana/asana2sql/pull/3" rel="nofollow">https://github.com/Asana/asana2sql/pull/3</a></p>
0
2016-10-18T19:11:46Z
[ "python", "sqlite", "asana" ]
Fetch particular text from another file (python)
40,095,113
<p>I have a file of the following pattern:</p> <pre><code>"abcd.asxs." "alphabets" "wedf.345.po&amp;%12." "numbers" "xyhd.iu*u." "characters" "megaten4.koryaku-memo.xyz." "alphabets" "adwdbk.uyequ." "alphabets" "233432.2321." "numbers" "tytqyw.sdfhgwq." "alphabets" </code></pre> <p>I want something like:</p> <pre><code>string[0]=abcd.asxs string[1]=megaten4.koryaku-memo.xyz string[2]=tytqyw.sdfhgwq and so on.... </code></pre> <p>What code I have written is:</p> <pre><code> #!/usr/bin/python import re important = [] needed_categories = ["alphabets"] with open('file.txt') as fp: rec=fp.readlines() for line in rec: for category in needed_categories: if category in line: important.append(line) break print("\n".join(important)) </code></pre> <p>Output I get:</p> <p>"abcd.asxs." "alphabets"</p> <p>"megaten4.koryaku-memo.xy." "alphabets"</p> <p>"tytqyw.sdfhgwq." "alphabets"</p>
-3
2016-10-17T20:28:44Z
40,095,358
<p><strong>Points for your code:</strong></p> <ul> <li>You can iterate line by line using file handle directly. No need to save file data using <code>fp.readlines()</code> in list and then iterating.</li> <li>Once needed_category is found, you are directly appending complete line. That's why you are getting wrong output. You need to split line and save first element only.</li> <li>Didn't understand why you used <code>break</code>.</li> </ul> <p><strong>Working Code :</strong></p> <pre><code>important = [] needed_categories = ["alphabets"] with open('a.txt') as fp: for line in fp: temp = [] for category in needed_categories: if category in line: temp = line.split() important.append(temp[0].replace('"','').strip(".")) print((important) </code></pre> <p><strong>Output:</strong></p> <pre><code>C:\Users\dinesh_pundkar\Desktop&gt;python c.py ['abcd.asxs', 'megaten4.koryaku-memo.xyz', 'adwdbk.uyequ', 'tytqyw.sdfhgwq'] C:\Users\dinesh_pundkar\Desktop&gt; </code></pre>
0
2016-10-17T20:44:26Z
[ "python" ]
Fetch particular text from another file (python)
40,095,113
<p>I have a file of the following pattern:</p> <pre><code>"abcd.asxs." "alphabets" "wedf.345.po&amp;%12." "numbers" "xyhd.iu*u." "characters" "megaten4.koryaku-memo.xyz." "alphabets" "adwdbk.uyequ." "alphabets" "233432.2321." "numbers" "tytqyw.sdfhgwq." "alphabets" </code></pre> <p>I want something like:</p> <pre><code>string[0]=abcd.asxs string[1]=megaten4.koryaku-memo.xyz string[2]=tytqyw.sdfhgwq and so on.... </code></pre> <p>What code I have written is:</p> <pre><code> #!/usr/bin/python import re important = [] needed_categories = ["alphabets"] with open('file.txt') as fp: rec=fp.readlines() for line in rec: for category in needed_categories: if category in line: important.append(line) break print("\n".join(important)) </code></pre> <p>Output I get:</p> <p>"abcd.asxs." "alphabets"</p> <p>"megaten4.koryaku-memo.xy." "alphabets"</p> <p>"tytqyw.sdfhgwq." "alphabets"</p>
-3
2016-10-17T20:28:44Z
40,095,426
<p>change <code>important.append(line)</code> to:</p> <p><code> if line.strip().endswith('"alphabets"'): important.append(line.split(' ')[0].strip('"').strip(''')) </code></p>
0
2016-10-17T20:50:28Z
[ "python" ]
'str' object has no attribute 'sort'
40,095,127
<p>I am quite new to python and was wondering if someone could help me fix a problem. Im making an anagram checker and have run into an issue. </p> <pre><code>def anagram(): worda = input("Please choose your first word:") wordb = input("Please choose your second word:") if worda.isalpha(): print((worda),"is a word") else: print((worda),"is not a word, please try again") anagram() if wordb.isalpha(): print((wordb),"is a word") else: print((wordb),"is not a word,please try again") anagram() worda.sort wordb.sort anagram() </code></pre> <p>I get the error: AttributeError: 'str' object has no attribute 'sort'when I try to run it. </p>
-4
2016-10-17T20:29:52Z
40,095,156
<p>strings in Python are immutable, so it would make no sense for them to have a <code>sort</code> method, what you can do is use <code>sorted(worda)</code>, which returns a sorted list made out of the characters of the string.</p> <p>Then to get a string back again, you can use <code>''.join(sorted(worda))</code></p>
4
2016-10-17T20:32:09Z
[ "python" ]
'str' object has no attribute 'sort'
40,095,127
<p>I am quite new to python and was wondering if someone could help me fix a problem. Im making an anagram checker and have run into an issue. </p> <pre><code>def anagram(): worda = input("Please choose your first word:") wordb = input("Please choose your second word:") if worda.isalpha(): print((worda),"is a word") else: print((worda),"is not a word, please try again") anagram() if wordb.isalpha(): print((wordb),"is a word") else: print((wordb),"is not a word,please try again") anagram() worda.sort wordb.sort anagram() </code></pre> <p>I get the error: AttributeError: 'str' object has no attribute 'sort'when I try to run it. </p>
-4
2016-10-17T20:29:52Z
40,095,162
<p>In Python, it is not possible to sort strings in lexicographic order, since strings are immutable. Instead, you must use the <code>sorted</code> function, which takes the string, converts it to a list, and then sorts that. Once you have done that, you can use the <code>join</code> function to convert your result back into a string. </p> <pre><code>worda = "".join(sorted(worda)) </code></pre>
1
2016-10-17T20:32:29Z
[ "python" ]
'str' object has no attribute 'sort'
40,095,127
<p>I am quite new to python and was wondering if someone could help me fix a problem. Im making an anagram checker and have run into an issue. </p> <pre><code>def anagram(): worda = input("Please choose your first word:") wordb = input("Please choose your second word:") if worda.isalpha(): print((worda),"is a word") else: print((worda),"is not a word, please try again") anagram() if wordb.isalpha(): print((wordb),"is a word") else: print((wordb),"is not a word,please try again") anagram() worda.sort wordb.sort anagram() </code></pre> <p>I get the error: AttributeError: 'str' object has no attribute 'sort'when I try to run it. </p>
-4
2016-10-17T20:29:52Z
40,095,164
<p>There is no property as <code>sort</code> or any <code>sort()</code> function with <code>str</code> in Python. For sorting the <code>str</code> you can use <a href="https://docs.python.org/2/library/functions.html#sorted" rel="nofollow"><code>sorted()</code></a> as:</p> <pre><code>&gt;&gt;&gt; x = 'abcsd123ab' &gt;&gt;&gt; sorted(x) # returns list ['1', '2', '3', 'a', 'a', 'b', 'b', 'c', 'd', 's'] </code></pre> <p>If you need the result as sorted <code>string</code>, you need to explicitly <a href="https://www.tutorialspoint.com/python/string_join.htm" rel="nofollow"><code>join</code></a> it as:</p> <pre><code>&gt;&gt;&gt; ''.join(sorted(x)) '123aabbcds' </code></pre>
0
2016-10-17T20:32:34Z
[ "python" ]
finding an amount of variable in a text file by python
40,095,133
<p>I have a variable which its amount is changing every time. I like to know how can I find the line which contained the amount of my variable. I am looking something like this: but in this way it looks for the letter of "A" how can I write a command which look for its amount("100")? I tried this before</p> <pre><code>A = 100 with open ('my_file') as f: for line in f : if "A" in line: print line </code></pre>
2
2016-10-17T20:30:17Z
40,096,392
<p>Putting quotes around something makes it a String. You want to actually reference the variable which contains your number, i.e. <code>A</code> instead of <code>"A"</code></p> <pre><code>A = 100 with open('my_file') as f: for line in f: # str() converts an integer into a string for searching. if str(A) in line: print line </code></pre>
1
2016-10-17T22:02:04Z
[ "python", "variables", "text" ]
Python regular expression search text file count substring
40,095,306
<p>I am attempting to use a regular expression statement in python to search a text file and count the number of times a user defined word appears. When I run my code though, instead of getting a sum of the number of times that unique word appears in the file, I am getting a count for the number lines within that file contain that word.</p> <p>Example: the word 'apple' exists 56 times in the text file. Appearing in 20 of the total 63 lines of text. When I run my code the console prints '20' for the count of 'apple' instead of the correct '56'. </p> <p>I thought by using the re.findall() method it would fix this, but it has not.</p> <pre><code>import re #If user selects Regular Expressions as their search method elif user_search_method == "2": print "\n&gt;&gt;&gt; You selected the Regular Expressions search method" f = open(filename, 'r') words = sum(1 for w in f if re.findall(user_search_value, w, re.M|re.I)) f.close() print("Your search value of '%s' appears %s times in this file" % (user_search_value, words)) </code></pre>
0
2016-10-17T20:41:12Z
40,095,364
<p>You're just adding 1 if it matches, I guess you don't want the search to go over lines, so you can do this:</p> <pre><code>words = sum(len(re.findall(user_search_value, w, re.M|re.I)) for w in f) </code></pre>
0
2016-10-17T20:44:53Z
[ "python", "regex", "full-text-search" ]
Covariance matrix from np.polyfit() has negative diagonal?
40,095,325
<p><strong>Problem:</strong> the <code>cov=True</code> option of <code>np.polyfit()</code> produces a diagonal with non-sensical negative values.</p> <p><strong>UPDATE:</strong> after playing with this some more, I am <em>really starting to suspect a bug in numpy</em>? Is that possible? Deleting any pair of 13 values from the dataset will fix the problem.</p> <p>I am using <code>np.polyfit()</code> to calculate the slope and intercept coefficients of a dataset. A plot of the values produces a very linear (but not perfectly) linear graph. I am attempting to get the standard deviation on these coefficients with <code>np.sqrt(np.diag(cov))</code>; however, this throws an error because the diagonal contains negative values. </p> <p><em>It should be mathematically impossible to produce a covariate matrix with a negative diagonal--what is numpy doing wrong?</em></p> <p>Here is a snippet that reproduces the problem:</p> <pre><code>import numpy as np x = [1476728821.797, 1476728821.904, 1476728821.911, 1476728821.920, 1476728822.031, 1476728822.039, 1476728822.047, 1476728822.153, 1476728822.162, 1476728822.171, 1476728822.280, 1476728822.289, 1476728822.297, 1476728822.407, 1476728822.416, 1476728822.423, 1476728822.530, 1476728822.539, 1476728822.547, 1476728822.657, 1476728822.666, 1476728822.674, 1476728822.759, 1476728822.788, 1476728822.797, 1476728822.805, 1476728822.915, 1476728822.923, 1476728822.931, 1476728823.038, 1476728823.047, 1476728823.054, 1476728823.165, 1476728823.175, 1476728823.182, 1476728823.292, 1476728823.300, 1476728823.308, 1476728823.415, 1476728823.424, 1476728823.432, 1476728823.551, 1476728823.559, 1476728823.567, 1476728823.678, 1476728823.689, 1476728823.697, 1476728823.808, 1476728823.828, 1476728823.837, 1476728823.947, 1476728823.956, 1476728823.964, 1476728824.074, 1476728824.083, 1476728824.091, 1476728824.201, 1476728824.209, 1476728824.217, 1476728824.324, 1476728824.333, 1476728824.341, 1476728824.451, 1476728824.460, 1476728824.468, 1476728824.579, 1476728824.590, 1476728824.598, 1476728824.721, 1476728824.730, 1476728824.788] y = [6309927, 6310105, 6310116, 6310125, 6310299, 6310317, 6310326, 6310501, 6310513, 6310523, 6310688, 6310703, 6310712, 6310875, 6310891, 6310900, 6311058, 6311069, 6311079, 6311243, 6311261, 6311272, 6311414, 6311463, 6311479, 6311490, 6311665, 6311683, 6311692, 6311857, 6311867, 6311877, 6312037, 6312054, 6312065, 6312230, 6312248, 6312257, 6312430, 6312442, 6312455, 6312646, 6312665, 6312675, 6312860, 6312879, 6312894, 6313071, 6313103, 6313117, 6313287, 6313304, 6313315, 6313489, 6313505, 6313518, 6313675, 6313692, 6313701, 6313875, 6313888, 6313898, 6314076, 6314093, 6314104, 6314285, 6314306, 6314321, 6314526, 6314541, 6314638] z, cov = np.polyfit(np.asarray(x), np.asarray(y), 1, cov=True) std = np.sqrt(np.diag(cov)) print z print cov print std </code></pre>
0
2016-10-17T20:42:24Z
40,104,022
<p>It looks like it's related to your x values: they have a total range of about 3, with an offset of about 1.5 billion.</p> <p>In your code</p> <pre><code>np.asarray(x) </code></pre> <p>converts the x values in a ndarray of float64. While this is fine to correctly represent the x values themselves, it might not be enough to carry on the required computations to get the covariance matrix.</p> <pre><code>np.asarray(x, dtype=np.float128) </code></pre> <p>would solve the problem, but polyfit can't work with float128 :(</p> <pre><code>TypeError: array type float128 is unsupported in linalg </code></pre> <p>As a workaround, you can subtract the offset from x and then using polyfit. This produces a covariance matrix with positive diagonal:</p> <pre><code>x1 = x - np.mean(x) z1, cov1 = np.polyfit(np.asarray(x1), np.asarray(y), 1, cov=True) std1 = np.sqrt(np.diag(cov1)) print z1 # prints: array([ 1.56607841e+03, 6.31224162e+06]) print cov1 # prints: array([[ 4.56066546e+00, -2.90980285e-07], # [ -2.90980285e-07, 3.36480951e+00]]) print std1 # prints: array([ 2.13557146, 1.83434171]) </code></pre> <p>You'll have to rescale the results accordingly.</p>
1
2016-10-18T09:07:22Z
[ "python", "python-2.7", "numpy", "statistics", "linear-regression" ]
graphene django relay: Relay transform error
40,095,362
<p>Being very new to GraphQL, I have a graphene django implementation of a server with two models, following rather closely the <a href="http://docs.graphene-python.org/projects/django/en/latest/tutorial.html" rel="nofollow">graphene docs' example</a>.</p> <p>In graphiql, I can do this, and get a result back.</p> <p><a href="https://i.stack.imgur.com/TUy48.png" rel="nofollow"><img src="https://i.stack.imgur.com/TUy48.png" alt="enter image description here"></a></p> <p>Following another <a href="https://medium.com/@clayallsopp/relay-101-building-a-hacker-news-client-bb8b2bdc76e6#.vephqa6ww" rel="nofollow">relay tutorial</a>, I'm intending to render the result of this query on screen.</p> <p>My attempt looks like this:</p> <pre><code>class Note extends Component { render() { return( &lt;div&gt; {this.props.store.title} &lt;/div&gt; ) } } Note = Relay.createContainer(Note, { fragments: { store: () =&gt; Relay.QL` fragment on Query { note(id: "Tm90ZU5vZGU6MQ==") { id title } } ` } }); class NoteRoute extends Relay.Route { static routeName = 'NoteRoute'; static queries = { store: Component =&gt; { return Relay.QL` query { ${Component.getFragment('store')} } `}, }; } </code></pre> <p>My browser's console shows the following error:</p> <p><code>Uncaught Error: Relay transform error ``There are 0 fields supplied to the query named `Index`, but queries must have exactly one field.`` in file `/Users/.../src/index.js`. Try updating your GraphQL schema if an argument/field/type was recently added. </code></p> <p>I've been trying to figure it out on my own with limited success.</p> <p>Can someone point me in the right direction?</p>
0
2016-10-17T20:44:47Z
40,108,241
<p>Thanks @stubailo for pointing me in the right direction. I made some adjustments, and now have a minimum example running like this:</p> <pre><code>NoteList = Relay.createContainer(NoteList, { fragments: { store: () =&gt; Relay.QL` fragment N on NoteNodeConnection { edges { node{ id title note } } } ` } }); class NoteRoute extends Relay.Route { static routeName = 'NoteRoute'; static queries = { store: Component =&gt; { return Relay.QL` query { notes { ${Component.getFragment('store')} } } `}, }; } </code></pre>
0
2016-10-18T12:26:26Z
[ "python", "django", "reactjs", "graphql", "relay" ]
Replacing values in a column for a subset of rows
40,095,632
<p>I have a <code>dataframe</code> having multiple columns. I would like to replace the value in a column called <code>Discriminant</code>. Now this value needs to only be replaced for a few rows, whenever a condition is met in another column called <code>ids</code>. I tried various methods; The most common method seems to be using the <code>.loc</code> method, but for some reason it doesn't work for me. </p> <p>Here are the variations that I am unsuccessfully trying:</p> <p><code>encodedid</code> - variable used for condition checking</p> <p><code>indices</code> - variable used for subsetting the <code>dataframe</code> (starts from zero)</p> <p><strong>Variation 1:</strong></p> <pre><code>df[df.ids == encodedid].loc[df.ids==encodedid, 'Discriminant'].values[indices] = 'Y' </code></pre> <p><strong>Variation 2:</strong></p> <pre><code>df[df['ids'] == encodedid].iloc[indices,:].set_value('questionid','Discriminant', 'Y') </code></pre> <p><strong>Variation 3:</strong></p> <pre><code>df.loc[df.ids==encodedid, 'Discriminant'][indices] = 'Y' </code></pre> <p><code>Variation 3</code> particularly has been disappointing in that most posts on SO tend to say it should work but it gives me the following error:</p> <pre><code>ValueError: [ 0 1 2 3 5 6 7 8 10 11 12 13 14 16 17 18 19 20 21 22 23] not contained in the index </code></pre> <p>Any pointers will be highly appreciated.</p>
0
2016-10-17T21:04:46Z
40,095,736
<p>you are slicing too much. try something like this:</p> <pre><code>indexer = df[df.ids == encodedid].index df.loc[indexer, 'Discriminant'] = 'Y' </code></pre> <p><code>.loc[]</code> needs an index list and a column list. you can set the value of that slice easily using <code>=</code> 'what you need'</p> <p>looking at your problem you might want to set that for 2 columns at the same time such has:</p> <pre><code>indexer = df[df.ids == encodedid].index column_list = ['Discriminant', 'questionid'] df.loc[indexer, column_list] = 'Y' </code></pre>
1
2016-10-17T21:12:21Z
[ "python", "pandas", "dataframe" ]