title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Using slices in Python
39,211,339
<p>I use the dataset from UCI repo: <a href="http://archive.ics.uci.edu/ml/datasets/Energy+efficiency" rel="nofollow">http://archive.ics.uci.edu/ml/datasets/Energy+efficiency</a> Then doing next:</p> <pre><code>from pandas import * from sklearn.neighbors import KNeighborsRegressor from sklearn.linear_model import LinearRegression, LogisticRegression from sklearn.svm import SVR from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import r2_score from sklearn.cross_validation import train_test_split dataset = read_excel('/Users/Half_Pint_boy/Desktop/ENB2012_data.xlsx') dataset = dataset.drop(['X1','X4'], axis=1) trg = dataset[['Y1','Y2']] trn = dataset.drop(['Y1','Y2'], axis=1) </code></pre> <p>Then do the models and cross validate:</p> <pre><code>models = [LinearRegression(), RandomForestRegressor(n_estimators=100, max_features ='sqrt'), KNeighborsRegressor(n_neighbors=6), SVR(kernel='linear'), LogisticRegression() ] Xtrn, Xtest, Ytrn, Ytest = train_test_split(trn, trg, test_size=0.4) </code></pre> <p>I'm creating a regression model for predicting values but have a problems. Here is the code:</p> <pre><code>TestModels = DataFrame() tmp = {} for model in models: m = str(model) tmp['Model'] = m[:m.index('(')] for i in range(Ytrn.shape[1]): model.fit(Xtrn, Ytrn[:,i]) tmp[str(i+1)] = r2_score(Ytest[:,0], model.predict(Xtest)) TestModels = TestModels.append([tmp]) TestModels.set_index('Model', inplace=True) </code></pre> <p>It shows unhashable type: 'slice' for line model.fit(Xtrn, Ytrn[:,i])</p> <p>How can it be avoided and made working?</p> <p>Thanks!</p>
0
2016-08-29T16:55:14Z
39,234,260
<p>I think that I had a similar problem before! Try to convert your data to numpy arrays before feeding them to <code>sklearn</code> estimators. It most probably solve the hashing problem. For instance, You can do:</p> <pre><code>Xtrn_array = Xtrn.as_matrix() Ytrn_array = Ytrn.as_matrix() </code></pre> <p>and use Xtrn_array and Ytrn_array when you fit your data to estimators. </p>
1
2016-08-30T18:04:29Z
[ "python", "pandas", "scikit-learn", "slice", "prediction" ]
Boto3 get contents of S3 bucket
39,211,453
<p>I am trying to get the list of files in a subfolder of a bucket. Everything works fine, except, when I try to parse the files I notice that the first key my code pulls is the subfolder name. Is there any way to leave out the subfolder name as a key?</p> <pre><code>s3 = session.resource('s3') bucket = s3.Bucket('bucket_name') for obj in bucket.objects.filter(Prefix="sub1"): key = obj.key print(key) </code></pre> <p>Results from print key</p> <pre><code>sub1/ sub1/file1 sub1/file2 . . </code></pre>
1
2016-08-29T17:01:40Z
39,211,704
<p>I'd imagine there is a <code>.exclude</code> on the collections like in django but i couldn't see it as an option. You could try something like this</p> <pre><code>s3 = session.resource('s3') bucket = s3.Bucket('bucket_name') prefix = "sub1/" data = [obj for obj in list(bucket.objects.filter(Prefix=prefix)) if obj.key != prefix] for obj in data: print(obj.key) </code></pre>
2
2016-08-29T17:16:48Z
[ "python", "amazon-s3", "boto3" ]
Scrapy spider does not store state (persistent state)
39,211,490
<p>Hi have a basic spider that runs to fetch all links on a given domain. I want to make sure it persists its state so that it can resume from where it left. I have followed the given url <a href="http://doc.scrapy.org/en/latest/topics/jobs.html" rel="nofollow">http://doc.scrapy.org/en/latest/topics/jobs.html</a> .But when i try it the first time it runs fine and i end it with Ctrl+C and when I try to resume it the crawl stops on the first url itself.</p> <p>Below is the log when it ends:</p> <pre><code>2016-08-29 16:51:08 [scrapy] INFO: Dumping Scrapy stats: {'downloader/request_bytes': 896, 'downloader/request_count': 4, 'downloader/request_method_count/GET': 4, 'downloader/response_bytes': 35320, 'downloader/response_count': 4, 'downloader/response_status_count/200': 4, 'dupefilter/filtered': 149, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2016, 8, 29, 16, 51, 8, 837853), 'log_count/DEBUG': 28, 'log_count/INFO': 7, 'offsite/domains': 22, 'offsite/filtered': 23, 'request_depth_max': 1, 'response_received_count': 4, 'scheduler/dequeued': 2, 'scheduler/dequeued/disk': 2, 'scheduler/enqueued': 2, 'scheduler/enqueued/disk': 2, 'start_time': datetime.datetime(2016, 8, 29, 16, 51, 7, 821974)} 2016-08-29 16:51:08 [scrapy] INFO: Spider closed (finished) </code></pre> <p>Here is my spider:</p> <pre><code>from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from Something.items import SomethingItem class maxSpider(CrawlSpider): name = 'something' allowed_domains = ['thecheckeredflag.com', 'inautonews.com'] start_urls = ['http://www.thecheckeredflag.com/', 'http://www.inautonews.com/'] rules = (Rule(LinkExtractor(allow=()), callback='parse_obj', follow=True),) def parse_obj(self,response): for link in LinkExtractor(allow=self.allowed_domains,deny =() ).extract_links(response): item = SomethingItem() item['url'] = link.url yield item #print item </code></pre> <p>Scrapy version: Scrapy 1.1.2 </p> <p>Python version: 2.7</p> <p>I am new to scrapy, if i need to post any more info please let me know.</p>
2
2016-08-29T17:04:06Z
39,221,381
<p>The reason this was happening was due to the spider process being killed abruptly.</p> <p>The spider was not shutting down properly when I hit the Ctrl+C. Now, when the crawler shuts down properly the first time, it resumes properly too.</p> <p>So basically, make sure that you see the crawler ends/shuts down properly for it to resume.</p>
2
2016-08-30T07:30:25Z
[ "python", "scrapy" ]
Is there some way to make sure that the raw_input is only non-numeric?
39,211,531
<p>I want to make sure that the user enters the input in the correct format and i do know how to make sure its numeric input but i dont understand how to make sure its not numeric input.</p> <pre><code>x = raw_input('What is your name? ') y = raw_input('What is your age? ') try: something_to_make_sure_its_not_numeric(x) int(y) print "Hello {0}, You look very handsome for someone who is {1}.".format(x, y) except: print('please enter input in correct format') </code></pre> <p>y question is that is there some function in python like int() that makes sure that it only has letters.</p>
-2
2016-08-29T17:06:45Z
39,211,571
<p>There is also <code>isdigit()</code> function with <code>string</code> to check whether string is numeric or not. To check whether it is non-numeric, simply use <code>not</code> with the condition</p> <pre><code>&gt;&gt;&gt; 'xyx'.isdigit() False &gt;&gt;&gt; '123'.isdigit() True # Now check output with "not" &gt;&gt;&gt; not 'xyx'.isdigit() True &gt;&gt;&gt; not '123'.isdigit() False </code></pre> <p>It will be good idea to create your custom function to achieve this using <code>isdigit()</code></p> <pre><code>def is_non_numeric(num_str): return not num_str.isdigit() # Example &gt;&gt;&gt; is_non_numeric('123') False &gt;&gt;&gt; is_non_numeric('xyz') True </code></pre>
1
2016-08-29T17:09:11Z
[ "python", "python-2.7" ]
Is there some way to make sure that the raw_input is only non-numeric?
39,211,531
<p>I want to make sure that the user enters the input in the correct format and i do know how to make sure its numeric input but i dont understand how to make sure its not numeric input.</p> <pre><code>x = raw_input('What is your name? ') y = raw_input('What is your age? ') try: something_to_make_sure_its_not_numeric(x) int(y) print "Hello {0}, You look very handsome for someone who is {1}.".format(x, y) except: print('please enter input in correct format') </code></pre> <p>y question is that is there some function in python like int() that makes sure that it only has letters.</p>
-2
2016-08-29T17:06:45Z
39,211,658
<p>Check if its a digit, and take the not of it</p> <pre><code>if x.isdigit(): print_error else: </code></pre> <p>Or use </p> <pre><code>x.isnumeric() </code></pre>
0
2016-08-29T17:14:08Z
[ "python", "python-2.7" ]
Is there some way to make sure that the raw_input is only non-numeric?
39,211,531
<p>I want to make sure that the user enters the input in the correct format and i do know how to make sure its numeric input but i dont understand how to make sure its not numeric input.</p> <pre><code>x = raw_input('What is your name? ') y = raw_input('What is your age? ') try: something_to_make_sure_its_not_numeric(x) int(y) print "Hello {0}, You look very handsome for someone who is {1}.".format(x, y) except: print('please enter input in correct format') </code></pre> <p>y question is that is there some function in python like int() that makes sure that it only has letters.</p>
-2
2016-08-29T17:06:45Z
39,211,672
<p>You might use <a href="https://docs.python.org/3/library/re.html?highlight=single%20line%20mode#re.VERBOSE" rel="nofollow">re module</a>, this allow you to check if a string contain for example a digit:</p> <pre><code>import re string = "626dsqd" test = re.search("\d", string) if test: print('please enter input in correct format') </code></pre>
0
2016-08-29T17:14:52Z
[ "python", "python-2.7" ]
Is there some way to make sure that the raw_input is only non-numeric?
39,211,531
<p>I want to make sure that the user enters the input in the correct format and i do know how to make sure its numeric input but i dont understand how to make sure its not numeric input.</p> <pre><code>x = raw_input('What is your name? ') y = raw_input('What is your age? ') try: something_to_make_sure_its_not_numeric(x) int(y) print "Hello {0}, You look very handsome for someone who is {1}.".format(x, y) except: print('please enter input in correct format') </code></pre> <p>y question is that is there some function in python like int() that makes sure that it only has letters.</p>
-2
2016-08-29T17:06:45Z
39,211,674
<p>The following expression return <code>True</code> only of all the letters are non-digits:</p> <pre><code>all(not s.isdigit() for s in x) </code></pre>
0
2016-08-29T17:14:58Z
[ "python", "python-2.7" ]
Is there some way to make sure that the raw_input is only non-numeric?
39,211,531
<p>I want to make sure that the user enters the input in the correct format and i do know how to make sure its numeric input but i dont understand how to make sure its not numeric input.</p> <pre><code>x = raw_input('What is your name? ') y = raw_input('What is your age? ') try: something_to_make_sure_its_not_numeric(x) int(y) print "Hello {0}, You look very handsome for someone who is {1}.".format(x, y) except: print('please enter input in correct format') </code></pre> <p>y question is that is there some function in python like int() that makes sure that it only has letters.</p>
-2
2016-08-29T17:06:45Z
39,212,065
<p>You can use Regular Expressions to do that:</p> <pre><code>import re tester = re.match(r'^[a-zA-Z]*$', x) if tester: print x else: print 'Incorrect input' </code></pre> <p>If the return of the match method is <code>None</code> then your input does not satisfy your Regular Expression rule. In the example above it only verify if is a single string but you can change your re rule to match naything you want. </p> <p>You can consult the documentation in <a href="https://docs.python.org/2/library/re.html" rel="nofollow">here</a> for more information about re.</p>
0
2016-08-29T17:39:47Z
[ "python", "python-2.7" ]
Bug in TensorFlow reduce_max for negative infinity?
39,211,546
<p>Using <code>tf.maximum</code> with negative inf inputs as follows:</p> <pre><code>tf.maximum(-math.inf, -math.inf).eval() </code></pre> <p>gives the expected result <code>-inf</code></p> <p>However, <code>tf.reduce_max</code>, on the same inputs:</p> <pre><code>tf.reduce_max([-math.inf, -math.inf]).eval() </code></pre> <p>gives: <code>-3.40282e+38</code> which is the min float32.</p> <p>For positive infinity inputs, both functions result in <code>inf</code>. Is this a bug?</p>
4
2016-08-29T17:07:41Z
39,358,214
<p>This turned out to be a bug in Eigen which has already been fixed and pushed out to TensorFlow.</p> <p>The issue can be tracked here: <a href="https://github.com/tensorflow/tensorflow/issues/4131" rel="nofollow">https://github.com/tensorflow/tensorflow/issues/4131</a></p>
0
2016-09-06T21:37:24Z
[ "python", "tensorflow" ]
mailgun sent attachments are 1kb blank images
39,211,606
<p>I have a very simple django based server i wish to use as an email sending server with mailgun</p> <p>I've managed to create a server endpoint that trigger an email with an attachment, this seems to work fine but when checking out the received email the attachment jpg file is just a 1kb blank image, im not sure if its a django issue, mailgun or even the fact that its a sandbox domain</p> <p>here is my code including imports:</p> <pre><code>from django.shortcuts import render from django.http import HttpResponse from rest_framework import generics import requests class Email(generics.GenericAPIView): def post(self, req, *args, **kwargs): response = requests.post("https://api.mailgun.net/v3/sandbox....mailgun.org/messages", auth=("api", "&lt;API_KEY&gt;"), files=[("attachment", open("files/test.jpg"))], data={"from": "Dummy user &lt;mg.mymail@gmail.com&gt;", "to": ["mymail@gmail.com"], "subject": "Hello worlds", "text": "testing this thing out"}) resString = str(response) return HttpResponse(resString) </code></pre>
2
2016-08-29T17:11:03Z
39,215,148
<p>As an answer instead of in comments - you're reading your files in text mode, not binary mode. That'll introduce odd line endings or otherwise mangle your files before you submit them to MailGun's API. You want to read your files in binary mode like so:</p> <pre><code>open('path/to/file', 'rb') </code></pre>
1
2016-08-29T21:01:39Z
[ "python", "django", "mailgun" ]
Is str.replace() or combining two slices a better way to remove a character?
39,211,615
<p>I am using CodingBat for practice exercises for the Python Language, I got to the "Warmup-1 > missing_char" exercise. The problem is as so:</p> <blockquote> <p>Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..len(str)-1 inclusive).</p> </blockquote> <p>The examples were:</p> <blockquote> <p>missing_char('kitten', 1) → 'ktten'</p> <p>missing_char('kitten', 0) → 'itten'</p> <p>missing_char('kitten', 4) → 'kittn'</p> </blockquote> <p>I wrote:</p> <pre><code>def missing_char(str, n): return str.replace(str[n], "") </code></pre> <p>It returned all correct. As I usually do when I get my answers correct, I look and see how CodingBat answered it. They answered it in the following way:</p> <pre><code>def missing_char(str, n): front = str[:n] # up to but not including n back = str[n+1:] # n+1 through end of string return front + back </code></pre> <p>Now, my question is the following: which answer is more viable? Is there setbacks to my method whereas CodingBat's method is more solid? Or is this just one of those "multiple approaches to things" kind of situation?</p>
1
2016-08-29T17:11:37Z
39,212,031
<p>For the sake of posting a formal answer and as all previous comments suggest:</p> <p><code>str.replace(char,"")</code> will remove all occurences of the character regardless of their position. <code>str[:n]+str[n+1:]</code> will only remove the n-th character.</p> <p>So for that exercice <code>str.replace(char,"")</code> is <strong>not</strong> suitable.</p>
1
2016-08-29T17:37:58Z
[ "python" ]
Matplotlib xticks font size if string
39,211,707
<p>I am trying to change the font size of my x axis that happens to be strings and not numbers. I have changed other charts that have integers by using :</p> <pre><code>plt.xticks(size=10) </code></pre> <p>However, this dose not work for some of my graphs that have months in the place of integers. Keep in mind i am not using subplots. </p>
1
2016-08-29T17:16:56Z
39,212,381
<p>Try setting the fontsize either by using the the <code>fontsize</code> keyword argument or if you want to globally change it to every plot in your script by updating the <code>rcParams</code> as</p> <pre><code>import matplotlib matplotlib.rc('xtick', labelsize=20) </code></pre> <p>Also look at this answer: <a href="http://stackoverflow.com/questions/3899980/how-to-change-the-font-size-on-a-matplotlib-plot">How to change the font size on a matplotlib plot</a></p> <p>Or here: <a href="http://stackoverflow.com/questions/13139630/how-can-i-change-the-font-size-of-ticks-of-axes-object-in-matplotlib">How can I change the font size of ticks of axes object in matplotlib</a></p>
1
2016-08-29T18:00:51Z
[ "python", "matplotlib" ]
Python 3 - A simple text string from user input to hex
39,211,716
<p>I want my code to accept user input then convert it to Hex</p> <pre><code>hex_name = input("Would you like to convert to hex?,Type Yes or No: ") if hex_name == 'Yes' or hex_name == 'yes' or hex_name == 'YES': hex_input = input("Enter String value here:") h_input = binascii.hexlify(b'hex_input') print(hex_input, "Converts to: ", h_input) #when user enters no elif hex_name == 'No' or hex_name == 'no' or hex_name == 'NO': print("You said", hex_name, "have a nice day!") #when user enters an empty space or hits the enter-bar elif hex_name == '' or hex_name == ' ' or hex_name == ' ': print("Empty value detected, please try again") #Ends program if user enters anything than a yes or no elif hex_name != 'Yes' or hex_name != 'yes': print("Sorry", hex_name, "is not a valid input") print("Please enter Yes or No, ", "have a nice day!") </code></pre> <p>'''The code works but it prints the hex value of hex_input instead of the user input, What am i doing wrong?'''</p> <p>I am all very new to python and i use python 3.3.2</p>
1
2016-08-29T17:17:13Z
39,211,766
<p>Remove the quotes around <code>hex_input</code>:</p> <pre><code>binascii.hexlify(bytes(hex_input)) </code></pre>
0
2016-08-29T17:21:31Z
[ "python", "python-3.3" ]
Python 3 - A simple text string from user input to hex
39,211,716
<p>I want my code to accept user input then convert it to Hex</p> <pre><code>hex_name = input("Would you like to convert to hex?,Type Yes or No: ") if hex_name == 'Yes' or hex_name == 'yes' or hex_name == 'YES': hex_input = input("Enter String value here:") h_input = binascii.hexlify(b'hex_input') print(hex_input, "Converts to: ", h_input) #when user enters no elif hex_name == 'No' or hex_name == 'no' or hex_name == 'NO': print("You said", hex_name, "have a nice day!") #when user enters an empty space or hits the enter-bar elif hex_name == '' or hex_name == ' ' or hex_name == ' ': print("Empty value detected, please try again") #Ends program if user enters anything than a yes or no elif hex_name != 'Yes' or hex_name != 'yes': print("Sorry", hex_name, "is not a valid input") print("Please enter Yes or No, ", "have a nice day!") </code></pre> <p>'''The code works but it prints the hex value of hex_input instead of the user input, What am i doing wrong?'''</p> <p>I am all very new to python and i use python 3.3.2</p>
1
2016-08-29T17:17:13Z
39,211,771
<p>You're specifically passing the string "hex_input", not the variable hex_input. That's why it's giving you the hex value of the string "hex_input".</p> <p>You have to remove the quotes around "hex_input":</p> <pre><code>if hex_name == 'Yes' or hex_name == 'yes' or hex_name == 'YES': hex_input = input("Enter String value here:") h_input = binascii.hexlify(b'hex_input') ^ ^ these need to be removed </code></pre> <p>So the line should be:</p> <pre><code>h_input = binascii.hexlify(bytes(hex_input)) </code></pre> <p>If you put quotes around something Python is going to look at whatever is between the quotes as a string. The value of <code>hex_input</code> is already a string, therefore you can just pass <code>hex_input</code>.</p>
0
2016-08-29T17:21:54Z
[ "python", "python-3.3" ]
Python 3 - A simple text string from user input to hex
39,211,716
<p>I want my code to accept user input then convert it to Hex</p> <pre><code>hex_name = input("Would you like to convert to hex?,Type Yes or No: ") if hex_name == 'Yes' or hex_name == 'yes' or hex_name == 'YES': hex_input = input("Enter String value here:") h_input = binascii.hexlify(b'hex_input') print(hex_input, "Converts to: ", h_input) #when user enters no elif hex_name == 'No' or hex_name == 'no' or hex_name == 'NO': print("You said", hex_name, "have a nice day!") #when user enters an empty space or hits the enter-bar elif hex_name == '' or hex_name == ' ' or hex_name == ' ': print("Empty value detected, please try again") #Ends program if user enters anything than a yes or no elif hex_name != 'Yes' or hex_name != 'yes': print("Sorry", hex_name, "is not a valid input") print("Please enter Yes or No, ", "have a nice day!") </code></pre> <p>'''The code works but it prints the hex value of hex_input instead of the user input, What am i doing wrong?'''</p> <p>I am all very new to python and i use python 3.3.2</p>
1
2016-08-29T17:17:13Z
39,212,314
<p>Just remove the quotes around hex_input and you're good to go.</p> <p>Since you're pretty new to python, be aware that you can easily improve the quality and readability of your code. Following is just the start of it !</p> <pre><code>hex_name = input("Would you like to convert to hex?,Type Yes or No: ") hex_name = hex_name.strip().lower() if hex_name: if hex_name not in ["yes", "no"]: print("Sorry", hex_name, "is not a valid input") print("Please enter Yes or No, ", "have a nice day!") elif hex_name == "yes": hex_input = input("Enter String value here:") h_input = binascii.hexlify(bytes(hex_input)) print(hex_input, "Converts to: ", h_input) elif hex_name == "no": print("You said", hex_name, "have a nice day!") else: print("Empty value detected, please try again") </code></pre>
0
2016-08-29T17:56:29Z
[ "python", "python-3.3" ]
Python Pyplot won't plot surface fully
39,211,765
<p>In the attached picture you can see two plots of the same data. The left one is plotted with <code>plot_wireframe()</code> the right one with <code>plot_surface()</code></p> <p>Like this:</p> <pre><code>fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(xm, ym, Values) fig2 = plt.figure() ax2 = fig2.add_subplot(111, projection='3d') ax2.plot_wireframe(xm, ym, Values) plt.show() </code></pre> <p>Why is this? The <code>plot_wireframe</code> is correct. Why is for example the peak in the left upper corner not shown on the surface plot? Thanks</p> <p><a href="http://i.stack.imgur.com/jH4Du.png" rel="nofollow"><img src="http://i.stack.imgur.com/jH4Du.png" alt="the two plots of the same data"></a></p> <p>Here, another example with the data matrix:</p> <p><a href="http://i.stack.imgur.com/PZIJS.png" rel="nofollow"><img src="http://i.stack.imgur.com/PZIJS.png" alt="enter image description here"></a></p>
2
2016-08-29T17:21:22Z
39,219,458
<p>Given what the discussion in the comments, I <em>think</em> what's going on is you have a normal wireframe that looks as it should, but the surface plot is a 2D projection in that 3D axes object. I noticed that you are missing a line that shows up in <a href="http://matplotlib.org/examples/mplot3d/surface3d_demo.html" rel="nofollow">the matplotlib surface example</a>: <code>X, Y = np.meshgrid(X, Y)</code>. Assuming I'm on the right track, you need to insert an analogous statement prior to the <code>axes.plot_surface()</code> call.</p>
0
2016-08-30T05:37:23Z
[ "python", "matplotlib" ]
Creating more rows based on condition in pandas
39,211,772
<p>I have a dataframe like following:</p> <pre><code>id, index, val_1, val_2 1, 1, 0.2, 0 1, 2, 0.4, 0.2 2,2, 0.1, 0.5 2,4, 0.7, 0.0 .... </code></pre> <p>and so on</p> <p>Now, the complete range of index values that are allowed for each id is </p> <pre><code>[1,2,3,4] </code></pre> <p>So, if any of this index is missing for each id, I want to add those rows. So for the above example, the desired output is</p> <pre><code>id, index, val_1, val_2 1, 1, 0.2, 0 1, 2, 0.4, 0.2 1, 3, 0, 0 # added because index 3 was missing for id 1 1, 4, 0, 0 # added because index 4 was missing for id 1 2, 1,0,0 # added because index 1 was missing for id 2 2,2, 0.1, 0.5 2, 3, 0, 0 2,4, 0.7, 0.0 .... </code></pre> <p>How do i perform this in operation in pandas?</p>
3
2016-08-29T17:22:03Z
39,211,924
<p>try this:</p> <pre><code>In [210]: from itertools import product In [211]: x = pd.DataFrame(list(product(df.id.unique(), [1,2,3,4])), columns=['id','index']).assign(val_1=0, val_2=0).set_index(['id','index']) In [212]: x.update(df.set_index(['id','index'])) In [213]: x Out[213]: val_1 val_2 id index 1 1 0.2 0.0 2 0.4 0.2 3 0.0 0.0 4 0.0 0.0 2 1 0.0 0.0 2 0.1 0.5 3 0.0 0.0 4 0.7 0.0 In [214]: x.reset_index() Out[214]: id index val_1 val_2 0 1 1 0.2 0.0 1 1 2 0.4 0.2 2 1 3 0.0 0.0 3 1 4 0.0 0.0 4 2 1 0.0 0.0 5 2 2 0.1 0.5 6 2 3 0.0 0.0 7 2 4 0.7 0.0 </code></pre> <p>Explanation:</p> <pre><code>In [225]: x = (pd.DataFrame(list(product(df.id.unique(), [1,2,3,4])), columns=['id','index']) .....: .assign(val_1=0, val_2=0) .....: .set_index(['id','index'])) In [226]: x Out[226]: val_1 val_2 id index 1 1 0 0 2 0 0 3 0 0 4 0 0 2 1 0 0 2 0 0 3 0 0 4 0 0 In [227]: x.update(df.set_index(['id','index'])) In [228]: x Out[228]: val_1 val_2 id index 1 1 0.2 0.0 2 0.4 0.2 3 0.0 0.0 4 0.0 0.0 2 1 0.0 0.0 2 0.1 0.5 3 0.0 0.0 4 0.7 0.0 In [229]: x.reset_index() Out[229]: id index val_1 val_2 0 1 1 0.2 0.0 1 1 2 0.4 0.2 2 1 3 0.0 0.0 3 1 4 0.0 0.0 4 2 1 0.0 0.0 5 2 2 0.1 0.5 6 2 3 0.0 0.0 7 2 4 0.7 0.0 </code></pre>
4
2016-08-29T17:31:22Z
[ "python", "pandas", "dataframe" ]
Creating more rows based on condition in pandas
39,211,772
<p>I have a dataframe like following:</p> <pre><code>id, index, val_1, val_2 1, 1, 0.2, 0 1, 2, 0.4, 0.2 2,2, 0.1, 0.5 2,4, 0.7, 0.0 .... </code></pre> <p>and so on</p> <p>Now, the complete range of index values that are allowed for each id is </p> <pre><code>[1,2,3,4] </code></pre> <p>So, if any of this index is missing for each id, I want to add those rows. So for the above example, the desired output is</p> <pre><code>id, index, val_1, val_2 1, 1, 0.2, 0 1, 2, 0.4, 0.2 1, 3, 0, 0 # added because index 3 was missing for id 1 1, 4, 0, 0 # added because index 4 was missing for id 1 2, 1,0,0 # added because index 1 was missing for id 2 2,2, 0.1, 0.5 2, 3, 0, 0 2,4, 0.7, 0.0 .... </code></pre> <p>How do i perform this in operation in pandas?</p>
3
2016-08-29T17:22:03Z
39,212,919
<p>Try this:</p> <p>Starting with this a df: </p> <pre><code>id index val_1 val_2 0 1 1 0.2 0.0 1 1 2 0.4 0.2 2 2 2 0.1 0.5 3 2 4 0.7 0.0 </code></pre> <p>Build New DataFrame:</p> <pre><code>df2 = pd.DataFrame({'id': np.repeat(df.id.unique(),4),'index': np.asarray([1,2,3,4]*len(df.id.unique()))}, columns = [u'id', u'index', u'val_1', u'val_2']).fillna(0) </code></pre> <p>Append, drop dups and sort DataFrame: </p> <pre><code>dfx = df.append(df2).drop_duplicates(subset=['id', 'index'], keep="first") dfx.sort_values(['id','index']).reset_index(drop=True) id index val_1 val_2 0 1 1 0.2 0.0 1 1 2 0.4 0.2 2 1 3 0.0 0.0 3 1 4 0.0 0.0 4 2 1 0.0 0.0 5 2 2 0.1 0.5 6 2 3 0.0 0.0 7 2 4 0.7 0.0 </code></pre> <p>df2 looks like this: </p> <pre><code> id index val_1 val_2 0 1 1 0 0 1 1 2 0 0 2 1 3 0 0 3 1 4 0 0 4 2 1 0 0 5 2 2 0 0 6 2 3 0 0 7 2 4 0 0 </code></pre>
-1
2016-08-29T18:35:43Z
[ "python", "pandas", "dataframe" ]
Django: simple model for storing messages/notifications to/from users
39,211,784
<p>I am trying to create a simple Notification/Message model for my Django app. This will store notifications from the site to the user, and messages from one user to another. A working model I had been using looks like this:</p> <pre><code>class Notification(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='sender_notification') recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='recipient_notification') message = models.TextField() read = models.BooleanField(default=False) recieved_date = models.DateTimeField(auto_now_add=True) </code></pre> <p>A message will have 0-1 senders (0 if the message is a notification from the site to the user), and typically one recipient (when the notification is meant for one specific user - e.g., "there is a comment on your post" - or when a message has been sent from one user to another). This had been working for me. However, it occurred to me that in some cases I want to send a notification to <em>every</em> user. I could potentially create <code>Notification</code> objects in a loop:</p> <pre><code>for user in User.objects.all(): Notification.objects.create(recipient=user, message='message for all uses') </code></pre> <p>But this seems like it will be pretty inefficient, and create unnecessary clutter in the database.</p> <p>I experimented with updating my model like this:</p> <pre><code>class Notification(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='sender_notification') recipient = models.ManyToManyField(User) message = models.TextField() read = models.BooleanField(default=False) recieved_date = models.DateTimeField(auto_now_add=True) </code></pre> <p>But this requires a <code>sender</code> (for reasons that I don't understand), and since there is only one record for each notification, when one recipient reads the notification and I set <code>read = True</code>, it will show as read for all recipients.</p> <p><strong>Is there an easy solution that I am missing where I can use a single model to handle notifications/messages, or am I going to have to add some additional models (or duplicate notifications in the notifications table)?</strong> </p> <p>Forgive my ignorance of database design. It is definitely a weakness of mine that I am working on.</p>
2
2016-08-29T17:22:46Z
39,211,882
<p>My solution is to create a ReadFlag model.</p> <pre><code>class ReadFlag(models.Model): user = models.ForeignKey(User) message = models.ForeignKey(Message) created = ... </code></pre>
1
2016-08-29T17:28:55Z
[ "python", "django", "django-models" ]
Using pre-trained word embeddings in tensorflow's seq2seq function
39,211,791
<p>I am building a seq2seq model using functions in tensorflow's <code>seq2seq.py</code>, where they have a function like this:</p> <pre><code>embedding_rnn_seq2seq(encoder_inputs, decoder_inputs, cell, num_encoder_symbols, num_decoder_symbols, embedding_size, output_projection=None, feed_previous=False, dtype=dtypes.float32, scope=None) </code></pre> <p>however, it seems that this function does not take pre-trained embeddings as input, are there any ways that I can take pre-trained word embeddings as input in this function?</p>
1
2016-08-29T17:22:59Z
39,212,608
<p>There is no parameter you just hand over. Read in your embeddings (make sure vocabulary IDs match). Then, once you initialized all variables, find the embedding tensor (iterate through tf.all_variables to find the name). Then use tf.assign to overwrite the randomly initialized embeddings there with your embeddings.</p>
1
2016-08-29T18:17:09Z
[ "python", "machine-learning", "tensorflow", "recurrent-neural-network", "lstm" ]
Tkinter - Preload window?
39,211,867
<p>I started building a python tkinter gui, the problem is, after adding many features to the gui, the loading started looking <strong>really ugly</strong>. When starting the mainloop, a blank window shows up for a few miniseconds before the widgets are loaded, the same happens with the other Toplevel windows ( except the ones with few static elements that don't need updates ). </p> <h2>My question is</h2> <p>Is there a way to 'preload' the window so that when I would call it, it would start smoothly?</p> <h3>For example</h3> <pre><code>root = MyTkRoot() root.build_stuff_before_calling() root.mainloop() # Smooth without widget loading lag </code></pre> <h3>Part of my code</h3> <pre><code>from root_gui import Root import threading from time import sleep from data_handler import DataHandler def handle_conn(): DataHandler.try_connect() smtp_client.refresh() def conn_manager(): # Working pretty well while 'smtp_client' in locals(): sleep(3) handle_conn() smtp_client = Root() handle_conn() MyConnManager = threading.Thread(target=conn_manager) MyConnManager.start() # Thanks to the second thread, the tk window doesn't have to wait for 3 seconds before loading the widgets. smtp_client.mainloop() </code></pre> <h3>The full project on git</h3> <p>Too much code to put in here...</p> <p><a href="https://github.com/cernyd/smtp_client" rel="nofollow">https://github.com/cernyd/smtp_client</a></p>
3
2016-08-29T17:27:52Z
39,211,981
<p>The short answer is yes. You can set the window to appear as though you can't see it. Perform any code that takes time, and then display the window.</p> <p>Here's how:</p> <pre><code>class MyTkRoot(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.attributes('-alpha', 0.0) # make window transparent # build gui... self.after(0, self.attributes, "-alpha", 1.0) # back to normal root = MyTkRoot() root.mainloop() </code></pre> <p><a href="http://effbot.org/tkinterbook/wm.htm#Tkinter.Wm.attributes-method" rel="nofollow">Here's</a> a reference to the code with the example of a Toplevel. It will also work with the root however.</p>
1
2016-08-29T17:34:34Z
[ "python", "user-interface", "tkinter", "lag" ]
Tkinter - Preload window?
39,211,867
<p>I started building a python tkinter gui, the problem is, after adding many features to the gui, the loading started looking <strong>really ugly</strong>. When starting the mainloop, a blank window shows up for a few miniseconds before the widgets are loaded, the same happens with the other Toplevel windows ( except the ones with few static elements that don't need updates ). </p> <h2>My question is</h2> <p>Is there a way to 'preload' the window so that when I would call it, it would start smoothly?</p> <h3>For example</h3> <pre><code>root = MyTkRoot() root.build_stuff_before_calling() root.mainloop() # Smooth without widget loading lag </code></pre> <h3>Part of my code</h3> <pre><code>from root_gui import Root import threading from time import sleep from data_handler import DataHandler def handle_conn(): DataHandler.try_connect() smtp_client.refresh() def conn_manager(): # Working pretty well while 'smtp_client' in locals(): sleep(3) handle_conn() smtp_client = Root() handle_conn() MyConnManager = threading.Thread(target=conn_manager) MyConnManager.start() # Thanks to the second thread, the tk window doesn't have to wait for 3 seconds before loading the widgets. smtp_client.mainloop() </code></pre> <h3>The full project on git</h3> <p>Too much code to put in here...</p> <p><a href="https://github.com/cernyd/smtp_client" rel="nofollow">https://github.com/cernyd/smtp_client</a></p>
3
2016-08-29T17:27:52Z
39,212,770
<p>On your operating system tkinter seems to show the base <code>Tk</code> window before loading it's widgets causing that few milliseconds of blank window. To make it appear with all the widgets already loaded you will need to hide the window when starting and <code>.after</code> it has loaded show it again.</p> <p>There are a number of ways to show and hide a window, personally I'd use <code>.withdraw()</code> to remove the window from the window manager (like it was never there) then <code>.deiconify()</code> (basically "unminimize") to show the window again.</p> <pre><code>class TEST(tk.Tk): def __init__(self,*args,**kw): tk.Tk.__init__(self,*args,**kw) self.withdraw() #hide the window self.after(0,self.deiconify) #as soon as possible (after app starts) show again #setup app... </code></pre> <p>An alternative to withdrawing the window completely is to start it minimized with <code>.iconify()</code> so it will appear on the taskbar/dock but won't open the window until it is completely loaded.</p> <p>Another way to hide/show the window is by changing the <code>-alpha</code> property as <a href="http://stackoverflow.com/a/39211981/5827215">@double_j has done</a> but I would not recommend that in production code because the window is technically still there, it (and the close button etc.) can be clicked on /interacted with for a brief moment before showing which could be undesired, as well it's behaviour can be ambiguous amongst operating systems, from <a href="http://wiki.tcl.tk/9457" rel="nofollow">http://wiki.tcl.tk/9457</a>:</p> <blockquote> <h2>Macintosh Attributes</h2> <p>-alpha double controls opacity (from 0.0 to 1.0) <br>...<br></p> <h2>Unix/X11 Attributes</h2> <p>-alpha double controls opacity (from 0.0 to 1.0).<br> This requires a compositing window manager to have any effect. [compiz] is one such, and xfwm4 (for the XFCE desktop) is another. <br>...<br></p> <h2>Windows Attributes</h2> <p>-alpha double how opaque the overall window is; <strong>note that changing between 1.0 and any other value may cause the window to flash</strong> (Tk changes the class of window used to implement the toplevel).</p> </blockquote> <p>So on some unix machines <code>-alpha</code> may have no effect and on windows it may cause the window to flash (probably not an issue before it is even opened but still worth noting)</p> <p>Where as <code>withdraw</code> and <code>deiconify</code> works identically amongst all platforms as far as I am aware.</p>
2
2016-08-29T18:27:18Z
[ "python", "user-interface", "tkinter", "lag" ]
Tkinter - Preload window?
39,211,867
<p>I started building a python tkinter gui, the problem is, after adding many features to the gui, the loading started looking <strong>really ugly</strong>. When starting the mainloop, a blank window shows up for a few miniseconds before the widgets are loaded, the same happens with the other Toplevel windows ( except the ones with few static elements that don't need updates ). </p> <h2>My question is</h2> <p>Is there a way to 'preload' the window so that when I would call it, it would start smoothly?</p> <h3>For example</h3> <pre><code>root = MyTkRoot() root.build_stuff_before_calling() root.mainloop() # Smooth without widget loading lag </code></pre> <h3>Part of my code</h3> <pre><code>from root_gui import Root import threading from time import sleep from data_handler import DataHandler def handle_conn(): DataHandler.try_connect() smtp_client.refresh() def conn_manager(): # Working pretty well while 'smtp_client' in locals(): sleep(3) handle_conn() smtp_client = Root() handle_conn() MyConnManager = threading.Thread(target=conn_manager) MyConnManager.start() # Thanks to the second thread, the tk window doesn't have to wait for 3 seconds before loading the widgets. smtp_client.mainloop() </code></pre> <h3>The full project on git</h3> <p>Too much code to put in here...</p> <p><a href="https://github.com/cernyd/smtp_client" rel="nofollow">https://github.com/cernyd/smtp_client</a></p>
3
2016-08-29T17:27:52Z
39,259,348
<p>After looking at your the project in your repository, I revised the code and dumped it all into one file. The following is the results from refactoring your modules and files into a fully self-contained program. The one thing that it is missing is the <code>Resource</code> class that handles all of the external dependencies.</p> <p>You can see the <a href="http://pastebin.com/bRZuq72L" rel="nofollow">complete program</a> on PasteBin.com.</p> <pre><code>#! /usr/bin/env python3 import base64 import contextlib import email.mime.text import enum import functools import pathlib import pickle import pickletools import re import smtplib import socket import sys import threading import tkinter.messagebox import traceback import zlib # Dump all of tkinter's constants into the local namespace. from tkinter.constants import * # Import custom modules in a way that an IDE will recognize them. with Resource.load('affinity.py'), \ Resource.load('threadbox.py'), \ Resource.load('safetkinter.py'): try: from .safetkinter import * except SystemError: from safetkinter import * try: from . import threadbox except SystemError: import threadbox # Patch the messagebox module to use a thread-safe version of Message. tkinter.messagebox.Message = Message # Create an enumeration to represents various program states. Status = enum.Enum('Status', 'mail_label login_button connection_error') def event_handler(method): """Allow command/event handlers to be marked and written more easily.""" @functools.wraps(method) def wrapper(self, event=None): nonlocal none_counter none_counter += event is None method(self) # print('Commands handled:', none_counter) none_counter = 0 return wrapper class SMTPClient(Frame): """Widget for sending emails through a GUI program in Python.""" TITLE = 'SMTP Mail Sender' AT_ICON = 'at.ico' HELP_ICON = 'help.ico' HELP_TEXT = 'get_help.txt' IS_TARGET = r'\A(\w|\.)+@\w+\.\w+\Z' IS_SUBJECT = r'\S+' IS_MESSAGE = r'\S+' @classmethod def main(cls): """Create an application containing a single SMTPClient widget.""" root = cls.create_application_root() cls.create_windows_bindings(root) cls.attach_window_icon(root) cls.setup_class_instance(root) root.mainloop() @classmethod def create_application_root(cls): """Create and configure the main application window.""" root = Tk() root.title(cls.TITLE) # root.resizable(False, False) root.minsize(275, 200) root.option_add('*tearOff', FALSE) return root @classmethod def create_windows_bindings(cls, root): """Change some global bindings to work like Microsoft products.""" root.bind_all('&lt;Control-Key-a&gt;', cls.handle_control_a) root.bind_all('&lt;Control-Key-A&gt;', cls.handle_control_a) root.bind_class('Text', '&lt;Control-Key-/&gt;', lambda event: 'break') @staticmethod def handle_control_a(event): """Treat Control-A as would be expected on a Windows system.""" widget = event.widget if isinstance(widget, Entry): widget.selection_range(0, END) return 'break' if isinstance(widget, Text): widget.tag_add(SEL, 1.0, END + '-1c') return 'break' @classmethod def attach_window_icon(cls, root): """Generate and use the icon in the window's corner.""" with Resource.load(cls.AT_ICON) as handle: root.iconbitmap(handle) @classmethod def setup_class_instance(cls, root): """Build a SMTPClient instance that expects to be have size changes.""" widget = cls(root) widget.grid(row=0, column=0, sticky=NSEW) root.grid_rowconfigure(0, weight=1) root.grid_columnconfigure(0, weight=1) def __init__(self, master=None, **kw): """Initialize the SMTPClient instance and configure for operation.""" super().__init__(master, **kw) self.__tk = self.capture_root() self.create_bindings() self.__to_entry = self.__subject_entry = self.__message_text = \ self.__quit_button = self.__send_button = self.__from_label = \ self.__to_label = self.__subject_label = self.__login_button = \ self.__grip = None self.create_widgets() self.configure_grid() self.__data_handler = DataHandler() self.__connector = self.after_idle(self.try_connect) def destroy(self): """Cancel the connection system before closing.""" self.after_cancel(self.__connector) super().destroy() def capture_root(self): """Capture the rook (Tk instance) of this application.""" widget = self.master while not isinstance(widget, Tk): widget = widget.master return widget def create_bindings(self): """Bind the frame to any events that it will need to handle.""" self.__tk.bind('&lt;Control-Key-h&gt;', self.handle_help) self.__tk.bind('&lt;Control-Key-H&gt;', self.handle_help) self.__tk.bind('&lt;Control-Key-l&gt;', self.handle_login) self.__tk.bind('&lt;Control-Key-L&gt;', self.handle_login) self.__tk.bind('&lt;Key&gt;', self.handle_update) self.__tk.bind('&lt;Return&gt;', self.handle_send) def create_widgets(self): """Create all the widgets that will be placed in this frame.""" self.__to_entry = Entry(self) self.__subject_entry = Entry(self) self.__message_text = Text(self) self.__quit_button = Button( self, text='Quit', command=self.__tk.destroy ) self.__send_button = Button( self, text='Send', command=self.do_send, state=DISABLED ) self.__from_label = Label(self, text='From:') self.__to_label = Label(self, text='To:') self.__subject_label = Label(self, text='Subject:') self.__login_button = Button( self, text='Login Before Sending', command=self.do_login ) self.__grip = Sizegrip(self) def configure_grid(self): """Place all widgets on the grid in their respective locations.""" pad = dict(padx=5, pady=5) self.__from_label.grid(row=0, column=0, **pad) self.__login_button.grid( row=0, column=1, columnspan=4, sticky=EW, **pad ) self.__to_label.grid(row=1, column=0, **pad) self.__to_entry.grid(row=1, column=1, columnspan=4, sticky=EW, **pad) self.__subject_label.grid(row=2, column=0, **pad) self.__subject_entry.grid( row=2, column=1, columnspan=4, sticky=EW, **pad ) self.__message_text.grid( row=3, column=0, columnspan=5, sticky=NSEW, **pad ) self.__quit_button.grid(row=4, column=2, **pad) self.__send_button.grid(row=4, column=3, **pad) self.__grip.grid(row=4, column=4, sticky=SE, **pad) self.grid_rowconfigure(3, weight=1) self.grid_columnconfigure(1, weight=1) @event_handler def handle_help(self): """Open the help window and show a message for the user.""" with Resource.load(self.HELP_TEXT) as text, \ Resource.load(self.HELP_ICON) as icon: TextViewer.load(self.__tk, text, icon) @event_handler def handle_login(self): """Decide if the user should be able to login to the server.""" if self.current_status == Status.login_button: self.do_login() @event_handler def handle_update(self): """Decide if it should be possible to send an e-mail or not.""" to = self.__to_entry.get() subject = self.__subject_entry.get() message = self.__message_text.get(0.0, END) self.__send_button['state'] = ACTIVE if self.is_target(to) \ and self.is_subject(subject) \ and self.is_message(message) \ and self.__data_handler.is_connected else DISABLED @classmethod def is_target(cls, text): """Determine if this is an acceptable e-mail address.""" return bool(re.search(cls.IS_TARGET, text)) @classmethod def is_subject(cls, text): """Determine if this is an acceptable subject line.""" return bool(re.search(cls.IS_SUBJECT, text)) @classmethod def is_message(cls, text): """Determine if this is an acceptable message to send.""" return bool(re.search(cls.IS_MESSAGE, text)) @event_handler def handle_send(self): """Send only if the application is ready to do so.""" if self.__send_button['state'] == ACTIVE: self.do_send() def do_send(self): """Start a thread to send an e-mail in an asynchronous method.""" threading.Thread(target=self.send_thread).start() @threadbox.MetaBox.thread def send_thread(self): """Try to send an e-mail and display the results of the attempt.""" destination = self.__to_entry.get() try: self.__data_handler.send( destination, self.__subject_entry.get(), self.__message_text.get(0.0, END) ) except: tkinter.messagebox.showerror( 'Error', 'An exception has occurred.\n' 'Continue for more details.', master=self ) TextViewer(self.__tk, 'Traceback', traceback.format_exc()) else: tkinter.messagebox.showinfo( 'Success', 'The message was sent successfully to {}.'.format(destination), master=self ) @property def current_status(self): """Find out what status the program currently is in.""" return (Status.connection_error if not self.__data_handler.is_connected else Status.login_button if not self.__data_handler.is_logged_in else Status.mail_label) def do_login(self): """Open the login window and also the user to supply credentials.""" with Resource.load('login.ico') as icon: LoginWindow(self.__tk, icon, self.__data_handler) self.__login_button['text'] = self.__data_handler.username or '' self.refresh() def try_connect(self): """Repeatedly try to connect to the server every 0.6 seconds.""" if not self.__data_handler.is_connected: self.__data_handler.try_connect(self.refresh) self.__connector = self.after(600, self.try_connect) def refresh(self, is_connected=False): """Let the user know if there is a connection to the server.""" if is_connected: tkinter.messagebox.showinfo( 'Server', 'Your connection is live!', master=self ) class TextViewer(Toplevel): """Widget designed to show text in a window.""" BACKGROUND = '#FFFFFF' FOREGROUND = '#000000' WIDTH = 800 HEIGHT = 600 X_OFFSET = 10 Y_OFFSET = 10 @classmethod def load(cls, parent, text_handle, icon_handle): """Open a TextViewer with information loaded from a file.""" with text_handle.open('rt') as file: title, *text = map(str.strip, file) cls(parent, title, '\n'.join(text), icon_handle) def __init__(self, parent, title, text, icon_handle=None): """Initializes the window for the reader to see its contents.""" super().__init__(parent, borderwidth=5) if icon_handle is not None: self.iconbitmap(icon_handle) self.geometry('={}x{}+{}+{}'.format( self.WIDTH, self.HEIGHT, parent.winfo_rootx() + self.X_OFFSET, parent.winfo_rooty() + self.Y_OFFSET )) self.__frame_text = self.__frame_buttons = self.__okay_button = \ self.__scrollbar_view = self.__text_view = None self.create_widgets() self.configure_widgets() self.title(title) self.transient(parent) self.grab_set() self.protocol('WM_DELETE_WINDOW', self.okay) self.__text_view.focus_set() self.create_bindings() self.__text_view.insert(0.0, text) self.__text_view['state'] = DISABLED self.wait_window() def create_widgets(self): """Populates the window with the widgets that will be needed.""" self.__frame_text = Frame(self, relief=SUNKEN, height=700) self.__frame_buttons = Frame(self) self.__okay_button = Button( self.__frame_buttons, text='Close', command=self.okay, takefocus=FALSE ) self.__scrollbar_view = Scrollbar( self.__frame_text, orient=VERTICAL, takefocus=FALSE ) self.__text_view = Text( self.__frame_text, wrap=WORD, fg=self.FOREGROUND, bg=self.BACKGROUND, highlightthickness=0 ) def configure_widgets(self): """Put them in their proper places throughout the layout.""" self.__scrollbar_view['command'] = self.__text_view.yview self.__text_view['yscrollcommand'] = self.__scrollbar_view.set self.__okay_button.pack() self.__scrollbar_view.pack(side=RIGHT, fill=Y) self.__text_view.pack(side=LEFT, expand=TRUE, fill=BOTH) self.__frame_buttons.pack(side=BOTTOM, fill=X) self.__frame_text.pack(side=TOP, expand=TRUE, fill=BOTH) @event_handler def okay(self): """Close the window.""" self.destroy() def create_bindings(self): """Allow the window to respond to certain events.""" self.bind('&lt;Return&gt;', self.okay) self.bind('&lt;Escape&gt;', self.okay) class DataHandler: """Handler for communications with a SMTP server.""" HOST = 'smtp.gmail.com' PORT = 587 __slots__ = ( '__is_logged_in', '__is_connected', '__server', '__username', '__password' ) def __init__(self): """Initializes the DataHandler instance's various flags.""" self.__is_logged_in = False self.__is_connected = self.__server = self.__username = \ self.__password = None self.__cancel_connection() @property def is_logged_in(self): """Checks whether or not the instance believes it is logged in.""" return self.__is_logged_in @property def is_connected(self): """Checks whether or not the instance believes it is connected.""" return self.__is_connected @staticmethod def __check_string(value, name): """Verify that the string has a value type and value.""" if not isinstance(value, str): raise TypeError('{} must be of type str'.format(name)) if not value: raise ValueError('{} must not be an empty string'.format(name)) def __get_username(self): """Retrieves the value of the username.""" return self.__username def __set_username(self, text): """Validates the username and sets its value.""" self.__check_string(text, 'username') self.__username = text username = property( __get_username, __set_username, None, 'Sets value of username.' ) def __set_password(self, text): """Validates the password and sets its value.""" self.__check_string(text, 'password') self.__password = text password = property(fset=__set_password, doc='Sets value of password.') def try_connect(self, callback=lambda status: None): """Attempt to connect to the pre-configured server address.""" threading.Thread(target=self.__connect, args=(callback,)).start() def __connect(self, callback): """Connect to the server in an asynchronous fashion.""" try: self.__server = smtplib.SMTP(self.HOST, self.PORT, None, 1) except (smtplib.SMTPException, socket.gaierror, socket.timeout): self.__cancel_connection() else: self.__is_connected = True callback(self.__is_connected) def send(self, destination, subject, message): """Try to send an e-mail with the provided information.""" if self.__server is None: raise RuntimeError('cannot send without a valid connection') packet = email.mime.text.MIMEText(message) packet['From'] = self.__username packet['To'] = destination packet['Subject'] = subject self.__server.starttls() self.__server.login(self.__username, self.__password) self.__server.send_message(packet) self.__finish() def __cancel_connection(self): """Reset the is_connected and server attributes to default values.""" self.__is_connected = False self.__server = None def validate_credentials(self): """Verify if the saved credentials are correct or not.""" if self.__server is None: raise RuntimeError('cannot validate without a working connection') try: self.__server.starttls() self.__server.login(self.__username, self.__password) except smtplib.SMTPException: self.__is_logged_in = False else: self.__is_logged_in = True finally: self.__finish() return self.__is_logged_in def __finish(self): """Finish the conversation taking place with the server.""" self.__server.close() self.__cancel_connection() class Dialog(Toplevel): """Generic widget that should be used as a base class.""" X_OFFSET = 50 Y_OFFSET = 50 def __init__(self, parent, title=None, icon_handle=None): """Initialize a Dialog window that takes focus away from the parent.""" super().__init__(parent) self.withdraw() if icon_handle is not None: self.iconbitmap(icon_handle) if parent.winfo_viewable(): self.transient(parent) if title: self.title(title) self.parent = parent self.result = None body = Frame(self) self.initial_focus = self.body(body) body.grid(sticky=NSEW, padx=5, pady=5) self.okay_button = self.cancel_button = None self.button_box() if not self.initial_focus: self.initial_focus = self self.protocol('WM_DELETE_WINDOW', self.cancel) parent = self.parent if parent is not None: self.geometry('+{}+{}'.format( parent.winfo_rootx() + self.X_OFFSET, parent.winfo_rooty() + self.Y_OFFSET )) self.deiconify() self.initial_focus.focus_set() try: self.wait_visibility() except tkinter.TclError: pass else: self.grab_set() self.wait_window(self) def destroy(self): """Destruct the Dialog window.""" self.initial_focus = None super().destroy() def body(self, master): """Create the body of this Dialog window.""" pass def button_box(self): """Create the standard buttons and Dialog bindings.""" box = Frame(self) self.okay_button = Button( box, text='Okay', width=10, command=self.okay, default=ACTIVE ) self.okay_button.grid(row=0, column=0, padx=5, pady=5) self.cancel_button = Button( box, text='Cancel', width=10, command=self.cancel ) self.cancel_button.grid(row=0, column=1, padx=5, pady=5) self.bind('&lt;Return&gt;', self.okay) self.bind('&lt;Escape&gt;', self.cancel) box.grid() @event_handler def okay(self): """Validate and apply the changes made by this Dialog.""" if self.validate(): self.withdraw() self.update_idletasks() try: self.apply() finally: self.cancel() else: self.initial_focus.focus_set() @event_handler def cancel(self): """Close the Dialog window and return to its parent.""" if self.parent is not None: self.parent.focus_set() self.destroy() def validate(self): """Verify that the Dialog is in a valid state.""" return True @staticmethod def apply(): """Make any changes the Dialog wishes to accomplish.""" pass class LoginWindow(Dialog): """Widget to allow easy process for supplying credentials.""" TITLE = 'E-mail Login' WIDTH = 45 MASK = '*' def __init__(self, parent, icon_handle, data_handler): """Initialize the dialog with the necessary information.""" self.__data_handler = data_handler super().__init__(parent, self.TITLE, icon_handle) self.__username_label = self.__password_label = self.__username = \ self.__password = None def body(self, master): """Create all the different widgets needed for the body.""" self.__username_label = Label(master, text='Gmail Address:') self.__password_label = Label(master, text='Password:') self.__username = Entry(master, width=self.WIDTH) self.__password = Entry(master, width=self.WIDTH, show=self.MASK) self.__username_label.grid(row=0, column=0, padx=5, pady=5, sticky=E) self.__username.grid(row=0, column=1, padx=5, pady=5, sticky=EW) self.__password_label.grid(row=1, column=0, padx=5, pady=5, sticky=E) self.__password.grid(row=1, column=1, padx=5, pady=5, sticky=EW) self.bind('&lt;Key&gt;', self.refresh) return self.__username def button_box(self): """Create the button box and change okay button's options.""" super().button_box() self.okay_button.configure(state=DISABLED, text='Login') @event_handler def refresh(self): """Perform a soft validation for the username and password.""" username = self.__username.get() password = self.__password.get() valid = re.search(r'\A(\w|\.)+@gmail\.com\Z', username) is not None \ and len(password) &gt; 3 self.okay_button['state'] = ACTIVE if valid else DISABLED def validate(self): """Attempt to validate username and password with the server.""" self.__data_handler.username = self.__username.get() self.__data_handler.password = self.__password.get() valid = self.__data_handler.validate_credentials() if valid: tkinter.messagebox.showinfo( 'Login Success', 'The credentials were accepted.\n' 'You are now logged in!', master=self ) else: self.__password.delete(0, END) tkinter.messagebox.showerror( 'Login Error', 'This username/password combination was not accepted.\n' 'Please try again.', master=self ) return valid if __name__ == '__main__': SMTPClient.main() </code></pre>
1
2016-08-31T21:33:04Z
[ "python", "user-interface", "tkinter", "lag" ]
Winerror 3: File not found using ac2git
39,211,875
<p>I was using the ac2git tool to concert my accurev depot to git repository. I am getting the following error when running the command <strong>python ac2git.py</strong> after following the necessary steps, as instructed <a href="https://github.com/NavicoOS/ac2git/blob/master/how_it_works.md" rel="nofollow">here</a>.</p> <pre class="lang-none prettyprint-override"><code>2016-08-29 09:54:14,058 - ac2git - ERROR - The script has encountered an exception, aborting! Traceback (most recent call last): File "ac2git.py", line 3596, in AccuRev2GitMain rv = state.Start(isRestart=args.restart, isSoftRestart=args.softRestart) File "ac2git.py", line 2974, in Start self.RetrieveStreams() File "ac2git.py", line 1556, in RetrieveStreams tr, commitHash = self.RetrieveStream(depot=depot, stream=streamInfo,dataRef=dataRef, stateRef=stateRef, hwmRef=hwmRef, startTransaction=self.config.accurev.startTransaction, endTransaction=endTr.id) File "ac2git.py", line 1511, in RetrieveStream dataTr, dataHash = self.RetrieveStreamData(stream=stream, dataRef=dataRef,stateRef=stateRef) File "ac2git.py", line 1394, in RetrieveStreamData commitHash = self.Commit(transaction=tr, allowEmptyCommit=True,messageOverride="transaction {trId}".format(trId=tr.id), parents=[], ref=dataRef) File "ac2git.py", line 670, in Commit self.PreserveEmptyDirs() File "ac2git.py", line 440, in PreserveEmptyDirs if git.GetGitDirPrefix(path) is None and len(os.listdir(path)) == 0: FileNotFoundError: [WinError 3] The system cannot find the path specified:'C:///Users/*****/*****/app/node_modules/bower/node_modules/update-notifier/node_modules/latest-version/node_modules/package-json/node_modules/registry-url/node_modules/npmconf/node_modules/config-chain/node_modules/proto-list' </code></pre> <p>The error is quite vague and I can't seem to find any documentation on this tool that can help with the error. Has anyone faced this issue before?</p>
1
2016-08-29T17:28:27Z
39,228,780
<p>I am not familiar with the tool you are using but it seems the last line in the output excerpt you provided gives the best information:</p> <pre><code>FileNotFoundError: [WinError 3] The system cannot find the path specified:'C:///Users/*****/*****/app/node_modules/bower/node_modules/update-notifier/node_modules/latest-version/node_modules/package-json/node_modules/registry-url/node_modules/npmconf/node_modules/config-chain/node_modules/proto-list' </code></pre> <p>That path looks to be malformed with extra slashes and directory names that are not valid within the file system. Also, the file path is at 227 characters in the output and if the directory names between "Users" and "app" are long enough, you could be hitting the 256 character path name limit in Windows.</p>
1
2016-08-30T13:24:59Z
[ "python", "git", "accurev" ]
How can calculate the real distance between two points with GeoDjango?
39,211,879
<pre><code>from django.contrib.gis.geos import Point p1 = Point(36.74851779201058, -6.429006806692149, srid=4326) p2 = Point(37.03254161520977, -8.98366068931684, srid=4326) p1.distance(p2) Out: 2.5703941316759376 </code></pre> <p>But what is the unit of this float number?</p> <p>If you calculate this distance, this is <a href="http://boulter.com/gps/distance/?from=36.74851779201058%2C-6.429006806692149&amp;to=37.03254161520977%2C%20-8.98366068931684&amp;units=k" rel="nofollow">229.88 Km</a>. You can get it too using geopy:</p> <pre><code>from geopy.distance import distance distance(p1, p2) Out: Distance(229.883275249) distance(p1, p2).km Out: 229.88327524944066 </code></pre> <p>I have read that you can get (so so) this, if you divide the previous number for 111:</p> <pre><code>(2.5703941316759376 / 111) * 10000 Out: 231.5670388897241 # kilometers </code></pre> <p>Is there any way to get the real distance using only GeoDjango? Or should I use geopy?</p>
3
2016-08-29T17:28:44Z
39,259,317
<p>There's a solution to this online, which explains both what GeoDjango is doing originally (a distance calculation that doesn't use any standard units, essentially), but also, how to get it into a form that returns the distance in more useful units -- the code is very similar to what you're already doing, except that it makes use of a transform on each point before retrieving the distance. The link is below, hopefully it's useful to you:</p> <p><a href="https://coderwall.com/p/k1gg1a/distance-calculation-in-geodjango" rel="nofollow">https://coderwall.com/p/k1gg1a/distance-calculation-in-geodjango</a></p>
1
2016-08-31T21:30:56Z
[ "python", "django", "gis", "geodjango" ]
How can calculate the real distance between two points with GeoDjango?
39,211,879
<pre><code>from django.contrib.gis.geos import Point p1 = Point(36.74851779201058, -6.429006806692149, srid=4326) p2 = Point(37.03254161520977, -8.98366068931684, srid=4326) p1.distance(p2) Out: 2.5703941316759376 </code></pre> <p>But what is the unit of this float number?</p> <p>If you calculate this distance, this is <a href="http://boulter.com/gps/distance/?from=36.74851779201058%2C-6.429006806692149&amp;to=37.03254161520977%2C%20-8.98366068931684&amp;units=k" rel="nofollow">229.88 Km</a>. You can get it too using geopy:</p> <pre><code>from geopy.distance import distance distance(p1, p2) Out: Distance(229.883275249) distance(p1, p2).km Out: 229.88327524944066 </code></pre> <p>I have read that you can get (so so) this, if you divide the previous number for 111:</p> <pre><code>(2.5703941316759376 / 111) * 10000 Out: 231.5670388897241 # kilometers </code></pre> <p>Is there any way to get the real distance using only GeoDjango? Or should I use geopy?</p>
3
2016-08-29T17:28:44Z
39,302,364
<p>As far as I know, GeoDjango doesn't support calculating the real distance. It just calculates the distance geometrically. Therefore, I think you should use geopy as I did in my project..</p> <pre><code>from geopy.distance import vincenty distance = vincenty((lat1, lon1), (lat2, lon2)).kilometers </code></pre> <p>This will give the right distance as kilometers.</p> <p>For further information, check the geopy documentation.</p> <p><a href="http://geopy.readthedocs.io/en/latest/" rel="nofollow">http://geopy.readthedocs.io/en/latest/</a></p>
1
2016-09-03T01:04:10Z
[ "python", "django", "gis", "geodjango" ]
How can calculate the real distance between two points with GeoDjango?
39,211,879
<pre><code>from django.contrib.gis.geos import Point p1 = Point(36.74851779201058, -6.429006806692149, srid=4326) p2 = Point(37.03254161520977, -8.98366068931684, srid=4326) p1.distance(p2) Out: 2.5703941316759376 </code></pre> <p>But what is the unit of this float number?</p> <p>If you calculate this distance, this is <a href="http://boulter.com/gps/distance/?from=36.74851779201058%2C-6.429006806692149&amp;to=37.03254161520977%2C%20-8.98366068931684&amp;units=k" rel="nofollow">229.88 Km</a>. You can get it too using geopy:</p> <pre><code>from geopy.distance import distance distance(p1, p2) Out: Distance(229.883275249) distance(p1, p2).km Out: 229.88327524944066 </code></pre> <p>I have read that you can get (so so) this, if you divide the previous number for 111:</p> <pre><code>(2.5703941316759376 / 111) * 10000 Out: 231.5670388897241 # kilometers </code></pre> <p>Is there any way to get the real distance using only GeoDjango? Or should I use geopy?</p>
3
2016-08-29T17:28:44Z
39,304,823
<p>GeoDjango returns the Cartesian distance between points as a float value in degrees. To get the value of Distance in km or miles you can do the following: </p> <pre><code> dist = p1.distance(p2) dist.km # or dist.mi for miles </code></pre> <p>source: <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/gis/functions/#distance" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/contrib/gis/functions/#distance</a></p>
-1
2016-09-03T08:22:21Z
[ "python", "django", "gis", "geodjango" ]
How can calculate the real distance between two points with GeoDjango?
39,211,879
<pre><code>from django.contrib.gis.geos import Point p1 = Point(36.74851779201058, -6.429006806692149, srid=4326) p2 = Point(37.03254161520977, -8.98366068931684, srid=4326) p1.distance(p2) Out: 2.5703941316759376 </code></pre> <p>But what is the unit of this float number?</p> <p>If you calculate this distance, this is <a href="http://boulter.com/gps/distance/?from=36.74851779201058%2C-6.429006806692149&amp;to=37.03254161520977%2C%20-8.98366068931684&amp;units=k" rel="nofollow">229.88 Km</a>. You can get it too using geopy:</p> <pre><code>from geopy.distance import distance distance(p1, p2) Out: Distance(229.883275249) distance(p1, p2).km Out: 229.88327524944066 </code></pre> <p>I have read that you can get (so so) this, if you divide the previous number for 111:</p> <pre><code>(2.5703941316759376 / 111) * 10000 Out: 231.5670388897241 # kilometers </code></pre> <p>Is there any way to get the real distance using only GeoDjango? Or should I use geopy?</p>
3
2016-08-29T17:28:44Z
39,314,643
<p>Usually, all spatial calculations yield results in the same coordinate system as the input was given. In your case you should seek a calculation using the <em>SRID 4326</em> which is longitude/latitude polars in degrees from the prime meridian and equator.</p> <p>Consequently, GeoDjango's distance calculation - if I get it correctly - is the Euclidean distance between the two pairs of coordinates. You are searching for the <strong>big circle distance</strong> (where your division by <code>111</code> is just a rough approximation that is only close to the actual big circle distance in certain ranges of latitude).</p> <p><code>geopy</code> should use the big circle distance for <em>SRID 4326</em> implicitly, yielding the correct result.</p> <p>You now have a few different options:</p> <h2>A: Implement big circle on your own</h2> <p>Google for <code>haversine</code> formula, you can punch in two pairs of lat/lon coordinates and you should get a good approximation of the actual big circle distance. However, this depends on the mercator approximation that is used -- remember that Earth is not a sphere. You may run into problems near the poles with this.</p> <h2>B: Transform to a metric (local) coordinate system</h2> <p>If you transform your two locations to another coordinate system that is measured in meters, calculating the Euclidean distance will yield the correct result. However, such coordinate systems (call them <em>planar systems</em>) are different for various regions on the globe. There are different projections for different countries, as the approximation of the Earth's irregularly curved surface as a plane is errorneous -- especially not uniquely errorneous for any location on its surface.</p> <p>This is only applicable if all points among which you wish to calculate distances are in the same geographical region. </p> <h2>C: Use a library for this</h2> <p>Use <code>geopy</code> or <code>shapely</code> or any other qualified library that can calculate the actual big circle distance based on the <em>SRID</em> your points are given in. Remember that all coordinates are just approximations due to Earth's irregularity.</p>
2
2016-09-04T07:39:47Z
[ "python", "django", "gis", "geodjango" ]
Python regular expression returns nothing for match
39,211,916
<p>I am learning web scrapping using Python. I am trying to extract all links from one of popular financial site's site map.</p> <pre><code>bsObj = BeautifulSoup(html, "html.parser") for link in bsObj.findAll("a", href=re.compile("^(/india/stockmarket/pricechartquote/)*$")): if 'href' in link.attrs: print(link.attrs['href']) print('found nothing') </code></pre> <p>This code founds nothing. Although many links with above match is present in site. Sample : /india/stockmarket/pricechartquote/A</p>
-1
2016-08-29T17:30:50Z
39,211,963
<p>Have you tried checking if this regex matches the provided part of a url - it does not:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; &gt;&gt;&gt; pattern = re.compile("^(/india/stockmarket/pricechartquote/)*$") &gt;&gt;&gt; pattern.search("/india/stockmarket/pricechartquote/A") &gt;&gt;&gt; </code></pre> <p>Instead, you meant to have the last part after the <code>pricechartquote/</code> matching, for instance, one or more uppercase letters: </p> <pre><code>&gt;&gt;&gt; pattern = re.compile(r"^/india/stockmarket/pricechartquote/[A-Z]+$") &gt;&gt;&gt; pattern.search("/india/stockmarket/pricechartquote/A") &lt;_sre.SRE_Match object at 0x109240098&gt; </code></pre> <p>Please adjust the <code>[A-Z]+</code> part depending on what kind of character set you expect to see after <code>pricechartquote/</code>.</p> <hr> <p>Also note that you don't have to check the beginning and end of the string and might be good to go with a partial url match:</p> <pre><code>for link in bsObj.find_all("a", href=re.compile(r"/india/stockmarket/pricechartquote/")): # ... </code></pre>
2
2016-08-29T17:33:51Z
[ "python", "regex", "beautifulsoup" ]
Error Inserting data to mysql server through mysqldb in python
39,211,973
<p>MYsqldb is returning 1L when executing this:-</p> <pre><code>db=MySQLdb.connect('localhost','root','12345678','kitkat') cur=db.cursor() cur.execute("INSERT INTO justdial(id,email_raw,status) VALUES (NULL,'none','none')") </code></pre>
-2
2016-08-29T17:34:16Z
39,214,197
<p>If you are getting no errors Try adding db.commit after your execute</p> <p>I personally prefer mysql.connector.</p>
0
2016-08-29T19:58:00Z
[ "python", "sql", "mysql-python" ]
how to run jupyter notebook from 5th cell to 100th cell, without running other part of the notebook?
39,212,117
<p>Say I have a jupyter nootebook with 200 cells.</p> <p>how to run from 5th cell to 100th cell, without running other part of the notebook?</p> <p>Now I commend out 101th-200th and 1st-4th cell. I'm sure it is not the best practise.</p>
0
2016-08-29T17:43:45Z
39,217,231
<p>One cannot just run cells 5 thru 100 easily with the Jupyter notebook but there are a few options. The first is just selecting each cell and running <em>Merge Cell Above</em> from the edit menu then just running the new cell. The second, and best way I've found to do this is:</p> <ol> <li>First select the top cells to be ignored (or bottom if there are less on the bottom) and change the <em>Cell Type</em> to <em>Raw NBConvert</em> to prevent IPython from interpreting it.</li> </ol> <p><a href="http://i.stack.imgur.com/shtyk.png" rel="nofollow"><img src="http://i.stack.imgur.com/shtyk.png" alt="jupyter notebook menu Cell-&gt;Cell Type-&gt;Raw NB"></a></p> <ol start="2"> <li>Go to the cell after the one you want to run and select <em>Run All Above</em> (or below if less there).</li> </ol> <p><a href="http://i.stack.imgur.com/U8eHM.png" rel="nofollow"><img src="http://i.stack.imgur.com/U8eHM.png" alt="menu Cell-&gt;Run All Above"></a></p> <p>Now you've only run those middle cells and can just go back and reset the cell type to code (instead of having to comment and then un-comment) and keep going.</p> <p>* If you are using NBViewer you can <a href="http://stackoverflow.com/questions/27934885/how-to-hide-code-from-cells-in-ipython-notebook-visualized-with-nbviewer">hide the code</a> or just set it to <em>Markdown</em></p>
1
2016-08-30T00:42:42Z
[ "python", "jupyter" ]
python only writes last output to file
39,212,267
<p>I am trying to write a program that picks a random musical scale until all have been chosen, and the problem I have is that my code is only writing one line to my text file. </p> <p>I know this is a similar question to <a href="http://stackoverflow.com/questions/19419751/python-only-writes-last-line-of-output">Python: Only writes last line of output</a> but I have already tried the solution to open and then close the file outside of the loop (at least to the best of my ability, please correct me if I'm wrong).</p> <p>My code is this:</p> <pre><code>#imports the required library import random #picks 1 hands separate major scale def MajorScalesHandsSeparate(): #initialises the chars variable chars = 0 #creates the checker file if it has not previously been created while True: with open('MajorScalesHandsSeparate.txt', 'a') as f: break #counts the number of chars in the file with open('MajorScalesHandsSeparate.txt', 'r') as f: for line in f: chars += len(line) #converts file to list with open('MajorScalesHandsSeparate.csv', 'r') as f: MajorScalesHandsSeparate = [line.strip() for line in f] #opens file to check for the number of lines with open('MajorScalesHandsSeparate.csv', 'r') as f: Items = sum(1 for _ in f) #asks the user how many scales they would like NumScales = input("How many hands separate major scales would you like? ") #resets the loop counter and picker to 0 WhileControl = 0 ScalePicker = 0 '''HERE IS WHERE I BELIEVE I FOLLOWED THE LINKED QUESTION''' checker = open('MajorScalesHandsSeparate.txt', 'w+') #choses a number while WhileControl != NumScales: ScalePicker = random.randint(0, Items-1) #checks if scale has already been chosen if MajorScalesHandsSeparate[ScalePicker] not in open('MajorScalesHandsSeparate.txt').read(): #writes scale to file Scale=str(MajorScalesHandsSeparate[ScalePicker]) checker.seek(chars) checker.write(Scale + '\n') #prints chosen scale print MajorScalesHandsSeparate[ScalePicker] #increments the loop counter by one WhileControl = WhileControl + 1 #removes item from list else: MajorScalesHandsSeparate.remove(MajorScalesHandsSeparate[ScalePicker]) Items = Items - 1 #checks if all scales have been used if len(MajorScalesHandsSeparate) == 0: with open('MajorScalesHandsSeparate.csv', 'r') as f: #converts file to list once again MajorScalesHandsSeparate = [line.strip() for line in f] #closes the file checker.close() #calls the function MajorScalesHandsSeparate() </code></pre> <p>My output looks like this:</p> <pre><code>How many hands separate major scales would you like? 3 Db major RH only F# major LH only F# major RH only &gt;&gt;&gt; </code></pre> <p>But the text file reads:</p> <pre><code>F# major RH only </code></pre> <p>I want it to look like this:</p> <pre><code>Db major RH only F# major LH only F# major RH only </code></pre>
1
2016-08-29T17:54:01Z
39,212,485
<p>The code writes and overwrites at the same place in the output file. This is due to:</p> <pre><code>checker.seek(chars) checker.write(Scale + '\n') </code></pre> <p><code>chars</code> is set once and is never updated</p>
1
2016-08-29T18:07:21Z
[ "python", "list", "file", "append", "seek" ]
capture all matches in regex (g modifier not working for me)
39,212,327
<p>If I want to capture all of the last term in each product in this pattern:</p> <pre><code>PatternAnchor: Product-Computer-Keyboard, Product-Computer-Monitor, Product-Computer-Motherboard PatternEnd: </code></pre> <p>I tried this:</p> <pre><code>PatternAnchor: Product-(.*?)-(?P&lt;Item&gt;.*?)(,|PatternEnd:) </code></pre> <p>but I still only get the first match.</p> <p><a href="https://regex101.com/r/cR0aG8/1" rel="nofollow">https://regex101.com/r/cR0aG8/1</a></p>
1
2016-08-29T17:57:26Z
39,212,486
<p>If you want to match multiple strings starting with <code>Product-</code> with <code>PatternAnchor:</code> at start then you can use this PCRE regex with <code>\G</code></p> <pre><code>(?:PatternAnchor: |\G\h*,\h*)Product-([^-]*)-(?P&lt;Item&gt;[^,\h]*)(?=,|\h*PatternEnd:) </code></pre> <p><a href="https://regex101.com/r/cR0aG8/3" rel="nofollow">RegEx Demo</a></p> <p><code>\G</code> asserts position at the end of the previous match or the start of the string for the first match.</p> <hr> <p>Based on comments it seems OP wants a python specific regex. Since <code>\G</code> is not available in python regex one can use:</p> <pre><code>\bProduct-([^-]*)-(?P&lt;Item&gt;[^,\s]*)(?=,|\s*PatternEnd:) </code></pre> <p>and a separate check to ensure input starts with <code>PatternAnchor:</code>.</p> <p><a href="https://regex101.com/r/cR0aG8/4" rel="nofollow">RegEx Demo</a></p>
0
2016-08-29T18:07:27Z
[ "python", "regex" ]
capture all matches in regex (g modifier not working for me)
39,212,327
<p>If I want to capture all of the last term in each product in this pattern:</p> <pre><code>PatternAnchor: Product-Computer-Keyboard, Product-Computer-Monitor, Product-Computer-Motherboard PatternEnd: </code></pre> <p>I tried this:</p> <pre><code>PatternAnchor: Product-(.*?)-(?P&lt;Item&gt;.*?)(,|PatternEnd:) </code></pre> <p>but I still only get the first match.</p> <p><a href="https://regex101.com/r/cR0aG8/1" rel="nofollow">https://regex101.com/r/cR0aG8/1</a></p>
1
2016-08-29T17:57:26Z
39,213,131
<p>In Python, you may just use a 2 step approach:</p> <ul> <li>Check if the <code>PatternAnchor:</code> is present at the start of the string (note: this step might also be done with a regex in case of a more complex string)</li> <li>If yes, find all the patterns you need with a shorter <code>r'\bProduct-(.*?)-(?P&lt;Item&gt;.*?)(?:,|PatternEnd:)'</code> pattern.</li> </ul> <p>See this <a href="http://ideone.com/HKfAS8" rel="nofollow">Python demo</a>:</p> <pre><code>import re pat = r'\bProduct-(.*?)-(?P&lt;Item&gt;.*?)(?:,|PatternEnd:)' s = 'PatternAnchor: Product-Computer-Keyboard, Product-Computer-Monitor, Product-Computer-Motherboard PatternEnd:' res = [] if (s.startswith("PatternAnchor: ")): res = re.findall(pat, s[15:]) print(res) </code></pre>
0
2016-08-29T18:48:06Z
[ "python", "regex" ]
capture all matches in regex (g modifier not working for me)
39,212,327
<p>If I want to capture all of the last term in each product in this pattern:</p> <pre><code>PatternAnchor: Product-Computer-Keyboard, Product-Computer-Monitor, Product-Computer-Motherboard PatternEnd: </code></pre> <p>I tried this:</p> <pre><code>PatternAnchor: Product-(.*?)-(?P&lt;Item&gt;.*?)(,|PatternEnd:) </code></pre> <p>but I still only get the first match.</p> <p><a href="https://regex101.com/r/cR0aG8/1" rel="nofollow">https://regex101.com/r/cR0aG8/1</a></p>
1
2016-08-29T17:57:26Z
39,241,253
<p>Is this what you want? </p> <p><a href="https://regex101.com/r/mM1cV0/2" rel="nofollow">https://regex101.com/r/mM1cV0/2</a></p> <p>Your description and code/example feels very different to each other.</p>
0
2016-08-31T05:14:52Z
[ "python", "regex" ]
pandas drop rows with duplicates in some columns relative to other columns
39,212,332
<p>consider the dataframe <code>df</code></p> <pre><code>data = [ ['a', 'b', 'c', 'd'], ['a', 'b', 'e', 'f'], ['g', 'h', 'i', 'j'], ['k', 'l', 'm', 'n'], ['m', 'n', 'o', 'p'], ['q', 'r', 's', 't'], ['u', 'v', 'w', 'x'], ['y', 'z', 'q', 'r'], ] cols = pd.MultiIndex.from_product([list('AB'), list('XY')]) df = pd.DataFrame(data, columns=cols) df </code></pre> <p><a href="http://i.stack.imgur.com/cXM4G.png" rel="nofollow"><img src="http://i.stack.imgur.com/cXM4G.png" alt="enter image description here"></a></p> <p>I want to compare all rows of <code>df.A</code> with all rows of <code>df.B</code> and drop the rows that have matches. I do <strong>not</strong> want to drop rows that have mathces within <code>df.A</code> or <code>df.B</code> by themselves.</p> <p><strong><em>Visual</em></strong></p> <p><a href="http://i.stack.imgur.com/5u95A.png" rel="nofollow"><img src="http://i.stack.imgur.com/5u95A.png" alt="enter image description here"></a></p> <ul> <li>leave rows <code>[0, 1]</code> alone.</li> <li>drop rows <code>[3, 4]</code> because <code>'m', 'n'</code> match</li> <li>drop rows <code>[5, 7]</code> because <code>'q', 'r'</code> match</li> </ul> <p>Results should look like</p> <pre><code>df.loc[[0, 1, 2, 6]] </code></pre> <p><a href="http://i.stack.imgur.com/8EFA7.png" rel="nofollow"><img src="http://i.stack.imgur.com/8EFA7.png" alt="enter image description here"></a></p> <hr> <p><strong><em>I've tried</em></strong> to <code>stack</code> and <code>drop_duplicates</code></p> <pre><code>df.stack(0).drop_duplicates(keep=False) \ .unstack().dropna() \ .swaplevel(0, 1, 1).sort_index(1) </code></pre> <p><a href="http://i.stack.imgur.com/M33AL.png" rel="nofollow"><img src="http://i.stack.imgur.com/M33AL.png" alt="enter image description here"></a></p> <p>But that catches duplicates in the same sub-columns, which isn't what I want.</p>
3
2016-08-29T17:57:38Z
39,212,476
<p>try this:</p> <pre><code>In [248]: df[~(df.A.isin(df.B.to_dict('list')).all(1) | df.B.isin(df.A.to_dict('list')).all(1))] Out[248]: A B X Y X Y 0 a b c d 1 a b e f 2 g h i j 6 u v w x </code></pre> <p>Explanation:</p> <pre><code>In [249]: df.A.isin(df.B.to_dict('list')) Out[249]: X Y 0 False False 1 False False 2 False False 3 False False 4 True True 5 True True 6 False False 7 False False In [250]: df.A.isin(df.B.to_dict('list')).all(1) Out[250]: 0 False 1 False 2 False 3 False 4 True 5 True 6 False 7 False dtype: bool In [251]: df.B.isin(df.A.to_dict('list')) Out[251]: X Y 0 False False 1 False False 2 False False 3 True True 4 False False 5 False False 6 False False 7 True True In [252]: df.B.isin(df.A.to_dict('list')).all(1) Out[252]: 0 False 1 False 2 False 3 True 4 False 5 False 6 False 7 True dtype: bool </code></pre> <p>combining both:</p> <pre><code>In [253]: df.A.isin(df.B.to_dict('list')).all(1) | df.B.isin(df.A.to_dict('list')).all(1) Out[253]: 0 False 1 False 2 False 3 True 4 True 5 True 6 False 7 True dtype: bool </code></pre>
3
2016-08-29T18:06:59Z
[ "python", "pandas" ]
IF statement picking first option in currency converter (python)
39,212,354
<pre><code>print "Pound Sterling converter" print "You can convert pounds to either dollars, euros or yen" print dollar = 0 euro = 0 yen = 0 convert_to = input ("What currency do you want to convert to? ") amount = input("How much would you like to convert? ") print if convert_to == dollar: amount = amount * 1.3 elif convert_to == euro: amount = amount * 1.17 elif convert_to == yen: amount = amount * 133.66 else: print "You must pick either dollar, euro or yen." print amount </code></pre> <p>I'm a beginner in Python, as you can probably tell. All I want this program to do is have the user choose a currency (convert_to) and then choose how much they want to convert (amount) and then the program will convert it for them.</p> <p>When I run the program, the if statement does not work correctly. Instead of seeing what convert_to is, it goes through the convert_to == dollar part regardless of if you type euro or yen. The numbers they are being multiplied by are simply the conversion rates from pounds.</p> <p>also, a side note but less important one, the final else part does not work. The program brings up a "input not defined" error instead of printing "You must pick either dollar, euro or yen."</p> <p>Thanks in advance</p>
0
2016-08-29T17:59:07Z
39,212,532
<p>Please try to change to this:</p> <pre><code>if convert_to == "dollar": amount = float(amount) * 1.3 elif convert_to == "euro": amount = float(amount) * 1.17 elif convert_to == "yen": amount = float(amount) * 133.66 </code></pre> <p>There are 2 changes. First one is to set currencies (dollar , euro , yen) to string cause that way it will be possible to compare it with the user's input which will be also a string. Second, amount that is entered by user is string again so we have to convert it to float in order to calculate the converted amount.</p>
1
2016-08-29T18:10:41Z
[ "python", "if-statement" ]
IF statement picking first option in currency converter (python)
39,212,354
<pre><code>print "Pound Sterling converter" print "You can convert pounds to either dollars, euros or yen" print dollar = 0 euro = 0 yen = 0 convert_to = input ("What currency do you want to convert to? ") amount = input("How much would you like to convert? ") print if convert_to == dollar: amount = amount * 1.3 elif convert_to == euro: amount = amount * 1.17 elif convert_to == yen: amount = amount * 133.66 else: print "You must pick either dollar, euro or yen." print amount </code></pre> <p>I'm a beginner in Python, as you can probably tell. All I want this program to do is have the user choose a currency (convert_to) and then choose how much they want to convert (amount) and then the program will convert it for them.</p> <p>When I run the program, the if statement does not work correctly. Instead of seeing what convert_to is, it goes through the convert_to == dollar part regardless of if you type euro or yen. The numbers they are being multiplied by are simply the conversion rates from pounds.</p> <p>also, a side note but less important one, the final else part does not work. The program brings up a "input not defined" error instead of printing "You must pick either dollar, euro or yen."</p> <p>Thanks in advance</p>
0
2016-08-29T17:59:07Z
39,212,583
<p>Your code is not working because you're assuming that the <code>input()</code> function returns an integer. It does not. The <code>input()</code> function returns a string, so this:</p> <p><code>convert_to == dollars</code> </p> <p>is equal to: </p> <p><code>str == 1</code></p> <p>which will never be true. Just change what you're comparing to to a string. Instead of using a variable just say <code>convert_to == "dollars"</code>, and so on for the other choices. Also, you must change this line <code>amount = input("How much would you like to convert? ")</code> to this <code>amount = int(input("How much would you like to convert? "))</code>, so you can get the input as an integer and not a string.</p> <pre><code>print "Pound Sterling converter" print "You can convert pounds to either dollars, euros or yen" convert_to = raw_input("What currency do you want to convert to? ") amount = int(raw_input("How much would you like to convert? ")) if convert_to == "dollars": amount *= 1.3 elif convert_to == "euros": amount *= 1.17 elif convert_to == "yen": amount *= 133.66 else: print "You must pick either dollar, euro or yen." print amount </code></pre>
0
2016-08-29T18:14:30Z
[ "python", "if-statement" ]
IF statement picking first option in currency converter (python)
39,212,354
<pre><code>print "Pound Sterling converter" print "You can convert pounds to either dollars, euros or yen" print dollar = 0 euro = 0 yen = 0 convert_to = input ("What currency do you want to convert to? ") amount = input("How much would you like to convert? ") print if convert_to == dollar: amount = amount * 1.3 elif convert_to == euro: amount = amount * 1.17 elif convert_to == yen: amount = amount * 133.66 else: print "You must pick either dollar, euro or yen." print amount </code></pre> <p>I'm a beginner in Python, as you can probably tell. All I want this program to do is have the user choose a currency (convert_to) and then choose how much they want to convert (amount) and then the program will convert it for them.</p> <p>When I run the program, the if statement does not work correctly. Instead of seeing what convert_to is, it goes through the convert_to == dollar part regardless of if you type euro or yen. The numbers they are being multiplied by are simply the conversion rates from pounds.</p> <p>also, a side note but less important one, the final else part does not work. The program brings up a "input not defined" error instead of printing "You must pick either dollar, euro or yen."</p> <p>Thanks in advance</p>
0
2016-08-29T17:59:07Z
39,212,588
<p>First of all dollar, euro and yen have the same start value (0).</p> <p>I think, you must put different values.</p> <pre><code>dollar = 0 euro = 1 yen = 2 </code></pre> <p>Then, you can show amount (print amount) but your calculate value is "amountpython".</p>
0
2016-08-29T18:14:46Z
[ "python", "if-statement" ]
IF statement picking first option in currency converter (python)
39,212,354
<pre><code>print "Pound Sterling converter" print "You can convert pounds to either dollars, euros or yen" print dollar = 0 euro = 0 yen = 0 convert_to = input ("What currency do you want to convert to? ") amount = input("How much would you like to convert? ") print if convert_to == dollar: amount = amount * 1.3 elif convert_to == euro: amount = amount * 1.17 elif convert_to == yen: amount = amount * 133.66 else: print "You must pick either dollar, euro or yen." print amount </code></pre> <p>I'm a beginner in Python, as you can probably tell. All I want this program to do is have the user choose a currency (convert_to) and then choose how much they want to convert (amount) and then the program will convert it for them.</p> <p>When I run the program, the if statement does not work correctly. Instead of seeing what convert_to is, it goes through the convert_to == dollar part regardless of if you type euro or yen. The numbers they are being multiplied by are simply the conversion rates from pounds.</p> <p>also, a side note but less important one, the final else part does not work. The program brings up a "input not defined" error instead of printing "You must pick either dollar, euro or yen."</p> <p>Thanks in advance</p>
0
2016-08-29T17:59:07Z
39,212,703
<p>If i understand correctly, the user will input either "0", "1" or "2" as a input, for the convertion for dollar, euro or yen respectively. So you need to change the initial values of dollar, euro and yen. Changing that, the version with integer input will work.</p> <pre><code>dollar = 0 euro = 1 yen = 2 </code></pre> <p>If the input is a string such as "dollar", "euro" or "yen", the variables need to be changed to these respective strings, so firstly you need to set the variable as:</p> <pre><code>dollar = "dollar" euro = "euro" yen = "yen" </code></pre> <p>Then change the input type for raw_input, as python requires this type of input to recognize a String input. So change <code>convert_to</code> to:</p> <pre><code>convert_to = raw_input ("What currency do you want to convert to? ") </code></pre> <p>If you try to pass a string to a <code>input</code> variable it will always return 0. And since the initial values for all the variable are 0, the if statements returns true when comparing <code>convert_to</code> to <code>dollar</code> , <code>euro</code> or <code>yen</code>. Because the comparsion to the dollar is hapening first, it always goes to that case. These are the changes necessary for the code to run.</p> <p>Extra: You also don't need the variables in this case, since you're only using them in one field. So on your if statements, you can just compare them to the specific strings, as:</p> <pre><code>if convert_to == "dollars": amount *= 1.3 elif convert_to == "euros": amount *= 1.17 elif convert_to == "yen": amount *= 133.66 else: print "You must pick either dollar, euro or yen." </code></pre> <p>Hope it helps.</p>
1
2016-08-29T18:23:32Z
[ "python", "if-statement" ]
IF statement picking first option in currency converter (python)
39,212,354
<pre><code>print "Pound Sterling converter" print "You can convert pounds to either dollars, euros or yen" print dollar = 0 euro = 0 yen = 0 convert_to = input ("What currency do you want to convert to? ") amount = input("How much would you like to convert? ") print if convert_to == dollar: amount = amount * 1.3 elif convert_to == euro: amount = amount * 1.17 elif convert_to == yen: amount = amount * 133.66 else: print "You must pick either dollar, euro or yen." print amount </code></pre> <p>I'm a beginner in Python, as you can probably tell. All I want this program to do is have the user choose a currency (convert_to) and then choose how much they want to convert (amount) and then the program will convert it for them.</p> <p>When I run the program, the if statement does not work correctly. Instead of seeing what convert_to is, it goes through the convert_to == dollar part regardless of if you type euro or yen. The numbers they are being multiplied by are simply the conversion rates from pounds.</p> <p>also, a side note but less important one, the final else part does not work. The program brings up a "input not defined" error instead of printing "You must pick either dollar, euro or yen."</p> <p>Thanks in advance</p>
0
2016-08-29T17:59:07Z
39,212,860
<p>In your case dollar, euro and yen , you have initialized to the same value that is zero. You should assign different values , for example;</p> <pre><code>dollar=0 euro=0 yen=0 </code></pre> <p>Then try this</p> <pre><code>print "Pound Sterling converter" print "You can convert pounds to either dollars, euros or yen" convert_to = input ("What currency do you want to convert to? ") amount = int(input("How much would you like to convert? ")) if convert_to == "dollars": amount *= 1.3 elif convert_to == "euros": amount *= 1.17 elif convert_to == "yen": amount *= 133.66 else: print "You must pick either dollar, euro or yen." print amount </code></pre>
0
2016-08-29T18:32:03Z
[ "python", "if-statement" ]
Can't get Django to work on my Mac
39,212,384
<p>I'm having difficulty getting Django to work on my Mac. I pip installed it, as well as downloading it on PyCharm. I have a feeling it will work on PyCharm if I knew what I'm doing. I dont. haha. It's my first time. I am trying to work off the tutorial that they provide on their site. Here is where I run into trouble.</p> <p>In terminal I type:</p> <pre><code>python -m django --version </code></pre> <p>and I get:</p> <pre><code>/usr/bin/python: No module named django </code></pre> <p>but when I type:</p> <pre><code>pip install Django </code></pre> <p>I get:</p> <pre><code>Requirement already satisfied (use --upgrade to upgrade): Django in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages </code></pre> <p>The tutorial wants me to type:</p> <pre><code>django-admin startproject mysite </code></pre> <p>and I get this:</p> <pre><code>-bash: django-admin: command not found </code></pre> <p>So to my question. What is going on here? I'm thinking my path to it is different than what is expected, though I'm not fully sure. If you know the startproject mysite could you give it to me? Meaning, if you know the folders and content I think I could get it running on PyCharm. My PyCharm says it's been downloaded, so I think this would be a great way to go into it. </p> <p>Many thanks.</p>
0
2016-08-29T18:01:11Z
39,213,408
<p>Seems to me that pip is not configured with the python that you are using. From the output you posted, pip is installing Django for the python executable residing in here:</p> <pre><code>/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages </code></pre> <p>what is the output of <code>ls -l $(which python)</code> ?</p> <p>This will tell you where the python you are using is. If it's different than the path above, pip is installing packages on another python executable.</p> <p>You have 2 quick options.</p> <ol> <li><p>Put a softlink to the python residing in <code>/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages</code> inside your <code>/usr/bin/</code> or wherever is imported before the path that <code>which python</code> shows.</p> <p>ln -s {target-filename} {symbolic-filename} </p></li> </ol> <p>which is probably</p> <pre><code>ln -s /Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /usr/bin/python </code></pre> <ol start="2"> <li><p>Use a <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/" rel="nofollow">Virtual Environment</a>.</p> <p>pyenv ./env<br> source ./env/bin/activate</p></li> </ol> <p>Now you are working on a virtual environment, which has its own pip and python so you should be fine to do anything you'd want !</p> <p>Hope it helps</p>
0
2016-08-29T19:05:33Z
[ "python", "django", "osx", "terminal" ]
Can't get Django to work on my Mac
39,212,384
<p>I'm having difficulty getting Django to work on my Mac. I pip installed it, as well as downloading it on PyCharm. I have a feeling it will work on PyCharm if I knew what I'm doing. I dont. haha. It's my first time. I am trying to work off the tutorial that they provide on their site. Here is where I run into trouble.</p> <p>In terminal I type:</p> <pre><code>python -m django --version </code></pre> <p>and I get:</p> <pre><code>/usr/bin/python: No module named django </code></pre> <p>but when I type:</p> <pre><code>pip install Django </code></pre> <p>I get:</p> <pre><code>Requirement already satisfied (use --upgrade to upgrade): Django in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages </code></pre> <p>The tutorial wants me to type:</p> <pre><code>django-admin startproject mysite </code></pre> <p>and I get this:</p> <pre><code>-bash: django-admin: command not found </code></pre> <p>So to my question. What is going on here? I'm thinking my path to it is different than what is expected, though I'm not fully sure. If you know the startproject mysite could you give it to me? Meaning, if you know the folders and content I think I could get it running on PyCharm. My PyCharm says it's been downloaded, so I think this would be a great way to go into it. </p> <p>Many thanks.</p>
0
2016-08-29T18:01:11Z
39,215,077
<p><strong>From Comments</strong></p> <p>Looks like a virtual environment problem. Without going into the extreme details of your environment settings, try the following: make and navigate to an empty directory, type <code>pyvenv-3.5 ./Env</code>, then <code>source ./Env/bin/activate</code>, next <code>pip install django</code>, and finally <code>python -m django --version</code>. This virtual environment should work and be less prone to other odd PATH problems. </p> <p><strong>Additional Info</strong></p> <p>You will need to run the command <code>source ./Env/bin/activate</code> when you open up a new shell or run a bash script in order to active this environment.</p> <p>Also, you can now manage your pip packages (including django) by using <code>pip freeze &gt; ./requirements.txt</code> to create a lists of your packages w/ version numbers and 'pip install -r ./requirements.txt` to install the packages.</p>
0
2016-08-29T20:56:40Z
[ "python", "django", "osx", "terminal" ]
How to check environment variables in python
39,212,491
<p>How to check all environment variables in python. I'm trying to install cx_Oracle and instant client and want to make sure all my variables are ok. </p>
-1
2016-08-29T18:07:51Z
39,212,652
<p>To elaborate further on my comment. All environment variables can be found within the <code>os.environ</code> dictionary (you'll need to <code>import os</code> first).</p> <p>It looks like <code>TNS_ADMIN</code> is one of the environment variables used for <code>tnsnames.ora</code>, so you can check like this:</p> <pre><code>import os if 'TNS_ADMIN' in os.environ: print('TNS_ADMIN is set to {}'.format(os.environ['TNS_ADMIN'])) else: print('TNS_ADMIN has not been set.') </code></pre>
1
2016-08-29T18:19:42Z
[ "python", "oracle11g", "cx-oracle" ]
Django use URL tag in template from app specific urls?
39,212,519
<p>I have the following URLs in my project <code>urls.py</code></p> <pre><code>urlpatterns = i18n_patterns( url(r'^register/', include('register.urls')), ) </code></pre> <p>So I maintain urls in the register app, so the <code>urls.py</code> in my <code>register</code> app looks like this:</p> <pre><code>urlpatterns = patterns( url(r'^test/$', views.Test, name="register_test"), ) </code></pre> <p>So I have a template that is located outside the register app, is located in the root of the project, and I am trying to use the above url like this:</p> <pre><code>&lt;a href="{% url 'register_test' %}"/&gt;Test&lt;/a&gt; </code></pre> <p>But I get the following error:</p> <pre><code>NoReverseMatch at /en/ Reverse for 'register_test' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] </code></pre>
0
2016-08-29T18:09:38Z
39,212,556
<p>Have you tried: <code>&lt;a href="{% url 'register:register_test' %}"/&gt;Test&lt;/a&gt;</code>? You might want to give the register urls a name space first though:</p> <p>urls.py</p> <pre><code>urlpatterns = i18n_patterns( url(r'^register/', include('register.urls', namespace='register'), ) </code></pre> <p>urls.py in register app:</p> <pre><code>urlpatterns = patterns( 'register.views', url(r'^test/$', 'Test', name="register_test"), ) </code></pre> <p>Django doc about <a href="https://docs.djangoproject.com/en/1.10/topics/http/urls/#url-namespaces" rel="nofollow">url namespace</a>.</p>
1
2016-08-29T18:12:05Z
[ "python", "django", "url" ]
Django use URL tag in template from app specific urls?
39,212,519
<p>I have the following URLs in my project <code>urls.py</code></p> <pre><code>urlpatterns = i18n_patterns( url(r'^register/', include('register.urls')), ) </code></pre> <p>So I maintain urls in the register app, so the <code>urls.py</code> in my <code>register</code> app looks like this:</p> <pre><code>urlpatterns = patterns( url(r'^test/$', views.Test, name="register_test"), ) </code></pre> <p>So I have a template that is located outside the register app, is located in the root of the project, and I am trying to use the above url like this:</p> <pre><code>&lt;a href="{% url 'register_test' %}"/&gt;Test&lt;/a&gt; </code></pre> <p>But I get the following error:</p> <pre><code>NoReverseMatch at /en/ Reverse for 'register_test' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] </code></pre>
0
2016-08-29T18:09:38Z
39,212,623
<p>project urls.py</p> <pre><code>urlpatterns = i18n_patterns( url(r'^register/', include('register.urls', namespace="register")), ) </code></pre> <p>app urls.py</p> <pre><code>urlpatterns = patterns( url(r'^test/$', views.Test, name="register_test"), ) </code></pre> <p>template.html</p> <pre><code>&lt;a href="{% url 'register:register_test' %}"/&gt;Test&lt;/a&gt; </code></pre>
0
2016-08-29T18:17:48Z
[ "python", "django", "url" ]
Is there a way to create and name an object/class, as well as run a method of the class in the same line?
39,212,524
<p>I am just trying to clean up some code and I was wondering if there is a way to create a new named object as well as run a method in the objects class in the same line. For example:</p> <pre><code>self.equipment_widgets["NumOfStagesLabelCentComp"]=tk.Label(self.parent, text="Number of Stages:", bg="white") self.equipment_widgets["NumOfStagesLabelCentComp"].place(relx=0.5, y=260, anchor="center") </code></pre> <p>In the first line, I am initializing a new <code>tk.Label</code> class as an object in a dictionary called <code>equipment_widgets</code>. In the next line, I use the <code>place()</code> method to place the label object in my GUI.</p> <p>If I put <code>.place</code> at the end of the first line instead, a <code>nonetype</code> object is created.</p>
0
2016-08-29T18:10:14Z
39,212,701
<p>You need to design your class methods to be chainable, which means that all methods that just modify the object (as opposed to returning information from the object) should end with <code>return self</code>. This allows you to write:</p> <pre><code>object.method1(...).method2(...).method3(...) </code></pre> <p>If the <code>place()</code> method is designed this way, you should be able to use it on the first line.</p> <pre><code>self.equipment_widgets["NumOfStagesLabelCentComp"]=tk.Label(self.parent, text="Number of Stages:", bg="white").place(relx=0.5, y=260, anchor="center") </code></pre> <p>Note that most mutating methods in Python's standard classes are not chainable, they typically return <code>None</code>. So this type of programming is not very pythonic.</p>
1
2016-08-29T18:23:22Z
[ "python", "python-2.7", "tkinter" ]
Unable to pipe python output to program
39,212,541
<p>I want to pipe stdout from python to another program, but I am faceing a problem where my stdout is not piped.</p> <p>I have it shortened down to a simple sample:</p> <pre><code>import time while True: print("Hello!") time.sleep(1) </code></pre> <p>I check it with cat like so:</p> <pre><code>./my_python_script.py | cat </code></pre> <p>And then I get nothing at all.</p> <p>Strange thing is that it works just fine if i remove the sleep command. However, I do not want to pipe the output that fast, so I would really like to sleep for a second.</p> <p>I checked with the corresponding bash script:</p> <pre><code>while true; do echo "Hello!" sleep 1 done </code></pre> <p>And that works like a charm too. So any idea as to why the python script does not pipe the output as expected? Thanks!</p>
1
2016-08-29T18:11:20Z
39,212,574
<p>You'll need to flush the stdout:</p> <pre><code>import time import sys while True: print("Hello!") sys.stdout.flush() time.sleep(1) </code></pre>
4
2016-08-29T18:13:44Z
[ "python", "linux" ]
Querying postgresql for DateTime values between two dates
39,212,620
<p>I have the following dateTime text type variable in Postgres table</p> <pre><code>"2016-05-12T23:59:11+00:00" "2016-05-13T11:00:11+00:00" "2016-05-13T23:59:11+00:00" "2016-05-15T10:10:11+00:00" "2016-05-16T10:10:11+00:00" "2016-05-17T10:10:11+00:00" </code></pre> <p>I have to write a Python function to extract the data for a few variables between two dates</p> <pre><code>def fn(dateTime): df1=pd.DataFrame() query = """ SELECT "recordId" from "Table" where "dateTime" BETWEEN %s AND %s """ %(dStart,dEnd) df1=pd.read_sql_query(query1,con=engine) return df1 </code></pre> <p>I need to create dStart and dEnd variables and use them as function parameters as below</p> <pre><code> fn('2016-05-12','2016-05-15') </code></pre> <p>I tried using to_char("dateTime", 'YYYY-MM-DD') Postgres function but didn't work out. Please let me know how to solve this</p>
0
2016-08-29T18:17:32Z
39,213,596
<p>I'm not familiar with postgresql, but you can convert the strings to the <code>struct_time</code> class which is part of the built in <a href="https://docs.python.org/3/library/time.html" rel="nofollow"><code>time</code> package</a> in Python and simply make comparisons between them.</p> <pre><code>import time time_data = ["2016-05-12T23:59:11+00:00", "2016-05-13T11:00:11+00:00", "2016-05-13T23:59:11+00:00", "2016-05-15T10:10:11+00:00", "2016-05-16T10:10:11+00:00", "2016-05-17T10:10:11+00:00"] def fn(t_init, t_fin, t_all): # Convert string inputs to struct_time using time.strptime() t_init, t_fin = [time.strptime(x, '%Y-%m-%d') for x in [t_init, t_fin]] t_all = [time.strptime(x, '%Y-%m-%dT%H:%M:%S+00:00') for x in time_all] out = [] for jj in range(len(t_all)): if t_init &lt; t_all[jj] &lt; t_fin: out.append(jj) return out out = fn('2016-05-12','2016-05-15', time_data) print(out) # [0, 1, 2] </code></pre> <p>The <code>time.strptime</code> routine uses a format specifiers to specify which parts of the string correspond to different time components. </p> <pre><code>%Y Year with century as a decimal number. %m Month as a decimal number [01,12]. %d Day of the month as a decimal number [01,31]. %H Hour (24-hour clock) as a decimal number [00,23]. %M Minute as a decimal number [00,59]. %S Second as a decimal number [00,61]. %z Time zone offset from UTC. %a Locale's abbreviated weekday name. %A Locale's full weekday name. %b Locale's abbreviated month name. %B Locale's full month name. %c Locale's appropriate date and time representation. %I Hour (12-hour clock) as a decimal number [01,12]. %p Locale's equivalent of either AM or PM. </code></pre>
0
2016-08-29T19:18:55Z
[ "python", "postgresql", "datetime", "pandas" ]
Querying postgresql for DateTime values between two dates
39,212,620
<p>I have the following dateTime text type variable in Postgres table</p> <pre><code>"2016-05-12T23:59:11+00:00" "2016-05-13T11:00:11+00:00" "2016-05-13T23:59:11+00:00" "2016-05-15T10:10:11+00:00" "2016-05-16T10:10:11+00:00" "2016-05-17T10:10:11+00:00" </code></pre> <p>I have to write a Python function to extract the data for a few variables between two dates</p> <pre><code>def fn(dateTime): df1=pd.DataFrame() query = """ SELECT "recordId" from "Table" where "dateTime" BETWEEN %s AND %s """ %(dStart,dEnd) df1=pd.read_sql_query(query1,con=engine) return df1 </code></pre> <p>I need to create dStart and dEnd variables and use them as function parameters as below</p> <pre><code> fn('2016-05-12','2016-05-15') </code></pre> <p>I tried using to_char("dateTime", 'YYYY-MM-DD') Postgres function but didn't work out. Please let me know how to solve this</p>
0
2016-08-29T18:17:32Z
39,214,437
<p>When working with sql, you should always use your sql library to substitute parameters into the query, instead of using Python's string operators. This avoids the risk of malformed queries or sql injection attacks. See e.g., <a href="http://bugcharmer.blogspot.com/2013/03/basics-avoiding-sql-injection.html" rel="nofollow">this page</a>. Right now your code won't run because it directly inserts <code>dStart</code> and <code>dEnd</code> without any quoting, so they are interpreted as mathematical expressions (2016 - 5 - 12 = 1999).</p> <p>There's also a secondary problem that your query will exclude <code>dateTime</code> values <em>on</em> the end date, because <code>endDate</code> will be treated as having a time value of 00:00:00 when it is compared to <code>dateTime</code>. And if you use <code>to_char()</code> or some other function to extract just the date from the <code>dateTime</code> column to do the comparison, it will prevent your query from using indexes, making it very inefficient. </p> <p>Here is some revised code that may work for you:</p> <pre><code>def fn(dStart, dEnd): query = """ SELECT "recordId" FROM "Table" WHERE "dateTime" &gt;= %(start)s AND "dateTime" &lt; %(end)s + interval '1 day' """ query_params = {'start': dStart, 'end': dEnd} df1 = pd.read_sql_query(query1, con=engine, params=query_params) return df1 </code></pre> <p>This code relies on a few assumptions (welcome to the wonderful world of datetime querying!): </p> <ol> <li>you will pass <code>dStart</code> and <code>dEnd</code> to <code>fn()</code>, instead of just a single <code>dateTime</code>, </li> <li>the <code>dateTime</code> column is type <code>timestamp with timezone</code> (not <code>text</code>), </li> <li>the timezones in the <code>dateTime</code> column are correct, and</li> <li>the dates given by <code>dStart</code> and <code>dEnd</code> are in the server's timezone or you have used <code>SET TIMEZONE ...</code> with your <code>engine</code> object to select the right time zone to use for this session.</li> </ol> <h3>Notes</h3> <p>Different database engines use <a href="https://www.python.org/dev/peps/pep-0249/#paramstyle" rel="nofollow">different placeholders</a> for the parameters, so you will need to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_query.html" rel="nofollow">check your database driver's documentation</a> to decide what placeholders to use. The code above should work fine for postgresql.</p> <p>With the code above, <code>dStart</code> and <code>dEnd</code> will be inserted into the query as strings, and postgresql automatically convert them into timestamps when it runs the query. This should work fine for the example dates you gave, but if you need more direct control, you have two options:</p> <ol> <li>call <code>fn()</code> with Python <code>date</code> or <code>datetime</code> values for <code>dStart</code> and <code>dEnd</code>, and the code above will insert them into the query as postgresql dates or timestamps; or </li> <li>explicitly convert the <code>dStart</code> and <code>dEnd</code> strings into postgresql dates by replacing <code>%(start)s</code> and <code>%(end)s</code> with something like this: <code>to_date(%(start)s, 'YYYY-MM-DD')</code>.</li> </ol>
0
2016-08-29T20:13:36Z
[ "python", "postgresql", "datetime", "pandas" ]
Why print command gives a new line even though there is no data to print
39,212,632
<p>Just typing <code>print</code> only gives newline in python. Typing <code>print</code> without the brackets in 3.x will also gives a newline. Why?</p>
2
2016-08-29T18:18:24Z
39,212,664
<p>Because <a href="https://docs.python.org/3/library/functions.html#print">the documentation</a> says so</p> <blockquote> <p><code>print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)</code></p> <p>Print objects to the text stream file, separated by sep and followed by end. sep, end and file, if present, must be given as keyword arguments.</p> <p>All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. <strong>If no objects are given, <code>print()</code> will just write <code>end</code>.</strong></p> <p>The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.</p> <p>Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.</p> <p>Changed in version 3.3: Added the flush keyword argument.</p> </blockquote> <p>Note that <code>end</code> is defaulted to <code>'\n'</code> which is a new line.</p>
6
2016-08-29T18:20:42Z
[ "python", "python-2.7", "python-3.x" ]
Why print command gives a new line even though there is no data to print
39,212,632
<p>Just typing <code>print</code> only gives newline in python. Typing <code>print</code> without the brackets in 3.x will also gives a newline. Why?</p>
2
2016-08-29T18:18:24Z
39,212,669
<p>In Python 3, print is now a function. It will print a new line character at the end of your statement. </p> <p>If you don't specify an "end" it will by default use a new line character. </p> <p>You can prevent this by doing something such as:</p> <pre><code>print("hello world", end="") </code></pre>
1
2016-08-29T18:21:23Z
[ "python", "python-2.7", "python-3.x" ]
Why print command gives a new line even though there is no data to print
39,212,632
<p>Just typing <code>print</code> only gives newline in python. Typing <code>print</code> without the brackets in 3.x will also gives a newline. Why?</p>
2
2016-08-29T18:18:24Z
39,213,065
<p>It is interesting how languages differ in this. </p> <p><code>print</code> in the Korn shell (ksh) has the same behaviour as <code>python</code>, i.e. it adds a newline. Bash does not have a <code>print</code>, relying on <code>echo</code> instead, which also adds a newline (which, like python, can be suppressed).</p> <p><code>print</code> in Perl does not, and caused so much inconvenience that another version, called <code>say</code>, was added which does add a newline. </p> <p>Ruby and PHP are like Perl in that <code>print</code> also does not add a newline. This of course is less of an issue when embedded in HTML.</p> <p>If you look at other languages, for example <a href="http://c2.com/cgi/wiki?HelloWorldInManyProgrammingLanguages" rel="nofollow">here</a> you will find opinion divided as to whether a newline should be added or not. The removal of the newline in Python is discussed in <a href="https://www.python.org/dev/peps/pep-0259/" rel="nofollow">PEP259</a>.</p>
1
2016-08-29T18:43:25Z
[ "python", "python-2.7", "python-3.x" ]
Why print command gives a new line even though there is no data to print
39,212,632
<p>Just typing <code>print</code> only gives newline in python. Typing <code>print</code> without the brackets in 3.x will also gives a newline. Why?</p>
2
2016-08-29T18:18:24Z
39,213,600
<p>Because the default parameter in print is \n for the end, though if you pass parameter for print end variable as \t or space , then you can see the same ! </p> <p>But it works 2.7 and above!</p>
1
2016-08-29T19:19:17Z
[ "python", "python-2.7", "python-3.x" ]
How can I convert a list to named variables in Python?
39,212,783
<p>Is there a quick way in python to convert a list of values to named variables?</p> <p>For example:</p> <pre><code>row = ['files', 'file.pdf', 'D1234', 43] folder = row[0] name = row[1] doc_id = row[2] page_num = row[3] </code></pre>
0
2016-08-29T18:27:54Z
39,212,797
<p>You can use <a href="https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists">unpacking</a></p> <pre><code>folder, name, doc_id, page_num = row </code></pre>
5
2016-08-29T18:28:54Z
[ "python", "list" ]
How can I convert a list to named variables in Python?
39,212,783
<p>Is there a quick way in python to convert a list of values to named variables?</p> <p>For example:</p> <pre><code>row = ['files', 'file.pdf', 'D1234', 43] folder = row[0] name = row[1] doc_id = row[2] page_num = row[3] </code></pre>
0
2016-08-29T18:27:54Z
39,213,552
<p>You can use this below patterns to do it more professionally</p> <pre><code>v = ['files', 'file.pdf', 'D1234', 43] keys = ['folder', 'name', 'doc_id', 'page_num'] junk = map(lambda k, v: dict.update({k: v}), keys, values) </code></pre>
0
2016-08-29T19:15:52Z
[ "python", "list" ]
InvalidSchema("No connection adapters were found for '%s'" % url)
39,212,867
<p>I was able to gather data from a web page using this </p> <pre><code>import requests import lxml.html import re url = "http://animesora.com/flying-witch-episode-7-english-subtitle/" r = requests.get(url) page = r.content dom = lxml.html.fromstring(page) for link in dom.xpath('//div[@class="downloadarea"]//a/@href'): down = re.findall('https://.*',link) print (down) </code></pre> <p>when I try this to gather more data on the results of the above code I was presented with this error:</p> <pre><code>Traceback (most recent call last): File "/home/sven/PycharmProjects/untitled1/.idea/test4.py", line 21, in &lt;module&gt; r2 = requests.get(down) File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 70, in get return request('get', url, params=params, **kwargs) File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 56, in request return session.request(method=method, url=url, **kwargs) File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 475, in request resp = self.send(prep, **send_kwargs) File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 590, in send adapter = self.get_adapter(url=request.url) File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 672, in get_adapter raise InvalidSchema("No connection adapters were found for '%s'" % url) requests.exceptions.InvalidSchema: No connection adapters were found for '['https://link.safelinkconverter.com/review.php?id=aHR0cDovLygqKC5fKC9zTGZYZ0s=&amp;c=1&amp;user=51757']' </code></pre> <p>This is the code I was using:</p> <pre><code>for link2 in down: r2 = requests.get(down) page2 = r.url dom2 = lxml.html.fromstring(page2) for link2 in dom2('//div[@class="button green"]//onclick'): down2 = re.findall('.*',down2) print (down2) </code></pre>
-1
2016-08-29T18:32:32Z
39,212,974
<p>You are passing in the <em>whole list</em>:</p> <pre><code>for link2 in down: r2 = requests.get(down) </code></pre> <p>Note how you passed in <code>down</code>, <em>not</em> <code>link2</code>. <code>down</code> is a list, not a single URL string.</p> <p>Pass in <code>link2</code>:</p> <pre><code>for link2 in down: r2 = requests.get(link2) </code></pre> <p>I'm not sure why you are using regular expressions. In the loop</p> <pre><code>for link in dom.xpath('//div[@class="downloadarea"]//a/@href'): </code></pre> <p>each <code>link</code> is <em>already</em> a fully qualified URL:</p> <pre><code>&gt;&gt;&gt; for link in dom.xpath('//div[@class="downloadarea"]//a/@href'): ... print link ... https://link.safelinkconverter.com/review.php?id=aHR0cDovLygqKC5fKC9FZEk2Qg==&amp;c=1&amp;user=51757 https://link.safelinkconverter.com/review.php?id=aHR0cDovLygqKC5fKC95Tmg2Qg==&amp;c=1&amp;user=51757 https://link.safelinkconverter.com/review.php?id=aHR0cDovLygqKC5fKC93dFBmVFg=&amp;c=1&amp;user=51757 https://link.safelinkconverter.com/review.php?id=aHR0cDovLygqKC5fKC9zTGZYZ0s=&amp;c=1&amp;user=51757 </code></pre> <p>You don't need to do any further processing on that.</p> <p>Your remaining code has more errors; you confused <code>r2.url</code> with <code>r2.content</code>, and forgot the <code>.xpath</code> part in your <code>dom2.xpath(...)</code> query.</p>
0
2016-08-29T18:38:43Z
[ "python", "python-requests" ]
Change IP Address Python Selenium
39,212,888
<p>I Try run code with Python Selenium</p> <pre><code>from selenium import webdriver import time profile = webdriver.FirefoxProfile() profile.set_preference("network.proxy_type",1) profile.set_preference("network.proxy.http","124.240.187.80") profile.set_preference("network.proxy.http_port",82) profile.update_preferences() driver=webdriver.Firefox(firefox_profile=profile) driver.get('https://www.whatismyip.com/') driver.sleep(3) driver.close() </code></pre> <p>But my IP address does not change when you run this file.</p> <p>How can I change my ip address. I am developing a web crawler and need to change the ip</p>
0
2016-08-29T18:34:03Z
39,213,025
<p>Use desired capabilities for FF.</p> <pre><code>proxy = "124.240.187.80:82" webdriver.DesiredCapabilities.FIREFOX['proxy'] = { "httpProxy":proxy, "ftpProxy":proxy, "sslProxy":proxy, "noProxy":None, "proxyType":"MANUAL", "class":"org.openqa.selenium.Proxy", "autodetect":False } </code></pre> <p><a href="http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp#using-a-proxy" rel="nofollow">WebDriver: Advanced Usage - proxy</a></p>
0
2016-08-29T18:41:23Z
[ "python", "selenium", "proxy", "web-crawler" ]
UNAME_SYSNAME on Python3
39,212,894
<p>I'm having problems installing an extention on python3.5 on Windows.</p> <p>Traced it to a <code>IF UNAME_SYSNAME == u"Windows":</code> not being triggered. According to <a href="http://stackoverflow.com/questions/35887318/cannot-install-pylearn2-to-winpython-64bit-3-4-4-1/35970202#35970202">Cannot install pylearn2 to WinPython-64bit-3.4.4.1</a> adding the <code>u</code> should solve this but doesn't.</p> <p>What is the expected output of <code>UNAME_SYSNAME</code> on Windows10 / Python 3.5?</p> <p>sys.version = '3.5.2 |Anaconda 4.0.0 (64-bit)| (default, Jul 5 2016, 11:41:13) [MSC v.1900 64 bit (AMD64)]'</p>
1
2016-08-29T18:34:48Z
39,232,480
<p>Looks like Cython doesn't really support python3.</p> <p>If it adds support feel free to replace this answer</p>
0
2016-08-30T16:16:28Z
[ "python", "windows", "python-3.x", "cython" ]
why does this code not work in real environment? saying 'normal' is undefined (new coder)
39,212,903
<p>my question: I can get this to work in codeskulptor but not any of my IDE. Please help!</p> <pre><code>Uinput = input("first morph") Uinput2 = input("second morph") #this section of code accepts normal or recessive to #calculate if you will get hets. If hets, clarify morph in separate function #input to compare are words def normal_recessive(): if Uinput == ("normal") and Uinput2 == ("normal"): print("your results will be all wildtypes") elif Uinput == ("normal") and Uinput2 == ("recessive"): print("Your results will be heterozygous aka hets") elif Uinput == ("recessive") and Uinput2 == ("normal"): print("Your results will be heterozygous aka hets") elif Uinput == ("recessive") and Uinput2 == ("recessive"): print("Your results will be all recessive") else: print("input error, please input recessive or normal for morph type") print("please check your spelling and try again") normal_recessive() </code></pre>
0
2016-08-29T18:35:12Z
39,212,966
<p>It sounds like CodeSkulptor is running Python 3 and your IDEs are running Python 2. The <code>input</code> function behaves differently between the two Pythons.</p> <p>If you configure your IDEs to use Python 3, your code should work.</p> <p>Alternatively, the Python 2 <code>raw_input</code> function does what the Python 3 <code>input</code> function does, so if you need to use Python 2 instead of Python 3, then replace <code>input</code> in your code with <code>raw_input</code>.</p>
0
2016-08-29T18:38:02Z
[ "python", "python-2.x" ]
Trying to split out a character from a bash "list"
39,212,923
<p>So I have this command that runs the following report in your shell; </p> <pre><code>Command output Available Reports for: isl-01-chi Time Zone: CDT ================================================================================ |ID |FSA Job Start |FSA Job End |Size | ================================================================================ |313 |Aug 21 2016, 10:00 PM |Aug 22 2016, 12:33 AM |1.040G | -------------------------------------------------------------------------------- |318 |Aug 22 2016, 10:00 PM |Aug 23 2016, 12:35 AM |1.039G | -------------------------------------------------------------------------------- |323 |Aug 23 2016, 10:00 PM |Aug 24 2016, 12:34 AM |1.045G | -------------------------------------------------------------------------------- |328 |Aug 24 2016, 10:00 PM |Aug 25 2016, 12:35 AM |1.043G | -------------------------------------------------------------------------------- |333 |Aug 25 2016, 10:00 PM |Aug 26 2016, 12:57 AM |1.057G | -------------------------------------------------------------------------------- |339 |Aug 26 2016, 10:00 PM |Aug 27 2016, 03:01 AM |2.183G | -------------------------------------------------------------------------------- |346 |Aug 28 2016, 07:24 AM |Aug 28 2016, 11:53 AM |2.183G | -------------------------------------------------------------------------------- |351 |Aug 28 2016, 10:00 PM |Aug 29 2016, 02:37 AM |2.182G | ================================================================================ </code></pre> <p>What I'm looking to do is find the latest ID (Greatest number) and was wondering what the easiest method of doing this was in python ?</p>
0
2016-08-29T18:36:00Z
39,212,984
<p>If the output is always sorted, then read each line into a list, get the second to last entry in the list, and discard the rest.</p>
0
2016-08-29T18:39:07Z
[ "python" ]
Trying to split out a character from a bash "list"
39,212,923
<p>So I have this command that runs the following report in your shell; </p> <pre><code>Command output Available Reports for: isl-01-chi Time Zone: CDT ================================================================================ |ID |FSA Job Start |FSA Job End |Size | ================================================================================ |313 |Aug 21 2016, 10:00 PM |Aug 22 2016, 12:33 AM |1.040G | -------------------------------------------------------------------------------- |318 |Aug 22 2016, 10:00 PM |Aug 23 2016, 12:35 AM |1.039G | -------------------------------------------------------------------------------- |323 |Aug 23 2016, 10:00 PM |Aug 24 2016, 12:34 AM |1.045G | -------------------------------------------------------------------------------- |328 |Aug 24 2016, 10:00 PM |Aug 25 2016, 12:35 AM |1.043G | -------------------------------------------------------------------------------- |333 |Aug 25 2016, 10:00 PM |Aug 26 2016, 12:57 AM |1.057G | -------------------------------------------------------------------------------- |339 |Aug 26 2016, 10:00 PM |Aug 27 2016, 03:01 AM |2.183G | -------------------------------------------------------------------------------- |346 |Aug 28 2016, 07:24 AM |Aug 28 2016, 11:53 AM |2.183G | -------------------------------------------------------------------------------- |351 |Aug 28 2016, 10:00 PM |Aug 29 2016, 02:37 AM |2.182G | ================================================================================ </code></pre> <p>What I'm looking to do is find the latest ID (Greatest number) and was wondering what the easiest method of doing this was in python ?</p>
0
2016-08-29T18:36:00Z
39,212,996
<p>how about</p> <p><code>largest_id = max(int(line.split()[0][1:]) for line in output.split("\n")[5::2])</code></p> <p>if the output is always sorted, then</p> <p><code>largest_id = int(output.split('\n')[-2].split()[0][1:])</code></p> <p>more educatively :</p> <pre><code>lines = output.split('\n') second_to_last_line = lines[-2] splitted_by_whitespace = second_to_last_line.split() first_non_whitespace_blob = splitted_by_whitespace[0] id_string_ignoring_the_column_char = first_non_whitespace_blob[1:] id = int(id_string_ignoring_the_column_char) </code></pre>
2
2016-08-29T18:39:50Z
[ "python" ]
Trying to split out a character from a bash "list"
39,212,923
<p>So I have this command that runs the following report in your shell; </p> <pre><code>Command output Available Reports for: isl-01-chi Time Zone: CDT ================================================================================ |ID |FSA Job Start |FSA Job End |Size | ================================================================================ |313 |Aug 21 2016, 10:00 PM |Aug 22 2016, 12:33 AM |1.040G | -------------------------------------------------------------------------------- |318 |Aug 22 2016, 10:00 PM |Aug 23 2016, 12:35 AM |1.039G | -------------------------------------------------------------------------------- |323 |Aug 23 2016, 10:00 PM |Aug 24 2016, 12:34 AM |1.045G | -------------------------------------------------------------------------------- |328 |Aug 24 2016, 10:00 PM |Aug 25 2016, 12:35 AM |1.043G | -------------------------------------------------------------------------------- |333 |Aug 25 2016, 10:00 PM |Aug 26 2016, 12:57 AM |1.057G | -------------------------------------------------------------------------------- |339 |Aug 26 2016, 10:00 PM |Aug 27 2016, 03:01 AM |2.183G | -------------------------------------------------------------------------------- |346 |Aug 28 2016, 07:24 AM |Aug 28 2016, 11:53 AM |2.183G | -------------------------------------------------------------------------------- |351 |Aug 28 2016, 10:00 PM |Aug 29 2016, 02:37 AM |2.182G | ================================================================================ </code></pre> <p>What I'm looking to do is find the latest ID (Greatest number) and was wondering what the easiest method of doing this was in python ?</p>
0
2016-08-29T18:36:00Z
39,213,303
<p>I think that is better thake the value with shell. </p> <pre><code>your_command | grep -Eo '^\|[0-9]+'| cut -d "|" -f2 | sort | tail -n1 </code></pre>
0
2016-08-29T18:59:11Z
[ "python" ]
Trying to split out a character from a bash "list"
39,212,923
<p>So I have this command that runs the following report in your shell; </p> <pre><code>Command output Available Reports for: isl-01-chi Time Zone: CDT ================================================================================ |ID |FSA Job Start |FSA Job End |Size | ================================================================================ |313 |Aug 21 2016, 10:00 PM |Aug 22 2016, 12:33 AM |1.040G | -------------------------------------------------------------------------------- |318 |Aug 22 2016, 10:00 PM |Aug 23 2016, 12:35 AM |1.039G | -------------------------------------------------------------------------------- |323 |Aug 23 2016, 10:00 PM |Aug 24 2016, 12:34 AM |1.045G | -------------------------------------------------------------------------------- |328 |Aug 24 2016, 10:00 PM |Aug 25 2016, 12:35 AM |1.043G | -------------------------------------------------------------------------------- |333 |Aug 25 2016, 10:00 PM |Aug 26 2016, 12:57 AM |1.057G | -------------------------------------------------------------------------------- |339 |Aug 26 2016, 10:00 PM |Aug 27 2016, 03:01 AM |2.183G | -------------------------------------------------------------------------------- |346 |Aug 28 2016, 07:24 AM |Aug 28 2016, 11:53 AM |2.183G | -------------------------------------------------------------------------------- |351 |Aug 28 2016, 10:00 PM |Aug 29 2016, 02:37 AM |2.182G | ================================================================================ </code></pre> <p>What I'm looking to do is find the latest ID (Greatest number) and was wondering what the easiest method of doing this was in python ?</p>
0
2016-08-29T18:36:00Z
39,213,453
<hr> <h2> </h2> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>data="..." #// Load Your Shell output l=[] Output="" MaxID=0 for a in data.split("\n"): id=a.split()[0][1:] l.append(id) if max(l)==id: Output=a MaxID=id print MaxID,Output</code></pre> </div> </div> </p> <p>##</p>
-1
2016-08-29T19:08:12Z
[ "python" ]
Trying to split out a character from a bash "list"
39,212,923
<p>So I have this command that runs the following report in your shell; </p> <pre><code>Command output Available Reports for: isl-01-chi Time Zone: CDT ================================================================================ |ID |FSA Job Start |FSA Job End |Size | ================================================================================ |313 |Aug 21 2016, 10:00 PM |Aug 22 2016, 12:33 AM |1.040G | -------------------------------------------------------------------------------- |318 |Aug 22 2016, 10:00 PM |Aug 23 2016, 12:35 AM |1.039G | -------------------------------------------------------------------------------- |323 |Aug 23 2016, 10:00 PM |Aug 24 2016, 12:34 AM |1.045G | -------------------------------------------------------------------------------- |328 |Aug 24 2016, 10:00 PM |Aug 25 2016, 12:35 AM |1.043G | -------------------------------------------------------------------------------- |333 |Aug 25 2016, 10:00 PM |Aug 26 2016, 12:57 AM |1.057G | -------------------------------------------------------------------------------- |339 |Aug 26 2016, 10:00 PM |Aug 27 2016, 03:01 AM |2.183G | -------------------------------------------------------------------------------- |346 |Aug 28 2016, 07:24 AM |Aug 28 2016, 11:53 AM |2.183G | -------------------------------------------------------------------------------- |351 |Aug 28 2016, 10:00 PM |Aug 29 2016, 02:37 AM |2.182G | ================================================================================ </code></pre> <p>What I'm looking to do is find the latest ID (Greatest number) and was wondering what the easiest method of doing this was in python ?</p>
0
2016-08-29T18:36:00Z
39,213,493
<p>Also you can do it using sort command in shell.</p> <pre><code>your_command | awk '{print $1}' | sort | tail -n1 </code></pre>
-1
2016-08-29T19:11:13Z
[ "python" ]
Trying to split out a character from a bash "list"
39,212,923
<p>So I have this command that runs the following report in your shell; </p> <pre><code>Command output Available Reports for: isl-01-chi Time Zone: CDT ================================================================================ |ID |FSA Job Start |FSA Job End |Size | ================================================================================ |313 |Aug 21 2016, 10:00 PM |Aug 22 2016, 12:33 AM |1.040G | -------------------------------------------------------------------------------- |318 |Aug 22 2016, 10:00 PM |Aug 23 2016, 12:35 AM |1.039G | -------------------------------------------------------------------------------- |323 |Aug 23 2016, 10:00 PM |Aug 24 2016, 12:34 AM |1.045G | -------------------------------------------------------------------------------- |328 |Aug 24 2016, 10:00 PM |Aug 25 2016, 12:35 AM |1.043G | -------------------------------------------------------------------------------- |333 |Aug 25 2016, 10:00 PM |Aug 26 2016, 12:57 AM |1.057G | -------------------------------------------------------------------------------- |339 |Aug 26 2016, 10:00 PM |Aug 27 2016, 03:01 AM |2.183G | -------------------------------------------------------------------------------- |346 |Aug 28 2016, 07:24 AM |Aug 28 2016, 11:53 AM |2.183G | -------------------------------------------------------------------------------- |351 |Aug 28 2016, 10:00 PM |Aug 29 2016, 02:37 AM |2.182G | ================================================================================ </code></pre> <p>What I'm looking to do is find the latest ID (Greatest number) and was wondering what the easiest method of doing this was in python ?</p>
0
2016-08-29T18:36:00Z
39,213,739
<p>I'd use a regex because it looks like the ID is a 3 digit (or more) number preceded by the pipe (|) character.</p> <p>This should do it:</p> <pre><code>regex = re.compile(r'(?&lt;=\|)\d{,3}') m = regex.findall(text) max(m) </code></pre>
0
2016-08-29T19:27:55Z
[ "python" ]
django binary file download corrupted in browsers
39,212,965
<p>I have a view that after authentication/permissions serves a file as saved in a FileField.</p> <pre><code>from django.http import StreamingHttpResponse from rest_framework import viewsets from rest_framework.decorators import detail_route from wsgiref.util import FileWrapper import mimetypes from myapp.models import MyModel class ExampleViewSet(viewsets.ViewSet): # Normal crud (retrive, list, etc.) @detail_route(methods=['GET']) def download(self, *args, **kwargs): pk = self.request.parser_context['kwargs'].get('pk', None) if pk is None: raise exceptions.ParseError('no pk') instance = MyModel.objects.get(pk=pk) filename = instance.file_field.name.split('/')[-1] mime = mimetypes.guess_type(filename)[0] file = instance.file_field.file response = StreamingHttpResponse( FileWrapper(open(file, 'rb'), 10240)) response['Content-Type'] = "{0}; charset=utf-8".format(mime) response['Content-Length'] = file.size response[ 'Content-Disposition'] = 'attachment; filename={0}'.format(filename) return response </code></pre> <p>The file itself is a 3.7MB file jpeg that was previously uploaded by the user. Under the upload directory the file is 3.7MB and opens correctly. when downloaded via the browser (Firefox or Chrome) the file is 7.0MB and corrupted (does not have the correct header for jpegs which should start with two specific bytes) when downloaded from curl or wget the file is 3.7MB and opens correctly</p> <p>The following is curl's output of the response fields using curl -v</p> <pre><code>curl -v http://localhost:3000/api/school_admin/posters/7/download?token=ZXlKaGJHY2lPaUpJVXpVeE1pSXNJblI1Y0NJNklrcFhWQ0o5LmV5SndhR0Z6YUNJNkltSmpjbmx3ZEY5emFHRXlOVFlrSkRKaUpERXlKR2hzVlUxd2QyOWpTM1pMTnk1VlRuSXZPR1ZNVWs5aFJEVjBVbmR2V21FeVVGVlZiWGhxTTJWb1UzZFhla1JNU3k5RmFqZFRJaXdpY0hKdlptbHNaVjl3YXlJNk15d2laWGh3SWpveE5EY3lOalUyTWpFMGZRLmV6OGg5SWVwLUozYjdQcHJLVGJCZWlSSjJPN1JRdnItaFVuLVg0dmdLZGdtRGdQV0s2ZzkzdktialN2Uy1EVTVkM1hRc2hRZ3YxeVZmQlJhUDBBVlhB -o test.jpeg % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 3000 (#0) &gt; GET /api/school_admin/posters/7/download?token=ZXlKaGJHY2lPaUpJVXpVeE1pSXNJblI1Y0NJNklrcFhWQ0o5LmV5SndhR0Z6YUNJNkltSmpjbmx3ZEY5emFHRXlOVFlrSkRKaUpERXlKR2hzVlUxd2QyOWpTM1pMTnk1VlRuSXZPR1ZNVWs5aFJEVjBVbmR2V21FeVVGVlZiWGhxTTJWb1UzZFhla1JNU3k5RmFqZFRJaXdpY0hKdlptbHNaVjl3YXlJNk15d2laWGh3SWpveE5EY3lOalUyTWpFMGZRLmV6OGg5SWVwLUozYjdQcHJLVGJCZWlSSjJPN1JRdnItaFVuLVg0dmdLZGdtRGdQV0s2ZzkzdktialN2Uy1EVTVkM1hRc2hRZ3YxeVZmQlJhUDBBVlhB HTTP/1.1 &gt; Host: localhost:3000 &gt; User-Agent: curl/7.43.0 &gt; Accept: */* &gt; &lt; HTTP/1.1 200 OK &lt; date: Mon, 29 Aug 2016 18:31:30 GMT &lt; server: WSGIServer/0.2 CPython/3.4.3 &lt; allow: GET, DELETE, HEAD, OPTIONS &lt; content-type: image/jpeg; charset=utf-8 &lt; vary: Accept &lt; content-length: 3947925 &lt; content-disposition: attachment; filename=poster_28F7bdD4caAbCc583831c9E7C9baDaEC88Ecbde6FBAA6aE71cAdC09fd8EFCF7BD515155bec1C3FC6f01c6FEf5Ba76e41952E_Colosseum_in_Rome_Italy_-_April_2007.jpg &lt; x-frame-options: SAMEORIGIN &lt; via: 1.1 fedora &lt; Connection: keep-alive &lt; { [15913 bytes data] 100 3855k 100 3855k 0 0 141M 0 --:--:-- --:--:-- --:--:-- 144M * Connection #0 to host localhost left intact </code></pre>
3
2016-08-29T18:38:01Z
39,213,147
<p>This is typically caused while uploading files/data through FTP as ASCII file transfer type. The "ASCII transfer type" will transfer the files as regular text files and so no problem. but, the "Binary transfer type" will transfer the data in binary mode which handles the files as binary data instead of text data. Setting your FTP client to Binary will prevent your files from becoming corrupted through ftp transit. Please see the following on how to switch your FTP program to Binary.</p> <p>Here you should be trying the Binary data as in terms of ASCII.</p>
0
2016-08-29T18:49:11Z
[ "python", "django", "django-rest-framework" ]
django binary file download corrupted in browsers
39,212,965
<p>I have a view that after authentication/permissions serves a file as saved in a FileField.</p> <pre><code>from django.http import StreamingHttpResponse from rest_framework import viewsets from rest_framework.decorators import detail_route from wsgiref.util import FileWrapper import mimetypes from myapp.models import MyModel class ExampleViewSet(viewsets.ViewSet): # Normal crud (retrive, list, etc.) @detail_route(methods=['GET']) def download(self, *args, **kwargs): pk = self.request.parser_context['kwargs'].get('pk', None) if pk is None: raise exceptions.ParseError('no pk') instance = MyModel.objects.get(pk=pk) filename = instance.file_field.name.split('/')[-1] mime = mimetypes.guess_type(filename)[0] file = instance.file_field.file response = StreamingHttpResponse( FileWrapper(open(file, 'rb'), 10240)) response['Content-Type'] = "{0}; charset=utf-8".format(mime) response['Content-Length'] = file.size response[ 'Content-Disposition'] = 'attachment; filename={0}'.format(filename) return response </code></pre> <p>The file itself is a 3.7MB file jpeg that was previously uploaded by the user. Under the upload directory the file is 3.7MB and opens correctly. when downloaded via the browser (Firefox or Chrome) the file is 7.0MB and corrupted (does not have the correct header for jpegs which should start with two specific bytes) when downloaded from curl or wget the file is 3.7MB and opens correctly</p> <p>The following is curl's output of the response fields using curl -v</p> <pre><code>curl -v http://localhost:3000/api/school_admin/posters/7/download?token=ZXlKaGJHY2lPaUpJVXpVeE1pSXNJblI1Y0NJNklrcFhWQ0o5LmV5SndhR0Z6YUNJNkltSmpjbmx3ZEY5emFHRXlOVFlrSkRKaUpERXlKR2hzVlUxd2QyOWpTM1pMTnk1VlRuSXZPR1ZNVWs5aFJEVjBVbmR2V21FeVVGVlZiWGhxTTJWb1UzZFhla1JNU3k5RmFqZFRJaXdpY0hKdlptbHNaVjl3YXlJNk15d2laWGh3SWpveE5EY3lOalUyTWpFMGZRLmV6OGg5SWVwLUozYjdQcHJLVGJCZWlSSjJPN1JRdnItaFVuLVg0dmdLZGdtRGdQV0s2ZzkzdktialN2Uy1EVTVkM1hRc2hRZ3YxeVZmQlJhUDBBVlhB -o test.jpeg % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 3000 (#0) &gt; GET /api/school_admin/posters/7/download?token=ZXlKaGJHY2lPaUpJVXpVeE1pSXNJblI1Y0NJNklrcFhWQ0o5LmV5SndhR0Z6YUNJNkltSmpjbmx3ZEY5emFHRXlOVFlrSkRKaUpERXlKR2hzVlUxd2QyOWpTM1pMTnk1VlRuSXZPR1ZNVWs5aFJEVjBVbmR2V21FeVVGVlZiWGhxTTJWb1UzZFhla1JNU3k5RmFqZFRJaXdpY0hKdlptbHNaVjl3YXlJNk15d2laWGh3SWpveE5EY3lOalUyTWpFMGZRLmV6OGg5SWVwLUozYjdQcHJLVGJCZWlSSjJPN1JRdnItaFVuLVg0dmdLZGdtRGdQV0s2ZzkzdktialN2Uy1EVTVkM1hRc2hRZ3YxeVZmQlJhUDBBVlhB HTTP/1.1 &gt; Host: localhost:3000 &gt; User-Agent: curl/7.43.0 &gt; Accept: */* &gt; &lt; HTTP/1.1 200 OK &lt; date: Mon, 29 Aug 2016 18:31:30 GMT &lt; server: WSGIServer/0.2 CPython/3.4.3 &lt; allow: GET, DELETE, HEAD, OPTIONS &lt; content-type: image/jpeg; charset=utf-8 &lt; vary: Accept &lt; content-length: 3947925 &lt; content-disposition: attachment; filename=poster_28F7bdD4caAbCc583831c9E7C9baDaEC88Ecbde6FBAA6aE71cAdC09fd8EFCF7BD515155bec1C3FC6f01c6FEf5Ba76e41952E_Colosseum_in_Rome_Italy_-_April_2007.jpg &lt; x-frame-options: SAMEORIGIN &lt; via: 1.1 fedora &lt; Connection: keep-alive &lt; { [15913 bytes data] 100 3855k 100 3855k 0 0 141M 0 --:--:-- --:--:-- --:--:-- 144M * Connection #0 to host localhost left intact </code></pre>
3
2016-08-29T18:38:01Z
39,332,657
<p>The problem was solved when I used nginx + uwsgi. I think it has to do with some of the 'Hop-by-hop' headers that django's runserver refuses to add and errors out if I add them manually. Which are generally related to reverse proxies. </p>
1
2016-09-05T14:22:45Z
[ "python", "django", "django-rest-framework" ]
Scrapy export csv without specifying in cmd
39,213,095
<p>I understand how to export my scraped data in to a csv format via</p> <pre><code>scrapy crawl &lt;spider_name&gt; -o filename.csv </code></pre> <p>However I'd like to run my spider from a script and automatically write to csv (so I can use schedule to run the spider at particular times). How could I implement this into my code and where would it go? I.E would it go into pipeline or my actual spider assuming this can be done.</p>
0
2016-08-29T18:45:42Z
39,213,373
<p>Scrapy uses pipelines to post process the data you have scraped. You can create a file called <code>pipelines.py</code> which contains the following code which exports your data into a folder <code>exports</code>. Here's some code that I use in one of my pip projects</p> <pre><code>from scrapy import signals from scrapy.contrib.exporter import CsvItemExporter, JsonItemExporter class ExportData(object): def __init__(self): self.files = {} self.exporter = None @classmethod def from_crawler(cls, crawler): pipeline = cls() crawler.signals.connect(pipeline.spider_opened, signals.spider_opened) crawler.signals.connect(pipeline.spider_closed, signals.spider_closed) return pipeline def spider_opened(self, spider): raise NotImplementedError def spider_closed(self, spider): self.exporter.finish_exporting() file_to_save = self.files.pop(spider) file_to_save.close() def process_item(self, item, spider): self.exporter.export_item(item) return item class ExportJSON(ExportData): """ Exporting to export/json/spider-name.json file """ def spider_opened(self, spider): file_to_save = open('exports/%s.json' % spider.name, 'w+b') self.files[spider] = file_to_save self.exporter = JsonItemExporter(file_to_save) self.exporter.start_exporting() class ExportCSV(ExportData): """ Exporting to export/csv/spider-name.csv file """ def spider_opened(self, spider): file_to_save = open('exports/%s.csv' % spider.name, 'w+b') self.files[spider] = file_to_save self.exporter = CsvItemExporter(file_to_save) self.exporter.start_exporting() </code></pre> <p>You can view the project code on <a href="https://github.com/kirankoduru/arachne/blob/master/arachne/pipelines.py" rel="nofollow">github</a>. You just need to add these class names in your scrapy settings correctly.</p>
1
2016-08-29T19:03:15Z
[ "python", "python-2.7", "scrapy", "scrapy-spider" ]
Python 3 - Post comment on forum
39,213,526
<p>I have some python background experience. However I don't know how to post comment to forum.</p> <p>How can I get started? I read about urllib, but I still don't know how to post.</p> <p>Can you help me?</p> <p>What information do I need to extract?</p>
-1
2016-08-29T19:14:14Z
39,213,783
<p>Here are some tools that might help you:</p> <ul> <li>Browser developer tools is probably where you should begin. Try to record a POST request in the "network" pane and see what parameters your browser sends to the server.</li> <li>If you need to parse HTML to extract data, use <a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a></li> <li>I would recommend you use <a href="http://docs.python-requests.org/en/master/" rel="nofollow">Python Requests</a> instead of urllib directly for your HTTP requests. It's much easier to work with than urllib.</li> </ul> <p>As for what data you need to extract... That's site specific, so a little bit of trial and error will probably be required.</p>
0
2016-08-29T19:31:08Z
[ "python", "post", "comments" ]
Python Regular Expression; replacing a portion of match
39,213,585
<p>How would I limit match/replacement the leading zeros in e004_n07? However, if either term contains all zeros, then I need to retain one zero in the term (see example below). For the input string, there will always be 3 digits in the first value and 2 digits in the second value.</p> <p>Example input and output</p> <pre><code>e004_n07 #e4_n7 e020_n50 #e20_n50 e000_n00 #e0_n0 </code></pre> <p>Can this be accomplished with re.sub alone, or do I need to use re.search/re.match?</p>
1
2016-08-29T19:18:16Z
39,213,641
<p>There's no need to use <code>re.sub</code> if your replacement is so simple - simply use <a class='doc-link' href="http://stackoverflow.com/documentation/python/278/string-methods/1008/replace-all-occurrences-of-one-substring-with-another-substring#t=201608291922416212581"><code>str.replace</code></a>:</p> <pre><code>s = 'e004_n07' s.replace('0', '') # =&gt; 'e4_n7' </code></pre>
1
2016-08-29T19:21:51Z
[ "python", "regex" ]
Python Regular Expression; replacing a portion of match
39,213,585
<p>How would I limit match/replacement the leading zeros in e004_n07? However, if either term contains all zeros, then I need to retain one zero in the term (see example below). For the input string, there will always be 3 digits in the first value and 2 digits in the second value.</p> <p>Example input and output</p> <pre><code>e004_n07 #e4_n7 e020_n50 #e20_n50 e000_n00 #e0_n0 </code></pre> <p>Can this be accomplished with re.sub alone, or do I need to use re.search/re.match?</p>
1
2016-08-29T19:18:16Z
39,213,817
<p>If you want to only remove zeros after letters, you may use:</p> <pre><code>([a-zA-Z])0+ </code></pre> <p>Replace with <code>\1</code> backreference. See the <a href="https://regex101.com/r/oI2vF0/1" rel="nofollow">regex demo</a>.</p> <p>The <code>([a-zA-Z])</code> will capture a letter and <code>0+</code> will match 1 or more zeros. </p> <p><a href="http://ideone.com/n1BaaV" rel="nofollow">Python demo</a>:</p> <pre><code>import re s = 'e004_n07' res = re.sub(r'([a-zA-Z])0+', r'\1', s) print(res) </code></pre> <p>Note that <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow"><strong><code>re.sub</code></strong></a> will find and replace all non-overlapping matches (will perform a global search and replace). If there is no match, the string will be returned as is, without modifications. So, there is no need using additional <code>re.match</code>/<code>re.search</code>.</p> <p><strong>UDPATE</strong></p> <p>To keep 1 zero if the numbers only contain zeros, you may use</p> <pre><code>import re s = ['e004_n07','e000_n00'] res = [re.sub(r'(?&lt;=[a-zA-Z])0+(\d*)', lambda m: m.group(1) if m.group(1) else '0', x) for x in s] print(res) </code></pre> <p>See the <a href="http://ideone.com/QeFcsL" rel="nofollow">Python demo</a></p> <p>Here, <code>r'(?&lt;=[a-zA-Z])0+(\d*)'</code> regex matches one or more zeros (<code>0+</code>) that are after an ASCII letter (<code>(?&lt;=[a-zA-Z])</code>) and then any other digits (0 or more) are captured into Group 1 with <code>(\d*)</code>. Then, in the replacement, we check if Group 1 is empty, and if it is empty, we insert <code>0</code> (there are only zeros), else, we insert Group 1 contents (the remaining digits after the first leading zeros).</p>
4
2016-08-29T19:33:09Z
[ "python", "regex" ]
Python Regular Expression; replacing a portion of match
39,213,585
<p>How would I limit match/replacement the leading zeros in e004_n07? However, if either term contains all zeros, then I need to retain one zero in the term (see example below). For the input string, there will always be 3 digits in the first value and 2 digits in the second value.</p> <p>Example input and output</p> <pre><code>e004_n07 #e4_n7 e020_n50 #e20_n50 e000_n00 #e0_n0 </code></pre> <p>Can this be accomplished with re.sub alone, or do I need to use re.search/re.match?</p>
1
2016-08-29T19:18:16Z
39,213,823
<p>If your requirement is that you MUST use <code>regex</code>, then below is your regex pattern:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = 'e004_n07' &gt;&gt;&gt; line = re.sub(r"0", "", s) &gt;&gt;&gt; line 'e4_n7' </code></pre> <p>However it is recommended not to use regex when there is other efficient way to perform the same opertaion, i.e. using <code>replace</code> function</p> <pre><code>&gt;&gt;&gt; line = s.replace('0', '') &gt;&gt;&gt; line 'e4_n7' </code></pre>
0
2016-08-29T19:33:24Z
[ "python", "regex" ]
Python Regular Expression; replacing a portion of match
39,213,585
<p>How would I limit match/replacement the leading zeros in e004_n07? However, if either term contains all zeros, then I need to retain one zero in the term (see example below). For the input string, there will always be 3 digits in the first value and 2 digits in the second value.</p> <p>Example input and output</p> <pre><code>e004_n07 #e4_n7 e020_n50 #e20_n50 e000_n00 #e0_n0 </code></pre> <p>Can this be accomplished with re.sub alone, or do I need to use re.search/re.match?</p>
1
2016-08-29T19:18:16Z
39,213,914
<p><em><strong>edit:</strong> Don't let anybody talk you out of validating the format of the fixed data. If that's what you need, don't settle for something overly simple .</em> </p> <p>Not very pretty, but in a situation that seems fixed, you can just<br> set all the permutations, then blindly capture the good parts,<br> leave out the zero's then substitute it all back. </p> <p>Find <code>([a-z])(?:([1-9][0-9][0-9])|0([1-9][0-9])|00([1-9]))(_[a-z])(?:([1-9][0-9])|0([1-9]))</code></p> <p>Replace <code>$1$2$3$4$5$6$7</code> </p> <p>Expanded </p> <pre><code> ( [a-z] ) # (1) (?: ( [1-9] [0-9] [0-9] ) # (2) | 0 ( [1-9] [0-9] ) # (3) | 00 ( [1-9] ) # (4) ) ( _ [a-z] ) # (5) (?: ( [1-9] [0-9] ) # (6) | 0 ( [1-9] ) # (7) ) </code></pre> <p>Output </p> <pre><code> ** Grp 0 - ( pos 0 , len 8 ) e004_n07 ** Grp 1 - ( pos 0 , len 1 ) e ** Grp 2 - NULL ** Grp 3 - NULL ** Grp 4 - ( pos 3 , len 1 ) 4 ** Grp 5 - ( pos 4 , len 2 ) _n ** Grp 6 - NULL ** Grp 7 - ( pos 7 , len 1 ) 7 </code></pre>
-1
2016-08-29T19:39:52Z
[ "python", "regex" ]
Convert text data from requests object to dataframe with pandas
39,213,597
<p>Using requests I am creating an object which is in .csv format. How can I then write that object to a DataFrame with pandas?</p> <p>To get the requests object in text format:</p> <pre><code>import requests import pandas as pd url = r'http://test.url' r = requests.get(url) r.text #this will return the data as text in csv format </code></pre> <p>I tried (doesn't work):</p> <pre><code>pd.read_csv(r.text) pd.DataFrame.from_csv(r.text) </code></pre>
1
2016-08-29T19:19:04Z
39,213,616
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a> with <code>url</code>:</p> <pre><code>pd.read_csv(url) </code></pre> <blockquote> <p><strong>filepath_or_buffer</strong> : str, pathlib.Path, py._path.local.LocalPath or any object with a read() method (such as a file handle or StringIO)</p> <p>The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. For instance, a local file could be file ://localhost/path/to/table.csv</p> </blockquote> <p>If it doesnt work, try:</p> <pre><code>import pandas as pd import io import requests url = r'http://...' r = requests.get(url) df = pd.read_csv(io.StringIO(r) </code></pre>
1
2016-08-29T19:20:11Z
[ "python", "csv", "pandas", "dataframe", "python-requests" ]
Convert text data from requests object to dataframe with pandas
39,213,597
<p>Using requests I am creating an object which is in .csv format. How can I then write that object to a DataFrame with pandas?</p> <p>To get the requests object in text format:</p> <pre><code>import requests import pandas as pd url = r'http://test.url' r = requests.get(url) r.text #this will return the data as text in csv format </code></pre> <p>I tried (doesn't work):</p> <pre><code>pd.read_csv(r.text) pd.DataFrame.from_csv(r.text) </code></pre>
1
2016-08-29T19:19:04Z
39,213,730
<p>if the url has no authentication then you can directly use read_csv(url)</p> <p>if you have authentication you can use request to get it un-pickel and print the csv and make sure the result is CSV and use panda.</p> <p>You can directly use importing import csv</p>
1
2016-08-29T19:27:31Z
[ "python", "csv", "pandas", "dataframe", "python-requests" ]
Convert text data from requests object to dataframe with pandas
39,213,597
<p>Using requests I am creating an object which is in .csv format. How can I then write that object to a DataFrame with pandas?</p> <p>To get the requests object in text format:</p> <pre><code>import requests import pandas as pd url = r'http://test.url' r = requests.get(url) r.text #this will return the data as text in csv format </code></pre> <p>I tried (doesn't work):</p> <pre><code>pd.read_csv(r.text) pd.DataFrame.from_csv(r.text) </code></pre>
1
2016-08-29T19:19:04Z
39,213,780
<p>Try this</p> <pre><code>import requests import pandas as pd import io urlData = requests.get(url).content rawData = pd.read_csv(io.StringIO(urlData.decode('utf-8'))) </code></pre>
1
2016-08-29T19:30:35Z
[ "python", "csv", "pandas", "dataframe", "python-requests" ]
Apparently, Python Strings are not 'born equal'
39,213,688
<p>I'm trying to wrap my brain around the 'text encoding standards'. When interpreting a bunch of bytes as 'text', one has to know which 'encoding sheme' applies. Possible candidates that I know of:</p> <ul> <li>ASCII: Very basic encoding scheme, supports 128 characters.</li> <li>CP-1252: Windows encoding scheme for the Latin alphabet. Also known as 'ANSI'.</li> <li>UTF-8: A coding scheme for the Unicode table (1.114.112 characters). Represents each character with one byte if possible, more bytes if needed (max. 4 bytes).</li> <li>UTF-16: Another coding scheme for the Unicode table (1.114.112 characters). Represents each character with min 2 bytes, max 4 bytes.</li> <li>UTF-32: Yet another coding scheme for the Unicode table. Represents each character with 4 bytes.</li> <li>. . .</li> </ul> <p>Now I would expect that Python consistently uses one encoding scheme for its built-in String type. I did the following test, and the result makes me shiver. I start to believe that Python is not consistently sticking to one encoding scheme to store its Strings internally. In other words: Python Strings seem to be 'not born equal'..</p> <p><strong>EDIT :</strong></p> <p>I forgot to mention that I'm using Python 3.x . Sorry :-)</p> <p><strong>1. The test</strong></p> <p>I have two simple text files in a folder: <code>myAnsi.txt</code> and <code>myUtf.txt</code>. As you can guess, the first is encoded in the <code>CP-1252</code> encoding scheme, also known as <code>ANSI</code>. The latter is encoded in <code>utf-8</code>. In my test, I open each file and read out its content. I assign the content to a native Python String variable. Then I close the file. After that, I create a new file and write the content of the String variable to that file. Here is the code to do all that:</p> <pre><code> ############################## # TEST ON THE ANSI-coded # # FILE # ############################## import os file = open(os.getcwd() + '\\myAnsi.txt', 'r') fileText = file.read() file.close() file = open(os.getcwd() + '\\outputAnsi.txt', 'w') file.write(fileText) file.close() # A print statement here like: # &gt;&gt; print(fileText) # will raise an exception. # But if you're typing this code in a python terminal, # you can just write: # &gt;&gt; fileText # and get the content printed. In my case, it is the exact # content of the file. # PS: I use the native windows cmd.exe as my Python terminal ;-) ############################## # TEST ON THE Utf-coded # # FILE # ############################## import os file = open(os.getcwd() + '\\myUtf.txt', 'r') fileText = file.read() file.close() file = open(os.getcwd() + '\\outputUtf.txt', 'w') file.write(fileText) file.close() # A print statement here like: # &gt;&gt; print(fileText) # will just work fine (at least for me). ############# END OF TEST ############# </code></pre> <p><strong>2. The result I would expect</strong></p> <p>Let us suppose that Python consistently sticks to one internal coding scheme - for example <code>utf-8</code> - for all its Strings. Assigning other content to a String would lead to some sort of implicit conversion. Under these assumptions, I would expect both output files to be of the <code>utf-8</code> type:</p> <pre><code> outputAnsi.txt -&gt; utf-8 encoded outputUtf.txt -&gt; utf-8 encoded </code></pre> <p><strong>3. The result I get</strong></p> <p>The result I get is this:</p> <pre><code> outputAnsi.txt -&gt; CP-1252 encoded (ANSI) outputUtf.txt -&gt; utf-8 encoded </code></pre> <p>From these results, I have to conclude that the String variable <code>fileText</code> somehow stores the encoding scheme it adheres to.</p> <p>Many people tell me in their answers:</p> <blockquote> <p>When no encoding is passed explicitly, <code>open()</code> uses the preferred system encoding both for reading and for writing.</p> </blockquote> <p>I just cannot wrap my brain around that statement. If open() uses the 'preferred system encoding' - say <code>cp1252</code> as example - then both <code>*.txt</code> outputs should be encoded in that way, wouldn't they?</p> <p><strong>4. Questions..</strong></p> <p>My test raises several questions to me:</p> <p>(1) When I open a file to read its content, how does Python know the encoding scheme of that file? I did not specify it when opening the file.</p> <p>(2) Apparently a Python String can adhere to any encoding scheme supported by Python. So not all Python Strings are born equal. How do you find out the encoding scheme of a particular String, and how do you convert it? Or how do you make sure your freshly created Python String is of the expected type?</p> <p>(3) When I create a file, how does Python decide in what encoding scheme the file will be created? I did not specify the encoding scheme when creating those files in my test. Nevertheless, Python made a different (!) decision in each case.</p> <p><strong>5. Extra information (based on the comments to this question):</strong></p> <ul> <li>Python version: Python 3.x (installed from Anaconda)</li> <li>Operating system: Windows 10</li> <li>Terminal: Standard Windows command prompt <code>cmd.exe</code></li> <li>Some questions raised about the temporary variable <code>fileText</code>. Apparently the instruction <code>print(fileText)</code> does not work for the ANSI case. An exception is thrown. But in the python terminal window, I can simply type the variable name <code>fileText</code> and get the file content printed out.</li> <li>Encoding detection of files: Bottom right corner of Notepad++ for first check, online tool for double check: <a href="https://nlp.fi.muni.cz/projects/chared/" rel="nofollow">https://nlp.fi.muni.cz/projects/chared/</a></li> <li>The output files <code>outputAnsi.txt</code> and <code>outputUtf.txt</code> do not exist at the start of the test. They are created at the very moment that I issue the <code>open(..)</code> command with the <code>'w'</code> option.</li> </ul> <p><strong>6. The actual files (for completeness):</strong></p> <p>I got several comments encouraging me to share the actual files on which I'm doing this test. Those files were quite large, so I've trimmed them down and re-did the tests. Results are similar. Here are the files (PS: of course, my files contain source code, what else?):</p> <p><strong>myAnsi.txt</strong></p> <pre><code>/* ****************************************************************************** ** ** File : LinkerScript.ld ** ** Author : Auto-generated by Ac6 System Workbench ** ** Abstract : Linker script for STM32F746NGHx Device from STM32F7 series ** ** Target : STMicroelectronics STM32 ** ** Distribution: The file is distributed “as is,” without any warranty ** of any kind. ** ***************************************************************************** ** @attention ** ** &lt;h2&gt;&lt;center&gt;&amp;copy; COPYRIGHT(c) 2014 Ac6&lt;/center&gt;&lt;/h2&gt; ** ***************************************************************************** */ /* Entry Point */ /*ENTRY(Reset_Handler)*/ ENTRY(Default_Handler) /* Highest address of the user mode stack */ _estack = 0x20050000; /* end of RAM */ _Min_Heap_Size = 0; /* required amount of heap */ _Min_Stack_Size = 0x400; /* required amount of stack */ /* Memories definition */ MEMORY { RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 320K ROM (rx) : ORIGIN = 0x8000000, LENGTH = 1024K } </code></pre> <p>The print statement of the <code>fileText</code> variable leads to the following exception:</p> <pre><code>&gt;&gt;&gt; print(fileText) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Anaconda3\lib\encodings\cp850.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u201c' in position 357: character maps to &lt;undefined&gt; </code></pre> <p>But just typing the name of the variable prints out the contents without problems:</p> <pre><code>&gt;&gt;&gt; fileText ### contents of the file are printed out :-) ### </code></pre> <p><strong>myUtf.txt</strong></p> <pre><code>/*--------------------------------------------------------------------------------------------------------------------*/ /* _ _ _ */ /* / -,- \ __ _ _ */ /* // | \\ / __\ | ___ ___| | __ _ _ */ /* | 0--,| / / | |/ _ \ / __| |/ / __ ___ _ _ __| |_ __ _ _ _| |_ ___ */ /* \\ // / /___| | (_) | (__| &lt; / _/ _ \ ' \(_-&lt; _/ _` | ' \ _(_-&lt; */ /* \_-_-_/ \____/|_|\___/ \___|_|\_\ \__\___/_||_/__/\__\__,_|_||_\__/__/ */ /*--------------------------------------------------------------------------------------------------------------------*/ #include "clock_constants.h" #include "../CMSIS/stm32f7xx.h" #include "stm32f7xx_hal_rcc.h" /*--------------------------------------------------------------------------------------------------*/ /* S y s t e m C o r e C l o c k i n i t i a l v a l u e */ /*--------------------------------------------------------------------------------------------------*/ /* */ /* This variable is updated in three ways: */ /* 1) by calling CMSIS function SystemCoreClockUpdate() */ /* 2) by calling HAL API function HAL_RCC_GetHCLKFreq() */ /* 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency */ /* Note: If you use this function to configure the system clock; then there */ /* is no need to call the 2 first functions listed above, since SystemCoreClock */ /* variable is updated automatically. */ /* */ uint32_t SystemCoreClock = 16000000; const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; /*--------------------------------------------------------------------------------------------------*/ /* S y s t e m C o r e C l o c k v a l u e u p d a t e */ /*--------------------------------------------------------------------------------------------------*/ /* */ /* @brief Update SystemCoreClock variable according to Clock Register Values. */ /* The SystemCoreClock variable contains the core clock (HCLK), it can */ /* be used by the user application to setup the SysTick timer or configure */ /* other parameters. */ /*--------------------------------------------------------------------------------------------------*/ </code></pre>
4
2016-08-29T19:24:34Z
39,214,238
<p>CP-1252 is basically a byte for byte codec; it can decode arbitrary bytes, including the bytes from UTF-8 encoding. So effectively, assuming you're on Windows using a Western locale, where the default encoding provided to <code>open</code> is <code>cp-1252</code>, if you never work with the string in Python, just read and write it, you may as well have just read and written in binary mode. You'd only see a problem if you tried to use the string in ways that exposed the problem.</p> <p>For example, consider the following test file with a single UTF-8 encoded character in it:</p> <pre><code>with open('utf8file.txt', 'w', encoding='utf-8') as f: f.write('é') </code></pre> <p>The actual bytes in that file are <code>C3 A9</code>.</p> <p>If you read that file in <code>cp-1252</code>, it will happily do so, because every byte is a legal <code>cp-1252</code> byte:</p> <pre><code>with open('utf8file.txt') as f: data = f.read() </code></pre> <p>But it's not the string <code>'é'</code>, it's what those two bytes happen to represent in <code>cp-1252</code>: <code>"é"</code> (you can print them or check the length and you'll see that, assuming your console encoding handles non-ASCII)</p> <p>If you're just writing it back though, without using it, you'd never see this; the output step is (default) encoding <code>"é"</code> as <code>C9 A9</code>, which restores the original bytes that you expect.</p> <p>Your problem is that most files are legal <code>cp-1252</code> text files (and it's possible Python will silently read unassigned bytes as equivalent Unicode ordinals; I know it does so for <code>latin-1</code> for unassigned bytes like <code>\x8d</code>), and when they're legal, reading as such and writing back in the same encoding is non-mutating.</p>
3
2016-08-29T20:00:41Z
[ "python", "python-3.x", "unicode", "encoding", "utf-8" ]
Apparently, Python Strings are not 'born equal'
39,213,688
<p>I'm trying to wrap my brain around the 'text encoding standards'. When interpreting a bunch of bytes as 'text', one has to know which 'encoding sheme' applies. Possible candidates that I know of:</p> <ul> <li>ASCII: Very basic encoding scheme, supports 128 characters.</li> <li>CP-1252: Windows encoding scheme for the Latin alphabet. Also known as 'ANSI'.</li> <li>UTF-8: A coding scheme for the Unicode table (1.114.112 characters). Represents each character with one byte if possible, more bytes if needed (max. 4 bytes).</li> <li>UTF-16: Another coding scheme for the Unicode table (1.114.112 characters). Represents each character with min 2 bytes, max 4 bytes.</li> <li>UTF-32: Yet another coding scheme for the Unicode table. Represents each character with 4 bytes.</li> <li>. . .</li> </ul> <p>Now I would expect that Python consistently uses one encoding scheme for its built-in String type. I did the following test, and the result makes me shiver. I start to believe that Python is not consistently sticking to one encoding scheme to store its Strings internally. In other words: Python Strings seem to be 'not born equal'..</p> <p><strong>EDIT :</strong></p> <p>I forgot to mention that I'm using Python 3.x . Sorry :-)</p> <p><strong>1. The test</strong></p> <p>I have two simple text files in a folder: <code>myAnsi.txt</code> and <code>myUtf.txt</code>. As you can guess, the first is encoded in the <code>CP-1252</code> encoding scheme, also known as <code>ANSI</code>. The latter is encoded in <code>utf-8</code>. In my test, I open each file and read out its content. I assign the content to a native Python String variable. Then I close the file. After that, I create a new file and write the content of the String variable to that file. Here is the code to do all that:</p> <pre><code> ############################## # TEST ON THE ANSI-coded # # FILE # ############################## import os file = open(os.getcwd() + '\\myAnsi.txt', 'r') fileText = file.read() file.close() file = open(os.getcwd() + '\\outputAnsi.txt', 'w') file.write(fileText) file.close() # A print statement here like: # &gt;&gt; print(fileText) # will raise an exception. # But if you're typing this code in a python terminal, # you can just write: # &gt;&gt; fileText # and get the content printed. In my case, it is the exact # content of the file. # PS: I use the native windows cmd.exe as my Python terminal ;-) ############################## # TEST ON THE Utf-coded # # FILE # ############################## import os file = open(os.getcwd() + '\\myUtf.txt', 'r') fileText = file.read() file.close() file = open(os.getcwd() + '\\outputUtf.txt', 'w') file.write(fileText) file.close() # A print statement here like: # &gt;&gt; print(fileText) # will just work fine (at least for me). ############# END OF TEST ############# </code></pre> <p><strong>2. The result I would expect</strong></p> <p>Let us suppose that Python consistently sticks to one internal coding scheme - for example <code>utf-8</code> - for all its Strings. Assigning other content to a String would lead to some sort of implicit conversion. Under these assumptions, I would expect both output files to be of the <code>utf-8</code> type:</p> <pre><code> outputAnsi.txt -&gt; utf-8 encoded outputUtf.txt -&gt; utf-8 encoded </code></pre> <p><strong>3. The result I get</strong></p> <p>The result I get is this:</p> <pre><code> outputAnsi.txt -&gt; CP-1252 encoded (ANSI) outputUtf.txt -&gt; utf-8 encoded </code></pre> <p>From these results, I have to conclude that the String variable <code>fileText</code> somehow stores the encoding scheme it adheres to.</p> <p>Many people tell me in their answers:</p> <blockquote> <p>When no encoding is passed explicitly, <code>open()</code> uses the preferred system encoding both for reading and for writing.</p> </blockquote> <p>I just cannot wrap my brain around that statement. If open() uses the 'preferred system encoding' - say <code>cp1252</code> as example - then both <code>*.txt</code> outputs should be encoded in that way, wouldn't they?</p> <p><strong>4. Questions..</strong></p> <p>My test raises several questions to me:</p> <p>(1) When I open a file to read its content, how does Python know the encoding scheme of that file? I did not specify it when opening the file.</p> <p>(2) Apparently a Python String can adhere to any encoding scheme supported by Python. So not all Python Strings are born equal. How do you find out the encoding scheme of a particular String, and how do you convert it? Or how do you make sure your freshly created Python String is of the expected type?</p> <p>(3) When I create a file, how does Python decide in what encoding scheme the file will be created? I did not specify the encoding scheme when creating those files in my test. Nevertheless, Python made a different (!) decision in each case.</p> <p><strong>5. Extra information (based on the comments to this question):</strong></p> <ul> <li>Python version: Python 3.x (installed from Anaconda)</li> <li>Operating system: Windows 10</li> <li>Terminal: Standard Windows command prompt <code>cmd.exe</code></li> <li>Some questions raised about the temporary variable <code>fileText</code>. Apparently the instruction <code>print(fileText)</code> does not work for the ANSI case. An exception is thrown. But in the python terminal window, I can simply type the variable name <code>fileText</code> and get the file content printed out.</li> <li>Encoding detection of files: Bottom right corner of Notepad++ for first check, online tool for double check: <a href="https://nlp.fi.muni.cz/projects/chared/" rel="nofollow">https://nlp.fi.muni.cz/projects/chared/</a></li> <li>The output files <code>outputAnsi.txt</code> and <code>outputUtf.txt</code> do not exist at the start of the test. They are created at the very moment that I issue the <code>open(..)</code> command with the <code>'w'</code> option.</li> </ul> <p><strong>6. The actual files (for completeness):</strong></p> <p>I got several comments encouraging me to share the actual files on which I'm doing this test. Those files were quite large, so I've trimmed them down and re-did the tests. Results are similar. Here are the files (PS: of course, my files contain source code, what else?):</p> <p><strong>myAnsi.txt</strong></p> <pre><code>/* ****************************************************************************** ** ** File : LinkerScript.ld ** ** Author : Auto-generated by Ac6 System Workbench ** ** Abstract : Linker script for STM32F746NGHx Device from STM32F7 series ** ** Target : STMicroelectronics STM32 ** ** Distribution: The file is distributed “as is,” without any warranty ** of any kind. ** ***************************************************************************** ** @attention ** ** &lt;h2&gt;&lt;center&gt;&amp;copy; COPYRIGHT(c) 2014 Ac6&lt;/center&gt;&lt;/h2&gt; ** ***************************************************************************** */ /* Entry Point */ /*ENTRY(Reset_Handler)*/ ENTRY(Default_Handler) /* Highest address of the user mode stack */ _estack = 0x20050000; /* end of RAM */ _Min_Heap_Size = 0; /* required amount of heap */ _Min_Stack_Size = 0x400; /* required amount of stack */ /* Memories definition */ MEMORY { RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 320K ROM (rx) : ORIGIN = 0x8000000, LENGTH = 1024K } </code></pre> <p>The print statement of the <code>fileText</code> variable leads to the following exception:</p> <pre><code>&gt;&gt;&gt; print(fileText) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Anaconda3\lib\encodings\cp850.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u201c' in position 357: character maps to &lt;undefined&gt; </code></pre> <p>But just typing the name of the variable prints out the contents without problems:</p> <pre><code>&gt;&gt;&gt; fileText ### contents of the file are printed out :-) ### </code></pre> <p><strong>myUtf.txt</strong></p> <pre><code>/*--------------------------------------------------------------------------------------------------------------------*/ /* _ _ _ */ /* / -,- \ __ _ _ */ /* // | \\ / __\ | ___ ___| | __ _ _ */ /* | 0--,| / / | |/ _ \ / __| |/ / __ ___ _ _ __| |_ __ _ _ _| |_ ___ */ /* \\ // / /___| | (_) | (__| &lt; / _/ _ \ ' \(_-&lt; _/ _` | ' \ _(_-&lt; */ /* \_-_-_/ \____/|_|\___/ \___|_|\_\ \__\___/_||_/__/\__\__,_|_||_\__/__/ */ /*--------------------------------------------------------------------------------------------------------------------*/ #include "clock_constants.h" #include "../CMSIS/stm32f7xx.h" #include "stm32f7xx_hal_rcc.h" /*--------------------------------------------------------------------------------------------------*/ /* S y s t e m C o r e C l o c k i n i t i a l v a l u e */ /*--------------------------------------------------------------------------------------------------*/ /* */ /* This variable is updated in three ways: */ /* 1) by calling CMSIS function SystemCoreClockUpdate() */ /* 2) by calling HAL API function HAL_RCC_GetHCLKFreq() */ /* 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency */ /* Note: If you use this function to configure the system clock; then there */ /* is no need to call the 2 first functions listed above, since SystemCoreClock */ /* variable is updated automatically. */ /* */ uint32_t SystemCoreClock = 16000000; const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; /*--------------------------------------------------------------------------------------------------*/ /* S y s t e m C o r e C l o c k v a l u e u p d a t e */ /*--------------------------------------------------------------------------------------------------*/ /* */ /* @brief Update SystemCoreClock variable according to Clock Register Values. */ /* The SystemCoreClock variable contains the core clock (HCLK), it can */ /* be used by the user application to setup the SysTick timer or configure */ /* other parameters. */ /*--------------------------------------------------------------------------------------------------*/ </code></pre>
4
2016-08-29T19:24:34Z
39,214,252
<p>When no encoding is passed explicitly, <a href="https://docs.python.org/3.5/library/functions.html#open" rel="nofollow"><code>open()</code> uses the preferred system encoding</a> both for reading and for writing (not sure exactly how the preferred encoding is detected on Windows).</p> <p>So, when you write:</p> <pre><code>file = open(os.getcwd() + '\\myAnsi.txt', 'r') file = open(os.getcwd() + '\\outputAnsi.txt', 'w') file = open(os.getcwd() + '\\myUtf.txt', 'r') file = open(os.getcwd() + '\\outputUtf.txt', 'w') </code></pre> <p>All four files are opened using the same encoding, both for reading and for writing.</p> <p>You have to pass <code>encoding='cp1252'</code> or <code>encoding='utf-8'</code> if you want to be sure that files are opened using these encodings:</p> <pre><code>file = open(os.getcwd() + '\\myAnsi.txt', 'r', encoding='cp1252') file = open(os.getcwd() + '\\outputAnsi.txt', 'w', encoding='cp1252') file = open(os.getcwd() + '\\myUtf.txt', 'r', encoding='utf-8') file = open(os.getcwd() + '\\outputUtf.txt', 'w', encoding='utf-8') </code></pre> <p>(As a side note, I'm not a Windows expert, but I think you can write <code>'myAnsi.txt'</code> instead of <code>os.getcwd() + '\\myAnsi.txt'</code>.)</p> <hr> <p>Apart from that, you have to consider that some characters are represented in the same way with different encodings. For example, the string <code>hello</code> has the same representation in ASCII, CP-1252 or UTF-8. In general, you have to use some non-ASCII characters to see some differences:</p> <pre><code>&gt;&gt;&gt; 'hello'.encode('cp1252') b'hello' &gt;&gt;&gt; 'hello'.encode('utf-8') b'hello' # different encoding, same byte representation </code></pre> <p>Not only that, but some byte strings can be perfectly valid in two distinct encodings, even though they can have different meanings, so that when you try to decode a file with the wrong encoding you don't get an error, but a weird string:</p> <pre><code>&gt;&gt;&gt; b'\xe2\x82\xac'.decode('utf-8') '€' &gt;&gt;&gt; b'\xe2\x82\xac'.decode('cp1252') '€' # same byte representation, different string </code></pre> <hr> <p>For the record, <a href="https://docs.python.org/3.5/c-api/unicode.html" rel="nofollow">Python uses UTF-8, UTF-16 or UTF-32</a> to represent strings internally. Python tries to use the "shortest" representation, even though UTF-8 and UTF-16 are used without continuation bytes, so that lookups are always O(1).</p> <hr> <p>In short, you have read two files using the system encoding and written two files using the same encoding (therefore without any transformation). The content of the files you have read are compatible with both CP-1252 and UTF-8.</p>
2
2016-08-29T20:02:19Z
[ "python", "python-3.x", "unicode", "encoding", "utf-8" ]
Apparently, Python Strings are not 'born equal'
39,213,688
<p>I'm trying to wrap my brain around the 'text encoding standards'. When interpreting a bunch of bytes as 'text', one has to know which 'encoding sheme' applies. Possible candidates that I know of:</p> <ul> <li>ASCII: Very basic encoding scheme, supports 128 characters.</li> <li>CP-1252: Windows encoding scheme for the Latin alphabet. Also known as 'ANSI'.</li> <li>UTF-8: A coding scheme for the Unicode table (1.114.112 characters). Represents each character with one byte if possible, more bytes if needed (max. 4 bytes).</li> <li>UTF-16: Another coding scheme for the Unicode table (1.114.112 characters). Represents each character with min 2 bytes, max 4 bytes.</li> <li>UTF-32: Yet another coding scheme for the Unicode table. Represents each character with 4 bytes.</li> <li>. . .</li> </ul> <p>Now I would expect that Python consistently uses one encoding scheme for its built-in String type. I did the following test, and the result makes me shiver. I start to believe that Python is not consistently sticking to one encoding scheme to store its Strings internally. In other words: Python Strings seem to be 'not born equal'..</p> <p><strong>EDIT :</strong></p> <p>I forgot to mention that I'm using Python 3.x . Sorry :-)</p> <p><strong>1. The test</strong></p> <p>I have two simple text files in a folder: <code>myAnsi.txt</code> and <code>myUtf.txt</code>. As you can guess, the first is encoded in the <code>CP-1252</code> encoding scheme, also known as <code>ANSI</code>. The latter is encoded in <code>utf-8</code>. In my test, I open each file and read out its content. I assign the content to a native Python String variable. Then I close the file. After that, I create a new file and write the content of the String variable to that file. Here is the code to do all that:</p> <pre><code> ############################## # TEST ON THE ANSI-coded # # FILE # ############################## import os file = open(os.getcwd() + '\\myAnsi.txt', 'r') fileText = file.read() file.close() file = open(os.getcwd() + '\\outputAnsi.txt', 'w') file.write(fileText) file.close() # A print statement here like: # &gt;&gt; print(fileText) # will raise an exception. # But if you're typing this code in a python terminal, # you can just write: # &gt;&gt; fileText # and get the content printed. In my case, it is the exact # content of the file. # PS: I use the native windows cmd.exe as my Python terminal ;-) ############################## # TEST ON THE Utf-coded # # FILE # ############################## import os file = open(os.getcwd() + '\\myUtf.txt', 'r') fileText = file.read() file.close() file = open(os.getcwd() + '\\outputUtf.txt', 'w') file.write(fileText) file.close() # A print statement here like: # &gt;&gt; print(fileText) # will just work fine (at least for me). ############# END OF TEST ############# </code></pre> <p><strong>2. The result I would expect</strong></p> <p>Let us suppose that Python consistently sticks to one internal coding scheme - for example <code>utf-8</code> - for all its Strings. Assigning other content to a String would lead to some sort of implicit conversion. Under these assumptions, I would expect both output files to be of the <code>utf-8</code> type:</p> <pre><code> outputAnsi.txt -&gt; utf-8 encoded outputUtf.txt -&gt; utf-8 encoded </code></pre> <p><strong>3. The result I get</strong></p> <p>The result I get is this:</p> <pre><code> outputAnsi.txt -&gt; CP-1252 encoded (ANSI) outputUtf.txt -&gt; utf-8 encoded </code></pre> <p>From these results, I have to conclude that the String variable <code>fileText</code> somehow stores the encoding scheme it adheres to.</p> <p>Many people tell me in their answers:</p> <blockquote> <p>When no encoding is passed explicitly, <code>open()</code> uses the preferred system encoding both for reading and for writing.</p> </blockquote> <p>I just cannot wrap my brain around that statement. If open() uses the 'preferred system encoding' - say <code>cp1252</code> as example - then both <code>*.txt</code> outputs should be encoded in that way, wouldn't they?</p> <p><strong>4. Questions..</strong></p> <p>My test raises several questions to me:</p> <p>(1) When I open a file to read its content, how does Python know the encoding scheme of that file? I did not specify it when opening the file.</p> <p>(2) Apparently a Python String can adhere to any encoding scheme supported by Python. So not all Python Strings are born equal. How do you find out the encoding scheme of a particular String, and how do you convert it? Or how do you make sure your freshly created Python String is of the expected type?</p> <p>(3) When I create a file, how does Python decide in what encoding scheme the file will be created? I did not specify the encoding scheme when creating those files in my test. Nevertheless, Python made a different (!) decision in each case.</p> <p><strong>5. Extra information (based on the comments to this question):</strong></p> <ul> <li>Python version: Python 3.x (installed from Anaconda)</li> <li>Operating system: Windows 10</li> <li>Terminal: Standard Windows command prompt <code>cmd.exe</code></li> <li>Some questions raised about the temporary variable <code>fileText</code>. Apparently the instruction <code>print(fileText)</code> does not work for the ANSI case. An exception is thrown. But in the python terminal window, I can simply type the variable name <code>fileText</code> and get the file content printed out.</li> <li>Encoding detection of files: Bottom right corner of Notepad++ for first check, online tool for double check: <a href="https://nlp.fi.muni.cz/projects/chared/" rel="nofollow">https://nlp.fi.muni.cz/projects/chared/</a></li> <li>The output files <code>outputAnsi.txt</code> and <code>outputUtf.txt</code> do not exist at the start of the test. They are created at the very moment that I issue the <code>open(..)</code> command with the <code>'w'</code> option.</li> </ul> <p><strong>6. The actual files (for completeness):</strong></p> <p>I got several comments encouraging me to share the actual files on which I'm doing this test. Those files were quite large, so I've trimmed them down and re-did the tests. Results are similar. Here are the files (PS: of course, my files contain source code, what else?):</p> <p><strong>myAnsi.txt</strong></p> <pre><code>/* ****************************************************************************** ** ** File : LinkerScript.ld ** ** Author : Auto-generated by Ac6 System Workbench ** ** Abstract : Linker script for STM32F746NGHx Device from STM32F7 series ** ** Target : STMicroelectronics STM32 ** ** Distribution: The file is distributed “as is,” without any warranty ** of any kind. ** ***************************************************************************** ** @attention ** ** &lt;h2&gt;&lt;center&gt;&amp;copy; COPYRIGHT(c) 2014 Ac6&lt;/center&gt;&lt;/h2&gt; ** ***************************************************************************** */ /* Entry Point */ /*ENTRY(Reset_Handler)*/ ENTRY(Default_Handler) /* Highest address of the user mode stack */ _estack = 0x20050000; /* end of RAM */ _Min_Heap_Size = 0; /* required amount of heap */ _Min_Stack_Size = 0x400; /* required amount of stack */ /* Memories definition */ MEMORY { RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 320K ROM (rx) : ORIGIN = 0x8000000, LENGTH = 1024K } </code></pre> <p>The print statement of the <code>fileText</code> variable leads to the following exception:</p> <pre><code>&gt;&gt;&gt; print(fileText) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Anaconda3\lib\encodings\cp850.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u201c' in position 357: character maps to &lt;undefined&gt; </code></pre> <p>But just typing the name of the variable prints out the contents without problems:</p> <pre><code>&gt;&gt;&gt; fileText ### contents of the file are printed out :-) ### </code></pre> <p><strong>myUtf.txt</strong></p> <pre><code>/*--------------------------------------------------------------------------------------------------------------------*/ /* _ _ _ */ /* / -,- \ __ _ _ */ /* // | \\ / __\ | ___ ___| | __ _ _ */ /* | 0--,| / / | |/ _ \ / __| |/ / __ ___ _ _ __| |_ __ _ _ _| |_ ___ */ /* \\ // / /___| | (_) | (__| &lt; / _/ _ \ ' \(_-&lt; _/ _` | ' \ _(_-&lt; */ /* \_-_-_/ \____/|_|\___/ \___|_|\_\ \__\___/_||_/__/\__\__,_|_||_\__/__/ */ /*--------------------------------------------------------------------------------------------------------------------*/ #include "clock_constants.h" #include "../CMSIS/stm32f7xx.h" #include "stm32f7xx_hal_rcc.h" /*--------------------------------------------------------------------------------------------------*/ /* S y s t e m C o r e C l o c k i n i t i a l v a l u e */ /*--------------------------------------------------------------------------------------------------*/ /* */ /* This variable is updated in three ways: */ /* 1) by calling CMSIS function SystemCoreClockUpdate() */ /* 2) by calling HAL API function HAL_RCC_GetHCLKFreq() */ /* 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency */ /* Note: If you use this function to configure the system clock; then there */ /* is no need to call the 2 first functions listed above, since SystemCoreClock */ /* variable is updated automatically. */ /* */ uint32_t SystemCoreClock = 16000000; const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; /*--------------------------------------------------------------------------------------------------*/ /* S y s t e m C o r e C l o c k v a l u e u p d a t e */ /*--------------------------------------------------------------------------------------------------*/ /* */ /* @brief Update SystemCoreClock variable according to Clock Register Values. */ /* The SystemCoreClock variable contains the core clock (HCLK), it can */ /* be used by the user application to setup the SysTick timer or configure */ /* other parameters. */ /*--------------------------------------------------------------------------------------------------*/ </code></pre>
4
2016-08-29T19:24:34Z
39,214,323
<p>To fully grasp the answer we need to look at the documentation a bit. </p> <p>Let's start with the <em>open()</em> function. According to the Python 3.* documentation </p> <blockquote> <p>open() returns a file object, and is most commonly used with two arguments: open(filename, mode). <a href="https://docs.python.org/3/tutorial/inputoutput.html" rel="nofollow">1</a></p> </blockquote> <p>This means that we are dealing with a file object which could mean raw binary, buffered binary or in this case, text files <a href="https://docs.python.org/3/glossary.html#term-file-object" rel="nofollow">2</a>. But how can this text file object know it's encoding? Well again, according to the documentation </p> <blockquote> <p>A file object able to read and write str objects. Often, a text file actually accesses a byte-oriented datastream and handles the text encoding automatically.<a href="https://docs.python.org/3/glossary.html#term-text-file" rel="nofollow">3</a></p> </blockquote> <p>So there we have it, it's handle automatically. And since both of those formats fall within the supported codecs. Python knows how to encode your files on writes given the file object. </p>
1
2016-08-29T20:06:31Z
[ "python", "python-3.x", "unicode", "encoding", "utf-8" ]
Apparently, Python Strings are not 'born equal'
39,213,688
<p>I'm trying to wrap my brain around the 'text encoding standards'. When interpreting a bunch of bytes as 'text', one has to know which 'encoding sheme' applies. Possible candidates that I know of:</p> <ul> <li>ASCII: Very basic encoding scheme, supports 128 characters.</li> <li>CP-1252: Windows encoding scheme for the Latin alphabet. Also known as 'ANSI'.</li> <li>UTF-8: A coding scheme for the Unicode table (1.114.112 characters). Represents each character with one byte if possible, more bytes if needed (max. 4 bytes).</li> <li>UTF-16: Another coding scheme for the Unicode table (1.114.112 characters). Represents each character with min 2 bytes, max 4 bytes.</li> <li>UTF-32: Yet another coding scheme for the Unicode table. Represents each character with 4 bytes.</li> <li>. . .</li> </ul> <p>Now I would expect that Python consistently uses one encoding scheme for its built-in String type. I did the following test, and the result makes me shiver. I start to believe that Python is not consistently sticking to one encoding scheme to store its Strings internally. In other words: Python Strings seem to be 'not born equal'..</p> <p><strong>EDIT :</strong></p> <p>I forgot to mention that I'm using Python 3.x . Sorry :-)</p> <p><strong>1. The test</strong></p> <p>I have two simple text files in a folder: <code>myAnsi.txt</code> and <code>myUtf.txt</code>. As you can guess, the first is encoded in the <code>CP-1252</code> encoding scheme, also known as <code>ANSI</code>. The latter is encoded in <code>utf-8</code>. In my test, I open each file and read out its content. I assign the content to a native Python String variable. Then I close the file. After that, I create a new file and write the content of the String variable to that file. Here is the code to do all that:</p> <pre><code> ############################## # TEST ON THE ANSI-coded # # FILE # ############################## import os file = open(os.getcwd() + '\\myAnsi.txt', 'r') fileText = file.read() file.close() file = open(os.getcwd() + '\\outputAnsi.txt', 'w') file.write(fileText) file.close() # A print statement here like: # &gt;&gt; print(fileText) # will raise an exception. # But if you're typing this code in a python terminal, # you can just write: # &gt;&gt; fileText # and get the content printed. In my case, it is the exact # content of the file. # PS: I use the native windows cmd.exe as my Python terminal ;-) ############################## # TEST ON THE Utf-coded # # FILE # ############################## import os file = open(os.getcwd() + '\\myUtf.txt', 'r') fileText = file.read() file.close() file = open(os.getcwd() + '\\outputUtf.txt', 'w') file.write(fileText) file.close() # A print statement here like: # &gt;&gt; print(fileText) # will just work fine (at least for me). ############# END OF TEST ############# </code></pre> <p><strong>2. The result I would expect</strong></p> <p>Let us suppose that Python consistently sticks to one internal coding scheme - for example <code>utf-8</code> - for all its Strings. Assigning other content to a String would lead to some sort of implicit conversion. Under these assumptions, I would expect both output files to be of the <code>utf-8</code> type:</p> <pre><code> outputAnsi.txt -&gt; utf-8 encoded outputUtf.txt -&gt; utf-8 encoded </code></pre> <p><strong>3. The result I get</strong></p> <p>The result I get is this:</p> <pre><code> outputAnsi.txt -&gt; CP-1252 encoded (ANSI) outputUtf.txt -&gt; utf-8 encoded </code></pre> <p>From these results, I have to conclude that the String variable <code>fileText</code> somehow stores the encoding scheme it adheres to.</p> <p>Many people tell me in their answers:</p> <blockquote> <p>When no encoding is passed explicitly, <code>open()</code> uses the preferred system encoding both for reading and for writing.</p> </blockquote> <p>I just cannot wrap my brain around that statement. If open() uses the 'preferred system encoding' - say <code>cp1252</code> as example - then both <code>*.txt</code> outputs should be encoded in that way, wouldn't they?</p> <p><strong>4. Questions..</strong></p> <p>My test raises several questions to me:</p> <p>(1) When I open a file to read its content, how does Python know the encoding scheme of that file? I did not specify it when opening the file.</p> <p>(2) Apparently a Python String can adhere to any encoding scheme supported by Python. So not all Python Strings are born equal. How do you find out the encoding scheme of a particular String, and how do you convert it? Or how do you make sure your freshly created Python String is of the expected type?</p> <p>(3) When I create a file, how does Python decide in what encoding scheme the file will be created? I did not specify the encoding scheme when creating those files in my test. Nevertheless, Python made a different (!) decision in each case.</p> <p><strong>5. Extra information (based on the comments to this question):</strong></p> <ul> <li>Python version: Python 3.x (installed from Anaconda)</li> <li>Operating system: Windows 10</li> <li>Terminal: Standard Windows command prompt <code>cmd.exe</code></li> <li>Some questions raised about the temporary variable <code>fileText</code>. Apparently the instruction <code>print(fileText)</code> does not work for the ANSI case. An exception is thrown. But in the python terminal window, I can simply type the variable name <code>fileText</code> and get the file content printed out.</li> <li>Encoding detection of files: Bottom right corner of Notepad++ for first check, online tool for double check: <a href="https://nlp.fi.muni.cz/projects/chared/" rel="nofollow">https://nlp.fi.muni.cz/projects/chared/</a></li> <li>The output files <code>outputAnsi.txt</code> and <code>outputUtf.txt</code> do not exist at the start of the test. They are created at the very moment that I issue the <code>open(..)</code> command with the <code>'w'</code> option.</li> </ul> <p><strong>6. The actual files (for completeness):</strong></p> <p>I got several comments encouraging me to share the actual files on which I'm doing this test. Those files were quite large, so I've trimmed them down and re-did the tests. Results are similar. Here are the files (PS: of course, my files contain source code, what else?):</p> <p><strong>myAnsi.txt</strong></p> <pre><code>/* ****************************************************************************** ** ** File : LinkerScript.ld ** ** Author : Auto-generated by Ac6 System Workbench ** ** Abstract : Linker script for STM32F746NGHx Device from STM32F7 series ** ** Target : STMicroelectronics STM32 ** ** Distribution: The file is distributed “as is,” without any warranty ** of any kind. ** ***************************************************************************** ** @attention ** ** &lt;h2&gt;&lt;center&gt;&amp;copy; COPYRIGHT(c) 2014 Ac6&lt;/center&gt;&lt;/h2&gt; ** ***************************************************************************** */ /* Entry Point */ /*ENTRY(Reset_Handler)*/ ENTRY(Default_Handler) /* Highest address of the user mode stack */ _estack = 0x20050000; /* end of RAM */ _Min_Heap_Size = 0; /* required amount of heap */ _Min_Stack_Size = 0x400; /* required amount of stack */ /* Memories definition */ MEMORY { RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 320K ROM (rx) : ORIGIN = 0x8000000, LENGTH = 1024K } </code></pre> <p>The print statement of the <code>fileText</code> variable leads to the following exception:</p> <pre><code>&gt;&gt;&gt; print(fileText) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Anaconda3\lib\encodings\cp850.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u201c' in position 357: character maps to &lt;undefined&gt; </code></pre> <p>But just typing the name of the variable prints out the contents without problems:</p> <pre><code>&gt;&gt;&gt; fileText ### contents of the file are printed out :-) ### </code></pre> <p><strong>myUtf.txt</strong></p> <pre><code>/*--------------------------------------------------------------------------------------------------------------------*/ /* _ _ _ */ /* / -,- \ __ _ _ */ /* // | \\ / __\ | ___ ___| | __ _ _ */ /* | 0--,| / / | |/ _ \ / __| |/ / __ ___ _ _ __| |_ __ _ _ _| |_ ___ */ /* \\ // / /___| | (_) | (__| &lt; / _/ _ \ ' \(_-&lt; _/ _` | ' \ _(_-&lt; */ /* \_-_-_/ \____/|_|\___/ \___|_|\_\ \__\___/_||_/__/\__\__,_|_||_\__/__/ */ /*--------------------------------------------------------------------------------------------------------------------*/ #include "clock_constants.h" #include "../CMSIS/stm32f7xx.h" #include "stm32f7xx_hal_rcc.h" /*--------------------------------------------------------------------------------------------------*/ /* S y s t e m C o r e C l o c k i n i t i a l v a l u e */ /*--------------------------------------------------------------------------------------------------*/ /* */ /* This variable is updated in three ways: */ /* 1) by calling CMSIS function SystemCoreClockUpdate() */ /* 2) by calling HAL API function HAL_RCC_GetHCLKFreq() */ /* 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency */ /* Note: If you use this function to configure the system clock; then there */ /* is no need to call the 2 first functions listed above, since SystemCoreClock */ /* variable is updated automatically. */ /* */ uint32_t SystemCoreClock = 16000000; const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; /*--------------------------------------------------------------------------------------------------*/ /* S y s t e m C o r e C l o c k v a l u e u p d a t e */ /*--------------------------------------------------------------------------------------------------*/ /* */ /* @brief Update SystemCoreClock variable according to Clock Register Values. */ /* The SystemCoreClock variable contains the core clock (HCLK), it can */ /* be used by the user application to setup the SysTick timer or configure */ /* other parameters. */ /*--------------------------------------------------------------------------------------------------*/ </code></pre>
4
2016-08-29T19:24:34Z
39,214,402
<p>What you're hoping for is unfortunately impossible.</p> <p>Files do not contain encoding information and therefore it's impossible to read them as text without providing an encoding or assuming one.</p> <p>When doing things like <code>text = open("myfile.txt").read()</code> there is no one in the world that can tell for sure what encoding to use to translate the byte stream contained in the file into unicode points if the file contains characters beyond ASCII. Note that's even possible that a file doesn't contain text in a single encoding (just concatenate one encoded with <code>iso-8859-1</code> to another using <code>utf-8</code> instead).</p> <p>IIRC russian locale for example can contain any byte from <code>0x00</code> to <code>0xFF</code> an thus any file can be interpreted as containing russian locale text without decoding errors.</p> <p>There are libraries that try to solve this problem by statistical-based guessing, but they're just guessing, not telling for sure.</p> <p>Python 3 strings are unicode and therefore when reading a text file it applies a decoding using the "system default" unless provided a different one explicitly.</p> <p>If the system default is not the correct one but can decode all the 8-bit bytes contained you will just get wrong content silently. When writing back the string it will use the system default again thus rewriting the same bytes in output.</p> <p>This is what happened to you.</p> <p>If the system default encoding however is not able to decode the file content you will get a <code>UnicodeDecodeError</code> exception. Error detection depends on the file content and the encodings used.</p> <p>For example reading <code>Città</code> encoded in <code>iso8859-1</code> as if it were an <code>utf-8</code> content (default on my system) you get an error as the character <code>à</code> in <code>iso8859-1</code> is <code>0xe0</code> and that byte cannot be present in a valid <code>utf-8</code> file preceded by <code>t</code> (<code>0x74</code>).</p> <p>Doing the opposite however (i.e. reading <code>Città</code> encoded in <code>utf-8</code> as if it were <code>iso8859-1</code>) will apparently "work" but will wrongly give as text <code>Città</code> (i.e. an uppercase <code>A</code> with a tilde on top <code>0xc3</code> and a non-breaking space <code>0xA0</code>).</p>
0
2016-08-29T20:12:00Z
[ "python", "python-3.x", "unicode", "encoding", "utf-8" ]
Workaround to open COM port for serial communication on client-side (preferably in Python)
39,213,798
<h2>Goal</h2> <p>I have made a website using the Flask framework and am fairly comfortable with HTML, CSS, JS, Python. My goal is to connect an arduino to the <strong>client's</strong> PC's usb port and use serial.write() to send a number to it.</p> <h2>Notes</h2> <p>I have a working example of <a href="http://playground.arduino.cc/Interfacing/Python" rel="nofollow">interfacing with python</a> if arduino was connected to the server. </p> <pre><code>import serial ser = serial.Serial('COM4', 9600) ser.write('5') </code></pre> <p>Now I want to run these exact 3 lines on the client side. </p> <p><strong>Is this even doable?</strong> I have researched a lot and it seems that this is not doable due to security reasons? (I'm hoping somebody proves me wrong here.) That is why I'm looking for a workaround. But before that I must mention, I don't need any of the data (numbers) to come from the server. Once the webpage is loaded all serial communication that I need is on the client side.</p> <p><strong>Client side python</strong>: I have looked into writing python on the client side and read about skulpt and PyPyjs but am not sure how I could run the mentioned 3 lines with them on client side(neither seems to support <em>pyserial</em> needed for <em>import serial</em> or at least I have not had any luck finding documentation)</p> <p>I also looked into arduino documentation for <a href="http://playground.arduino.cc/Main/InterfacingWithSoftware" rel="nofollow">interfacing with software</a> but it seems that all the languages mentioned are server side. If you know of any possible direction languages that could help, I'd be happy to know and go learn them. I saw many forums mentioning Node.js but my understanding is that would also only do the job on the server side.</p> <p>I'd appreciate any help on where else/other topics I should look into. Thanks in advance.</p>
0
2016-08-29T19:31:54Z
39,213,984
<blockquote> <p>Is this even doable? I have researched a lot and it seems that this is not doable due to security reasons? </p> </blockquote> <p>You are correct. There is no ability for browsers to access a COM port. It doesn't matter what language or framework you pick, a browser isn't going to give you that access.</p> <p>You would need to make a standalone desktop application. You <em>can</em> use HTML and JavaScript to access serial ports, just not in a browser. Chrome <em>Apps</em> (which are actually going away) can do it, as well as an App that uses Electron.</p>
0
2016-08-29T19:44:49Z
[ "python", "arduino", "serial-port", "pyserial", "client-side-scripting" ]
random_state maintained when running script again?
39,213,911
<p>Suppose I have a program, called <code>script.py</code>:</p> <pre><code>import pandas as pd import numpy as np from sklearn.cross_validation import train_test_split if __name__ == "__main__": df = pd.DataFrame({"x": [1,2,3,4,5,6,6,5,6,3], "y": [1,1,0,0,0,0,1,0,0,1]}) train, test = train_test_split(df, test_size = 0.20, random_state = 100) </code></pre> <p>If I run this script from my command line once:</p> <pre><code>H:\&gt;python script.py </code></pre> <p>How can I ensure that the <code>train</code> and <code>test</code> dataframes in subsequent runs (i.e. when I run <code>script.py</code> again) are identical to the <code>train</code> and <code>test</code> dataframes from previous iterations? I know the <code>random_state</code> works if you don't leave the console, but would the equality of these <code>train</code> and <code>test</code> sets be preserved if I came back tomorrow, turned my PC back on, and re-ran <code>script.py</code>?</p> <p>I am testing the accuracies of different machine learning algorithms, all stored in different scripts, which is why I want to make sure the train and test sets are identical across scripts. </p>
0
2016-08-29T19:39:40Z
39,214,159
<p>Random state how nothing to do with when you run your code. The whole concept of specifing random state is to have <strong>exactly the same results every time you run this code with the same parameters</strong>. So as long as you do not change df, test_size and random_state, this function will always return the same values, no matter how many days pass. It might, however, change if you update the underlying library.</p>
1
2016-08-29T19:55:39Z
[ "python", "random", "scikit-learn" ]
Dynamically link a Span and a Slider in a python bokeh plot
39,213,949
<p>I am trying to create plots in python using bokeh that allow dynamic visualization of data in bins. It's worth knowing that I am relatively new to python, very new to bokeh, and I know ZERO javascript. I have consulted this:</p> <p><a href="http://stackoverflow.com/questions/38032737/link-a-span-or-cursor-in-between-plots-with-bokeh-in-python">Link a Span or Cursor in between plots with Bokeh in Python</a></p> <p>and this:</p> <p><a href="http://bokeh.pydata.org/en/latest/docs/user_guide/interaction/callbacks.html" rel="nofollow">http://bokeh.pydata.org/en/latest/docs/user_guide/interaction/callbacks.html</a></p> <p>but am having trouble implementing the necessary parts of each. Here is my code prior to adding the requested capabilities:</p> <pre><code>from bokeh.layouts import column, widgetbox from bokeh.models.widgets import Slider from bokeh.models import Span, CustomJS output_file('Raw_Spectra_and_Spillover_Data.html') # widgets for bin setup Pix1_LowLow = Slider(start = self.StartDAC, end = self.EndDAC, value = 129, step = 1, title = 'Pixel-1 - Low Bin - Low Thresh') Pix1_LowHigh = Slider(start = self.StartDAC, end = self.EndDAC, value = 204, step = 1, title = 'Pixel-1 - Low Bin - High Thresh') Pix1_HighLow = Slider(start = self.StartDAC, end = self.EndDAC, value = 218, step = 1, title = 'Pixel-1 - High Bin - Low Thresh') Pix1_HighHigh = Slider(start = self.StartDAC, end = self.EndDAC, value = 500, step = 1, title = 'Pixel-1 - High Bin - High Thresh') plot1spect = figure(width=700, height=250, title='pixel-1 Spectrum') plot1spect.line(self.SpectDACvals1[0], self.SpectrumData1[0], line_width=2) plot1spect_LowLowSpan = Span(location=Pix1_LowLow.value, dimension = 'height') plot1spect_LowHighSpan = Span(location=Pix1_LowHigh.value, dimension = 'height') plot1spect_HighLowSpan = Span(location=Pix1_HighLow.value, dimension = 'height') plot1spect_HighHighSpan = Span(location=Pix1_HighHigh.value, dimension = 'height') plot1spect.renderers.extend([plot1spect_LowLowSpan, plot1spect_LowHighSpan, plot1spect_HighLowSpan, plot1spect_HighHighSpan]) plot1spill = figure(width=700, height=250, title='pixel-1 Spillover') plot1spill.line(self.SpillDACvals1[0], self.SpillData1[0], line_width=2) plot1spill_LowLowSpan = Span(location=Pix1_LowLow.value, dimension = 'height') plot1spill_LowHighSpan = Span(location=Pix1_LowHigh.value, dimension = 'height') plot1spill_HighLowSpan = Span(location=Pix1_HighLow.value, dimension = 'height') plot1spill_HighHighSpan = Span(location=Pix1_HighHigh.value, dimension = 'height') plot1spill.renderers.extend([plot1spill_LowLowSpan, plot1spill_LowHighSpan, plot1spill_HighLowSpan, plot1spill_HighHighSpan]) show(row(plot1spect,plot1spill, widgetbox(Pix1_LowLow, Pix1_LowHigh, Pix1_HighLow, Pix1_HighHigh))) </code></pre> <p>This code gives me this:</p> <p><img src="http://i.stack.imgur.com/dGEbT.png" alt="Bokeh plot of code above."></p> <p>If someone can show me how get <code>Pix1_LowLow</code> slider to dynamically control the location of <code>plot1spect_LowLowSpan</code>, then I can extend the technique to the other sliders and spans. Many thanks in advance!</p> <p>python 3.5.2 - bokeh 12.0</p>
3
2016-08-29T19:42:00Z
39,235,127
<p>Here is a minimal complete example. Note that the recommended way to add annotations like <code>Span</code> is with <code>plot.add_layout</code> as shown below:</p> <pre><code>from bokeh.layouts import row, widgetbox from bokeh.models import Slider, Span, CustomJS from bokeh.plotting import figure, output_file, show slider = Slider(start=0, end=10, value=3, step=0.1, title='Slider') plot = figure(width=700, height=250, x_range=(0,10), y_range=(-1, 1)) span = Span(location=slider.value, dimension='height') plot.add_layout(span) slider.callback = CustomJS(args=dict(span=span, slider=slider), code=""" span.location = slider.value """) output_file('span_slider.html') show(row(plot, widgetbox(slider))) </code></pre>
2
2016-08-30T18:57:04Z
[ "python", "bokeh" ]
Dynamically link a Span and a Slider in a python bokeh plot
39,213,949
<p>I am trying to create plots in python using bokeh that allow dynamic visualization of data in bins. It's worth knowing that I am relatively new to python, very new to bokeh, and I know ZERO javascript. I have consulted this:</p> <p><a href="http://stackoverflow.com/questions/38032737/link-a-span-or-cursor-in-between-plots-with-bokeh-in-python">Link a Span or Cursor in between plots with Bokeh in Python</a></p> <p>and this:</p> <p><a href="http://bokeh.pydata.org/en/latest/docs/user_guide/interaction/callbacks.html" rel="nofollow">http://bokeh.pydata.org/en/latest/docs/user_guide/interaction/callbacks.html</a></p> <p>but am having trouble implementing the necessary parts of each. Here is my code prior to adding the requested capabilities:</p> <pre><code>from bokeh.layouts import column, widgetbox from bokeh.models.widgets import Slider from bokeh.models import Span, CustomJS output_file('Raw_Spectra_and_Spillover_Data.html') # widgets for bin setup Pix1_LowLow = Slider(start = self.StartDAC, end = self.EndDAC, value = 129, step = 1, title = 'Pixel-1 - Low Bin - Low Thresh') Pix1_LowHigh = Slider(start = self.StartDAC, end = self.EndDAC, value = 204, step = 1, title = 'Pixel-1 - Low Bin - High Thresh') Pix1_HighLow = Slider(start = self.StartDAC, end = self.EndDAC, value = 218, step = 1, title = 'Pixel-1 - High Bin - Low Thresh') Pix1_HighHigh = Slider(start = self.StartDAC, end = self.EndDAC, value = 500, step = 1, title = 'Pixel-1 - High Bin - High Thresh') plot1spect = figure(width=700, height=250, title='pixel-1 Spectrum') plot1spect.line(self.SpectDACvals1[0], self.SpectrumData1[0], line_width=2) plot1spect_LowLowSpan = Span(location=Pix1_LowLow.value, dimension = 'height') plot1spect_LowHighSpan = Span(location=Pix1_LowHigh.value, dimension = 'height') plot1spect_HighLowSpan = Span(location=Pix1_HighLow.value, dimension = 'height') plot1spect_HighHighSpan = Span(location=Pix1_HighHigh.value, dimension = 'height') plot1spect.renderers.extend([plot1spect_LowLowSpan, plot1spect_LowHighSpan, plot1spect_HighLowSpan, plot1spect_HighHighSpan]) plot1spill = figure(width=700, height=250, title='pixel-1 Spillover') plot1spill.line(self.SpillDACvals1[0], self.SpillData1[0], line_width=2) plot1spill_LowLowSpan = Span(location=Pix1_LowLow.value, dimension = 'height') plot1spill_LowHighSpan = Span(location=Pix1_LowHigh.value, dimension = 'height') plot1spill_HighLowSpan = Span(location=Pix1_HighLow.value, dimension = 'height') plot1spill_HighHighSpan = Span(location=Pix1_HighHigh.value, dimension = 'height') plot1spill.renderers.extend([plot1spill_LowLowSpan, plot1spill_LowHighSpan, plot1spill_HighLowSpan, plot1spill_HighHighSpan]) show(row(plot1spect,plot1spill, widgetbox(Pix1_LowLow, Pix1_LowHigh, Pix1_HighLow, Pix1_HighHigh))) </code></pre> <p>This code gives me this:</p> <p><img src="http://i.stack.imgur.com/dGEbT.png" alt="Bokeh plot of code above."></p> <p>If someone can show me how get <code>Pix1_LowLow</code> slider to dynamically control the location of <code>plot1spect_LowLowSpan</code>, then I can extend the technique to the other sliders and spans. Many thanks in advance!</p> <p>python 3.5.2 - bokeh 12.0</p>
3
2016-08-29T19:42:00Z
39,360,644
<p>Thanks to @bigreddot for providing the answer. This is the code that implemented my solution specifically... Now how to do this programmatically for 128 data files... hmmmm..</p> <pre><code> from bokeh.layouts import row, widgetbox from bokeh.models import Span, CustomJS, Slider output_file('Raw_Spectra_and_Spillover_Data.html') # widgets for bin setup Pix1_LowLow = Slider(start = self.StartDAC, end = self.EndDAC, value = 129, step = 1, title = 'Pixel-1 - Low Bin - Low Thresh') Pix1_LowHigh = Slider(start = self.StartDAC, end = self.EndDAC, value = 204, step = 1, title = 'Pixel-1 - Low Bin - High Thresh') Pix1_HighLow = Slider(start = self.StartDAC, end = self.EndDAC, value = 218, step = 1, title = 'Pixel-1 - High Bin - Low Thresh') Pix1_HighHigh = Slider(start = self.StartDAC, end = self.EndDAC, value = 500, step = 1, title = 'Pixel-1 - High Bin - High Thresh') plot1spect = figure(width=700, height=250, title='pixel-1 Spectrum') plot1spect.line(self.SpectDACvals1[0], self.SpectrumData1[0], line_width=2) plot1spect_LowLowSpan = Span(location=Pix1_LowLow.value, dimension = 'height') plot1spect.add_layout(plot1spect_LowLowSpan) plot1spect_LowHighSpan = Span(location=Pix1_LowHigh.value, dimension = 'height') plot1spect.add_layout(plot1spect_LowHighSpan) plot1spect_HighLowSpan = Span(location=Pix1_HighLow.value, dimension = 'height') plot1spect.add_layout(plot1spect_HighLowSpan) plot1spect_HighHighSpan = Span(location=Pix1_HighHigh.value, dimension = 'height') plot1spect.add_layout(plot1spect_HighHighSpan) #plot1spect.renderers.extend([plot1spect_LowLowSpan, plot1spect_LowHighSpan, plot1spect_HighLowSpan, plot1spect_HighHighSpan]) plot1spill = figure(width=700, height=250, title='pixel-1 Spillover') plot1spill.line(self.SpillDACvals1[0], self.SpillData1[0], line_width=2) plot1spill_LowLowSpan = Span(location=Pix1_LowLow.value, dimension = 'height') plot1spill.add_layout(plot1spill_LowLowSpan) plot1spill_LowHighSpan = Span(location=Pix1_LowHigh.value, dimension = 'height') plot1spill.add_layout(plot1spill_LowHighSpan) plot1spill_HighLowSpan = Span(location=Pix1_HighLow.value, dimension = 'height') plot1spill.add_layout(plot1spill_HighLowSpan) plot1spill_HighHighSpan = Span(location=Pix1_HighHigh.value, dimension = 'height') plot1spill.add_layout(plot1spill_HighHighSpan) #plot1spill.renderers.extend([plot1spill_LowLowSpan, plot1spill_LowHighSpan, plot1spill_HighLowSpan, plot1spill_HighHighSpan]) Pix1_LowLow.callback = CustomJS(args=dict(span1 = plot1spect_LowLowSpan, span2 = plot1spill_LowLowSpan, slider = Pix1_LowLow), code = """span1.location = slider.value; span2.location = slider.value""") Pix1_LowHigh.callback = CustomJS(args=dict(span1 = plot1spect_LowHighSpan, span2 = plot1spill_LowHighSpan, slider = Pix1_LowHigh), code = """span1.location = slider.value; span2.location = slider.value""") Pix1_HighLow.callback = CustomJS(args=dict(span1 = plot1spect_HighLowSpan, span2 = plot1spill_HighLowSpan, slider = Pix1_HighLow), code = """span1.location = slider.value; span2.location = slider.value""") Pix1_HighHigh.callback = CustomJS(args=dict(span1 = plot1spect_HighHighSpan, span2 = plot1spill_HighHighSpan, slider = Pix1_HighHigh), code = """span1.location = slider.value; span2.location = slider.value""") </code></pre> <p>Here is a repeat of the plots, but now each slider manipulates the respective span in both plots...</p> <p><a href="http://i.stack.imgur.com/Wp9aU.png" rel="nofollow"><img src="http://i.stack.imgur.com/Wp9aU.png" alt="enter image description here"></a></p>
0
2016-09-07T03:08:19Z
[ "python", "bokeh" ]
python kafka: how to make each msg consumed only once by group from begining
39,214,046
<p>I am using <a href="http://kafka-python.readthedocs.io/en/master/apidoc/KafkaConsumer.html" rel="nofollow">Kafka consumer</a> here (version 1.3.1). </p> <p>What I am going to acheive: </p> <ul> <li><p>There are 10 partitions. each partition begins with offset 0. </p></li> <li><p>There is a group of consumers (1,2,3, eg). </p></li> <li><p>Sometimes, one consumer is down or is up. </p></li> <li><p>So, the group members may change. But I want each message in each partition should be consumed by the group only once (1 OR 2 OR 3).</p></li> </ul> <p>My codes are:</p> <pre><code>consumer = KafkaConsumer('my_topic', bootstrap_servers=['ip:9092'], auto_offset_reset='earliest', max_partition_fetch_bytes=131072, group_id='writer.test') </code></pre> <p>Is the above configuration enough? Any comments welcomed. Thanks</p> <p><strong>UPDATE</strong></p> <p><strong>I tried the following codes. Each time in partition 760, each message maybe consumed twice by two consumers in one group. Why? Something wrong?</strong></p> <pre><code>def test(): #PULL FROM KAFKA consumer = KafkaConsumer( 'topic', bootstrap_servers=[ip], auto_offset_reset='latest', max_partition_fetch_bytes=131072, auto_commit_interval_ms=500, group_id='writer2.test') print consumer.poll() for i in range(10000): msg = next(consumer) if str(msg[1])=='670': print 'partition= %s, offset= %s' % (msg[1], msg[2]) consumer.unsubscribe() if __name__ == "__main__": for i in range(10): import time time.sleep(5) test() </code></pre> <p>Output 1:</p> <pre><code>{} partition= 670, offset= 224 partition= 670, offset= 225 partition= 670, offset= 226 partition= 670, offset= 227 partition= 670, offset= 228 partition= 670, offset= 229 partition= 670, offset= 230 partition= 670, offset= 231 partition= 670, offset= 232 partition= 670, offset= 233 partition= 670, offset= 234 partition= 670, offset= 235 partition= 670, offset= 236 partition= 670, offset= 237 partition= 670, offset= 238 partition= 670, offset= 239 partition= 670, offset= 240 {} partition= 670, offset= 241 partition= 670, offset= 242 partition= 670, offset= 243 partition= 670, offset= 244 partition= 670, offset= 245 partition= 670, offset= 246 partition= 670, offset= 247 partition= 670, offset= 248 partition= 670, offset= 249 partition= 670, offset= 250 partition= 670, offset= 251 partition= 670, offset= 252 partition= 670, offset= 253 partition= 670, offset= 254 partition= 670, offset= 255 partition= 670, offset= 256 partition= 670, offset= 257 partition= 670, offset= 258 partition= 670, offset= 259 {} {} partition= 670, offset= 241 partition= 670, offset= 242 partition= 670, offset= 243 partition= 670, offset= 244 partition= 670, offset= 245 partition= 670, offset= 246 partition= 670, offset= 247 partition= 670, offset= 248 partition= 670, offset= 249 partition= 670, offset= 250 partition= 670, offset= 251 partition= 670, offset= 252 partition= 670, offset= 253 partition= 670, offset= 254 partition= 670, offset= 255 partition= 670, offset= 256 partition= 670, offset= 257 partition= 670, offset= 258 partition= 670, offset= 259 {} partition= 670, offset= 241 partition= 670, offset= 242 partition= 670, offset= 243 partition= 670, offset= 244 partition= 670, offset= 245 partition= 670, offset= 246 partition= 670, offset= 247 partition= 670, offset= 248 partition= 670, offset= 249 partition= 670, offset= 250 partition= 670, offset= 251 partition= 670, offset= 252 partition= 670, offset= 253 partition= 670, offset= 254 partition= 670, offset= 255 partition= 670, offset= 256 partition= 670, offset= 257 partition= 670, offset= 258 partition= 670, offset= 259 {} partition= 670, offset= 241 partition= 670, offset= 242 partition= 670, offset= 243 partition= 670, offset= 244 partition= 670, offset= 245 partition= 670, offset= 246 partition= 670, offset= 247 partition= 670, offset= 248 partition= 670, offset= 249 partition= 670, offset= 250 partition= 670, offset= 251 partition= 670, offset= 252 partition= 670, offset= 253 partition= 670, offset= 254 partition= 670, offset= 255 partition= 670, offset= 256 partition= 670, offset= 257 partition= 670, offset= 258 partition= 670, offset= 259 {} partition= 670, offset= 241 partition= 670, offset= 242 partition= 670, offset= 243 partition= 670, offset= 244 partition= 670, offset= 245 partition= 670, offset= 246 partition= 670, offset= 247 partition= 670, offset= 248 partition= 670, offset= 249 partition= 670, offset= 250 partition= 670, offset= 251 partition= 670, offset= 252 partition= 670, offset= 253 partition= 670, offset= 254 partition= 670, offset= 255 partition= 670, offset= 256 partition= 670, offset= 257 partition= 670, offset= 258 partition= 670, offset= 259 {} partition= 670, offset= 241 partition= 670, offset= 242 partition= 670, offset= 243 partition= 670, offset= 244 partition= 670, offset= 245 partition= 670, offset= 246 partition= 670, offset= 247 partition= 670, offset= 248 partition= 670, offset= 249 partition= 670, offset= 250 partition= 670, offset= 251 partition= 670, offset= 252 partition= 670, offset= 253 partition= 670, offset= 254 partition= 670, offset= 255 partition= 670, offset= 256 partition= 670, offset= 257 partition= 670, offset= 258 partition= 670, offset= 259 {} {} partition= 670, offset= 241 partition= 670, offset= 242 partition= 670, offset= 243 partition= 670, offset= 244 partition= 670, offset= 245 partition= 670, offset= 246 partition= 670, offset= 247 partition= 670, offset= 248 partition= 670, offset= 249 partition= 670, offset= 250 partition= 670, offset= 251 partition= 670, offset= 252 partition= 670, offset= 253 partition= 670, offset= 254 partition= 670, offset= 255 partition= 670, offset= 256 partition= 670, offset= 257 partition= 670, offset= 258 partition= 670, offset= 259 </code></pre> <p>Run the same file in another window, output:</p> <pre><code>{} partition= 670, offset= 241 partition= 670, offset= 242 partition= 670, offset= 243 partition= 670, offset= 244 partition= 670, offset= 245 partition= 670, offset= 246 partition= 670, offset= 247 partition= 670, offset= 248 partition= 670, offset= 249 partition= 670, offset= 250 partition= 670, offset= 251 partition= 670, offset= 252 partition= 670, offset= 253 partition= 670, offset= 254 partition= 670, offset= 255 partition= 670, offset= 256 partition= 670, offset= 257 partition= 670, offset= 258 partition= 670, offset= 259 {} partition= 670, offset= 241 partition= 670, offset= 242 partition= 670, offset= 243 partition= 670, offset= 244 partition= 670, offset= 245 partition= 670, offset= 246 partition= 670, offset= 247 partition= 670, offset= 248 partition= 670, offset= 249 partition= 670, offset= 250 partition= 670, offset= 251 partition= 670, offset= 252 partition= 670, offset= 253 partition= 670, offset= 254 partition= 670, offset= 255 partition= 670, offset= 256 partition= 670, offset= 257 partition= 670, offset= 258 partition= 670, offset= 259 {} partition= 670, offset= 241 partition= 670, offset= 242 partition= 670, offset= 243 partition= 670, offset= 244 partition= 670, offset= 245 partition= 670, offset= 246 partition= 670, offset= 247 partition= 670, offset= 248 partition= 670, offset= 249 partition= 670, offset= 250 partition= 670, offset= 251 partition= 670, offset= 252 partition= 670, offset= 253 partition= 670, offset= 254 partition= 670, offset= 255 partition= 670, offset= 256 partition= 670, offset= 257 partition= 670, offset= 258 partition= 670, offset= 259 {} partition= 670, offset= 241 partition= 670, offset= 242 partition= 670, offset= 243 partition= 670, offset= 244 partition= 670, offset= 245 partition= 670, offset= 246 partition= 670, offset= 247 partition= 670, offset= 248 partition= 670, offset= 249 partition= 670, offset= 250 partition= 670, offset= 251 partition= 670, offset= 252 partition= 670, offset= 253 partition= 670, offset= 254 partition= 670, offset= 255 partition= 670, offset= 256 partition= 670, offset= 257 partition= 670, offset= 258 partition= 670, offset= 259 {} partition= 670, offset= 241 partition= 670, offset= 242 partition= 670, offset= 243 partition= 670, offset= 244 partition= 670, offset= 245 partition= 670, offset= 246 partition= 670, offset= 247 partition= 670, offset= 248 partition= 670, offset= 249 partition= 670, offset= 250 partition= 670, offset= 251 partition= 670, offset= 252 partition= 670, offset= 253 partition= 670, offset= 254 partition= 670, offset= 255 partition= 670, offset= 256 partition= 670, offset= 257 partition= 670, offset= 258 partition= 670, offset= 259 {} partition= 670, offset= 241 partition= 670, offset= 242 partition= 670, offset= 243 partition= 670, offset= 244 partition= 670, offset= 245 partition= 670, offset= 246 partition= 670, offset= 247 partition= 670, offset= 248 partition= 670, offset= 249 partition= 670, offset= 250 partition= 670, offset= 251 partition= 670, offset= 252 partition= 670, offset= 253 partition= 670, offset= 254 partition= 670, offset= 255 partition= 670, offset= 256 partition= 670, offset= 257 partition= 670, offset= 258 partition= 670, offset= 259 {} {} partition= 670, offset= 241 partition= 670, offset= 242 partition= 670, offset= 243 partition= 670, offset= 244 partition= 670, offset= 245 partition= 670, offset= 246 partition= 670, offset= 247 partition= 670, offset= 248 partition= 670, offset= 249 partition= 670, offset= 250 partition= 670, offset= 251 partition= 670, offset= 252 partition= 670, offset= 253 partition= 670, offset= 254 partition= 670, offset= 255 partition= 670, offset= 256 partition= 670, offset= 257 partition= 670, offset= 258 partition= 670, offset= 259 {} partition= 670, offset= 241 partition= 670, offset= 242 partition= 670, offset= 243 partition= 670, offset= 244 partition= 670, offset= 245 partition= 670, offset= 246 partition= 670, offset= 247 partition= 670, offset= 248 partition= 670, offset= 249 partition= 670, offset= 250 partition= 670, offset= 251 partition= 670, offset= 252 partition= 670, offset= 253 partition= 670, offset= 254 partition= 670, offset= 255 partition= 670, offset= 256 partition= 670, offset= 257 partition= 670, offset= 258 partition= 670, offset= 259 {} partition= 670, offset= 241 partition= 670, offset= 242 partition= 670, offset= 243 partition= 670, offset= 244 partition= 670, offset= 245 partition= 670, offset= 246 partition= 670, offset= 247 partition= 670, offset= 248 partition= 670, offset= 249 partition= 670, offset= 250 partition= 670, offset= 251 partition= 670, offset= 252 partition= 670, offset= 253 partition= 670, offset= 254 partition= 670, offset= 255 partition= 670, offset= 256 partition= 670, offset= 257 partition= 670, offset= 258 partition= 670, offset= 259 </code></pre>
0
2016-08-29T19:47:58Z
39,247,980
<p>If you use consumer groups, Kafka provides at-least-once delivery guarantees, thus, on failure of a consumer an re-assignment of those consumer's partitions some messages might be delivered a second time.</p> <p>If you want to make sure, no message is processed twice, you can switch your pattern to at-most-once delivery guarantees. However, for this, you might loose some messages (ie, never processed) in case of failure.</p> <p>To enable at-most-once, you need to disable auto-commit, and commit manually directy after <code>poll</code>, ie, before you start processing the messages received via <code>poll</code>.</p> <p>See <a href="http://docs.confluent.io/3.0.0/clients/consumer.html#detailed-examples" rel="nofollow">http://docs.confluent.io/3.0.0/clients/consumer.html#detailed-examples</a> for more details (even if the examples are not in Python, the general pattern is the same).</p>
0
2016-08-31T11:08:51Z
[ "python", "apache-kafka", "kafka-consumer-api", "python-kafka" ]
wxPython how to get row ID of list item that is double clicked
39,214,079
<p>I am working on a wxPython app in which I have used a wx.ListCtrl with 12 columns. The control gets populated with some values upon clicking a button... let's say Name, Age, Class, House... etc.</p> <p>Now I want to create a double click event which upon double cliking a list item should pop-up a msgbox with the Name value, however I am unable to get the row number or ID of the row item that is being double clicked...</p> <p>here is my Code:-</p> <pre><code>self.subList.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.DblClickOptions) def DblClickOptions(self, extra): itm = self.subList.GetItem(itemId='???', col=1) itm_text = itm.GetText() ctypes.windll.user32.MessageBoxA(0, itm_text, "title", 1) </code></pre> <p>in the code above I need to get the row number of the list item that is double clicked in place of '???'</p> <p>Please someone help me with this.</p> <p>Regards, Premanshu</p>
0
2016-08-29T19:50:00Z
39,214,158
<p><a href="http://xoomer.virgilio.it/infinity77/wxPython/Events/wx.ListEvent.html#methods-summary" rel="nofollow">http://xoomer.virgilio.it/infinity77/wxPython/Events/wx.ListEvent.html#methods-summary</a></p> <p>(typically the variable you named <code>extra</code> is named <code>event</code> or <code>evt</code> ...)</p> <p><code>extra.GetIndex()</code> would be the row id</p> <p><code>extra.GetText()</code> would be the row text</p> <p>etc</p>
0
2016-08-29T19:55:37Z
[ "python", "wxpython", "listctrl" ]
django and internet explorer session loss
39,214,117
<p>I have been trying to find a fix for this all day but no luck.</p> <p>I have a Django 1.9.4 website that works for all major browsers except for IE.</p> <p>I am using eclipse to run the Django site locally for testing.</p> <p>When I log into my site with IE-11 on the local server, it works just fine.</p> <p>When I pull the site onto a production unit (different IP address, over a network), IE seems to lose the session and I am just in an infinite loop on the login page.</p> <p>Below are the two functions that I believe are in context to this issue. "return redirect("myapp:homepage")" goes to a view that is decorated with "@checkLogin"</p> <p>applylogin gets run and when monitoring the network with IE dev tools under cookies I see the following</p> <p>Direction Key Value Expires Domain Path Secure HTTP only</p> <p>Received sessionid pk5svspepe9xk3og6ctnrwqrc56ukgrh Mon, 29-Aug-2016 15:39:03 GMT / No Yes</p> <p>so it appears to have received a session id.</p> <pre><code>@requires_csrf_token def applylogin(request): newUsername = "" password = "" err_username = False err_pass=False if(request.POST.has_key('username')): newUsername=request.POST['username'] if(request.POST.has_key('password')): password=request.POST['password'] try: user = User.objects.get(username=newUsername) if(user.check_password(password)): request.session['login'] = newUsername request.session['userid'] = user.id request.session['useraccess'] = user.access if user.access &gt;= 255: request.session['admin'] = True else: request.session['admin'] = False return redirect("myapp:homepage") else: err_pass=True except User.DoesNotExist as e: err_username=True logger.exception(e) except Exception as e: logger.exception(e) build = getBuildType() return render(request, "Redacted") def checkLogin(fn): def wrapped(request, *param, **dparam): str_redirect = "" str_loc = dparam.get('location', "xxxx") if(str_loc == "xxxx"): str_redirect = "xxxx:landingpage" else: str_redirect = str_loc+":login" loginname = request.session.get("login", "") try: if loginname == "": return redirect(str_redirect) User.objects.get(username=loginname) except User.DoesNotExist: return redirect(str_redirect) return fn(request, *param, **dparam) return wrapped </code></pre> <p>Also, I am unsure if this has anything to do with the issue but I get this message in my log file only when accessing the site with IE</p> <pre><code>&gt; Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/gunicorn/workers/sync.py", line 66, in run_for_one self.accept(listener) File "/usr/local/lib/python2.7/dist-packages/gunicorn/workers/sync.py", line 27, in accept client, addr = listener.accept() File "/usr/lib/python2.7/socket.py", line 202, in accept sock, addr = self._sock.accept() error: [Errno 11] Resource temporarily unavailable </code></pre> <p>I am at a loss right now. I do not know if it is a Django issue or purely an IE issue.</p> <p>p.s. I have tried the p3p stuff but that didn't seem to work.</p>
1
2016-08-29T19:52:17Z
39,216,058
<p>The problem lies in the timezone difference and the cookie expiry.</p> <p>To test it, I set the SESSION_COOKIE_AGE = 37200 (2hours + 30000seconds) and IE loaded the site just fine.</p> <p>Interesting that chrome and firefox do not have an issue with this.</p>
0
2016-08-29T22:20:30Z
[ "python", "django", "internet-explorer", "session", "gunicorn" ]
Data Conversion Error while applying a function to each row in pandas Python
39,214,164
<p>I have a data frame in pandas in python which resembles something like this - </p> <pre><code> contest_login_count contest_participation_count ipn_ratio 0 1 1 0.000000 1 3 3 0.083333 2 3 3 0.000000 3 3 3 0.066667 4 5 13 0.102804 5 2 3 0.407407 6 1 3 0.000000 7 1 2 0.000000 8 53 91 0.264151 9 1 2 0.000000 </code></pre> <p>Now I want to apply a function to each row of this dataframe The function is written as this - </p> <pre><code>def findCluster(clusterModel,data): return clusterModel.predict(data) </code></pre> <p>I apply this function to each row in this manner - </p> <pre><code>df_fil.apply(lambda x : findCluster(cluster_all,x.reshape(1,-1)),axis=1) </code></pre> <p>When I run this code, I get a warning saying - </p> <blockquote> <p>DataConversionWarning: Data with input dtype object was converted to float64.</p> <p>warnings.warn(msg, DataConversionWarning)</p> </blockquote> <p>This warning is printed once for each row. Since, I have around 450K rows in my data frame, my computer hangs while printing all these warning messages that too on ipython notebook.</p> <p>But to test my function I created a dummy dataframe and tried applying the same function on that and it works well. Here is the code for that - </p> <pre><code>t = pd.DataFrame([[10.35,100.93,0.15],[10.35,100.93,0.15]]) t.apply(lambda x:findCluster(cluster_all,x.reshape(1,-1)),axis=1) </code></pre> <p>The output to this is - </p> <pre><code> 0 1 2 0 4 4 4 1 4 4 4 </code></pre> <p>Can anyone suggest what am I doing wrong or what can I change to make this error go away?</p>
1
2016-08-29T19:55:50Z
39,219,950
<p>I think there is problem <code>dtype</code> of some column is not <code>float</code>.</p> <p>You need cast it by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>astype</code></a>:</p> <pre><code>df['colname'] = df['colname'].astype(float) </code></pre>
1
2016-08-30T06:10:23Z
[ "python", "function", "pandas", "dataframe", "apply" ]
Python: Creating nested lists of floats using a for loop
39,214,206
<p>I am working with a list of points <code>[(1,2),(3,4),(5,6),(7,8)]</code>. I want to find the euclidean distance from each point to every other point in the list.</p> <p>I then need a new list created to represent each point in the original list, and in the new list I will add the distances relating to that point only.</p> <p>So far I have:</p> <pre><code>for i in mat_ary1: points_dist_i = [] for j in i: row = [] x2 = [u[0] for u in i] y2 = [u[1] for u in i] # Calculate the distance from point j to all others for a in x2: dist_x_1 = pow((a - j[0]),2) for b in y2: dist_y_1 = pow((b - j[1]),2) dist_xy_1 = float('{0:.2f}'.format((math.sqrt(dist_x_1 + dist_y_1)))) for item in j: if item not in row: row.append(dist_xy_1) else: continue points_dist_i.append(row) </code></pre> <p>Each <code>i</code> in <code>mat_ary1</code> represents a list of points. With the loops I am using I appear to repeating the same calculations.</p> <p>My input seems to be duplicating the rows:</p> <pre><code>[[6.32, 6.32], [6.32, 6.32], [0.0, 0.0], [0.0, 0.0]] [[11.4, 11.4], [11.4, 11.4], [0.0, 0.0], [0.0, 0.0]] [[16.49, 16.49], [16.49, 16.49], [0.0, 0.0], [0.0, 0.0]] [[14.32, 14.32], [14.32, 14.32], [0.0, 0.0], [0.0, 0.0]] [[13.0, 13.0], [13.0, 13.0], [0.0, 0.0], [0.0, 0.0]] [[11.66, 11.66], [11.66, 11.66], [0.0, 0.0], [0.0, 0.0]] </code></pre>
2
2016-08-29T19:58:25Z
39,214,305
<p>You can use the following nested list comprehension</p> <pre><code>&gt;&gt;&gt; import math &gt;&gt;&gt; [[math.hypot(point[0]-x, point[1]-y) for x,y in points] for point in points] [[0.0, 2.8284271247461903, 5.656854249492381, 8.48528137423857], [2.8284271247461903, 0.0, 2.8284271247461903, 5.656854249492381], [5.656854249492381, 2.8284271247461903, 0.0, 2.8284271247461903], [8.48528137423857, 5.656854249492381, 2.8284271247461903, 0.0]] </code></pre> <p>This essentially makes a matrix with the distance from one point to any other point, where the row and column indexes are the "from" and "to" points, in which case the matrix will also be symmetric about the diagonal, and the diagonal will be all zeros.</p>
3
2016-08-29T20:05:28Z
[ "python", "loops" ]
Python: Creating nested lists of floats using a for loop
39,214,206
<p>I am working with a list of points <code>[(1,2),(3,4),(5,6),(7,8)]</code>. I want to find the euclidean distance from each point to every other point in the list.</p> <p>I then need a new list created to represent each point in the original list, and in the new list I will add the distances relating to that point only.</p> <p>So far I have:</p> <pre><code>for i in mat_ary1: points_dist_i = [] for j in i: row = [] x2 = [u[0] for u in i] y2 = [u[1] for u in i] # Calculate the distance from point j to all others for a in x2: dist_x_1 = pow((a - j[0]),2) for b in y2: dist_y_1 = pow((b - j[1]),2) dist_xy_1 = float('{0:.2f}'.format((math.sqrt(dist_x_1 + dist_y_1)))) for item in j: if item not in row: row.append(dist_xy_1) else: continue points_dist_i.append(row) </code></pre> <p>Each <code>i</code> in <code>mat_ary1</code> represents a list of points. With the loops I am using I appear to repeating the same calculations.</p> <p>My input seems to be duplicating the rows:</p> <pre><code>[[6.32, 6.32], [6.32, 6.32], [0.0, 0.0], [0.0, 0.0]] [[11.4, 11.4], [11.4, 11.4], [0.0, 0.0], [0.0, 0.0]] [[16.49, 16.49], [16.49, 16.49], [0.0, 0.0], [0.0, 0.0]] [[14.32, 14.32], [14.32, 14.32], [0.0, 0.0], [0.0, 0.0]] [[13.0, 13.0], [13.0, 13.0], [0.0, 0.0], [0.0, 0.0]] [[11.66, 11.66], [11.66, 11.66], [0.0, 0.0], [0.0, 0.0]] </code></pre>
2
2016-08-29T19:58:25Z
39,214,442
<p>Scikit-learn has a function for this exact problem, and it will probably be the fastest implementation if your array is large.</p> <pre><code>&gt;&gt;&gt;&gt;from sklearn.metrics.pairwise import pairwise_distances &gt;&gt;&gt;&gt;pairwise_distances(mat_ary1) array([[ 0. , 2.82842712, 5.65685425, 8.48528137], [ 2.82842712, 0. , 2.82842712, 5.65685425], [ 5.65685425, 2.82842712, 0. , 2.82842712], [ 8.48528137, 5.65685425, 2.82842712, 0. ]]) </code></pre>
2
2016-08-29T20:13:52Z
[ "python", "loops" ]
download django 1.10 to python 3.5
39,214,247
<p>How do I download django for python 3.5? When I run my virtual environment and type:</p> <pre><code>pip install Django </code></pre> <p>I get:</p> <pre><code>Requirement already satisfied (use --upgrade to upgrade): django in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages </code></pre> <p>I noticed the problem when using PyCharm. PyCharm shows Django installed in Python 2.7, but not in 3.5. How do I pip install django into 3.5?</p> <p>My main python package is 2.7. My work uses 2.7, and is migrating towards 3.5. So I'll need both, and would like to keep 2.7 as the default. </p>
0
2016-08-29T20:01:39Z
39,214,813
<p>You created your virtualenv with Python 2.7. You should first create a virtualenv with Python 3.5</p> <pre><code>virtualenv -p &lt;path/to/python3.5&gt; &lt;path/to/new/virtualenv&gt; </code></pre> <p>Then activate this new virtualenv, and finally, run <code>pip install django</code> on the virtualenv with Python 3.5</p> <p>You can have as many virtual environments as you wish, but each virtualenv can only hold a single Python installation; if you don't specify a Python interpreter, the default one will be used to create the virtualenv (in your case, the default is 2.7)</p>
1
2016-08-29T20:38:54Z
[ "python", "django", "virtualenv" ]
download django 1.10 to python 3.5
39,214,247
<p>How do I download django for python 3.5? When I run my virtual environment and type:</p> <pre><code>pip install Django </code></pre> <p>I get:</p> <pre><code>Requirement already satisfied (use --upgrade to upgrade): django in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages </code></pre> <p>I noticed the problem when using PyCharm. PyCharm shows Django installed in Python 2.7, but not in 3.5. How do I pip install django into 3.5?</p> <p>My main python package is 2.7. My work uses 2.7, and is migrating towards 3.5. So I'll need both, and would like to keep 2.7 as the default. </p>
0
2016-08-29T20:01:39Z
39,220,706
<p>Try using:</p> <p>pip3 install Django or even pip3.5 install Django</p> <p>This is what I used, as pip alone picks up python2 pip. I have Django installed for both python2 and python3.</p>
0
2016-08-30T06:55:34Z
[ "python", "django", "virtualenv" ]
If we don't know the number of entries then how to stop a input() loop of while or for
39,214,263
<p>I tried to get input by bigger number entries but it says "index out of range"</p> <p>if we don't know the number of entries then how to stop a input() loop of while or for, in python: </p> <pre><code>while(): listMatch.append(input()) </code></pre> <p>Look what if I have:</p> <pre><code>Djokovic:Murray:2-6,6-7,7-6,6-3,6-1 Murray:Djokovic:6-3,4-6,6-4,6-3 Djokovic:Murray:6-0,7-6,6-7,6-3 Murray:Djokovic:6-4,6-4 Djokovic:Murray:2-6,6-2,6-0 Murray:Djokovic:6-3,4-6,6-3,6-4 Djokovic:Murray:7-6,4-6,7-6,2-6,6-2 Murray:Djokovic:7-5,7-5 Williams:Muguruza:3-6,6-3,6-3 </code></pre> <p>AND </p> <pre><code>Halep:Raonic:2-6,6-7,7-6,6-3,6-1 Kerber:Raonic:6-3,4-6,6-4,6-3 Raonic:Wawrinka:6-0,7-6,6-7,6-3 Wawrinka:Raonic:6-4,6-4 Halep:Raonic:2-6,6-2,6-0 Wawrinka:Raonic:6-3,4-6,6-3,6-4 Raonic:Wawrinka:7-6,4-6,7-6,2-6,6-2 Wawrinka:Kerber:7-5,7-5 Halep:Kerber:3-6,6-3,6-3 Halep:Wawrinka:0-6,0-6,6-0,6-0,7-5 Kerber:Wawrinka:6-3,4-6,7-6,0-6,7-5 </code></pre> <p>Here I don't know how many entries I want to enter. In above examples there are 9 and 11.</p>
-2
2016-08-29T20:03:01Z
39,214,355
<p>add a control loop that checks for input:</p> <pre><code>listMatch =[] while(True): input_value = input() if(input_value == '' or input_value == 'quit'): break listMatch.append(input_value) </code></pre> <p>if no text or quit is entered, loop will break</p>
0
2016-08-29T20:08:20Z
[ "python", "loops", "for-loop", "input", "while-loop" ]
If we don't know the number of entries then how to stop a input() loop of while or for
39,214,263
<p>I tried to get input by bigger number entries but it says "index out of range"</p> <p>if we don't know the number of entries then how to stop a input() loop of while or for, in python: </p> <pre><code>while(): listMatch.append(input()) </code></pre> <p>Look what if I have:</p> <pre><code>Djokovic:Murray:2-6,6-7,7-6,6-3,6-1 Murray:Djokovic:6-3,4-6,6-4,6-3 Djokovic:Murray:6-0,7-6,6-7,6-3 Murray:Djokovic:6-4,6-4 Djokovic:Murray:2-6,6-2,6-0 Murray:Djokovic:6-3,4-6,6-3,6-4 Djokovic:Murray:7-6,4-6,7-6,2-6,6-2 Murray:Djokovic:7-5,7-5 Williams:Muguruza:3-6,6-3,6-3 </code></pre> <p>AND </p> <pre><code>Halep:Raonic:2-6,6-7,7-6,6-3,6-1 Kerber:Raonic:6-3,4-6,6-4,6-3 Raonic:Wawrinka:6-0,7-6,6-7,6-3 Wawrinka:Raonic:6-4,6-4 Halep:Raonic:2-6,6-2,6-0 Wawrinka:Raonic:6-3,4-6,6-3,6-4 Raonic:Wawrinka:7-6,4-6,7-6,2-6,6-2 Wawrinka:Kerber:7-5,7-5 Halep:Kerber:3-6,6-3,6-3 Halep:Wawrinka:0-6,0-6,6-0,6-0,7-5 Kerber:Wawrinka:6-3,4-6,7-6,0-6,7-5 </code></pre> <p>Here I don't know how many entries I want to enter. In above examples there are 9 and 11.</p>
-2
2016-08-29T20:03:01Z
39,214,361
<p>This loop will stop as soon as you just press return (no string entered)</p> <pre><code>listMatch=[] while True: z=input() if z: listMatch.append(z) else: break </code></pre>
0
2016-08-29T20:08:28Z
[ "python", "loops", "for-loop", "input", "while-loop" ]
If we don't know the number of entries then how to stop a input() loop of while or for
39,214,263
<p>I tried to get input by bigger number entries but it says "index out of range"</p> <p>if we don't know the number of entries then how to stop a input() loop of while or for, in python: </p> <pre><code>while(): listMatch.append(input()) </code></pre> <p>Look what if I have:</p> <pre><code>Djokovic:Murray:2-6,6-7,7-6,6-3,6-1 Murray:Djokovic:6-3,4-6,6-4,6-3 Djokovic:Murray:6-0,7-6,6-7,6-3 Murray:Djokovic:6-4,6-4 Djokovic:Murray:2-6,6-2,6-0 Murray:Djokovic:6-3,4-6,6-3,6-4 Djokovic:Murray:7-6,4-6,7-6,2-6,6-2 Murray:Djokovic:7-5,7-5 Williams:Muguruza:3-6,6-3,6-3 </code></pre> <p>AND </p> <pre><code>Halep:Raonic:2-6,6-7,7-6,6-3,6-1 Kerber:Raonic:6-3,4-6,6-4,6-3 Raonic:Wawrinka:6-0,7-6,6-7,6-3 Wawrinka:Raonic:6-4,6-4 Halep:Raonic:2-6,6-2,6-0 Wawrinka:Raonic:6-3,4-6,6-3,6-4 Raonic:Wawrinka:7-6,4-6,7-6,2-6,6-2 Wawrinka:Kerber:7-5,7-5 Halep:Kerber:3-6,6-3,6-3 Halep:Wawrinka:0-6,0-6,6-0,6-0,7-5 Kerber:Wawrinka:6-3,4-6,7-6,0-6,7-5 </code></pre> <p>Here I don't know how many entries I want to enter. In above examples there are 9 and 11.</p>
-2
2016-08-29T20:03:01Z
39,214,379
<pre><code>listMatch = [] while True: # get the user's input stuff = input() # if they typed "quit", stop looping if stuff == 'quit': break # otherwise append their input to the list and keep on looping listMatch.append(stuff) </code></pre>
0
2016-08-29T20:10:00Z
[ "python", "loops", "for-loop", "input", "while-loop" ]
method within class is not callable within that class?
39,214,277
<p>If I have a file, foo.py with contents:</p> <pre><code>import pandas as pd class Marcher(object): def __init__(self, p_path): self.p_path = p_path p_m = 'ID' def first_call(self): df_p = pd.read_csv(self.p_path, header=None) return df_p def p_to_i(self, p): pii = p.set_index(self.p_m, drop=False).loc[p[self.p_m]] return pii m1 = p_to_i(first_call()) </code></pre> <p>What I would like to do with this is something like this:</p> <pre><code>test = Marcher(p_path='/some/path/to/file.csv') test.m1 </code></pre> <p>However when I try this I get back an error:</p> <pre><code>TypeError: first_call() takes exactly 1 argument (0 given) </code></pre>
0
2016-08-29T20:03:56Z
39,214,416
<p>why do you want <code>m1</code> to be a class member variable? just move the call like this:</p> <pre><code>def __init__(self, path): self.path = path self.m1 = self.p_to_i(self.first_call()) </code></pre>
2
2016-08-29T20:12:40Z
[ "python" ]
method within class is not callable within that class?
39,214,277
<p>If I have a file, foo.py with contents:</p> <pre><code>import pandas as pd class Marcher(object): def __init__(self, p_path): self.p_path = p_path p_m = 'ID' def first_call(self): df_p = pd.read_csv(self.p_path, header=None) return df_p def p_to_i(self, p): pii = p.set_index(self.p_m, drop=False).loc[p[self.p_m]] return pii m1 = p_to_i(first_call()) </code></pre> <p>What I would like to do with this is something like this:</p> <pre><code>test = Marcher(p_path='/some/path/to/file.csv') test.m1 </code></pre> <p>However when I try this I get back an error:</p> <pre><code>TypeError: first_call() takes exactly 1 argument (0 given) </code></pre>
0
2016-08-29T20:03:56Z
39,214,483
<p>The issue is you're trying to call the methods before creating an instance. Take for instance a simple Circle class:</p> <pre><code>import math class Circle(object): def __init__(self, radius): self.radius = radius def get_area(self): return math.pi * self.radius ** 2 # You cannot do this because every circle can have a different radius # area = get_area() # But you can use a property @property def area(self): return self.get_area() print Circle(2).area # 12.5663706144 print Circle(10).area # 314.159265359 </code></pre> <p>Also, sometimes people like to cache property values to avoid re-computing them, that looks something like this:</p> <pre><code>class Circle(object): # ... _area = None @property area(self): if self._area is None: self._area = self.get_area() return self._area </code></pre> <p>The downside to this method is that <code>Circle</code> is no longer a dynamic object, you should not update the "radius" attribute once the instance is created because the area is cached and will not get updated.</p>
2
2016-08-29T20:16:17Z
[ "python" ]
SyntaxError: python Arabic encoding
39,214,320
<p>I have this Code -I am using Python 2.7- :</p> <pre><code>#!/usr/bin/python # -*- Coding: UTF-8 -*- import nltk from nltk.tokenize import StanfordTokenizer sentence = u"السلام عليكم و رحمة الله و بركاته" print StanfordTokenizer().tokenize(sentence) </code></pre> <p>I saved the code in a file called example.py, when I write python example.py in the terminal I get the following error:</p> <pre><code>File "example.py", line 5 SyntaxError: Non-ASCII character '\xd8' in file example.py on line 5, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details </code></pre> <p>I already declared the type of encoding as UTF-8. So what is the problem? However, if I run the code line by line in the terminal it is working and no error.</p>
1
2016-08-29T20:06:20Z
39,214,374
<blockquote> <p>... the first or second line must match the regular expression "^[ \t\v]<em>#.</em>?coding[:=][ \t]*([-_.a-zA-Z0-9]+)".</p> </blockquote> <p><a href="https://www.python.org/dev/peps/pep-0263/" rel="nofollow">source</a></p> <p>Your encoding declaration does not match that regex. The <code>c</code> needs to be lowercase.</p>
1
2016-08-29T20:09:17Z
[ "python", "encoding", "arabic" ]
scrape Url and text from website using lxml python
39,214,339
<p>I don't know much about lxml and xpaths and I want to learn how to scrape data from website. When I run this code I don't get any results and don't know why. Please help me to fix it.</p> <p>code here</p> <pre><code>from lxml import html import requests pageLen=str(100) page = requests.get('http://www.yellowpages.com/search?search_terms=lawyer&amp;geo_location_terms=usa&amp;page=2') print(page) tree = html.fromstring(page.content) #phoneNumber = tree.xpath('//span[@class="c411Phone"]/text()') Link=tree.xpath('//div[@class="info"]/a/@href') Bname=tree.xpath('//a[@class="business-name"]/text()') print(Bussiness_names) print(Bname) </code></pre> <p>HTML CODE</p> <p><img src="http://i.stack.imgur.com/Ar0oG.png" alt="enter image description here"></p>
-1
2016-08-29T20:07:17Z
39,214,818
<p>quick and dirty:</p> <pre><code>from lxml import html import requests url = 'http://www.yellowpages.com/search?search_terms=lawyer&amp;geo_location_terms=usa&amp;page=2' page = requests.get(url) tree = html.fromstring(page.text) tree.make_links_absolute(url) for business in tree.xpath('//a[@class="business-name"]'): print business.attrib['href'], business.text </code></pre>
-1
2016-08-29T20:39:23Z
[ "python", "web-scraping", "lxml" ]