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 |
|---|---|---|---|---|---|---|---|---|---|
Python socket always does the same | 38,614,032 | <p>I wanted to make a program, with a server and a client(yes, still the same).
The client sends an request to the server, with an command.
And depending on the command the server sends an response.</p>
<p>Unfortunatly, regardless of the command, the client sends, the server always gives the same response, why?</p>
<... | 0 | 2016-07-27T13:13:25Z | 38,615,921 | <p>Your server code should handle the possibility that <code>c.recv()</code> fails,</p>
<pre><code>while True:
try:
pcommand = c.recv(2048)
except IOError as e:
if e.errno == errno.EWOULDBLOCK or e.errno == errno.EAGAIN:
continue
else:
pass # raise an error / han... | 0 | 2016-07-27T14:30:44Z | [
"python",
"sockets"
] |
Python socket always does the same | 38,614,032 | <p>I wanted to make a program, with a server and a client(yes, still the same).
The client sends an request to the server, with an command.
And depending on the command the server sends an response.</p>
<p>Unfortunatly, regardless of the command, the client sends, the server always gives the same response, why?</p>
<... | 0 | 2016-07-27T13:13:25Z | 38,619,554 | <p>I found a solution for this Problem, but I don't like it, because it uses to much internet volume.
The Problem was that the error was handeled by the try... except clause, but if an error occured, it was handeled and than nothing happened, so pcommand stayed the same.
So I made a recursive funktion, that tries to co... | 0 | 2016-07-27T17:25:22Z | [
"python",
"sockets"
] |
It should be some tiny mistake in quicksort algorithm implementation in python | 38,614,156 | <p>I have implemented quicksort algorithm in python but when I compute the number of swaps done to sort the array it does not compute correctly. I am sure I am doing some very silly mistake, but I am just not able to find it. Can anyone please help me in this regard? Here is the code which I made.</p>
<pre><code>def p... | -2 | 2016-07-27T13:18:47Z | 38,639,496 | <p>DISCLAIMER: I haven't tested this, but I believe I've found a few problems.</p>
<p>First, it looks like the line </p>
<pre><code>count += iArray.index(pivot)
</code></pre>
<p>is wrong, because the index will be the index in the ENTIRE array, not just between <code>l</code> and <code>r</code>. So change it to thi... | 0 | 2016-07-28T14:36:19Z | [
"python",
"algorithm",
"quicksort"
] |
It should be some tiny mistake in quicksort algorithm implementation in python | 38,614,156 | <p>I have implemented quicksort algorithm in python but when I compute the number of swaps done to sort the array it does not compute correctly. I am sure I am doing some very silly mistake, but I am just not able to find it. Can anyone please help me in this regard? Here is the code which I made.</p>
<pre><code>def p... | -2 | 2016-07-27T13:18:47Z | 38,642,942 | <p>The answer you are seeking is the number of comparisons and not the number of swaps. So there are two changes: </p>
<ol>
<li><p>The line is incorrect and is really not computing the number of comparisons.</p>
<p><code>count += iArray.index(pivot)</code></p>
<p>Since the number of comparisons is done over the enti... | 0 | 2016-07-28T17:22:33Z | [
"python",
"algorithm",
"quicksort"
] |
How can i show a simple instagram feed with the new api permissions | 38,614,256 | <p>I am trying to set up a instagram plugin on django cms to show my recent images on a homepage by the username set in the plugin. It seems you can no longer simply get public content from instagram. This is the current method im using with my sandbox account.</p>
<pre><code>user_request = requests.get("https://api.i... | 1 | 2016-07-27T13:23:30Z | 38,618,181 | <p>Yes, the first results is not always the match, you have loop through all the search results and compare the username to your searched username, and then get id</p>
<p>Something like this:</p>
<pre><code>var user_id = 0;
user_request.json().values()["data"].forEach(function(user){
if(user.username == str(insta... | 1 | 2016-07-27T16:08:36Z | [
"python",
"django",
"instagram-api",
"django-cms"
] |
Plot coordinates with different colours corresponding to class labels in matplotlib | 38,614,257 | <p>I have a matrix <code>X</code> of shape <code>Nx2</code> and a corresponding set of labels (5 labels for 5 classes, eg., 0,1,2,3,4) in matrix <code>Y</code> of length <code>N</code>. Now I want to plot <code>X</code> using matplotlib scatter plot such that the value in <code>X</code> corresponding to each label in <... | 1 | 2016-07-27T13:23:31Z | 38,614,333 | <p>You can specify the colors parameter to <code>scatter</code>. If you simply pass the class label array as the color parameter, the colormap will be used to map each label to a corresponding RGB value.</p>
<pre><code>plt.scatter(X[:,0], X[:,1], c=Y)
</code></pre>
| 3 | 2016-07-27T13:26:47Z | [
"python",
"python-2.7",
"matplotlib"
] |
Weird behaviour using FLASK socketIO in python with the library eventlet | 38,614,277 | <p>i'm trying here to interact with my back end (Python 2.7 FLASK) by pressing buttons on my front end HTML.</p>
<p>Here the behaviour I expect :</p>
<p>My state machine is in wait Status (waiting for user action)</p>
<p><code>startEvent.wait()</code></p>
<p>When I press the button START, I set an event in my back ... | 0 | 2016-07-27T13:24:05Z | 38,631,792 | <p>Alright, I found the solution :</p>
<p>In fact, the sleep from time library in python was blocking my socket throught the GUI. To solve this problem, I had to use the sleep function from the eventlet library like this :</p>
<pre><code>import sleep from eventlet
</code></pre>
| 0 | 2016-07-28T09:06:41Z | [
"javascript",
"python",
"sockets",
"flask"
] |
TypeError: unsupported operand type(s) for ** or pow(): 'function' and 'int' probability calculator | 38,614,321 | <p>I'm trying to put my probability calculator inside a nice GUI but I ran into a problem with my probability calculations.</p>
<p>I've made 3 scripts:</p>
<ol>
<li>Tkinter script, my user interface and also the place where I get
my numbers from.</li>
<li>My runable script, this script has been put in place to preven... | 0 | 2016-07-27T13:26:22Z | 38,614,394 | <p>You are clearly assigning the default value of <code>s</code> as a function:</p>
<pre><code>from run_file import projected_hold_player1
...
def game_prob(s=projected_hold_player1, v=0, w=0)
# ^^^^^^^^^^^^^^^^^^^^^^^^
</code></pre>
<p>So calling <code>s**a</code> raises that error, as the operator doe... | 2 | 2016-07-27T13:29:27Z | [
"python"
] |
Python string.Template: Replace field containing spaces | 38,614,437 | <p>Using Python's string.Template class - how might I utilize the ${} for fields in a dictionary that contain spaces?</p>
<p>E.g.</p>
<pre><code>t = string.Template("hello ${some field}")
d = { "some field": "world" }
print( t.substitute(d) ) # Returns "invalid placeholder in string"
</code></pre>
<hr>
<p><strong>E... | 0 | 2016-07-27T13:31:02Z | 38,614,561 | <p>Just in case this might be helpful to somebody else. In python 3 you can use <code>format_map</code>:</p>
<pre><code>t = "hello {some field}"
d = { "some field": "world" }
print( t.format_map(d) )
# hello world
</code></pre>
| 0 | 2016-07-27T13:36:56Z | [
"python",
"string",
"python-2.7",
"replace"
] |
Python string.Template: Replace field containing spaces | 38,614,437 | <p>Using Python's string.Template class - how might I utilize the ${} for fields in a dictionary that contain spaces?</p>
<p>E.g.</p>
<pre><code>t = string.Template("hello ${some field}")
d = { "some field": "world" }
print( t.substitute(d) ) # Returns "invalid placeholder in string"
</code></pre>
<hr>
<p><strong>E... | 0 | 2016-07-27T13:31:02Z | 38,615,240 | <p>From Doc it says that we could use Template option </p>
<p><a href="https://docs.python.org/dev/library/string.html#template-strings" rel="nofollow">https://docs.python.org/dev/library/string.html#template-strings</a></p>
<pre><code>import string
class MyTemplate(string.Template):
delimiter = '%'
idpatter... | 0 | 2016-07-27T14:04:22Z | [
"python",
"string",
"python-2.7",
"replace"
] |
Converting a single pandas index into a three level MultiIndex in python | 38,614,659 | <p>I have some data in a pandas dataframe which looks like this:</p>
<pre><code>gene VIM
time:2|treatment:TGFb|dose:0.1 -0.158406
time:2|treatment:TGFb|dose:1 0.039158
time:2|treatment:TGFb|dose:10 -0.052608
time:24|treatment:TGFb|dose:0.1 0.157153
time:24|treatment:T... | 0 | 2016-07-27T13:40:58Z | 38,614,847 | <p>You can first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html" rel="nofollow"><code>replace</code></a> unnecessary strings (index has to be converted to <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.to_series.html" rel="no... | 1 | 2016-07-27T13:48:37Z | [
"python",
"pandas",
"indexing",
"multi-index"
] |
Randomly splitting training and testing data | 38,614,675 | <p>I have around 3000 objects where each object has a count associated with it. I want to randomly divide these objects in training and testing data with a 70%
training and 30% testing split. But, I want to divide them based on the count associated with each object but not based on the number of objects.</p>
<p>An ex... | 1 | 2016-07-27T13:42:01Z | 38,614,966 | <p>Assuming I understand your question correctly, my suggestion would be this:</p>
<pre><code>from random import shuffle
sum = sum([obj.count for obj in obj_list]) #Get the total "count" of all the objects, O(n)
shuffle(obj_list)
running_sum = 0
i = 0
while running_sum < sum * .3
running_sum += obj_list[i].coun... | 2 | 2016-07-27T13:53:44Z | [
"python",
"python-2.7",
"machine-learning",
"training-data"
] |
Randomly splitting training and testing data | 38,614,675 | <p>I have around 3000 objects where each object has a count associated with it. I want to randomly divide these objects in training and testing data with a 70%
training and 30% testing split. But, I want to divide them based on the count associated with each object but not based on the number of objects.</p>
<p>An ex... | 1 | 2016-07-27T13:42:01Z | 38,614,975 | <p>I do not know if there is a specific function in Python, but assuming there isn't, here is an approach.</p>
<p>Shuffle objects:</p>
<pre><code> from random import shuffle
values = shuffle[200, 40, 30, 110, 20]
</code></pre>
<p>Calculate percentage of dictionary values:</p>
<pre><code> prob = [float(i)/sum(value... | 0 | 2016-07-27T13:53:59Z | [
"python",
"python-2.7",
"machine-learning",
"training-data"
] |
Rotate the ticklabels while keeping the letter horizontal | 38,614,677 | <p>When I use <code>ax.set_xticklabels(['somethinghere']*10, rotation='-90')</code>, I get a result like this:</p>
<p><a href="http://i.stack.imgur.com/jynNC.png" rel="nofollow"><img src="http://i.stack.imgur.com/jynNC.png" alt="rotated word"></a></p>
<p>I want to just rotate the words while keeping the letters horiz... | 0 | 2016-07-27T13:42:05Z | 38,619,600 | <p>Maybe not the best way but certainly works</p>
<pre><code>ax.set_xticklabels((['s\n''o\n''m\n''e\n''t\n''h\n''i\n''n\n''g\n' ])*10)
</code></pre>
| 0 | 2016-07-27T17:27:54Z | [
"python",
"matplotlib",
"axes"
] |
ValueError with randint | 38,614,702 | <p>I'm having this really weird error and I have no idea what it is.
This is my code:</p>
<pre><code>def wordChoice():
theme = themechoice
word = theme[randint(0, len(theme) - 1)]
</code></pre>
<p>This is the error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Andrei\Documents\USB Ba... | -3 | 2016-07-27T13:42:55Z | 38,614,840 | <p>This error will occur when <code>theme</code> is empty.</p>
<pre><code>>>> theme = []
>>> random.randint(0, len(theme)-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Programming\Python 3.5\lib\random.py", line 218, in randint
return self.rand... | 1 | 2016-07-27T13:48:17Z | [
"python"
] |
Sentiment Analysis - Cross Validation not valid score | 38,614,738 | <p>I am testing a Sentiment Analysis model using NLTK and SKlearn.</p>
<p>Movie_reviews data has "pos" and "neg" labels. For training the classifier I am using "featuresets". I am using cross validation on training data and accuracy on testing data. However cross validation is always much higher than accuracy. In the ... | 1 | 2016-07-27T13:44:32Z | 38,625,869 | <p>You are using <strong>training_set[traincv[0]:traincv[len(traincv)-1]]</strong> which means range from traincv[0] to traincv[len(traincv)-1]</p>
<p>In your case traincv[0] and testcv[0] will be always near to 0 and traincv[len(traincv)-1] and testcv[len(testcv)-1] will be near to 1499. So you are using almost same ... | 1 | 2016-07-28T01:47:31Z | [
"python",
"scikit-learn",
"nltk",
"cross-validation"
] |
python : how to know max size of a queue | 38,614,806 | <p>Size of a queue can be known by using <code>qsize()</code> </p>
<ul>
<li>How do we know the max size of a queue? Or in other way, when the condition <code>queue.full()</code> will return <code>True</code>?</li>
<li><p>Why is the result for <code>q.put(i)</code> always resulting in <code>None</code> whereas <code>q.... | 0 | 2016-07-27T13:47:20Z | 38,614,916 | <p>Check out the source code for the implementation of Queue: <a href="https://hg.python.org/cpython/file/3.5/Lib/queue.py" rel="nofollow">https://hg.python.org/cpython/file/3.5/Lib/queue.py</a></p>
<p>As you can see from the init function, 'queue.maxsize' is a member variable that should contain the max size of the q... | 1 | 2016-07-27T13:51:27Z | [
"python",
"multithreading",
"queue"
] |
python : how to know max size of a queue | 38,614,806 | <p>Size of a queue can be known by using <code>qsize()</code> </p>
<ul>
<li>How do we know the max size of a queue? Or in other way, when the condition <code>queue.full()</code> will return <code>True</code>?</li>
<li><p>Why is the result for <code>q.put(i)</code> always resulting in <code>None</code> whereas <code>q.... | 0 | 2016-07-27T13:47:20Z | 38,615,135 | <p>To answer your 1st question: for all intents and purposes, the max size of a Queue is infinite. The reason why is that if you try to put something in a Queue that is full, it will wait until a slot has opened up before it puts the next item into the queue. This is assuming you initialize the Queue with the max size ... | 2 | 2016-07-27T14:00:14Z | [
"python",
"multithreading",
"queue"
] |
Python searching multiple directories and reading select files | 38,614,910 | <p>I am looking for some help performing actions on a set of files in two different directories using Python.</p>
<p>I am attempting to:</p>
<ol>
<li><p>Search two different directories</p></li>
<li><p>Find the 15 last modified files (comparing files in both directories)</p></li>
<li><p>Read all 15 recently modified ... | 1 | 2016-07-27T13:51:11Z | 38,615,030 | <p>I'm not sure this is what you are after but if you were to use <code>glob.glob</code> instead of <code>glob.iglob</code>, you could do</p>
<pre><code>dir1 = glob.glob("/dir1/data_log.*")
dir2 = glob.glob("/dir2/message_log.*")
latest=heapq.nlargest(10, dir1+dir2, key=os.path.getmtime)
</code></pre>
<p>And actuall... | 5 | 2016-07-27T13:55:52Z | [
"python",
"glob",
"text-parsing"
] |
de-duplicate timeindex by adding milliseconds | 38,614,988 | <p>I want to use time datetime as main index, but have a lots of duplicates there. What I want is to add artificial milliseconds that works as âcounterâ inside each group of seconds.</p>
<p>For example â the original dataframe looks like:</p>
<pre><code> Bid BidVol
2016-06-27 13:00:10 ... | 0 | 2016-07-27T13:54:28Z | 38,615,090 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>cumcount</code></a> for creating <code>ms</code> , convert it <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow"><code>to_tim... | 2 | 2016-07-27T13:58:28Z | [
"python",
"pandas"
] |
Tf-Idf vectorizer analyze vectors from lines instead of words | 38,615,088 | <p>I'm trying to analyze a text which is given by lines, and I wish to vectorize the lines using sckit-learn package's TF-IDF-vectorization in python.
The problem is that the vectorization can be done either by words or n-grams but I want them to be done for lines, and I already ruled out a work around that just vector... | 2 | 2016-07-27T13:58:16Z | 38,615,418 | <p>You seem to be misunderstanding what the TF-IDF vectorization is doing. For each word (or N-gram), it assigns a weight to the word which is a function of both the frequency of the term (TF) and of its inverse frequency of the other terms in the document (IDF). It makes sense to use it for words (e.g. knowing how oft... | 1 | 2016-07-27T14:11:05Z | [
"python",
"scikit-learn",
"vectorization",
"tf-idf",
"text-analysis"
] |
Limit Tensorflow CPU and Memory usage | 38,615,121 | <p>I've seen several questions about GPU Memory with Tensorflow but I've installed it on a Pine64 with no GPU support.</p>
<p>That means I'm running it with very limited resources (CPU and RAM only) and Tensorflow seems to want it all, completely freezing my machine.</p>
<p><br></p>
<p>Is there a way to limit the am... | 1 | 2016-07-27T13:59:40Z | 38,619,385 | <p>This will create a session that runs one op at a time, and only one thread per op</p>
<pre><code>sess = tf.Session(
tf.ConfigProto(inter_op_parallelism_threads=1,
intra_op_parallelism_threads=1))
</code></pre>
<p>Not sure about limiting memory, it seems to be allocated on demand, I've had Te... | 1 | 2016-07-27T17:15:56Z | [
"python",
"memory-management",
"tensorflow",
"cpu-usage"
] |
Problems with gridspec plotting with APLpy | 38,615,147 | <p>So I'm attempting to plot to fits images (identical fits images) with some annotations provided by a DS9 region file using APLpy:</p>
<p>My script is as follows:</p>
<pre><code>import aplpy
import matplotlib
import matplotlib.pyplot as pyplot
import matplotlib.gridspec as gridspec
from astropy.io import fits
ma... | -1 | 2016-07-27T14:00:35Z | 38,628,614 | <p>You need to use <code>show_grayscale</code> or <code>show_colorscale</code> to display the images, e.g.:</p>
<pre><code>M33_galax.show_grayscale()
</code></pre>
| 1 | 2016-07-28T06:28:45Z | [
"python",
"matplotlib",
"grid",
"astropy",
"aplpy"
] |
Pandas: add several dataframes to a single Excel file | 38,615,306 | <p>I need to add several <code>df</code> to one excel and I want that they looks like
<a href="http://i.stack.imgur.com/iUIbM.png" rel="nofollow"><img src="http://i.stack.imgur.com/iUIbM.png" alt="enter image description here"></a>.
Is any function in <code>pandas</code>. that can make it?</p>
| -3 | 2016-07-27T14:07:30Z | 38,615,493 | <p>For the layout, see <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html" rel="nofollow"><code>to_excel</code></a> docs.
Note that you will have to pass it a <code>pd.ExcelWriter</code> object instead of a path string and then call its <code>save</code> method to be able to s... | 0 | 2016-07-27T14:14:09Z | [
"python",
"pandas"
] |
I used the website's URL before using Ajax URL which parsed the table. Now I get "none" when i print | 38,615,388 | <pre><code>import requests
import csv
from BeautifulSoup import BeautifulSoup
payload = {
'action': "historical_data",
'curr_id': "160",
'st_date' : "01/05/2016",
'end_date' : "30/05/2016",
'interval_sec' : "Daily"
}
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:4... | -1 | 2016-07-27T14:10:02Z | 38,620,672 | <p>First off use <em>bs4</em>, <em>BeautifulSoup3</em> is deprecated and no longer maintained, to fix your issue you need to add another header, <em>"X-Requested-With":"XMLHttpRequest"</em>:</p>
<pre><code>from bs4 import BeautifulSoup
import requests
payload = {
'action': "historical_data",
'curr_id': "160"... | 0 | 2016-07-27T18:32:30Z | [
"python",
"ajax",
"web-scraping",
"beautifulsoup",
"python-requests"
] |
How to set up a distributed worker pool with Celery and RabbitMQ | 38,615,427 | <p>I'm still really new to this kind of thing so it's entirely possible that I've got this wrong. </p>
<p>I am trying to set up a distributed task system. I have a Django webapp that is generating tasks using Celery. Right now, I have the webapp, the worker, and RabbitMQ running all on the same server. I would like to... | 0 | 2016-07-27T14:11:16Z | 38,650,520 | <p>You can run your worker code (async_tasks.py) like this:</p>
<pre><code>from celery import Celery
app = Celery('tasks', broker=broker_url)
@app.task(queue='queue_name')
def async_compute_something(input):
# do something
return "Result"
</code></pre>
<p>on other machines using this command :</p>
<pre><co... | 1 | 2016-07-29T04:28:15Z | [
"python",
"django",
"rabbitmq",
"celery"
] |
drop elements of a level of a multi-level index pandas | 38,615,616 | <p>In the following DataFrame there are a 2-level MultiIndex, namely <code>city</code> and <code>date</code>:</p>
<pre><code> temp
count
city date
SFO 2014-05-31 31
2014-06-30 30
2014-07-31 31
2014-08-31 31
2014-09-30 30
YYZ 2014-05-31 ... | 4 | 2016-07-27T14:18:54Z | 38,616,050 | <p>You can give <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.drop.html">drop</a> a specific <code>level</code>:</p>
<pre><code>In[4]: df.drop([Timestamp('2014-05-31'),Timestamp('2014-09-30')],level=1)
Out[4]:
temp
count
city date
SFO 20... | 7 | 2016-07-27T14:35:51Z | [
"python",
"pandas",
"indexing",
"multi-index"
] |
Regular Expression to accept all Thai characters and English letters in python | 38,615,740 | <p>I need to vectorize text documents in Thai (e.g Bag of Words, doc2vec). </p>
<p>First I want to go over each document, omitting everything except the Thai characters and English words (e.g. no punctuation, no numbers, no other special characters except apostrophe). </p>
<p>For English documents, I use this regular... | 0 | 2016-07-27T14:23:38Z | 38,616,295 | <p>In Python 3,</p>
<pre><code>s = "à¸à¸£à¸¹à¸§à¸´à¸à¸±à¹à¸à¸ªà¹ à¸à¸£à¸°à¸à¸²à¸¨à¸à¹à¸²à¸¢à¸à¸à¸à¸ªà¸à¸¨à¸¶à¸à¸à¸¸à¸à¸à¸à¸¥ à¸à¸£à¸µà¹à¸¡à¸µà¸¢à¸£à¹ ลีภà¸à¸±à¸à¸à¸¤à¸© à¸à¸£à¸à¸à¸¸à¸à¸à¸±à¸à¹à¸à¹à¸à¹à¸§à¸¥à¸² 3 à¸à¸µ à¸à¸±à¹à¸à¹à¸à¹à¸¤à¸à¸¹à¸à¸²à¸¥ 2016/2017 - 2018/2... | 0 | 2016-07-27T14:46:02Z | [
"python",
"regex",
"thai"
] |
Regular Expression to accept all Thai characters and English letters in python | 38,615,740 | <p>I need to vectorize text documents in Thai (e.g Bag of Words, doc2vec). </p>
<p>First I want to go over each document, omitting everything except the Thai characters and English words (e.g. no punctuation, no numbers, no other special characters except apostrophe). </p>
<p>For English documents, I use this regular... | 0 | 2016-07-27T14:23:38Z | 38,617,380 | <p>I'll be using some lists to do what I need. </p>
<p>First, let's create the pattern :</p>
<pre><code>pattern = re.compile(r"[^\u0E00-\u0E7Fa-zA-Z' ]|^'|'$|''")
</code></pre>
<p>I'll use a string named <code>test_string</code>, containing your example : </p>
<pre><code>test_string="à¸à¸£à¸¹à¸§à¸´à¸à¸±à¹à¸à¸ª... | 2 | 2016-07-27T15:31:20Z | [
"python",
"regex",
"thai"
] |
Regular Expression to accept all Thai characters and English letters in python | 38,615,740 | <p>I need to vectorize text documents in Thai (e.g Bag of Words, doc2vec). </p>
<p>First I want to go over each document, omitting everything except the Thai characters and English words (e.g. no punctuation, no numbers, no other special characters except apostrophe). </p>
<p>For English documents, I use this regular... | 0 | 2016-07-27T14:23:38Z | 38,617,492 | <p>Sadly, there are not many regular expression libraries with good Unicode support, and Python's <code>re</code> library is one of them. Oniguruma has proper Unicode support and I believe it has Python bindings, and Perl's built-in regular expressions have good Unicode support.</p>
<p>I normally don't suggest that p... | 0 | 2016-07-27T15:35:29Z | [
"python",
"regex",
"thai"
] |
Making a dataframe global so that i can access it anywhere in the class | 38,615,761 | <p>I am working on the below program, I am unable to access the data (its a dataframe) object from the search method inside the displayPage class. I tried using the global key word. Doesn't seems to work, can anyone help me out with this?</p>
<pre><code>import tkinter as tk
import tkinter.messagebox as tm
from tkinter... | 0 | 2016-07-27T14:24:28Z | 38,615,864 | <p>You should move <code>global data</code> to the line above <code>data = scrape.scrape_info(item,loc)</code>, since without it, the assignment creates a new <code>data</code> variable in the scope of <code>displayPage</code>'s <code>__init__</code> method.</p>
<p>See this very basic example:</p>
<pre><code>def foo(... | 0 | 2016-07-27T14:28:38Z | [
"python",
"tkinter"
] |
Making a dataframe global so that i can access it anywhere in the class | 38,615,761 | <p>I am working on the below program, I am unable to access the data (its a dataframe) object from the search method inside the displayPage class. I tried using the global key word. Doesn't seems to work, can anyone help me out with this?</p>
<pre><code>import tkinter as tk
import tkinter.messagebox as tm
from tkinter... | 0 | 2016-07-27T14:24:28Z | 38,616,907 | <p>You need to use <code>global</code> keyword in the <code>search</code> method to access global <code>data</code>.</p>
<pre><code>def search(item,loc,cont):
global data
</code></pre>
| 0 | 2016-07-27T15:09:31Z | [
"python",
"tkinter"
] |
How to download a file with Python, Selenium and PhantomJS | 38,615,811 | <p>Here is my situation: I have to login to a Website and download a CSV from there, headless from a linux server. The page uses JS and does not work without it.</p>
<p>After some research I went with Selenium and PhantomJS.
Logging in, setting the parameters for the CSV and finding the download button with Selenium/P... | 0 | 2016-07-27T14:26:37Z | 38,616,151 | <p>If the button that you want to download has the file link, you are able to test downloading it using python code, because PhantonJs does not support a download by itself. So, if your download button does not provide the file link, you're not able to test.</p>
<p>To test using file link and phyton (to assert that fi... | 1 | 2016-07-27T14:39:43Z | [
"python",
"csv",
"selenium",
"phantomjs"
] |
How to download a file with Python, Selenium and PhantomJS | 38,615,811 | <p>Here is my situation: I have to login to a Website and download a CSV from there, headless from a linux server. The page uses JS and does not work without it.</p>
<p>After some research I went with Selenium and PhantomJS.
Logging in, setting the parameters for the CSV and finding the download button with Selenium/P... | 0 | 2016-07-27T14:26:37Z | 38,616,430 | <p>You can try something like:</p>
<pre><code>from requests.auth import HTTPBasicAuth
import requests
url = "http://some_site/files?file=file.csv" # URL used to download file
# GET-request to get file content using your web-site's credentials to access file
r = requests.get(url, auth=HTTPBasicAuth("your_username", ... | 0 | 2016-07-27T14:51:09Z | [
"python",
"csv",
"selenium",
"phantomjs"
] |
How to download a file with Python, Selenium and PhantomJS | 38,615,811 | <p>Here is my situation: I have to login to a Website and download a CSV from there, headless from a linux server. The page uses JS and does not work without it.</p>
<p>After some research I went with Selenium and PhantomJS.
Logging in, setting the parameters for the CSV and finding the download button with Selenium/P... | 0 | 2016-07-27T14:26:37Z | 38,616,605 | <p>I recently used Selenium to utilize ChromeDriver to download a file from the web. This works because Chrome automatically downloads the file and stores it in the Downloads file for you. This was easier than using PhantomJS.</p>
<p>I recommend looking into using ChromeDriver with Selenium and going that route: <a ... | 1 | 2016-07-27T14:58:16Z | [
"python",
"csv",
"selenium",
"phantomjs"
] |
How to download a file with Python, Selenium and PhantomJS | 38,615,811 | <p>Here is my situation: I have to login to a Website and download a CSV from there, headless from a linux server. The page uses JS and does not work without it.</p>
<p>After some research I went with Selenium and PhantomJS.
Logging in, setting the parameters for the CSV and finding the download button with Selenium/P... | 0 | 2016-07-27T14:26:37Z | 38,655,474 | <p>I found a solution and wanted to share it.
One requirement changed, I am not using <code>PhantomJS</code> anymore but the <code>chromedriver</code> which works headlessly with a virtual framebuffer. Same result and it gets the job done.</p>
<hr>
<p>What you need is:</p>
<p><code>pip install selenium pyvirtualdsip... | 1 | 2016-07-29T09:39:12Z | [
"python",
"csv",
"selenium",
"phantomjs"
] |
Running a Python script in a Makefile | 38,615,860 | <p>I have a Python script (scr1.py) that calls another Python script (scr2.py) and they both on the same path. When I open CMD and run scr1.py everything works perfectly.</p>
<p>I want to run scr1.py inside a Makefile that is NOT on the same path as the scripts. The scr1.py is executing but fail on calling scr2.py. I ... | 1 | 2016-07-27T14:28:28Z | 38,616,195 | <p>Since both files are in same directory, how about just appending the current working directory path before second file name ?</p>
<pre><code>import os
import scr2
fileinfo = os.stat( os.getcwd() + '/scr2.py')
if os.path.isfile("infofile.txt"):
file=open("infofile.txt",'r')
lm = file.read()... | 0 | 2016-07-27T14:42:09Z | [
"python",
"python-2.7",
"makefile"
] |
Live stdout output from Python subprocess in Jupyter notebook | 38,616,077 | <p>I'm using subprocess to run a command line program from a Python (3.5.2) script, which I am running in a Jupyter notebook. The subprocess takes a long time to run and so I would like its stdout to be printed live to the screen in the Jupyter notebook.</p>
<p>I can do this no problem in a normal Python script run fr... | 1 | 2016-07-27T14:36:35Z | 39,667,715 | <p>If you set <code>stdout = None</code> (this is the default, so you can omit the <code>stdout</code> argument altogether), then your process should write its output to the terminal running your IPython notebook server.</p>
<p>This happens because the default behavior is for subprocess to inherit from the parent file... | 0 | 2016-09-23T18:53:17Z | [
"python",
"subprocess",
"ipython",
"stdout",
"jupyter"
] |
turn of outliers boxplot in python | 38,616,099 | <p>Any ideas on how to turn of the outliers for the box plot?
Or send a link to the documentation for kind="box" because I've not been able to find it</p>
<p>Code is: </p>
<pre><code> df9=df.ix[Month+"-2015":Month+"-2015"]
df9=df9.rename(columns={'hour_mean': "2015"})
x=pd.concat([df1['2004'],df2['2005']... | 1 | 2016-07-27T14:37:32Z | 38,765,171 | <p>Have you tried </p>
<pre><code> ax=x.plot(kind="box", showfliers=False)
</code></pre>
<p>Outliers in pyplot are called fliers. Check this <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.boxplot" rel="nofollow">doc</a>.</p>
| 0 | 2016-08-04T10:44:37Z | [
"python",
"boxplot"
] |
Python3; Speed when sending data : IRC protocol, DCC file transfer | 38,616,138 | <p>I've written a new IRC client to which I just added the DCC SEND part, therefore supporting direct file transfer for both users of the app. Nothing, fancy, I'm using the irc python library to power the client and Django for the GUI. The great miniupnpc lib takes care of port forwarding. However, whilst the file is p... | 2 | 2016-07-27T14:39:15Z | 38,676,992 | <p>As I already suspected and as Bakuriu pointed out, the problem did indeed lie at the <code>file.read(buffer)</code> line. I finally found out why I had <code>struct.pack</code> error : the bytes acknowledgment was properly sent back to the sender, but sometimes a few packets were joined together. That is, for every ... | 0 | 2016-07-30T18:06:10Z | [
"python",
"performance",
"file-transfer",
"irc"
] |
Find k nearest neighbors | 38,616,164 | <p>I have a matrix</p>
<pre><code>a = np.array([[ 8.6569141 , 8.19847655, 7.83540289, 8.49673563],
[ 7.86962825, 9.16869072, 8.60084933, 8.91840291],
[ 9.61896688, 9.69620637, 9.1879124 , 9.87479709],
[ 9.17427532, 8.98877464, 8.4313078 , 7.81914999]])
</code></pre... | -2 | 2016-07-27T14:40:17Z | 38,618,903 | <p>NumPy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html#numpy.argsort" rel="nofollow"><code>argsort</code></a> returns the indices that would sort an array:</p>
<pre><code>In [864]: a.argsort()
Out[864]:
array([[2, 1, 3, 0],
[0, 2, 3, 1],
[2, 0, 1, 3],
[3, 2, 1,... | -1 | 2016-07-27T16:48:06Z | [
"python",
"numpy"
] |
cx_freeze freezed python program doesn't run - no time to see the error message on executing | 38,616,200 | <p>so I made that python program using several module including os, zipfile, time, datetime, shutil, shelve and ftplib. I froze it with cx_freeze, it won't run on the target machine (but it run on mine). I'm super new to cx_freeze, but I've poked around a bit and I suspect it's a module ot found error. Trouble is, when... | 0 | 2016-07-27T14:42:15Z | 38,618,295 | <p>Executing the exe from the console works out fine. Thanks.</p>
| 0 | 2016-07-27T16:15:28Z | [
"python",
"cx-freeze"
] |
Pandas: Create aggregation table with percentages | 38,616,237 | <p>I have a data</p>
<pre><code>Third party unique identifier Qsex
9ea3e3cb6719f3d336d324c446f486bd 1
d1b69bc4cccf0afef66debf4e3f0643e 2
f574fc585db0cddef88306ef6f32da59 1
8bc0a586bf0abec653c29cf4160753f9 1
7c22b56929378ec2eb3a536b4f4bc4e0 2
23d8433168c46d57a271a6b979037094 1
5743b7eec1b018572b6c5b... | -1 | 2016-07-27T14:43:59Z | 38,616,463 | <p>Here's an answer that uses <code>pandas</code> API.</p>
<p>I've done my best in building up the function calls so that you can follow the logic. Answer inspired by <a href="http://stackoverflow.com/questions/23377108/pandas-percentage-of-total-with-groupby#23377232">this post</a>.</p>
<pre><code>In [1]: import pan... | 0 | 2016-07-27T14:52:49Z | [
"python",
"pandas"
] |
Pandas: Create aggregation table with percentages | 38,616,237 | <p>I have a data</p>
<pre><code>Third party unique identifier Qsex
9ea3e3cb6719f3d336d324c446f486bd 1
d1b69bc4cccf0afef66debf4e3f0643e 2
f574fc585db0cddef88306ef6f32da59 1
8bc0a586bf0abec653c29cf4160753f9 1
7c22b56929378ec2eb3a536b4f4bc4e0 2
23d8433168c46d57a271a6b979037094 1
5743b7eec1b018572b6c5b... | -1 | 2016-07-27T14:43:59Z | 38,618,006 | <p>Try This: </p>
<pre><code>df["Sex"] = np.where(df["Qsex"] == 1, "Male", "Female")
df2 = pd.crosstab(df.Sex, df.Qsex, margins=True)
df3 = np.round(df2[["All"]]/df['Sex'].count()*100,2).rename(columns ={"All" :'%'})
pd.concat([df2[["All"]],df3], axis =1 )
Qsex All %
Sex
Femal... | 0 | 2016-07-27T16:00:41Z | [
"python",
"pandas"
] |
Sorting a pandas DataFrame by one level of a MultiIndex | 38,616,263 | <p>I have a MultiIndexed pandas DataFrame that needs sorting by one of the indexers. Here is a snippet of the data:</p>
<pre><code>gene VIM
treatment dose time
TGFb 0.1 2 -0.158406
1 2 0.039158
10 2 -0.052608
0.1 24 0.15715... | 2 | 2016-07-27T14:44:52Z | 38,616,603 | <p>Use <code>sort_index</code> specifying <code>level</code>:</p>
<pre><code>df.sort_index(level=2)
</code></pre>
<p>Or</p>
<pre><code>df.sort_index(level=-1)
</code></pre>
<p>Or</p>
<pre><code>df.sort_index(level='time')
</code></pre>
<p>All yield:</p>
<p><a href="http://i.stack.imgur.com/DbxlB.png" rel="nofoll... | 4 | 2016-07-27T14:58:13Z | [
"python",
"sorting",
"pandas",
"multi-index"
] |
Cannot run Whoosh 'quickstart' example (FileNotFoundError) | 38,616,405 | <p>I just tried to run the example at <a href="https://whoosh.readthedocs.io/en/latest/quickstart.html#a-quick-introduction" rel="nofollow">https://whoosh.readthedocs.io/en/latest/quickstart.html#a-quick-introduction</a></p>
<pre><code>cedricvr@atlantis94:~/repos/bibworm$ python3
Python 3.5.2 (default, Jul 5 2016, 12... | 0 | 2016-07-27T14:50:22Z | 38,617,281 | <p>Stupid me: you have to <code>mkdir</code> the directory before:</p>
<pre><code>import os
os.mkdir('indexdir')
</code></pre>
| 0 | 2016-07-27T15:26:40Z | [
"python",
"whoosh"
] |
Why are dates in pandas being displayed in a different format to input (CSV) data? | 38,616,424 | <p>I have a CSV which has dates in this format:</p>
<pre><code>Date
01/01/1997
02/01/1997
03/01/1997
04/01/1997
</code></pre>
<p>I am importing the data into a dataset using <code>df = pd.read_csv('data.csv')</code></p>
<p><strong>When I look at the data held in the dataframe it appears in a different format:</stron... | 0 | 2016-07-27T14:50:56Z | 38,616,491 | <p>Because that's <code>pandas</code> default time format. </p>
<p>You can pass <code>read_csv</code> <code>dayfirst=True</code>, as can be seen in the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>dayfirst : boolean, defau... | 1 | 2016-07-27T14:54:10Z | [
"python",
"csv",
"pandas"
] |
Why are dates in pandas being displayed in a different format to input (CSV) data? | 38,616,424 | <p>I have a CSV which has dates in this format:</p>
<pre><code>Date
01/01/1997
02/01/1997
03/01/1997
04/01/1997
</code></pre>
<p>I am importing the data into a dataset using <code>df = pd.read_csv('data.csv')</code></p>
<p><strong>When I look at the data held in the dataframe it appears in a different format:</stron... | 0 | 2016-07-27T14:50:56Z | 38,622,743 | <p>You can use <code>parse_dates</code> option from <code>read_csv</code> to get data in same format as on your .csv file. Key is <code>dayfirst=True</code> to get dates first then month and you can change accordingly.
You can also change the format as below: </p>
<pre><code>df.apply(pd.to_datetime, dayfirst=True)
<... | 1 | 2016-07-27T20:36:47Z | [
"python",
"csv",
"pandas"
] |
Why does python dictionary use so much memory? | 38,616,544 | <p>I have seen a <a href="http://stackoverflow.com/questions/17313381/why-does-a-dictionary-use-so-much-ram-in-python">similar question</a> to this but i think my predicament is different in enough ways to warrant a new question.</p>
<p>I have created a function which opens a csv file and aggregates the data into a js... | 1 | 2016-07-27T14:56:24Z | 38,617,053 | <p>Each call will use the same dictionary. See <a href="http://docs.python-guide.org/en/latest/writing/gotchas/" rel="nofollow">http://docs.python-guide.org/en/latest/writing/gotchas/</a>. The empty dictionary <code>{}</code> is created as an attribute of the function at compilation time. </p>
<p>If you called the f... | 2 | 2016-07-27T15:15:40Z | [
"python",
"csv",
"dictionary",
"memory"
] |
Why do I get UnboundLocalError in my second code but not in the first? | 38,616,563 | <p>When I execute</p>
<pre><code>x = 0
def f():
print('x' in locals())
x = 1
print('x' in locals())
f()
</code></pre>
<p>I get what I expect, namely</p>
<pre><code>False
True
</code></pre>
<p>Yet when I execute </p>
<pre><code>x = 3
def f():
print(x, 'x' in locals())
x = 7
print(x, 'x' i... | 1 | 2016-07-27T14:57:06Z | 38,617,026 | <p>The error is from printing <code>x</code>, not from the call <code>'x' in locals()</code>. You are not actually doing anything with the variable <code>x</code> when you do <code>'x' in locals()</code> since you are giving it a string value, not a reference to a variable. </p>
| 0 | 2016-07-27T15:14:41Z | [
"python"
] |
Why do I get UnboundLocalError in my second code but not in the first? | 38,616,563 | <p>When I execute</p>
<pre><code>x = 0
def f():
print('x' in locals())
x = 1
print('x' in locals())
f()
</code></pre>
<p>I get what I expect, namely</p>
<pre><code>False
True
</code></pre>
<p>Yet when I execute </p>
<pre><code>x = 3
def f():
print(x, 'x' in locals())
x = 7
print(x, 'x' i... | 1 | 2016-07-27T14:57:06Z | 38,617,063 | <p><code>dis.dis</code> for first function:</p>
<pre><code> 2 0 LOAD_CONST 1 ('x')
3 LOAD_GLOBAL 0 (locals)
6 CALL_FUNCTION 0
9 COMPARE_OP 6 (in)
12 PRINT_ITEM
13 PRINT_NEWLINE
3 ... | 2 | 2016-07-27T15:16:06Z | [
"python"
] |
deployed apache + django application access local files outside project directory | 38,616,568 | <p>I am trying to develop a django web app to be used locally where I work. the problem is there are some reports that I am transforming to be HTML based. some of the data being used in my app exist in excel files that are located on a network drive.</p>
<p>In development I can access all the files without any problem... | 0 | 2016-07-27T14:57:13Z | 38,742,223 | <p>so after trying the solution provided in the comment of Ivan <a href="http://askubuntu.com/questions/325498/apache-cant-access-folders-in-my-home-directory">allow Apache to access folders</a>. I have tested it on local folders and it worked fine. when trying it with network drives (eg: "Z:\shared_folder") apache cou... | 0 | 2016-08-03T11:25:31Z | [
"python",
"django",
"apache"
] |
Extract HTML comments in Python, using regex or lxml? | 38,616,592 | <p>How do I extract all HTML-style comments from a document, using Python?</p>
<p>I've tried using a regex:</p>
<pre><code>text = 'hello, world <!-- comment -->'
re.match('<!--(.*?)-->', text)
</code></pre>
<p>But it produces nothing. I don't understand this since the same regex works fine on the same st... | 1 | 2016-07-27T14:57:48Z | 38,616,781 | <p>You could use Beautiful Soup's to extract the comment in a for loop like this</p>
<pre><code>from bs4 import BeautifulSoup, Comment
text = 'hello, world <!-- comment -->'
soup = BeautifulSoup(text, 'lxml')
for x in soup.findAll(text=lambda text:isinstance(text, Comment)):
print(x)
</code></pre>
| 0 | 2016-07-27T15:04:44Z | [
"python",
"regex"
] |
Extract HTML comments in Python, using regex or lxml? | 38,616,592 | <p>How do I extract all HTML-style comments from a document, using Python?</p>
<p>I've tried using a regex:</p>
<pre><code>text = 'hello, world <!-- comment -->'
re.match('<!--(.*?)-->', text)
</code></pre>
<p>But it produces nothing. I don't understand this since the same regex works fine on the same st... | 1 | 2016-07-27T14:57:48Z | 38,616,782 | <p>Change <code>match</code> to <code>search</code> an then:</p>
<pre><code>text = 'hello, world <!-- comment -->'
comment = re.search('<!--(.*?)-->', text)
comment.group(1)
</code></pre>
<p>Output:</p>
<pre><code>' comment '
</code></pre>
| 0 | 2016-07-27T15:04:45Z | [
"python",
"regex"
] |
Extract HTML comments in Python, using regex or lxml? | 38,616,592 | <p>How do I extract all HTML-style comments from a document, using Python?</p>
<p>I've tried using a regex:</p>
<pre><code>text = 'hello, world <!-- comment -->'
re.match('<!--(.*?)-->', text)
</code></pre>
<p>But it produces nothing. I don't understand this since the same regex works fine on the same st... | 1 | 2016-07-27T14:57:48Z | 38,616,922 | <p>You have to use the re.findall() method to extract all substring that match a certain pattern.</p>
<p>re.match() will only check whether the pattern fits at the beginning of the string, while re.search() will only get you the first match within the string. For your purpose, re.findall() is definitely the right meth... | 1 | 2016-07-27T15:10:26Z | [
"python",
"regex"
] |
Extract HTML comments in Python, using regex or lxml? | 38,616,592 | <p>How do I extract all HTML-style comments from a document, using Python?</p>
<p>I've tried using a regex:</p>
<pre><code>text = 'hello, world <!-- comment -->'
re.match('<!--(.*?)-->', text)
</code></pre>
<p>But it produces nothing. I don't understand this since the same regex works fine on the same st... | 1 | 2016-07-27T14:57:48Z | 38,616,959 | <p>This seems to print the comment for me:</p>
<pre><code>from lxml import etree
txt = """<?xml version="1.0" encoding="UTF-8"?>
<clinical_study rank="220398">
<intervention_browse>
<!-- CAUTION: The following MeSH terms are assigned with an imperfect algorithm -->
<mesh_term>... | 1 | 2016-07-27T15:11:49Z | [
"python",
"regex"
] |
cqlsh won't connect on Linux | 38,616,858 | <p>I've tried all the measures from <a href="http://stackoverflow.com/questions/29121904/cassandra-cqlsh-connection-refused">this post</a> and <a href="http://wiki.apache.org/cassandra/GettingStarted" rel="nofollow">Cassandra doc</a>. </p>
<p>I've tried running all the versions of Cassandra including the latest releas... | 5 | 2016-07-27T15:07:50Z | 38,617,851 | <p>You are running into <a href="https://issues.apache.org/jira/browse/CASSANDRA-11850" rel="nofollow">CASSANDRA-11850</a>, where cqlsh breaks with Python 2.7.11+. This ticket has been marked as "Resolved" and a patch has been applied to Cassandra 3.9 which has not been released yet.</p>
<blockquote>
<p>I believe I... | 6 | 2016-07-27T15:52:53Z | [
"python",
"linux",
"cassandra",
"cqlsh"
] |
cqlsh won't connect on Linux | 38,616,858 | <p>I've tried all the measures from <a href="http://stackoverflow.com/questions/29121904/cassandra-cqlsh-connection-refused">this post</a> and <a href="http://wiki.apache.org/cassandra/GettingStarted" rel="nofollow">Cassandra doc</a>. </p>
<p>I've tried running all the versions of Cassandra including the latest releas... | 5 | 2016-07-27T15:07:50Z | 39,515,889 | <p>refer <a href="https://issues.apache.org/jira/browse/CASSANDRA-11850">https://issues.apache.org/jira/browse/CASSANDRA-11850</a></p>
<p>After setting environment variable</p>
<pre><code>CQLSH_NO_BUNDLED=TRUE
</code></pre>
<p>it resolved.</p>
<p>I use windows 7, python 2.7.12, cassandra 3.7</p>
| 6 | 2016-09-15T16:18:04Z | [
"python",
"linux",
"cassandra",
"cqlsh"
] |
Update continuous function in real time | 38,616,865 | <p>I can't figure how to plot a continuous function using Matplotlib. I got how to plot a scatterplot, but I would like a continuous plot.</p>
<p>Here is my code:</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.pyplot import autoscale
import matplotlib.animation as animation
import numpy
class MyPlo... | 1 | 2016-07-27T15:07:58Z | 38,617,432 | <p>You are only plotting a line with a single point at a time (which doesn't exist), so nothing shows up. If you replace <code>self.ax.plot</code> with <code>self.ax.scatter</code>, it plots correctly. </p>
<p>If you really want lines, you can just keep track of the last index and value and plot a line connecting th... | 2 | 2016-07-27T15:33:20Z | [
"python",
"matplotlib",
"plot"
] |
Update continuous function in real time | 38,616,865 | <p>I can't figure how to plot a continuous function using Matplotlib. I got how to plot a scatterplot, but I would like a continuous plot.</p>
<p>Here is my code:</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.pyplot import autoscale
import matplotlib.animation as animation
import numpy
class MyPlo... | 1 | 2016-07-27T15:07:58Z | 38,618,117 | <p>You can actually append values to a line plot in matplotlib:</p>
<pre><code>self.line.set_xdata(numpy.append(self.line.get_xdata(), self.index))
self.line.set_ydata(numpy.append(self.line.get_ydata(), val))
</code></pre>
<p>This way, you do not have to do any of the bookkeeping yourself.</p>
<p>More details can b... | 2 | 2016-07-27T16:05:24Z | [
"python",
"matplotlib",
"plot"
] |
django: customized token authentication | 38,616,880 | <p>I am doing APIs, and trying to use token. I want to achieve:
1, client issues a request to server with token in the header;
2, server verify the token and do something (one time).</p>
<p>Looking into the <a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/authentication.py#L43" ... | 0 | 2016-07-27T15:08:22Z | 38,641,578 | <p>First of all create model Token in models.py, also you need to create token_required decorator. whenever user login token create and when he logout token destroy.</p>
<p>login:</p>
<pre><code>def login(request):
username=request.payload.get('username')
password=request.payload.get('password')
user,err=... | 0 | 2016-07-28T16:08:36Z | [
"python",
"django",
"django-rest-framework"
] |
String extraction in Python / Pandas with repeated delimiter | 38,616,916 | <p>I have a data frame with a column that includes any combination of one or many variables, separated by a '/' delimiter, e.g.: </p>
<pre><code>Rd/MLERS
Rd
Rd
Rd/DLEPC/DLERS
SLERS
MLERS
</code></pre>
<p>Etc., etc. I want to extract the primary classifier, i.e.: the only or the first variable immediately p... | 2 | 2016-07-27T15:10:13Z | 38,616,968 | <p>use <code>str.split</code> and <code>str[0]</code> to access the first split, this will still return the initial string even without the separator:</p>
<pre><code>In [121]:
df["primaryEjecta1"] = df['text'].str.split('/').str[0]
df
Out[121]:
text primaryEjecta1
0 Rd/MLERS Rd
1 ... | 2 | 2016-07-27T15:12:17Z | [
"python",
"regex",
"python-3.x",
"pandas"
] |
String extraction in Python / Pandas with repeated delimiter | 38,616,916 | <p>I have a data frame with a column that includes any combination of one or many variables, separated by a '/' delimiter, e.g.: </p>
<pre><code>Rd/MLERS
Rd
Rd
Rd/DLEPC/DLERS
SLERS
MLERS
</code></pre>
<p>Etc., etc. I want to extract the primary classifier, i.e.: the only or the first variable immediately p... | 2 | 2016-07-27T15:10:13Z | 38,616,974 | <p>you can use powerful <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow">extract()</a> method:</p>
<pre><code>In [31]: df
Out[31]:
txt
0 Rd/MLERS
1 Rd
2 Rd
3 Rd/DLEPC/DLERS
4 SLERS
5 MLERS
... | 1 | 2016-07-27T15:12:29Z | [
"python",
"regex",
"python-3.x",
"pandas"
] |
How to print arrays of multiple data formats with control on precision of floats in Python? | 38,617,083 | <p>I am trying to print to file with np.savetxt arrays of multiple formats as show below:</p>
<pre><code>import numpy as np
f = open('./multiple_format.dat', 'w')
c1 = np.array(['A', 'B'])
n1 = np.array([1.545446367853, 6.8218467347894])
n2 = np.array([1.546715887182, 2.9718145367852])
np.savetxt(f, np.column_stack... | 0 | 2016-07-27T15:16:54Z | 38,618,880 | <p>The core of <code>savetxt</code> is</p>
<pre><code> for row in X:
try:
fh.write(asbytes(format % tuple(row) + newline))
</code></pre>
<p>It iterates on the rows of your array, and applies</p>
<pre><code> format % tuple(row)
</code></pre>
<p>to turn it into a string.</p>
<p><c... | 0 | 2016-07-27T16:46:58Z | [
"python",
"numpy"
] |
Get a hashable numpy memory view | 38,617,088 | <p>I want to hash numpy arrays without copying the data into a bytearray first.</p>
<p>Specifically, I have a contiguous read-only two-dimensional int64 numpy array <code>A</code> with unique rows. To be concrete, let's say:</p>
<pre><code>A = np.array([[1, 2], [3, 4], [5, 6]])
A.setflags(write=False)
</code></pre>
... | 1 | 2016-07-27T15:17:09Z | 38,620,614 | <p>I can't make sense of what you are trying to do.</p>
<p>When I create an array:</p>
<pre><code>In [111]: A=np.array([1,0,1,2,3,0,2])
In [112]: A.__array_interface__
Out[112]:
{'data': (173599672, False),
'descr': [('', '<i4')],
'shape': (7,),
'strides': None,
'typestr': '<i4',
'version': 3}
In [113]: A... | 0 | 2016-07-27T18:28:53Z | [
"python",
"arrays",
"numpy",
"hash"
] |
Why aren't metaclass's attributes searched in instance attribute lookups? | 38,617,090 | <p>According to Python 2.7.12 documentation, 3.4.2.3. Invoking Descriptors¶:</p>
<blockquote>
<p>The default behavior for attribute access is to get, set, or delete
the attribute from an objectâs dictionary. For instance, <code>a.x</code> has a
lookup chain starting with <code>a.__dict__['x']</code>, then
<... | 1 | 2016-07-27T15:17:14Z | 38,625,734 | <p>This is because the attribute lookup searches all <strong>bases</strong> of <code>type(a)</code>(<code>type(a).__mro__</code>), rather than all <strong>types</strong> of <code>type(a)</code>(<code>type(type(a))</code>).</p>
<p>Also, <code>type(self)</code> is not called continuously, so the lookup chain looks like ... | 1 | 2016-07-28T01:30:34Z | [
"python",
"attributes",
"metaclass",
"python-internals",
"getattribute"
] |
Reg ex to recognize leading zeros? | 38,617,125 | <p>I'm working on a program that searches all the files in my database and groups them based on what number is in the file name (from 001 to 100). </p>
<p>The only problem is that python interprets '001' as '1', but '001' is the exact number in the file name, and since I'm using regular expressions to search it doesn... | 0 | 2016-07-27T15:18:42Z | 38,617,258 | <p>You use <a href="https://docs.python.org/3/library/stdtypes.html#old-string-formatting" rel="nofollow">printf-style string formatting</a>. Using printf-style formatting, you may specify leading zereos and a field width.</p>
<p>Replace your <code>%s</code> with <code>%03d</code>:</p>
<pre><code>re.search("t.*%03d_z... | 0 | 2016-07-27T15:25:14Z | [
"python",
"regex",
"python-2.7",
"file",
"sorting"
] |
Reg ex to recognize leading zeros? | 38,617,125 | <p>I'm working on a program that searches all the files in my database and groups them based on what number is in the file name (from 001 to 100). </p>
<p>The only problem is that python interprets '001' as '1', but '001' is the exact number in the file name, and since I'm using regular expressions to search it doesn... | 0 | 2016-07-27T15:18:42Z | 38,617,504 | <p>Suggest that you build an index based on a flexible length number portion and use this to lookup the appropriate file. E.g.:</p>
<pre><code>>>> import re
>>>
>>> locations = ['_z{0:03d}_'.format(x) for x in range(1,101)]
>>>
>>> def create_zindex(names):
... reg = re.c... | 0 | 2016-07-27T15:36:09Z | [
"python",
"regex",
"python-2.7",
"file",
"sorting"
] |
Flask app.after_request() keeps user on the same page | 38,617,136 | <p>I have the following code:</p>
<pre><code>@app.after_request
def sense_inactive(response):
if session.has_key('usercode'): ## if user has logged in
usercode = session['usercode']
inactive_rmt = info.find_one({'usercode': usercode})['inactive']
curr_time = time.time()
last_req = session['req_tim... | -1 | 2016-07-27T15:19:04Z | 38,618,128 | <p>Assuming your code actually looks like this:</p>
<pre><code>if 'usercode' in session:
...
else: # if user hasn't logged in
return response
</code></pre>
<p>You're only returning a response if the user is not logged in. Remove the <code>else</code> and always return the response whether you do something e... | 2 | 2016-07-27T16:05:45Z | [
"python",
"flask"
] |
How form action works in django when using a class in views.py for form creation | 38,617,166 | <p>I am building a form in django based on my models. I have this in my views.py:</p>
<pre><code>class GroupCreateView(CreateView):
model = Group
form_class = GroupForm
template_name = 'ipaswdb/group/group_form.html'
</code></pre>
<p>the template is looking good with some nice form css and a datepicker a... | 1 | 2016-07-27T15:20:45Z | 38,617,834 | <p>Dont be afraid to read django's source code :P, the generic class has two methods: "get" and "post" (and "put" too, but it calls "post") you can overwrite any of them if you need to.</p>
<pre><code>class BaseCreateView(ModelFormMixin, ProcessFormView):
"""
Base view for creating an new object instance.
... | 1 | 2016-07-27T15:52:12Z | [
"python",
"django",
"forms",
"django-forms"
] |
NLTK FreqDist, plot the normalised counts? | 38,617,172 | <p>In NLTK, you can easily compute the counts for the words in a text, say, by doing</p>
<pre><code>from nltk.probability import FreqDist
fd = FreqDist([word for word in text.split()])
</code></pre>
<p>where text is a string.
Now, you can plot the distribution as </p>
<pre><code>fd.plot()
</code></pre>
<p>and that ... | 1 | 2016-07-27T15:21:05Z | 38,626,956 | <p>Pardon the lack of documentation. In <code>nltk</code>, <code>FreqDist</code> provides you with the raw counts (i.e. frequencies of words) in the text but <code>ProbDist</code> provides you with the probabilities of a word given a text.</p>
<p>For more information, you have to do some code reading: <a href="https:/... | 0 | 2016-07-28T04:09:47Z | [
"python",
"nlp",
"nltk",
"normalization",
"probability"
] |
NLTK FreqDist, plot the normalised counts? | 38,617,172 | <p>In NLTK, you can easily compute the counts for the words in a text, say, by doing</p>
<pre><code>from nltk.probability import FreqDist
fd = FreqDist([word for word in text.split()])
</code></pre>
<p>where text is a string.
Now, you can plot the distribution as </p>
<pre><code>fd.plot()
</code></pre>
<p>and that ... | 1 | 2016-07-27T15:21:05Z | 38,681,085 | <p>You can update <strong>fd[word]</strong> with <strong>fd[word] / total</strong></p>
<pre><code>from nltk.probability import FreqDist
text = "This is an example . This is test . example is for freq dist ."
fd = FreqDist([word for word in text.split()])
total = fd.N()
for word in fd:
fd[word] /= float(total)
f... | 1 | 2016-07-31T05:36:27Z | [
"python",
"nlp",
"nltk",
"normalization",
"probability"
] |
How to add self to ManyToManyField by default? | 38,617,178 | <p>Is it possible to add <code>self</code> - I mean the current object it's <code>ManyToManyField</code>? </p>
<pre><code>class City(models.Model):
name = models.CharField(max_length=80)
country = models.ForeignKey('Country')
close_cities = models.ManyToManyField('City',blank=True, related_name='close_citi... | 2 | 2016-07-27T15:21:23Z | 38,618,504 | <p>In this case <code>pre_save</code> signal will be better solution.</p>
<p>In Your solution <code>city.save</code> calls <code>add_self_into_many_to_many_field</code>. <code>instance.save</code> calls <code>add_self_into_many_to_many_field</code>. and so on...</p>
<pre><code>@receiver(pre_save, sender=myapp_models.... | 0 | 2016-07-27T16:26:20Z | [
"python",
"django",
"django-models",
"django-signals"
] |
kivy on_dropfile multiple bindings | 38,617,194 | <p>Is it possible to bind <code>on_dropfile</code> in multiple objects? Or is it always just one bind?</p>
<p>I've decalred class</p>
<pre><code>class dropFile(Label):
def __init__(self, **kwargs):
super(dropFile, self).__init__(**kwargs)
Window.bind(mouse_pos=lambda w, p: setattr(helper, 'mpos', ... | 0 | 2016-07-27T15:22:04Z | 38,669,114 | <p>Now it makes more sense to me. In this case, why don't you just make a list and execute whatever function you like on <code>Window.on_dropfile</code>?</p>
<pre><code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.core.window import Window
from kivy.uix.boxlayout im... | 0 | 2016-07-30T00:09:58Z | [
"python",
"drag-and-drop",
"kivy",
"kivy-language"
] |
Scrapy NameError: name 'filename' is not defined | 38,617,242 | <p>I'm completely new to Python and I'm doing summer independent practical project about web scraping where I'm trying to use Scrapy. So far I've used <a href="http://doc.scrapy.org/en/1.1/intro/tutorial.html" rel="nofollow">http://doc.scrapy.org/en/1.1/intro/tutorial.html</a> to begin, but due to tutorial spider not w... | -1 | 2016-07-27T15:24:28Z | 38,620,948 | <pre><code>import scrapy
class DmozSpider(scrapy.Spider):
name = "turo"
allowed_domains = ["turotarjoo.com"]
start_urls = [
"http://turotarjoo.com/siipiravintola/",
"http://turotarjoo.com/info/"
]
def parse(self, response):
filename = response.url.split("/")[-1] + '.html'
... | -1 | 2016-07-27T18:49:12Z | [
"python",
"web-scraping",
"scrapy"
] |
How does one verify Python script is a pure math function? | 38,617,314 | <p>I have a Python project that dynamically loads Python scripts from a set of specified directories and executes an expected function off of them. To harden the security of this application, I would like to analyze the scripts to ensure that they are just pure math functions and, therefore, not interacting with any s... | 2 | 2016-07-27T15:28:31Z | 38,617,415 | <p>It appears that sandboxing to disable things like I/O, network etc.. isn't fully reliable.
Since Python doesn't have any permission system embedded, it'll be pretty hard to do what you want.</p>
| 1 | 2016-07-27T15:32:32Z | [
"python",
"python-3.x",
"security",
"scripting"
] |
Pandas extract multicharacter regex | 38,617,383 | <p>I would like to extract an expression each time it occurs in an element of a Pandas DataFrame as an array but get an error every time I use a multiple character expression. Why am I getting this error? How do I make the extraction work as expected?</p>
<h1>MWE</h1>
<pre><code>import pandas as pd
wiki = ["In the... | 1 | 2016-07-27T15:31:23Z | 38,617,526 | <p>The <code>extractall()</code> method has a <a href="https://github.com/pydata/pandas/issues/13382" rel="nofollow">bug</a> which should be fixed in pandas 0.18.2, which should be released pretty soon, so let's be patient or risk a little bit and use a <a href="http://pandas.pydata.org/" rel="nofollow">beta 0.18.2 ver... | 1 | 2016-07-27T15:37:15Z | [
"python",
"string",
"pandas"
] |
Google BigQuery - Python Query not being parsed correctly | 38,617,633 | <p>I am trying to set up a simple Google BigQuery application using the Python API. I followed the quick-start guide: </p>
<pre><code>import argparse
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from oauth2client.client import GoogleCredentials
def main(project_id):
p... | 1 | 2016-07-27T15:41:38Z | 38,617,703 | <p>When the query string gets concatenated by the python parser, you're left with the word <code>ASCLIMIT</code> which isn't valid BQ SQL. Add a space after <code>ASC</code> in the query and you should be OK.</p>
<pre><code>{
'query': (
'SELECT ticker,close1 ' # Space at the end of this line too
... | 3 | 2016-07-27T15:45:09Z | [
"python",
"google-app-engine",
"google-bigquery"
] |
Print actual XPath using Python 2.7 ElementTree Library | 38,617,736 | <p>I have the following python code:</p>
<pre><code>from xml.etree import ElementTree as et
from optparse import OptionParser
import ConfigParser
import fileinput, sys
import os
config_file = 'ClientConfig.xml'
tree = et.parse(config_file)
root = tree.getroot()
for element in root.findall("/client/config/TEST_CLIEN... | 0 | 2016-07-27T15:46:37Z | 38,618,028 | <p>You would need to use <a href="http://stackoverflow.com/questions/1577293/how-to-get-path-of-an-element-in-lxml"><code>lxml.etree</code> and <code>getpath()</code> method</a> for it:</p>
<pre><code>for element in root.findall("/client/config/TEST_CLIENT"):
for elem in element.iter(tag='Item'):
print(tre... | 0 | 2016-07-27T16:01:20Z | [
"python",
"xml",
"python-2.7",
"xpath"
] |
Can Only Scrape Portion of Table with Python and BS4 | 38,617,746 | <p>I am trying to scrape the table with the draft order from <a href="https://en.wikipedia.org/wiki/2012_NFL_Draft" rel="nofollow">this wikipedia page</a></p>
<p>I am having a problem where the only data that is being pulled is from the rows with a different background color (the ones with an '*' next to the round num... | 0 | 2016-07-27T15:47:06Z | 38,617,957 | <p>That's because of the <code>if len(cols) == 9:</code> condition. You need to:</p>
<ul>
<li>skip the first header row</li>
<li>look for both <code>td</code> and <code>th</code> elements inside every <code>tr</code></li>
<li>skip rows with count less than 6</li>
</ul>
<p>Fixed version:</p>
<pre><code>for row in pla... | 1 | 2016-07-27T15:58:21Z | [
"python",
"beautifulsoup",
"python-requests",
"wikipedia",
"bs4"
] |
Extract comments from any website (Comments in the .js file ) in python3 using PhantomJS | 38,617,808 | <p>I want to extract comments from the link (WebCrawler) .
This code is from <a href="https://www.rt.com/usa/353493-clinton-speech-affairs-silence/" rel="nofollow">this</a> link (Ctrl+u).</p>
<pre><code> <div class="spot-im-frame-inpage" data-post-id="353493"></div><script type="text/javascript">
!... | -2 | 2016-07-27T15:50:49Z | 38,618,412 | <p>Since all the comments are tied to the class message-entities. I would make the crawler extract the html for each element with that class. The easiest way to use phantomJS with python is via Selenium or Ghostdriver. If you're not stuck to using python then I'd suggest using something like node-horseman or casperjs t... | 1 | 2016-07-27T16:21:15Z | [
"javascript",
"python",
"phantomjs"
] |
Apache2 and context path for virtual host with Django and AngularJS | 38,617,860 | <p>I had the following working Django configuration:</p>
<pre><code>WSGIScriptAlias / /MyDjangoProjectFolder/MyDjangoProject/wsgi.py
WSGIPythonPath /MyDjangoProjectFolder
<Directory /MyDjangoProjectFolder/MyDjangoProject>
<Files wsgi.py>
Order deny,allow
Require all granted
</Files... | 8 | 2016-07-27T15:53:16Z | 38,798,734 | <p>For the <em>Directory</em> you need to add the follow directive:</p>
<pre><code> Require all granted
</code></pre>
<p>or some equivalent for the access to the directory. Apache might not have access to view that directory or be configured to have access to it. You also need to make sure that Apache has permissio... | 0 | 2016-08-05T22:48:48Z | [
"python",
"django",
"apache",
"virtualhost"
] |
need to package jinja2 template for python | 38,617,900 | <p>(UPDATE: I've made a better question with a better answer <a href="http://stackoverflow.com/questions/38642557/how-to-load-jinja-template-directly-from-filesystem">here</a>. I was going to delete this question, but some of the answers might prove useful to future searchers.)</p>
<p>My question is just about identi... | 0 | 2016-07-27T15:54:55Z | 38,620,915 | <p>I don't know the process involved with packaging but I figure since Jinja2 is written in Python, the process would be the same as packaging any other application in Python. </p>
<p>Here are a few links that may be useful to you:</p>
<ul>
<li>The Hitchhiker's Guide to Python (great resource): <a href="http://docs.p... | 1 | 2016-07-27T18:47:19Z | [
"python",
"templates",
"module",
"jinja2",
"setup.py"
] |
need to package jinja2 template for python | 38,617,900 | <p>(UPDATE: I've made a better question with a better answer <a href="http://stackoverflow.com/questions/38642557/how-to-load-jinja-template-directly-from-filesystem">here</a>. I was going to delete this question, but some of the answers might prove useful to future searchers.)</p>
<p>My question is just about identi... | 0 | 2016-07-27T15:54:55Z | 38,622,261 | <p>I've discovered a WORKAROUND, <a href="http://kagerato.net/articles/software/libraries/jinja-quickstart.html" rel="nofollow">here</a>. In this usage, the template is not part of a module or package; it is loaded directly from the file system. File system:</p>
<pre><code>./index.py
./template.html
</code></pre>
<... | 1 | 2016-07-27T20:06:58Z | [
"python",
"templates",
"module",
"jinja2",
"setup.py"
] |
need to package jinja2 template for python | 38,617,900 | <p>(UPDATE: I've made a better question with a better answer <a href="http://stackoverflow.com/questions/38642557/how-to-load-jinja-template-directly-from-filesystem">here</a>. I was going to delete this question, but some of the answers might prove useful to future searchers.)</p>
<p>My question is just about identi... | 0 | 2016-07-27T15:54:55Z | 38,630,259 | <p>Maybe an issue is in PYTHONPATH . According to Python documantation <a href="https://docs.python.org/2.7/tutorial/modules.html#the-module-search-path" rel="nofollow">https://docs.python.org/2.7/tutorial/modules.html#the-module-search-path</a>
it searches for modules in :</p>
<blockquote>
<ul>
<li>the directory ... | 0 | 2016-07-28T07:53:28Z | [
"python",
"templates",
"module",
"jinja2",
"setup.py"
] |
How to reintroduce "no prompt to save" option in IDLE if file has never been saved | 38,617,902 | <p>Currently I am using the latest version of Python 2 on my laptop (2.7.12), along with IDLE version 2.7.12 and TK version 8.5.15, in case those are relevant.</p>
<p>On my school computers a slightly older version of IDLE is being used (version 2.7a0) which has, in the "general" tab of the IDLE preferences (under Opt... | 0 | 2016-07-27T15:54:49Z | 38,622,774 | <p>I am puzzled by this report. The Autosave Preferences section is still present. idlelib.configDialog.py, class ConfigDialog, method CreatePageGeneral has (should have) this code at lines 384 and 396.</p>
<pre><code> frameSave = LabelFrame(frame, borderwidth=2, relief=GROOVE,
text=' A... | 0 | 2016-07-27T20:39:23Z | [
"python",
"save",
"preferences",
"prompt",
"python-idle"
] |
Python NLTK Word Tokenize UnicodeDecode Error | 38,617,910 | <p>I get the error when trying the below code. I try to read from a text file and tokenize the words using nltk. Any ideas? The text file can be found <a href="https://pythonprogramming.net/static/downloads/short_reviews/positive.txt" rel="nofollow">here</a></p>
<pre><code>from nltk.tokenize import word_tokenize
short... | -1 | 2016-07-27T15:55:34Z | 38,623,859 | <p>Looks like this text is encoded in Latin-1. So this works for me:</p>
<pre><code>import codecs
with codecs.open("positive.txt", "r", "latin-1") as inputfile:
text=inputfile.read()
short_pos_words = word_tokenize(text)
print len(short_pos_words)
</code></pre>
<p>You can test for different en... | 0 | 2016-07-27T21:55:22Z | [
"python",
"nltk",
"python-unicode"
] |
Python NLTK Word Tokenize UnicodeDecode Error | 38,617,910 | <p>I get the error when trying the below code. I try to read from a text file and tokenize the words using nltk. Any ideas? The text file can be found <a href="https://pythonprogramming.net/static/downloads/short_reviews/positive.txt" rel="nofollow">here</a></p>
<pre><code>from nltk.tokenize import word_tokenize
short... | -1 | 2016-07-27T15:55:34Z | 38,625,300 | <p>Your file is encoded using <strong>"latin-1"</strong>.</p>
<pre><code>from nltk.tokenize import word_tokenize
import codecs
with codecs.open("positive.txt", "r", "latin-1") as inputfile:
text=inputfile.read()
short_pos_words = word_tokenize(text)
print short_pos_words
</code></pre>
| 0 | 2016-07-28T00:31:53Z | [
"python",
"nltk",
"python-unicode"
] |
How to set a plot widget to Power Spectrum mode in PyQtGraph? | 38,617,954 | <p>I have data being plotted and I need to display its Fourier transform in real time. Right clicking on the plot and going through the Plot Options menu lets me select Power Spectrum mode, but is there any way to have this mode be active when the plot widget is created in the first place? I need the Fourier transform ... | 0 | 2016-07-27T15:58:11Z | 40,009,377 | <p>Seems like this has been out there a while, but since it's something others can eventually benefit from, I'll add my 2 cents:</p>
<p>Easiest way I found to accomplish this is with programmatically hitting the check box just after creating the plot. The PlotItem created has a self.ctrl menu, so doing a:</p>
<pre><... | 1 | 2016-10-12T22:25:31Z | [
"python",
"plot",
"pyqtgraph"
] |
How to generate request to the ADFS, get session and authenticate user on Django server? | 38,618,068 | <p>I'm configure Web SSO authentication by using ADFS on <a href="https://technet.microsoft.com/en-us/library/dd378921(v=ws.10).aspx" rel="nofollow">this</a> guide. ÐÑ back-end developed using Django. How to generate Django request for user authentication? As I understand request looks like this.:</p>
<p><em>decoded... | 0 | 2016-07-27T16:03:07Z | 38,634,630 | <p>Why don't you use directly the SAML protocol?. ADFS supports SAML and I think is easier to setup than ws-fed (and also more adopted).</p>
<p>You will need to add SAML support to the django app, in order to do that you have 2 alternatives:</p>
<ul>
<li><a href="https://github.com/KristianOellegaard/django-saml-serv... | 0 | 2016-07-28T11:09:05Z | [
"python",
"django",
"authentication",
"single-sign-on",
"adfs"
] |
Django app works on runserver, but fails on uwsgi | 38,618,097 | <p>python3 manage.py runserver works fine, but running on nginx/uwsgi Django application doesn't work.
Uwsgi log:</p>
<pre><code>binary reloading uWSGI...
chdir() to /
closing all non-uwsgi socket fds > 2 (max_fd = 1024)...
found fd 3 mapped to socket 0 (/home/nginx/pythonworld.sock)
running /usr/local/bin/uwsgi
[u... | 0 | 2016-07-27T16:04:27Z | 38,619,994 | <p>Problem was solved by changing permissions allowing read source code by uwsgi user.</p>
| 0 | 2016-07-27T17:52:16Z | [
"python",
"django",
"python-3.x",
"uwsgi"
] |
advanced aggregation pandas python | 38,618,141 | <p>If I have a simple table, such as:</p>
<pre><code>index location col1 col2 col3 col4
1 a TRUE yes 1 4
2 a FALSE null 2 6
3 b TRUE null 6 3
4 b TRUE no 3 4
5 b F... | 2 | 2016-07-27T16:06:27Z | 38,618,218 | <p>Use <code>groupby</code> and <code>agg</code></p>
<pre><code>funcs = dict(
col1=dict(Trump=lambda x: x.any()),
col3='sum',
col4=dict(Avg='mean')
)
df.groupby('location').agg(funcs)
</code></pre>
<p><a href="http://i.stack.imgur.com/BEA5T.png" rel="nofollow"><img src="http://i.stack.imgur.com/BEA5T.png... | 4 | 2016-07-27T16:11:07Z | [
"python",
"pandas"
] |
Python generating a range of numbers that have no same digits & unique | 38,618,203 | <p>i am trying to figure out how to generate a list of numbers that are not only unique but also have no similar digits
The purpose is to crack sample hashes using crypt, what i know is the passwords are unique, no repeating digits and up to 6 digits</p>
<p>Example></p>
<pre><code>[1,2,3,4,5,6,7,8,9...120, 123,124,12... | -1 | 2016-07-27T16:10:14Z | 38,618,310 | <p>Use <code>itertools.permutations()</code> on an increasing number of repeated digits, up to 9, combining these with all digits between 1 and 9 (to prevent generating numbers with a leading 0).</p>
<pre><code>from itertools import permutations
def generate_unique_numbers():
yield 0
for i in range(10):
... | 3 | 2016-07-27T16:16:22Z | [
"python"
] |
Python generating a range of numbers that have no same digits & unique | 38,618,203 | <p>i am trying to figure out how to generate a list of numbers that are not only unique but also have no similar digits
The purpose is to crack sample hashes using crypt, what i know is the passwords are unique, no repeating digits and up to 6 digits</p>
<p>Example></p>
<pre><code>[1,2,3,4,5,6,7,8,9...120, 123,124,12... | -1 | 2016-07-27T16:10:14Z | 38,618,355 | <p>You could check if the length of the number when represented as a string is the same when the digits in the number are placed in a set:</p>
<pre><code>def unique_count():
for i in range(1000000):
if len(str(i)) == len(set(str(i))):
yield i
</code></pre>
<p>The set eliminates duplicate digit... | 3 | 2016-07-27T16:18:43Z | [
"python"
] |
Python generating a range of numbers that have no same digits & unique | 38,618,203 | <p>i am trying to figure out how to generate a list of numbers that are not only unique but also have no similar digits
The purpose is to crack sample hashes using crypt, what i know is the passwords are unique, no repeating digits and up to 6 digits</p>
<p>Example></p>
<pre><code>[1,2,3,4,5,6,7,8,9...120, 123,124,12... | -1 | 2016-07-27T16:10:14Z | 38,618,612 | <p>You can use the generate function below for a maximum number i then it will generate a liste of digits smaller then i unique, and without a digit repeated.</p>
<pre><code>def isDigitsRepeated(integer):
n = str(integer)
digits = []
for digit in n:
if digit in digits:
return True
... | 0 | 2016-07-27T16:32:21Z | [
"python"
] |
Python - create txt file on the fly and send it via FTP? | 38,618,261 | <p>So i am currently creating a text file from a jinja2 template on the fly and having it be downloaded by the users browser, however i want to add an option to send it somewhere via FTP (all the FTP details are predefined and wont change)
how do i create the file to be sent?</p>
<p>Thanks</p>
<p>code:</p>
<pre><co... | 0 | 2016-07-27T16:12:58Z | 38,618,578 | <p>You can use the <code>tempfile</code> module to create a named temporary file.</p>
<pre><code>import tempfile
with tempfile.NamedTemporaryFile() as temp:
temp.write(content)
temp.flush()
filename = temp.name
session.storbinary('STOR {0}'.format(file_name), temp)
</code></pre>
| 2 | 2016-07-27T16:30:18Z | [
"python",
"ftp"
] |
Python - create txt file on the fly and send it via FTP? | 38,618,261 | <p>So i am currently creating a text file from a jinja2 template on the fly and having it be downloaded by the users browser, however i want to add an option to send it somewhere via FTP (all the FTP details are predefined and wont change)
how do i create the file to be sent?</p>
<p>Thanks</p>
<p>code:</p>
<pre><co... | 0 | 2016-07-27T16:12:58Z | 38,618,738 | <p>Here is a working example using <code>BytesIO</code> under <code>io</code> module. Code is tested and works.</p>
<pre><code>import ftplib
import io
session = ftplib.FTP('192.168.1.1','USERNAME','PASSWORD')
# session.set_debuglevel(2)
buf=io.BytesIO()
buf.write("test string")
buf.seek(0)
session.storbinary("STOR tes... | 0 | 2016-07-27T16:39:09Z | [
"python",
"ftp"
] |
Precision Difference: NumPy Object Array vs. Float Array | 38,618,414 | <p>I understand that the precision of a NumPy float array's element is limited by the machine epsilon.</p>
<p>However, I'm struggling to understand why specifying the array's datatype as a Python object, instead of as the default float, results in the array storing the precise value I feed it. Can someone please expla... | 0 | 2016-07-27T16:21:20Z | 38,618,487 | <p>That's just a matter of display formatting you're seeing. You're not actually getting a more precise number either way; it's just that the <code>precision=64</code> display setting you set doesn't apply to object arrays. It only applies to arrays of floating-point dtype.</p>
<p>If you print more digits of the conte... | 3 | 2016-07-27T16:25:19Z | [
"python",
"numpy",
"precision",
"eps"
] |
Precision Difference: NumPy Object Array vs. Float Array | 38,618,414 | <p>I understand that the precision of a NumPy float array's element is limited by the machine epsilon.</p>
<p>However, I'm struggling to understand why specifying the array's datatype as a Python object, instead of as the default float, results in the array storing the precise value I feed it. Can someone please expla... | 0 | 2016-07-27T16:21:20Z | 38,618,772 | <p>I agree that the issue you with floats is a matter of display, not precision. </p>
<p>But there is a different issue with long integers. Python has a long integer type that does not have a <code>numpy</code> dtype. </p>
<pre><code>In [87]: x=12312312312311231231241241242342
In [88]: x
Out[88]: 123123123123112312... | 0 | 2016-07-27T16:41:05Z | [
"python",
"numpy",
"precision",
"eps"
] |
I need to split a python list into several python lists but the new lists need to contain fields between certain strings | 38,618,526 | <p>I have a fairly large Python 2.7 list containing strings like this: </p>
<pre><code>biglist = ['A','B1','C00','D','A','1','2000','A','X','3','1','C','D','A','B','C']
</code></pre>
<p>I need to cut this up in several seperate lists cutted each time it finds a 'A' string in the list and then that new list contains e... | 0 | 2016-07-27T16:27:32Z | 38,618,698 | <p>This might not be elegant, but should do the trick:</p>
<pre><code>biglist = ['A','B','C','D','A','1','2','A','X','3','1','C','D','A','B','C']
</code></pre>
<p>Make the list into a string first:</p>
<pre><code>bigstring=" ".join(biglist)
</code></pre>
<p>Split on "A", sneakily insert A again</p>
<pre><code>fina... | 1 | 2016-07-27T16:37:06Z | [
"python",
"python-2.7"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.