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 |
|---|---|---|---|---|---|---|---|---|---|
pass data result from python to Java variable by processbuilder | 39,908,283 | <p>I used process builder to run a python script from java. and i can sent the data from Java to python variable ( import sys to get data from Java) . and print out the python result in java.
for example: </p>
<pre><code>public static void main(String a[]){
try{
int number1 = 100;
int number2 = 200;
String searchTerm... | 0 | 2016-10-07T02:09:42Z | 39,955,546 | <p>u can save the python result in JSON format. and use java to read parser the json file to get the content so as to create the variable.</p>
| 1 | 2016-10-10T09:46:25Z | [
"java",
"python",
"json",
"processbuilder",
"sys"
] |
Pass variable to an exception? | 39,908,291 | <p>I am trying to learn Python and I want to know if it is possible to pass a variable to an <code>Exception</code>? This is the code I have:</p>
<pre><code>try:
staffId = int(row['staffId'])
openingSalary = int(row['initialSalary'])
monthsWorked = float(row['monthsWorked'])
except CutomException:
pass... | 0 | 2016-10-07T02:10:39Z | 39,908,321 | <p>The caller of the exception, e.g. the one that <code>raise</code> exception will have to pass an argument to the constructor.</p>
<pre><code>class CustomException(ValueError): # raised if data conversion fails
def __init__(self, message):
self.message = message;
print("There was a problem conver... | 1 | 2016-10-07T02:13:55Z | [
"python",
"exception"
] |
Pass variable to an exception? | 39,908,291 | <p>I am trying to learn Python and I want to know if it is possible to pass a variable to an <code>Exception</code>? This is the code I have:</p>
<pre><code>try:
staffId = int(row['staffId'])
openingSalary = int(row['initialSalary'])
monthsWorked = float(row['monthsWorked'])
except CutomException:
pass... | 0 | 2016-10-07T02:10:39Z | 39,908,528 | <p>The custom exception will need to be <code>raise</code>'d conditionally by the <code>try</code> block to include the <code>staffId</code> variable. As an example, when the <code>staffId</code> is a <code>str</code> and not an <code>int</code>.</p>
<pre><code>try:
# conditionalize a scenario where you'd want to ... | 1 | 2016-10-07T02:38:22Z | [
"python",
"exception"
] |
Slice all strings in a list? | 39,908,314 | <p>Is there a Pythonic way to slice all strings in a list?</p>
<p>Suppose I have a list of strings:</p>
<pre><code>list = ['foo', 'bar', 'baz']
</code></pre>
<p>And I want just the last 2 characters from each string:</p>
<pre><code>list2 = ['oo', 'ar', 'az']
</code></pre>
<p>How can I get that? </p>
<p>I know I c... | 2 | 2016-10-07T02:13:03Z | 39,908,453 | <p>You mentioned that you can do <code>list[i][-2:]</code> for transforming the list per your specification, but what you are actually looking for is:</p>
<pre><code>[word[1:] for word in lst]
</code></pre>
<p>Furthermore, for the code sample you provided where you are looking to seem to slice 20 characters from the ... | 5 | 2016-10-07T02:29:48Z | [
"python",
"string",
"list",
"slice"
] |
Mock standard input - multi line in python 3 | 39,908,390 | <p>I am new to python and have been using python 3 for my learning. I am using python's unit test framework to test my code.</p>
<p>Problem :-</p>
<p>The function that I need to unit test takes inputs in the following manner:-</p>
<pre><code>def compare():
a, b, c = input().strip().split(' ')
d, e, f = input()... | 0 | 2016-10-07T02:22:10Z | 39,908,499 | <p>You can't patch it twice like that. You'll have to patch it once, with an object that returns different values on subsequent calls. Here's an example:</p>
<pre><code>fake_input = iter(['1 2 3', '4 5 6']).__next__
@patch("builtins.input", fake_input)
def test_compare(self):
...
</code></pre>
| 2 | 2016-10-07T02:34:12Z | [
"python",
"unit-testing",
"python-3.x",
"lambda",
"patch"
] |
Mock standard input - multi line in python 3 | 39,908,390 | <p>I am new to python and have been using python 3 for my learning. I am using python's unit test framework to test my code.</p>
<p>Problem :-</p>
<p>The function that I need to unit test takes inputs in the following manner:-</p>
<pre><code>def compare():
a, b, c = input().strip().split(' ')
d, e, f = input()... | 0 | 2016-10-07T02:22:10Z | 39,908,502 | <p>The patch decorator will ensure the patched function always return that value, and if subsequent calls must be different, your mock object must have a way to simulate that. This ends up being much more complicated.</p>
<p>What you can do however is go one step lower and patch the underlying layer, which is the sta... | 2 | 2016-10-07T02:34:48Z | [
"python",
"unit-testing",
"python-3.x",
"lambda",
"patch"
] |
Mock standard input - multi line in python 3 | 39,908,390 | <p>I am new to python and have been using python 3 for my learning. I am using python's unit test framework to test my code.</p>
<p>Problem :-</p>
<p>The function that I need to unit test takes inputs in the following manner:-</p>
<pre><code>def compare():
a, b, c = input().strip().split(' ')
d, e, f = input()... | 0 | 2016-10-07T02:22:10Z | 39,908,520 | <p>You can't patch out your function twice like that. When you are looking to mock the same function, and have it return different values each time it is called, you should use <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.side_effect" rel="nofollow">side_effect</a>.</p>
<p><code>sid... | 2 | 2016-10-07T02:37:04Z | [
"python",
"unit-testing",
"python-3.x",
"lambda",
"patch"
] |
Pythonanywhere - ImportError: No module named 'myapp.settings' | 39,908,467 | <p>Using Python 3.5 and Django 1.9, I was trying to deploy my app to pythonanywhere, but I keep getting this error</p>
<pre><code>2016-10-07 01:44:28,879 :Error running WSGI application
Traceback (most recent call last):
File "/bin/user_wsgi_wrapper.py", line 154, in __call__
app_iterator = self.app(environ, sta... | 2 | 2016-10-07T02:31:01Z | 39,917,257 | <p>The path in your wsgi file is wrong. It's supposed to be the path to your app, so:</p>
<pre><code>path = '/home/nidalmer/trailersapp'
</code></pre>
<p>Also, I think you're looking at an old traceback or an old copy of the wsgi file. Make sure they're both up-to-date.</p>
| 3 | 2016-10-07T12:24:41Z | [
"python",
"django",
"pythonanywhere"
] |
numpy version error when importing tensorflow | 39,908,504 | <p>I have executed <code>pip install</code> for tensorflow.</p>
<p>Under the python command line environment, when I tried </p>
<pre><code>import tensorflow as tf
</code></pre>
<p>I met the following errors:</p>
<pre><code>RuntimeError: module compiled against API version 0xa but this version of numpy is 0x9
Traceb... | 0 | 2016-10-07T02:35:08Z | 39,913,467 | <p>From the error, it looks like you're running python 2.7 from <code>usr/local/bin</code>. There is a mismatch problem between your <code>numpy</code> version and <code>tensorflow</code> installation. I'd recommend you to install anaconda since it will make sure that correct version of <code>tensorflow</code> that is ... | 0 | 2016-10-07T09:04:34Z | [
"python",
"python-2.7",
"numpy",
"runtime-error",
"tensorflow"
] |
Weeks difference between two dates in python | 39,908,548 | <p>How do I get the differences between two valid dates in weeks. I have googled many, but none are the one that I have been looking for</p>
<p>Say I have two dates:</p>
<blockquote>
<p><strong>02-Dec-2016</strong> and <strong>10-Jan-2017</strong>.</p>
</blockquote>
<p>I want it to provide me with output like foll... | -2 | 2016-10-07T02:40:54Z | 39,912,043 | <p>This is what you actualy want: </p>
<pre><code>import datetime
def diff(d1, d2):
result = []
delta = datetime.timedelta(days=0)
day = datetime.timedelta(days=1)
while d1.weekday() != 0:
d1 += day
delta += day
result.append((d1 - delta, d1 - day))
weeks, days = divmod((... | 1 | 2016-10-07T07:44:33Z | [
"python"
] |
flask-login:Exception: No user_loader has been installed for this LoginManager. Add one with the 'LoginManager.user_loader' decorator | 39,908,552 | <p>I want to use flask_login to manager user login but some error like this:</p>
<p>Exception: No user_loader has been installed for this LoginManager. Add one with the 'LoginManager.user_loader' decorator.</p>
<p>this is my models.py (PS:I use Flask peewee to build my models)</p>
<pre><code>from peewee import *
fro... | 0 | 2016-10-07T02:42:07Z | 39,908,998 | <p>According to <a href="https://flask-login.readthedocs.io/en/latest/#configuring-your-application" rel="nofollow">https://flask-login.readthedocs.io/en/latest/#configuring-your-application</a></p>
<blockquote>
<p>Once the actual application object has been created, you can configure
it for login with:</p>
<... | 0 | 2016-10-07T03:41:28Z | [
"python",
"flask",
"flask-login"
] |
How to define an Integral as an objective function in pyomo? | 39,908,555 | <p>I want to be able to define an integral in <code>pyomo</code> as part of an objective function. </p>
<p>I cannot figure out what kind of expression is needed for the integral.<br>
Here's my best guess:</p>
<pre><code>model = ConcreteModel()
model.t = ContinuousSet(bounds = (0,1))
model.y = Var(model.t)
model.dydt ... | 0 | 2016-10-07T02:42:32Z | 39,908,672 | <p>This looks like a bug. You should open up a ticket here: <a href="https://github.com/Pyomo/pyomo/issues" rel="nofollow">https://github.com/Pyomo/pyomo/issues</a></p>
| 1 | 2016-10-07T02:57:39Z | [
"python",
"pyomo"
] |
How to define an Integral as an objective function in pyomo? | 39,908,555 | <p>I want to be able to define an integral in <code>pyomo</code> as part of an objective function. </p>
<p>I cannot figure out what kind of expression is needed for the integral.<br>
Here's my best guess:</p>
<pre><code>model = ConcreteModel()
model.t = ContinuousSet(bounds = (0,1))
model.y = Var(model.t)
model.dydt ... | 0 | 2016-10-07T02:42:32Z | 39,960,159 | <p>Gabe is right, this is indeed a bug in the Integral class and it has been fixed on the github repository. One other error in your example model is the specification of the Objective component. You should be using the 'rule' keyword instead of 'expr'</p>
<pre><code>def myobjective(model):
return model.n
model.o... | 2 | 2016-10-10T14:04:49Z | [
"python",
"pyomo"
] |
Python dill: Pickle namedtuple doesnt seem to work | 39,908,774 | <p>I have namedtuple inside a class. When pickling using dill, it complains the classic issue of not being able to find the namedtuple object at top module. </p>
<pre><code>import dill as pickle
class NNRTMParse(object):
def __init__(self,logfile)):
.
.
.
.
self.TM = n... | 0 | 2016-10-07T03:11:59Z | 39,942,024 | <p>The issue is the <code>self.TM</code> <code>namedtuple</code>. If you don't use the <code>namedtuple</code> as a class attribute, then your class should pickle.</p>
<pre><code># file: xxx.py
from collections import namedtuple
class NNRTMParse(object):
def __init__(self):
TM = namedtuple("TM", 'a')
CFH =... | 0 | 2016-10-09T09:27:35Z | [
"python",
"pickle",
"namedtuple",
"dill"
] |
This python code is not solving equations | 39,908,815 | <p>I have a chat bot for an Instant messenger and I am trying to make a math solver for it but it can't send the solution of equation to the Instant messenger, it sends equation instead.</p>
<p>If someone from Instant messenger sends "solve: 2+2", this program should send them "4" not "2+2".</p>
<p><strong>Main probl... | 0 | 2016-10-07T03:17:29Z | 39,909,052 | <p>What you need to do this evaluating math expressions in string form.</p>
<p>However, user inputs are dangerous if you are just <code>eval</code> things whatever they give you. <a href="http://stackoverflow.com/questions/661084/security-of-pythons-eval-on-untrusted-strings">Security of Python's eval() on untrust... | 0 | 2016-10-07T03:48:25Z | [
"python",
"bots",
"irc",
"instant-messaging",
"payload"
] |
This python code is not solving equations | 39,908,815 | <p>I have a chat bot for an Instant messenger and I am trying to make a math solver for it but it can't send the solution of equation to the Instant messenger, it sends equation instead.</p>
<p>If someone from Instant messenger sends "solve: 2+2", this program should send them "4" not "2+2".</p>
<p><strong>Main probl... | 0 | 2016-10-07T03:17:29Z | 39,909,195 | <p>Your test code</p>
<pre><code>str(2 + 2 -3 + 8 * 7)
</code></pre>
<p>is distinct from your production code</p>
<pre><code>str(parser.getPayload()[7:])
</code></pre>
<p>which gets expanded into</p>
<pre><code>str("2 + 2 -3 + 8 * 7")
</code></pre>
<p>assuming you pass in the same equotation. Good thing is you ha... | 0 | 2016-10-07T04:04:53Z | [
"python",
"bots",
"irc",
"instant-messaging",
"payload"
] |
Reading user selection from Django 1.5 template without using Models | 39,908,826 | <p>Im using <strong>Python27</strong> with <strong>Django 1.5</strong>.</p>
<p>i have been scowering the internet for hours without success. Is there a way to capture what the user has selected from a dropdown listbox in a template without using Models? Im looking for a direct way to read some sort of var into code in... | 0 | 2016-10-07T03:18:14Z | 39,908,885 | <p>You can read raw form data by using <code>HttpRequest.POST</code> API</p>
<p><a href="https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpRequest.POST" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpRequest.POST</a></p>
<p>It's a dictionary-like... | 0 | 2016-10-07T03:25:56Z | [
"python",
"html",
"django",
"templates",
"html-select"
] |
Reading user selection from Django 1.5 template without using Models | 39,908,826 | <p>Im using <strong>Python27</strong> with <strong>Django 1.5</strong>.</p>
<p>i have been scowering the internet for hours without success. Is there a way to capture what the user has selected from a dropdown listbox in a template without using Models? Im looking for a direct way to read some sort of var into code in... | 0 | 2016-10-07T03:18:14Z | 39,908,897 | <p>Yes, you don't need models for this at all, what you need is a simple <a href="https://docs.djangoproject.com/en/1.10/topics/forms/" rel="nofollow">django form</a>. </p>
<pre><code>CHOICES = ( (1,"10"), (2,"20"), ...)
class MyForm(forms.form):
...
num_select = forms.ChoiceField(choices = CHOICES)
...
<... | 1 | 2016-10-07T03:26:44Z | [
"python",
"html",
"django",
"templates",
"html-select"
] |
pandas update dataframe by another dataframe with group by columns | 39,908,914 | <p>I have two dataframe like this </p>
<pre><code>df1 = pd.DataFrame({'A': ['1', '2', '3', '4','5'],
'B': ['1', '1', '1', '1','1'],
'C': ['A', 'A1', 'A2', 'A3','A4'],
'D': ['B0', 'B1', 'B2', 'B3','B4'],
'E': ['A', 'A', 'S', 'S','S']})
df2 = pd.Dat... | 2 | 2016-10-07T03:30:40Z | 39,909,146 | <p>I think this will be more space efficient:</p>
<h2>Edit To Add</h2>
<p>This may be more efficient:</p>
<pre><code>In [22]: df1,df2 = df1.align(df2,join='left',axis=0)
In [23]: df1
Out[23]:
A B C D E
0 1 1 A B0 A
1 2 1 A1 B1 A
2 3 1 A2 B2 S
3 4 1 A3 B3 S
4 5 1 A4 B4 S
In [24]:... | 1 | 2016-10-07T03:58:45Z | [
"python",
"pandas"
] |
How to get elements of webpage that load after initial webpage? | 39,909,063 | <p>I'm trying to download stock option data from Yahoo Finance (<a href="https://finance.yahoo.com/quote/GOOG/options?p=GOOG" rel="nofollow">here's Google as an example</a>) with <code>requests.get</code>, which doesn't seem to be downloading everything. I'm trying to get the dropdown of dates with an XPath but even <c... | 0 | 2016-10-07T03:50:00Z | 39,909,172 | <p>If you open the dev console and refresh the page again (caches might need to be purged), you can see some requests with type <code>xhr</code>.</p>
<p>They are usually initiated by JavaScript programs and will load some data besides those provided by HTML body.</p>
<p>That's what you can look into.</p>
| 0 | 2016-10-07T04:02:45Z | [
"python",
"html",
"python-3.x",
"xpath",
"web-scraping"
] |
How to Crawl Website Content by Python | 39,909,065 | <p>I'm studying Python. I want to get content on one URL . Get all text in one title on the website and save it to file .txt. Can you show me some code example? </p>
| -1 | 2016-10-07T03:50:17Z | 39,909,741 | <p>By <code>Get all text in one title on the website</code> I assume you mean get the title of the page?</p>
<p>Firstly, you'll need BeautifulSoup</p>
<p>If you have <code>pip</code>, use</p>
<p><code>pip install beautifulsoup4</code></p>
<p>Now onto the code:</p>
<pre><code>from bs4 import BeautifulSoup
from requ... | 0 | 2016-10-07T05:02:29Z | [
"python",
"python-3.x",
"web",
"website",
"web-crawler"
] |
Regex: How to extract a particular pattern individually from a text? | 39,909,109 | <p>I am trying to extract a pattern using regular expression from a text shown bellow.</p>
<pre><code>to_timestamp('02-04-09 00:00:00.000000000','RR-MM-DD HH24:MI:SS.FF'),'REP00061 ',to_timestamp('08-05-30 07:27:36.000000000','RR-MM-DD HH24:MI:SS.FF'),
</code></pre>
<p>How can I write a regex in Python to extract ... | 0 | 2016-10-07T03:55:14Z | 39,909,229 | <p>basically using pythex.org you can create your regex with ease.</p>
<p>for example :</p>
<pre><code>m = re.findall(r'(to_timestamp\(\'.*?\',\'.*? .*?\'\))',str)
</code></pre>
<p>the findall in the re module will create a list of all the matches.</p>
| 1 | 2016-10-07T04:08:25Z | [
"python",
"regex"
] |
How can I only parse/split this list with multiple colons in each element? Create dictionary | 39,909,214 | <p>I have the following Python list:</p>
<pre><code>list1 = ['EW:G:B<<LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A<F<AF', 'GR:A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX:F:-111', 'DS:f:115.5', 'MW:AA:0', 'MA:A:0XT:i:0', 'EY:EE:KJERWEWERKJWE']
</code></pre>
<p>I would like to take the entries of this list and... | 4 | 2016-10-07T04:07:02Z | 39,909,245 | <p>You can specify a maximum number of times to split with the second argument to <a href="https://docs.python.org/3.5/library/stdtypes.html#str.split" rel="nofollow"><code>split</code></a>.</p>
<pre><code>list1 = ['EW:G:B<<LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A<F<AF', 'GR:A:OUO-1-XXX-EGD:forthyFive:1:HM... | 5 | 2016-10-07T04:10:02Z | [
"python",
"dictionary",
"split"
] |
How can I only parse/split this list with multiple colons in each element? Create dictionary | 39,909,214 | <p>I have the following Python list:</p>
<pre><code>list1 = ['EW:G:B<<LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A<F<AF', 'GR:A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX:F:-111', 'DS:f:115.5', 'MW:AA:0', 'MA:A:0XT:i:0', 'EY:EE:KJERWEWERKJWE']
</code></pre>
<p>I would like to take the entries of this list and... | 4 | 2016-10-07T04:07:02Z | 39,909,368 | <p>You can also use <a href="https://docs.python.org/3/library/stdtypes.html#str.partition" rel="nofollow"><code>str.partition</code></a></p>
<pre><code>list1 = ['EW:G:B<<LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A<F<AF', 'GR:A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX:F:-111', 'DS:f:115.5', 'MW:AA:0', 'MA:A... | 2 | 2016-10-07T04:26:06Z | [
"python",
"dictionary",
"split"
] |
How to convert Multiplication sign into Asterisk sign in python? | 39,909,478 | <p>I have a math solver python program but it can't read "Ã" sign, so It can not solve the equation. Is there any way to convert "Ã" into "*"?</p>
<p><strong>Python shell:</strong></p>
<pre><code>>>> 3 Ã 5
`SyntaxError: invalid character in identifier
>>> 3 * 5
15
>>>
</code></pre>
<p>... | 0 | 2016-10-07T04:36:55Z | 39,919,610 | <p>Let's go over your code line by line.</p>
<pre><code>if (parser.getPayload().lower()[:6]=="solve:"):
</code></pre>
<p>Fine I guess, don't know your protocol but makes sense this way.</p>
<pre><code> if ("Ã" in parser.getPayload().lower()):
</code></pre>
<p>Converting to lower case should not ... | 0 | 2016-10-07T14:25:46Z | [
"python",
"math",
"character-encoding",
"special-characters",
"identifier"
] |
Creating a new tmux session from within a session | 39,909,581 | <p>I am using a voice assistant on my RPi, but because of a certain tmux session I have, it won't work.</p>
<p>That is fine, because I came up with an idea to fix this.</p>
<p>Since my voice assistant is written in Python, I thought I could use the <code>os</code> module to do a <code>os.system('tmux kill-session -t ... | 0 | 2016-10-07T04:47:06Z | 39,909,839 | <p>You'll need to unset the TMUX environment variable</p>
<pre><code># assuming this is the shell inside tmux
$ export TMUX=
# now you can run tmux inside tmux
$ tmux
</code></pre>
<p>So the important line is <code>export TMUX=</code> prior to the inception of tmux.</p>
| 0 | 2016-10-07T05:11:46Z | [
"python",
"raspberry-pi",
"tmux"
] |
Python listing all files in directory | 39,909,655 | <p>Can anybody help me creating a function which will creating a list all files under certain directory by using pathlib library?</p>
<p>Here, I have a</p>
<p><a href="http://i.stack.imgur.com/jJMwB.png" rel="nofollow"><img src="http://i.stack.imgur.com/jJMwB.png" alt="enter image description here"></a></p>
<p>I hav... | 0 | 2016-10-07T04:54:43Z | 39,909,791 | <pre><code>def searching_all_files(directory: Path):
file_list = [] # A list for storing files existing in directories
for x in directory.iterdir():
if x.is_file():
file_list.append(x)#here should be appended
else:
file_list.extend(searching_all_files(directory/x))# n... | 0 | 2016-10-07T05:06:20Z | [
"python",
"pathlib"
] |
Python listing all files in directory | 39,909,655 | <p>Can anybody help me creating a function which will creating a list all files under certain directory by using pathlib library?</p>
<p>Here, I have a</p>
<p><a href="http://i.stack.imgur.com/jJMwB.png" rel="nofollow"><img src="http://i.stack.imgur.com/jJMwB.png" alt="enter image description here"></a></p>
<p>I hav... | 0 | 2016-10-07T04:54:43Z | 39,909,947 | <p>You can use os.listdir(). It will get you everything that's in a directory - files and directories.</p>
<p>If you want just files, you could either filter this down using os.path:</p>
<pre><code>from os import listdir
from os.path import isfile, join
onlyfiles = [files for files in listdir(mypath) if isfile(join(m... | 1 | 2016-10-07T05:20:05Z | [
"python",
"pathlib"
] |
Python listing all files in directory | 39,909,655 | <p>Can anybody help me creating a function which will creating a list all files under certain directory by using pathlib library?</p>
<p>Here, I have a</p>
<p><a href="http://i.stack.imgur.com/jJMwB.png" rel="nofollow"><img src="http://i.stack.imgur.com/jJMwB.png" alt="enter image description here"></a></p>
<p>I hav... | 0 | 2016-10-07T04:54:43Z | 39,911,421 | <pre><code>from pathlib import Path
from pprint import pprint
def searching_all_files(directory):
dirpath = Path(directory)
assert(dirpath.is_dir())
file_list = []
for x in dirpath.iterdir():
if x.is_file():
file_list.append(x)
elif x.is_dir():
file_list.extend(s... | 0 | 2016-10-07T07:08:56Z | [
"python",
"pathlib"
] |
Using Python to Read Rows of CSV Files With Column Content containing Comma | 39,909,740 | <p>I am trying to parse this CSV and print out the various columns separately.</p>
<p>However my code is having difficulty doing so possibly due to the commas in the addresses, making it hard to split them into 3 columns.</p>
<p>How can this be done?</p>
<p><strong>Code</strong></p>
<pre><code>with open("city.csv")... | 0 | 2016-10-07T05:02:24Z | 39,909,989 | <p>If you just want to parse the file, I would recommend using <a href="http://pandas.pydata.org/" rel="nofollow">Pandas Library</a> </p>
<pre><code>import pandas as pd
data_frame = pd.read_csv("city.csv")
</code></pre>
<p>which gives you a data frame that looks like this in iPython notebook.
<a href="http://i.stack.... | 1 | 2016-10-07T05:23:21Z | [
"python",
"python-2.7",
"csv"
] |
Using Python to Read Rows of CSV Files With Column Content containing Comma | 39,909,740 | <p>I am trying to parse this CSV and print out the various columns separately.</p>
<p>However my code is having difficulty doing so possibly due to the commas in the addresses, making it hard to split them into 3 columns.</p>
<p>How can this be done?</p>
<p><strong>Code</strong></p>
<pre><code>with open("city.csv")... | 0 | 2016-10-07T05:02:24Z | 39,909,992 | <p>You should always use <code>csv</code> module</p>
<pre><code>import csv
with open("city.csv") as f:
csv_reader = csv.reader(f):
for row in csv_reader:
print row
</code></pre>
| 1 | 2016-10-07T05:23:40Z | [
"python",
"python-2.7",
"csv"
] |
Is it possible to check for global variables in IPython when running a file? | 39,909,760 | <p>I have a file like so:</p>
<pre><code>import pandas a pd
def a_func():
print 'doing stuff'
if __name__ == "__main__":
if 'data' not in globals():
print 'loading data...'
data = pd.read_csv('datafile.csv')
</code></pre>
<p>When I run the file in IPython with <code>run file.py</code>, it al... | 2 | 2016-10-07T05:03:32Z | 39,909,953 | <p>Everytime a python file is executed the globals() dictionary is reset by the interpreter. So if you will try to do something like </p>
<pre><code>print globals().keys()
</code></pre>
<p>you can see that 'data' is not in globals. This dictionary gets updated as the program runs. So I don't think you can refer to th... | 0 | 2016-10-07T05:20:36Z | [
"python",
"ipython"
] |
How to print just the content of the help string of a specific argument of ArgParse | 39,909,927 | <p>Is there a way to access the help strings for specific arguments of the argument parser library object? </p>
<p>I want to print the help string content if the option was present on the command line. <em>Not</em> the complete help text that Argument Parser can display via ArgumentParser.print_help .</p>
<p>So somet... | 4 | 2016-10-07T05:19:01Z | 39,910,425 | <p>There is <code>parser._option_string_actions</code> which is mapping between option strings (<code>-d</code> or <code>--do_x</code>) and <a href="https://docs.python.org/3/library/argparse.html#action-classes" rel="nofollow"><code>Action</code> objects</a>. <code>Action.help</code> attribute holds the help string.</... | 3 | 2016-10-07T06:01:55Z | [
"python",
"argparse"
] |
How to print just the content of the help string of a specific argument of ArgParse | 39,909,927 | <p>Is there a way to access the help strings for specific arguments of the argument parser library object? </p>
<p>I want to print the help string content if the option was present on the command line. <em>Not</em> the complete help text that Argument Parser can display via ArgumentParser.print_help .</p>
<p>So somet... | 4 | 2016-10-07T05:19:01Z | 39,910,688 | <p><code>parser._actions</code> is a list of the <code>Action</code> objects. You can also grab object when creating the parser.</p>
<pre><code>a=parser.add_argument(...)
...
If args.do_x:
print a.help
</code></pre>
<p>Play with <code>argparse</code> in an interactive session. Look at <code>a</code> from suc... | 2 | 2016-10-07T06:20:34Z | [
"python",
"argparse"
] |
How do you show an error message when a test does not throw an expected exception? | 39,909,935 | <p>I am new to python. I wanted to test if my code throws an exception. I got the code from here: <a href="http://stackoverflow.com/questions/129507/how-do-you-test-that-a-python-function-throws-an-exception">How do you test that a Python function throws an exception?</a></p>
<pre><code>import mymod
import unittest
c... | 0 | 2016-10-07T05:19:27Z | 39,910,294 | <p>As of python 3.3, <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises" rel="nofollow">assertRaises</a> can be used as a context manager with a message:</p>
<pre><code>import unittest
def sayHelloTo(name):
print("Hello " + name)
class MyTestCase(unittest.TestCase):
def t... | 2 | 2016-10-07T05:50:38Z | [
"python",
"unit-testing",
"exception"
] |
How do you show an error message when a test does not throw an expected exception? | 39,909,935 | <p>I am new to python. I wanted to test if my code throws an exception. I got the code from here: <a href="http://stackoverflow.com/questions/129507/how-do-you-test-that-a-python-function-throws-an-exception">How do you test that a Python function throws an exception?</a></p>
<pre><code>import mymod
import unittest
c... | 0 | 2016-10-07T05:19:27Z | 39,936,068 | <blockquote>
<p>Now, I also want to display a message if the exception is not thrown. How do I do that ?</p>
</blockquote>
<p>The general philosophy of <em>unittest</em> is for the tests to be silent when they succeed and only become verbose when they fail. Accordingly, the API provides a "msg" keyword argument for... | 0 | 2016-10-08T18:46:22Z | [
"python",
"unit-testing",
"exception"
] |
How to view the source code of numpy.random.exponential? | 39,910,050 | <p>I want to see if <code>numpy.random.exponential</code> was implemented using F^{-1} (U) method, where F is the c.d.f of exponential distribution and U is uniform distribution. </p>
<p>I tried <code>numpy.source(random.exponential)</code>, but returned '<em>Not available for this object'</em>. Does it mean this func... | 3 | 2016-10-07T05:28:28Z | 39,910,139 | <p>numpy's sources are <a href="https://github.com/numpy/numpy" rel="nofollow">at github</a> so you can use github's <a href="https://github.com/numpy/numpy/search?utf8=%E2%9C%93&q=exponential" rel="nofollow">source-search</a>.</p>
<p>As often, these parts of the library are not implemented in pure python.</p>
<p... | 5 | 2016-10-07T05:36:53Z | [
"python",
"numpy",
"random"
] |
How to view the source code of numpy.random.exponential? | 39,910,050 | <p>I want to see if <code>numpy.random.exponential</code> was implemented using F^{-1} (U) method, where F is the c.d.f of exponential distribution and U is uniform distribution. </p>
<p>I tried <code>numpy.source(random.exponential)</code>, but returned '<em>Not available for this object'</em>. Does it mean this func... | 3 | 2016-10-07T05:28:28Z | 39,920,776 | <p>A lot of numpy functions are written with C/C++ and Fortran. <code>numpy.source()</code> returns the source code only for objects written in Python. It is written on <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.source.html" rel="nofollow">NumPy website</a>.</p>
<p>You can find all of the NumPy... | 1 | 2016-10-07T15:23:22Z | [
"python",
"numpy",
"random"
] |
Python PIL image warping / Affine transformations | 39,910,190 | <p>Using Python PIL I want to transform input images in such a way that they seem to be in perspective. Most of the answers I have found are about rotating etc. The images below show one of the effects I am aiming at. Similarly I would like to do this not only from front to back, but also from left to right and vice ve... | 0 | 2016-10-07T05:42:55Z | 39,942,374 | <p>I believe you are looking for <a href="https://en.wikipedia.org/wiki/3D_projection" rel="nofollow">perspective transformations</a>. You can do it with Pillow in following way:</p>
<pre><code>transformed = image.transform(
image.size, Image.PERSPECTIVE,
[
a0, a1, a2,
a3, a4, a5,
a6, ... | 1 | 2016-10-09T10:11:02Z | [
"python",
"python-imaging-library"
] |
Need help understanding a short python code | 39,910,208 | <p>I want to emphasis that this is not a ask for completing my homework or job: I am studying the LZW algorithm for gif file compression by reading someone's code on <a href="https://github.com/j-s-n/mazes/blob/master/python2/GIF_maze.py" rel="nofollow">github</a>, and got confused by a code block here:</p>
<pre><code... | 1 | 2016-10-07T05:44:47Z | 39,911,790 | <p>Try looking at it this way:</p>
<ul>
<li>You will be given a <code>bytearray</code> object (call it <code>x</code> for the moment).</li>
<li>How many bytes are in the object? (Obviously, it's just <code>len(x)</code>.)</li>
<li>How many <em>bits</em> are in the object? (This is an exercise; please calculate the a... | 0 | 2016-10-07T07:30:26Z | [
"python"
] |
Why does PyQt's pyuic ignore default margins? | 39,910,217 | <p>In Qt Designer I can see <code>verticalLayout</code> has a default margin (13px), but pyuic5 always gives me <code>self.verticalLayout.setContentsMargins(0, 0, 0, 0)</code>. In <code>uiparser.py:443</code> I found this comment:</p>
<blockquote>
<p>A layout widget should, by default, have no margins.</p>
</blockqu... | 2 | 2016-10-07T05:45:23Z | 39,922,915 | <p>There is a <a href="http://riverbankcomputing.com/pipermail/pyqt/2015-December/036659.html" rel="nofollow">PyQt mailing list thread</a> on this, which seems to have resulted in the default margins being forced to zero for certain widgets. I don't know whether the behaviour of the C++ uic tool has changed since then,... | 1 | 2016-10-07T17:30:02Z | [
"python",
"qt",
"layout",
"pyqt",
"qt-designer"
] |
CPython 2.7 + Java | 39,910,350 | <p>My major program is written in Python 2.7 (on Mac) and need to leverage some function which is written in a Java 1.8, I think CPython cannot import Java library directly (different than Jython)?</p>
<p>If there is no solution to call Java from CPython, could I integrate in this way -- wrap the Java function into a ... | 0 | 2016-10-07T05:54:22Z | 39,929,049 | <ul>
<li>If you have lot of dependcieis on Java/JVM, you can consider using <code>Jython</code>.</li>
<li>If you would like to develop a scalable/maintainable application, consider using microservices and keep Java and Python components separate.</li>
<li>If your call to Java is simple and it is easy to capture the out... | 1 | 2016-10-08T05:34:34Z | [
"java",
"python",
"osx",
"python-2.7",
"cpython"
] |
Determine length of NumberLong in Python | 39,910,423 | <p>I have some documents in my MongoDB collection, some of which contain NumberLong values :</p>
<pre><code>{ "_id" : ObjectId("57e4d18df4733211b613f199"), "parentid" : "P1000016", "phone" : NumberLong("9819733299") }
{ "_id" : ObjectId("57e4d18df4733211b613f19a"), "parentid" : "P1000014", "phone" : "24306574|99205994... | 0 | 2016-10-07T06:01:28Z | 39,912,136 | <p>Depending on your use case, you can either add a filter to your query, to only return field <code>phone</code> where the value is string by utilising <a href="https://docs.mongodb.com/manual/reference/operator/query/type/#type" rel="nofollow">$type</a></p>
<pre><code>client = MongoClient()
db = client.database
co... | -1 | 2016-10-07T07:50:15Z | [
"python",
"mongodb",
"pymongo"
] |
Putting a variable value into a input's string | 39,910,547 | <p>Is there anyway to have a variable be in the string of an input?</p>
<pre><code>score = float(input("Test", grade, "-- Enter score: "))
</code></pre>
<p>I keep getting:</p>
<p>TypeError: input expected at most 1 arguments, got 3</p>
| 0 | 2016-10-07T06:10:39Z | 39,910,602 | <p>You are passing 3 strings, should be only one. You're incorrectly concatenating string. Use <code>format</code> for that</p>
<pre><code>score = float(input("Test {} -- Enter score: ".format(grade)))
</code></pre>
| 1 | 2016-10-07T06:14:46Z | [
"python",
"variables",
"input"
] |
Putting a variable value into a input's string | 39,910,547 | <p>Is there anyway to have a variable be in the string of an input?</p>
<pre><code>score = float(input("Test", grade, "-- Enter score: "))
</code></pre>
<p>I keep getting:</p>
<p>TypeError: input expected at most 1 arguments, got 3</p>
| 0 | 2016-10-07T06:10:39Z | 39,910,699 | <p>You can use % or format to put variable into string:</p>
<pre><code>score = float(input("Test %s -- Enter score: " % grade))
</code></pre>
<p>or </p>
<pre><code>score = float(input("Test {} -- Enter score: ".format(grade)))
</code></pre>
| 0 | 2016-10-07T06:21:39Z | [
"python",
"variables",
"input"
] |
Putting a variable value into a input's string | 39,910,547 | <p>Is there anyway to have a variable be in the string of an input?</p>
<pre><code>score = float(input("Test", grade, "-- Enter score: "))
</code></pre>
<p>I keep getting:</p>
<p>TypeError: input expected at most 1 arguments, got 3</p>
| 0 | 2016-10-07T06:10:39Z | 39,915,426 | <p>Your error is because the input function received more than 1 argument. It received:</p>
<ol>
<li>"Test"</li>
<li>grade</li>
<li>"-- Enter score: "</li>
</ol>
<p>You need to combine those three elements into one, the best way would be using a formatter (%), allowing Python to interpret it as one string:</p>
<pre>... | 0 | 2016-10-07T10:47:55Z | [
"python",
"variables",
"input"
] |
Orders of growth involving both recursion and two inner for loops | 39,910,580 | <p>I have attempted the below question but I am uncertain whether I am correct or not. I have arrived at the conclusion that it is a big theta of n^2 function. My reasoning is that the inner 2 loops for i and for j will amount to a sequence of operations, 0, 1, 2, 3, 4, 5....x -1, which can be translated into (x * x - ... | 0 | 2016-10-07T06:13:02Z | 39,911,252 | <p><strong>EDIT:</strong> First there was <code>i+i</code> in question but now there is <code>i+j</code> so now my answer is wrong.</p>
<hr>
<p>When <code>x < 1</code> it prints 'boo' - nothing intersting.</p>
<p>When <code>x >= 1</code> then you can reach loops</p>
<pre><code>for i in range(x):
for j in... | -1 | 2016-10-07T06:59:37Z | [
"python",
"recursion",
"runtime"
] |
Pandas group and record grouped values | 39,910,677 | <p>I have the following dataset:</p>
<pre><code>Code Value
100004 1
1017 1
1017 3
1071 1
1071 3
3039 1
3397 1
3397 3
</code></pre>
<p>I was able to count the Value using pandasDataFrame.groupby('Code', as_index=False).agg('count')</p>
<p>I would like to count and in the same time to record t... | 2 | 2016-10-07T06:20:03Z | 39,910,737 | <p>You can use <code>groupby</code> + <code>agg</code>:</p>
<pre><code>df.Value.groupby(df.Code).agg({'Values': lambda g: list(g), 'NumValues': lambda g: len(g)}).reset_index()
</code></pre>
<p>For example:</p>
<pre><code>df = pd.DataFrame({'Code': [1004, 1004, 1007], 'Value': [1, 2, 8]})
>>> df.Value.group... | 1 | 2016-10-07T06:24:44Z | [
"python",
"pandas"
] |
python scripts creating csv file, with Archive check box is checked. How to create a csv file not archive? | 39,910,681 | <p>I am facing a strange problem
Whenever my python scripts are creating any csv file, it is making them "Archive".
I mean in properties, Archive check box is checked.
Because of which it can't be read in later part of same script .
How can i create a csv file not archive?
Please help me resolve this problem.</p>
| -1 | 2016-10-07T06:20:21Z | 39,910,994 | <p>Are you running a Windows OS? If yes, then this is not a problem with the Python CSV library. As about the error encountered while reading the CSV; you may want to re-check your python code for any flaws.</p>
<p>The Archive checkbox is actually an attribute of the file on Windows systems that indicates that the fil... | 1 | 2016-10-07T06:43:25Z | [
"python"
] |
Unable to download files from S3 bucket | 39,910,911 | <p>I want to download all files from S3 bucket which are in this path <code>All Buckets /abc/or/uploads</code></p>
<p>I tried with this snippet but only managed to get files in <code>All Buckets /abc</code></p>
<p>Changing the path in <code>bucket_list = bucket.list('or/uploads')</code>
this line is not working? why?... | 2 | 2016-10-07T06:38:11Z | 39,912,007 | <p>Amazon S3 does not have folders/directories. It is a flat file structure.
To maintain the appearance of directories, path names are stored as part of the object Key (filename). </p>
<p>Make sure the place where you are downloading the files, have exact same structure i.e.. <code>/abc/or/uploads</code> </p>
<p>sni... | 0 | 2016-10-07T07:42:20Z | [
"python",
"amazon-web-services",
"amazon-s3"
] |
Logging each in/out of each function | 39,910,941 | <p>Currently I typically add a log line to my functions with details of the variables that are inputted and returned. However I am looking for an elegant way around this.</p>
<p>Is there a way to log each input to a function and what is returned using some form of magic methods?</p>
<p>Below is an example,</p>
<pre>... | 3 | 2016-10-07T06:40:19Z | 39,911,346 | <p>There is a concept of <a href="https://wiki.python.org/moin/PythonDecorators" rel="nofollow">decorators in python</a>. They help you abstract out the common code you want to inject on any function on your will. Make a decorator named <code>log</code> as follows:</p>
<pre><code>import logging
from functools import w... | 3 | 2016-10-07T07:04:32Z | [
"python"
] |
Update PHP variable without refresh | 39,910,958 | <p>I am new in JSON and PHP programming. I am making a web page that allows to view data from <strong>file.py</strong>, those data will be linked in a <code>gauge</code> and updated <code>second by second</code>.</p>
<pre><code> var gauge1;
var x = <?php echo python /home/usr/Desktop/file.py ?> ;
setInte... | -2 | 2016-10-07T06:41:07Z | 39,911,166 | <p>You can use ajax to execute a backend script in a time interval like this .</p>
<pre><code>var x=null;
setInterval(retriveData, 300000);
function retriveData() {
$.ajax({url: "pyData.php", success: function(data){
x=data;
}});
}
</code></pre>
<p>And your Php code like this <strong>(pyData.php)</strong... | 0 | 2016-10-07T06:54:46Z | [
"javascript",
"php",
"python",
"html",
"json"
] |
Pandas Apply returns matrix instead of single column | 39,911,083 | <p>This is probably a stupid question, but I have been trying for a while and I can't seem to get it to work.</p>
<p>I have a dataframe:</p>
<pre><code> df1 = pd.DataFrame({'Type': ['A','A', 'B', 'F', 'C', 'G', 'A', 'E'], 'Other': [999., 999., 999., 999., 999., 999., 999., 999.]})
</code></pre>
<p>I now want to cr... | 1 | 2016-10-07T06:49:47Z | 39,911,986 | <p>You can use <code>map</code> to achieve this:</p>
<pre><code>In [62]:
df1['Type'].map(df2.set_index('Type')['Value'],na_action='ignore')
Out[62]:
0 1
1 1
2 1
3 4
4 2
5 5
6 1
7 4
Name: Type, dtype: int64
</code></pre>
<p>If you modified your <code>apply</code> attempt to the following then ... | 1 | 2016-10-07T07:41:12Z | [
"python",
"pandas",
"apply"
] |
How to create a TensorProto in c#? | 39,911,330 | <p>This is a snipped of the c# client I created to query the tensorflow server I set up using this tutorial: <a href="https://tensorflow.github.io/serving/serving_inception.html" rel="nofollow">https://tensorflow.github.io/serving/serving_inception.html</a></p>
<pre><code> var channel = new Channel("TFServer:90... | 1 | 2016-10-07T07:03:20Z | 40,091,359 | <p>I also implemented that client in another language (Java). </p>
<p>Try to change </p>
<pre><code>jpgeproto.Dtype = DataType.DtStringRef;
</code></pre>
<p>to </p>
<pre><code>jpgeproto.Dtype = DataType.DtString;
</code></pre>
<p>You may also need to add a tensor shape with a dimension to your tensor proto. Her... | 0 | 2016-10-17T16:28:39Z | [
"c#",
"python",
"tensorflow"
] |
Why would a pip installed package's __init__.py NOT have the canonical if __name__ == "__main__":? | 39,911,357 | <p>I am playing around with <a href="http://github.com/getpelican/pelican" rel="nofollow">pelican</a>, the static blog generator, which I have</p>
<ul>
<li><p>cloned from github</p>
<p>$ git clone <a href="https://github.com/getpelican/pelican.git" rel="nofollow">https://github.com/getpelican/pelican.git</a></p></li>... | 2 | 2016-10-07T07:05:19Z | 39,911,648 | <p>The <a href="https://github.com/getpelican/pelican/blob/master/setup.py" rel="nofollow"><code>pelican/setup.py</code></a> defines several entrypoints:</p>
<pre><code>entry_points = {
'console_scripts': [
'pelican = pelican:main',
'pelican-import = pelican.tools.pelican_import:main',
'pel... | 4 | 2016-10-07T07:21:59Z | [
"python",
"python-2.7",
"pycharm"
] |
Tensorflow elementwise matrix multiplication (for-loop) error | 39,911,373 | <p>I want to calculate matrix multiplication with Tensorflow. <br>
But it occured errors while numpy usage doesn't make errors. <br>
(Process finished with exit code 139 (interrupted by signal 11: SIGSEGV))</p>
<p><strong>Tensorflow with CPU / GPU : occured the error : Process finished with exit code 139 (interrupted ... | -1 | 2016-10-07T07:05:50Z | 39,947,305 | <p>You have a few errors in what you pasted. You aren't importing numpy correctly.</p>
<p>for tensorflow you need to create a session. </p>
<pre><code>with tf.Session() as sess:
... cpu or gpu code here...
print(sess.run([cost]))
</code></pre>
<p>for numpy it as built in element wise multiplication</p>
<pr... | 0 | 2016-10-09T18:53:27Z | [
"python",
"tensorflow"
] |
update query execution in python | 39,911,430 | <p>I am executing this query on sql developer and it is working fine</p>
<pre><code>update TABLE_X set COL_SID='19' where ID='1';
</code></pre>
<p>But when I am doing this via python code </p>
<pre><code>cur=conn.cursor()
updt_query='update TABLE_X set COL_SID=? where ID=?'
cur.execute(updt_query,('19','1'))
cur.clo... | 0 | 2016-10-07T07:09:09Z | 39,911,500 | <p>Could be the ID are number and not string so you should use </p>
<pre><code> cur.execute(updt_query,(19,1))
</code></pre>
| 0 | 2016-10-07T07:13:21Z | [
"python",
"sql",
"oracle"
] |
update query execution in python | 39,911,430 | <p>I am executing this query on sql developer and it is working fine</p>
<pre><code>update TABLE_X set COL_SID='19' where ID='1';
</code></pre>
<p>But when I am doing this via python code </p>
<pre><code>cur=conn.cursor()
updt_query='update TABLE_X set COL_SID=? where ID=?'
cur.execute(updt_query,('19','1'))
cur.clo... | 0 | 2016-10-07T07:09:09Z | 39,911,716 | <p>I got a better way</p>
<pre><code>cur=conn.cursor()
updt_query='update TABLE_X set COL_SID=:cs where ID=:id'
cur.execute(updt_query,{cs:'19',id:'1'})
cur.close()
</code></pre>
<p>Its done ! Thanks!</p>
| 0 | 2016-10-07T07:25:53Z | [
"python",
"sql",
"oracle"
] |
Binary Tree Traversal - Preorder - visit to parent | 39,911,442 | <p>I'm trying to understand the recursive implementation of preorder traversal as shown in this link <a href="http://interactivepython.org/runestone/static/pythonds/Trees/TreeTraversals.html" rel="nofollow">http://interactivepython.org/runestone/static/pythonds/Trees/TreeTraversals.html</a></p>
<pre><code>def preorder... | -2 | 2016-10-07T07:09:43Z | 39,911,679 | <p><code>preorder(tree.getLefChild())</code> goes through all the left children for the current tree. That method then returns, just like all other methods, then continues on with the parent's right children. </p>
<p>A quick visualization </p>
<pre><code>def preorder(tree):
if tree:
print(tree.getRootV... | 0 | 2016-10-07T07:23:16Z | [
"python",
"recursion",
"binary-tree"
] |
How are the commit timestamps generated in cvs2git/cvs2svn? | 39,911,698 | <p>I am converting a very old and huge CVS repository to Git using cvs2git via Cygwin. It works fine and I started testing the new repository. I found no bigger peculiarities. But I wonder how the timestamps of a commit/change set are determined.</p>
<p>So far I determined, that the timestamps between certain CVS revi... | 0 | 2016-10-07T07:24:52Z | 40,013,821 | <p>You ask two questions:</p>
<ol>
<li><p>How are timestamps generated for commits touching multiple files?</p>
<p>For commits that modify files, cvs2svn/cvs2git takes the newest timestamp from among the file-level commits that comprise the commit. However, if that timestamp is earlier than the timestamp of the previ... | 1 | 2016-10-13T06:32:38Z | [
"python",
"git",
"timestamp",
"cvs2svn",
"cvs2git"
] |
Trying to view User Profile in Django, but Page Not Found when searching URLs | 39,911,741 | <p>I am trying to view a user profile for my website with the Detail CBV. Below is the code for views.py, urls.py, models.py and profile.html.</p>
<p>A user exists with the username "brian_weber", but for some reason when I navigate to this link: <a href="http://0.0.0.0:8000/accounts/profile/brian_weber" rel="nofollo... | 0 | 2016-10-07T07:27:15Z | 39,912,215 | <p>Your mistake is very small, the regular expression provided in url for profile, <code>(?P<username>[a-zA-Z0-9]+)</code> does not match <code>brian_weber</code> because of the <code>_</code>.</p>
<p>You can simply update the regex to match <code>_</code> too.</p>
<pre><code>username_regex = r'[a-zA-Z0-9_]+'
... | 2 | 2016-10-07T07:54:29Z | [
"python",
"django",
"django-views",
"django-class-based-views",
"user-profile"
] |
Functions in python 3 | 39,911,985 | <p>I'm struggling with functions in python 3. How can I make the below code print out the result in degrees Celsius? Is the indentation wrong, or has it to do with me not defining Celsius outside the function in the first place? Does this mean I do not have to use functions for simple tasks or is it better to do so any... | 1 | 2016-10-07T07:41:10Z | 39,912,052 | <p>Quite a few changes needed, yes you had the indentation wrong for the print statement. But that's not all see how the code is ordered now</p>
<pre><code>def converter_fahrenheit(fahrenheit):
celsius = (fahrenheit - 32) * 5/9
print (fahrenheit, "graden Fahrenheit is omgerekend ","%.2f" % celsius,"graden Cels... | 1 | 2016-10-07T07:44:59Z | [
"python"
] |
Functions in python 3 | 39,911,985 | <p>I'm struggling with functions in python 3. How can I make the below code print out the result in degrees Celsius? Is the indentation wrong, or has it to do with me not defining Celsius outside the function in the first place? Does this mean I do not have to use functions for simple tasks or is it better to do so any... | 1 | 2016-10-07T07:41:10Z | 39,912,516 | <p>You can do this by defining your function <code>converter_fahrenheit()</code> first then taking the input and finally calling the function after having the input. You haven't called the function to get the value of <code>celsius</code> and it's the main issue.
The code should be like in this way:</p>
<pre><code>def... | 1 | 2016-10-07T08:10:53Z | [
"python"
] |
Functions in python 3 | 39,911,985 | <p>I'm struggling with functions in python 3. How can I make the below code print out the result in degrees Celsius? Is the indentation wrong, or has it to do with me not defining Celsius outside the function in the first place? Does this mean I do not have to use functions for simple tasks or is it better to do so any... | 1 | 2016-10-07T07:41:10Z | 39,912,769 | <p>You seem to have misunderstood how functions work. When you write something like:</p>
<pre><code>def converter_farenheit(farenheit):
some_code
</code></pre>
<p>The code inside doesn't actually get run until you call the function by calling it later in the program. You've already called a few functions like <co... | 1 | 2016-10-07T08:26:19Z | [
"python"
] |
MultiIndex look up all indices that have a given value for a given level | 39,912,657 | <p>I am using a <code>pandas.Series</code> with a <code>MultiIndex</code> for a bidirectional weighted lookup. I thought it should be easy to also find the corresponding other levels for a given level using the MultiIndex, but I cannot find a simple function <code>other</code> that does something like the following:</p... | 2 | 2016-10-07T08:20:06Z | 39,913,283 | <p>How about this:</p>
<pre><code>>>> index.get_level_values('concept').values[index.get_level_values('word').values == 0]
array([0, 8, 9])
>>> index.get_level_values('concept').values[index.get_level_values('word').values == 6]
array([5])
>>> index.get_level_values('word').values[index.ge... | 1 | 2016-10-07T08:54:28Z | [
"python",
"pandas",
"indexing",
"multi-index"
] |
MultiIndex look up all indices that have a given value for a given level | 39,912,657 | <p>I am using a <code>pandas.Series</code> with a <code>MultiIndex</code> for a bidirectional weighted lookup. I thought it should be easy to also find the corresponding other levels for a given level using the MultiIndex, but I cannot find a simple function <code>other</code> that does something like the following:</p... | 2 | 2016-10-07T08:20:06Z | 39,915,353 | <p><strong>Approach 1:</strong></p>
<p>You could build up a custom function using a vectorized approach as shown:</p>
<pre><code>def other(index, slicing, value):
arr = np.column_stack(index.values.tolist())
return (np.delete(arr, slicing, axis=0)[0][arr[slicing]==value])
</code></pre>
<p><em>Usage:</em></p>... | 1 | 2016-10-07T10:42:21Z | [
"python",
"pandas",
"indexing",
"multi-index"
] |
Reading sequential user input to an array in python | 39,912,937 | <p>I am very new to python, so apologise in advance if this question is straightforward.</p>
<p>I am writing a script in python that needs to ask the user for input sequentially (the input will all be floats), and then it needs to write that input to a list. The rest of the code will then do stuff with the list.</p>
... | 0 | 2016-10-07T08:36:09Z | 39,913,059 | <p>It should be:</p>
<pre><code>li = [a1, a2, a3]
for s in li:
num_array.append(float(s))
</code></pre>
<p>You want to refer to <code>a1</code> the variable and not <code>"a1"</code> the string</p>
<p>Note you could combine everything into your loop:</p>
<pre><code>num_list = []
for c in ("A","B","C"):
num_... | 0 | 2016-10-07T08:42:25Z | [
"python",
"arrays",
"variables",
"input"
] |
Reading sequential user input to an array in python | 39,912,937 | <p>I am very new to python, so apologise in advance if this question is straightforward.</p>
<p>I am writing a script in python that needs to ask the user for input sequentially (the input will all be floats), and then it needs to write that input to a list. The rest of the code will then do stuff with the list.</p>
... | 0 | 2016-10-07T08:36:09Z | 39,913,412 | <p>Instead of using <code>str</code> type in <code>li</code> list, use the variables as: </p>
<pre><code> li = [a1, a2, a3]
</code></pre>
<p>Still your loop might raise <code>ValueError</code> if the value you are passing with <code>raw_input()</code> could not be convert into <code>float</code>. Better way to conver... | 0 | 2016-10-07T09:01:56Z | [
"python",
"arrays",
"variables",
"input"
] |
Reading sequential user input to an array in python | 39,912,937 | <p>I am very new to python, so apologise in advance if this question is straightforward.</p>
<p>I am writing a script in python that needs to ask the user for input sequentially (the input will all be floats), and then it needs to write that input to a list. The rest of the code will then do stuff with the list.</p>
... | 0 | 2016-10-07T08:36:09Z | 39,913,956 | <pre><code>a = input ("enter the value of a")
b = input ("enter the value of b")
c = input {"enter the value of c")
l = [a,b,c]
num_array = []
for i in l:
if type(i)==int
i=float(i)
num_array.append(i)
print l,num_array
</code></pre>
| -1 | 2016-10-07T09:30:11Z | [
"python",
"arrays",
"variables",
"input"
] |
List project RhodeCode | 39,913,076 | <p>my problem is the following one: I would want to list all the projects which are present on a RhodeCode instance through Python package. However, I do not find the necessary information within the documentation. Is it someone would have a solution?</p>
| 0 | 2016-10-07T08:43:28Z | 39,913,571 | <p>RhodeCode has a JSON-RPC api. You can use python requests lib to fetch all list of projects, read the JSON and then iterate over the results.</p>
<p>The JSON api call to make is get_repos. Check out RhodeCode docs on the API topic, and how to call it. Also if you need more detailed example how to call the API, look... | 0 | 2016-10-07T09:10:22Z | [
"python",
"scripting",
"package",
"rhodecode"
] |
Unable to parse XML response and obtain elements | 39,913,114 | <p>This is my XML response from a <code>http</code> request </p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<Dataset name="aggregations/g/ds083.2/2/TP"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xml.opendap.org/ns/DAP2"
xsi:schemaLocation="http://xml.opendap.org/ns/DAP... | 0 | 2016-10-07T08:45:25Z | 39,913,767 | <p>As stated in <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#parsing-xml-with-namespaces" rel="nofollow">the doc</a>, due to the <code>xmlns="http://xml.opendap.org/ns/DAP2"</code>attribute of the Dataset root tag, all tag names you're looking for have to be prefixed by <code>{http://xml.openda... | 1 | 2016-10-07T09:21:06Z | [
"python",
"xml",
"python-3.x",
"xml-parsing",
"httprequest"
] |
Unable to parse XML response and obtain elements | 39,913,114 | <p>This is my XML response from a <code>http</code> request </p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<Dataset name="aggregations/g/ds083.2/2/TP"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xml.opendap.org/ns/DAP2"
xsi:schemaLocation="http://xml.opendap.org/ns/DAP... | 0 | 2016-10-07T08:45:25Z | 39,913,781 | <p>The XML document uses namespaces so you need to support that in your code. There is an explanation and example code in the <a href="https://docs.python.org/3/library/xml.etree.elementtree.html#parsing-xml-with-namespaces" rel="nofollow"><code>etree</code> documentation</a>.</p>
<p>Basically you can do this:</p>
<p... | 1 | 2016-10-07T09:21:27Z | [
"python",
"xml",
"python-3.x",
"xml-parsing",
"httprequest"
] |
How to parse some optional elements present in XML document using python script? | 39,913,239 | <p>I have xml document collected from below link</p>
<p><a href="http://ieeexplore.ieee.org/gateway/ipsSearch.jsp?py=2000&hc=100" rel="nofollow">http://ieeexplore.ieee.org/gateway/ipsSearch.jsp?py=2000&hc=100</a></p>
<p>I am parsing <code>Title</code>, <code>Abstract</code>, <code>Author</code> and <code>Affi... | -1 | 2016-10-07T08:51:46Z | 39,914,144 | <p>Play the safe way - check if the element is present first, otherwise assign an empty string.</p>
<p>Now, since the parsed XML appears as dictionary you can use the <code>in</code> operator to check for that, and the ternary <code>if...else</code> operator to default the cases where you cant find an <code>abstract<... | 0 | 2016-10-07T09:40:43Z | [
"python",
"xml",
"parsing"
] |
Error handling when accessing API | 39,913,367 | <p>I am trying to access an API (Scopus) through python, downloading multiple abstracts within the for loop below:</p>
<pre><code>for t in eid:
url = "http://api.elsevier.com/content/abstract/eid/"+str(t)+"?view=FULL"
# url = "http://api.elsevier.com/content/abstract/eid/2-s2.0-84934272190?view=FULL"
re... | 0 | 2016-10-07T08:58:57Z | 39,913,699 | <p>Unfortunately you haven't included 'the above exception' that is mentioned in your output.</p>
<p>But in general, when an exceptional situation, such as an error, happens during execution of a piece of code, you can catch that exception and deal with it. An exception is an object with information on board about wha... | 0 | 2016-10-07T09:17:05Z | [
"python",
"scopus"
] |
Why does pandas.Series.corr return Nan whereas numpy or scipy compute a number? | 39,913,479 | <p>I try to compute correlation between two pandas series. This is what I get from numpy or scipy :</p>
<pre><code>scipy.stats.pearsonr(xfarines["400"].values, yfarines["PROTREF"].values)
(0.71564870605278108, 2.9185934338775347e-23)
pd.np.corrcoef(xfarines["400"].values, yfarines["PROTREF"].values)
array([[ 1. ... | 0 | 2016-10-07T09:05:03Z | 39,915,520 | <p>Strange that you mention numpy (v 1.8.0) but use the scipy import which may be different. This is what numpy does</p>
<pre><code>>>> a
array([[ 3.00000000, 0.17157288],
[ 3.00000000, 1.58578644],
[ 3.00000000, 3.00000000],
[ 3.00000000, 4.41421356],
[ 3.00000000, 5.8284271... | 0 | 2016-10-07T10:53:38Z | [
"python",
"pandas",
"numpy",
"correlation"
] |
Fill in missing values using climatology data except for current year | 39,913,543 | <pre><code>df.groupby([df.index.month, df.index.day])[vars_rs].transform(lambda y: y.fillna(y.median()))
</code></pre>
<p>I am filling missing values in a dataframe with median values from climatology. The days range from Jan 1 2010 to Dec 31st 2016. However, I only want to fill in missing values for days before curre... | 0 | 2016-10-07T09:08:33Z | 39,914,991 | <p>Use <code>np.where</code>, example:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'A':['a','a','b','b','c','c'],'B':[1,2,3,4,5,6],'C':[1,np.nan,np.nan,np.nan,np.nan,np.nan]})
df.ix[:,'C'] = np.where((df.A != 'c')&(df.B < 4)&(pd.isnull(df.C)),-99,df.ix[:,'C'])
</code></pre>
<p>... | 1 | 2016-10-07T10:22:12Z | [
"python",
"pandas"
] |
Fill in missing values using climatology data except for current year | 39,913,543 | <pre><code>df.groupby([df.index.month, df.index.day])[vars_rs].transform(lambda y: y.fillna(y.median()))
</code></pre>
<p>I am filling missing values in a dataframe with median values from climatology. The days range from Jan 1 2010 to Dec 31st 2016. However, I only want to fill in missing values for days before curre... | 0 | 2016-10-07T09:08:33Z | 39,916,202 | <p>The algorithm would be:</p>
<ol>
<li>Get a part of the data frame which contains only rows filtered by date with a boolean mask</li>
<li>Perform required replacements on it</li>
<li>Append the rest of the initial data frame to the end of the resulting data frame.</li>
</ol>
<p>Dummy data:</p>
<pre><code>df = pd.D... | 1 | 2016-10-07T11:31:40Z | [
"python",
"pandas"
] |
Login in to AJAX form using scrapy | 39,913,636 | <p>I am trying to logging in to the page <a href="http://www.kumhoepos.com.au/epos/index.jsp" rel="nofollow">http://www.kumhoepos.com.au/epos/index.jsp</a> which is java scripted. I am trying this but not successful.</p>
<pre><code>class ElementSpider(scrapy.Spider):
name = 'epos'
start_urls = ['http://www.kum... | 0 | 2016-10-07T09:14:05Z | 39,915,784 | <p>The Scrapy does not support on-page JS evaluation.
The submit button triggers JS <a href="http://view-source:http://www.kumhoepos.com.au/epos/index.jsp" rel="nofollow">login()</a> function:</p>
<pre><code>function login()
{
var cookie_user_id ='KHTIRE_USER_ID';
var f = document.loginForm;
if(isNull(f.u... | -1 | 2016-10-07T11:08:58Z | [
"python",
"web-scraping",
"scrapy"
] |
How can I convert a int type to time type | 39,913,642 | <p>I want to convert 20161017(int type) to 20161017(time type)</p>
<p>I try</p>
<pre><code>import time
a=20161017
b = time.strftime('%Y%m%d',a)
print(b)
</code></pre>
<p>but It cannot work</p>
<p>additional question</p>
<p>in int type, i use 20161017 - 10000 = 20151017
how can i do this in 20161017(time type)?</... | -1 | 2016-10-07T09:14:22Z | 39,913,663 | <p>strptime takes string as argument. So you have to first convert your <code>a</code> to string. And you should also use str<strong>p</strong>time instead of str<strong>f</strong>time</p>
<pre><code>b = time.strptime(str(a), '%Y%m%d')
</code></pre>
<p>as for your additional question. There is <code>dateutil.relative... | 1 | 2016-10-07T09:15:25Z | [
"python",
"time"
] |
BeautifulSoup - Extract text with tags as text | 39,913,686 | <p>Lets say i have the html</p>
<pre><code><div>Hey</div><div>This is <b>some text<b/>, right here. <a>Link<a/></div>
</code></pre>
<p>and the code</p>
<pre><code>soup = BeautifulSoup(html)
texts = soup.findAll(text=True)
</code></pre>
<p>print() will return</p>
<pre... | 0 | 2016-10-07T09:16:10Z | 39,913,741 | <p>based on updated OP's question:</p>
<pre><code>eDiv = soup.findAll("div")
if eDiv.find("b") is None:
tag = eDiv.text
else:
tag = eDiv
</code></pre>
<p>now you can append this into list.</p>
| -1 | 2016-10-07T09:19:49Z | [
"python",
"beautifulsoup"
] |
How can i get my program to return the password strength | 39,913,740 | <p>I'm struggling with my password rater program. How can i make sure that when i insert a password, my program returns the password strength. When i run this program it says that password_strength is stored at .....) is the return that i call at the end of my program wrong?</p>
<pre><code>print ("Welcome to this pass... | 1 | 2016-10-07T09:19:46Z | 39,914,143 | <p>You never call your python functions. </p>
<pre><code>def potatis():
print("Hello yu!")
</code></pre>
<p>defines a function, but you also need to call the function <code>potatis()</code> for the code inside to actually run.</p>
| 1 | 2016-10-07T09:40:37Z | [
"python",
"python-3.x"
] |
How can i get my program to return the password strength | 39,913,740 | <p>I'm struggling with my password rater program. How can i make sure that when i insert a password, my program returns the password strength. When i run this program it says that password_strength is stored at .....) is the return that i call at the end of my program wrong?</p>
<pre><code>print ("Welcome to this pass... | 1 | 2016-10-07T09:19:46Z | 39,914,145 | <p>Well first of all, you tell python to print the function, not the evaluation of the function. This is why you get that message.</p>
<p>Also, you never call any of the functions you wrote. To get a working program
after the declaration of all definitions is the following:</p>
<p>Call the check_len definition:</p>
... | 3 | 2016-10-07T09:40:44Z | [
"python",
"python-3.x"
] |
ImportError when configuring python's logging module with a dict and custom handler | 39,913,749 | <p>I've written a custom logging handler for python's logging package. This handler may or may not work, but this is beyond the scope of the question.</p>
<p>I'm trying to specify the handler using a configuration dict. However the logging package seems to be unable to find the correct class. This is the relevant s... | 0 | 2016-10-07T09:20:20Z | 39,915,471 | <p>I think I well victim to Python's confusing(!) import sematics. The module <code>iis.logging</code> was shaddowing the global <code>logging</code> module (somehow). Renaming to <code>iss.log</code> did the trick.</p>
| 0 | 2016-10-07T10:50:49Z | [
"python",
"logging",
"flask",
"python-3.5"
] |
Is there a way to compile python application into static binary? | 39,913,847 | <p>What I'm trying to do is ship my code to a remote server, that may have different python version installed and/or may not have packages my app requires.</p>
<p>Right now to achieve such portability I have to build relocatable virtualenv with interpreter and code. That approach has some issues (for example, you have... | 22 | 2016-10-07T09:24:20Z | 39,994,355 | <p>Freeze options:</p>
<ul>
<li><a href="https://pypi.python.org/pypi/bbfreeze/1.1.3" rel="nofollow">https://pypi.python.org/pypi/bbfreeze/1.1.3</a></li>
<li><a href="http://cx-freeze.sourceforge.net/" rel="nofollow">http://cx-freeze.sourceforge.net/</a></li>
</ul>
<p>However, your target server should have the envir... | 0 | 2016-10-12T08:51:20Z | [
"python",
"build"
] |
Is there a way to compile python application into static binary? | 39,913,847 | <p>What I'm trying to do is ship my code to a remote server, that may have different python version installed and/or may not have packages my app requires.</p>
<p>Right now to achieve such portability I have to build relocatable virtualenv with interpreter and code. That approach has some issues (for example, you have... | 22 | 2016-10-07T09:24:20Z | 40,057,486 | <p>You're probably looking for something like Freeze, which is able to compile your Python application with all its libraries into a static binary:</p>
<p><a href="https://pypi.python.org/pypi/cx_Freeze" rel="nofollow">PyPi page of Freeze</a></p>
<p><a href="https://wiki.python.org/moin/Freeze" rel="nofollow">Python ... | 0 | 2016-10-15T09:45:07Z | [
"python",
"build"
] |
Is there a way to compile python application into static binary? | 39,913,847 | <p>What I'm trying to do is ship my code to a remote server, that may have different python version installed and/or may not have packages my app requires.</p>
<p>Right now to achieve such portability I have to build relocatable virtualenv with interpreter and code. That approach has some issues (for example, you have... | 22 | 2016-10-07T09:24:20Z | 40,057,634 | <p>There are two ways you could go about to solve your problem</p>
<ol>
<li>Use a static builder, like freeze, or pyinstaller, or py2exe</li>
<li>Compile using cython</li>
</ol>
<p>I will explain how you can go about doing it using the second, since the first method is not cross platform and version, and has been exp... | 11 | 2016-10-15T10:00:42Z | [
"python",
"build"
] |
Is there a way to compile python application into static binary? | 39,913,847 | <p>What I'm trying to do is ship my code to a remote server, that may have different python version installed and/or may not have packages my app requires.</p>
<p>Right now to achieve such portability I have to build relocatable virtualenv with interpreter and code. That approach has some issues (for example, you have... | 22 | 2016-10-07T09:24:20Z | 40,077,889 | <p>To freeze your python executable and ship it along your code, embed it in an empty shell app. Follow the instructions how to embed python in an application from the <a href="https://docs.python.org/3/extending/embedding.html#embedding-python-in-another-application" rel="nofollow">official documentation</a>. You can ... | 0 | 2016-10-17T03:03:30Z | [
"python",
"build"
] |
Is there a way to compile python application into static binary? | 39,913,847 | <p>What I'm trying to do is ship my code to a remote server, that may have different python version installed and/or may not have packages my app requires.</p>
<p>Right now to achieve such portability I have to build relocatable virtualenv with interpreter and code. That approach has some issues (for example, you have... | 22 | 2016-10-07T09:24:20Z | 40,099,944 | <p>You might wish to investigate <a href="http://nuitka.net/" rel="nofollow">Nuitka</a>. It takes python source code and converts it in to C++ API calls. Then it compiles into an executable binary (ELF on Linux). It has been around for a few years now and supports a wide range of Python versions.</p>
<p>You will proba... | 0 | 2016-10-18T05:06:17Z | [
"python",
"build"
] |
Is there a way to compile python application into static binary? | 39,913,847 | <p>What I'm trying to do is ship my code to a remote server, that may have different python version installed and/or may not have packages my app requires.</p>
<p>Right now to achieve such portability I have to build relocatable virtualenv with interpreter and code. That approach has some issues (for example, you have... | 22 | 2016-10-07T09:24:20Z | 40,135,113 | <p>If you are on a Mac you can use py2app to create a .app bundle, which starts your Django app when you double-click on it.</p>
<p>I described how to bundle Django and CherryPy into such a bundle at <a href="https://moosystems.com/articles/14-distribute-django-app-as-native-desktop-app-01.html" rel="nofollow">https:/... | 0 | 2016-10-19T15:01:53Z | [
"python",
"build"
] |
Selecting a column vector from a matrix in Python | 39,914,049 | <p>I would like to index a column vector in a matrix in Python/numpy and have it returned as a column vector and not a 1D array.</p>
<pre><code>x = np.array([[1,2],[3,4]])
x[:,1]
>array([2, 4])
</code></pre>
<p>Giving </p>
<p><code>np.transpose(x[:,1])</code></p>
<p>is not a solution. Following the <code>numpy.t... | 2 | 2016-10-07T09:35:07Z | 39,914,077 | <p>Few options -</p>
<pre><code>x[:,[1]]
x[:,None,1]
x[:,1,None]
x[:,1][:,None]
x[:,1].reshape(-1,1)
x[None,:,1].T
</code></pre>
| 4 | 2016-10-07T09:36:10Z | [
"python",
"numpy",
"matrix",
"indexing"
] |
looping over product to compute a serie in python | 39,914,160 | <p>I'm just gonna compute the result of below serie in python:</p>
<p>The formula</p>
<p><a href="http://i.stack.imgur.com/vxNE0.gif" rel="nofollow"><img src="http://i.stack.imgur.com/vxNE0.gif" alt="enter image description here"></a></p>
<p>So, here is my function to compute:</p>
<pre><code> def compute(limit):
... | 1 | 2016-10-07T09:41:33Z | 39,914,253 | <p>You have <code>//</code> and not <code>/</code>, you wanted division, but made floor division</p>
<pre><code>def compute(limit):
pi = 1
for i in range(1,limit):
pi = pi * ((4*(i**2))/(4*(i**2)-1)) # you had here //
print(2*pi)
compute(10000)
</code></pre>
<p>Output:</p>
<pre><code>3.14151411... | 0 | 2016-10-07T09:45:41Z | [
"python"
] |
looping over product to compute a serie in python | 39,914,160 | <p>I'm just gonna compute the result of below serie in python:</p>
<p>The formula</p>
<p><a href="http://i.stack.imgur.com/vxNE0.gif" rel="nofollow"><img src="http://i.stack.imgur.com/vxNE0.gif" alt="enter image description here"></a></p>
<p>So, here is my function to compute:</p>
<pre><code> def compute(limit):
... | 1 | 2016-10-07T09:41:33Z | 39,914,341 | <p>Change one of the 4s into a float by putting a . after it and change the // into /. It makes python interpret everything as floats:</p>
<pre><code>def compute(limit):
pi = 1
for i in range(1,limit):
pi = pi * ((4.*(i**2))/(4*(i**2)-1))
print(2*pi)
compute(10000)
</code></pre>
| 0 | 2016-10-07T09:50:36Z | [
"python"
] |
looping over product to compute a serie in python | 39,914,160 | <p>I'm just gonna compute the result of below serie in python:</p>
<p>The formula</p>
<p><a href="http://i.stack.imgur.com/vxNE0.gif" rel="nofollow"><img src="http://i.stack.imgur.com/vxNE0.gif" alt="enter image description here"></a></p>
<p>So, here is my function to compute:</p>
<pre><code> def compute(limit):
... | 1 | 2016-10-07T09:41:33Z | 39,914,546 | <p>As others have already mentioned, <code>//</code> is integer division. No matter whether you're dividing floats or integers, the result will always be an integer. Pi is not an integer, so you should use float division: <code>/</code> and tell Python explicitly that you really want a float by converting one of the nu... | 1 | 2016-10-07T10:01:01Z | [
"python"
] |
Combining databases: identifying common records -- most efficient way | 39,914,198 | <p>I have a set of 20 sqlite databases (50 tables each and roughly 100 thousand records total per DB).
I want to combine these 20 databases into one master DB.
The concept is to have an additional column, which indicates for which domain the record is applicable.</p>
<hr>
<p>For example:</p>
<p><strong>Table A</stro... | 0 | 2016-10-07T09:43:11Z | 39,914,929 | <p>Making individual selects and updates for each record*domain is way slower than merging records in memory.</p>
<p>Load 20 tables into memory. Make complete list of records in memory. Bulk insert into DB.</p>
<p>Probably speed-efficient way for merge would be like this:</p>
<p>Load (key,value)->(domain code, null ... | 0 | 2016-10-07T10:20:06Z | [
"python",
"database",
"performance",
"sqlite3"
] |
What is the reason that a java method cannot return more than one value? | 39,914,362 | <p>As you know in python, a function can returns more than one value</p>
<p>eg:</p>
<pre><code>def myfun():
return 1, 2, 3
</code></pre>
<p>And we can call it in this way:</p>
<pre><code>a, b, c= myfun()
</code></pre>
<p>But in JAVA, we have cannot return more that one value, so we have to create one object ... | -1 | 2016-10-07T09:51:28Z | 39,914,403 | <p>Strictly speaking, Python does not return more than one value either. <code>1, 2, 3</code> is a tuple; it's just that Python's syntax supports automatically unpacking that tuple into separate variables.</p>
| 10 | 2016-10-07T09:53:28Z | [
"java",
"python"
] |
What is the reason that a java method cannot return more than one value? | 39,914,362 | <p>As you know in python, a function can returns more than one value</p>
<p>eg:</p>
<pre><code>def myfun():
return 1, 2, 3
</code></pre>
<p>And we can call it in this way:</p>
<pre><code>a, b, c= myfun()
</code></pre>
<p>But in JAVA, we have cannot return more that one value, so we have to create one object ... | -1 | 2016-10-07T09:51:28Z | 39,914,420 | <p>That Python function is only returning one value.</p>
<pre><code>>>> def myfun():
... return 1, 2, 3
...
>>> a = myfun()
>>> type(a)
<class 'tuple'>
</code></pre>
<p>As you can see, it's a container, just like you need in Java.</p>
| 8 | 2016-10-07T09:54:30Z | [
"java",
"python"
] |
Python: Matplotlib open interactive figures | 39,914,370 | <p>since I like the interactive figures of matlab (*.fig). I wrote a small program for saving interactive figures in Python. I use pickle to dump a matplotlib.pyplot figure in a name.pyfig file:</p>
<pre><code> output = open('name.pyfig', 'wb')
pickle.dump(plt.gcf(), output)
output.close()
</code></pre>
<... | 2 | 2016-10-07T09:51:56Z | 39,915,987 | <p>You need to give the full absolute path if you want to put the bat file somewhere else.</p>
<pre><code>f = open('C:\full\path\to\folder\name.pyfig','rb')
</code></pre>
| 0 | 2016-10-07T11:20:58Z | [
"python",
"matplotlib",
"save",
"interactive",
"figure"
] |
Python: Matplotlib open interactive figures | 39,914,370 | <p>since I like the interactive figures of matlab (*.fig). I wrote a small program for saving interactive figures in Python. I use pickle to dump a matplotlib.pyplot figure in a name.pyfig file:</p>
<pre><code> output = open('name.pyfig', 'wb')
pickle.dump(plt.gcf(), output)
output.close()
</code></pre>
<... | 2 | 2016-10-07T09:51:56Z | 39,958,604 | <p>Nevermind, I manually added a registry entry which worked fine:</p>
<pre><code> Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\pyfig_auto_file]
@=""
[HKEY_CLASSES_ROOT\pyfig_auto_file\DefaultIcon]
@="path_to_ico_file"
[HKEY_CLASSES_ROOT\pyfig_auto_file\shell]
[HKEY_CLASSES_RO... | 0 | 2016-10-10T12:44:41Z | [
"python",
"matplotlib",
"save",
"interactive",
"figure"
] |
indent is broken after saving back updated json dict to file | 39,914,524 | <p>I have a nested dictionary with many items in a json file:</p>
<pre><code>{
"Create Code For Animals": {
"mammals": {
"dog": {
"color": "brown",
"name": "John",
"legs": "four",
"tail": "yes"
},
"cat": {
"color": "blue",
... | 4 | 2016-10-07T09:59:49Z | 39,914,589 | <p>json.dumps and dump have a parameter called indent</p>
<pre><code>If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation. Since the de... | 4 | 2016-10-07T10:02:31Z | [
"python",
"json",
"dictionary"
] |
How to convert "\uxxxx\uxxxx" to u'\Uxxxxxxxx'? | 39,914,531 | <p>I have a text file who is filled with unicode characters as <code>"\ud83d\udca5"</code> but python don't seem to like them.<br>
But if I replace it by <code>u'\U0001f4a5'</code> which seems to be his python escape style (<a href="http://www.charbase.com/1f4a5-unicode-collision-symbol" rel="nofollow">Charbase</a>), i... | 0 | 2016-10-07T10:00:12Z | 39,915,220 | <p>You're mixing up Unicode and encoded strings. <code>u'\U0001f4a5'</code> is a Unicode object, Python's internal datatype for handling strings. (In Python 3, the <code>u</code> is optional since now <em>all</em> strings are Unicode objects).</p>
<p>Files, on the other hand, use encodings. UTF-8 is the most common on... | 0 | 2016-10-07T10:35:13Z | [
"python",
"python-3.x",
"unicode",
"escaping",
"unicode-escapes"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.