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 |
|---|---|---|---|---|---|---|---|---|---|
how to get the values from fields as a variable | 38,875,124 | <p>I got a piece of code and I want to change it for my project, but I don't know how to get the value of my entries has a variable to be used in the <code>start</code> function. Here is my code:</p>
<pre><code>#!/usr/bin/python3
import wiringpi
from time import sleep
gpio = wiringpi.GPIO(wiringpi.GPIO.WPI_MODE_GPIO)
... | -1 | 2016-08-10T13:40:22Z | 38,883,206 | <p>You seem to have the right idea on the <code>fetch function</code> part of your code, to access the typed text in a Entry Box on Tkinter, you can use the <code>.get()</code> function, like so:</p>
<pre><code># main tk window
root = Tk()
# creates the entry_box
entry_box = Entry(root, text='')
# places the entry_box... | 1 | 2016-08-10T20:45:12Z | [
"python",
"tkinter"
] |
Use Flask to run a python script using javascript | 38,875,202 | <p>I want to run a python script using javascript. </p>
<p>I installed Flask.</p>
<p>this is my html code : </p>
<pre><code><input type="button" value="tester" onclick="addImage()" />
<p id="result"></p>
<script>
function callPy(data1, data2){
$.ajax({
type: "POST",
url:... | -2 | 2016-08-10T13:43:34Z | 38,925,010 | <p>First, the parameter name for the allowed methods is <code>methods</code> (not <code>method</code>) and it accepts a list with the allowed methods. In this case, it will have only one element.</p>
<pre class="lang-py prettyprint-override"><code>@app.route('/test', methods=['POST'])
</code></pre>
<p>With this, the ... | 0 | 2016-08-12T19:14:09Z | [
"javascript",
"python",
"html",
"flask"
] |
Share Odoo Dashboard to all users | 38,875,222 | <p>How can I share my customized dashboard for all users, I found that every customized dashboard created is stored on customized views, then to share a dashboard you should duplicate the customized view corresponding to that dashboard, and change the user field.</p>
<p>Is there a better solution ?</p>
| 0 | 2016-08-10T13:44:45Z | 38,877,250 | <p>I fear without changing some base elements of Odoo there is no other solution than duplicating the views and change the user, because the field user is required.</p>
| 0 | 2016-08-10T15:08:59Z | [
"python",
"openerp",
"odoo-8",
"dashboard"
] |
Share Odoo Dashboard to all users | 38,875,222 | <p>How can I share my customized dashboard for all users, I found that every customized dashboard created is stored on customized views, then to share a dashboard you should duplicate the customized view corresponding to that dashboard, and change the user field.</p>
<p>Is there a better solution ?</p>
| 0 | 2016-08-10T13:44:45Z | 38,877,788 | <p>There is a workaround which you can apply by overriding the default board module, and removing the user filter.</p>
<pre><code>from openerp import SUPERUSER_ID
from openerp.osv import fields, osv
from operator import itemgetter
from textwrap import dedent
class board(osv.osv):
_inherit = 'board.board'
d... | 1 | 2016-08-10T15:31:38Z | [
"python",
"openerp",
"odoo-8",
"dashboard"
] |
Making random intial position by Python | 38,875,304 | <p>I am now working to make rotational trajectories. In the begining I need to define the intial position of an rotating object. Can you please suggest me about how to make 1000 random intial position in three dimensions of this kind of object by Python or NumPy? I think a python function can solve the problem.</p>
| 0 | 2016-08-10T13:47:51Z | 38,878,247 | <p>If I understand the question, you need to pick up point uniformly distributed on a sphere. See <a href="http://mathworld.wolfram.com/SpherePointPicking.html" rel="nofollow">here</a> for details.</p>
<pre><code>import math
import numpy as np
cos_theta = 2.0 * np.random.random(100) - 1.0
phi = 2.0 * math.pi * ... | 0 | 2016-08-10T15:53:34Z | [
"python",
"numpy",
"random",
"position"
] |
Why exceptions in asnycio are late or do not appear at all? | 38,875,361 | <p>Sometimes after using <code>async/await</code> syntax I see the program no longer work correctly. But there are no any exceptions.
For example:</p>
<pre><code>async def my_func(self):
async with self.engine() as conn:
print('step1') # step1 shows in console
await conn.exceute("INSERT INTO bla-bla")
... | 1 | 2016-08-10T13:50:24Z | 38,890,966 | <p>Exception is raised, stack is unrolled.</p>
<p>The real question is: what do you use to run your coroutine?</p>
<p><code>loop.run_until_complete(my_func())</code> will process an exception as you are expecting. Another usage scenarios may differ.</p>
| 1 | 2016-08-11T08:21:16Z | [
"python",
"exception",
"async-await",
"future",
"python-asyncio"
] |
Python multiprocessing - graceful exit when an unhandled exception occurs | 38,875,378 | <p>The logic of my multiprocessing program that tries to handle exceptions in processes is pretty much like the following:</p>
<pre><code>import multiprocessing
class CriticalError(Exception):
def __init__(self, error_message):
print error_message
q.put("exit")
def foo_process():
while True... | 0 | 2016-08-10T13:50:59Z | 38,875,737 | <p>Since the child will die on exception anyway (i.e. <code>p.terminate()</code> is pointless) then why not let the master process check if its child is still alive?</p>
<pre><code>from queue import Empty
# from Queue import Empty # if Python 2.x
while not q.empty():
if not p.is_alive():
break
try:
... | 0 | 2016-08-10T14:06:48Z | [
"python",
"exception",
"multiprocessing",
"unhandled"
] |
Using MySQLdb Python module with mysql_old_password | 38,875,477 | <p>I need to use Python to connect to a database that uses the mysql_old_password authentication plugin. I do not have db admin access so I cannot change this setting, so please do not suggest that.</p>
<p>I just installed the MySQLdb module, downloaded <a href="https://pypi.python.org/pypi/MySQL-python/1.2.5" rel="no... | 1 | 2016-08-10T13:55:39Z | 38,877,145 | <p><code>mysql_old_password</code> support was removed from the mysql client libraries in <a href="http://dev.mysql.com/doc/refman/5.7/en/password-hashing.html" rel="nofollow">5.7.5</a>, so you're probably using a newer version of the client libraries then that.</p>
<p>You'll have to downgrade your client library vers... | 2 | 2016-08-10T15:04:43Z | [
"python",
"mysql",
"mysql-python"
] |
Transform list with regex | 38,875,489 | <p>I have a list that has elements in this form,the strings may change but the formats stay similar:</p>
<pre><code>["Radio0","Tether0","Serial0/0","Eth0/0","Eth0/1","Eth1/0","Eth1/1","vlanX","modem0","modem1","modem2","modem3","modem6"]
</code></pre>
<p>I would like to transform it to the list below. You can see it ... | 7 | 2016-08-10T13:56:05Z | 38,876,923 | <pre><code>import re
def particular_case(string):
return re.sub("\d+", "X", re.sub("\d+/\d+", "X/Y", w))
def generic_case(string, letters=['X', 'Y', 'Z']):
len_letters = len(letters)
list_matches = list(re.finditer(r'\d+', string))
result, last_index = "", 0
if len(list_matches) == 0:
r... | 1 | 2016-08-10T14:55:15Z | [
"python",
"regex"
] |
Transform list with regex | 38,875,489 | <p>I have a list that has elements in this form,the strings may change but the formats stay similar:</p>
<pre><code>["Radio0","Tether0","Serial0/0","Eth0/0","Eth0/1","Eth1/0","Eth1/1","vlanX","modem0","modem1","modem2","modem3","modem6"]
</code></pre>
<p>I would like to transform it to the list below. You can see it ... | 7 | 2016-08-10T13:56:05Z | 38,877,056 | <p>The following code should be general enough to allow for up to 3 numbers in the strings, but you can simply change the <em>repl</em> variable to allow for more.</p>
<pre><code>import re
elements = ["Radio0","Tether0","Serial0/0","Eth0/0","Eth0/1","Eth1/0","Eth1/1","vlanX","modem0","modem1","modem2","modem3","modem... | 2 | 2016-08-10T15:01:10Z | [
"python",
"regex"
] |
Transform list with regex | 38,875,489 | <p>I have a list that has elements in this form,the strings may change but the formats stay similar:</p>
<pre><code>["Radio0","Tether0","Serial0/0","Eth0/0","Eth0/1","Eth1/0","Eth1/1","vlanX","modem0","modem1","modem2","modem3","modem6"]
</code></pre>
<p>I would like to transform it to the list below. You can see it ... | 7 | 2016-08-10T13:56:05Z | 38,877,128 | <p>I used <a href="https://docs.python.org/2/library/re.html#re.finditer" rel="nofollow"><code>re.finditer</code></a> to find and replace all numbers:</p>
<pre><code>def repl(string):
#use regex to find all numbers
numbers= re.finditer(r'\d+', string)
#replace the numbers with letters. zip will stop when ... | 1 | 2016-08-10T15:04:19Z | [
"python",
"regex"
] |
Transform list with regex | 38,875,489 | <p>I have a list that has elements in this form,the strings may change but the formats stay similar:</p>
<pre><code>["Radio0","Tether0","Serial0/0","Eth0/0","Eth0/1","Eth1/0","Eth1/1","vlanX","modem0","modem1","modem2","modem3","modem6"]
</code></pre>
<p>I would like to transform it to the list below. You can see it ... | 7 | 2016-08-10T13:56:05Z | 38,877,154 | <p>You could go for:</p>
<pre><code>import re
rx = r'\d+'
incoming = ["Radio0","Tether0","Serial0/0","Eth0/0","Eth0/1","Eth1/0","Eth1/1","vlanX","modem0","modem1","modem2","modem3","modem6"]
outgoing = []
for item in incoming:
t = re.sub(rx, 'X', item)
if t not in outgoing:
outgoing.append(t)
print(o... | 1 | 2016-08-10T15:04:59Z | [
"python",
"regex"
] |
Transform list with regex | 38,875,489 | <p>I have a list that has elements in this form,the strings may change but the formats stay similar:</p>
<pre><code>["Radio0","Tether0","Serial0/0","Eth0/0","Eth0/1","Eth1/0","Eth1/1","vlanX","modem0","modem1","modem2","modem3","modem6"]
</code></pre>
<p>I would like to transform it to the list below. You can see it ... | 7 | 2016-08-10T13:56:05Z | 38,878,478 | <pre><code>import re
import functools
lst = ["Radio0","Tether0","Serial0/0","Eth0/0","Eth0/1","Eth1/0","Eth1/1","vlanX","modem0","modem1","modem2","modem3","modem6"]
def process_str(s, letters='XY'):
return functools.reduce(lambda txt, letter: re.sub(r'\d+', letter, txt, 1), letters, s)
r = set(map(process_str, ... | 1 | 2016-08-10T16:05:22Z | [
"python",
"regex"
] |
Changing the field name from inherited model? | 38,875,530 | <p>Is changing names of fields even possible?
so I have two models,</p>
<pre><code>class ChangeLog(IpHandlerModel):
id = models.AutoField(primary_key=True)
change_operations = models.CharField(max_length=1, choices=CHANGE_OPERATION_CHOICES)
change_type = models.CharField(max_length=3, choices=CHANGE_TYPE_C... | -1 | 2016-08-10T13:57:33Z | 38,876,638 | <p>I am not sure if it is possible to change it. But what you could do, is to create a new field with the new name. And link it to the other field. So any save of either ChangeLog or ChangeLogArchive overwrites the value in the new field original_ip_assign_ts.</p>
<p>Just an idea.</p>
| 1 | 2016-08-10T14:44:08Z | [
"python",
"django",
"inheritance",
"django-models"
] |
Mongo Cursor not returnning a cursor but an object | 38,875,609 | <pre><code>test_cursor = db.command({
"aggregate": "New_layout",
"pipeline": [
{ "$match": { "$and": [
{ "FIRST_DATE": { "$gte": new_date } },
{ "CHAIN_ID": { "$ne": "" } }
] } },
{ "$unwind": { "path": "$ENTERS", "includeArrayIndex": "Date" } },
{ "$proje... | 0 | 2016-08-10T14:00:39Z | 38,876,620 | <p>You should use <a href="http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.aggregate" rel="nofollow">aggregate()</a> instead of <a href="http://api.mongodb.com/python/current/api/pymongo/database.html#pymongo.database.Database.command" rel="nofollow">command()</a>.</p>
<... | 0 | 2016-08-10T14:43:24Z | [
"python",
"mongodb",
"pymongo",
"aggregation-framework",
"mongodb-aggregation"
] |
(cr, uid, frozendict(context) TypeError: 'float' object is not iterable | 38,875,735 | <p>I'm trying to update a field using onchange method in odoo.</p>
<p>My .py code is </p>
<pre><code>class hr_contract(osv.osv):
_name = 'hr.contract'
_description = 'Contract'
def _wage(self, cr, uid, ids,context=None):
res = {}
pay_slip = 0
pay_slip1 = 0
for obj in self.browse(cr,... | -1 | 2016-08-10T14:06:45Z | 38,876,100 | <p>This is waht the <code>TypeError: 'float' object is not iterable"</code> means :-</p>
<p><code>count=7</code> for say then <code>for i in count:</code> means <code>for i in 7:</code>, which won't work. The bit after the <code>in</code> should be of an iterable type, not a number. Try this:</p>
<pre><code>for i in ... | 0 | 2016-08-10T14:21:58Z | [
"python",
"typeerror"
] |
Count unique dates in pandas dataframe | 38,875,752 | <p>I have a dataframe of surface weather observations (<code>fzraHrObs</code>) organized by a station identifier code and date. <code>fzraHrObs</code> has several columns of weather data. The station code and date (datetime objects) look like:</p>
<pre><code>usaf dat
716270 2014-11-23 12:00:00
2015-1... | 2 | 2016-08-10T14:07:18Z | 38,876,702 | <p>Could be something like this, group the date by <code>usaf</code> and <code>year</code> and then count the number of unique values:</p>
<pre><code>import pandas as pd
df.dat.apply(lambda dt: dt.date()).groupby([df.usaf, df.dat.apply(lambda dt: dt.year)]).nunique()
# usaf dat
# 716270 2014 1
# 2015... | 1 | 2016-08-10T14:46:48Z | [
"python",
"pandas"
] |
Count unique dates in pandas dataframe | 38,875,752 | <p>I have a dataframe of surface weather observations (<code>fzraHrObs</code>) organized by a station identifier code and date. <code>fzraHrObs</code> has several columns of weather data. The station code and date (datetime objects) look like:</p>
<pre><code>usaf dat
716270 2014-11-23 12:00:00
2015-1... | 2 | 2016-08-10T14:07:18Z | 38,876,722 | <p>The following should work:</p>
<pre><code>df.groupby(['usaf', df.dat.dt.year])['dat'].apply(lambda s: s.dt.date.nunique())
</code></pre>
<p>What I did differently is group by two levels only, then use the <code>nunique</code> method of pandas series to count the number of unique dates in each group.</p>
| 2 | 2016-08-10T14:47:22Z | [
"python",
"pandas"
] |
How to extract specific fields from a list in Python | 38,875,815 | <p>Here is an example of 1 line form a large List, I save 200,000 such lines into a file one after the other for easier readability.</p>
<pre><code>['{activities:[{activity:121,dbCount:234,totalHits:4,query:Identification', 'and', 'prioritization', 'of', 'merozoite,searchedFrom:PersistentLink,searchType:And,logTime:14... | -4 | 2016-08-10T14:09:53Z | 38,876,131 | <p>Your line looks very weird. However, assuming you store the line in a single string variable called 'mystring' you could do something like the following to parse out the value of query:</p>
<pre><code> query = mystring[mystring.find("query:"):mystring.find("searchedFrom:")]
</code></pre>
<p>this would produce: </p... | 0 | 2016-08-10T14:23:10Z | [
"python"
] |
How to extract specific fields from a list in Python | 38,875,815 | <p>Here is an example of 1 line form a large List, I save 200,000 such lines into a file one after the other for easier readability.</p>
<pre><code>['{activities:[{activity:121,dbCount:234,totalHits:4,query:Identification', 'and', 'prioritization', 'of', 'merozoite,searchedFrom:PersistentLink,searchType:And,logTime:14... | -4 | 2016-08-10T14:09:53Z | 38,877,563 | <p>So, I made couple of changes and used your code like here to get the desired field query in response, but what if I want all 4 fields altogether at once ? </p>
<pre><code>mystring = ['{activities:[{activity:121,dbCount:234,totalHits:4,query:Identification', 'and', 'prioritization', 'of', 'merozoite,searchedFrom:... | 0 | 2016-08-10T15:22:19Z | [
"python"
] |
How to extract specific fields from a list in Python | 38,875,815 | <p>Here is an example of 1 line form a large List, I save 200,000 such lines into a file one after the other for easier readability.</p>
<pre><code>['{activities:[{activity:121,dbCount:234,totalHits:4,query:Identification', 'and', 'prioritization', 'of', 'merozoite,searchedFrom:PersistentLink,searchType:And,logTime:14... | -4 | 2016-08-10T14:09:53Z | 38,877,626 | <p>Using a the following <strong>regex</strong> -> <code>(query|an|dbCount|shortDbName|profileId):([A-Za-z0-9]*)</code> we should be able to capture the <strong>key/value</strong>
pair from these fields. This should match any of those key words you mentioned followed by a <code>:</code> (<em>doesn't capture</em>) and ... | 1 | 2016-08-10T15:24:26Z | [
"python"
] |
Django hstore field in sqlite | 38,875,927 | <p>I am using sqlite (development stage) database for my django project. I would like to store a dictionary field in a model. In this respect, i would like to use django-hstore field in my model. </p>
<p>My question is, can i use django-hstore dictionary field in my model even though i am using sqlite as my database? ... | 0 | 2016-08-10T14:15:06Z | 38,875,962 | <p>hstore is specific to Postgres. It won't work on sqlite.</p>
<p>If you just want to store JSON, and don't need to search within it, then you can use one of the many third-party JSONField implementations.</p>
| 0 | 2016-08-10T14:16:25Z | [
"python",
"django",
"postgresql",
"sqlite",
"django-models"
] |
class and methods in python. introduction in oop | 38,875,928 | <pre><code>class Person:
def __init__(self, name):
"""Make a new person with the given name."""
self.myname = name
def introduction(myname):
"""Returns an introduction for this person."""
return "Hi, my name is {}.".format(myname)
# Use the class to introduce Mark and Steve
mar... | 0 | 2016-08-10T14:15:16Z | 38,876,043 | <p>You need to declare <code>introduction()</code> -> <code>introduction(self)</code> as an instance method (<em>by passing in</em> <code>self</code>) to be able to access the instance variable <code>self.myname</code>. </p>
<pre><code>class Person:
def __init__(self, name):
"""Make a new person with the ... | 2 | 2016-08-10T14:19:54Z | [
"python",
"class",
"oop",
"object",
"methods"
] |
class and methods in python. introduction in oop | 38,875,928 | <pre><code>class Person:
def __init__(self, name):
"""Make a new person with the given name."""
self.myname = name
def introduction(myname):
"""Returns an introduction for this person."""
return "Hi, my name is {}.".format(myname)
# Use the class to introduce Mark and Steve
mar... | 0 | 2016-08-10T14:15:16Z | 38,876,086 | <p>It should be printing the object's representation in memory (something along the lines of <code>Hi, my name is <__main__.Person object at 0x005CEA10></code>).</p>
<p>The reason is that the first argument of a method is expected to be the object that the method is called upon.</p>
<p>Just like you have <code>... | 3 | 2016-08-10T14:21:12Z | [
"python",
"class",
"oop",
"object",
"methods"
] |
class and methods in python. introduction in oop | 38,875,928 | <pre><code>class Person:
def __init__(self, name):
"""Make a new person with the given name."""
self.myname = name
def introduction(myname):
"""Returns an introduction for this person."""
return "Hi, my name is {}.".format(myname)
# Use the class to introduce Mark and Steve
mar... | 0 | 2016-08-10T14:15:16Z | 38,876,212 | <p>Your problem is that your giving your introduction method the parameter <code>myname</code>, but never supplying it with a valid argument.You can simply do:</p>
<pre><code>mark = Person(" Mark")
steve = Person(" Steve")
print(mark.introduction(mark.myname))
print(steve.introduction(steve.myname))
</code></pre>
<... | 0 | 2016-08-10T14:26:25Z | [
"python",
"class",
"oop",
"object",
"methods"
] |
Running R's aov() mixed effects model from Python using rpy2 | 38,876,274 | <p>First to see if rpy2 was working properly I ran a simple model (stats.lm):</p>
<pre><code>import pandas as pd
from rpy2 import robjects as ro
from rpy2.robjects import pandas2ri
pandas2ri.activate()
from rpy2.robjects.packages import importr
stats = importr('stats')
R = ro.r
df = pd.DataFrame(data={'subject':['1','... | 1 | 2016-08-10T14:29:12Z | 38,883,975 | <p>[Voting up just because you have a nice small and self-contained example.]</p>
<p>The R equivalent of what you are doing with rpy2 is the following (and returns the same error)</p>
<pre><code>> mixed <- aov("result ~ group*session + covar + Error(as.factor(subject)/session)",data=df)
Error: $ operator is inv... | 1 | 2016-08-10T21:35:37Z | [
"python",
"pandas",
"rpy2"
] |
Anaconda selenium and Chrome | 38,876,281 | <p>I am running selenium through anaconda on my mac. To be able to choose Chrome as my webdriver I need to download the latest chromedriver. But I can't figure out where to put the file for it to be in path.
If I just run </p>
<pre><code>driver = webdriver.Chrome()
WebDriverException: Message: unknown error: cannot f... | 1 | 2016-08-10T14:29:38Z | 38,876,780 | <p>You can start up your selenium server and specify where the chrome driver is:</p>
<pre><code>java -jar selenium.jar -Dwebdriver.chrome.driver=/~path/chromedriver
</code></pre>
| 0 | 2016-08-10T14:49:32Z | [
"python",
"google-chrome",
"selenium"
] |
Python Introspection with Object Inheritance | 38,876,335 | <p>I'm working with an older version of python, 2.6.5. I can use dir to see what members an object has but I'd like to differentiate among the members in an object versus the members inherited from a parent class.</p>
<pre><code>class Parent(object):
def parent_method1(self):
return 1
def parent_me... | 1 | 2016-08-10T14:31:55Z | 38,876,378 | <p>No, <code>dir()</code> does not give that distinction.</p>
<p>You'd have to manually traverse the <a href="https://docs.python.org/2/library/stdtypes.html#class.__mro__" rel="nofollow">class MRO</a> and produce the list yourself:</p>
<pre><code>def dir_with_context(cls):
for c in cls.__mro__:
for name ... | 2 | 2016-08-10T14:34:03Z | [
"python",
"inheritance",
"python-2.6"
] |
Make Matplotlib Button callback take effect immediately rather than after moving mouse off the button | 38,876,353 | <p>I'm trying to make a GUI for the game of Tic Tac Toe using Matplotlib. So far, I've made an array of buttons which change their labels to "X" when clicked:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
def callback(event, button):
print button
butto... | 1 | 2016-08-10T14:32:53Z | 38,887,865 | <p>You just need to add a call to <code>draw_idle</code> which asks the GUI to repaint the window (which in turn re-draws the figure) the next time it is convenient.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
def callback(event, button):
print(button)
... | 1 | 2016-08-11T05:26:13Z | [
"python",
"matplotlib"
] |
How to convert from RGB values to color temperature? | 38,876,429 | <p>How does one take a color expressed in an RGB value (say, three coordinates from 0-255) and produce from it a <a href="https://en.wikipedia.org/wiki/Color_temperature" rel="nofollow">color temperature</a> in kelvin (or mireds)?</p>
<p>I see <a href="http://stackoverflow.com/questions/13975917/calculate-colour-tempe... | 3 | 2016-08-10T14:36:11Z | 38,889,696 | <p>You could use <a href="https://github.com/colour-science/colour/" rel="nofollow">Colour</a> to perform that computation using the <code>colour.xy_to_CCT_Hernandez1999</code> definition:</p>
<pre class="lang-python prettyprint-override"><code> import numpy as np
import colour
# Assuming sRGB encoded colour val... | 2 | 2016-08-11T07:16:13Z | [
"python",
"colors"
] |
Best way to save/load list of strings and the file will be manipulated by two Python scripts at the same time | 38,876,441 | <p>I will create two Python scripts. One will generate strings and save them to a file. The other will traverse through the list of string from the top down, do operations on each string and then delete the string when done.</p>
<p>I would like to know which file type can best satisfy this purpose (e.g. pickle, json, ... | 2 | 2016-08-10T14:36:28Z | 38,876,740 | <p>If the first script just writes the file once and then at some point the second script has to read it, I would use csv (or just plain text and the elements separated by a coma).</p>
<p>If the second file has to read periodically the strings that the first writes I would use a socket to send it to the second script.... | 1 | 2016-08-10T14:48:04Z | [
"python",
"json",
"string",
"list",
"pickle"
] |
numpy - How to compare custom dtypes conveniently? | 38,876,516 | <p>I have a dtype that has more than 30 fields. I want to compare two objects with that dtype so that I know exactly which fields are unequal. A trivial solution would be to hard-code each field comparison in a series of if statements: </p>
<pre><code>if (obj1['field1']==obj2['field1']) DO_SOMETHING
if (obj1['field2'... | 1 | 2016-08-10T14:39:27Z | 38,878,485 | <p>You can access an object's dtype fields by <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.names.html" rel="nofollow"><code>OBJECT.dtype.names</code></a>. So: </p>
<pre><code># obj1 and obj2 are elements in a numpy array with a custom dtype
for field in obj1.dtype.names:
if obj1[field]... | 2 | 2016-08-10T16:05:58Z | [
"python",
"numpy"
] |
python Django repeat url many times | 38,876,624 | <p>I'm a starter of Django1.10. I just started play around with it. I am trying to show an image on website.</p>
<p>This is myproject/settings.py:</p>
<pre><code>MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
</code></pre>
<p>and myproject/urls.py</p>
<pre><code>from django.conf.urls import ur... | 0 | 2016-08-10T14:43:36Z | 38,876,779 | <p>Have you checked how the URL looks in the generated HTML code? E.g. does the URL look correct when the HTML is loaded, and when you click it, it starts repeating it?</p>
| 0 | 2016-08-10T14:49:31Z | [
"python",
"django",
"django-models",
"django-urls"
] |
python Django repeat url many times | 38,876,624 | <p>I'm a starter of Django1.10. I just started play around with it. I am trying to show an image on website.</p>
<p>This is myproject/settings.py:</p>
<pre><code>MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
</code></pre>
<p>and myproject/urls.py</p>
<pre><code>from django.conf.urls import ur... | 0 | 2016-08-10T14:43:36Z | 38,877,261 | <p>First of all I think you are missing a forwardshals in your <code>models.py</code> on line :</p>
<pre><code>info_image = models.ImageField(upload_to='images/%Y%m/%d')
</code></pre>
<p>Unless it's your intention, I think it should be like this:</p>
<pre><code>info_image = models.ImageField(upload_to='images/%Y/%m/... | 1 | 2016-08-10T15:09:25Z | [
"python",
"django",
"django-models",
"django-urls"
] |
Error occurs when I use pyenv? | 38,876,645 | <p>When I tried to use pyenv install, an error occurred. I'm not sure how to solve this problem. Any help will be appreciated.</p>
<pre><code>DennisdeMacBook-Pro:~ Dennis$ pyenv install 3.5.2
Downloading Python-3.5.2.tar.xz...
-> https://www.python.org/ftp/python/3.5.2/Python-3.5.2.tar.xz
Installing Python-3.5.2...... | 0 | 2016-08-10T14:44:17Z | 38,877,283 | <p>Use Xcode:</p>
<pre><code>xcode-select --install
</code></pre>
| 0 | 2016-08-10T15:10:29Z | [
"python",
"python-2.7",
"install",
"homebrew",
"pyenv"
] |
Flask threaded = True? | 38,876,721 | <p>What exactly does putting <code>threaded = True</code> in my <code>app.run()</code> do?</p>
<p>My application processes input from the user, and takes a bit of time to do so. During this time, the application is unable to handle other requests.</p>
<p>I'm looking at options that allow me to handle more than 1 requ... | 1 | 2016-08-10T14:47:22Z | 38,876,910 | <pre><code>How many requests will my application be able to handle concurrently with this statement?
</code></pre>
<p>This depends drastically on your application. Each new request will have a thread launched- it depends on how many threads your machine can handle. I don't see an option to limit the number of thread... | 1 | 2016-08-10T14:54:45Z | [
"python",
"flask"
] |
Flask threaded = True? | 38,876,721 | <p>What exactly does putting <code>threaded = True</code> in my <code>app.run()</code> do?</p>
<p>My application processes input from the user, and takes a bit of time to do so. During this time, the application is unable to handle other requests.</p>
<p>I'm looking at options that allow me to handle more than 1 requ... | 1 | 2016-08-10T14:47:22Z | 38,876,915 | <p>Normally, the WSGI server included with Flask is run in single-threaded mode, and can only handle one request at a time. Any parallel requests will have to wait until they can be handled, which can lead to issues if you <a href="https://stackoverflow.com/questions/12591760/flask-broken-pipe-with-requests">tried to c... | 2 | 2016-08-10T14:54:53Z | [
"python",
"flask"
] |
Python web scraping, symbols meaning | 38,876,805 | <p>In below code, what does each and every element of the symbol string <code>re.sub('<[^>]*>|[\n]|\[[0-9]*\]', '', htmlread)</code> mean? </p>
<pre><code>import urllib2
import re
htmltext = urllib2.urlopen("https://en.wikipedia.org/wiki/Linkin_Park")
htmlread = htmltext.read()
htmlread = re.sub('<[^>]... | 0 | 2016-08-10T14:50:49Z | 38,876,926 | <p>The line <code>htmlread = re.sub('<[^>]*>|[\n]|\[[0-9]*\]', '', htmlread)</code> removes either</p>
<ul>
<li>an expression between <code><></code> OR</li>
<li>a newline</li>
<li>a number between brackets or empty brackets</li>
</ul>
<p>from htmlread</p>
<p>interesting wiki post here: <a href="http:... | 0 | 2016-08-10T14:55:25Z | [
"python",
"web-scraping"
] |
Python web scraping, symbols meaning | 38,876,805 | <p>In below code, what does each and every element of the symbol string <code>re.sub('<[^>]*>|[\n]|\[[0-9]*\]', '', htmlread)</code> mean? </p>
<pre><code>import urllib2
import re
htmltext = urllib2.urlopen("https://en.wikipedia.org/wiki/Linkin_Park")
htmlread = htmltext.read()
htmlread = re.sub('<[^>]... | 0 | 2016-08-10T14:50:49Z | 38,876,927 | <p>Replace every character with '', that means delete it from htmlread variable</p>
<p>Please read more about RegEx</p>
| 0 | 2016-08-10T14:55:26Z | [
"python",
"web-scraping"
] |
Change Value of a Dataframe Column Based on a Filter | 38,876,816 | <p>I have a Dataframe that consists of 2 columns: </p>
<ol>
<li>"Time Spent on website"</li>
<li>"Dollars spent on the website"</li>
</ol>
<p>I want to perform some classification analysis on this dataset and I only care whether a user made a purchase or not. So I want to run through the "Dollars spent on the websit... | 0 | 2016-08-10T14:51:12Z | 38,876,924 | <pre><code>df['purchase'] = 0
df.loc[df['dollars_spent'] > 0, 'purchase'] = 1
</code></pre>
<p>or</p>
<pre><code>df['purchase'] = df['dollars_spent'].apply(lambda x: 1 if x > 0 else 0)
</code></pre>
| 0 | 2016-08-10T14:55:15Z | [
"python",
"pandas",
"dataframe"
] |
programmatically send outlook email from shared mailbox | 38,876,817 | <p>I'm trying to send an email with python from a shared mailbox.</p>
<p>I have been able to sucessfuly send it through my own email, but sending one with a shared mailbox (that I have tested that I have access too) is giving me issues.</p>
<p>Code used for email script in python
<code>
import win32com.clien... | 0 | 2016-08-10T14:51:13Z | 38,878,250 | <p>In case if you have multiple accounts configured in Outlook you may use the <a href="https://msdn.microsoft.com/en-us/library/office/ff869311.aspx?f=255&MSPPError=-2147217396" rel="nofollow">SendUsingAccount</a> property of the MailItem class. Or if you have sufficient privileges (rights) you may consider using ... | 1 | 2016-08-10T15:53:44Z | [
"python",
"windows",
"email",
"outlook",
"outlook-2010"
] |
programmatically send outlook email from shared mailbox | 38,876,817 | <p>I'm trying to send an email with python from a shared mailbox.</p>
<p>I have been able to sucessfuly send it through my own email, but sending one with a shared mailbox (that I have tested that I have access too) is giving me issues.</p>
<p>Code used for email script in python
<code>
import win32com.clien... | 0 | 2016-08-10T14:51:13Z | 38,882,759 | <p>Added this right before the <code>newMail.send()</code> step and it worked</p>
<pre><code>newMail.SentOnBehalfOfName = 'SharedFolder'
</code></pre>
| 0 | 2016-08-10T20:17:23Z | [
"python",
"windows",
"email",
"outlook",
"outlook-2010"
] |
How to use eventlet library for async gunicorn workers | 38,876,827 | <p>One of my django projects is deployed using <strong>ansible (gunicorn & nginx)</strong>. Below is <strong>gunicorn</strong> configuration :</p>
<pre><code>bind = '127.0.0.1:8001'
backlog = 2048
workers = 8
worker_class = 'sync'
worker_connections = 1000
timeout = 300
keepalive = 2
spew = False
daemon = False... | 2 | 2016-08-10T14:51:29Z | 38,894,879 | <p>You've already done everything required. <code>worker_class = eventlet</code> or <code>gunicorn -k eventlet</code> is enough to run HTTP request handlers concurrently. And then you can serve many concurrent requests with sleep or IO in their handlers.</p>
| 1 | 2016-08-11T11:16:32Z | [
"python",
"django",
"gunicorn",
"eventlet",
"green-threads"
] |
Python: how to pass a file from a zip to a function that reads data from that file | 38,876,829 | <p>I have a zip-file that contains <a href="https://github.com/mhe/pynrrd" rel="nofollow">.nrrd</a> type files. The pynrrd lib comes with a read function. How can I pull the <code>.nrrd</code> file from the zip and pass it to the <code>nrrd.read()</code> function?</p>
<p>I tried following, but that gives the following... | 1 | 2016-08-10T14:51:35Z | 38,876,954 | <p>I think that your is a good way... </p>
<p>Here there is a similar question: </p>
<p><a href="http://stackoverflow.com/questions/19371860/python-open-file-from-zip-without-temporary-extracting-it">Similar question</a></p>
<p>Plus answer:
I think that the problem maybe is that when you use zipfile.ZipFile you not... | 0 | 2016-08-10T14:56:40Z | [
"python",
"zip"
] |
Python: how to pass a file from a zip to a function that reads data from that file | 38,876,829 | <p>I have a zip-file that contains <a href="https://github.com/mhe/pynrrd" rel="nofollow">.nrrd</a> type files. The pynrrd lib comes with a read function. How can I pull the <code>.nrrd</code> file from the zip and pass it to the <code>nrrd.read()</code> function?</p>
<p>I tried following, but that gives the following... | 1 | 2016-08-10T14:51:35Z | 38,877,803 | <p>The following works: </p>
<pre><code>file_nrrd = zf.extract(f_name) # extract the file from the zip
</code></pre>
| 0 | 2016-08-10T15:32:27Z | [
"python",
"zip"
] |
Replacing missing values of an input Python | 38,876,862 | <p>Suppose you have an input formatted like this:</p>
<pre><code>id____value1____value2...valueN
1____hello____world...something
2________goodnight...world
</code></pre>
<p>the 4 <code>'_'</code> are supposed to be <code>'/t'</code></p>
<p>So far, I get something like this: the first item has an <code>{ID:1, value1:... | 3 | 2016-08-10T14:52:46Z | 38,876,940 | <p>Why not <code>replace</code>?</p>
<pre><code>for line in f:
line.replace('\t\t','n/a')
</code></pre>
<p>Anywhere there are two adjacent <code>\t</code> values, you will have 'n/a' instead. As @DeepSpace points out, f isn't actually changing so you'll have to append line to your list or do something to keep tr... | 1 | 2016-08-10T14:56:05Z | [
"python",
"string"
] |
Replacing missing values of an input Python | 38,876,862 | <p>Suppose you have an input formatted like this:</p>
<pre><code>id____value1____value2...valueN
1____hello____world...something
2________goodnight...world
</code></pre>
<p>the 4 <code>'_'</code> are supposed to be <code>'/t'</code></p>
<p>So far, I get something like this: the first item has an <code>{ID:1, value1:... | 3 | 2016-08-10T14:52:46Z | 38,877,300 | <p>Depending a bit on how you want to use the list at the end of the day, you could also use the <code>csv</code> module for something which will be a bit more flexible for cases where more than one column might come without entries;</p>
<pre><code>import csv
with open(file, 'r') as f:
reader = csv.reader(f, deli... | 3 | 2016-08-10T15:11:26Z | [
"python",
"string"
] |
Three quotation marks instead of one | 38,876,886 | <p>I want transfer/write a list of lists into a txt file. Some of the strings in the lists contain quotation marks, which should be transferred, too. </p>
<p>But if I try to write them in the txt file they contain three quotation marks before and three after the string. How can I change <code>"""3"""</code> to <code>... | 0 | 2016-08-10T14:54:07Z | 38,876,980 | <p>You are writing data <em>with</em> quotes. The <code>csv.writer()</code> by default uses quote characters already, to surround data that may have the delimiter in the value, and will escape any <code>"</code> characters <em>in the value</em> with double <code>""</code> marks before surrounding the value with <code>"... | 2 | 2016-08-10T14:57:28Z | [
"python",
"csv"
] |
Python - Convert a epoch timestamp to yyyy/mm/dd hh:mm | 38,876,907 | <p>I'm given a timestamp (time since the epoch) and I need to convert it into this format: </p>
<p><code>yyyy/mm/dd hh:mm</code></p>
<p>I looked around and it seems like everyone else is doing this the other way around (date to timestamp).</p>
<p>If your answer involves <code>dateutil</code> that would be great.</p>... | 2 | 2016-08-10T14:54:42Z | 38,877,090 | <p>Using <code>datetime</code> instead of <code>dateutil</code>:</p>
<pre><code>import datetime as dt
dt.datetime.utcfromtimestamp(seconds_since_epoch).strftime("%Y/%m/%d %H:%M")
</code></pre>
<p>An example:</p>
<pre><code>import time
import datetime as dt
epoch_now = time.time()
sys.stdout.write(str(epoch_now))
&g... | 3 | 2016-08-10T15:02:22Z | [
"python",
"datetime"
] |
Copying and merging directories excluding certain extensions | 38,876,945 | <p>I want to copy multiple directories with identical structure (subdirectories have the same names) but different contents into a third location and merge them. At the same time, i want to ignore certain file extensions and not copy them.</p>
<hr>
<p>I found that the first task alone can be easily handled by <code>c... | 8 | 2016-08-10T14:56:12Z | 38,949,340 | <p>if you do want to use shutil directly, here's a hot patch for os.makedirs to skip the error.</p>
<pre><code>import os
os_makedirs = os.makedirs
def safe_makedirs(name, mode=0777):
if not os.path.exists(name):
os_makedirs(name, mode)
os.makedirs = safe_makedirs
import shutil
dirs_to_copy = [r'J:\Data\F... | 0 | 2016-08-15T04:30:26Z | [
"python",
"windows",
"copy-paste"
] |
Copying and merging directories excluding certain extensions | 38,876,945 | <p>I want to copy multiple directories with identical structure (subdirectories have the same names) but different contents into a third location and merge them. At the same time, i want to ignore certain file extensions and not copy them.</p>
<hr>
<p>I found that the first task alone can be easily handled by <code>c... | 8 | 2016-08-10T14:56:12Z | 38,979,429 | <p>As <strong>PeterBrittain</strong> suggested, writing my own version of <code>shutil.copytree()</code> was the way to go. Below is the code. Note that the only difference is the wrapping of the <code>os.makedirs()</code> in an <code>if</code> block.</p>
<pre><code>from shutil import copy2, copystat, Error, ignore_pa... | 3 | 2016-08-16T15:56:24Z | [
"python",
"windows",
"copy-paste"
] |
What is the fastest way to access elements in a nested list? | 38,876,963 | <p>I have a list which is made up out of three layers, looking something like this for illustrative purposes:</p>
<pre><code>a = [[['1'],['2'],['3'],['']],[['5'],['21','33']]]
</code></pre>
<p>Thus I have a top list which contains several other lists each of which again contains lists.</p>
<p>The first layer will co... | 2 | 2016-08-10T14:56:56Z | 38,877,027 | <p>Accessing elements via their index (ie: a[1][1][0]) is a O(1) operation: <a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow">source</a>. You won't get much quicker than that. </p>
<p>Now, assignment is also a O(1) operation, so there's no difference between the two methods you've described as far a... | 2 | 2016-08-10T14:59:43Z | [
"python",
"list",
"python-2.7",
"nested-lists"
] |
What is the fastest way to access elements in a nested list? | 38,876,963 | <p>I have a list which is made up out of three layers, looking something like this for illustrative purposes:</p>
<pre><code>a = [[['1'],['2'],['3'],['']],[['5'],['21','33']]]
</code></pre>
<p>Thus I have a top list which contains several other lists each of which again contains lists.</p>
<p>The first layer will co... | 2 | 2016-08-10T14:56:56Z | 38,877,120 | <p>The two methods are more or less identical, given that <code>b=a[0]</code> only binds another name to the list at that index. It does not copy the list. That said, the only difference is that, in your second method, the only difference is that you, in addition to access the nested lists, you end up throwing referenc... | 1 | 2016-08-10T15:03:58Z | [
"python",
"list",
"python-2.7",
"nested-lists"
] |
How to write Python script as Amazon Lambda function? | 38,877,031 | <p>I want to write the Python script below as Amazon lambda function, the script publish RabbitMQ metrics to Amazon cloudwatch, I've tried several times and managed to get rabbitmq depths but my Lambda function failed to publish metrics to cloudwatch.</p>
<pre><code>from __future__ import with_statement, print_functio... | -2 | 2016-08-10T14:59:49Z | 38,881,659 | <p>Problem solved by adding a NAT gateway to the VPC in order for the lambda function to get access to Aws resources. As suggested by Mark B in the comment</p>
| 0 | 2016-08-10T19:07:39Z | [
"python",
"amazon-web-services",
"rabbitmq",
"amazon-cloudwatch",
"amazon-lambda"
] |
How do I add python libraries to an AWS lambda function for Alexa? | 38,877,058 | <p>I was following the tutorial to create an Alexa app using Python: </p>
<p><a href="https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/alexa-skill-tutorial" rel="nofollow">Python Alexa Tutorial</a></p>
<p>I was able to successfully follow all the steps and get the app to work.I now want to modify ... | 0 | 2016-08-10T15:01:16Z | 38,877,273 | <p>The <a href="http://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html" rel="nofollow">official documentation</a> is pretty good. In a nutshell, you need to create a zip file of a directory containing both the code of your lambda function and all external libraries you use at th... | 2 | 2016-08-10T15:09:50Z | [
"python",
"amazon-web-services",
"pip",
"aws-lambda",
"alexa-skills-kit"
] |
Low accuracies due to lack of data for machine learning | 38,877,098 | <p>I'm currently applying Tensorflow to the Titanic machine learning problem on Kaggle: <a href="https://www.kaggle.com/c/titanic" rel="nofollow">https://www.kaggle.com/c/titanic</a></p>
<p>My training data is 891 by 8 (891 data points and 8 features). The goal is to predict whether a passenger on the Titanic survived... | 0 | 2016-08-10T15:02:44Z | 38,877,888 | <p>Try cross-validating the training data locally and see what accuracy you get. The sklearn package has a simple k-fold cross-validation utility (<a href="http://scikit-learn.org/stable/modules/cross_validation.html#cross-validation-iterators" rel="nofollow">here</a>) that divides the samples in training and test fold... | 0 | 2016-08-10T15:35:49Z | [
"python",
"machine-learning",
"tensorflow"
] |
How To Detect Red Color In OpenCV Python? | 38,877,102 | <p>I am trying to detect red color from the video that's being taken from my webcam. The following code example given below is taken from <a href="http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_colorspaces/py_colorspaces.html" rel="nofollow">OpenCV Documentation.</a>
The code is give... | 0 | 2016-08-10T15:02:48Z | 38,877,354 | <p>Running the same code for red seems to work:</p>
<pre><code>>>> red = numpy.uint8([[[0,0,255]]])
>>> hsv_red = cv2.cvtColor(red,cv2.COLOR_BGR2HSV)
>>> print(hsv_red)
[[[ 0 255 255]]]
</code></pre>
<p>And then you can try different colors that appear reddish. Beware that the red range in... | 1 | 2016-08-10T15:13:42Z | [
"python",
"python-2.7",
"opencv",
"computer-vision",
"opencv3.1"
] |
Django Channels | 38,877,117 | <p>I've little question about Django Channels, WebSockets, and chat applications. Serving with google gets me to chatrooms, where people can connect and start a chat. But I don't know how one user can send another user instant message.</p>
<p>For example:</p>
<p>1) I add John to friends, and want to start chat.
2) On... | 1 | 2016-08-10T15:03:46Z | 38,940,607 | <p>Simply make "automatic unique rooms" for user pairs. The rest stays the same. For example like this</p>
<pre><code>def get_group_name(user1, user2):
return 'chat-{}-{}'.format(*sorted([user1.id, user2.id]))
</code></pre>
<p>Give it two user objects, and it returns a unique room for that pair of users, ordered ... | 2 | 2016-08-14T08:52:01Z | [
"python",
"django",
"chat",
"django-channels"
] |
GroupBy one column, custom operation on another column of grouped records in pandas | 38,877,172 | <p>I wanted to apply a custom operation on a column by grouping the values on another column. Group by column to get the count, then divide the another column value with this count for all the grouped records.</p>
<p>My Data Frame:</p>
<pre><code> emp opp amount
0 a 1 10
1 b 1 10
2 c 2 30
3 b 2 ... | 0 | 2016-08-10T15:05:43Z | 38,877,342 | <pre><code>df['amount'] = df.groupby('opp')['amount'].transform(lambda g: g/g.size)
df
# emp opp amount
# 0 a 1 5
# 1 b 1 5
# 2 c 2 10
# 3 b 2 10
# 4 d 2 10
</code></pre>
<p>Or:</p>
<pre><code>df['amount'] = df.groupby('opp')['amount'].apply(lambda g: g/g.size)
</code></pr... | 2 | 2016-08-10T15:13:06Z | [
"python",
"pandas",
"apply"
] |
GroupBy one column, custom operation on another column of grouped records in pandas | 38,877,172 | <p>I wanted to apply a custom operation on a column by grouping the values on another column. Group by column to get the count, then divide the another column value with this count for all the grouped records.</p>
<p>My Data Frame:</p>
<pre><code> emp opp amount
0 a 1 10
1 b 1 10
2 c 2 30
3 b 2 ... | 0 | 2016-08-10T15:05:43Z | 38,877,355 | <p>You could try something like this:</p>
<pre><code>df2 = df.groupby('opp').amount.count()
df.loc[:, 'calculated'] = df.apply( lambda row: \
row.amount / df2.ix[row.opp], axis=1)
df
</code></pre>
<p>Yields:</p>
<pre><code> emp opp amount calculated
0 a 1 10 ... | 2 | 2016-08-10T15:13:42Z | [
"python",
"pandas",
"apply"
] |
How can I write a large csv file using Python? | 38,877,208 | <p>I need to extract a big amount of data(>1GB) from a database to a csv file. I'm using this script:</p>
<pre><code>rs_cursor = rs_db.cursor()
rs_cursor.execute("""SELECT %(sql_fields)s
FROM table1""" % {"sql_fields": sql_fields})
sqlData = rs_cursor.fetchall()
rs_cursor.close()
c = csv.writer(o... | 0 | 2016-08-10T15:07:29Z | 38,877,446 | <p>Have you tried fetchone()?</p>
<pre><code>rs_cursor = rs_db.cursor()
rs_cursor.execute("""SELECT %(sql_fields)s
FROM table1""" % {"sql_fields": sql_fields})
c = csv.writer(open(filename, "wb"))
c.writerow(headers)
row = rs_cursor.fetchone()
while row:
c.writerow(row)
row = rs_cursor.fe... | 0 | 2016-08-10T15:17:32Z | [
"python",
"csv"
] |
How can I write a large csv file using Python? | 38,877,208 | <p>I need to extract a big amount of data(>1GB) from a database to a csv file. I'm using this script:</p>
<pre><code>rs_cursor = rs_db.cursor()
rs_cursor.execute("""SELECT %(sql_fields)s
FROM table1""" % {"sql_fields": sql_fields})
sqlData = rs_cursor.fetchall()
rs_cursor.close()
c = csv.writer(o... | 0 | 2016-08-10T15:07:29Z | 38,877,680 | <p><code>psycopg2</code> (which OP uses) has a <code>fetchmany</code> method which accepts a <code>size</code> argument. Use it to read a certain number of lines from the database. You can expirement with the value of <code>n</code> to balance between run-time and memory usage.</p>
<p><code>fetchmany</code> docs: <a h... | 2 | 2016-08-10T15:26:53Z | [
"python",
"csv"
] |
how to calculate accurady based on two lists python? | 38,877,301 | <p>I have two lists.</p>
<pre><code> a = [0,0,1,1,1] # actual labels
b = [1,1,0,0,1] # predicted labels
</code></pre>
<p>How can I calculate accuracy based on these lists?</p>
| 0 | 2016-08-10T15:11:29Z | 38,877,374 | <pre><code>sum(1 for x,y in zip(a,b) if x == y) / len(a)
</code></pre>
<p>This will give you the percentage that were correct - that is, the number correct over the total number. It works by calculating the number that are equal between the two lists then dividing by the total number of labels.</p>
<p>Also note that ... | 4 | 2016-08-10T15:14:46Z | [
"python",
"numpy"
] |
how to calculate accurady based on two lists python? | 38,877,301 | <p>I have two lists.</p>
<pre><code> a = [0,0,1,1,1] # actual labels
b = [1,1,0,0,1] # predicted labels
</code></pre>
<p>How can I calculate accuracy based on these lists?</p>
| 0 | 2016-08-10T15:11:29Z | 38,877,421 | <p>If the two lists are always the same size, the following code should be okay :)</p>
<pre><code>a = [0,0,1,1,1] # actual labels
b = [1,1,0,0,1] # predicted labels
accuracy = len([a[i] for i in range(0, len(a)) if a[i] == b[i]]) / len(a)
print(accuracy)
</code></pre>
| 2 | 2016-08-10T15:16:37Z | [
"python",
"numpy"
] |
how to calculate accurady based on two lists python? | 38,877,301 | <p>I have two lists.</p>
<pre><code> a = [0,0,1,1,1] # actual labels
b = [1,1,0,0,1] # predicted labels
</code></pre>
<p>How can I calculate accuracy based on these lists?</p>
| 0 | 2016-08-10T15:11:29Z | 38,877,445 | <p>if accuracy is defined as % correct:</p>
<pre><code>count = 0.0
correct = 0.0
for i in range(len(a)):
count+=1
if a[i]==b[i]:
correct+=1
print correct/count
print (correct/count)*100
</code></pre>
<p>This will print decimal representation of % correct, followed by % representation.</p>
| 1 | 2016-08-10T15:17:27Z | [
"python",
"numpy"
] |
how to calculate accurady based on two lists python? | 38,877,301 | <p>I have two lists.</p>
<pre><code> a = [0,0,1,1,1] # actual labels
b = [1,1,0,0,1] # predicted labels
</code></pre>
<p>How can I calculate accuracy based on these lists?</p>
| 0 | 2016-08-10T15:11:29Z | 38,877,601 | <p>Since you've tagged <code>numpy</code>, here's a <code>numpy</code> solution:</p>
<pre><code>import numpy as np
a = np.array([0,0,1,1,1]) # actual labels
b = np.array([1,1,0,0,1]) # predicted labels
correct = (a == b)
accuracy = correct.sum() / correct.size
</code></pre>
| 3 | 2016-08-10T15:23:18Z | [
"python",
"numpy"
] |
How to prompt for user input using a Matplotlib GUI rather than a command line prompt | 38,877,303 | <p>Suppose I to write a function <code>get_coords</code> which prompts the user for some input coordinates. One way to do this would be as follows:</p>
<pre><code>def get_coords():
coords_string = input("What are your coordinates? (x,y)")
coords = tuple(coords_string)
return coords
</code></pre>
<p>Howeve... | 0 | 2016-08-10T15:11:31Z | 38,887,795 | <pre><code>import matplotlib.pyplot as plt
def get_coords_from_figure():
ev = None
def onclick(event):
nonlocal ev
ev = event
fig, ax = plt.subplots()
ax.axvline(x=0.5) # Placeholder data
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show(block=True)
... | 1 | 2016-08-11T05:20:28Z | [
"python",
"matplotlib"
] |
How do I compute the counts of one column based on the values of two others in Pandas? | 38,877,338 | <p>I have a dataset that includes three columns:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'A': [1,2,3,2,3,3],
'B': [1.0, 2.0, 3.0, 2.0, 3.0, 3.0],
'C': [0.0, 3.5, 1.2, 2.1, 3.1, 0.0]})
</code></pre>
<p>Now, obviously I can use <code>df['A'].value_cou... | 1 | 2016-08-10T15:12:55Z | 38,877,765 | <pre><code>df['counts'] = 0
df.loc[df['B'] - df['C'] > 0, 'counts'] = 1
df.loc[df['B'] - df['C'] < 0, 'counts'] = -1
</code></pre>
| 2 | 2016-08-10T15:30:34Z | [
"python",
"pandas"
] |
How do I compute the counts of one column based on the values of two others in Pandas? | 38,877,338 | <p>I have a dataset that includes three columns:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'A': [1,2,3,2,3,3],
'B': [1.0, 2.0, 3.0, 2.0, 3.0, 3.0],
'C': [0.0, 3.5, 1.2, 2.1, 3.1, 0.0]})
</code></pre>
<p>Now, obviously I can use <code>df['A'].value_cou... | 1 | 2016-08-10T15:12:55Z | 38,877,958 | <pre><code>import pandas as pd
import numpy as np
df['counts'] = np.sign(df.B - df.C) # use the numpy.sign to create the count column
df.groupby('A')['counts'].sum() # group the counts by column A and sum the value
#A
#1 1.0
#2 -2.0
#3 1.0
#Name: counts, dtype: float64
</code></pre>
| 4 | 2016-08-10T15:39:06Z | [
"python",
"pandas"
] |
Python: JSON saved as string, can't get it back to JSON | 38,877,345 | <p>I had some JSON data that I converted to string using:</p>
<pre><code>myString = str(myJSON)
</code></pre>
<p>and I saved into an SQLite database. Now, when I retrieve <code>myString</code> looks more or less like this:</p>
<pre><code>'{u\'foo\': False, u\'bar\': 20, u\'name\': u\'Anna\'}'
</code></pre>
<p>I am ... | 0 | 2016-08-10T15:13:16Z | 38,877,495 | <p>You don't have JSON. You have a Python dictionary.</p>
<p>If you did have JSON, you wouldn't need to convert it to a string, because it would already be one. However, as the db value shows, what you have actually done is convert a dict straight to a string.</p>
<p>Don't do any of this. If you are actually receivin... | 1 | 2016-08-10T15:19:13Z | [
"python",
"json",
"sqlite3"
] |
Python: JSON saved as string, can't get it back to JSON | 38,877,345 | <p>I had some JSON data that I converted to string using:</p>
<pre><code>myString = str(myJSON)
</code></pre>
<p>and I saved into an SQLite database. Now, when I retrieve <code>myString</code> looks more or less like this:</p>
<pre><code>'{u\'foo\': False, u\'bar\': 20, u\'name\': u\'Anna\'}'
</code></pre>
<p>I am ... | 0 | 2016-08-10T15:13:16Z | 38,877,524 | <p>You can use <a href="https://docs.python.org/2/library/ast.html#ast.literal_eval" rel="nofollow">ast.literal_eval</a> to get a dictionary back.</p>
<pre><code>import ast
original = {'foo': False, 'bar': 20, 'name': 'Anna'}
dict_string = str(original)
print original == dict_string # False
print original == ast.lit... | 4 | 2016-08-10T15:20:34Z | [
"python",
"json",
"sqlite3"
] |
Python: JSON saved as string, can't get it back to JSON | 38,877,345 | <p>I had some JSON data that I converted to string using:</p>
<pre><code>myString = str(myJSON)
</code></pre>
<p>and I saved into an SQLite database. Now, when I retrieve <code>myString</code> looks more or less like this:</p>
<pre><code>'{u\'foo\': False, u\'bar\': 20, u\'name\': u\'Anna\'}'
</code></pre>
<p>I am ... | 0 | 2016-08-10T15:13:16Z | 38,878,269 | <p>As @Karin said, your string is not JSON, that said, you should use <a href="https://docs.python.org/3.4/library/json.html#json.dump" rel="nofollow"><code>json.dump()</code> </a>directly with the var <code>myJSON</code> (this var <strong>should</strong> be a <code>dict</code>) like this:</p>
<pre><code> myJSON = ... | 0 | 2016-08-10T15:54:51Z | [
"python",
"json",
"sqlite3"
] |
Aggregate time between alternate rows | 38,877,496 | <p>I have a dataset that's roughly 200KB in size. I've cleaned up the data and loaded it into an RDD in Spark (using pyspark) so that the header format is the following:</p>
<pre><code>Employee ID | Timestamp (MM/DD/YYYY HH:MM) | Location
</code></pre>
<p>This dataset stores employee stamp-in and stamp-out times, and... | 1 | 2016-08-10T15:19:14Z | 38,880,045 | <p>You can try using the window function <a href="http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.lead" rel="nofollow"><code>lead</code></a>:</p>
<pre><code>from pyspark.sql import Window
from pyspark.sql.functions import *
window = Window.partitionBy("id").orderBy("timestamp")
n... | 0 | 2016-08-10T17:36:11Z | [
"python",
"apache-spark",
"pyspark"
] |
VideoLan song change event for radio stream | 38,877,514 | <p>I'm new to using programming vlc, I'm using python specifically python-vlc to play a internet radio station.</p>
<p>I have it playing the station but can't get the current track that is playing.
When I get the audio track info it returns Track 1 all the time.</p>
<p>Anyways, I am looking for a way to get the song ... | 0 | 2016-08-10T15:19:55Z | 38,877,998 | <p>In an MPEG stream, there is no such thing as "songs". It's just an audio stream. Some radio stations do change metadata in between, so you might be able to check whether the stream title changes or something. But that's purely heuristic.</p>
<p>I guess the notification you see is also triggered by the metadata chan... | 1 | 2016-08-10T15:40:42Z | [
"python",
"vlc",
"libvlc"
] |
Using Python range and calendar to check for leap year | 38,877,628 | <p>Noob question. Is there a more ideal way to express a range using both range and calendar. Looking to set up a print True if any of the years in my range are leap years </p>
<pre><code>year = calendar.isleap(range(2016,2036))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Fil... | 1 | 2016-08-10T15:24:31Z | 38,877,653 | <p>List comprehensions are good for this</p>
<pre><code>leap_years = [year for year in range(2016, 2036) if calendar.isleap(year)]
</code></pre>
<p>As are filters, if you prefer the map/reduce/filter way of doing things</p>
<pre><code>leap_years = filter(calendar.isleap, range(2016, 2036))
</code></pre>
<p>The form... | 1 | 2016-08-10T15:25:50Z | [
"python",
"python-2.7"
] |
Using Python range and calendar to check for leap year | 38,877,628 | <p>Noob question. Is there a more ideal way to express a range using both range and calendar. Looking to set up a print True if any of the years in my range are leap years </p>
<pre><code>year = calendar.isleap(range(2016,2036))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Fil... | 1 | 2016-08-10T15:24:31Z | 38,877,754 | <p>It sounds like you want to make use of the Python <a href="https://docs.python.org/3/library/functions.html#any" rel="nofollow"><code>any</code></a> built-in;</p>
<pre><code>In [1]: import calendar
In [2]: test1 = any(calendar.isleap(y) for y in range(2016, 2036))
In [3]: test2 = any(calendar.isleap(y) for y in r... | 4 | 2016-08-10T15:29:51Z | [
"python",
"python-2.7"
] |
Converting pandas dataframe into list of tuples with index | 38,877,766 | <p>I'm currently trying convert a pandas dataframe into a list of tuples. However I'm having difficulties getting the Index (which is the Date) for the values in the tuple as well. My first step was going here, but they do not add any index to the tuple.</p>
<p><a href="http://stackoverflow.com/questions/9758450/panda... | 1 | 2016-08-10T15:30:37Z | 38,878,035 | <p>You can iterate over the result of <code>to_records(index=True)</code>.</p>
<p>Say you start with this:</p>
<pre><code>In [6]: df = pd.DataFrame({'a': range(3, 7), 'b': range(1, 5), 'c': range(2, 6)}).set_index('a')
In [7]: df
Out[7]:
b c
a
3 1 2
4 2 3
5 3 4
6 4 5
</code></pre>
<p>then this wo... | 1 | 2016-08-10T15:42:32Z | [
"python",
"pandas",
"numpy",
"tuples"
] |
python sys.exit :an integer is required (got type str)? | 38,877,777 | <p>New to python.
I want to stop my code in main for debugging purpose. I use logging module to print the variable value I would like to inspect.</p>
<p>However, it raises error. Not sure how to solve it.
I also wonder using sys.exit instead of set up debugging point is the right way to run only small portion of the c... | 0 | 2016-08-10T15:31:05Z | 38,877,857 | <p>You do need an integer - a traditional Unix return code (0 for no error, and something bigger than 0 for something bad happening).</p>
<p>In terms of debugging, you should try the <a href="https://en.wikipedia.org/wiki/IDLE_(Python)" rel="nofollow">IDLE</a> IDE, or <a href="https://docs.python.org/2/library/pdb.htm... | -7 | 2016-08-10T15:34:46Z | [
"python"
] |
python sys.exit :an integer is required (got type str)? | 38,877,777 | <p>New to python.
I want to stop my code in main for debugging purpose. I use logging module to print the variable value I would like to inspect.</p>
<p>However, it raises error. Not sure how to solve it.
I also wonder using sys.exit instead of set up debugging point is the right way to run only small portion of the c... | 0 | 2016-08-10T15:31:05Z | 38,908,789 | <p>From the comment discussion, I suspect your issue is that PyCharm is trying to handle the sys.exit() internally and it doesn't like the fact you are using a custom error message. There are similar issues in other IDEs like Python logging not working properly in Spyder (May or may not have been resolved by now). </p>... | 3 | 2016-08-12T02:09:54Z | [
"python"
] |
python `traceback` production performance | 38,877,881 | <p>I'm using try catch blocks to handle exceptions in my Django app. However, I'm also using <code>traceback</code> module to print debug information in case an exception is caught. </p>
<pre><code>try:
# Exception gets thrown here
except:
traceback.print_exc()
</code></pre>
<p>Should I remove this when moving ... | 0 | 2016-08-10T15:35:36Z | 38,877,905 | <p>No, there are no significant performance implications to this; the traceback is already present with the exception when it is raised.</p>
<p>All <code>traceback.print_exc()</code> does is <em>print</em> the information already there.</p>
| 1 | 2016-08-10T15:36:27Z | [
"python",
"django",
"traceback"
] |
python re.sub() with ?P | 38,877,915 | <p>Can I use a variable from the first argument of re.sub (), to use it in the second argument? Let me explain with an example:</p>
<pre><code>re.sub(r'(?P<id>>>>[0-9]+)', 'sometext(?P=id)sometext', self.text))
</code></pre>
<p>Can I use id variable in 'sometext(?P=id)sometext'? Actually, this code don... | 0 | 2016-08-10T15:37:09Z | 38,877,950 | <p>You can refer to a capturing group by number, e.g. the first capturing group would be <code>\1</code>.</p>
| 2 | 2016-08-10T15:38:39Z | [
"python",
"regex"
] |
Python: How is my set being turned into a list? | 38,877,972 | <p>I've written a program to recursively get all the hyponym-children of a given synset in the wordnet graph.</p>
<p>However, that is not relevant to my question here.</p>
<p>I'm basically adding all the nodes I pass through to a set.
The output I'm getting, however, is a list</p>
<p>Here's my code</p>
<pre><code>i... | -1 | 2016-08-10T15:39:40Z | 38,878,107 | <p><code>sorted()</code> creates a list, if you do a simple test, this behavior is clear. The Python <a href="https://docs.python.org/2/library/stdtypes.html#set" rel="nofollow">documentation</a> says a "set object is an <em>unordered</em> collection of distinct hashable objects".</p>
<pre><code>>>> x = {1,3,... | 3 | 2016-08-10T15:46:35Z | [
"python"
] |
Type of hypothesis test in scipy.stats.linregress | 38,878,063 | <p>Python documentation notes that this is a two tailed test but there is no comment on what kind of test it is. Is it a T Test, Z Test, F Test...</p>
<p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.linregress.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.st... | 1 | 2016-08-10T15:44:07Z | 38,880,953 | <p>It uses the <em>t</em>-test. In the latest version of scipy, you can find the code in <a href="https://github.com/scipy/scipy/blob/master/scipy/stats/_stats_mstats_common.py" rel="nofollow">https://github.com/scipy/scipy/blob/master/scipy/stats/_stats_mstats_common.py</a></p>
<p>The relevant code in <code>linregre... | 2 | 2016-08-10T18:27:43Z | [
"python",
"python-3.x",
"scipy",
"statistics"
] |
Activate Anaconda Python environment from makefile | 38,878,088 | <p>I want to use a makefile to build my project's environment using a makefile and <a href="http://conda.pydata.org/docs/using/envs.html" rel="nofollow">anaconda/miniconda</a>, so I should be able to clone the repo and simply run <code>make myproject</code></p>
<pre><code>myproject: build
build:
@printf "\nBuilding... | 2 | 2016-08-10T15:45:27Z | 39,908,959 | <p>I had the same problem. Essentially the only solution is stated by 9000. I have a setup shell script inside which I setup the conda environment (source activate python2), then I call the make command. I experimented with setting up the environment from inside Makefile and no success. </p>
<p>I have this line in ... | 0 | 2016-10-07T03:36:50Z | [
"python",
"bash",
"makefile",
"virtualenv",
"anaconda"
] |
What is the best file format to upload to MongoDB | 38,878,208 | <p>I am totally unfamiliar with MongoDB so pardon if my question is too simple. </p>
<p>I have <strong>4 datasets</strong> and each dataset has files corresponding to samples, each sample has 3 files corresponding to three normalization method. The total number of samples in all 4 datasets is 20000 so the total files ... | 0 | 2016-08-10T15:52:03Z | 38,879,221 | <p>For your requirement i'll do it in below way.</p>
<p>Create a CSV with below columns. Parse your files and dump data into the CSV. In any programming language CSV creation is very easy.</p>
<pre><code>dt_set, sample, type, norm, id, value
</code></pre>
<p>After that import your CSV into MongoDB using <a href="htt... | 0 | 2016-08-10T16:45:53Z | [
"python",
"json",
"mongodb"
] |
Can not read the content input in the dictionary file with python | 38,878,281 | <p>I tried to make a python dictionary, the input of file format (.txt or .csv) and I want to match based database that I have.<br></p>
<p>This my file input</p>
<blockquote>
<p>John <br>
Smith<br>
Ana<br>
Adam<br>
Steven</p>
</blockquote>
<p>This My script</p>
<pre><code>data = [{"name":"John","school":"... | 1 | 2016-08-10T15:55:33Z | 38,878,339 | <p>change get_name to get_school</p>
<pre><code>data = [{"name":"John","school":"A","age":"17"},
{"name":"Smith","school":"B ","age":"16"},
{"name":"Ana","school":"B","age":"19 "},
{"name":"Adam","school":"C ","age":"18 "},
{"name":"Steven","school":"B ","age":"19 "},]
file_input = ope... | 1 | 2016-08-10T15:58:37Z | [
"python",
"python-2.7"
] |
Ordering users by date created in django admin panel | 38,878,409 | <p>How do you order users in the django admin panel so that upon display they are ordered by date created? Currently they are listed in alphabetical order</p>
<p>I know that I can import the <code>User</code> model via: <code>from django.contrib.auth.models import User</code></p>
<p>How do I go about doing this?</p>
| 0 | 2016-08-10T16:01:30Z | 38,878,706 | <p>The admin site will default to the ordering specified on your model itself, e.g.</p>
<pre><code>class MyUserModel:
created = models.DateTimeField()
class Meta:
ordering = ('created', )
</code></pre>
<p>If you want something more flexible, that is, if you want to use Django default user model witho... | 0 | 2016-08-10T16:16:40Z | [
"python",
"django"
] |
Ordering users by date created in django admin panel | 38,878,409 | <p>How do you order users in the django admin panel so that upon display they are ordered by date created? Currently they are listed in alphabetical order</p>
<p>I know that I can import the <code>User</code> model via: <code>from django.contrib.auth.models import User</code></p>
<p>How do I go about doing this?</p>
| 0 | 2016-08-10T16:01:30Z | 38,878,743 | <p>To change the default ordering of users in admin panel you can subclass the default UserAdmin class. In your applications's <code>admin.py</code>:</p>
<pre><code>from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class MyUserAdmin(UserAdmin):
# override the default sort... | 3 | 2016-08-10T16:18:29Z | [
"python",
"django"
] |
Decode a base64 string to a decimal strin | 38,878,504 | <p>I have a string say <code>FhY=</code> which has been encoded to hex. So when run</p>
<pre><code>>>> b6 = 'FhY='
>>> b6.decode('base64')
'\x16\x16'
</code></pre>
<p>This is a hex string that once converted should be <code>22 22</code>. This result has been proven on the site <a href="https://conv.... | 0 | 2016-08-10T16:06:47Z | 38,878,737 | <p>You need to convert each byte from the decoded string to its decimal value. So this should solve it:</p>
<pre class="lang-py prettyprint-override"><code>b6 = 'FhY='
' '.join([ str(ord(c)) for c in b6.decode('base64') ])
</code></pre>
<p>Results in <code>22 22</code></p>
| 1 | 2016-08-10T16:18:13Z | [
"python",
"string",
"encoding",
"base64"
] |
Is there a way to change the SHELL program called by os.system()? | 38,878,547 | <p>Iâm in an embedded environment where<code>/bin/sh</code>doesnât exist so when I call<code>posix.system()</code>or <code>os.system()</code>it always returns<code>-1</code>.<br>
Because of that environment, the<code>subprocess</code>module isnât available. I canât create pipes too.</p>
<p>Iâm using <a href=... | 0 | 2016-08-10T16:08:49Z | 38,878,594 | <p>No, you can't change what shell <code>os.system()</code> uses, because that function makes a call to the <a href="http://linux.die.net/man/3/system" rel="nofollow"><code>system()</code> C function</a>, and that function has the shell hardcoded to <code>/bin/sh</code>.</p>
<p>Use the <a href="https://docs.python.org... | 3 | 2016-08-10T16:11:29Z | [
"python",
"linux",
"python-2.7",
"shell",
"os.system"
] |
Run some initialization code when Django (1.9) loads | 38,878,603 | <p>I saw that from 1.7 there is <a href="https://docs.djangoproject.com/en/dev/ref/applications/#django.apps.AppConfig.ready" rel="nofollow" title="apps.AppConfig.ready()">https://docs.djangoproject.com/en/dev/ref/applications/#django.apps.AppConfig.ready</a>, however this is per <strong>each app</strong>.</p>
... | 0 | 2016-08-10T16:11:56Z | 38,878,690 | <p>In newer versions of Django, you generally have a project directory containing the global, app-independent files like <code>settings.py</code> and <code>wsgi.py</code>. You can add global initialization code to <code>__init__.py</code> in that directory.</p>
<p>Be advised that this code is run very early (even bef... | 1 | 2016-08-10T16:15:44Z | [
"python",
"django"
] |
python convert filetime to datetime for dates before 1970 | 38,878,647 | <p>I need to convert filetime to datetime. I am using this code <a href="http://reliablybroken.com/b/wp-content/filetimes.py/%22filetime.py%22" rel="nofollow">filetime.py</a>, from <a href="http://stackoverflow.com/questions/3694487/python-initialize-a-datetime-object-with-seconds-since-epoch/%22here2%22">here</a> as m... | 1 | 2016-08-10T16:13:32Z | 38,878,860 | <p><a href="https://docs.python.org/3/library/datetime.html#datetime.datetime.utcfromtimestamp" rel="nofollow">According to docs</a>, you have to use: </p>
<pre><code>dt = datetime.fromtimestamp(s, datetime.timezone.utc)
</code></pre>
<p>instead of:</p>
<pre><code>dt = datetime.utcfromtimestamp(s)
</code></pre>
| 0 | 2016-08-10T16:24:34Z | [
"python",
"datetime",
"filetime"
] |
python convert filetime to datetime for dates before 1970 | 38,878,647 | <p>I need to convert filetime to datetime. I am using this code <a href="http://reliablybroken.com/b/wp-content/filetimes.py/%22filetime.py%22" rel="nofollow">filetime.py</a>, from <a href="http://stackoverflow.com/questions/3694487/python-initialize-a-datetime-object-with-seconds-since-epoch/%22here2%22">here</a> as m... | 1 | 2016-08-10T16:13:32Z | 38,880,683 | <p>By adding a <code>timedelta</code> to a reference date you can use any date formula you'd like. <code>timedelta</code> is allowed to be positive or negative.</p>
<pre><code>def filetime_to_dt(ft):
us = (ft - EPOCH_AS_FILETIME) // 10
return datetime(1970, 1, 1) + timedelta(microseconds = us)
</code></pre>
| 2 | 2016-08-10T18:11:46Z | [
"python",
"datetime",
"filetime"
] |
Django 1.9 migrate for the first time is not creating tables | 38,878,666 | <p>I've never had this problem before. I've started countless projects and had no problem when I went to run 'makemigrations" for the first time. In this project I keep getting the error:</p>
<blockquote>
<p>django.db.utils.OperationalError: no such table: accounts_customuser</p>
</blockquote>
<p>That's the point, ... | 0 | 2016-08-10T16:14:14Z | 38,907,653 | <p>The problem is that your <code>CustomUser.objects.get(pk=1)</code> query is running when the URL config is loaded and imports the views, before the tables have even been created. You can fix this by moving the code into a <code>get_queryset</code> method.</p>
<pre><code>class PostViewSet(ModelViewSet):
def get_... | 1 | 2016-08-11T23:32:32Z | [
"python",
"django",
"django-rest-framework"
] |
PyPugJs with Pyramid - Basic | 38,878,714 | <p>I am trying to use <a href="https://github.com/matannoam/pypugjs" rel="nofollow">PyPugJs</a> with Pyramid.
Inside my <code>__init.py</code>, I have this</p>
<pre><code>config.include('pypugjs.ext.pyramid')
</code></pre>
<p>Inside <code>views.py</code>,</p>
<pre><code>@view_defaults(renderer='json')
class St2Views... | 1 | 2016-08-10T16:17:11Z | 38,889,943 | <p>The issue was with the pug/jade template, where an undefined(unpassed) variable was being used.</p>
| 1 | 2016-08-11T07:27:37Z | [
"python",
"pyramid",
"pyjade"
] |
The difference between __main__ and launch() methods | 38,878,721 | <p>I'm still in the learning phase and I have this question. </p>
<p>So in order to execute a class, we use <code>if __name__ == '__main__':</code> and call the class as the following </p>
<pre><code>class Example():
def test(self):
print "Hello There"
if __name__ == '__main__':
Example()
</code></p... | 0 | 2016-08-10T16:17:30Z | 38,879,172 | <p>Python runs anything in the top level this is why we use classes and functions to separate jobs (among other reasons).</p>
<p>So for example here</p>
<p>Script <code>a.py</code></p>
<pre><code>def main():
pass
main()
</code></pre>
<p>The interpreter will define a function called <code>main()</code> but when... | -1 | 2016-08-10T16:43:08Z | [
"python"
] |
"GetPassWarning: Can not control echo on the terminal" when running from IDLE | 38,878,741 | <p>When I run this code:</p>
<pre><code>import getpass
p = getpass.getpass(prompt='digite a senha\n')
if p == '12345':
print('YO Paul')
else:
print('BRHHH')
print('O seu input foi:', p) # p = seu input
</code></pre>
<p>I got this warning:</p>
<pre><code>Warning (from warnings module):
File "/usr/lib/pyth... | 1 | 2016-08-10T16:18:23Z | 38,879,520 | <p>Use an actual terminal -- that is, an environment where <code>stdin</code>, <code>stdout</code> and <code>stderr</code> are connected to <code>/dev/tty</code>, or another PTY-compliant device.</p>
<p>The IDLE REPL does not meet this requirement.</p>
| 4 | 2016-08-10T17:03:03Z | [
"python",
"python-3.x"
] |
How to insert data into SQLite with pythons dictionary | 38,878,841 | <p>I need some help with inserting data into SQLite with python.</p>
<p>I have this part of code for inserting data into table, sqlDataDict is name of Dictionary:</p>
<pre><code>cur.execute(''' INSERT INTO ProductAtt (imgID, productName, col1, col2, col3, col4, col5, col6,
col7, col8, col9, col10, col1... | 0 | 2016-08-10T16:23:44Z | 38,878,896 | <p>I suppose this is what you're looking for:</p>
<pre><code>values = {'col1':'val1','col2':'val2'}
columns = ', '.join(values.keys())
placeholders = ', '.join('?' * len(values))
sql = 'INSERT INTO Media ({}) VALUES ({})'.format(columns, placeholders)
cur.execute(sql, tuple(values.values()))
</code></pre>
| 1 | 2016-08-10T16:26:20Z | [
"python",
"sqlite",
"dictionary"
] |
How do I call a database function using SQLAlchemy in Flask? | 38,878,846 | <p>I want to call a function that I created in my PostgreSQL database. I've looked at the official SQLAlchemy documentation as well as several questions here on SO, but nobody seems to explain how to set up the function in SQLAlchemy.</p>
<p>I did find <a href="http://stackoverflow.com/questions/15293547/named-paramet... | 0 | 2016-08-10T16:24:02Z | 38,881,280 | <pre><code>from sqlalchemy.sql import text
with engine.connect() as con:
statement = text("""your function""")
con.execute(statement)
</code></pre>
<p>You must execute raw sql through sqlalchemy</p>
| 0 | 2016-08-10T18:46:36Z | [
"python",
"postgresql",
"flask",
"sqlalchemy",
"flask-sqlalchemy"
] |
Serving Python (Flask) REST API over HTTP2 | 38,878,880 | <p>I have a Python REST service and I want to serve it using HTTP2. My current server setup is <code>nginx -> Gunicorn</code>. In other words, nginx (port 443 and 80 that redirects to port 443) is running as a reverse proxy and forwards requests to Gunicorn (port 8000, no SSL). nginx is running in HTTP2 mode and I c... | 1 | 2016-08-10T16:25:28Z | 38,891,504 | <blockquote>
<p>Is it possible to serve a Python (Flask) application with HTTP/2?</p>
</blockquote>
<p>Yes, by the information you provide, you are doing it just fine.</p>
<blockquote>
<p>In my case (one reverse proxy server and one serving the actual API), which server has to support HTTP2?</p>
</blockquote>
<p... | 1 | 2016-08-11T08:45:57Z | [
"python",
"rest",
"nginx",
"gunicorn",
"http2"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.