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 remove rows from a dataframe if 75 % of its column values is equal to 0 | 37,992,585 | <p>I have a data frame of 44 column and 60,000 rows. I wanted to remove those rows if it has 0 up to 75 % of columns. This 75% :For example in my case out of 44 columns its 33 columns. And so I tried the following function in R
as,</p>
<pre><code>filter <- apply(df, 1,function(x) any(x[1:33]!=0) && any(x[34... | 0 | 2016-06-23T13:07:35Z | 37,992,701 | <p>Or analgously to @colonel-beauvel's use of <code>rowMeans</code> you can use <code>rowSums</code>.</p>
<pre><code>df[rowSums(df[, -1] > 0) / (ncol(df)-1) >= 0.75,]
</code></pre>
<ul>
<li>df[, -1] > 0 takes the data.frame, df except the ID column and returns a logical matrix whether each element.</li>
<li><co... | 1 | 2016-06-23T13:13:14Z | [
"python",
"numpy",
"pandas"
] |
How to remove rows from a dataframe if 75 % of its column values is equal to 0 | 37,992,585 | <p>I have a data frame of 44 column and 60,000 rows. I wanted to remove those rows if it has 0 up to 75 % of columns. This 75% :For example in my case out of 44 columns its 33 columns. And so I tried the following function in R
as,</p>
<pre><code>filter <- apply(df, 1,function(x) any(x[1:33]!=0) && any(x[34... | 0 | 2016-06-23T13:07:35Z | 37,992,799 | <p>try this (Pandas):</p>
<pre><code>df[(df==0).sum(axis=1)/len(df.columns) <= 0.75]
</code></pre>
| 3 | 2016-06-23T13:16:44Z | [
"python",
"numpy",
"pandas"
] |
How to remove rows from a dataframe if 75 % of its column values is equal to 0 | 37,992,585 | <p>I have a data frame of 44 column and 60,000 rows. I wanted to remove those rows if it has 0 up to 75 % of columns. This 75% :For example in my case out of 44 columns its 33 columns. And so I tried the following function in R
as,</p>
<pre><code>filter <- apply(df, 1,function(x) any(x[1:33]!=0) && any(x[34... | 0 | 2016-06-23T13:07:35Z | 37,992,840 | <p>Pandas method, here we compare the df against <code>0</code> and <code>sum</code> row-wise using <code>axis=1</code>, this will produce a <code>Series</code> with a count of the 0 values and we compare this against 75% of the row length and filter the df:</p>
<pre><code>In [14]:
df[(df == 0).sum(axis=1) < df.sha... | 2 | 2016-06-23T13:18:31Z | [
"python",
"numpy",
"pandas"
] |
How to remove rows from a dataframe if 75 % of its column values is equal to 0 | 37,992,585 | <p>I have a data frame of 44 column and 60,000 rows. I wanted to remove those rows if it has 0 up to 75 % of columns. This 75% :For example in my case out of 44 columns its 33 columns. And so I tried the following function in R
as,</p>
<pre><code>filter <- apply(df, 1,function(x) any(x[1:33]!=0) && any(x[34... | 0 | 2016-06-23T13:07:35Z | 37,992,888 | <p>Simple code, it should work:</p>
<pre><code>for i in df:
iLength = 0
countZeros = 0
for j in df:
iLength += 1
if i[j] == 0:
countZeros += 1
zeroRate = countZeros / iLength
if zeroRate >= 0.75:
#DeleteRow
</code></pre>
| 0 | 2016-06-23T13:20:45Z | [
"python",
"numpy",
"pandas"
] |
How to remove rows from a dataframe if 75 % of its column values is equal to 0 | 37,992,585 | <p>I have a data frame of 44 column and 60,000 rows. I wanted to remove those rows if it has 0 up to 75 % of columns. This 75% :For example in my case out of 44 columns its 33 columns. And so I tried the following function in R
as,</p>
<pre><code>filter <- apply(df, 1,function(x) any(x[1:33]!=0) && any(x[34... | 0 | 2016-06-23T13:07:35Z | 37,995,502 | <p>R solution (hopefully)</p>
<p>I think I got this, skip down a bit for the piece you want. The code between here and there is so its all in context, and can be seen working in R.</p>
<pre><code>MakeDF.R <- function(CustomVector,n){
#just a function to make a sample df
NewDF <- data.frame(matrix(nrow=n,nco... | -2 | 2016-06-23T15:09:36Z | [
"python",
"numpy",
"pandas"
] |
Passing two arguments (dates) from C# to a python script | 37,992,606 | <p>I am using Visual Studio 12 to create forms utilizing C#. I have been successful in passing one argument from C# to python. I am not using Iron python. The new application I am working on needs to pass two arguments to python. Both arguments are dates that the user picks.
<a href="http://i.stack.imgur.com/aSNtd.png"... | 0 | 2016-06-23T13:08:36Z | 37,992,695 | <p>Your problem is that you are passing two variables in only one parameters. If your function accepts more parameters you can add a simple comma between them.</p>
<pre><code>CallPython python = new CallPython(@"C:\Python27\ArcGIS10.3\python.exe");
python.Run_Script(@"\\gisdb01\gis\tools\Python\TA_Report\U... | 0 | 2016-06-23T13:13:03Z | [
"c#",
"python"
] |
Passing two arguments (dates) from C# to a python script | 37,992,606 | <p>I am using Visual Studio 12 to create forms utilizing C#. I have been successful in passing one argument from C# to python. I am not using Iron python. The new application I am working on needs to pass two arguments to python. Both arguments are dates that the user picks.
<a href="http://i.stack.imgur.com/aSNtd.png"... | 0 | 2016-06-23T13:08:36Z | 37,992,808 | <p>I'd change <code>RunScript</code> to accept an array of arguments with the <code>params</code> modifier.</p>
<pre><code>public void Run_Script(string scriptPathName, params object[] arguments)
</code></pre>
<p>Then change this line</p>
<pre><code>processStartInfo.Arguments = scriptPathName;
</code></pre>
<p>to t... | 1 | 2016-06-23T13:17:05Z | [
"c#",
"python"
] |
How to install PIL on Google DataLAB? | 37,992,617 | <p>I'm trying to install PIL using pip on google datalab with the following code: </p>
<blockquote>
<p>%bash pip install pil</p>
</blockquote>
<p>and receiving the following error:</p>
<blockquote>
<p>Downloading/unpacking pil Could not find any downloads that satisfy
the requirement pil Cleaning up... No di... | 1 | 2016-06-23T13:09:09Z | 37,993,031 | <p>The following worked in my test environment:</p>
<pre><code>%bash
apt-get install -y libjpeg-dev
pip install pillow
</code></pre>
| 0 | 2016-06-23T13:26:55Z | [
"python",
"pip",
"python-imaging-library",
"pillow",
"google-cloud-datalab"
] |
How to ensure double quote in multiline strings | 37,992,722 | <p>I wrote an SQL query which uses data passed in from WTForms as parameters.
How do I ensure double quotes on the variable? </p>
<pre><code>q = """
select * from table
where dt_date >= %(date)s""" % {'date':date}
</code></pre>
<p>Right now it shows as </p>
<pre><code>select * from table
where dt_date >= 23-06... | 2 | 2016-06-23T13:13:57Z | 37,992,876 | <p>Try escaping the double quotes in your multine.</p>
<pre><code>>>> q = """
... select * from table
... where dt_date >= \"%(date)s\""""%{'date':date}
>>> q
'\nselect * from table\nwhere dt_date >= "23-06-2016"'
>>> print q
select * from table
where dt_date >= "23-06-2016"
</code... | 1 | 2016-06-23T13:19:56Z | [
"python",
"wtforms"
] |
How to ensure double quote in multiline strings | 37,992,722 | <p>I wrote an SQL query which uses data passed in from WTForms as parameters.
How do I ensure double quotes on the variable? </p>
<pre><code>q = """
select * from table
where dt_date >= %(date)s""" % {'date':date}
</code></pre>
<p>Right now it shows as </p>
<pre><code>select * from table
where dt_date >= 23-06... | 2 | 2016-06-23T13:13:57Z | 37,993,224 | <p>Python doesn't stop you from using double-quotes inside your multiline strings. The trouble is only when you place them next to each other (<code>""""</code>). You can either escape your double quotes as <code>\"</code> or simply leave a space between them and the triple-quotes (<code>" """</code>).</p>
<p><strong>... | 0 | 2016-06-23T13:35:17Z | [
"python",
"wtforms"
] |
Matrix addition of unequal matrices | 37,992,852 | <p>From what I know, 2 matrices can be added only if they have equal sizes.</p>
<p>Consider the cases-</p>
<pre><code>1. a=eye(5)
b=1
</code></pre>
<p>a+b is valid as b is treated as a scalar:</p>
<pre><code>2. a=eye(5)
b=[1,2]
</code></pre>
<p>a+b -> This is invalid due to unequal sizes.</p>
<pre><code>3.... | 0 | 2016-06-23T13:18:57Z | 37,992,977 | <p>Assuming you are using Numpy, <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.add.html" rel="nofollow">their docs explains</a> what can happen when adding objects with different sizes:</p>
<blockquote>
<p>Parameters:</p>
<pre><code>x1, x2 : array_like
</code></pre>
<p>The arrays to be add... | 3 | 2016-06-23T13:24:28Z | [
"python",
"numpy",
"matrix"
] |
Tornado JSON output new line each data instead of each character | 37,992,856 | <p>I cant get to output the json data accordingly. Instead it outputs each character new line. Code:</p>
<pre><code>import tornado.web
import tornado.ioloop
import tornado.httpserver
from tornado.escape import json_encode
class Handler(tornado.web.RequestHandler):
def get(self):
#Sample Json Data
... | 0 | 2016-06-23T13:19:04Z | 37,993,028 | <p>Make your data a list of dictionaries instead of a string. </p>
<p><code>jsondata = [{"name": "DU-001", "lat": "4.901787", "lng": "114.925919"},{ "name": "DU-002", "lat": "4.901789", "lng": "114.925929"}]</code></p>
| 1 | 2016-06-23T13:26:47Z | [
"python",
"json",
"encoding",
"tornado",
"decoding"
] |
PDF to TEXT converted in a wrong way | 37,992,961 | <p>I am extracting the text from many PDF files using pdfminer.
The result text file for some pdf files is strange where each line consits of one character only.
Not all of the PDF files but some of them and I still can't find out why and which PDF files will cause this problem.</p>
<p>Here is my code:</p>
<pre><code... | 0 | 2016-06-23T13:23:35Z | 37,993,157 | <p>Use <a href="https://github.com/chrismattmann/tika-python" rel="nofollow"><code>tika</code></a> it's giving better result for me.</p>
<pre><code>from tika import parser
def pdf_parser_tika(file_pointer):
parsed = parser.from_file(file_pointer)
return parsed["content"]
</code></pre>
| 0 | 2016-06-23T13:32:43Z | [
"python",
"pdfminer"
] |
How to update directory to look for new files in Python using subprocess.Popen | 37,993,004 | <p>Dear pythonists I have some software.exe executable that is called by a python module. This software.exe creates new files as outputs.
I would like to move one of these files called "whatever.xml' to anotherFolder how can I "refresh" a directory contents?
The following code only consider the previous state and cann... | 1 | 2016-06-23T13:25:45Z | 37,993,593 | <p>Popen does not block so the files may not be created before you call copy, you can call <code>.communicate()</code> or just use <code>check_call</code> which wont return until the process completes.</p>
<pre><code>subprocess.check_call('sofware.exe')
shutil.copy( 'whatever.xml' , anotherFolder )
</code></pre>
| 1 | 2016-06-23T13:50:40Z | [
"python",
"python-2.7",
"subprocess"
] |
Nothing is printed after reading text from a table (td) using Selenium Python | 37,993,099 | <p>I'm trying to print the text for a table cell, but nothing is being printed. It's identifying the element, but doesn't seem to be able to locate the text.</p>
<p>The HTML looks like this:</p>
<pre><code><tr style="font-weight: 600;">
<td>
"
Available Balance
... | 1 | 2016-06-23T13:30:12Z | 37,993,752 | <p>I think it's just a timing issue - the balance has not been set/updated at the moment you retrieve it's value. Add an <a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" rel="nofollow"><em>Explicit Wait</em></a> to wait for the text to be present:</p>
<pre><code>from selenium.webdriver.common.... | 1 | 2016-06-23T13:56:58Z | [
"python",
"html",
"selenium"
] |
Nothing is printed after reading text from a table (td) using Selenium Python | 37,993,099 | <p>I'm trying to print the text for a table cell, but nothing is being printed. It's identifying the element, but doesn't seem to be able to locate the text.</p>
<p>The HTML looks like this:</p>
<pre><code><tr style="font-weight: 600;">
<td>
"
Available Balance
... | 1 | 2016-06-23T13:30:12Z | 37,994,630 | <p>(Thanks to RemcoW)</p>
<p>print(Balance.get_attribute('textContent'))</p>
| 0 | 2016-06-23T14:32:19Z | [
"python",
"html",
"selenium"
] |
How do I detect variables in a python eval expression | 37,993,137 | <p>Let's say i get a string to eval</p>
<pre><code>temperature*x
</code></pre>
<p>And I have two sets of variables - the easy one:</p>
<pre><code>easy_ns = {'x':3, 'y':4}
</code></pre>
<p>And a harder one:</p>
<pre><code>harder = ['temperature', 'sumofall']
</code></pre>
<p>Each of which will take significant tim... | -1 | 2016-06-23T13:31:41Z | 37,993,480 | <p>You could, if you really really have to, parse the code using the <a href="https://docs.python.org/2/library/ast.html" rel="nofollow"><code>ast</code></a> module. The <code>ast.parse</code> helper will give you an AST tree representation of the code:</p>
<pre><code>import ast
code = "temperature*x"
st = ast.parse(c... | 3 | 2016-06-23T13:45:19Z | [
"python"
] |
How do I detect variables in a python eval expression | 37,993,137 | <p>Let's say i get a string to eval</p>
<pre><code>temperature*x
</code></pre>
<p>And I have two sets of variables - the easy one:</p>
<pre><code>easy_ns = {'x':3, 'y':4}
</code></pre>
<p>And a harder one:</p>
<pre><code>harder = ['temperature', 'sumofall']
</code></pre>
<p>Each of which will take significant tim... | -1 | 2016-06-23T13:31:41Z | 37,993,941 | <p>You could make it a lambda function, and simply execute it whenever you need to, as such:</p>
<pre><code>a = lambda : 5*temperature
a()
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "<stdin>", line 1, in <lambda>
> NameError: global name 't... | 0 | 2016-06-23T14:04:05Z | [
"python"
] |
difference between command prompt and anaconda prompt | 37,993,175 | <p>I installed anaconda into my computer using python. After I install the software, I found there is one program called anaconda prompt.</p>
<p>What is the difference between anaconda prompt and command prompt? If I want to update the package, which one I should use or either one. Like (conda update conda)</p>
<p>Th... | 1 | 2016-06-23T13:33:11Z | 37,995,670 | <p>Anaconda command prompt is just like command prompt, but it makes sure that you are able to use anaconda and conda commands from the prompt, without having to change directories or your path. </p>
<p>When you start Anaconda command prompt, you'll notice that it adds/("prepends") a bunch of locations to your PATH. T... | 1 | 2016-06-23T15:18:01Z | [
"python",
"command-prompt",
"anaconda"
] |
Model.create does not save to DB | 37,993,600 | <p>I am trying to save an instance of a model to the database as described in this article:</p>
<p>Create method from <code>Promo</code> class:</p>
<pre><code>@classmethod
def create(cls, discount_money):
promo = cls(discount_money=discount_money)
return promo
</code></pre>
<hr>
<pre><code>@staticmethod
de... | -1 | 2016-06-23T13:50:53Z | 37,993,708 | <p>Neither method ever calls <code>save</code>, so nothing will be reflected in the database.</p>
<p>You need to make sure you call <code>save</code> in at least one of those methods. Probably makes more sense in the <code>create</code> method.</p>
<pre><code>@classmethod
def create(cls, discount_money):
promo = ... | 2 | 2016-06-23T13:54:52Z | [
"python",
"django"
] |
Model.create does not save to DB | 37,993,600 | <p>I am trying to save an instance of a model to the database as described in this article:</p>
<p>Create method from <code>Promo</code> class:</p>
<pre><code>@classmethod
def create(cls, discount_money):
promo = cls(discount_money=discount_money)
return promo
</code></pre>
<hr>
<pre><code>@staticmethod
de... | -1 | 2016-06-23T13:50:53Z | 37,993,721 | <p>As it is mentioned in the <a href="https://docs.djangoproject.com/en/1.9/ref/models/instances/" rel="nofollow">Django docs</a>:</p>
<blockquote>
<p>Note that instantiating a model in no way touches your database; for
that, you need to save().</p>
</blockquote>
<p>Therefore you need to add <code>promo.save()</c... | 1 | 2016-06-23T13:55:20Z | [
"python",
"django"
] |
How to use requests to send a PATCH request with headers | 37,993,624 | <p>I have a Rails 4 application which uses token based authentication for APIs and need to be able to update records through Python 3 script.</p>
<p>My current script looks like this</p>
<pre><code>import requests
import json
url = 'http://0.0.0.0:3000/api/v1/update_experiment.json'
payload = {'expt_name' : 'A60E001... | 3 | 2016-06-23T13:51:45Z | 37,993,830 | <p><a href="http://docs.python-requests.org/en/master/_modules/requests/api/#patch" rel="nofollow">patch</a> takes kwargs, just pass headers = {your_header}:</p>
<pre><code>def patch(url, data=None, **kwargs):
"""Sends a PATCH request.
:param url: URL for the new :class:`Request` object.
:param data: (opt... | 2 | 2016-06-23T13:59:38Z | [
"python",
"python-3.x",
"python-requests"
] |
Python convert (read & save) excel xlsx to xls | 37,993,868 | <p>How can I convert an existing <code>xlsx</code> Excel file into <code>xls</code> while retaining my Excel file formatting? I use Anaconda Python 3, so I'm not sure I can use <code>xlutils</code>... I was not able to install it via <code>conda install xlutils</code> because of lots of incompatibilities. So now I use ... | 0 | 2016-06-23T14:01:01Z | 37,995,832 | <p>You can try to use openpyxl, and install it by <strong>conda install openpyxl</strong>
and it should work with python3.5*
Then the following code might work</p>
<pre><code>import openpyxl as xl
wb = xl.load_workbook("yourfile.xlsx")
wb.save("file.xls")
</code></pre>
<p>You can learn more from openpyxl documentatio... | 0 | 2016-06-23T15:24:40Z | [
"python",
"excel",
"xls",
"xlsx"
] |
How to pass function with parameters in a dictionary key value pair | 37,993,933 | <p>I am new to python and was trying to create a dictionary with value as a function. here is my code </p>
<pre><code>import os
class Foo():
def print1(self,n):
print 5
def print2(self,n):
print 6
def foo(self):
bar = {'a': self.print1, 'b': self.print2}
bar['b'](5)
... | 2 | 2016-06-23T14:03:42Z | 37,994,023 | <p>The way you do it, the function gets called and the result gets stored (which is None because you don't return anything), if you want the function to be callable as such, you could either write a <code>lambda</code> around it or use <code>functools.partial</code></p>
| 0 | 2016-06-23T14:07:18Z | [
"python",
"dictionary"
] |
How to pass function with parameters in a dictionary key value pair | 37,993,933 | <p>I am new to python and was trying to create a dictionary with value as a function. here is my code </p>
<pre><code>import os
class Foo():
def print1(self,n):
print 5
def print2(self,n):
print 6
def foo(self):
bar = {'a': self.print1, 'b': self.print2}
bar['b'](5)
... | 2 | 2016-06-23T14:03:42Z | 37,994,036 | <p>Try this code:</p>
<pre><code>class Foo():
def print1(self,n):
print 6
def print2(self,n):
print n
def foo(self):
bar = {'a': self.print1, 'b': self.print2 }
bar['b'](5)
bar['a'](3)
f = Foo()
f.foo()
</code></pre>
<p>It does what you want.</p>
| 0 | 2016-06-23T14:07:39Z | [
"python",
"dictionary"
] |
How to pass function with parameters in a dictionary key value pair | 37,993,933 | <p>I am new to python and was trying to create a dictionary with value as a function. here is my code </p>
<pre><code>import os
class Foo():
def print1(self,n):
print 5
def print2(self,n):
print 6
def foo(self):
bar = {'a': self.print1, 'b': self.print2}
bar['b'](5)
... | 2 | 2016-06-23T14:03:42Z | 37,994,051 | <p><code>bar = {'a': self.print1(6), 'b': self.print2(5) }</code> doesn't store the functions as the values in the dictionary. </p>
<p>It calls the functions <code>print1</code> and <code>print2</code> and stores their return values. Since both the functions only <code>print</code> and don't return anything, you get t... | 1 | 2016-06-23T14:08:16Z | [
"python",
"dictionary"
] |
access nested data in json | 37,994,091 | <p>I want to retrieve all the IP address range from Azure cloud from <a href="https://www.microsoft.com/en-in/download/details.aspx?id=41653" rel="nofollow">here</a>
The data after conversion in json is in the following format:</p>
<pre><code>{
"AzurePublicIpAddresses": {
"Region": [
{
...
... | 0 | 2016-06-23T14:09:48Z | 37,994,406 | <p><code>AzurePublicIpAddresses</code> is a dictionary, so:</p>
<pre><code>for i in data["AzurePublicIpAddresses"]:
</code></pre>
<p>Iterates through the keys (which are strings, in this case). I.e. you're trying to do "Region"["Region"], which is string slicing. Try something more like:</p>
<pre><code>for i in data... | 0 | 2016-06-23T14:22:38Z | [
"python",
"json",
"azure"
] |
access nested data in json | 37,994,091 | <p>I want to retrieve all the IP address range from Azure cloud from <a href="https://www.microsoft.com/en-in/download/details.aspx?id=41653" rel="nofollow">here</a>
The data after conversion in json is in the following format:</p>
<pre><code>{
"AzurePublicIpAddresses": {
"Region": [
{
...
... | 0 | 2016-06-23T14:09:48Z | 37,994,649 | <p><code>data["AzurePublicIpAddresses"]</code> is a <code>dict</code>. Iterating directly over a <code>dict</code> just gives you the the keys of that <code>dict</code>.</p>
<p>So </p>
<pre><code>for i in data["AzurePublicIpAddresses"]:
print(i)
</code></pre>
<p>will print </p>
<pre><code>Region
_xmlns:xsd
_xml... | 1 | 2016-06-23T14:33:12Z | [
"python",
"json",
"azure"
] |
Web Scraping with Python - Selecting div, h2 and h3 class | 37,994,270 | <p>This is my first time with Python and web scraping. Have been looking around and still unable to get what I need to do.</p>
<p>Below are print screen of the elements that I've used via Chrome.</p>
<p>What I am trying to do is that, I am trying to get the apartment names and the address from the selected city name.... | 2 | 2016-06-23T14:17:21Z | 37,994,669 | <p>As I commented, some of the data is dynamically created, if we look at the source itself we see:</p>
<pre><code> <div class="content">
<div class="title-container">
<h2 class="building-name"><%= b... | 3 | 2016-06-23T14:34:16Z | [
"python",
"html",
"beautifulsoup"
] |
pandas timedelta to int as a vectorized operation | 37,994,276 | <p>I have a dataframe with a date column (not a datetime index). I want to create another columns whose value is today minus date from the date column. I can do this as a vectorized operation <code>ts['days ago'] = dt.date.today() -ts['foo']</code></p>
<p>But this gives me a Timedelta object, while I want an int. T... | 1 | 2016-06-23T14:17:36Z | 37,994,524 | <p><code>.apply</code> to get the days property can get you the days as <code>ints</code></p>
<pre><code>ts["days ago int "] = ts['days ago'].apply(lambda x:x.days)
</code></pre>
| 2 | 2016-06-23T14:27:56Z | [
"python",
"datetime",
"pandas"
] |
Python script runs perfect in PyCharm but in terminal don't | 37,994,290 | <p>I really don't understand... If you need screenshots of some settings please tell me because I really don't know why it works in PyCharm but not outside Pycharm...</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import unittest
from datetime import datetime
cla... | -1 | 2016-06-23T14:17:57Z | 37,994,384 | <p>When you run <code>unittest</code>s in Pycharm, Pycharm provides a wrapper that executes other code before your code.</p>
<p>To execute <code>unittest</code>s from the terminal, you should use this command, provided that you have <code>python</code> set in your <code>PATH</code>:</p>
<p><code>python -m unittest /p... | 0 | 2016-06-23T14:21:51Z | [
"python",
"python-3.x",
"pycharm"
] |
Interchanging columns in a CSV file | 37,994,382 | <p>I have a csv file and i need to alter the colum indexes. My current file is</p>
<pre><code>A B C D E F G
1 0 0.5 5 1 7 6
2 0 0.6 4 0 7 6
3 0 0.7 3 1 7 6
4 0 0.8 2 0 7 6
</code></pre>
<p>But i need it like: </p>
<pre><code>D F G A B C E
5 7 6 1 ... | 1 | 2016-06-23T14:21:46Z | 37,994,481 | <p>Use csv.DictReader csv.DictWriter.</p>
<pre><code>import csv
with open('names_in.csv') as csvin, open('names_out.csv', 'w') as csvout:
reader = csv.DictReader(csvin)
writer = csv.DictWriter(csvout, fieldnames=["D", "F", "G", "A", "B","C", "E"])
for row in reader:
writer.writerow(row)
</code><... | 2 | 2016-06-23T14:25:57Z | [
"python",
"python-2.7",
"numpy",
"pandas"
] |
Interchanging columns in a CSV file | 37,994,382 | <p>I have a csv file and i need to alter the colum indexes. My current file is</p>
<pre><code>A B C D E F G
1 0 0.5 5 1 7 6
2 0 0.6 4 0 7 6
3 0 0.7 3 1 7 6
4 0 0.8 2 0 7 6
</code></pre>
<p>But i need it like: </p>
<pre><code>D F G A B C E
5 7 6 1 ... | 1 | 2016-06-23T14:21:46Z | 37,994,870 | <p>You can read your file using <code>pandas.read_csv</code> then reorder the columns and rewrite your file with <code>to_csv</code>:</p>
<pre><code>import pandas as pd
df = pd.read_csv(your_file)
ncols = 3
cols = df.columns[-ncols:].tolist() + df.columns[:-ncols].tolist()
df[cols].to_csv(your_file)
</code></pre>
... | 1 | 2016-06-23T14:42:40Z | [
"python",
"python-2.7",
"numpy",
"pandas"
] |
Pandas pivot table ignoring zeros while taking mean | 37,994,434 | <p>I am trying the following</p>
<pre><code>import pandas as pd
import numpy as np
dfout3 = pd.DataFrame({'Idx': MnthIdx,
'Col1': Val1,
'Col2': Val2,
'Col3': Val3)})
MeanTable1 = pd.pivot_table(dfout3, index=['Idx'], values=['Col1','Col2','Col3'], ... | 0 | 2016-06-23T14:23:32Z | 37,994,938 | <p>I don't know if there is a way to ignore zeros, but you can set them as the mean value before the <code>pivot</code> (which will give the same result):</p>
<pre><code>for col in dfout3.columns:
dfout3.ix[dfout3.col == 0,col] = dfout3.col.mean()
</code></pre>
| 1 | 2016-06-23T14:45:24Z | [
"python",
"numpy",
"pandas",
"pivot-table"
] |
Unable to save existing model instance created via _from_json method | 37,994,509 | <p>Method <code>from_json</code> of <code>mongoengine</code> <code>ModelClass</code> used for:</p>
<blockquote>
<p>Converts json data to an unsaved document instance</p>
</blockquote>
<p>If i send to a server json with some changed fields and trying to convert in to unsaved document instance, they dont track a <cod... | 0 | 2016-06-23T14:27:27Z | 37,994,739 | <p>Can't you just do this?</p>
<pre><code>data = self.request.data
model_instance = SomeModel(**data)
print(model_instance._changed_fields) # should not be empty
model_instance.save() # should work
</code></pre>
<p><strong>Explanations:</strong></p>
<p>In python, if a function or a class takes arguments (args) and... | 1 | 2016-06-23T14:36:57Z | [
"python",
"django",
"mongoengine"
] |
Cannot replicate results comparing Python, Numpy and Numba matrix multiplication | 37,994,521 | <p>So while evaluating possibilities to speed up Python code i came across this Stack Overflow post: <a href="http://stackoverflow.com/questions/36526708/comparing-python-numpy-numba-and-c-for-matrix-multiplication">Comparing Python, Numpy, Numba and C++ for matrix multiplication</a></p>
<p>I was quite impressed with ... | 2 | 2016-06-23T14:27:42Z | 37,995,031 | <p>In the <a href="http://stackoverflow.com/questions/36526708/comparing-python-numpy-numba-and-c-for-matrix-multiplication">linked stackoverflow</a> question where you got the code from, <code>m = n = 3</code> and <code>p</code> is variable, whereas you are using <code>m = n = 1000</code>, which is going to make a hug... | 3 | 2016-06-23T14:49:06Z | [
"python",
"numpy",
"scipy",
"numba"
] |
How do I send commands from PHP script to Terminal running a Python interpreter? | 37,994,538 | <p>I want to access the Terminal from a PHP script to open a standalone version of Maya and then run a Python script in Maya from the Terminal.</p>
<p>I've been able to send commands to the Terminal from my PHP script using the <code>exec()</code> function. For example, I've been able to open Maya with an .OBJ file us... | 0 | 2016-06-23T14:28:37Z | 38,002,105 | <p>You don't need to code separate with mayapy, you can run script directly with mayapy</p>
<p><strong>test.py</strong></p>
<pre><code>import os
import maya.standalone
maya.standalone.initialize()
import maya.cmds as cmds
print dir(cmds)
</code></pre>
<p>You can simply call this script like this </p>
<pre><code>may... | 2 | 2016-06-23T21:23:29Z | [
"php",
"python",
"shell",
"interpreter",
"maya"
] |
Django + celery - why my periodic task in not running? | 37,994,714 | <p>I'm working in a periodic task using django + celery. My project has django-celery==3.1.17, the broker used is Redis and it is working.</p>
<p>In my settings file:</p>
<pre><code>CELERYBEAT_SCHEDULE={
'delivery_send': {
'task': 'delivery.tasks.DeliverySendTask',
'schedule': timedelta(minutes=1)... | 0 | 2016-06-23T14:35:58Z | 37,997,967 | <p>celery beat does not execute tasks. Only schedule tasks into queue. <code>celery worker</code> executes tasks.</p>
<p>To execute tasks periodically you have to start both <code>celery beat</code> and <code>celery worker</code>.</p>
<pre><code>python manage.py celery beat
python manage.py celery worker
</code></pre... | 3 | 2016-06-23T17:16:13Z | [
"python",
"django",
"django-celery"
] |
Need to figure out the random number the function gives me | 37,994,716 | <p>Since I am using random generator to place the ships how can I be able to get the exact value of x and y coordinate from my function:</p>
<pre><code>def addShip(board):
x = randint(0, 9)
y = randint(0, 9)
board[x][y] = 1
</code></pre>
<p>How would i be able to print the exact value that the function used f... | -3 | 2016-06-23T14:36:07Z | 37,995,325 | <pre><code>def addShip(board):
x = randint(0, 9)
y = randint(0, 9)
return x, y
board[x][y] = 1
</code></pre>
| 0 | 2016-06-23T15:01:20Z | [
"python"
] |
WeasyPrint usage with Python 3.x on Windows | 37,994,733 | <p>I can't seem to get WeasyPrint to work on Windows with Python 3.4 or 3.5. Has anyone been able to do this? There aren't forums at weasyprint.org and the IRC channel is dead. </p>
<p>I've been able to install using both Python 3.4.3 and 3.5.1. I've followed the guideline found here [1]. I've also made note that... | 0 | 2016-06-23T14:36:44Z | 38,082,024 | <p>I had looked through the issues list at weasyprint.org and didn't find anyone else complaining about Python 3.x compatibility with WeasyPrint. Then I happened upon a pull request that did complain about just that and mirrors my difficulties exactly. So off the shelf it does <em>not</em> work with Python 3.x, but w... | 0 | 2016-06-28T16:52:02Z | [
"python",
"weasyprint"
] |
In pandas how to read csv files with lists in a column? | 37,994,791 | <p>I have a csv file in which some columns which look like this:</p>
<pre><code>df = pd.DataFrame({'a':[['ID1','ID2','ID3'],['ID1','ID4'],[]],'b':[[8.6,1.3,2.5],[7.5,1.2],[]],'c':[[12,23,79],[42,10],[]]})
Out[1]: a b c
0 [ID1, ID2, ID3] [8.6, 1.3, 2.5] [12, 23, 79]
1... | -1 | 2016-06-23T14:38:51Z | 37,995,412 | <p>To do this, you can make use of the <code>converters</code> in the <code>pd.read_csv</code> function (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow" title="doc">Documentation for read_csv</a>:</p>
<p>Using your example,</p>
<pre><code>'ID of the project' 'postc... | 0 | 2016-06-23T15:05:46Z | [
"python",
"csv",
"pandas",
"dataframe"
] |
Pip "install" Installs in Jython instead of python | 37,994,792 | <p>I am trying to install "XLRD" library for python using PIP install, the library is installed successfully, after execution i tried to import the same but i get the error that no modules have been installed.</p>
<p>After some research i found that everything is getting installed in the C:jython/site-packages directo... | 1 | 2016-06-23T14:38:53Z | 37,994,850 | <p>On your terminal/command prompt navigate to the Python home directory of the version for which you need to install the module. Then navigate into the scripts folder and run the pip command. Like below</p>
<pre><code>cd C:/python27/Scripts
pip install XLRD
</code></pre>
<p>You basically need to point to the pip scr... | 2 | 2016-06-23T14:41:32Z | [
"python",
"python-2.7",
"pip",
"jython"
] |
Getting Kivy running with Python on Winpython | 37,994,830 | <p>I've done tons of research on my issues, and I haven't really found an answer:
I'm trying to use Kivy in Eclipse on my computer. I've got an environment setup already, and I installed Kivy and the dependencies just like this:
<a href="https://kivy.org/docs/installation/installation-windows.html#" rel="nofollow">htt... | 1 | 2016-06-23T14:40:55Z | 38,058,743 | <p>Paste output of <code>echo %PATH%</code> here. Feel free to cut of personal things, I only want to know if sdl2 is available on the path (which I think is not). If not, add it. Should look like this:</p>
<pre><code><python.exe dir>\share\sdl2\bin
</code></pre>
<p>If it doesn't work for you, well... I'm still... | 0 | 2016-06-27T16:17:34Z | [
"python",
"kivy"
] |
How to use list of RegEx's when defining LxmlLinkExtractor rule | 37,994,874 | <p>I would like to know how I can define a list of RegEx's outside of my Scrapy spider, and then read the RegEx's into a <strong>LxmlLinkExtractor</strong>.</p>
<p>I'm using the current code: </p>
<pre><code>file = open("myFile.txt")
regexs = [rule.strip() for rule in file.readlines()]
file.close()
return regexs
</co... | 1 | 2016-06-23T14:42:44Z | 37,995,080 | <p>This <em>should</em> work:</p>
<pre><code>regexs = [rule.strip() for rule in file.readlines()]
LinkExtractor(allow=regexs, callback='parse_file')
</code></pre>
<p>See more here about the allow parameter:
<a href="http://doc.scrapy.org/en/latest/topics/link-extractors.html#module-scrapy.linkextractors.lxmlhtml" rel... | 1 | 2016-06-23T14:51:00Z | [
"python",
"scrapy"
] |
Best way to improve UDP transfer speeds with Python? | 37,995,053 | <p>I have written a Python program for sending and receiving large files over UDP. Right now, I can hit speeds of about .01GB/s when transferring between two computers on a 10 Gigabit Ethernet cable. I'm looking to improve that speed significantly, but I'm unsure what the best approach is.</p>
<p>For what it's worth, ... | 3 | 2016-06-23T14:50:07Z | 37,995,253 | <p>Some approaches to try:</p>
<ol>
<li>Varied packet sizes (depending on <a href="https://en.wikipedia.org/wiki/Maximum_transmission_unit" rel="nofollow">MTU</a>, might cause the chunk to be fragmented to several packets, or might be too small to optimally use the pipe)</li>
<li>Read the file to memory (the network s... | 0 | 2016-06-23T14:58:26Z | [
"python",
"performance",
"sockets",
"udp"
] |
Delete string from dataframe with condition using pandas | 37,995,244 | <p>I have data</p>
<pre><code> event_address event_time
0 https://mail.yandex.ru/clck=2230&uid=1189231... 2016-06-14 03:05:19
1 https://mail.yandex.ru/?ncrnd=2230&uid=1189231... 2016-06-14 03:05:23
2 https://mail.yandex.ru/clck=2230&am... | 0 | 2016-06-23T14:57:43Z | 37,995,311 | <p>try this:</p>
<pre><code>df[~df.event_address.str.contains(r"yandex.ru/clck")]
</code></pre>
<p>demo:</p>
<pre><code>In [167]: df[~df.event_address.str.contains(r"yandex.ru/clck")]
Out[167]:
event_address
1 https://mail.yandex.ru/?ncrnd=2230&uid=1189231
3 http://mail... | 2 | 2016-06-23T15:00:41Z | [
"python",
"pandas"
] |
How to create Azure AlertRule programmatically | 37,995,271 | <p>Is it possible to create an Azure VM AlertRule using either Java or Python? I do not see any documentation in the SDK for either language.</p>
<p>An acceptable answer shows code snippet in either language and does not suggest the usage of the Portal or Powershell.</p>
| 0 | 2016-06-23T14:59:13Z | 38,010,940 | <p>@bearrito,
As far as I know, currently there is not SDK for Python and Java about to create Azure VM alert rule. But we could use Azure REST API to create this rule.
Please refer to this document.<a href="https://msdn.microsoft.com/en-us/library/azure/dn510366.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/li... | 1 | 2016-06-24T10:13:28Z | [
"java",
"python",
"azure"
] |
Python ftp.retrbinary() does not work when called parallelized in function | 37,995,340 | <p>I am using a script to retrieve data from a ftp-server. As I want to parallelize the download, <code>ftp.retrbinary</code> is called within a function.</p>
<p>Atm the working code looks like this:</p>
<pre><code>from ftplib import FTP
def download_file(file_in, target_file):
ftp.retrbinary('RETR '+file_in, op... | 0 | 2016-06-23T15:01:48Z | 37,999,385 | <p>You cannot use one FTP session for multiple parallel transfers. The FTP protocol does not support that (contrary to the SFTP for example). </p>
<p>You have to open a separate FTP session for each parallel job.</p>
| 0 | 2016-06-23T18:40:04Z | [
"python",
"python-2.7",
"ftp"
] |
Django Create Multiple URLs that call same View for POST and GET | 37,995,384 | <p>I am using URLconfig. Can I create two URLs (for POST and GET) that call same View?</p>
<pre><code>url(r'^persons/(?P<id_person>P\.\d+)/forms/(?P<formacronym>\w+)/$', views.PersonFormView.as_view()),
url(r'^persons/(?P<id_person>P\.\d+)/forms/(?P<id_form>[\w.]+)/$', views.PersonFormView.as_... | 0 | 2016-06-23T15:04:13Z | 37,995,548 | <p>If you are using <a href="https://docs.djangoproject.com/en/1.9/topics/class-based-views/" rel="nofollow">CBV</a>, you can construct one URL that points to your View. Then depending on the request method the appropriate method on the class will be executed.</p>
<pre><code>from django.views.generic import View
clas... | 0 | 2016-06-23T15:12:15Z | [
"python",
"django",
"django-views",
"django-urls",
"django-class-based-views"
] |
check if text contained in a font tag | 37,995,417 | <p>Im using selenium in python in order to check if a text between font tags in contained and getting the tag tbody back if it is.</p>
<p>the html code:</p>
<pre><code><table width="100%" border="0" cellspacing="1" cellpadding="1" bgcolor="#000000" height="80">
<tbody>
<tr bgcolor="#666699"... | 0 | 2016-06-23T15:06:07Z | 37,995,561 | <p>This xpath return TBODY tag which contains FONT tag with 'PARTY 1' text:</p>
<p><code>//tbody[.//font[contains(.,'PARTY 1')]]</code></p>
| 0 | 2016-06-23T15:12:50Z | [
"python",
"html",
"selenium",
"selenium-webdriver",
"selenium-ide"
] |
check if text contained in a font tag | 37,995,417 | <p>Im using selenium in python in order to check if a text between font tags in contained and getting the tag tbody back if it is.</p>
<p>the html code:</p>
<pre><code><table width="100%" border="0" cellspacing="1" cellpadding="1" bgcolor="#000000" height="80">
<tbody>
<tr bgcolor="#666699"... | 0 | 2016-06-23T15:06:07Z | 38,003,986 | <p>First get the font element using <code>el = driver.find_element_by_xpath('insert xpath here')</code> and then use <code>el.text</code> to get the text. You're code should look like this:</p>
<pre><code>el = driver.find_element_by_xpath('insert xpath of font tag here')
if el.text == 'PARTY 1':
return driver.fin... | 0 | 2016-06-24T00:37:13Z | [
"python",
"html",
"selenium",
"selenium-webdriver",
"selenium-ide"
] |
Python pymqi : How to specify the message format for putting to a queue | 37,995,534 | <p>I amd trying put a string message in MQ using pymqi, the code is as follows; </p>
<pre><code>import xml.dom.minidom as minidom
import pymqi
class PutMQ:
def put_mq(args1):
doc = minidom.parse(args1)
queue_manager = "NameQueueManager"
channel = "ChannelName"
... | 3 | 2016-06-23T15:11:26Z | 38,003,297 | <p>According to the <a href="https://pythonhosted.org/pymqi/api.html" rel="nofollow">PyMQI Docs</a> this is the definition of the put call:</p>
<blockquote>
<p><strong>put(msg[, mDesc, putOpts])</strong></p>
<p>Put the string buffer âmsgâ on the queue. If the queue is not already open, it is opened now with... | 1 | 2016-06-23T23:08:08Z | [
"python",
"websphere-mq",
"mq"
] |
How do I replace multiple substrings in a Python list? | 37,995,663 | <p>I need to turn the input_string into the comment below using a for loop. First I sliced it using the split function, but now I need to somehow turn the input string into <code>['result1','result2', 'result3', 'result5']</code>. I tried replacing the .xls and the dash for nothing (') but the string output is unchange... | 1 | 2016-06-23T15:17:44Z | 37,995,741 | <p>Use the <a href="https://docs.python.org/3/library/re.html" rel="nofollow">re module's <code>sub</code></a> function and <a href="https://docs.python.org/3/library/stdtypes.html#str.split" rel="nofollow"><code>split</code></a>.</p>
<pre><code>>>> input_string = "01-result.xls,2-result.xls,03-result.xls,05-... | 3 | 2016-06-23T15:21:10Z | [
"python",
"regex",
"string",
"list",
"replace"
] |
How do I replace multiple substrings in a Python list? | 37,995,663 | <p>I need to turn the input_string into the comment below using a for loop. First I sliced it using the split function, but now I need to somehow turn the input string into <code>['result1','result2', 'result3', 'result5']</code>. I tried replacing the .xls and the dash for nothing (') but the string output is unchange... | 1 | 2016-06-23T15:17:44Z | 37,995,913 | <p>Here's a solution using list comprehension and string manipulation if you don't want to use re.</p>
<pre><code>input_string = "01-result.xls,2-result.xls,03-result.xls,05-result.xls"
# Must be turned into ['result1','result2', 'result3', 'result5']
splitted = input_string.split(',')
#Remove extension, then split... | 2 | 2016-06-23T15:28:44Z | [
"python",
"regex",
"string",
"list",
"replace"
] |
return formatted string with list comprehension in python2.7 | 37,995,830 | <p>Please note this is from a learning exercise for myself to learn OOP. <strong>Please do not tell me to use numpy</strong> because the point of this exercise for me is to learn about creating classes and defining methods (however, if numpy or any other library contains a method that does exactly what I'm asking for t... | 0 | 2016-06-23T15:24:35Z | 37,995,919 | <p>Seems to me that you're pretty close. You only need to alter what you're <code>join</code>ing on, and add an additional left bracket at the beginning. How about:</p>
<pre><code>return "[" + "]\n[".join("".join( "{:4}".format(num) for num in row) for row in self.matrix) +"]"
</code></pre>
<p>Which results in:</p>
... | 1 | 2016-06-23T15:28:56Z | [
"python",
"arrays",
"matrix",
"list-comprehension",
"nested-loops"
] |
Error: types.coroutine() expects a callable | 37,995,862 | <p>I have the following class:</p>
<pre><code>from tornado import gen
class VertexSync(Vertex):
@wait_till_complete
@gen.coroutine
@classmethod
def find_by_value(cls, *args, **kwargs):
stream = yield super().find_by_value(*args, **kwargs)
aggr = []
while True:
resp ... | 1 | 2016-06-23T15:26:18Z | 37,996,230 | <p>The problem is that <code>classmethod</code> does... interesting things. Once the class definition has <em>finished</em> you have a nice callable method on the class, but <em>during the definition</em> you have a <code>classmethod object</code>, which isn't callable:</p>
<pre><code>>>> a = classmethod(lamb... | 4 | 2016-06-23T15:44:35Z | [
"python",
"tornado"
] |
django - tuple in a template only returning first character? | 37,995,906 | <p>I am trying to access a tuple in a django template but for some reason i am only seeing the first character, i thought it may be because using .# returns substrings, so i took the # off, upon which it returns nothing at all</p>
<p>context_processors.py</p>
<pre><code>from django.conf import settings
def ProviderU... | -1 | 2016-06-23T15:28:21Z | 37,995,968 | <p>When you iterate over <code>circuit_providers</code> this way:</p>
<pre><code>{% for key, tuple in circuit_providers %}
...
{% endfor %}
</code></pre>
<p>You <em>unpack</em> every inner tuple, <code>key</code> is becoming <code>KCOM</code>, <code>tuple</code> is becoming <code>KCOM</code>, then <code>key</code... | 2 | 2016-06-23T15:31:07Z | [
"python",
"django"
] |
Strange python behaviour random | 37,995,911 | <p>This small script generates a random float beween 0 and 1 and then if its less than "0.000111111111111" it will print the message "found it"</p>
<pre><code>import random
value = 0.4 / 3600
print value
while True:
rand = random.random()
print "RAND IS: " + str(rand) + "----- VAL IS " + str(value)
if r... | 1 | 2016-06-23T15:28:38Z | 37,995,979 | <p>Your while loop is designed to run forever as <code>True</code> is always <code>True</code>. You never break out of that infinite loop. Even if it finds the value, it just prints it because the condition you give to the while loop is still True. Since you cannot change the condition, you need to add a break statemen... | 3 | 2016-06-23T15:31:37Z | [
"python",
"python-2.7",
"random"
] |
Strange python behaviour random | 37,995,911 | <p>This small script generates a random float beween 0 and 1 and then if its less than "0.000111111111111" it will print the message "found it"</p>
<pre><code>import random
value = 0.4 / 3600
print value
while True:
rand = random.random()
print "RAND IS: " + str(rand) + "----- VAL IS " + str(value)
if r... | 1 | 2016-06-23T15:28:38Z | 37,996,404 | <p>Your program does find numbers that are both smaller and larger than 'value', whether or not it prints all of them out. It's just that the output, <em>both ways</em>, is confusing you. This is because: (a) your computer is <em>faster</em> than you can probably imagine, as long as it doesn't have to print anything;... | 2 | 2016-06-23T15:52:45Z | [
"python",
"python-2.7",
"random"
] |
How do I lazy evaluate variables in a python eval expression | 37,995,920 | <p>The scenario is that my user can supply an expression string for evaluation. It could be:</p>
<pre><code>"power=(x**2+y**2)**0.5"
</code></pre>
<p>Then I get an input stream of data with labels. E.g.:</p>
<pre><code>x ; y ; z
1 ; 2 ; 3
1 ; 3 ; 4
</code></pre>
<p>And I will output a stream of data like this:</p>
... | 1 | 2016-06-23T15:28:57Z | 38,048,985 | <p>The best solution to the question is also posted in the linked question:</p>
<pre><code>import ast
def varsInExpression(expr):
st = ast.parse(expr)
return set(node.id for node in ast.walk(st) if type(node) is ast.Name)
</code></pre>
<p>This was posted by André Laszlo</p>
<p>It allows me to initialize the... | 0 | 2016-06-27T08:19:28Z | [
"python"
] |
Python/Django return all true variables | 37,995,950 | <p>I am trying to verify a variable condition to be greater than 0 and then if so then the text variable would be true. I have a fair amount of these as notifications I want to display in my code but for the sake of my question I will only list three here is my code:</p>
<pre><code>notifications1 = 100
if notification... | 0 | 2016-06-23T15:30:14Z | 37,996,001 | <p>You are missing the definition of some of either <code>text3</code> or <code>text</code> depending on the value of <code>notifications3</code>, because of the <code>else</code>. Try setting a default value for both of these variables before executing your code to modify their value.</p>
| 1 | 2016-06-23T15:32:58Z | [
"python",
"django",
"python-2.7",
"if-statement"
] |
Python/Django return all true variables | 37,995,950 | <p>I am trying to verify a variable condition to be greater than 0 and then if so then the text variable would be true. I have a fair amount of these as notifications I want to display in my code but for the sake of my question I will only list three here is my code:</p>
<pre><code>notifications1 = 100
if notification... | 0 | 2016-06-23T15:30:14Z | 37,996,038 | <p>I don't know much about Django, but I know what's wrong with your code. It is as the error says, you used <code>text3</code> before you assigned <code>text3</code>. Here's an explanation:</p>
<pre><code>if notifications3 > 1:
text3 = [{
'link': 'error1',
'icon_class': 'fa',
... | 2 | 2016-06-23T15:34:58Z | [
"python",
"django",
"python-2.7",
"if-statement"
] |
Homemade zoom shows wrong area | 37,995,957 | <p>Hey so I am working on a zoom function for a project I am working on at my internship. Normally I would just use the zoom provided already in plots and whatnot with matplotlib, but there is a special way we want to analyze multiple images at once that zoom doesn't support. I was trying to write a kind of zoom functi... | 1 | 2016-06-23T15:30:34Z | 37,996,718 | <p>At least one possible issue with your code is you are both slicing the <code>arr</code> when calling imshow as well as changing the axis limits (and setting these from zero to max-min). I would suggest simply adjusting the axis each time, with the following code:</p>
<pre><code>import matplotlib.pyplot as plt
from ... | 0 | 2016-06-23T16:07:51Z | [
"python",
"matplotlib"
] |
Print to Console Outside of the Class | 37,995,999 | <p>I am having trouble figuring this out.</p>
<p>I have a Class which prints the the console "inside" the class. I want to be able to print "outside" of the class so that I can use the data stream for other things. How can I get the stream from the code below?</p>
<pre><code>from ws4py.client.threadedclient import We... | 3 | 2016-06-23T15:32:54Z | 37,996,155 | <p>Why not print the messages in <code>received_message()</code>? Once you call <code>run_forever()</code>, it will only return when your client dies (or gets disconnect?). You have to handle events INSIDE the execution loop.</p>
<pre><code>run_forever() -->
code handling web-sockets -->
event handlers... | 2 | 2016-06-23T15:40:47Z | [
"python"
] |
Assign a tuple to multiple elements of a pandas dataframe | 37,996,000 | <p>I would like to assign a single tuple to a boolean-indexed slice of my dataframe, like this:</p>
<pre><code>>>> import pandas as pd
>>> mydataframe = pd.DataFrame([1,2,3,4,5],columns=['colname'])
>>> mydataframe.loc[mydataframe['colname']>2,'colname'] = (1,2)
</code></pre>
<p>Desired ... | 1 | 2016-06-23T15:32:55Z | 37,996,121 | <p>You'll have to construct a <code>Series</code> with the tuple repeated by the length of your df so it aligns:</p>
<pre><code>In [37]:
mydataframe = pd.DataFrame([1,2,3,4,5],columns=['colname'])
mydataframe.loc[mydataframe['colname']>2,'colname']=pd.Series([(1,2,3) for x in range(len(mydataframe))])
mydataframe
... | 1 | 2016-06-23T15:38:41Z | [
"python",
"pandas",
"indexing"
] |
Ida Pro 6.9 crash | 37,996,086 | <p>I am writing a plugin for Ida (in python) that utilizes the Etcd remote key value storage system. My problem is that when I attempt to get a lock on the server</p>
<pre><code> lock = etcd.Lock(self.client, 'ida_lock')
Should timeout after 30 seconds. Hopefully that is enough.
lock.acquire(blo... | 0 | 2016-06-23T15:37:08Z | 38,062,857 | <p><strong>There are keys already exist under the directory <code>/_locks/ida_lock</code>.</strong> </p>
<p>To list the files under <code>/_locks/ida_lock</code>:</p>
<pre><code>etcdctl ls /_locks/ida_lock
</code></pre>
<p>To rescue yourself from this, run :</p>
<pre><code>etcdctl rm /_locks/ida_lock --dir --recu... | 1 | 2016-06-27T20:41:02Z | [
"python",
"ida",
"etcd"
] |
QT: Hide QML Debugging warning | 37,996,105 | <p>QML debugging is enabled. Only use this in a safe environment.</p>
<p>I'm actually working on a test software in Python for a QtCreator project which need to use the QML Debugging. The python software is running the built project and test it's features. I would like to actually hide that message without disabling t... | 2 | 2016-06-23T15:38:09Z | 38,002,031 | <p>You can specify</p>
<pre><code>DEFINES += QT_QML_DEBUG_NO_WARNING
</code></pre>
<p>in the .pro file to disable the warning.</p>
| 2 | 2016-06-23T21:18:33Z | [
"python",
"debugging",
"qml",
"qt-creator"
] |
Slicing a wxPython WindowList | 37,996,119 | <p>In a GUI, I use a <code>wx.Treebook</code> filled with many <code>wx.lib.agw.ultimatelistctrl</code>s (ULCs). </p>
<p>I need to traverse the treebook pages (a.k.a. the ULCs).<br>
I use <code>lPages = treebook.GetChildren()</code> to get them. </p>
<p>However, the first children of the treebook is an instance of ... | 0 | 2016-06-23T15:38:40Z | 38,001,912 | <p>The object returned by <code>GetChildren</code> is not an actual Python list, but rather a C++ object that mimics some of the behavior of a list. You can convert it to a real list using <code>list()</code>, like this:</p>
<pre><code>lPages = list(treebook.GetChildren())
</code></pre>
<p>Then you can do your slici... | 1 | 2016-06-23T21:09:01Z | [
"python",
"wxpython",
"slice"
] |
How to save numpy array into computer for later use in python | 37,996,295 | <p>So I am doing some computation and I want to play around with a big array in python. The problem is that if I want to do stuff to the array, then my code will rebuild the array (which takes a lot of time). Ideally I would like to:</p>
<p>-Run my code once, and create the array.
-Save the array into my computer.
-... | 0 | 2016-06-23T15:47:35Z | 37,996,966 | <p>I am a bit confused why you need to use TemporaryFile, because as the documentation of it claims, the file created with TemporaryFile will cease to exist once it is closed, or else when your Python program exits. Also, this file will have no name so I believe that this is your problem and not np.save! </p>
<p>Now ,... | 0 | 2016-06-23T16:20:40Z | [
"python",
"arrays",
"numpy"
] |
Save Game Progress for Multiple Sprites | 37,996,299 | <p>I'm working on a game in Pygame that includes a player class and an enemy class. Each class has multiple variables within it. I'm trying to figure out how I can save the data of these sprites by using Python's built-in <code>pickle</code> module. I thought of doing something similar to this:</p>
<pre><code>data_fil... | 0 | 2016-06-23T15:47:43Z | 37,996,411 | <p><strong>Answer</strong></p>
<p>Since pickle is object serialization, you should just be able to dump your whole object. The <code>b</code> in <code>wb</code> is for binary. This is because you don't have to know how an object is represented in binary, you can just dump it like so:</p>
<pre><code>data_file = open_f... | 1 | 2016-06-23T15:52:54Z | [
"python",
"save",
"pygame",
"pickle"
] |
Add some sheetname to excel using pandas | 37,996,308 | <p>I have data </p>
<pre><code> date mail request
2016-06-17 13:27:49 yans.bouts@yandex.ru GET HTTP/1.1
2016-06-17 13:30:46 yans.bouts@yandex.ru GET HTTP/1.1
2016-06-17 12:05:04 titovtanya@yandex.ru GET HTTP/1.1
2016-06-17 12:05:28 titovtanya@yandex.ru GET HTTP/1.1
2016-0... | 0 | 2016-06-23T15:47:56Z | 37,996,785 | <p>You're using <code>g.to_excel</code> which is supposed to put data in the file.</p>
<p>Instead, create an empty dataframe and use it with <code>to_excel</code>.</p>
<pre><code>edf = pd.DataFrame()
f.groupby('mail').apply(lambda g: edf.to_excel(g.name + '.xlsx', u'sheet1'))
</code></pre>
| 1 | 2016-06-23T16:10:31Z | [
"python",
"excel",
"pandas"
] |
How can I read every field as string in xlwings? | 37,996,435 | <p>I have an exelfile that I want to convert but the default type for numbers is float. How can I change it so xlwings explicitly uses strings and not numbers?</p>
<p>This is how I read the value of a field:
<code>xw.Range(sheet, fieldname ).value</code></p>
<p>The problem is that numbers like <code>40</code> get con... | 0 | 2016-06-23T15:53:53Z | 37,997,146 | <p>With xlwings if no options are set during reading/writing operations single cells are read in as 'floats'. Also, by default cells with numbers are read as 'floats'. I scoured the docs, but don't think you can convert a cell that has numbers to a 'string' via xlwings outright. Fortunately all is not lost...</p>
<p>Y... | 2 | 2016-06-23T16:30:21Z | [
"python",
"converter",
"data-type-conversion",
"xlwings"
] |
Decrypt cipher text encrypted with PyCrypto using cryptopp | 37,996,442 | <p>My server encrypts files using pycrypto with AES in CTR mode. My counter is a simple counter like this:</p>
<pre><code>\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03
</... | 0 | 2016-06-23T15:54:08Z | 38,002,618 | <p>As I read their source codes I can say PyCrypto and Crypto++ Both are perfect libraries for cryptography for Python and C++. The problem was that I was prefixing the encrypted data with some meta information about file and I totally forgot about that, after handling these meta data in client Crypto++ decrypted my fi... | 0 | 2016-06-23T22:00:41Z | [
"python",
"pycrypto",
"crypto++"
] |
MySQL Connector/Python InterfaceError: âFailed parsing EOF packetâ only on specific host | 37,996,464 | <p>To preface this, I realize this question has been asked <a href="http://stackoverflow.com/questions/25538948/mysql-connector-python-interfaceerror-failed-parsing-eof-packet" title="Here it is">before</a>, but no resolution was ever reached. Hoping that two years might make a difference in understanding the issue.</p... | 0 | 2016-06-23T15:54:56Z | 38,230,307 | <p>Never found a solution to this for mysql.connector, but I found a different connector - <a href="https://github.com/PyMySQL/PyMySQL" rel="nofollow">PyMySQL</a>, which worked perfectly. Didn't even have to change the syntax.</p>
| 0 | 2016-07-06T17:38:20Z | [
"python",
"mysql",
"python-2.7",
"mysql-connector",
"mysql-connector-python"
] |
element wise test of numpy array is numeric | 37,996,471 | <p>I have an array as following:</p>
<pre><code>In [1]: x = array(['1.2', '2.3', '1.2.3'])
</code></pre>
<p>I want to test if each element in the array can be converted into numerical value. That is, a function: is_numeric(x) will return a True/False array as following:</p>
<pre><code>In [2]: is_numeric(x)
Out[2]: a... | 3 | 2016-06-23T15:55:18Z | 37,996,526 | <pre><code># method to check whether a string is a float
def is_numeric(s):
try:
float(s)
return True
except ValueError:
return False
# method to return an array of booleans that dictate whether a string can be parsed into a number
def is_numeric_array(arr):
return_array = []
fo... | 0 | 2016-06-23T15:58:07Z | [
"python",
"arrays",
"numpy"
] |
element wise test of numpy array is numeric | 37,996,471 | <p>I have an array as following:</p>
<pre><code>In [1]: x = array(['1.2', '2.3', '1.2.3'])
</code></pre>
<p>I want to test if each element in the array can be converted into numerical value. That is, a function: is_numeric(x) will return a True/False array as following:</p>
<pre><code>In [2]: is_numeric(x)
Out[2]: a... | 3 | 2016-06-23T15:55:18Z | 37,996,908 | <p>This also relies on the try-except method of getting the per-element result, but using <code>fromiter</code> pre-allocs the boolean result array:</p>
<pre><code>def is_numeric(x):
def try_float(xx):
try:
float(xx)
except ValueError:
return False
else:
... | 0 | 2016-06-23T16:17:01Z | [
"python",
"arrays",
"numpy"
] |
element wise test of numpy array is numeric | 37,996,471 | <p>I have an array as following:</p>
<pre><code>In [1]: x = array(['1.2', '2.3', '1.2.3'])
</code></pre>
<p>I want to test if each element in the array can be converted into numerical value. That is, a function: is_numeric(x) will return a True/False array as following:</p>
<pre><code>In [2]: is_numeric(x)
Out[2]: a... | 3 | 2016-06-23T15:55:18Z | 37,997,673 | <pre><code>import numpy as np
def is_float(val):
try:
float(val)
except ValueError:
return False
else:
return True
a = np.array(['1.2', '2.3', '1.2.3'])
is_numeric_1 = lambda x: map(is_float, x) # return python list
is_numeric_2 = lambda x: np.... | 1 | 2016-06-23T16:59:51Z | [
"python",
"arrays",
"numpy"
] |
element wise test of numpy array is numeric | 37,996,471 | <p>I have an array as following:</p>
<pre><code>In [1]: x = array(['1.2', '2.3', '1.2.3'])
</code></pre>
<p>I want to test if each element in the array can be converted into numerical value. That is, a function: is_numeric(x) will return a True/False array as following:</p>
<pre><code>In [2]: is_numeric(x)
Out[2]: a... | 3 | 2016-06-23T15:55:18Z | 38,001,113 | <pre><code>In [23]: x = np.array(['1.2', '2.3', '1.2.3', '1.2', 'foo'])
</code></pre>
<p>Trying to convert the whole array to <code>float</code>, results in an error if one or more strings can't be converted:</p>
<pre><code>In [24]: x.astype(float)
---------------------------------------------------------------------... | 1 | 2016-06-23T20:21:43Z | [
"python",
"arrays",
"numpy"
] |
element wise test of numpy array is numeric | 37,996,471 | <p>I have an array as following:</p>
<pre><code>In [1]: x = array(['1.2', '2.3', '1.2.3'])
</code></pre>
<p>I want to test if each element in the array can be converted into numerical value. That is, a function: is_numeric(x) will return a True/False array as following:</p>
<pre><code>In [2]: is_numeric(x)
Out[2]: a... | 3 | 2016-06-23T15:55:18Z | 38,004,749 | <p>I find the following works well for my purpose.</p>
<p>First, save the isNumeric function from <a href="https://rosettacode.org/wiki/Determine_if_a_string_is_numeric#C" rel="nofollow">https://rosettacode.org/wiki/Determine_if_a_string_is_numeric#C</a> in a file called ctest.h, then create a .pyx file as follows:</p... | 0 | 2016-06-24T02:29:52Z | [
"python",
"arrays",
"numpy"
] |
Creating objects in python within a formatted text file | 37,996,520 | <p>I have a text file that is formatted as such:</p>
<pre><code>T timestamp
U username
W text
</code></pre>
<p>Is there a way to create an object within the text file with the T U and W being attributes? I have only done scripting in Python and nothing object orientated so I'm a bit lost. </p>
<p>I need to ... | 0 | 2016-06-23T15:57:49Z | 37,996,609 | <p>Assuming the lines in your doc are space separated you would do something like this:</p>
<pre><code>class YourObj(object):
def __init__(self, t, u, w):
self.t = t
self.u = u
self.w = w
all_objs = []
with open("somefile.txt") as f:
lines = f.readlines()
for i in range(len(lines)... | 0 | 2016-06-23T16:02:05Z | [
"python"
] |
Creating objects in python within a formatted text file | 37,996,520 | <p>I have a text file that is formatted as such:</p>
<pre><code>T timestamp
U username
W text
</code></pre>
<p>Is there a way to create an object within the text file with the T U and W being attributes? I have only done scripting in Python and nothing object orientated so I'm a bit lost. </p>
<p>I need to ... | 0 | 2016-06-23T15:57:49Z | 37,996,843 | <p>I Like Luke's answer, but it looks to me like you'd need something more like this for your specific format:</p>
<pre><code>class YourObj(object):
def __init__(self, dictionary): #init class with dictionary storing data
self.T = dictionary['T']
self.U = dictionary['U']
self.W = dictionary... | 0 | 2016-06-23T16:13:50Z | [
"python"
] |
Creating objects in python within a formatted text file | 37,996,520 | <p>I have a text file that is formatted as such:</p>
<pre><code>T timestamp
U username
W text
</code></pre>
<p>Is there a way to create an object within the text file with the T U and W being attributes? I have only done scripting in Python and nothing object orientated so I'm a bit lost. </p>
<p>I need to ... | 0 | 2016-06-23T15:57:49Z | 37,998,588 | <p>You only need one way of doing it but here are two variations and a single file reading function that doesn't read the entire file at once (it stores 3-4 lines at most):</p>
<pre><code># **kwarg is a dictionary. It can hold any number of keyword arguments.
class obj1:
def __init__(self, **kwarg):
self.a... | 0 | 2016-06-23T17:51:24Z | [
"python"
] |
Restore string's original casing | 37,996,561 | <p>If I converted a string into lowercase, how would I convert it back to the original string the user entered? I have been searching for a particular python function that will convert the string back to the original string. I have used <code>.swapcase()</code> but unfortunately it didn't work. Please bear in mind that... | -6 | 2016-06-23T15:59:34Z | 37,996,600 | <p>You can't. "AbC" and "aBc" both turn into "abc" when lowercased. If an <code>unlowercase</code> method existed, how could it distinguish between those two cases? Should it return "AbC" or "aBc"? Keep in mind that strings have no "memory" of the letters they used to contain.</p>
| 0 | 2016-06-23T16:01:48Z | [
"python",
"string"
] |
Restore string's original casing | 37,996,561 | <p>If I converted a string into lowercase, how would I convert it back to the original string the user entered? I have been searching for a particular python function that will convert the string back to the original string. I have used <code>.swapcase()</code> but unfortunately it didn't work. Please bear in mind that... | -6 | 2016-06-23T15:59:34Z | 37,996,703 | <p>There is no function for this unfortunately. Rather than question why you need to do this, I would recommend keeping a separate list that keeps track of which characters in the string have been modified. Two approaches to this would keep:</p>
<p>1.) Keep a list of the indexes that in the original string were upp... | 0 | 2016-06-23T16:06:55Z | [
"python",
"string"
] |
Restore string's original casing | 37,996,561 | <p>If I converted a string into lowercase, how would I convert it back to the original string the user entered? I have been searching for a particular python function that will convert the string back to the original string. I have used <code>.swapcase()</code> but unfortunately it didn't work. Please bear in mind that... | -6 | 2016-06-23T15:59:34Z | 37,996,895 | <p>You can't convert it back. What you CAN do is keep the original sting and just make a new variable for the lowercase one:</p>
<pre><code>original = 'AbC'
lowered = original.lower()
</code></pre>
<p>What you could also do is store both values in a dict. For instance if the string is a name like 'John Smith' and you... | 0 | 2016-06-23T16:16:05Z | [
"python",
"string"
] |
Tornado secure websocket timeout | 37,996,591 | <p>My server got 2 Ip's (<strong>ip1 & ip2</strong>) i recently added ip2. When i try to open my tornado websocketserver on ip1 (where <code>apache2</code> is running) everything is fine, i specify a port e.g. 22000 and can connect to my <code>socket</code> via <code>wss://domain.tld:22000/sub</code></p>
<p>Howeve... | 0 | 2016-06-23T16:01:02Z | 38,142,113 | <p>According to <a href="http://www.tornadoweb.org/en/stable/httpserver.html" rel="nofollow">the documentation</a>, after the call to <code>bind</code>, you should call <code>start</code> on the server. So</p>
<pre><code>http_server.bind(443, address = "ip2")
print("Listening to ip2:443")
http_server.start()
ioloop.IO... | 2 | 2016-07-01T09:42:05Z | [
"python",
"sockets",
"ubuntu",
"tornado",
"iptables"
] |
Django management cannot import method from app | 37,996,623 | <p>I have a django app that's file tree looks like this:</p>
<ul>
<li>app1
<ul>
<li>____init____.py</li>
<li>functions.py</li>
<li>management (dir)
<ul>
<li>____init____.py</li>
<li>excel.py</li>
<li>commands (dir)
<ul>
<li>____init____.py</li>
<li>importfromexcel.py</li>
</ul></li>
</ul></li>
</ul></li>
</ul>
<p>... | 1 | 2016-06-23T16:02:44Z | 38,038,616 | <blockquote>
<p>I'd guess it's a circular import error but need to see more code to make sure - Take a gander at <a href="http://stackoverflow.com/a/10027101/784648">stackoverflow.com/a/10027101/784648</a> - @ARJMP</p>
</blockquote>
| 0 | 2016-06-26T12:44:43Z | [
"python",
"django",
"python-import",
"importerror"
] |
Extremely low p-values from non-parametric tests | 37,996,628 | <p>I'm using Python's non-parametric tests to check whether two samples are consistent with being drawn from the same underlying parent populations: <code>scipy.stats.ks_2samp</code> (2-sample Kolmogorov-Smirnov), <code>scipy.stats.anderson_ksamp</code> (Anderson-Darling for k samples), and <code>scipy.stats.ranksums</... | 1 | 2016-06-23T16:02:59Z | 37,996,674 | <p>You do not need to worry about something going wrong with the scipy functions. P values that low just mean that it's really unlikely that your samples have the same parent populations.</p>
<p>That said, if you were not expecting the distributions to be (that) different, now is a good time to make sure you're measu... | 0 | 2016-06-23T16:05:42Z | [
"python",
"scipy",
"statistics",
"distribution",
"kolmogorov-smirnov"
] |
Extremely low p-values from non-parametric tests | 37,996,628 | <p>I'm using Python's non-parametric tests to check whether two samples are consistent with being drawn from the same underlying parent populations: <code>scipy.stats.ks_2samp</code> (2-sample Kolmogorov-Smirnov), <code>scipy.stats.anderson_ksamp</code> (Anderson-Darling for k samples), and <code>scipy.stats.ranksums</... | 1 | 2016-06-23T16:02:59Z | 38,006,265 | <p>Well, you've bumped into a well-known feature of significance tests, which is that the p-value typically goes to zero as the sample size increases without bound. If the null hypothesis is false (which can often be established a priori), then you can get as small a p-value as you wish, just by increasing the sample s... | 0 | 2016-06-24T05:38:10Z | [
"python",
"scipy",
"statistics",
"distribution",
"kolmogorov-smirnov"
] |
Extremely low p-values from non-parametric tests | 37,996,628 | <p>I'm using Python's non-parametric tests to check whether two samples are consistent with being drawn from the same underlying parent populations: <code>scipy.stats.ks_2samp</code> (2-sample Kolmogorov-Smirnov), <code>scipy.stats.anderson_ksamp</code> (Anderson-Darling for k samples), and <code>scipy.stats.ranksums</... | 1 | 2016-06-23T16:02:59Z | 38,116,285 | <p>A common mistake (at least in life sciences) that can lead to incorrect (too small) p-values is that the <strong>independence assumption</strong> of the test -- tests typically assume that the observations (data points) in the sample are independent -- is violated. GraphPad's <a href="http://www.graphpad.com/guides... | 1 | 2016-06-30T07:15:22Z | [
"python",
"scipy",
"statistics",
"distribution",
"kolmogorov-smirnov"
] |
Python compare a datetime with a str with the same format | 37,996,682 | <p>I got this two values to compare</p>
<p>The first one came from a API with str format and the second one from function <code>datetime.datetime.now()</code></p>
<pre><code>2016-06-23 11:05:42.0
<class 'str'>
2016-06-23 18:00:03.063287
<class 'datetime.datetime'>
</code></pre>
<p>I'm having problems to... | 0 | 2016-06-23T16:06:07Z | 37,996,794 | <p>You would use `strptime and parse the string to a datetime object:</p>
<pre><code>In [27]: s = "2016-06-23 11:05:42.0"
In [28]: datetime.datetime.strptime(s,'%Y-%m-%d %H:%M:%S.%f')
Out[28]: datetime.datetime(2016, 6, 23, 11, 5, 42)
</code></pre>
<p>but you don't actually need to use strptime as the strings could ... | 1 | 2016-06-23T16:11:04Z | [
"python",
"datetime"
] |
Export Postgresql Table to excel with header | 37,996,764 | <p>i whrote a python script to export table from postgresql to Excel and it's works perfectly,but i get a file without header (only data)
here is my code:</p>
<pre><code>#!/usr/bin/python
import os
import psycopg2
"""Fichier en sortie"""
output_file_1=r"path\myfile.xls"
try:
conn = psycopg2.connect(database="", ... | 3 | 2016-06-23T16:09:38Z | 37,996,941 | <p>You can use <code>cur.description</code> to get the column names. It returns a tuple of tuples with the column name as the first element of each contained tuple.</p>
<pre><code>for colidx,heading in enumerate(cur.description):
worksheet.write(0,colidx,heading[0]) # first element of each tuple
# Write rows
for ... | 1 | 2016-06-23T16:19:12Z | [
"python",
"postgresql"
] |
How does a Python module that contains class of same name work when imported? | 37,996,793 | <p>I have recently been using web.py for some simple web applications in Python. I thought I understood how import statements, packages and modules worked but now I am a little confused.</p>
<p>According to web.py's API it says that the class <code>application</code> is located inside the module <code>web.application<... | 2 | 2016-06-23T16:11:02Z | 37,996,884 | <p>The attributes of <code>application.py</code> module have been imported into the <code>__init__.py</code> of the <code>web</code> package (via <code>__all__</code>).</p>
<p>In the <code>__init__.py</code> of the <code>web</code> package, you have:</p>
<pre><code>from application import * # referring to application... | 2 | 2016-06-23T16:15:38Z | [
"python",
"python-2.7",
"web.py"
] |
how do I prevent memory error for the following code | 37,996,800 | <p>This my python code it's working fine for small values as in primary testcases, but producing <code>Memory Error</code> due to large integer values. How can remove the Memory Error or how do I perform operations with large integers in python please?</p>
<pre><code>#taking input testcases T
n=int(raw_input())
#taki... | 0 | 2016-06-23T16:11:26Z | 37,996,934 | <p>It's likely this line</p>
<pre><code>for i in range(0,_iter)
</code></pre>
<p>This will create a list of length <code>_iter</code>, which will be massive for large values. You actually don't need to store the whole list; you only need to increment a single integer. Instead, use <code>xrange</code>, which produce... | 0 | 2016-06-23T16:18:54Z | [
"python",
"python-2.7"
] |
how do I prevent memory error for the following code | 37,996,800 | <p>This my python code it's working fine for small values as in primary testcases, but producing <code>Memory Error</code> due to large integer values. How can remove the Memory Error or how do I perform operations with large integers in python please?</p>
<pre><code>#taking input testcases T
n=int(raw_input())
#taki... | 0 | 2016-06-23T16:11:26Z | 37,996,936 | <p>Most likely, you run out of memory when a big number is passed to <code>range</code>, because it has to build the entire list in memory. Replace <code>range</code> calls with <code>xrange</code>.</p>
<pre><code>def main(_iter):
count=0
for i in xrange(0,_iter):
k = i + reverse(i)
if i%10... | 2 | 2016-06-23T16:19:01Z | [
"python",
"python-2.7"
] |
How to access elements of numpy ndarray? | 37,996,883 | <p>I'm using scipy's <code>loadmat</code> function to load a matlab data file into python.</p>
<pre><code>from scipy.io import loadmat
data = loadmat('data.mat')
fields = data['field']
</code></pre>
<p>The type of <code>fields</code> is <code>numpy.ndarray</code>:</p>
<pre><code>print 'fields type={}'.format(ty... | 4 | 2016-06-23T16:15:38Z | 37,997,214 | <p>Without looking at your errors in detail I can point out some pitfalls.</p>
<p>The .mat will contain MATLAB matrices (always 2d or higher), cells and structures.</p>
<p><code>loadmat</code> renders those in various ways. There are dictionaries that you have to index by name. There are object arrays (dtype=object... | 4 | 2016-06-23T16:34:04Z | [
"python",
"arrays",
"matlab",
"numpy",
"scipy"
] |
Can't seem to handle socket.timout exception | 37,997,025 | <p>I've written a "little" podcast downloading program in python called <a href="https://github.com/bamonroe/ppod" rel="nofollow" title="ppod">ppod</a> that I use to download the latest episodes of podcasts I follow. There are really 2 main steps that involve an internet connection: downloading the RSS XML page for the... | 0 | 2016-06-23T16:24:24Z | 37,997,129 | <p>Look at your stack trace- none of the code you posted is in the stack trace. The problem in your code is not in this snippet.</p>
| 0 | 2016-06-23T16:29:29Z | [
"python",
"xml",
"urllib"
] |
Python 64bit version Intel processor | 37,997,027 | <p>I´m new in python.
I have Intel processor 64bit (Windows 10)...
On Python internet page in download section (Version 3.5.1) is Python 32bit version. It is OK? Or I can install Windows x86-64 web-based installer?? It is not just for AMD processors? </p>
| 0 | 2016-06-23T16:24:37Z | 37,997,159 | <p>These threads might answer your question:</p>
<blockquote>
<p><a href="http://stackoverflow.com/questions/3117626/should-i-use-python-32bit-or-python-64bit#3117794">Should I use Python 32bit or Python 64bit</a></p>
<p><a href="http://stackoverflow.com/questions/7554103/which-python-to-install-if-i-have-an-in... | 0 | 2016-06-23T16:30:51Z | [
"python",
"version"
] |
How to write a dictionary of lists to a csv file? | 37,997,085 | <p>I have this dictionary of lists that I want to write it in a CSV file:</p>
<pre><code>file2_Dict = {'id': ' ', 'gender': ['M', 'M'], 'name': ['Smith', 'John'], 'city': ['Omaha','Lincoln']}
</code></pre>
<p>The problem is that not all the keys of the dictionary have a list of items as a value. In this case the ke... | 0 | 2016-06-23T16:27:37Z | 37,997,198 | <p>You can pre-process the dictionary and replace "empty" values with empty lists. Then use <a href="https://docs.python.org/2.7/library/itertools.html#itertools.izip_longest" rel="nofollow"><code>itertools.izip_longest()</code></a> instead of <code>zip()</code>:</p>
<pre><code>import csv
from itertools import izip_lo... | 2 | 2016-06-23T16:33:27Z | [
"python",
"list",
"csv",
"dictionary"
] |
Expression-combination of "A or B or both" | 37,997,114 | <p>Here is what I currently have:</p>
<pre><code>_filter_date_range = pp.Group(_keyword_date + pp.Group(
pp.Group(_function_before + _argument_string) & pp.Group(_function_after + _argument_string)
))
</code></pre>
<p>Since I use <code>Each</code>(<code>&</code>), both expressions are required. But I want... | 1 | 2016-06-23T16:28:56Z | 37,997,750 | <p>Here are three possible solutions for you:</p>
<pre><code>from pyparsing import Literal, OneOrMore, Optional
A = Literal("A")
B = Literal("B")
language = OneOrMore( A | B )
assert language.matches("A")
assert language.matches("B")
assert language.matches("A B")
assert language.matches("B A")
assert language.matc... | 2 | 2016-06-23T17:03:58Z | [
"python",
"pyparsing"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.