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 |
|---|---|---|---|---|---|---|---|---|---|
convert curl to requests using multipart/mixed in python | 37,686,247 | <p>I'm trying to convert the following curl post to a Python request:</p>
<pre><code>curl -k -i -H "Content-Type: multipart/mixed" -X POST --form
'session.id=e7a29776-5783-49d7-afa0-b0e688096b5e' --form 'ajax=upload'
--form 'file=@myproject.zip;type=application/zip' --form 'project=MyProject;type/plain' https://loca... | 1 | 2016-06-07T18:00:34Z | 37,710,239 | <p>I found the answer after trying out some of the examples from <a href="http://docs.python-requests.org/en/master/user/quickstart/#make-a-request" rel="nofollow">requests</a> site and finally it worked.</p>
<pre><code>data = {'ajax':'upload','project':'test','session.id':sessionId}
files = {'file':('projects.zip',o... | 1 | 2016-06-08T18:30:32Z | [
"python",
"curl",
"python-requests"
] |
convert curl to requests using multipart/mixed in python | 37,686,247 | <p>I'm trying to convert the following curl post to a Python request:</p>
<pre><code>curl -k -i -H "Content-Type: multipart/mixed" -X POST --form
'session.id=e7a29776-5783-49d7-afa0-b0e688096b5e' --form 'ajax=upload'
--form 'file=@myproject.zip;type=application/zip' --form 'project=MyProject;type/plain' https://loca... | 1 | 2016-06-07T18:00:34Z | 37,750,789 | <p>For the future reference I recommend you to check this online tool:
<a href="http://curl.trillworks.com/" rel="nofollow">http://curl.trillworks.com/</a>
it converts curl to python requests, node and php.
It has helped my multiple times.</p>
| 0 | 2016-06-10T14:29:39Z | [
"python",
"curl",
"python-requests"
] |
Install pymongo on macosx | 37,686,300 | <p>I want to install pymongo on my macosx. Using <code>python -m pip install pymongo</code>, I get this error message :</p>
<pre><code>Exception:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/basecommand.py", line 209, in main
status = self.run(options, args)
File "... | 0 | 2016-06-07T18:03:59Z | 37,686,324 | <p>It's because you're not running it as root. The safest thing to do is use the "user" mode to install your requirements in your home directory.</p>
<p>E.g.:</p>
<pre><code>python -m pip install --user pymongo
</code></pre>
| 1 | 2016-06-07T18:05:22Z | [
"python",
"pymongo"
] |
redirecting python output to a log file | 37,686,309 | <p>I have a simple request. I have a python file with a list of variables. I want to execute the python file and get the output of that written to the log file. What is the simple way to do this?
Example:
var.py has the following code</p>
<pre><code>x = (10,11,12)
y = str("case when id =1 then gr8 else ok end")
z = d... | 1 | 2016-06-07T18:04:45Z | 37,686,525 | <p><a href="http://www.tutorialspoint.com/python/python_files_io.htm" rel="nofollow">Input/Output Operations</a> with Python is easy.</p>
<p>You can open, write and close a file manually, ie.:</p>
<pre><code>text_file = open("OutputFile.txt", "w")
text_file.write("Write blablabla into a file")
text_file.close()
</cod... | 1 | 2016-06-07T18:17:38Z | [
"python",
"variables",
"output"
] |
redirecting python output to a log file | 37,686,309 | <p>I have a simple request. I have a python file with a list of variables. I want to execute the python file and get the output of that written to the log file. What is the simple way to do this?
Example:
var.py has the following code</p>
<pre><code>x = (10,11,12)
y = str("case when id =1 then gr8 else ok end")
z = d... | 1 | 2016-06-07T18:04:45Z | 37,686,550 | <p>Use the python logger functionality</p>
<blockquote>
<pre><code>import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
x = (10,11,12)
y = str("case when id =1 then gr8 else ok end")
logging.debug(x)
logging.debug(y)
</code></pre>
</blockquote>
| 0 | 2016-06-07T18:18:39Z | [
"python",
"variables",
"output"
] |
python jedi: how to retrieve methods of instances? | 37,686,311 | <p>I built simple text editor with some accessibility feature for screen reading software.
I'm using Python for .NET (pythonnet) to show a form containing a rich text box.
When user press tab after a period it pop-ups a context menu with completions for selected element.
Ok, it works fine with Python objects, but it do... | 10 | 2016-06-07T18:04:47Z | 39,013,916 | <p>This looks like a bug, where <code>jedi.evaluate.representation.Instance.__getattr__()</code> mistakenly blocks evaluation of <code>.names_dict</code>. I added a <a href="https://github.com/davidhalter/jedi/pull/763" rel="nofollow">pull request</a> to the jedi repository to fix this. In the mean time, you can either... | 6 | 2016-08-18T08:57:28Z | [
"python",
"autocomplete",
"python-jedi"
] |
How to run the same task in parallel on multiple hosts with different parameters using fabric? | 37,686,354 | <p>demo.py</p>
<pre><code>from fabric.api import env, run,execute
env.hosts = ['10.1.1.100','10.1.1.200']
env.remotePath = {'10.1.1.100':'/home','10.1.1.200':'/var'}
env.parallel=True
def mytask(remotePath):
run('ls %s' % remotePath)
def test():
execute(mytask,env.remotePath[env.host])
</code></pre>
<p>fab... | 0 | 2016-06-07T18:07:15Z | 37,695,996 | <p>Use <code>host_string</code> to get the current host, then the command/argument you want to use.</p>
<pre><code>@parallel
def mytask():
host_ip = env.host_string
remote_path = env.remotePath[host_ip]
run('ls %s' % remote_path)
</code></pre>
<p>According to Fabric's API doc: <a href="http://docs.fabfile.org/e... | 0 | 2016-06-08T07:31:41Z | [
"python",
"fabric"
] |
Condition based on nth row above or below current row - Python | 37,686,449 | <p>I want to replicate something similar to the "Multi Row Formula" tool in Alteryx. I am currently reading a csv file and would like to be able to set a value in a list if the value of another row in the same tested column is true.</p>
<p>Sample Data</p>
<pre><code>**Country**
China
India
Brazil
Indonesia
</code></p... | 0 | 2016-06-07T18:12:21Z | 37,686,680 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html" rel="nofollow"><code>shift</code></a> to build a Boolean array of where the <code>'Y'</code> values should appear, then use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofoll... | 1 | 2016-06-07T18:26:29Z | [
"python",
"pandas"
] |
Equation not showing up in Canvas | 37,686,489 | <p>Hey guys I am trying to write a code for a small program and everything works fine but I can't get my whole math equation (C = A + B) or any of its variants to show up in Canvas. here is my code below, any help would be appreciated. The user inputs their first number, then inputs the operator (+, -, *, /) then a sec... | 1 | 2016-06-07T18:14:52Z | 37,687,547 | <p>Your functions <code>Add</code>, <code>Subtract</code>, <code>Multiply</code>, <code>Divide</code> don't return anything, so when you call <code>D = Add(1 + 1)</code>, D is None. So just put <code>return</code> instead of <code>C =</code>:</p>
<pre><code>def Add(A, B):
return A + B
def Subtract(A, B):
retur... | 1 | 2016-06-07T19:15:25Z | [
"python",
"function",
"canvas",
"tkinter",
"equation"
] |
Calculating mean or median in one function in numpy | 37,686,609 | <p>I have function that is supposed to compute, depending on user input, either the mean or median of a numpy.array. I have written it like this </p>
<pre><code> import numpy as np
...
if input=='means':
return np.mean(matrix, axis=1)
if input=='median':
return np.median(matrix, axis=1)
</code></pre>
<p... | 1 | 2016-06-07T18:22:28Z | 37,686,798 | <p>If your input string is <code>mean</code> instead of <code>means</code>, you could do:</p>
<pre><code>return getattr(np, input)(matrix, axis=1)
</code></pre>
<p>Here the <code>getattr</code> call grabs the function you want from the numpy library. Then the second set of parentheses calls that function.</p>
| 2 | 2016-06-07T18:33:44Z | [
"python",
"arrays",
"numpy",
"mean"
] |
Calculating mean or median in one function in numpy | 37,686,609 | <p>I have function that is supposed to compute, depending on user input, either the mean or median of a numpy.array. I have written it like this </p>
<pre><code> import numpy as np
...
if input=='means':
return np.mean(matrix, axis=1)
if input=='median':
return np.median(matrix, axis=1)
</code></pre>
<p... | 1 | 2016-06-07T18:22:28Z | 37,686,849 | <p>I don't think you need something specific to NumPy.</p>
<p>For example:</p>
<pre><code>def myFunc(matrix, func, axis=1):
return func(matrix)
</code></pre>
<p>Then, to use the function:</p>
<pre><code>import numpy as np
#Create random matrix (10, 10)
mat = np.random.randint(100, size=(10, 10))
print myFunc(m... | 2 | 2016-06-07T18:36:40Z | [
"python",
"arrays",
"numpy",
"mean"
] |
File output to terminal | 37,686,697 | <p>Working in python, and databases in a class, my teacher told me to write the commands I would usually do in terminal using sqlite3 in a file, and then he outputted it to the terminal with a command that used the "<" symbol.</p>
<p>The file content is basically this </p>
<pre><code>CREATE TABLE palavras(
count I... | 2 | 2016-06-07T18:28:01Z | 37,686,762 | <p>Just load your db file with sqlite3 then pipe in the file containing the sql commands :</p>
<pre><code>sqlite3 file.db < file.sql
</code></pre>
| 1 | 2016-06-07T18:32:00Z | [
"python",
"sqlite",
"sqlite3"
] |
Will this implementation of a prime sieve work for all primes? or is it just a fluke(Python) | 37,686,767 | <pre><code>p = 2
for i in range(3,10000000000000000,2):
if p%i >= 1:
print(i)
p = p*(i*i)
</code></pre>
<p>I've tested it and it seems to work on at least the first 100 primes, will it accurately return primes indefinitely?(theoretically not literally).</p>
| 0 | 2016-06-07T18:32:19Z | 37,687,477 | <p>Your limit (besides code correctness, which the comments have been pointing out) is going to be based on the maximum integer that Python allows. It turns out Python has theoretically infinite integer precision -- limited by memory.</p>
<p><a href="https://docs.python.org/2/library/stdtypes.html#numeric-types-int-f... | 1 | 2016-06-07T19:11:14Z | [
"python",
"primes",
"sieve"
] |
Should I pass the broadcast variable or broadcast.value() into my RDD[custom object]? | 37,686,810 | <p>I have some fairly large lists that I need to access within each of the objects that comprise my RDD. So after I broadcast these lists, should I be passing in the broadcast variable or the broadcast.value() into each of the objects? I don't want the list to be replicated for each object, but for each object to be ab... | 0 | 2016-06-07T18:34:26Z | 37,688,409 | <p>Depends what you want <code>self.BROADCASTED</code> to contain. I'm assuming you've simplified your method <code>foo</code> for this example, but because of that it's not clear what the purpose of <code>foo</code> is.</p>
<p>If you want it to contain <code>[a,b,c,..]</code>, then do <code>broadcasted_list.value()</... | 2 | 2016-06-07T20:09:40Z | [
"python",
"apache-spark",
"pyspark",
"broadcast"
] |
Django: Set initial value for ForiegnKey in a CreateView | 37,686,875 | <p>I'm trying to create a view of type <code>CreateView</code>. This view will take the <code>form_class = CourseForm</code> that I created and excluded some fields in it. The <code>instructor</code> field is a foriegnKey and I don't want the user to be able to control it in the form. It's a field that depends on the s... | 0 | 2016-06-07T18:37:53Z | 37,687,073 | <p>If you want to set the initial value of <code>instructor</code> field, you shouldn't exclude it from the form. You could instead make the field hidden.</p>
<p>Or you could include that in the <code>exclude</code> list, but then you shouldn't override <code>get_initial</code> method, but do the assignment manually:<... | 1 | 2016-06-07T18:48:36Z | [
"python",
"django",
"django-1.9"
] |
Python / MySQL Select returns None with %s | 37,686,901 | <p>I'm currently working on learning Python and I'm already stuck on a strange problem.</p>
<p>I'm getting urls from a website using <em>beautifulsoup</em>, which I can already save to a mysql database. Now I want to let the script first check if a crawled url is already in the database. </p>
<p>The query looks like ... | 1 | 2016-06-07T18:39:09Z | 37,687,164 | <p>thanks to alexce i found the problem. </p>
<p>im now using: </p>
<pre><code>cursor.execute(check_url, (href, ))
</code></pre>
<p>the select now looks like this ('' removed)</p>
<pre><code>check_url = "SELECT url FROM shop_instantgaming " \
"WHERE url = %s"
</code></pre>
<p>thank you!</p>
| 0 | 2016-06-07T18:53:58Z | [
"python",
"mysql",
"beautifulsoup"
] |
How to embed a Python script into HTML | 37,687,080 | <p>Is it possible to embed a python script into HTML? For example:</p>
<pre><code>name = input("What is your name?")
print("Hi, " + name)
</code></pre>
<p>If so, can it use modules, for example <code>datetime, os, sys, random</code>?</p>
| 0 | 2016-06-07T18:49:02Z | 37,687,174 | <p>If I'm understanding your question correctly, you'd actually do the opposite. You would serve HTML from your Python script. You could use whatever modules you like in your Python application along with whatever modules are necessary for you to serve HTML content. </p>
<p>There are many web frameworks for doing such... | 3 | 2016-06-07T18:54:20Z | [
"python",
"html",
"embed"
] |
What is HTTPHandler with regards to Python's urllib2 library? | 37,687,192 | <p>I am new to using pythons HTTP interaction libraries urllib and urllib2 and I am wondering what is an HTTPHandler and what is the purpose of using in the the following context?</p>
<pre><code>http_handler = urllib2.HTTPHandler(debuglevel=_debug)
https_handler = urllib2.HTTPSHandler(debuglevel=_debug)
</code></pre>... | 0 | 2016-06-07T18:55:18Z | 37,687,520 | <p><a href="https://docs.python.org/2/library/urllib2.html?highlight=urllib2.httphandler#urllib2.HTTPHandler.http_open" rel="nofollow">As you can see</a>, those "handlers" are just objects that get a request (or I'd say "request params") object and actually make an HTTP request. And <a href="https://docs.python.org/2/l... | 0 | 2016-06-07T19:14:08Z | [
"python",
"http",
"urllib2",
"urllib"
] |
Fastest way to generate patches from an image/array and save the coordinates | 37,687,216 | <p>I have trained a CNN with Keras in order to segment specific patterns. It works really well, but now I have to start the "production phase", so my CNN must segment thousands of images.</p>
<p>So for a given image that the CNN has to segment, for each pixel into this image, I have to cut a patch around the pixel, an... | 0 | 2016-06-07T18:56:33Z | 39,938,461 | <blockquote>
<p>Here is a way to generate images with keras, hope it helps:</p>
</blockquote>
<pre><code>datagen = ImageDataGenerator(
rotation_range=.06,
width_shift_range=0.02,
height_shift_range=0.02,
shear_range=0.0002,
zoom_range=0.0002,
horizontal_flip=True,
fill_mode='nearest',
... | 2 | 2016-10-08T23:33:35Z | [
"python",
"keras"
] |
OperationalError When Connecting - Psycopg2 | 37,687,248 | <p>I want to interact with some data from an SQL database in Python, but am having connection issues. I've verified that the information below is correct, as I'm able to use these credentials (stored in a YAML file) to log in to the database via MySQL Workbench 6.3 CE.</p>
<pre><code>user_db : *******
user_host : ****... | 0 | 2016-06-07T18:58:37Z | 37,714,211 | <p>It seems like you're trying to connect to MySQL (port 3306) using a PostgreSQL client library (psycopg2), which also works for Redshift because Redshift is based on Postgres.</p>
<p>Please try installing <a href="https://github.com/PyMySQL/PyMySQL" rel="nofollow">PyMySQL</a> or any of the <a href="http://stackoverf... | 2 | 2016-06-08T22:51:03Z | [
"python",
"postgresql",
"ipython",
"port",
"psycopg2"
] |
In Cerberus can you use 'valueschema' with a type of 'dict'? | 37,687,293 | <p>So I'm using Cerberus for schema validation, but I'm running into a particular with validating a subdictionary of a dictionary whose key is unknown.</p>
<p>So say I have the following document:</p>
<pre><code>dict = {
'things': {
'0463': {
'foo': 'blah',
'bar': 'bleep'
},
... | 1 | 2016-06-07T19:01:14Z | 37,706,652 | <p>So i figured out that cerberus will handle <code>valueschema</code> if it's of type dict if you put a <code>schema</code> field after the <code>valueschema</code> key. So my structure should be:</p>
<pre><code>schema = {
'things': {
'type': 'dict',
'valueschema': {
'type': 'dict',
... | 1 | 2016-06-08T15:20:41Z | [
"python",
"cerberus"
] |
How to Remove Random Text Breaks in HTML Text | 37,687,447 | <p>I'm looking to scrape some of the text out of a couple HTML documents, but I can't get rid of some of the line breaks. Currently I have Beautiful Soup parsing the web pages, then I read in all the lines and attempt to strip all the newline characters out of the text, but I can't get rid of the ones in the middle of ... | 0 | 2016-06-07T19:09:42Z | 37,688,029 | <p>You haven't shared what the rest of your code looks like after the <code>for</code> loop, but I'm guessing a very simplified version is something like:</p>
<pre><code>data = ["a\nb", "c\nd", "e\nf"]
for i in range(len(data)):
row = data[i]
row = row.replace("\n", "")
#let's see if that fixed it...
pri... | 0 | 2016-06-07T19:44:57Z | [
"python",
"html",
"regex",
"python-3.x",
"web-scraping"
] |
Filter reservations created by logged in user | 37,687,451 | <p>I want to display all the reservations created by the currently logged-in user. </p>
<p><a href="http://stackoverflow.com/questions/14026750/django-model-filtering-by-user-always">Django model: Filtering by user, always</a></p>
<p><a href="https://docs.djangoproject.com/en/1.8/topics/db/examples/many_to_one/" rel=... | 0 | 2016-06-07T19:09:48Z | 37,687,643 | <p>You should override the <code>get_queryset</code> method of ListView, you can't do it by setting a static property (<code>queryset</code>) on the class. Here's how to do it:</p>
<pre>
class ReservationListView(LoginRequiredMixin, ListView):
model = Reservation
context_object_name = 'reservations'
def g... | 1 | 2016-06-07T19:21:50Z | [
"python",
"django",
"django-views",
"django-queryset"
] |
Single worker thread for all tasks or multiple specific workers? | 37,687,463 | <p>I'm creating a simple GUI application using PyQt5 where I request some data from an API which is then used to populate various controls of the UI.</p>
<p>The examples I was following about worker threads in PyQt all seem to sub-class <code>QThread</code> and then do their business logic in the overridden <code>run(... | 3 | 2016-06-07T19:10:41Z | 37,688,544 | <p>What you can do is design an object to do all these tasks (inherit QObject for slots / signals). Lets say each task is defined as a separate function - lets designate these functions as slots.</p>
<p>Then (a general order of events):</p>
<ul>
<li>instantiate a QThread object.</li>
<li>instantiate your class.</li>
... | 5 | 2016-06-07T20:18:16Z | [
"python",
"multithreading",
"qt",
"pyqt",
"pyqt5"
] |
Single worker thread for all tasks or multiple specific workers? | 37,687,463 | <p>I'm creating a simple GUI application using PyQt5 where I request some data from an API which is then used to populate various controls of the UI.</p>
<p>The examples I was following about worker threads in PyQt all seem to sub-class <code>QThread</code> and then do their business logic in the overridden <code>run(... | 3 | 2016-06-07T19:10:41Z | 37,837,008 | <p>Here is a concise example of one (but could be as many as you wish) worker object which is moved to a single running QThread (started) and is communicating via signals. Also the thread is stopped at the end. It demonstrates what code_fodder outlined in <a href="http://stackoverflow.com/a/37688544/1536976">his answer... | 1 | 2016-06-15T13:33:42Z | [
"python",
"multithreading",
"qt",
"pyqt",
"pyqt5"
] |
How to add images into a list | 37,687,485 | <p>Hi I have multiple images in my program. And I wish to display them randomly on the screen. I tried doing this by putting the images into the list and then selecting random positions for them. However when I assign a variale for the picture and add it into the list it doesn't work.
Heres an example.</p>
<pre><code>... | 1 | 2016-06-07T19:11:48Z | 37,687,566 | <p>According to the <a href="https://docs.python.org/3.6/library/random.html#random.randrange" rel="nofollow">randrange</a> docs, the function doesn't select an element randomly from a list, but rather returns a random integer from a certain range.</p>
<p>The way to call it would be: <code>x = room_list[random.randran... | 1 | 2016-06-07T19:16:45Z | [
"python",
"pygame"
] |
How can I get string as input to Bigrams in nltk | 37,687,607 | <p>I am new to nltk and I am using python.
I am taking string as input to Bigrams. When I am showing the items of this. I am getting each character as a word. </p>
<pre><code>import nltk
string = "Batman Superman"
bigram = nltk.bigrams(string)
print bigram.item()
[('B','a'),('a','t'),('t','m'),('m','a'),('a',... | 0 | 2016-06-07T19:19:00Z | 37,687,696 | <p>Ok, so what is happening here is that the <code>bigrams</code> function is expecting a tokenized version of you corpus, that is a list of words in order.</p>
<p>When you pass it a string, <code>nltk</code> is doing its best and converts that string into a list of chars, and then produces the bigrams of that list, w... | 1 | 2016-06-07T19:24:59Z | [
"python"
] |
Irregular binning p2 python pandas | 37,687,624 | <p>I have one small follow up question regarding binning in python pandas. </p>
<p>I have a data-frame like the following: </p>
<pre><code>df =
variable test_score
-1 52.0
1 53.0
4 54.0
6 64.0
6 64.0
-6 64.0
5 71.0
10 73.0
-15 ... | 2 | 2016-06-07T19:20:34Z | 37,688,494 | <p>This should get it done. I manufactured the data, so it won't look like yours.</p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed([3,1415])
df = pd.DataFrame(dict(variable=np.random.choice(range(20), (1000,)),
test_score=np.random.rand(1000,).round(2) * 100))
df_ = df.gro... | 2 | 2016-06-07T20:15:21Z | [
"python",
"pandas",
"dataframe",
"scatter-plot",
"binning"
] |
Irregular binning p2 python pandas | 37,687,624 | <p>I have one small follow up question regarding binning in python pandas. </p>
<p>I have a data-frame like the following: </p>
<pre><code>df =
variable test_score
-1 52.0
1 53.0
4 54.0
6 64.0
6 64.0
-6 64.0
5 71.0
10 73.0
-15 ... | 2 | 2016-06-07T19:20:34Z | 37,688,749 | <p>For your bins containing 5 items then pd.cut() to further slice the data :</p>
<pre><code>LL = df['test_score'].tolist()
bins = LL[::5]
</code></pre>
| 1 | 2016-06-07T20:30:20Z | [
"python",
"pandas",
"dataframe",
"scatter-plot",
"binning"
] |
Creating a variable filename for every new file in loop,python | 37,687,651 | <p>I have been trying to get this code to work for hours. But it just doesn't work, the files are being created. But all that is i'm getting back from the file is stuff which doesn't make sense to me. </p>
<pre><code>x=raw_input()
p=open(str(x) + ".txt", 'w+')
p.write("Test#1")
print p.read();
p.close()
</code></pre>
... | 0 | 2016-06-07T19:22:08Z | 37,687,752 | <p>After writing to the file, you need to move (seek) the file pointer to the beginning of the file in order for read to work:</p>
<pre><code>x=raw_input()
p=open(str(x) + ".txt", 'w+')
p.write("Test#1")
p.seek(0) # <== Seek to the beginning
print p.read()
p.close()
</code></pre>
| 0 | 2016-06-07T19:28:30Z | [
"python",
"file",
"io"
] |
Creating a variable filename for every new file in loop,python | 37,687,651 | <p>I have been trying to get this code to work for hours. But it just doesn't work, the files are being created. But all that is i'm getting back from the file is stuff which doesn't make sense to me. </p>
<pre><code>x=raw_input()
p=open(str(x) + ".txt", 'w+')
p.write("Test#1")
print p.read();
p.close()
</code></pre>
... | 0 | 2016-06-07T19:22:08Z | 37,687,784 | <p>One simple way of handling this is to close the file after writing it and re-open it for reading:</p>
<pre><code>x=raw_input()
p=open(str(x) + ".txt", 'w+')
p.write("Test#1")
p.close()
p=open(str(x) + ".txt", 'r')
print p.read();
p.close()
</code></pre>
| 0 | 2016-06-07T19:30:46Z | [
"python",
"file",
"io"
] |
GeoDjango tutorial | 37,687,655 | <p>Environment - Win 10, Python 2.7</p>
<p>I am going through GeoDjango tutorial. I've already installed PostgreSQL, psycopg2, GEOS, PROJ.4, GDAL (last three ones via OSGeo4W) and postGIS.</p>
<p>So far I 've got to Create a Spatial Database part (<a href="https://docs.djangoproject.com/en/1.8/ref/contrib/gis/tutoria... | -1 | 2016-06-07T19:22:27Z | 37,692,097 | <p>You haven't mentioned what versions of PostGIS and Postgreql you have installed </p>
<pre><code>CREATE EXTENSION postgis;
</code></pre>
<p>Is the correct method for newer versions of Postgis (IIRC version 2 onwards)</p>
<p>The create template method is the correct way for older versions. </p>
<p>You can determin... | 0 | 2016-06-08T01:58:21Z | [
"python",
"django",
"postgresql",
"geodjango"
] |
Embedding Python in C - Segfault | 37,687,770 | <p>From reading another <a href="http://stackoverflow.com/questions/13942128/how-to-pass-an-array-from-c-to-an-embedded-python-script">post</a>, I am trying to embbed some some Python code into C:</p>
<p><strong>main.c</strong></p>
<pre><code>#include <Python.h>
int callModuleFunc(int array[], size_t size) {
... | -1 | 2016-06-07T19:30:06Z | 37,689,456 | <p>There were several problems with your code:</p>
<ol>
<li><code>Py_Initialize()</code> was not called.</li>
<li><code>PyImport_ImportModule()</code> failed to find your python file, since in embedded Python you start <strong>without</strong> an initial module, relative to which the search can work. The fix is to exp... | 3 | 2016-06-07T21:12:41Z | [
"python",
"c",
"segmentation-fault"
] |
Plotting Data with a surface plot, gives strange results | 37,687,785 | <p>I want to plot a function chi_F which depends on another function (Chi_T). The functions are defined in the code below. Both functions depend on datasets F and T (write a message to me if you want to try the code with the data). If I run the code below, I always get very symmetric plots, which look like as if chi_F... | 0 | 2016-06-07T19:30:49Z | 37,689,569 | <p>You made some misprints in function <code>chi_F</code>: if you write 1/2 for python is means 0. You have to write:</p>
<pre><code>A = 1./2. - 1/np.pi * np.arctan(a*(chi_T(T) - 0.9))
B = 1./2. + 1/np.pi * np.arctan(a*(chi_T(T) + 0.1))
</code></pre>
<p>It can not verify your code because of you do not show data fr... | 0 | 2016-06-07T21:20:44Z | [
"python",
"matplotlib",
"plot",
"3d"
] |
How to stop depth-first search when the target vertex of the graph is found? | 37,687,838 | <p>Here is the graph:</p>
<pre><code>g = {
0: [2, 5, 7],
1: [7],
2: [0, 6],
3: [5, 4],
4: [3, 6, 7],
5: [3, 4, 0],
6: [2, 4],
7: [0, 1, 4]
}
</code></pre>
<p><a href="http://i.stack.imgur.com/4VPuI.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/4VPuI.jpg" alt="enter image descr... | 1 | 2016-06-07T19:34:29Z | 37,687,942 | <p>You want to test if you reached your target and, if you did, <code>return True</code>. This can be accomplished by making the following edits to your code:</p>
<p>Small edit for efficiency</p>
<pre><code>def dfs(graph, start, target, visited=None):
if visited is None:
visited = set()
visited.add(st... | 1 | 2016-06-07T19:40:47Z | [
"python",
"graph",
"depth-first-search",
"dfs"
] |
python 3.4 vs. 3.5 strftime same locale different output | 37,688,012 | <p>The execution of these commands in python 3.4.x (Windows 10 Home)</p>
<pre><code>import locale
from datetime import datetime
locale.setlocale(locale.LC_ALL, 'Spanish')
datetime.strftime(datetime.now(), '%a %d %b %Y')
</code></pre>
<p>renders the output</p>
<pre><code>'Spanish_Spain.1252'
'mar 07 jun 2016'
</code>... | 3 | 2016-06-07T19:44:16Z | 37,702,118 | <p>Ok, I issued the problem to the Python bug tracker and Eryk Sun answered my question:</p>
<blockquote>
<p>The universal CRT that's used by 3.5+ implements locales using Windows
locale names [1], which were introduced in Vista. Examples for Spanish
include 'es', 'es-ES', and 'es-ES_tradnl' . The latter is the
... | 1 | 2016-06-08T12:10:53Z | [
"python",
"datetime"
] |
Using Python RLocks across multiple independent processes | 37,688,053 | <p>I am working on a Django project that uses Celery to schedule some long-term tasks. Both Django and Celery run in completely independent processes and need a way to coordinate access to the database. I'd like to use Python's <code>multiprocessing.RLock</code> class (or equivalent) as I need the lock to be reentrant.... | 2 | 2016-06-07T19:46:47Z | 37,842,550 | <p>I ended up using RabbitMQ as a way to create distributed locks. Details on how to do this can be found on RabbitMQ's blog: <a href="https://www.rabbitmq.com/blog/2014/02/19/distributed-semaphores-with-rabbitmq/" rel="nofollow">https://www.rabbitmq.com/blog/2014/02/19/distributed-semaphores-with-rabbitmq/</a>.</p>
<... | 0 | 2016-06-15T17:58:22Z | [
"python",
"django",
"celery",
"python-multiprocessing"
] |
Saving a Pandas DataFrame to a Django Model | 37,688,054 | <p>I have stock price data that is stored in a pandas DataFrame as shown below (actually it was in a panel, but I converted it to a DataFrame)</p>
<pre><code> date ticker close tsr
0 2013-03-28 abc 22.81 1.000439
1 2013-03-28 def 94.21 1.006947
2 2013-03-28 ghi 95.84 1.014180
3 2013-03... | 0 | 2016-06-07T19:46:49Z | 37,689,712 | <p>It would be most efficient to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html" rel="nofollow"><code>to_sql()</code></a> with appropriate <code>connection</code> parameters for the <code>engine</code>, and run this inside your <code>Django</code> app rather than iterati... | 3 | 2016-06-07T21:29:58Z | [
"python",
"django",
"pandas"
] |
numpy count where the difference between values bigger than something | 37,688,205 | <p>I'm quite new to Numpy, and I could'nt find anything meeting my requirement.</p>
<p>Is there any good way to do a count.where( value-value2 > threshold ) ?</p>
<p>I have a x,y position numpy array and I need to count the closest neighbors </p>
<p>Something similar to this:</p>
<p><code>[(93, 256), (93, 256), (93... | 0 | 2016-06-07T19:56:30Z | 37,688,531 | <p>If you just want to count how many occurrences:</p>
<p>The condition is <code>value1 - value0 > 100</code></p>
<pre><code>x = np.array([[93, 256], [93, 256], [93, 256], [93, 257], [54, 130], [55, 131]])
y = np.where(x[:,1] - x[:,0] > 100)
print(y[0].shape[0])
</code></pre>
<p>If you have condition on both... | 0 | 2016-06-07T20:17:28Z | [
"python",
"numpy"
] |
numpy count where the difference between values bigger than something | 37,688,205 | <p>I'm quite new to Numpy, and I could'nt find anything meeting my requirement.</p>
<p>Is there any good way to do a count.where( value-value2 > threshold ) ?</p>
<p>I have a x,y position numpy array and I need to count the closest neighbors </p>
<p>Something similar to this:</p>
<p><code>[(93, 256), (93, 256), (93... | 0 | 2016-06-07T19:56:30Z | 37,689,315 | <p>There is a suitable method for calculating neighbours â <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.isclose.html#numpy.isclose" rel="nofollow">numpy.isclose(a, b, atol)</a>. The following calculates neighbours within a range of 4:</p>
<pre><code>threshold = 4
np.isclose([93, 256], [9... | 0 | 2016-06-07T21:03:19Z | [
"python",
"numpy"
] |
OSError: socket no longer exists (Python IDLE error) | 37,688,228 | <p>First let me give some background information that lead to the problem.
I had/have two versions of python installed in my Win 8.1 laptop. Originally Py 2.5 was set as the default. The way i did it was that i renamed the <code>python.exe</code> of Python 3.5 as <code>python35.exe</code> and the file
<code>pythonw.e... | 0 | 2016-06-07T19:57:55Z | 37,688,867 | <p>So i just installed the python 3.5.1 setup again and things are up and running.</p>
| 0 | 2016-06-07T20:36:28Z | [
"python",
"windows",
"python-2.7",
"python-3.5"
] |
missing django.apps on ubuntu | 37,688,245 | <p>Well, this is embarrassing, I was following <code>django</code> tutorial for the last couple of days, and all of a sudden, I can't start the server. The error I get is about the line </p>
<pre><code>from django.apps import AppConfig
</code></pre>
<p>and the error itsle is </p>
<pre><code>ImportError: No module na... | -1 | 2016-06-07T19:59:08Z | 37,688,469 | <ol>
<li><p>Have you activated Virtualenv?</p></li>
<li><p>Check what version of django you are running. I think added from django.apps import AppConfig after 1.6 or something.</p></li>
</ol>
<p>Sorry I can't comment due to my lack of reputation.</p>
| 1 | 2016-06-07T20:14:12Z | [
"python",
"django"
] |
Pygame Import error:No module named py | 37,688,281 | <p>I am trying to make a mobile app in which you can go to calculator with pygame. What I am trying to do is when you click the calculator image, it opens calculator app and then when you press the home button , it goes back to home. </p>
<p><strong>Problem:</strong> But then , if you are at home page after opening ... | -1 | 2016-06-07T20:01:28Z | 37,688,372 | <p>Here is an attempt to fix this.</p>
<pre><code>import pygame, time, sys
img = pygame.image.load('main1.png')
img2= pygame.image.load('calcu.png')
img15=pygame.image.load('HOME2.png')
img16=pygame.image.load('calcimg.png')
w = 600
h = 450
screen = pygame.display.set_mode([w, h])
x=y=0
pygame.init()
WHITE=(255,255,... | 3 | 2016-06-07T20:07:04Z | [
"python",
"python-2.7",
"pygame",
"importerror"
] |
Mixing threading of c function with python's multiprocessing | 37,688,414 | <p>I am writing a python 2.7.11 program on Linux. The program creates 12 sub-processes with multiprocessing.Pool. Each sub-process has cpu affinity with one of the 12 cpus through the psutil library for python.</p>
<p>I use multiprocessing.Event to make 11 sub-processes wait for sub-process 0.</p>
<p>Then, in sub-pro... | 1 | 2016-06-07T20:09:58Z | 37,704,963 | <p>Okay, I did a little research, and...</p>
<p>First, since the 12 threads are all in a single process, what happens in the other sub-processes should not effect the parent process in any way. There is some background processing happening by the OS to handle inter-process communications that will take place in the pr... | 1 | 2016-06-08T14:11:39Z | [
"python",
"multithreading",
"parallel-processing",
"multiprocessing"
] |
Does iterating over my_dict.keys() and modifying the values in the dictionary invalidate the iterator? | 37,688,512 | <p>My example is something like this</p>
<pre><code>for my_key in my_dict.keys():
my_dict[my_key].mutate()
</code></pre>
<p>Is the behavior of the above code defined (assuming <code>my_dict</code> is a dictionary and <code>mutate</code> is a method that mutates its object)? My concern is that mutating the values ... | 4 | 2016-06-07T20:16:30Z | 37,688,655 | <p>The document also says:</p>
<blockquote>
<p>The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.</p>
</blockquote>
<p>So, you can't mutate them at all.</p>
| 0 | 2016-06-07T20:23:54Z | [
"python",
"iterator",
"undefined-behavior"
] |
Does iterating over my_dict.keys() and modifying the values in the dictionary invalidate the iterator? | 37,688,512 | <p>My example is something like this</p>
<pre><code>for my_key in my_dict.keys():
my_dict[my_key].mutate()
</code></pre>
<p>Is the behavior of the above code defined (assuming <code>my_dict</code> is a dictionary and <code>mutate</code> is a method that mutates its object)? My concern is that mutating the values ... | 4 | 2016-06-07T20:16:30Z | 37,688,665 | <p>Yes, that's safe, at least in all of the C-based implementations of Python. It's also safe to do:</p>
<pre><code>for my_key in my_dict: # NOTE: no .keys() here
my_dict[my_key].mutate()
</code></pre>
<p>That is, the safety does not depend on materializing a list of the keys, and it's generally more efficient ... | 6 | 2016-06-07T20:24:30Z | [
"python",
"iterator",
"undefined-behavior"
] |
Does iterating over my_dict.keys() and modifying the values in the dictionary invalidate the iterator? | 37,688,512 | <p>My example is something like this</p>
<pre><code>for my_key in my_dict.keys():
my_dict[my_key].mutate()
</code></pre>
<p>Is the behavior of the above code defined (assuming <code>my_dict</code> is a dictionary and <code>mutate</code> is a method that mutates its object)? My concern is that mutating the values ... | 4 | 2016-06-07T20:16:30Z | 37,689,140 | <p>Yes. This isn't specific to Python, dictionaries, or even hash based data structures.</p>
<p>The internal structure of a dictionary is based entirely on its keys. If you change the keys around you can change the structure of the dictionary and if that happens in the middle of iterating directly over a dictionary th... | 1 | 2016-06-07T20:52:49Z | [
"python",
"iterator",
"undefined-behavior"
] |
Pygame Using Class to Randomize Image Placements | 37,688,597 | <p>I'm creating a card/tile memory association game. It is a 4x4 grid of 100x100 pixel images, so 16 images in total are displayed (8 pairs). </p>
<p>For now all I want is for the images to be displayed in a grid in a random order each time the game is started, which I feel I am close to doing using shuffling them in ... | 0 | 2016-06-07T20:20:48Z | 37,689,789 | <p>First of all, you forgot a comma at the end of the first line in the imagelist in your memorygame class. Changing that to</p>
<pre><code>imagelist = [image1,image2,image3,image4,image5,image6,image7,
image8,image9]
</code></pre>
<p>should fix the first syntax error.</p>
<p>Secondly, I'm not sure what... | 0 | 2016-06-07T21:35:38Z | [
"python",
"class",
"python-3.x",
"pygame"
] |
Erratic INSUFFICIENT_ACCESS error when using LDAP | 37,688,610 | <p>We have a Pyramid application that uses LDAP for authentication. Currently we don't use <code>pyramid_ldap</code> but custom code based on <code>python_ldap</code> to connect to the LDAP server.</p>
<p>The code is in a Singleton class: the <code>__init__</code> method (more precisely the method called during instan... | 2 | 2016-06-07T20:21:20Z | 37,769,235 | <p>I realized that the error comes from somewhere else in the code.</p>
| 0 | 2016-06-11T23:02:18Z | [
"python",
"openldap"
] |
What can I replace tuple(sorted(my_string)) with in Python? | 37,688,668 | <p>I want to use something like "characters where order does not matter" as the key to build a dictionary in Python.</p>
<p>Like "abc" and "cba" can give me the same hash index, and "aab" and "ab" give me different hash indices. </p>
<p>I found one way is to use <code>tuple(sorted(my_string))</code> to hashable a lis... | 1 | 2016-06-07T20:24:37Z | 37,688,762 | <p>You can get <code>O(N)</code> time complexity with <code>frozenset(Counter(my_string).items())</code>. You may want to time whether this actually wins in practice, though, because the constant factor of this code might be high enough to outweigh the extra logarithmic factor of <code>''.join(sorted(my_string))</code>... | 3 | 2016-06-07T20:30:57Z | [
"python",
"algorithm",
"sorting",
"data-structures",
"set"
] |
Spark avoid partition overwrite | 37,688,688 | <p>I am writing a Spark Application that saves log data into a directory <code>/logroot</code>.</p>
<p>My code is</p>
<pre><code>myDF.mode('overwrite').partitionBy('date','site').save('logroot')
</code></pre>
<p>I want to use the <code>overwrite</code> mode in order to re-process many times a week all the daily data... | 0 | 2016-06-07T20:25:46Z | 38,370,859 | <p>At the moment of writing the best solution seems:</p>
<ul>
<li>Extract from the initial dataframe the partition names that should be cleaned</li>
<li>Clean these partitions using hadoop fs api</li>
<li>Save dataframe using the <code>append mode</code></li>
</ul>
<p>Thanks to all for the help and hope Spark guys wi... | 0 | 2016-07-14T09:45:49Z | [
"python",
"apache-spark",
"pyspark"
] |
New to Python trying re. Why findall is not searching to end of line and matching ALL group of digits | 37,688,699 | <p>A simple re to match numbers on a line would be:</p>
<pre><code>/[0-9]+/gm
Will match (------> Match)
t1est ------->1
23 ------->23
foo
bar
304958 ------->304958
bar
as 4497 our 6702 personal 8454 assistants who can take care of many things -----> 4497 6702 8454
</code></pre>
<p>When I try ... | 0 | 2016-06-07T20:26:43Z | 37,688,779 | <p>They're skipped because you tell Python to skip them:</p>
<pre><code> numbers = int(stuff[0])
numlist.append(numbers)
</code></pre>
<p><code>stuff</code> is your array of ALL matched numbers for the line being analyzed, but you only ever extract the first one (<code>[0]</code>) and save it, which essentiall... | 2 | 2016-06-07T20:31:48Z | [
"python",
"python-2.7"
] |
New to Python trying re. Why findall is not searching to end of line and matching ALL group of digits | 37,688,699 | <p>A simple re to match numbers on a line would be:</p>
<pre><code>/[0-9]+/gm
Will match (------> Match)
t1est ------->1
23 ------->23
foo
bar
304958 ------->304958
bar
as 4497 our 6702 personal 8454 assistants who can take care of many things -----> 4497 6702 8454
</code></pre>
<p>When I try ... | 0 | 2016-06-07T20:26:43Z | 37,689,038 | <p>Untested, but here's a solution and what's happening...</p>
<pre><code>import re
# don't use `list()` here - use `[]` an empty list
numlist = []
# We can use a with statement here so the file automatically
# closes on an error or when the block ends...
with open('sum1.txt') as fin:
# iterate line by line
f... | 1 | 2016-06-07T20:46:27Z | [
"python",
"python-2.7"
] |
Django AJAX search function | 37,688,730 | <p>I'm trying to make a search function in my Django project using AJAX. But the functions in views.py don't seem to work properly. And maybe I have some other mistakes. Could you please tell me what I need to correct?</p>
<p>This is my AJAX file:</p>
<pre><code>$(document).ready( function(){
$('#suggestion').keyup(f... | 1 | 2016-06-07T20:28:55Z | 37,689,332 | <p>Django's <code>render</code> function renders HTML after parsing it with Jinja. If you want to write a view that acts as an endpoint for an AJAX function, you do not want that view to return <code>render</code>. </p>
<p>Instead you should use return <code>JsonResponse</code>. <code>JsonResponse</code> accepts a dic... | 0 | 2016-06-07T21:04:30Z | [
"python",
"ajax",
"django",
"django-templates",
"django-views"
] |
Error when loading csv on mysql using Python and odo module | 37,688,881 | <p>I decided to try <a href="http://odo.pydata.org/en/latest/perf.html" rel="nofollow">odo</a> for handling my csv data because it supposedly is way faster than doing it with pandas, but I can't make it work.</p>
<p>This is their documentation about migrating a 30gb csv file to a MySQL database:</p>
<pre><code>In [1]... | 0 | 2016-06-07T20:37:11Z | 37,690,281 | <p>Well, it was because MySQL couldn't access the file. It seems that it needs to be inside the mysql installation folder, which in my case was <code>/usr/local/mysql-5.6.20-osx10.7-x86_64/</code>.</p>
<p>I tried to put it inside the data folder, <code>/usr/local/mysql-5.6.20-osx10.7-x86_64/data/my_db</code> and that ... | 0 | 2016-06-07T22:12:58Z | [
"python",
"mysql",
"csv",
"odo"
] |
How to use pandas on spark notebook (data on dashDB) in python | 37,688,993 | <p>Hello I'm using IBM Bluemix.
Here I'm using an Apache Spark notebook and loading data from dashDB
I'm trying to provide a visualization and it's not displaying the rows, just the columns.</p>
<pre><code>def get_file_content(credentials):
from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)
props = {}
... | 1 | 2016-06-07T20:44:14Z | 37,690,393 | <pre><code>export PYSPARK_DRIVER_PYTHON=ipython
export PYSPARK_DRIVER_PYTHON_OPTS=notebook
</code></pre>
<p>And go to your spark directory</p>
<pre><code>cd ~/spark-1.6.1-bin-hadoop2.6/
./bin/pyspark --packages com.datastax.spark:spark-cassandra-connector_scalaversion:spark_version-M1
</code></pre>
<p>And you can w... | 0 | 2016-06-07T22:24:02Z | [
"python",
"pandas",
"ibm-bluemix",
"ibm",
"dashdb"
] |
How to use pandas on spark notebook (data on dashDB) in python | 37,688,993 | <p>Hello I'm using IBM Bluemix.
Here I'm using an Apache Spark notebook and loading data from dashDB
I'm trying to provide a visualization and it's not displaying the rows, just the columns.</p>
<pre><code>def get_file_content(credentials):
from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)
props = {}
... | 1 | 2016-06-07T20:44:14Z | 37,691,462 | <p>This is the solution that works for me.
I replaced
<code>BATTLES_df = pd.read_table(content_string)</code></p>
<p>with</p>
<p><code>BATTLES_df=data_df.toPandas()</code></p>
<p>Thank you</p>
| 1 | 2016-06-08T00:20:37Z | [
"python",
"pandas",
"ibm-bluemix",
"ibm",
"dashdb"
] |
Permision issue Python 3.4 apache | 37,689,034 | <p>im have FLASK app with
www/FlaskApp/FlaskApp/<strong>init</strong>.py file with funtion
python file wut next contains</p>
<pre><code>@app.route('/')
def hello():
file = open('myfile.txt', 'w+')
os.mknod("newfile.txt")
return render_template('page2.html')
</code></pre>
<p>but if im run site,its return ... | 0 | 2016-06-07T20:46:18Z | 37,736,652 | <p>Not sure if this is an optimal solution, and I don't know enough about Flask as to tell you why the relative path isn't working (I would think that it would write the file where ever your python script was) but you could get it to work by using an environment variable to specify where to store your apps data. For in... | 0 | 2016-06-09T21:41:40Z | [
"python",
"apache",
"python-3.x",
"ubuntu"
] |
How does multi-threading work in Python 3.4? | 37,689,138 | <p>I am just playing around with multi-threading, but I can't seem to get it to work. I have looked at other questions, but none really help me. Here's my code so far:</p>
<pre><code>import threading, time
def hello():
for i in range(1,5):
time.sleep(1)
print("Hello")
def world():
for i in ra... | 0 | 2016-06-07T20:52:41Z | 37,689,285 | <pre><code>threading.Thread(hello())
</code></pre>
<p>You called the function <code>hello</code> and passed the result to <code>Thread</code>, so it executed before the thread object even existed. Pass the plain function object:</p>
<pre><code>threading.Thread(target=hello)
</code></pre>
<p>Now the <code>Thread</cod... | 1 | 2016-06-07T21:01:09Z | [
"python",
"multithreading",
"python-multithreading"
] |
How does multi-threading work in Python 3.4? | 37,689,138 | <p>I am just playing around with multi-threading, but I can't seem to get it to work. I have looked at other questions, but none really help me. Here's my code so far:</p>
<pre><code>import threading, time
def hello():
for i in range(1,5):
time.sleep(1)
print("Hello")
def world():
for i in ra... | 0 | 2016-06-07T20:52:41Z | 37,689,784 | <p>You want something like this:</p>
<pre><code>import threading, time
def hello():
for i in range(1,5):
time.sleep(1)
print("Hello")
def world():
for i in range(1,5):
time.sleep(1)
print("World")
newthread = threading.Thread(target=hello)
newthread.start()
otherthread = thre... | 0 | 2016-06-07T21:35:28Z | [
"python",
"multithreading",
"python-multithreading"
] |
password_change_done not using custom template in Django | 37,689,159 | <p>I used Django's <em>auth_views.password_change</em> to allow a user to change their password. It uses a custom template and it works well, but the problem I'm having is that it redirects to Django's <em>password change successful</em> admin template instead of the custom template I declared.</p>
<p>urls.py</p>
<pr... | 0 | 2016-06-07T20:53:41Z | 37,689,304 | <p>In <code>INSTALLED_APPS</code> ensure that your app with the custom templates is specified before <code>admin</code>. </p>
<p>Django searches for the template in order. </p>
| 0 | 2016-06-07T21:02:43Z | [
"python",
"django",
"django-templates",
"django-urls"
] |
password_change_done not using custom template in Django | 37,689,159 | <p>I used Django's <em>auth_views.password_change</em> to allow a user to change their password. It uses a custom template and it works well, but the problem I'm having is that it redirects to Django's <em>password change successful</em> admin template instead of the custom template I declared.</p>
<p>urls.py</p>
<pr... | 0 | 2016-06-07T20:53:41Z | 37,689,318 | <p>You should use:</p>
<p><code>url(r'^settings/change/$', auth_views.password_change, {'template_name': 'users/forms/change-password.html',post_change_redirect:'change-password-done'},name='change-password'),</code></p>
<p>Without <code>post_change_redirect</code> default template will be loaded in that case.</p>
| 1 | 2016-06-07T21:03:39Z | [
"python",
"django",
"django-templates",
"django-urls"
] |
Sqlalchemy not committing object changes to postgres DB | 37,689,160 | <p>I am using the following passage of code:</p>
<pre><code>@app.route('/budget_item/<int:budget_id>/edit', methods=['GET', 'POST'])
def budget_item_edit(budget_id):
budget_item = session.query(Budget).filter_by(id=budget_id).one()
print "Start EDIT sequence"
# Return form data from HTML initial load form... | 0 | 2016-06-07T20:53:46Z | 37,689,455 | <p>i think that a simple</p>
<pre><code>budget_item.budget_amount_reallocated_total = budget_amount_reallocated_total
session.add(budget_item)
session.commit()
</code></pre>
<p>is the right way to do it</p>
| 0 | 2016-06-07T21:12:40Z | [
"python",
"postgresql",
"sqlalchemy",
"flask-sqlalchemy"
] |
Sqlalchemy not committing object changes to postgres DB | 37,689,160 | <p>I am using the following passage of code:</p>
<pre><code>@app.route('/budget_item/<int:budget_id>/edit', methods=['GET', 'POST'])
def budget_item_edit(budget_id):
budget_item = session.query(Budget).filter_by(id=budget_id).one()
print "Start EDIT sequence"
# Return form data from HTML initial load form... | 0 | 2016-06-07T20:53:46Z | 37,698,303 | <p>To answer your question, to update the <code>budget_item</code> that already exists in the database you need to update the <code>Budget</code> instance that you retrieved from the database, i.e.</p>
<pre><code>budget_item = session.query(Budget).filter_by(id=budget_id).one()
</code></pre>
<p>not the one that you h... | 0 | 2016-06-08T09:20:08Z | [
"python",
"postgresql",
"sqlalchemy",
"flask-sqlalchemy"
] |
Python Range function 100 - 0, on the same line | 37,689,172 | <p>so one of my assignments is to make a program in python to countdown 100 - 0 in increments of 10, i wrote the code but cannot figure out how to make it work on the same line instead of it using multiple lines to countdown. here is what i have so far.</p>
<pre><code>def main():
print(" I will print 100 down to ... | 1 | 2016-06-07T20:54:23Z | 37,689,259 | <p>Use <a href="https://docs.python.org/3/library/stdtypes.html?highlight=str.join#str.join" rel="nofollow"><code>str.join</code></a>,</p>
<pre><code>print(' '.join([str(i) for i in range(100, -10, -10)])) # 100 90 80 70 60 50 40 30 20 10 0
</code></pre>
<hr>
<p>Or use <a href="https://docs.python.org/3/library/func... | 2 | 2016-06-07T20:59:12Z | [
"python",
"function",
"range"
] |
Python Range function 100 - 0, on the same line | 37,689,172 | <p>so one of my assignments is to make a program in python to countdown 100 - 0 in increments of 10, i wrote the code but cannot figure out how to make it work on the same line instead of it using multiple lines to countdown. here is what i have so far.</p>
<pre><code>def main():
print(" I will print 100 down to ... | 1 | 2016-06-07T20:54:23Z | 37,689,277 | <p>You can pass an <code>end=" "</code> parameter to <code>print</code></p>
<pre><code>for num in range(100, -10, -10):
print(num, end=" ")
</code></pre>
<p>This will override the default newline character <code>'\n'</code> </p>
| 1 | 2016-06-07T21:00:46Z | [
"python",
"function",
"range"
] |
Rename Terminal Tabs Automatically with command | 37,689,218 | <p>I am trying to rename opened terminal tabs in OSX, but I can only change the Terminal title with the code below. Is there a way to change the Tab title with command? I am using osascript with python 2.7.</p>
<pre><code>name = """osascript -e 'tell application "Terminal" to set custom title in selected tab of the fr... | 0 | 2016-06-07T20:56:47Z | 37,690,160 | <p>This should do:</p>
<pre><code>title='Customized title for TAB'
os.system('echo -n -e "\033]0;{}\007"'.format(title))
</code></pre>
| 0 | 2016-06-07T22:01:53Z | [
"python",
"osx",
"shell",
"terminal",
"osascript"
] |
Rename Terminal Tabs Automatically with command | 37,689,218 | <p>I am trying to rename opened terminal tabs in OSX, but I can only change the Terminal title with the code below. Is there a way to change the Tab title with command? I am using osascript with python 2.7.</p>
<pre><code>name = """osascript -e 'tell application "Terminal" to set custom title in selected tab of the fr... | 0 | 2016-06-07T20:56:47Z | 37,690,491 | <p>using $title didn't work for me, but this did:</p>
<pre><code>>>> t = 'echo -n -e "\033]0;%s\007"' % title
>>> t
'echo -n -e "\x1b]0;Customized title for TAB\x07"'
>>> os.system(t)
-e 0
>>>
</code></pre>
| 1 | 2016-06-07T22:33:51Z | [
"python",
"osx",
"shell",
"terminal",
"osascript"
] |
Rename Terminal Tabs Automatically with command | 37,689,218 | <p>I am trying to rename opened terminal tabs in OSX, but I can only change the Terminal title with the code below. Is there a way to change the Tab title with command? I am using osascript with python 2.7.</p>
<pre><code>name = """osascript -e 'tell application "Terminal" to set custom title in selected tab of the fr... | 0 | 2016-06-07T20:56:47Z | 37,691,276 | <p>Here is the solution with using keys to open inspector, change title and close the inspector. Because according to my research there is no option to change tab title on OSX with using a ready apple script.</p>
<p>It works great, so no need to wait for Apple to release this option.</p>
<pre><code>tabinspector = """... | 0 | 2016-06-07T23:58:04Z | [
"python",
"osx",
"shell",
"terminal",
"osascript"
] |
Python script results in internal server error | 37,689,239 | <p>I'm working on a python script that generates html. Everything was working until I changed this: </p>
<pre><code>i=1;
for lijn in open("enquete.txt"):
slecht=0;
for lijn1 in open("enqueteres.txt"):
var=lijn1.split(":");
</code></pre>
<p>to this:</p>
<pre><code>i=1;
for lijn in open("enquete.txt"):
... | 0 | 2016-06-07T20:57:56Z | 37,689,396 | <p>There seems to be a '\r' character at the end of your line. Try deleting the line and retyping it. Also I would suggest removing the semicolons, they aren't necessary.</p>
<p>Also ensure that you are not intermingling tabs and spaces.</p>
| 0 | 2016-06-07T21:08:47Z | [
"python",
"html"
] |
Joining a Server with the Discord Python API | 37,689,289 | <p>I'm trying to setup a discord bot with python. I have a preexisting discord server that I would like the bot to join, but I seem to be having a bear of a time getting it to actually join. I am using discord.py 0.10.0 and python 3.5.1. Here's my code:</p>
<pre><code>import discord
import asyncio
import logging
logg... | 1 | 2016-06-07T21:01:17Z | 37,743,722 | <p>I had some trouble with this as well. What you need to do is:</p>
<ol>
<li>Go to the <a href="https://discordapp.com/developers/applications/me">Discord developer pages</a> (login if you haven't).</li>
<li>Go to the application with the bot you want to add to your channel.</li>
<li>Copy the Client/Application ID.</... | 6 | 2016-06-10T08:41:09Z | [
"python"
] |
How to validate installation of a Jupyter nbextension | 37,689,308 | <p>I have a <a href="https://github.com/conda-forge/vega-feedstock" rel="nofollow">conda recipe</a> that includes installation of a Jupyter nbextension. Assuming a package called <code>packagename</code>, the relevant pieces are:</p>
<pre><code>$ python setup.py install
$ jupyter nbextension install packagename --py -... | 2 | 2016-06-07T21:03:00Z | 37,695,903 | <p>Maybe have a notebook that uses the extension, then <code>jupyter nbconvert --execute</code> and validate the resulting HTML?</p>
| 1 | 2016-06-08T07:27:41Z | [
"python",
"jupyter",
"jupyter-notebook"
] |
Extracting text between two strings | 37,689,312 | <p>I am looking to extract the text between two patterns in my text file here is my text:</p>
<pre><code>Q2 2016 Apple Inc Earnings Call - Final
ONI SACCONAGHI, ANALYST, BERNSTEIN: I have one, and then a follow-up, as well. My sense is that you talked about adjusting for the changes in channel inventory, that you ... | -1 | 2016-06-07T21:03:15Z | 37,689,740 | <p>Before asking next time, make sure to look <a href="https://docs.python.org/3.5/library/re.html" rel="nofollow">at the docs</a>, go through <a href="https://docs.python.org/3.5/howto/regex.html#regex-howto" rel="nofollow">a tutorial</a>, take a look at other <a href="http://stackoverflow.com/questions/20014923/pytho... | 0 | 2016-06-07T21:31:58Z | [
"python",
"text"
] |
Production server saying it is missing modules after database flush with Python | 37,689,327 | <p>I have an application using Django1.9, and python2.7. I recently flushed my PostgreSQL database on my production server, and now whenever I try to use the application it is telling me there are missing modules. I never faced this issue before so I am curious, when you put your application on a production server, doe... | 0 | 2016-06-07T21:04:11Z | 37,689,395 | <blockquote>
<p>I am curious, when you put your application on a production server, does your virtual environment go with it ?</p>
</blockquote>
<p>Not necessarily unless you copied the virtualenv folder with it which isn't really a good practice, you should create the virtualenv on the production server</p>
<block... | 1 | 2016-06-07T21:08:43Z | [
"python",
"django",
"postgresql",
"virtualenv"
] |
python setup.py egg_info failed with error code 1 on amazon AMI | 37,689,335 | <p>After pouring over thread after thread regarding this issue I still cannot get rid of this error.</p>
<p>I have a Amazon Linux AMI 2016.03.1 x86_64 HVM GP2 set up on AWS.</p>
<p>When trying to run </p>
<pre><code>sudo pip install mysql-python
</code></pre>
<p>I get the Egg_info Code 1 Error</p>
<p>I have tried:... | 0 | 2016-06-07T21:04:41Z | 37,707,479 | <p>I was able to work around this by using the </p>
<pre><code>pip install mysql-connector-repackaged
</code></pre>
<p>package. This is replacing trying to use MySQLdb</p>
| 0 | 2016-06-08T15:59:53Z | [
"python",
"amazon-web-services"
] |
Using if result more than once | 37,689,360 | <p>I have a piece of code below which will skip functions dependent on a result. In a function, I have an if found statement, that will make the result true and run through the code below under if. I also have if not found in the function, which will set the result to False, so that the code inside the if statement bel... | -1 | 2016-06-07T21:06:19Z | 37,689,609 | <p>I <em>think</em> you're asking if you can do this:</p>
<pre><code>result = some_function1()
if result:
do()
some()
things()
result = some_function2()
if result:
do()
some()
other()
things()
</code></pre>
<p>Yes. You can do that. The value stored within <code>result</code> changes and... | 1 | 2016-06-07T21:23:01Z | [
"python"
] |
Dealing with mis-escaped characters in JSON | 37,689,400 | <p>I am reading a JSON file into Python which contains escaped single quotes (<em>\'</em>). This leads to all kinds of hiccups, as nicely discussed e.g. <a href="http://stackoverflow.com/questions/2275359/jquery-single-quote-in-json-response">here</a>. However, I could not find anything on how to <strong>address</stron... | 0 | 2016-06-07T21:09:04Z | 37,689,682 | <p>The right thing would be to fix whatever is creating the invalid JSON file. But if that's not possible, I guess the replace is needed. But you should use a regular expression so it doesn't replace <code>\\'</code> with <code>\'</code> -- in this case the first backslash is escaping the second backslash, they're not ... | 1 | 2016-06-07T21:27:32Z | [
"python",
"json",
"string",
"file-io",
"data-structures"
] |
Dealing with mis-escaped characters in JSON | 37,689,400 | <p>I am reading a JSON file into Python which contains escaped single quotes (<em>\'</em>). This leads to all kinds of hiccups, as nicely discussed e.g. <a href="http://stackoverflow.com/questions/2275359/jquery-single-quote-in-json-response">here</a>. However, I could not find anything on how to <strong>address</stron... | 0 | 2016-06-07T21:09:04Z | 37,689,688 | <p>The <a href="https://tools.ietf.org/html/rfc7159" rel="nofollow">JSON standard</a> defines specific set of <a href="https://tools.ietf.org/html/rfc7159#section-7" rel="nofollow">valid 2-character escape sequences</a>: <code>\\</code>, <code>\/</code>, <code>\"</code>, <code>\b</code>, <code>\r</code>, <code>\n</code... | 1 | 2016-06-07T21:28:07Z | [
"python",
"json",
"string",
"file-io",
"data-structures"
] |
Dealing with mis-escaped characters in JSON | 37,689,400 | <p>I am reading a JSON file into Python which contains escaped single quotes (<em>\'</em>). This leads to all kinds of hiccups, as nicely discussed e.g. <a href="http://stackoverflow.com/questions/2275359/jquery-single-quote-in-json-response">here</a>. However, I could not find anything on how to <strong>address</stron... | 0 | 2016-06-07T21:09:04Z | 37,689,722 | <p>The solution is not bad. It seems ugly because the problem is ugly - you have corrupt data. It's certainly simple, elegant, and effective. It will only fail if the substring <code>\\'</code> (that's three characters, I'm not escaping anything) is present anywhere, and even then only if the number of consecutive slas... | 1 | 2016-06-07T21:31:03Z | [
"python",
"json",
"string",
"file-io",
"data-structures"
] |
Python socketserver or socket with thread | 37,689,518 | <p>I am new to the module socket and I am learning how to implement it. I currently have this basic server written.</p>
<pre><code>import socket
s = socket.socket()
host = "Some IP"
port = 12345
s.bind((host, port))
print "Setting up server on", host + ":" + str(port)... | 0 | 2016-06-07T21:17:23Z | 37,689,625 | <p>The socket library is very low-level, you really have to implement most things yourself.</p>
<p>SocketServer is more high-level. It uses the socket library internally, and provides an easy interface, that allows you deal with multiple clients at a time, and you don't have to worry about the whole low-level stuff in... | 1 | 2016-06-07T21:23:49Z | [
"python",
"multithreading",
"sockets",
"server",
"connection"
] |
Acessing a property from a parent object | 37,689,534 | <p>In python, I'm creating an object inside a class:</p>
<pre><code>class A:
def __init__(self):
self.one = 1
self.two = B()
</code></pre>
<p>Now I define class B, and I want to access self.one from inside B()</p>
<pre><code>class B()
def __init__(self):
self.three = "hello"
... | 0 | 2016-06-07T21:18:41Z | 37,689,578 | <p>A is not a parent object, parent object is the object from which you inherit. B has no knowledge about A, you have to modify your classes structure, for example by passing reference to parent in B's constructor (which you say you do not want to do, althouth it is not entirely clear what do you mean by "without doing... | 2 | 2016-06-07T21:21:15Z | [
"python"
] |
Why doesn't the Process receive the queue event? | 37,689,571 | <p>I am trying to send data to a multi processing Process, using a queue. For some reason, the example does not work. Do you know why?</p>
<p>I expect the program to print out "Received something: hello" and "Received poison pill", but it never gets there. However, it does print "running" and "listening", so I know th... | 2 | 2016-06-07T21:20:49Z | 37,689,831 | <p><a href="https://docs.python.org/3/library/queue.html" rel="nofollow">queue</a> module is for multi-threaded programs. These threads would all be in a single process, meaning they also share memory. (see the See Also section at the end of the <a href="https://docs.python.org/3/library/queue.html" rel="nofollow">do... | 2 | 2016-06-07T21:39:04Z | [
"python",
"python-multiprocessing"
] |
Generate HTML using Django-Polymorphic models | 37,689,595 | <p>Can I generate HTML dynamically based on DJANGO-POLYMORPHIC Models? I'd like to read all of the rows from a table and generate divs based on the class type. Or is this bad practice?</p>
<pre><code>{% if content %}
{% for c in content %}
<ul>
{% if c.instance_of(Text) %}
<li>TEXT</li>
... | 0 | 2016-06-07T21:22:23Z | 37,689,943 | <p>I'd be reluctant to code it like that. </p>
<p>First, you'll need to pass <code>Text</code> and <code>Image</code> in your context, and regardless <a href="http://stackoverflow.com/questions/2468804/how-to-call-function-that-takes-an-argument-in-a-django-template">you can't call a function in a template with parame... | 1 | 2016-06-07T21:46:43Z | [
"python",
"html",
"django",
"polymorphism",
"django-polymorphic"
] |
How to make argparse parsers also function as subparsers | 37,689,627 | <p>Say I have some parsers already defined:</p>
<pre><code>foo_parser = argparse.ArgumentParser()
foo_parser.add_argument('-f')
bar_parser = argparse.ArgumentParser()
bar_parser.add_argument('-b')
</code></pre>
<p>Now I want those parsers to appears as sub-parsers.</p>
<pre><code>parser = argparse.ArgumentParser(pr... | 1 | 2016-06-07T21:23:53Z | 37,690,694 | <p>Have you tried the <code>parents</code> mechanism? It's a way of populating a new parser (including a subparser) with arguments (and groups) from another parser. Some even use it as a way of adding a subset of arguments to multiple subparsers. It copies the arguments (Action objects) by reference. Usually that w... | 1 | 2016-06-07T22:52:49Z | [
"python",
"argparse"
] |
Max margin loss in TensorFlow | 37,689,632 | <p>I'm trying to implement a max margin loss in TensorFlow.
the idea is that I have some positive example and i sample some negative examples and want to compute something like</p>
<p><img src="http://latex.codecogs.com/gif.latex?%5Csum_%7Bb%7D%5E%7BB%7D%20%5Csum_%7Bn%7D%5E%7BN%7Dmax%280%2C%201%20-%20score%28p_b%29%20... | 1 | 2016-06-07T21:24:06Z | 37,690,029 | <p>First we need to clean the input:</p>
<ul>
<li>we want an array of positive scores, of shape <code>[B, 1]</code></li>
<li>we want a matrix of negative scores, of shape <code>[B, N]</code></li>
</ul>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
B = 2
N = 2
scores = tf.constant([0.5, 0.2,... | 2 | 2016-06-07T21:52:30Z | [
"python",
"machine-learning",
"tensorflow"
] |
Python -> Organizing a List Text File | 37,689,636 | <p>I am a new user of python. I have a list in .txt format (and .csv) like this</p>
<pre><code>NEW YORK ....... from
31 Chatty, Seager Aarhaus
Atlas, Jones Abertham
Polly, Manning Antwerpen
Amazon, Brittle Belchental
LONDON ........ for
31 Park Dattemroed
Eleanor, ... | 0 | 2016-06-07T21:24:16Z | 37,689,794 | <p>Here is one program that prints the output you want:</p>
<pre><code>with open('x.in') as input_file:
for line in input_file:
line = line.rstrip()
if '....' in line:
city = line
continue
print (city, line)
</code></pre>
<p>Result:</p>
<pre class="lang-none pretty... | 3 | 2016-06-07T21:36:00Z | [
"python",
"python-3.x"
] |
Python -> Organizing a List Text File | 37,689,636 | <p>I am a new user of python. I have a list in .txt format (and .csv) like this</p>
<pre><code>NEW YORK ....... from
31 Chatty, Seager Aarhaus
Atlas, Jones Abertham
Polly, Manning Antwerpen
Amazon, Brittle Belchental
LONDON ........ for
31 Park Dattemroed
Eleanor, ... | 0 | 2016-06-07T21:24:16Z | 37,689,795 | <p>If the city lines always have <code>.....</code> you can use a groupby:</p>
<pre><code>from itertools import groupby
with open(your_file) as f:
grps = groupby(f, key=lambda line: "......." in line)
for k,v in grps:
if k:
head = next(v).strip()
print("\n".join(["{} {}".format... | 1 | 2016-06-07T21:36:07Z | [
"python",
"python-3.x"
] |
Python -> Organizing a List Text File | 37,689,636 | <p>I am a new user of python. I have a list in .txt format (and .csv) like this</p>
<pre><code>NEW YORK ....... from
31 Chatty, Seager Aarhaus
Atlas, Jones Abertham
Polly, Manning Antwerpen
Amazon, Brittle Belchental
LONDON ........ for
31 Park Dattemroed
Eleanor, ... | 0 | 2016-06-07T21:24:16Z | 37,702,211 | <p>thank you! </p>
<p>Actually, I was trying to organise according to the uppercase words. By changing Padraic Cunningham code, I did this </p>
<pre><code>for line in Text:
newline = re.sub('^([A-Z][A-Z]+[A-Z])', '\\1â', line)
</code></pre>
<p>â is just something that shows there is an uppercase word and then</p... | 0 | 2016-06-08T12:14:39Z | [
"python",
"python-3.x"
] |
can't download and install python image library | 37,689,800 | <p>I'm trying to download and install pythons image library PIL or pillow. I've looked at this question (<a href="http://stackoverflow.com/questions/12024397/no-module-named-image">No module named Image</a>) and this question (<a href="http://stackoverflow.com/questions/20614185/cant-install-python-imaging-library-usin... | 0 | 2016-06-07T21:36:36Z | 37,689,960 | <p>Python 2.7 and 3.3 have their own package locations. Since you have version 2.7 and 3.3 installed, you must do the following:</p>
<pre><code>pip2 install pillow
</code></pre>
| 0 | 2016-06-07T21:47:44Z | [
"python",
"image"
] |
can't download and install python image library | 37,689,800 | <p>I'm trying to download and install pythons image library PIL or pillow. I've looked at this question (<a href="http://stackoverflow.com/questions/12024397/no-module-named-image">No module named Image</a>) and this question (<a href="http://stackoverflow.com/questions/20614185/cant-install-python-imaging-library-usin... | 0 | 2016-06-07T21:36:36Z | 37,690,040 | <p>You have to use sudo, and specify which version of pip:</p>
<p><code>sudo pip2 install Pillow</code><br>
or<br>
<code>sudo pip3 install Pillow</code></p>
<p>Also, did you read the <a href="http://pillow.readthedocs.io/en/3.2.x/installation.html" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>Pillow and P... | 0 | 2016-06-07T21:53:00Z | [
"python",
"image"
] |
What is tensorflow.compat.as_str()? | 37,689,802 | <p>In the <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/5_word2vec.ipynb" rel="nofollow">Google/Udemy Tensorflow tutorial</a> there is the following code:</p>
<pre><code>import tensorflow as tf
...
def read_data(filename):
"""Extract the first file enclosed in a zip file... | 1 | 2016-06-07T21:36:43Z | 37,690,601 | <ol>
<li><p><code>tf.compat.as_str</code> converts input into a string</p></li>
<li><p>I couldn't find any documentation, but you can look at the source code <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/util/compat.py" rel="nofollow">here</a></p></li>
<li><p>Tensorflow functions as a ... | 2 | 2016-06-07T22:45:02Z | [
"python",
"tensorflow"
] |
Select array element from Spark Dataframes split method in same call? | 37,689,878 | <p>I'm splitting an HTTP request to look at the elements, and I was wondering if there was a way to specify the element I'd like to look at in the same call without having to do another operation.</p>
<p>For example:</p>
<pre><code>from pyspark.sql import functions as fn
df.select(fn.split(df.http_request, '/').alia... | 1 | 2016-06-07T21:42:20Z | 37,690,606 | <p>Well you could define a <code>UDF</code>:</p>
<pre><code>from pyspark.sql.functions import *
from pyspark.sql.types import *
def getter(column, index):
return column[index]
getterUDF = udf(getter, StringType())
df.select(getterUDF(split(df.http_request, '/').alias('http'), lit(1)))
</code></pre>
| 2 | 2016-06-07T22:45:17Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-sql"
] |
Select array element from Spark Dataframes split method in same call? | 37,689,878 | <p>I'm splitting an HTTP request to look at the elements, and I was wondering if there was a way to specify the element I'd like to look at in the same call without having to do another operation.</p>
<p>For example:</p>
<pre><code>from pyspark.sql import functions as fn
df.select(fn.split(df.http_request, '/').alia... | 1 | 2016-06-07T21:42:20Z | 38,454,127 | <p>Use <a href="http://spark.apache.org/docs/2.0.0-preview/api/python/pyspark.sql.html#pyspark.sql.Column.getItem" rel="nofollow">getItem</a>. I'd say don't use python UDF just to make the code looks prettier - it's much slower than native DataFrame functions (due to moving data between python and JVM).</p>
<pre><code... | 1 | 2016-07-19T09:10:09Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-sql"
] |
Copying site-package into my own project for a 'local copy' | 37,689,905 | <p>I was curious how I copy over site-packages stuff like for instance in django-filer I used a pip install for it installed it to:</p>
<p><code>/usr/local/lib/python2.7/site-packages/filer</code></p>
<p>Which is fine, but the stuff inside that filer folder (like under <code>/static/filer/css</code> are things I woul... | 0 | 2016-06-07T21:44:19Z | 37,690,117 | <p>You could simply create a virtual environment which is completely isolated: <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/" rel="nofollow">http://docs.python-guide.org/en/latest/dev/virtualenvs/</a></p>
<hr>
<p><strong>virtualenv</strong></p>
<p>virtualenv is a tool to create isolated Python env... | 1 | 2016-06-07T21:58:35Z | [
"python",
"css",
"django",
"django-filer"
] |
Tensorflow LSTM pixel-wise classification | 37,689,920 | <p>How would one do pixel-wise classification for LSTM networks? Specifically, in Tensorflow.</p>
<p>My intuition tells me that the output tensors (<code>pred</code> &<code>y</code> from the code) should be a 2-dimensional tensor with the same resolution as the input image. In other words, the input image would be... | 1 | 2016-06-07T21:45:21Z | 37,690,202 | <p>You cannot do matrix multiplication with a matrix of shape <code>[n_hidden, n_input, n_step]</code> of dimension 3.<br>
What you can do is output a vector of dimension <code>[batch_size, n_input * n_step]</code> and then reshape it back to <code>[batch_size, n_input, n_step]</code>.</p>
<pre class="lang-py prettypr... | 1 | 2016-06-07T22:05:43Z | [
"python",
"machine-learning",
"neural-network",
"tensorflow",
"lstm"
] |
Need help on this error: ValueError: too many values to unpack | 37,689,924 | <pre><code>from xlrd import open_workbook
book = open_workbook('Workbook2.csv')
sheet = book.sheet_by_index(0)
keys = [sheet.cell(0,col_index).value for col_index in xrange(sheet.ncols)]
dict_list =[]
for row_index in xrange(1,sheet.nrows):
d={keys[col_index]: sheet.cell(row_index, col_index).value for col_index i... | 0 | 2016-06-07T21:45:40Z | 37,689,972 | <p>Try, if you're using Python 2:</p>
<pre><code>for key, val in dict_list[i].iteritems():
</code></pre>
<p>Or with Python 3:</p>
<pre><code>for key, val in dict_list[i].items():
</code></pre>
<p>Alternatively, if you want just the keys, or just the values, you can use <code>dict_list[i].keys()</code> and <code>dic... | 1 | 2016-06-07T21:48:21Z | [
"python"
] |
Grid-Search finding Parameters for AUC | 37,689,942 | <p>I'm trying to find the parameters for my SVM, which give me the best AUC. But i can't find any scoring function for AUC in sklearn. Does someone have an idea? Here is my Code:</p>
<pre><code> parameters = {"C":[0.1, 1, 10, 100, 1000], "gamma":[0.1, 0.01, 0.001, 0.0001, 0.00001]}
clf = SVC(kernel = "rbf")
... | 0 | 2016-06-07T21:46:38Z | 37,690,154 | <p>I haven't tried this but I believe you want to use the <code>sklearn.metrics.roc_auc_score</code>.</p>
<p>The problem is that it's not a model scorer, so you need to build one.
Something like:</p>
<pre><code>from sklearn.metrics import roc_auc_score
def score_auc(estimator, X, y):
y_score = estimator.predict_... | 0 | 2016-06-07T22:01:31Z | [
"python",
"scikit-learn",
"svm",
"grid-search"
] |
Grid-Search finding Parameters for AUC | 37,689,942 | <p>I'm trying to find the parameters for my SVM, which give me the best AUC. But i can't find any scoring function for AUC in sklearn. Does someone have an idea? Here is my Code:</p>
<pre><code> parameters = {"C":[0.1, 1, 10, 100, 1000], "gamma":[0.1, 0.01, 0.001, 0.0001, 0.00001]}
clf = SVC(kernel = "rbf")
... | 0 | 2016-06-07T21:46:38Z | 37,696,446 | <p>You can simply use:</p>
<pre><code>clf = GridSearchCV(clf, parameters, scoring='roc_auc')
</code></pre>
| 0 | 2016-06-08T07:53:10Z | [
"python",
"scikit-learn",
"svm",
"grid-search"
] |
Finding files that have a numeric suffix in Python | 37,689,986 | <p>Prefacing this by saying I'm completely new to Python, but not new to programming.</p>
<p>I've been experimenting with glob.glob in compiling lists of file names for further analysis.</p>
<p>I have files that follow a format like the following:</p>
<ul>
<li>File 1.csv</li>
<li>File 2.csv</li>
<li>File 3.csv</li>
... | 2 | 2016-06-07T21:49:06Z | 37,690,208 | <p>You cannot match an arbitrary amount of digits with glob, if you wanted to specifically match <code>File some_digits.csv</code> you will need a regex:</p>
<pre><code>import glob
import re
import os
patt = re.compile(r"File \d+\.csv")
for f in os.listdir("."):
if patt.match(f):
print(f)
</code></pre>
<p... | 3 | 2016-06-07T22:06:04Z | [
"python"
] |
Finding files that have a numeric suffix in Python | 37,689,986 | <p>Prefacing this by saying I'm completely new to Python, but not new to programming.</p>
<p>I've been experimenting with glob.glob in compiling lists of file names for further analysis.</p>
<p>I have files that follow a format like the following:</p>
<ul>
<li>File 1.csv</li>
<li>File 2.csv</li>
<li>File 3.csv</li>
... | 2 | 2016-06-07T21:49:06Z | 37,690,282 | <p>Do it in two steps:</p>
<pre><code>import glob
import re
# First match all files which fit the general pattern (will match things
# like "File name without numbers.csv"
gross_match = glob.glob("File *.csv")
# Filter the list with a precise regular expression
my_files = [fname for fname in gross_match if match("Fil... | 0 | 2016-06-07T22:13:01Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.