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 |
|---|---|---|---|---|---|---|---|---|---|
In python 3 print() command to print chr with ascii directly under in a complete table | 38,112,455 | <p>I am very new to python and want to use it as retirement project. However I have a lot of trouble trying to print a table in the format below. I only will show the ascii table as below, in what I'm trying to achieve</p>
<pre><code>chr: ! " # $ % & ' ( ) * + , - . /
asc: 32 33 ... | 0 | 2016-06-30T01:15:06Z | 38,112,810 | <p>Not at all a pythonic or elegant solution by any stretch of the imagination, but building upon what you already have:</p>
<pre><code>print('chr:',end='')
for asc in range(32,48):
print('{:>4}'.format(chr(asc)),end='')
print()
print('asc:',end='')
for asc in range(32,48):
print('{:>4}'.format(ord(chr(a... | 0 | 2016-06-30T02:03:40Z | [
"python",
"python-3.x"
] |
In python 3 print() command to print chr with ascii directly under in a complete table | 38,112,455 | <p>I am very new to python and want to use it as retirement project. However I have a lot of trouble trying to print a table in the format below. I only will show the ascii table as below, in what I'm trying to achieve</p>
<pre><code>chr: ! " # $ % & ' ( ) * + , - . /
asc: 32 33 ... | 0 | 2016-06-30T01:15:06Z | 38,112,837 | <p>First of all why you are doing <code>ord(chr(asc))</code> in above code snippets. It simply means <code>asc</code> variable. Now, coming to your solution, you can first convert you <code>chr</code> and <code>ord</code> to string by using <code>str()</code> then you can apply <code>ljust()</code> or <code>rjust()</co... | 0 | 2016-06-30T02:06:51Z | [
"python",
"python-3.x"
] |
Extract an item from a JSON response | 38,112,562 | <p>I'm new to Python and JSON.</p>
<p>I'm getting the following response from <a href="http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=11554" rel="nofollow">Google Maps API</a>:</p>
<pre><code>{
"status": "OK",
"results": [
{
"geometry": {
"locati... | 0 | 2016-06-30T01:30:20Z | 38,112,607 | <p>So you have <code>print 'Country:', country</code>, </p>
<p>where <code>country= [{u'long_name': u'United States', u'types': [u'country', u'political'], u'short_name': u'US'}]</code>, so that is a list of one element. </p>
<p><code>country[0]['short_name]'</code> should give you <code>'US'</code></p>
<p>If you do... | 1 | 2016-06-30T01:35:28Z | [
"python",
"json"
] |
Accessing instance variable from other instance in python | 38,112,567 | <p>I'm trying to find the best way of accessing an instance variable from another instance. So far I've been able to pass that variable as an argument and save it in the new instance. But im wondering if there is some sort of "Global" variable that will work best. Specially if the classes are from different modules.<... | 0 | 2016-06-30T01:30:48Z | 38,112,701 | <p>It's possible to use global variables in python. </p>
<pre><code>class A(object):
def __init__(self):
global globalObject
globalObject = "Global Object"
self.listB = self.generateBList()
def generateBList(self):
return [B(i) for i in range(10)]
class B(object):
d... | 0 | 2016-06-30T01:47:32Z | [
"python"
] |
Accessing instance variable from other instance in python | 38,112,567 | <p>I'm trying to find the best way of accessing an instance variable from another instance. So far I've been able to pass that variable as an argument and save it in the new instance. But im wondering if there is some sort of "Global" variable that will work best. Specially if the classes are from different modules.<... | 0 | 2016-06-30T01:30:48Z | 38,112,822 | <p>Your example seems unnecessarily complicated, so I'll try to illustrate one way I've used before that I think may do what you want. If you think of creating a "world" that is the stage for what you want to happen, you can have each class instance inside the world, know the world. Like this:</p>
<pre><code>class T... | 0 | 2016-06-30T02:05:24Z | [
"python"
] |
Get all columns in a numpy structured array. | 38,112,588 | <p>I would like to slice a numpy structured array.
I have an array </p>
<pre><code>>>b
>>array([([11.0, 21.0, 31.0, 0.01], [1.0, 2.0, 3.0, 0.0]),
([41.0, 51.0, 61.0, 0.11], [4.0, 5.0, 6.0, 0.1]),
([71.0, 81.0, 91.0, 0.21], [7.0, 8.0, 9.0, 0.2])],
dtype=[('fd', '<f8', (4,)), ('av',... | 1 | 2016-06-30T01:32:47Z | 38,112,800 | <p>You access the fields of a structured array by field name. There isn't a way around this. Unless the dtypes let you view it in a different way.</p>
<p>Lets call your desire output <code>c</code>.</p>
<pre><code>In [1061]: b['fd']
Out[1061]:
array([[ 1.10000000e+01, 2.10000000e+01, 3.10000000e+01,
... | 2 | 2016-06-30T02:01:37Z | [
"python",
"arrays",
"numpy"
] |
Unable to fetch 20 NewsGroups dataset in Scikit-Learn | 38,112,650 | <p>I trying to fetch this datasets using the codes below.</p>
<pre><code>from sklearn.datasets import fetch_20newsgroups
twenty_train = fetch_20newsgroups(subset='train')
</code></pre>
<p>However, an error had occurred after this. The program is then killed.</p>
<pre><code>No handlers could be found for logger "skle... | 1 | 2016-06-30T01:40:41Z | 38,115,741 | <p>This looks like that scikit-learn is trying to report some error and you have not configured, where your output goes. Even I had the exact same problem when I tried your code. I fixed it by setting up my logger:</p>
<pre><code>import logging
logging.basicConfig()
</code></pre>
<p>Now trying to load the dataset giv... | 0 | 2016-06-30T06:45:50Z | [
"python",
"dataset",
"scikit-learn"
] |
How to iterate every 10 lines on CSV file | 38,112,729 | <pre><code>with open(example.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
Do something.
</code></pre>
<p>I need to skip every 10 lines in for loop, but doing readCSV[::10] won't work.</p>
| 0 | 2016-06-30T01:51:05Z | 38,112,765 | <pre><code>with open('example.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for i, row in enumerate(readCSV):
if i % 10 == 0:
# do stuff with every 10th row
</code></pre>
| 1 | 2016-06-30T01:55:48Z | [
"python",
"csv",
"for-loop"
] |
How to iterate every 10 lines on CSV file | 38,112,729 | <pre><code>with open(example.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
Do something.
</code></pre>
<p>I need to skip every 10 lines in for loop, but doing readCSV[::10] won't work.</p>
| 0 | 2016-06-30T01:51:05Z | 38,112,768 | <p>Keep track of the index with an iterator</p>
<pre><code>with open(example.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
i = 0
for row in readCSV:
if i%10 = 0:
continue
Do something.
i += 1
</code></pre>
| 0 | 2016-06-30T01:56:00Z | [
"python",
"csv",
"for-loop"
] |
How to iterate every 10 lines on CSV file | 38,112,729 | <pre><code>with open(example.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
Do something.
</code></pre>
<p>I need to skip every 10 lines in for loop, but doing readCSV[::10] won't work.</p>
| 0 | 2016-06-30T01:51:05Z | 38,112,774 | <p>You could add this to </p>
<pre><code>count = 0
for line in f:
count+=1
if count % 10 == 0:
print line
</code></pre>
| 0 | 2016-06-30T01:57:07Z | [
"python",
"csv",
"for-loop"
] |
How to iterate every 10 lines on CSV file | 38,112,729 | <pre><code>with open(example.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
Do something.
</code></pre>
<p>I need to skip every 10 lines in for loop, but doing readCSV[::10] won't work.</p>
| 0 | 2016-06-30T01:51:05Z | 38,112,966 | <p>This boils down to iterating over every 10<sup>th</sup> element from a generator, which can be done with <code>itertools.islice</code>:</p>
<pre><code>import itertools
import csv
with open('example.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in itertools.islice(readCSV, None, No... | 1 | 2016-06-30T02:22:56Z | [
"python",
"csv",
"for-loop"
] |
error during Web scraping using python | 38,112,747 | <p>i tried to scraping reply in news.</p>
<p>i tried tried many time.</p>
<p>but i can see only Traceback.</p>
<p>please help me.</p>
<p>i wrote code like this:</p>
<pre><code>import re
import urllib.request
import urllib
import requests
from bs4 import BeautifulSoup
url='http://news.naver.com/main/ranking/read.n... | 0 | 2016-06-30T01:53:04Z | 38,113,979 | <p>Following @AkshatMahajan advise, the below can be done using requests module instead.
In addition, you can also modify the last line to find the desired element. </p>
<pre><code>##import re
##import urllib.request
##import urllib
import requests
from bs4 import BeautifulSoup
url='http://news.naver.com/main/rankin... | 3 | 2016-06-30T04:26:23Z | [
"python",
"web-scraping",
"urllib",
"trackback"
] |
How to use Pyinstaller - cx_Freeze executable sys.MEIPASS/sys.executable | 38,112,752 | <p>I've been working on getting a python executable working for OSX El Capitan, and i successfully get the executable built using both Pyinstaller and cx_Freeze, the issue comes when i actually run the executable on another mac. The error i get is about not being able to find the .db file referenced in my main script, ... | 1 | 2016-06-30T01:54:00Z | 38,965,739 | <p>if you are trying to access any data file you specified in the .spec file, in your code, you must use Pyinstaller's _MEIPASS folder to reference your file. Here is how i did so with the file named Data.db:</p>
<pre><code>import sys
import os.path
if hasattr(sys, "_MEIPASS"):
datadir = os.path.j... | 0 | 2016-08-16T02:23:46Z | [
"python",
"executable",
"pyinstaller",
"cx-freeze"
] |
How do I access packages installed by `pip --user`? | 38,112,756 | <p>I realized I had an outdated numpy version:</p>
<pre><code>$ python
Python 2.7.10 (default, Oct 23 2015, 18:05:06)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> np.version.full_... | 0 | 2016-06-30T01:54:38Z | 38,112,757 | <p>As per <a href="https://docs.python.org/3/install/index.html#alternate-installation-the-user-scheme" rel="nofollow">the Python docs</a>, this is installing using the "user scheme":</p>
<blockquote>
<p>Files will be installed into subdirectories of <a href="https://docs.python.org/3/library/site.html#site.USER_BAS... | 0 | 2016-06-30T01:54:38Z | [
"python",
"pip",
"packages"
] |
Iterate thru ec2 describe instance boto3 | 38,112,770 | <p>I just started working with boto3 and trying to get specific values for a describe instance call. So for example, if I want to get the 'Hypervisor' value or the Ebs has 'DeleteOnTermintation' value from the output. Below is the current code I am currently using to make the call and iterate thru the dictionary output... | 0 | 2016-06-30T01:56:15Z | 38,157,300 | <p>Here's how you could display the information via the <a href="http://aws.amazon.com/cli/" rel="nofollow">AWS Command-Line Interface (CLI)</a>:</p>
<pre><code>aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId, Hypervisor, NetworkInterfaces[0].Attachment.DeleteOnTermination]'
</code></pre>
... | 1 | 2016-07-02T06:41:25Z | [
"python",
"amazon-ec2"
] |
Shutil multiple files after reading with "pydicom" | 38,112,799 | <p>What I basicalling want is for myvar to vary between 1-280 so that I can use this to read the file using pydicom. I.e. I want to read the files between /data/lfs2/model-mie/inputDataTest/subj2/mp2rage/<strong>0-280</strong>_tfl3d1.IMA. Then if M is true in gender then I want to shutil them into a folder. Doesnt seem... | 0 | 2016-06-30T02:01:36Z | 38,146,444 | <p>I think the <code>range()</code> function should do what you want, something like this:</p>
<pre><code>import shutil
from pydicom import dicomio
for i in range(281):
filename = "/data/lfs2/model-mie/inputDataTest/subj2/mp2rage/" + str(i) + "_tfl3d1.IMA"
ds = dicomio.read_file(filename)
if ds.get('Patie... | 1 | 2016-07-01T13:15:47Z | [
"python"
] |
Urllib bad request issue | 38,112,806 | <p>I tried every <code>'User-Agent'</code> in <a href="http://wolfprojects.altervista.org/articles/change-urllib-user-agent/" rel="nofollow">here</a>, still I get <code>urllib.error.HTTPError: HTTP Error 400: Bad Request</code>. I also tried <a href="http://stackoverflow.com/questions/26894320/again-urllib-error-httper... | 1 | 2016-06-30T02:03:21Z | 38,116,405 | <p>A quick fix is to replace the space with <code>+</code>:</p>
<pre><code>url = "http://www.game-debate.com"
r = urllib.request.Request(url + x[2:] ,headers={'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'})
</code></pre>
<p>A better option may be to let urll... | 1 | 2016-06-30T07:21:17Z | [
"python",
"beautifulsoup",
"python-3.4",
"urllib",
"bad-request"
] |
Adding entries from python dictionary based on key | 38,112,820 | <p>If I have a Python dictionary such as </p>
<pre><code>my_dict = {1:4, 2: 9, 3: 17, 4: 27, 5: 51, 6: 129, 7: 285, 8: 533}
</code></pre>
<p>how can I iterate through it to produce a count based on keys in the following way: </p>
<p>If my key is smallest i.e. 1, then return 4/sum(values) [I know how to compute this]... | 0 | 2016-06-30T02:05:08Z | 38,113,211 | <p>Try this:</p>
<pre><code>count_to_key = {
k: sum(vi for ki, vi in my_dict.items()
if ki <= k) / sum(my_dict.values())
for k in my_dict.keys()}
</code></pre>
| 0 | 2016-06-30T02:54:17Z | [
"python",
"dictionary"
] |
How to copy lines from several files base on conditions in python? | 38,113,018 | <p>I am coding a little python scrpit to grab lines from several files according to a config file. </p>
<p>Config file looks like this:</p>
<pre><code>[BeginObjects]
apple
banana
[EndObjects]
[BeginFiles]
path/fileA
path/fileB
[EndFiles]
</code></pre>
<p>Each of other files looks like this:</p>
<pre><code>some line... | 0 | 2016-06-30T02:31:23Z | 38,113,220 | <pre><code>Tag = False
for line in infile:
for item in itemObj:
if line.find("ObjectAlias " + item + "\n") !=-1:
Tag = True
if Tag:
dummy += line
if line.find("End") != -1:
Tag = False
</code></pre>
<p>You just need to change your if statement </p>
| -1 | 2016-06-30T02:55:19Z | [
"python",
"python-2.7"
] |
How to copy lines from several files base on conditions in python? | 38,113,018 | <p>I am coding a little python scrpit to grab lines from several files according to a config file. </p>
<p>Config file looks like this:</p>
<pre><code>[BeginObjects]
apple
banana
[EndObjects]
[BeginFiles]
path/fileA
path/fileB
[EndFiles]
</code></pre>
<p>Each of other files looks like this:</p>
<pre><code>some line... | 0 | 2016-06-30T02:31:23Z | 38,113,467 | <p>The easiest way to check this is with <code>if ... in ...</code>, like so:</p>
<pre><code>if "[BeginObjects]" in line:
print "We found the string '[BringObjects]'"
</code></pre>
| 0 | 2016-06-30T03:23:39Z | [
"python",
"python-2.7"
] |
Calculate F-distribution p values in python? | 38,113,120 | <p>Suppose that I have an F value and the associated degrees of freedom, df1 and df2. How can I use python to programmatically calculate the p value associated with these numbers?</p>
<p>Note: I would not accept a solution using scipy or statsmodels.</p>
| 1 | 2016-06-30T02:42:46Z | 38,148,563 | <p>The CDF for the F-distribution (and hence the p-value) can be calculated with the regularized (incomplete) beta function <code>I(x; a, b)</code>, see, e.g., <a href="http://mathworld.wolfram.com/F-Distribution.html" rel="nofollow">MathWorld</a>. Using the code for <code>I(x; a, b)</code> from this <a href="https://... | 1 | 2016-07-01T15:00:02Z | [
"python",
"math",
"statistics",
"probability"
] |
Assign value by comparison of different lists with different numbers of member | 38,113,142 | <p>I am a totally beginner on programming language including python and this problem kind of difficult for me.
Appreciate if you guys can help me.</p>
<p>So I have these two list of list:</p>
<pre><code>S = [[D, 0.67, 0.05], [A, 0.68, 0.06], [C, 2.00, 0.13], [B, 0.68, 0.39], [E, 1.28, 0.97], [F, 0.72, 1.05], [I, 0.58... | 0 | 2016-06-30T02:46:09Z | 38,113,512 | <p>This works:</p>
<pre><code>def maximum(arr):
x = arr[0]
for x1 in arr:
x = x1 if x1[2] > x[2] else x
return x
def foo(x, arr):
x1 = maximum(filter(lambda x2: x2[2] <= x[2], arr))
return (1/x[2])/(1/x1[2])
result = [[x[0], foo(x, R)] for x in S]
</code></pre>
<p>The idea here is ... | 0 | 2016-06-30T03:31:17Z | [
"python",
"list",
"comparison",
"value"
] |
How to construct a numpy array with multilple same timestamp? | 38,113,159 | <p>I have tried:</p>
<pre><code>import numpy as np
t = np.full((10),'2012-12-10', dtype=np.datetime64)
</code></pre>
<p>But got such an error:</p>
<pre><code>ValueError: Cannot create a NumPy datetime other than NaT with generic units
</code></pre>
<p>Do you have any idea? Thanks!</p>
| 0 | 2016-06-30T02:48:04Z | 38,113,253 | <p>EDIT: I figured it out, you must fully specify the datatype for datetime objects</p>
<p>Do this</p>
<pre><code>np.full((10), '2012-12-10', dtype='datetime64[D]')
array(['2012-12-10', '2012-12-10', '2012-12-10', '2012-12-10',
'2012-12-10', '2012-12-10', '2012-12-10', '2012-12-10',
'2012-12-10', '2012... | 1 | 2016-06-30T02:58:46Z | [
"python",
"arrays",
"numpy",
"timestamp"
] |
Python for loop dropping after 1 iteration | 38,113,186 | <p>I am new to python and thought I would practice what I have been learning to complete a little task. Essentially I am inserting a cognimatic cameras data into a database from a .csv file that I pulled from the web. sadly I have had to omit all the connection details as it can only be accessed from my works computer ... | 0 | 2016-06-30T02:51:54Z | 38,113,313 | <p>Have you tried to do something like</p>
<pre><code>queryResult = camCursor.execute("SELECT * FROM dbo.CAMERAS")
for rows in queryResult:
...
</code></pre>
<p>I guess this might solve the problem, which is probably the fact that you're trying to iterate over a cursor instead of the results.</p>
<p>You might f... | 0 | 2016-06-30T03:04:54Z | [
"python"
] |
Is there any way to use gcloud with python3? | 38,113,281 | <p>I have a little confused about gcloud with python3</p>
<p>After I installed gcloud in python3 env and I tried to example <a href="https://cloud.google.com/python/getting-started/hello-world" rel="nofollow">Quickstart for Python in the App Engine Flexible Environment</a>.</p>
<p>It said 'You need Google Cloud SDK',... | 2 | 2016-06-30T03:02:03Z | 38,114,536 | <p>The system requirement explicitly said python 2.7.x <a href="https://cloud.google.com/sdk/downloads" rel="nofollow">https://cloud.google.com/sdk/downloads</a></p>
<p>why do you want to run gcloud with python3 anyway?</p>
| 1 | 2016-06-30T05:21:01Z | [
"python",
"google-app-engine",
"google-cloud-platform",
"gcloud"
] |
Is there any way to use gcloud with python3? | 38,113,281 | <p>I have a little confused about gcloud with python3</p>
<p>After I installed gcloud in python3 env and I tried to example <a href="https://cloud.google.com/python/getting-started/hello-world" rel="nofollow">Quickstart for Python in the App Engine Flexible Environment</a>.</p>
<p>It said 'You need Google Cloud SDK',... | 2 | 2016-06-30T03:02:03Z | 38,121,707 | <p><a href="https://github.com/GoogleCloudPlatform/gcloud-python" rel="nofollow">gcloud-python</a> and <a href="https://cloud.google.com/sdk/docs/" rel="nofollow">gcloud-cli as in Cloud SDK</a> are somewhat unrelated products. It is true that you need python 2.7.x to run gcloud-cli, but that does no preclude you from u... | 0 | 2016-06-30T11:24:17Z | [
"python",
"google-app-engine",
"google-cloud-platform",
"gcloud"
] |
Unable to run my codes to make NAO move | 38,113,287 | <p>I have create a simple code using Python SDK version 2.7. I am trying to connect it to the simulated robot in choregraphe but the codes are unable to run with this error.</p>
<p>This is my codes:</p>
<pre><code>from naoqi import ALProxy
motion = ALProxy("ALMotion", "127.0.0.1", 9559)
motion.moveInit()
motion.moveT... | 0 | 2016-06-30T03:02:26Z | 38,135,703 | <p>I suppose you mean Python 2.7, not the SDK. What Version of Naoqi Python SDK are you using?</p>
<p>Also, what simulated robot are you trying to use? If it is the one included in Choregraphe, you simply can't connected it externally without launching choregraphe. That Simulated robot is initiated at Choregraphe star... | 0 | 2016-07-01T01:30:37Z | [
"python",
"python-2.7",
"nao-robot"
] |
Unable to run my codes to make NAO move | 38,113,287 | <p>I have create a simple code using Python SDK version 2.7. I am trying to connect it to the simulated robot in choregraphe but the codes are unable to run with this error.</p>
<p>This is my codes:</p>
<pre><code>from naoqi import ALProxy
motion = ALProxy("ALMotion", "127.0.0.1", 9559)
motion.moveInit()
motion.moveT... | 0 | 2016-06-30T03:02:26Z | 38,836,782 | <p>The error is just that the IP:port is not connecting to any robot. </p>
<p>If you want to connect to:</p>
<ul>
<li>the real robot: use the ip of the robot (press the chest button to get it) and port 9559</li>
<li>the Choregraphe simulated robot: use 127.0.0.1 and check in the Choregraphe connection menu to get the... | 0 | 2016-08-08T19:08:33Z | [
"python",
"python-2.7",
"nao-robot"
] |
The better way to perform subtraction of 3-dimensional array in numpy | 38,113,345 | <p>I would like to know a better alternative way to perform subtraction on three dimensional array.
Currently I'm using <code>np.array([x for x in xs])</code> to perform subtraction on each first axis like: </p>
<pre class="lang-python prettyprint-override"><code>import numpy as np
# ===============================... | 0 | 2016-06-30T03:09:13Z | 38,113,376 | <pre><code>coords2 = coords - centers[:, np.newaxis]
</code></pre>
<p>Take a view of <code>centers</code> with an extra length-1 axis in the middle to make the shapes line up right for broadcasting.</p>
| 2 | 2016-06-30T03:13:23Z | [
"python",
"arrays",
"numpy"
] |
How do you pass an encoding to odo when loading a csv file? | 38,113,403 | <p>The odo documentation is quite sparse, it does not explain how to pass further parameters when, say loading a csv file. For example, how do I tell odo that the file is latin1 encoded?</p>
<pre><code>data=[]
odo('mylatin1.csv',data)
</code></pre>
| 0 | 2016-06-30T03:16:12Z | 38,133,740 | <p>Try using the <code>encoding</code> keyword argument:</p>
<pre><code>data = []
odo('mylatin1.csv', data, encoding='latin1')
</code></pre>
<p>Alternatively, try specifying the encoding using <code>odo.resource</code>:</p>
<pre><code>from odo import resource
my_csv = resource('mylatin1.csv', encoding='latin1')
dat... | 1 | 2016-06-30T21:42:22Z | [
"python",
"blaze",
"odo"
] |
getattr on a decorated method generates a TypeError | 38,113,411 | <p>I needed memoization to be applied at an instance level, so I used the following decorator:</p>
<pre><code>from functools import partial, update_wrapper
class memoize(object):
def __init__(self, func):
self.func = func
update_wrapper(self, func)
def __get__(self, obj):
if obj is No... | 0 | 2016-06-30T03:17:24Z | 38,113,583 | <p><code>getattr</code> was passing the following arguments to <code>memoize</code>'s <code>__get__</code>:</p>
<pre><code>* `self`
* `None`
* `<class '__main__.A'>`
</code></pre>
<p>That was what was causing the errors. To fix it:</p>
<pre><code>def __get__(self, instance, owner):
if instance is None:
... | 0 | 2016-06-30T03:39:34Z | [
"python",
"python-2.7",
"decorator",
"python-3.5",
"python-decorators"
] |
Password is not created to specified length? | 38,113,413 | <p>I am creating a random password generator that takes in a user specified length but I have not been able to create the function in a way that it will make the password exactly that length. I have only been able to do it to multiples of 4 because of the 4 variables I have created. If i was to call the function with a... | 0 | 2016-06-30T03:17:55Z | 38,113,477 | <p>How about this:</p>
<pre><code>numbers = '1234567890'
letters = 'qwertyuiopasdfghjklzxcvbnm'
letters_caps = 'QWERTYUIOPLKJHGFDSAZXCVBNM'
symbols = '!@#$%^&*()_+=~`:"<>?|\;,."`'
import random
raw_psw = numbers + letters + letters_caps + symbols
raw_psw = list(raw_psw)
length = 10
for _ in range(5):
... | 1 | 2016-06-30T03:25:41Z | [
"python"
] |
Password is not created to specified length? | 38,113,413 | <p>I am creating a random password generator that takes in a user specified length but I have not been able to create the function in a way that it will make the password exactly that length. I have only been able to do it to multiples of 4 because of the 4 variables I have created. If i was to call the function with a... | 0 | 2016-06-30T03:17:55Z | 38,113,709 | <p>Just for pass time:</p>
<pre><code>class PasswordGenerator(object):
def __init__(self, alphabet_classes, r=None):
from random import SystemRandom
self.__alphabet_classes = alphabet_classes
self.__random = r if r else SystemRandom()
def generate(self, length):
password = []
... | 0 | 2016-06-30T03:55:01Z | [
"python"
] |
Password is not created to specified length? | 38,113,413 | <p>I am creating a random password generator that takes in a user specified length but I have not been able to create the function in a way that it will make the password exactly that length. I have only been able to do it to multiples of 4 because of the 4 variables I have created. If i was to call the function with a... | 0 | 2016-06-30T03:17:55Z | 38,113,850 | <p>If you're just concerned about the length and are otherwise happy with your function, the simplest solution would be to round up to the next multiple of four, and then truncate the password before returning it, like:</p>
<pre><code>def create_password(leng):
password = ''
for i in range((leng + 3) // 4):
... | 1 | 2016-06-30T04:09:57Z | [
"python"
] |
Password is not created to specified length? | 38,113,413 | <p>I am creating a random password generator that takes in a user specified length but I have not been able to create the function in a way that it will make the password exactly that length. I have only been able to do it to multiples of 4 because of the 4 variables I have created. If i was to call the function with a... | 0 | 2016-06-30T03:17:55Z | 38,114,038 | <p>Perhaps the least intrusive change would be to loop exactly the number of times you specify, and call a different function depending on the modulo.</p>
<pre><code>for i in range(leng):
mod = i % 4
if mod == 0:
randitem = numbers[random.randrange(0, len(numbers))]
elif mod == 1:
randitem ... | 0 | 2016-06-30T04:32:50Z | [
"python"
] |
Python : sys.getsizeof vaue of numpy ndarray seems too small | 38,113,549 | <pre><code>import sys
npArrayList = 20000 * [None]
npNdArray = np.random.normal(size = (20000, 4))
for i in xrange(20000):
npArrayList[i] = npNdArray[i, ]
if i == 0:
print 'npArrayList[i].nbytes = ' + str(npArrayList[i].nbytes)
print 'npArrayList size = ' + str(sys.getsizeof(npArrayList))
print 'npNdAr... | 0 | 2016-06-30T03:35:32Z | 38,113,645 | <p>As per the <a href="https://docs.python.org/3.5/library/sys.html#sys.getsizeof" rel="nofollow">documentation</a>, <code>sys.getsizeof</code> does the following:</p>
<blockquote>
<p>Return the size of an object in bytes. The object can be any type of
object. All built-in objects will return correct results, but ... | 1 | 2016-06-30T03:46:58Z | [
"python",
"numpy"
] |
Python: Nested dictionaries: getting string(key+value) as values then swap with keys, combining dictionaries | 38,113,585 | <p>Say I have this 3 dictionaries:</p>
<pre><code>d1 = {'Ben': {'Skill': 'true', 'Magic': 'false'}, 'Tom': {'Skill': 'true', 'Magic': 'true'}}
d2 = {'Ben': {'Strength': 'wo_mana', 'Int': 'wi_mana', 'Speed': 'wo_mana'}, 'Tom': {'Int': 'wi_mana', 'Agility': 'wo_mana'}}
d3 = {'Ben': {'Strength': '1.10', 'Int': '1.20', 'S... | 1 | 2016-06-30T03:39:51Z | 38,114,092 | <p>This could do the trick:</p>
<pre><code>d4 = {}
for k, v in d2.items():
d4[k] = {}
for k2, v2 in v.items():
try:
if v2 not in d4[k]:
d4[k][v2] = [k2 + ' = ' + d3[k][k2]]
else:
d4[k][v2].append(k2 + ' = ' + d3[k][k2])
except KeyError:
# this means k2 is a typo in d2; s... | 1 | 2016-06-30T04:39:29Z | [
"python",
"python-2.7",
"dictionary"
] |
Python: Nested dictionaries: getting string(key+value) as values then swap with keys, combining dictionaries | 38,113,585 | <p>Say I have this 3 dictionaries:</p>
<pre><code>d1 = {'Ben': {'Skill': 'true', 'Magic': 'false'}, 'Tom': {'Skill': 'true', 'Magic': 'true'}}
d2 = {'Ben': {'Strength': 'wo_mana', 'Int': 'wi_mana', 'Speed': 'wo_mana'}, 'Tom': {'Int': 'wi_mana', 'Agility': 'wo_mana'}}
d3 = {'Ben': {'Strength': '1.10', 'Int': '1.20', 'S... | 1 | 2016-06-30T03:39:51Z | 38,114,451 | <p>Here's how you can do this:</p>
<pre><code>d1 = {'Ben': {'Skill': 'true', 'Magic': 'false'},
'Tom': {'Skill': 'true', 'Magic': 'true'}}
d2 = {'Ben': {'Strength': 'wo_mana', 'Int': 'wi_mana', 'Speed': 'wo_mana'},
'Tom': {'Int': 'wi_mana', 'Agility': 'wo_mana'}}
d3 = {'Ben': {'Strength': '1.10', 'Int'... | 1 | 2016-06-30T05:14:13Z | [
"python",
"python-2.7",
"dictionary"
] |
How to pass multiple params in Fn when I using Python map(Fn, Iterable)? | 38,113,711 | <p>As for <code>map(Fn, Iterable)</code>, my <code>Fn()</code> is fllowing:</p>
<pre><code>def Fn(x, k):
return x+k
</code></pre>
<p>But, if I want to use the <code>Fn()</code> in <code>map()</code>, the code could not like this:</p>
<pre><code>map(Fn(Iterable, k), Iterable)
</code></pre>
<p>It means that how c... | 0 | 2016-06-30T03:55:13Z | 38,114,069 | <p>Here are some possibilities</p>
<pre><code>def fn(x,k):
return x+k
In [1095]: k=10 # in global space
In [1096]: map(lambda x: fn(x,k), [1,2,3])
Out[1096]: <map at 0xb263e04c> # ops, py3, need
In [1097]: list(map(lambda x: fn(x,k), [1,2,3]))
Out[1097]: [11, 12, 13]
</code></pre>
<p>I prefer list com... | 0 | 2016-06-30T04:36:34Z | [
"python",
"dictionary"
] |
YouTube Python Mortgage Calculator (Zero to Hero) | 38,113,840 | <p>This is a code I got off the Zero to Hero with Python programming tutorial off YouTube to calculate a mortgage. I'm trying to understand why this code isn't giving me the same answers I'm getting using other payment calculators. I know there are other codes that will give me the correct answer, but I'm trying to fig... | 1 | 2016-06-30T04:08:47Z | 38,114,072 | <p>I used a similar [post's][1] answer for the following code: </p>
<pre><code># M = L[i(1+i)n]/[(1+i)n-1]
#Declare and initialize the variables
monthlyPayment = 0.0
loanAmount = 0.0
interestRate = 0.0
numberOfPayments = 0.0
loanDurationInYears = 0.0
#Ask the user for the values needed to calculate the monthly paym... | 0 | 2016-06-30T04:36:55Z | [
"python",
"youtube"
] |
Flask: Restarting with reloader can't find file | 38,113,842 | <p>I'm trying to learn flask. I've created a virtual environment (venv) in my project directory (C:\users\ian\git\flasktutorial). FLASK_APP is set to flasktutorial, FLASK_DEBUG=1, and I do have a flasktutorial.py in the directory.</p>
<p>When I type "flask run" I get the following:</p>
<pre><code>* Serving Flask app ... | 0 | 2016-06-30T04:09:04Z | 38,198,782 | <p>Run flask as a module, then the reloader will work on Windows:</p>
<pre><code>python -m flask run
</code></pre>
<p>Explanation:</p>
<p>When starting the app in Windows with <code>flask.exe</code> then the reloader constructs wrong args for the new subprocess. Source code <a href="https://github.com/pallets/werkze... | 1 | 2016-07-05T08:36:44Z | [
"python",
"flask",
"virtualenv"
] |
Button not printing anything | 38,113,854 | <p>I created a function for my button. I am trying to get it to run through once per click so I integrated the lines 'for event in pygame.event.get() and pygame.MOUSEBUTTONDOWN so it will register one click, run through once and then stop until next click. But now it doesn't work at all.
1. how do i get it to run
2. ho... | 0 | 2016-06-30T04:10:34Z | 38,143,327 | <p>You don't want to check the event queue inside the Button function, but rather somewhere in your main game loop and then call the Button function if a click has occured. It also looks to me like the Button function you have there might be more sensibly implemented as a Button class with different methods, such as <c... | 0 | 2016-07-01T10:40:48Z | [
"python",
"button",
"pygame"
] |
py2exe compiling error : invalid syntax (_socket3.py, line 183) | 38,113,926 | <p>i am trying to compile a python application in single exe.
i am using python 2.7 and py2exe.</p>
<p>modules used in my application</p>
<ul>
<li>PyQt4</li>
<li>Pymongo</li>
<li>Psutil</li>
</ul>
<p>when i start compiling i am getting following error :</p>
<pre><code>*** searching for required modules ***
error: c... | 2 | 2016-06-30T04:19:26Z | 38,447,679 | <p>Version 1.1.1 of gevent contains file <em>_socket3.py</em> that is for python 3. With a python 2.7 compatible py2exe compiling <em>_socket3.py</em> to <em>_socket3.pyc</em> will fail.</p>
<p>gevent package should probably be fixed so that it does not install _socket3.py file for python 2.7</p>
<p>As a workaround t... | 1 | 2016-07-19T00:06:52Z | [
"python",
"python-2.7",
"py2exe"
] |
is there a way to print the output to stdout and capture as well? | 38,113,964 | <p>I am executing a command which takes around 15mins, I capture the output through <code>fetchPipe.communicate</code> and then print it. Is there a way in Python to print the output to stdout and capture as well?</p>
<pre><code> fetchPipe = subprocess.Popen(cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess... | 0 | 2016-06-30T04:24:26Z | 38,114,230 | <p>Yes. An example for that could be using a listener function: Writing to stdout and triggering something upon line recieve</p>
<pre><code>import sys
import subprocess
import threading
</code></pre>
<p>The listener </p>
<pre><code>def listener(proc):
for line in proc.stdout:
sys.stdout.write(line)
... | 2 | 2016-06-30T04:53:47Z | [
"python"
] |
Why does indexing numpy arrays with brackets and commas differ in behavior? | 38,113,994 | <p>I tend to index numpy arrays (matrices) with brackets, but I've noticed when I want to slice an array (matrix) I must use the comma notation. Why is this? For example,</p>
<pre><code>>>> x = numpy.array([[1, 2], [3, 4], [5, 6]])
>>> x
array([[1, 2],
[3, 4],
[5, 6]])
>>> x[1]... | 2 | 2016-06-30T04:27:53Z | 38,114,048 | <p>This:</p>
<pre><code>x[:, 1]
</code></pre>
<p>means "take all indices of <code>x</code> along the first axis, but only index 1 along the second".</p>
<p>This:</p>
<pre><code>x[:][1]
</code></pre>
<p>means "take all indices of <code>x</code> along the first axis (so all of <code>x</code>), then take index 1 alon... | 6 | 2016-06-30T04:34:03Z | [
"python",
"numpy",
"indexing",
"slice"
] |
Why does indexing numpy arrays with brackets and commas differ in behavior? | 38,113,994 | <p>I tend to index numpy arrays (matrices) with brackets, but I've noticed when I want to slice an array (matrix) I must use the comma notation. Why is this? For example,</p>
<pre><code>>>> x = numpy.array([[1, 2], [3, 4], [5, 6]])
>>> x
array([[1, 2],
[3, 4],
[5, 6]])
>>> x[1]... | 2 | 2016-06-30T04:27:53Z | 38,114,143 | <p>When you slide multi dimension of array, if fewer indices are provided than the number of axes, the missing indices are considered complete slices.
Hence, when you are essentially doing when calling <code>x[:][1]</code> is <code>x[:,:][1,:]</code>
Therefore, <code>x[:,:]</code> will just return x itself.</p>
| 0 | 2016-06-30T04:45:16Z | [
"python",
"numpy",
"indexing",
"slice"
] |
Python Google App Engine import error | 38,114,021 | <p>When i am trying to follow the on-line python course to implement demo project,i got problems in importing errors.so,here is what i have done
I use Google App Engine to run the server,and my python version is 2.7.
here is my server dir </p>
<pre><code>D:\PJ\Udacity\Python\engineapp
</code></pre>
<p>my program is e... | 0 | 2016-06-30T04:30:34Z | 38,119,014 | <p>The webapp2 you are trying to use will be deployed on the google cloud, having it in the local environment is fair enough only upto the point of testing it. </p>
<p>webapp2 also is there in a form of a library which is available in python app engine without having to put it in the lib folder. </p>
<p>You might wan... | 0 | 2016-06-30T09:27:32Z | [
"python"
] |
PyQt Button clicked as soon as program ran | 38,114,054 | <p>Using Qt Designer, I have created a simple Dialogue box. I have added a submit button called <code>self.pushButton</code>. I keep having a problem that when I run the program, the button is automatically clicked. I am getting the program to print to the shell, "button clicked" and this appears as soon as the program... | 1 | 2016-06-30T04:34:31Z | 38,114,996 | <p>You have a call to your click function at "setupUi"(line 75) function which is called to setup your ui at the beginning. So remove the <code>self.click()</code> from there.</p>
| 0 | 2016-06-30T05:56:35Z | [
"python",
"qt",
"python-3.x",
"pyqt",
"pyqt4"
] |
Training different scikit-learn classifiers on multiple CPUs for each iteration | 38,114,104 | <p>I have a script that randomly generates a set of data and trains several classifiers to compare them against each other (it's very similar to <a href="http://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html">http://scikit-learn.org/stable/auto_examples/classification/plot_classifi... | 10 | 2016-06-30T04:40:41Z | 38,115,300 | <p>This is less of an answer and more of a rough sketch of an answer to your first question, </p>
<blockquote>
<p>How would I be able to train the classifiers using different threads
<code>for every iteration of for num_samples, num_feats, num_feats_to_remove
in product(_samples, _feats, _feats_to_rm)</code></p>... | 2 | 2016-06-30T06:18:35Z | [
"python",
"multithreading",
"numpy",
"scikit-learn",
"threadpool"
] |
Can I refer to a subclass in another subclass? | 38,114,133 | <p>This is a somewhat general question. </p>
<p><strong>If I am creating a class with functions in it can i refer to another function in that class?</strong></p>
<p>For ex does this work:</p>
<pre><code>class pythonExcelFunctions():
def getSheetNumber(self, fileName, sheetName):
workbook = xlrd.open_wo... | 1 | 2016-06-30T04:44:23Z | 38,114,180 | <p>Yes, via that self variable. In this case, instead of <code>getSheetNumber(fileName, sheetName)</code> You'd want to do <code>self.getSheetNumber(fileName, sheetName)</code>. Self is basically the instance of the class, and you need to tell python which instance to call that function on.</p>
| 1 | 2016-06-30T04:49:00Z | [
"python",
"excel",
"class"
] |
Multiply every three rows of dataframe by different value | 38,114,174 | <p>I have a dataframe with 9 rows. I want to multiply the first three rows by one value, the second three rows by a second value and the third set of 3 rows by yet another value.</p>
<p>I'm using these variables:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([[i] * 5 for i in range(9)], columns=list('ABCDE')... | 3 | 2016-06-30T04:48:37Z | 38,114,206 | <p>you can use numpy reshaping</p>
<pre><code>df.loc[:, :] = (df.values.reshape(3, df.size / 3) * np.arange(3)[:, None]).reshape(df.shape)
</code></pre>
<hr>
<h3>Timing</h3>
<p><a href="http://i.stack.imgur.com/7bqgl.png" rel="nofollow"><img src="http://i.stack.imgur.com/7bqgl.png" alt="enter image description here... | 4 | 2016-06-30T04:52:02Z | [
"python",
"numpy",
"pandas"
] |
Multiply every three rows of dataframe by different value | 38,114,174 | <p>I have a dataframe with 9 rows. I want to multiply the first three rows by one value, the second three rows by a second value and the third set of 3 rows by yet another value.</p>
<p>I'm using these variables:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([[i] * 5 for i in range(9)], columns=list('ABCDE')... | 3 | 2016-06-30T04:48:37Z | 38,114,281 | <p>Another solution multiple <code>df</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mul.html" rel="nofollow"><code>mul</code></a> with <code>numpy array</code> expanded by <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow"><code>num... | 2 | 2016-06-30T04:58:28Z | [
"python",
"numpy",
"pandas"
] |
How to search for rows using an expression in numpy rec array | 38,114,261 | <p>Consider i have a numpy recarray as below:</p>
<pre><code>r = np.rec.array([(1,2,'Hello'),(2,3,"World")], \
dtype=[('foo', 'i4'),('bar', 'i4'), ('baz', 'S10')])
</code></pre>
<p>Now i want to get all the object that returns 'True' for the following expression stored in dict,</p>
<pre><code>expres... | 0 | 2016-06-30T04:56:33Z | 38,114,326 | <p>You can combine array comparisons with boolean operators.
For example (with a poor-mans implementations of a float comparison):</p>
<pre><code>EPS = 1e-7
mask = np.ones(len(r), dtype=np.bool)
mask &= r['foo'] == 1
mask &= (r['bar'] > 3-EPS) & (r['bar'] < 3+EPS)
mask &= r['baz'] == 'hello'
prin... | 1 | 2016-06-30T05:02:26Z | [
"python",
"numpy"
] |
How to search for rows using an expression in numpy rec array | 38,114,261 | <p>Consider i have a numpy recarray as below:</p>
<pre><code>r = np.rec.array([(1,2,'Hello'),(2,3,"World")], \
dtype=[('foo', 'i4'),('bar', 'i4'), ('baz', 'S10')])
</code></pre>
<p>Now i want to get all the object that returns 'True' for the following expression stored in dict,</p>
<pre><code>expres... | 0 | 2016-06-30T04:56:33Z | 38,130,387 | <p>If <code>r</code> is 1d (or can be flattened) <code>np.in1d</code> is a fast search tool. Most examples are with ints, but it works with a compound dtype as well.</p>
<pre><code>In [1127]: r = np.rec.array([(1,2,'Hello'),(2,3,"World")], \
......: dtype=[('foo', 'i4'),('bar', 'i4'), ('baz', 'S10... | 0 | 2016-06-30T18:07:17Z | [
"python",
"numpy"
] |
#Ruby Tk passing method/functions as arguments | 38,114,272 | <p>I explain:</p>
<p>I would like know how I can pass method or functions as arguments.</p>
<blockquote>
<p>For example, in <strong>Python</strong> will be:</p>
</blockquote>
<pre><code>from MyFile import MyClass
MyClass().my_method_click(function) # without parentheses
</code></pre>
<blockquote>
<p>In this e... | 1 | 2016-06-30T04:57:44Z | 38,114,760 | <p>Basically, you want to pass a runnable block of code. I haven't looked into Python yet, but I am sure it supports closures as well.</p>
<p>Anyhow, in Ruby, a "general" way of passing a runnable code is to use blocks (lambdas and procs).</p>
<pre><code>function = lambda { # your code }
MyClass.new.my_method_click(f... | 0 | 2016-06-30T05:39:46Z | [
"python",
"ruby-on-rails",
"ruby",
"methods",
"tk"
] |
python - iterate through list to map current element as Key, and front and back elements as Values? | 38,114,282 | <p>alist = ['A','B, 'C', 'D']</p>
<p>what this list represents is: A<->B<->C<->D</p>
<p>I want to map this like the following: </p>
<p>A: B</p>
<p>B: A, C</p>
<p>C: B, D</p>
<p>D: C </p>
<p>At first I did: </p>
<p>But this is obviously wrong because it skips two elements. </p>
<pre><code>alist = ['A',... | 0 | 2016-06-30T04:58:29Z | 38,114,346 | <p>What about something like:</p>
<pre><code>graph = {}
for i, item in enumerate(alist):
connections = []
for j in (i-1, i+1): # look at element before and after the i'th
if 0 <= j < len(alist): # check if the index is valid for `alist`
connections.append(alist[j])
graph[item] =... | 2 | 2016-06-30T05:04:22Z | [
"python",
"list",
"graph",
"iteration"
] |
python - iterate through list to map current element as Key, and front and back elements as Values? | 38,114,282 | <p>alist = ['A','B, 'C', 'D']</p>
<p>what this list represents is: A<->B<->C<->D</p>
<p>I want to map this like the following: </p>
<p>A: B</p>
<p>B: A, C</p>
<p>C: B, D</p>
<p>D: C </p>
<p>At first I did: </p>
<p>But this is obviously wrong because it skips two elements. </p>
<pre><code>alist = ['A',... | 0 | 2016-06-30T04:58:29Z | 38,114,398 | <p>This is almost definitely not what you want, but it was such a cute one line solution to your problem I could not resist.</p>
<pre><code> > l = ['A','B','C','D']
> { k: filter(None, [v1,v2]) for (k,v1,v2) in zip(l,[None]+l[:-1],l[1:]+[None]) }
{'A': ['B'], 'C': ['B', 'D'], 'B': ['A', 'C'], 'D': ['C']}
</cod... | 0 | 2016-06-30T05:09:26Z | [
"python",
"list",
"graph",
"iteration"
] |
python - iterate through list to map current element as Key, and front and back elements as Values? | 38,114,282 | <p>alist = ['A','B, 'C', 'D']</p>
<p>what this list represents is: A<->B<->C<->D</p>
<p>I want to map this like the following: </p>
<p>A: B</p>
<p>B: A, C</p>
<p>C: B, D</p>
<p>D: C </p>
<p>At first I did: </p>
<p>But this is obviously wrong because it skips two elements. </p>
<pre><code>alist = ['A',... | 0 | 2016-06-30T04:58:29Z | 38,114,442 | <p>Already there are many solutions, this one is very easy to understand:</p>
<pre><code>alist = ['A','B', 'C', 'D']
graph = {}
for index, item in enumerate(alist):
if index == 0:
if len(alist) == 1:
graph[item] = []
break
graph[item] = [alist[index+1]]
elif index == len... | 2 | 2016-06-30T05:12:56Z | [
"python",
"list",
"graph",
"iteration"
] |
python - iterate through list to map current element as Key, and front and back elements as Values? | 38,114,282 | <p>alist = ['A','B, 'C', 'D']</p>
<p>what this list represents is: A<->B<->C<->D</p>
<p>I want to map this like the following: </p>
<p>A: B</p>
<p>B: A, C</p>
<p>C: B, D</p>
<p>D: C </p>
<p>At first I did: </p>
<p>But this is obviously wrong because it skips two elements. </p>
<pre><code>alist = ['A',... | 0 | 2016-06-30T04:58:29Z | 38,114,525 | <p>Here's a quick and dirty solution (there are better ways I'm sure for longer items).</p>
<pre><code>graph = {alist[0]: alist[1], alist[-1]: alist[-2]} # terminal elements
for i in range(1, len(alist)-1): # middle elements
graph[alist[i]] = [alist[i-1], alist[i+1]]
In [43]: for k, v in sorted... | 0 | 2016-06-30T05:20:28Z | [
"python",
"list",
"graph",
"iteration"
] |
"ImportError: No module named xhaus" Python module importing error from ansible | 38,114,393 | <p>I have one python script it was working if I run from my terminal directly, but the same script I am running using Ansible but at the time I am getting below error.</p>
<p>Ansible command is:</p>
<pre><code>- name: run installer command 2
command: "{{auto_inst_loc}}/installer.py -i -s -c"
register: command_res... | 0 | 2016-06-30T05:09:10Z | 38,130,807 | <p>I personally try to use it and it work well, can you try this one:</p>
<pre><code>- name: Execute the script
script: "/Path-to-local-system/installer.py -i -s -c"
</code></pre>
<p>play with it and adjust the parameters, refere this <a href="http://docs.ansible.com/ansible/script_module.html" rel="nofollow">page<... | 0 | 2016-06-30T18:34:07Z | [
"python",
"ansible",
"jython",
"ansible-playbook"
] |
"ImportError: No module named xhaus" Python module importing error from ansible | 38,114,393 | <p>I have one python script it was working if I run from my terminal directly, but the same script I am running using Ansible but at the time I am getting below error.</p>
<p>Ansible command is:</p>
<pre><code>- name: run installer command 2
command: "{{auto_inst_loc}}/installer.py -i -s -c"
register: command_res... | 0 | 2016-06-30T05:09:10Z | 38,242,497 | <p>Finally, I had fixed above problem with a little bit hack. I had simply added sys.path.append('JAR location') line in my python script. Boom, its worked pretty well. Please let me know, if anyone know better solution.</p>
| 0 | 2016-07-07T09:54:11Z | [
"python",
"ansible",
"jython",
"ansible-playbook"
] |
why iter() is not getting updated with new value of etree elements in python? | 38,114,464 | <p>The iter() function is pointing to an element which i removed from etree during the previous iteration,why iter () is not updated with new value? is there anything wrong with the code? heres the code</p>
<pre><code>root = etree.parse(open("Sample.xml",'r'))
for e in root.iter():
print etree.tostring(e)
b=ro... | 0 | 2016-06-30T05:15:26Z | 38,114,626 | <p><a href="https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.iter" rel="nofollow"><code>iter()</code> documentation</a> explicitly states that behavior is undefined in when tree is modified:</p>
<blockquote>
<p>Creates a tree iterator with the current element as the root. Th... | 0 | 2016-06-30T05:29:25Z | [
"python",
"xml",
"iterator",
"elementtree"
] |
Basic 1d convolution in tensorflow | 38,114,534 | <p>OK, I'd like to do a 1-dimensional convolution of time series data in Tensorflow. This is apparently supported using <code>tf.nn.conv2d</code>, according to <a href="https://github.com/tensorflow/tensorflow/issues/2165" rel="nofollow">these</a> <a href="https://github.com/tensorflow/tensorflow/issues/1136" rel="nofo... | 2 | 2016-06-30T05:20:57Z | 38,117,279 | <p>I am sorry to say that, but your first code was almost right. You just inverted <code>x</code> and <code>phi</code> in <code>tf.nn.conv2d</code>:</p>
<pre class="lang-py prettyprint-override"><code>g = tf.Graph()
with g.as_default():
# data shape is "[batch, in_height, in_width, in_channels]",
x = tf.Variab... | 3 | 2016-06-30T08:02:31Z | [
"python",
"tensorflow"
] |
Basic 1d convolution in tensorflow | 38,114,534 | <p>OK, I'd like to do a 1-dimensional convolution of time series data in Tensorflow. This is apparently supported using <code>tf.nn.conv2d</code>, according to <a href="https://github.com/tensorflow/tensorflow/issues/2165" rel="nofollow">these</a> <a href="https://github.com/tensorflow/tensorflow/issues/1136" rel="nofo... | 2 | 2016-06-30T05:20:57Z | 38,857,776 | <p>I think I got it to work with the requirements that I needed. The comments/details of how it works are on the code:</p>
<pre><code>import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
task_name = 'task_MNIST_flat_auto_encoder'
mnist = input_data.read_data_sets("MNI... | 0 | 2016-08-09T18:15:17Z | [
"python",
"tensorflow"
] |
Unable catch exception in selenium+python | 38,114,593 | <p>I have written a method for explicit wait. However I am unable to catch exception when invalid locator is given</p>
<pre><code>from Page_Objectes import Base_Page
from Tests.Base_Test_SSA import BaseTest
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from seleniu... | 1 | 2016-06-30T05:26:17Z | 38,114,713 | <p>You need to <code>raise</code> the exception.</p>
<p><strong>General illustration:</strong></p>
<pre><code>try:
a
except:
print "exception"
raise Exception("An exception occured")
</code></pre>
<p><strong>output:</strong></p>
<blockquote>
<pre><code>exception
Traceback (most recent call last):
File "e... | 0 | 2016-06-30T05:36:48Z | [
"python",
"exception",
"xpath",
"selenium-webdriver"
] |
Look for celebrities linkedIn accounts using google search engine apis | 38,114,607 | <p>Looking for celebrities LinkedIn accounts using google apis - When I visit the bellow link I get the <code>Json</code> see bellow. I get users related using some sort of google ranking system but not the actual celebrity I'm looking for. </p>
<p>How do I get only the people who have the name <code>Stevie Wonder</co... | 0 | 2016-06-30T05:27:48Z | 38,114,685 | <p>I suppose you are looking for something like the following, if response is the response dict. Of course first you will have to convert the json to dict.</p>
<pre><code>response.get('items')[0].get('pagemap').get('hcard')[0].get('fn')
</code></pre>
| 0 | 2016-06-30T05:34:49Z | [
"python",
"google-api",
"google-search",
"google-search-api"
] |
pandas read_csv column dtype is set to decimal but converts to string | 38,114,654 | <p>I am using pandas (v0.18.1) to import the following data from a file called 'test.csv':</p>
<pre><code>a,b,c,d
1,1,1,1.0
</code></pre>
<p>I have set the dtype to 'decimal.Decimal' for columns 'c' and 'd' but instead they return as type 'str'.</p>
<pre><code>import pandas as pd
import decimal as D
df = pd.read_cs... | 2 | 2016-06-30T05:32:27Z | 38,114,744 | <p>I think you need converters:</p>
<pre><code>temp=u"""a,b,c,d
1,1,1,1.0"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp),
dtype={'a': int, 'b': float},
converters={'c': D.Decimal, 'd': D.Decimal})
print (df)
a b c d
0 1 1.0 1 ... | 1 | 2016-06-30T05:38:57Z | [
"python",
"csv",
"pandas",
"type-conversion",
"decimal"
] |
Extracting MS Word document formatting elements along with raw text information | 38,114,861 | <p>In <a href="http://stackoverflow.com/questions/125222/extracting-text-from-ms-word-files-in-python">this post</a> @mikemaccana describes how to use <a href="https://python-docx.readthedocs.io/en/latest/" rel="nofollow">python-docx</a> to extract raw text data from an MS Word document from within python. I'd like to ... | 2 | 2016-06-30T05:46:58Z | 38,117,282 | <p>The character level formatting ("font") properties are available at the run level. A paragraph is made up of runs. So you can get what you want by going down to that level, like:</p>
<pre><code>for paragraph in document.paragraphs:
for run in paragraph.run:
font = run.font
is_bold = font.bold
... | 1 | 2016-06-30T08:02:43Z | [
"python",
"ms-word",
"python-docx"
] |
I am new to django, I tried registration of users but there is a error while I try to go to the page | 38,114,924 | <p><strong>Traceback:</strong></p>
<pre><code>File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
147. ... | -4 | 2016-06-30T05:51:05Z | 38,126,108 | <p>I figured out the problem, it was a missing bracket</p>
<p>from django.conf.urls import url
from . import views
urlpatterns = [ url(r'^$', views.UserFormView.as_view(), name='register'), ]</p>
| 0 | 2016-06-30T14:27:05Z | [
"python",
"django"
] |
Terminal returning directory without output everytime I run my code | 38,114,971 | <p>I am trying to solve a tuple problem in python and I am running my python code on terminal but everytime I run it , It takes me back the folder I have stored it in, without any output. Here's the code :</p>
<pre><code>name = raw_input("Enter file:")
if len(name) < 1 :
name = "mbox-short.txt"
handle = open... | 1 | 2016-06-30T05:55:05Z | 38,117,778 | <pre><code>name = raw_input("Enter file: ")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
hours = {}
# handle = open("mbox-short.txt")
for line in handle:
if line.startswith('From '):
hour = line.split()[-2].split(':')[0]
if hour in hours:
hours[hour] = hours[hour] +... | 0 | 2016-06-30T08:29:06Z | [
"python",
"ubuntu",
"terminal"
] |
Terminal returning directory without output everytime I run my code | 38,114,971 | <p>I am trying to solve a tuple problem in python and I am running my python code on terminal but everytime I run it , It takes me back the folder I have stored it in, without any output. Here's the code :</p>
<pre><code>name = raw_input("Enter file:")
if len(name) < 1 :
name = "mbox-short.txt"
handle = open... | 1 | 2016-06-30T05:55:05Z | 38,118,359 | <pre><code>fh = handle.read()
for line in fh :
lines = line.rstrip()
</code></pre>
<p>In these lines you are reading all the file contents and storing it in <code>fh</code> as a <code>string</code>. Now when you iterate over it in <code>for line in fh</code>, you are just getting individual characters in <code>lin... | 0 | 2016-06-30T08:57:26Z | [
"python",
"ubuntu",
"terminal"
] |
OpenCV 3 Python 3.5 Anaconda | 38,114,999 | <p>I have tried installing opencv 3 in anaconda virtual env.I used the following binstar package..</p>
<pre><code>conda
source activate (envname)
conda install -c https://conda.binstar.org/menpo opencv
conda list
</code></pre>
<p><strong>cv__version__ also gives the correct output 3.1.0</strong></p>
<p>This is... | 0 | 2016-06-30T05:56:49Z | 38,125,632 | <p>Generally, you should run " python fp.py " instead of ./fp.py. </p>
<p>The . command will run a bash-script(xxx.sh) in current shell, and python xxx.py will run the python file.</p>
<p>Enjoy ! </p>
| 0 | 2016-06-30T14:08:43Z | [
"python",
"ffmpeg",
"anaconda",
"opencv3.0",
"python-3.5"
] |
loading json file using python | 38,115,024 | <p>I am trying to load json file availalble here : <a href="https://gist.githubusercontent.com/anonymous/e5ef9cb96acb98e1f813d5166d472c70/raw/eabf219c51ace122ad82b7037bbf93d347fb4a9b/data.json" rel="nofollow">https://gist.githubusercontent.com/anonymous/e5ef9cb96acb98e1f813d5166d472c70/raw/eabf219c51ace122ad82b7037bbf9... | 0 | 2016-06-30T05:58:47Z | 38,115,239 | <p>What wrong : json is not valid
Solution : update data to be a valid json, by example remove end of line inside string item.</p>
| 0 | 2016-06-30T06:14:13Z | [
"python",
"json"
] |
Grouping/Bucketing latitude and longitude | 38,115,135 | <p>This is more of a logical problem than the technical one. So request you guys to please not to flag it.</p>
<p>I want to write a method in python, that takes two parameters -> latitude and longitude. This method should return group/bucket. The grouping should be done based on 0.05 degree.</p>
<pre><code>def get_bu... | 0 | 2016-06-30T06:07:22Z | 38,115,243 | <p>Here is one implementation:</p>
<pre><code>def get_bucket(lat,lng):
int(lng/0.05)*(whatever the highest possible lat is)/0.05 + int(lat/0.05)
</code></pre>
| 0 | 2016-06-30T06:14:25Z | [
"python",
"algorithm",
"latitude-longitude",
"geo",
"geography"
] |
Grouping/Bucketing latitude and longitude | 38,115,135 | <p>This is more of a logical problem than the technical one. So request you guys to please not to flag it.</p>
<p>I want to write a method in python, that takes two parameters -> latitude and longitude. This method should return group/bucket. The grouping should be done based on 0.05 degree.</p>
<pre><code>def get_bu... | 0 | 2016-06-30T06:07:22Z | 38,128,614 | <p>There are typically 180 degrees of latitude (-90 to 90) and 360 degrees of longitude (-180 to 180).</p>
<p>So there are 18,000 hundredth-degree increments of latitude (i.e. -90.00, -89.99, ... 89.99, 90.00), and 36,000 hundredth-degree increments of longitude.</p>
<p>Let's say you put this in a two-dimensional arr... | 0 | 2016-06-30T16:22:12Z | [
"python",
"algorithm",
"latitude-longitude",
"geo",
"geography"
] |
how to add list items to tuples inside list of tuples | 38,115,182 | <p>lets say i have a list of tuples:</p>
<p><code>[(0, 11), (1, 12), (2, 13), (3, 14)]</code></p>
<p>and a list</p>
<p><code>[22, 24, 26, 28]</code></p>
<p>and i want to combine these to make</p>
<p><code>[(0, 11, 22), (1, 12, 24), (2, 13, 26), (3, 14, 28)]</code></p>
<p>is there an easy and efficient way to do t... | 1 | 2016-06-30T06:10:46Z | 38,115,237 | <p>Pattern matching is the way to go:</p>
<pre><code>>>> a
[(0, 11), (1, 12), (2, 13), (3, 14)]
>>> b
[22, 24, 26, 28]
>>> [(i, j, k) for ((i, j), k) in zip(a, b)]
[(0, 11, 22), (1, 12, 24), (2, 13, 26), (3, 14, 28)]
</code></pre>
<p>Inserting to different positions is trivial in this case.... | 5 | 2016-06-30T06:14:09Z | [
"python",
"list",
"tuples"
] |
django, logged in via rest api, doesn't show in browser | 38,115,201 | <p>I am working on openedx and i'm creating a user_login api, that will login the user coming from a particular site.<br>
I'm able to log in the user via
<code>login(request,user)</code> function and it's showing an output :</p>
<pre><code> 2016-06-30 01:57:23,361 INFO 5426 [audit] models.py:1805 - Login
success - c... | 0 | 2016-06-30T06:12:14Z | 38,116,433 | <p>Are you issuing a request explicitly after the <code>login</code> function? <code>login</code> will not create a response for you automatically, you have to do something like <a href="https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.login" rel="nofollow">this</a>. Use <code>return redir... | 0 | 2016-06-30T07:23:19Z | [
"python",
"django",
"rest",
"django-rest-framework"
] |
How to search for specific value in Json array using Python | 38,115,290 | <p>I'm using a website's <code>API</code> to get information. It outputs 100 values. </p>
<p>What is the best practice of searching for a specific value in this array?</p>
<p>The array looks something like this:</p>
<pre><code>{
"success":true,
"data":
{
"array":
[
{
"id":"1","name":"Valu... | 0 | 2016-06-30T06:17:45Z | 38,115,406 | <p>Your code can be simplified a lot:</p>
<pre><code># no need to call `r.json` so many times, can simply save it to a variable
json_data = r.json()
for item in json_data["data"]["array"]:
if item["name"] == "Value1":
# do something...
</code></pre>
| 0 | 2016-06-30T06:25:37Z | [
"python",
"json"
] |
How to search for specific value in Json array using Python | 38,115,290 | <p>I'm using a website's <code>API</code> to get information. It outputs 100 values. </p>
<p>What is the best practice of searching for a specific value in this array?</p>
<p>The array looks something like this:</p>
<pre><code>{
"success":true,
"data":
{
"array":
[
{
"id":"1","name":"Valu... | 0 | 2016-06-30T06:17:45Z | 38,115,427 | <p>Not sure where that piece of code came from but it looks very wrong.</p>
<p>Just looking at the structure you can do something like:</p>
<pre><code>for attrs in r.json()['data']['array']:
if attrs['name'] == s_name:
ident = attrs['id']
name = attrs['name']
print(name + ' - ' + ident)
... | 0 | 2016-06-30T06:26:22Z | [
"python",
"json"
] |
scikit-learn: don't separate hyphenated words while tokenization | 38,115,367 | <p>I am using the <code>CountVectorizer</code> and don't want to separate hyphenated words into different tokens. I have tried passing different pregex patterns into the <code>token_pattern</code> argument, but haven't been able to get the desired result.</p>
<p>Here's what I have tried: </p>
<pre><code>pattern = r''... | 3 | 2016-06-30T06:23:25Z | 38,161,028 | <p>There are a couple things to note. The first is that adding in all of those spaces, line breaks and comments into your pattern string makes all of those characters part of your regular expression. See here:</p>
<pre><code>import re
>>> re.match("[0-9]","3")
<_sre.SRE_Match object at 0x104caa920>
>... | 3 | 2016-07-02T14:05:40Z | [
"python",
"regex",
"scikit-learn",
"nltk"
] |
Finding occurence pattern in a timestamp interval | 38,115,387 | <p>Given an array of timestamps (epoch time), where each timestamp represents the time when an event occured</p>
<pre><code>timestamps = [1467267654, 1467267657, 1467267660, ... 146726821]
</code></pre>
<p>I must search for an interval of 30 seconds where the number of occurences is higher than 5.</p>
<p>So, if ther... | -2 | 2016-06-30T06:24:44Z | 38,115,996 | <p>Since the data is sorted, one pass is enough. Iterate through the array in the following manner:</p>
<ul>
<li>remember the current index <code>i</code>, let's call this index <code>start</code></li>
<li>increase <code>i</code> until either <code>i = start + 4</code> or <code>a[i] > a[start] + 30</code>: in the f... | 0 | 2016-06-30T07:00:24Z | [
"python",
"algorithm",
"timestamp"
] |
Finding occurence pattern in a timestamp interval | 38,115,387 | <p>Given an array of timestamps (epoch time), where each timestamp represents the time when an event occured</p>
<pre><code>timestamps = [1467267654, 1467267657, 1467267660, ... 146726821]
</code></pre>
<p>I must search for an interval of 30 seconds where the number of occurences is higher than 5.</p>
<p>So, if ther... | -2 | 2016-06-30T06:24:44Z | 38,116,524 | <p>Try all pairs of timestamps 4 indexes apart until you find one that differs by less than 30 seconds.</p>
<pre><code>for i in range(len(timestamps) - 4):
if timestamp[i + 4] - timestamp[i] <= 30:
return true
return false
</code></pre>
<p>After the problem statement, there is no need to report the int... | 0 | 2016-06-30T07:27:28Z | [
"python",
"algorithm",
"timestamp"
] |
My Code Doesn't work every time i run it | 38,115,405 | <p>Given a sequence of non-negative integers <code>a0,â¦,anâ1,</code> find the maximum pairwise product, that is, the largest integer that can be obtained by multiplying two different elements from the sequence (or, more formally, <code>max0â¤iâ jâ¤nâ1aiaj</code>). Different elements here mean ai and aj with <c... | 0 | 2016-06-30T06:25:36Z | 38,115,717 | <p>It is not recommended to use variable name which are also the name of modules you are using </p>
<pre><code>import random
import time
b=time.time()
a=list()
c=list()
n=random.randint(2,12)
#appending random numbers in a list 'a'
g=1
while(g<=n):
a.append(random.randint(0,10))
g=g+1
print... | 1 | 2016-06-30T06:44:32Z | [
"python"
] |
My Code Doesn't work every time i run it | 38,115,405 | <p>Given a sequence of non-negative integers <code>a0,â¦,anâ1,</code> find the maximum pairwise product, that is, the largest integer that can be obtained by multiplying two different elements from the sequence (or, more formally, <code>max0â¤iâ jâ¤nâ1aiaj</code>). Different elements here mean ai and aj with <c... | 0 | 2016-06-30T06:25:36Z | 38,115,742 | <p>Your code has two flaws:</p>
<ul>
<li><p>You run two loops with <code>range(2, n)</code>, but <code>n</code> randomly can be set to <code>2</code>. <code>range(2, 2)</code> is an <em>empty sequence</em>, so your loop body will not run and you end up with an empty list <code>c</code></p></li>
<li><p>You mask the nam... | 3 | 2016-06-30T06:45:57Z | [
"python"
] |
How to create rpm for a python project | 38,115,437 | <p>I have a python project, that does have a setup.py file. Now I am able to create an rpm using <code>python setup.py bdist_rpm</code>. I installed the several python dependencies using pip. Now when I take the resulted rpm to another machine/host, I am getting several python package related error, like:</p>
<pre><co... | 0 | 2016-06-30T06:26:55Z | 38,116,677 | <p>Jordan Sissel's <a href="https://github.com/jordansissel/fpm" rel="nofollow">FPM</a> project is really handy for making RPM/DEB from a bunch of different source types, python included. Take a look at the <a href="https://github.com/jordansissel/fpm/wiki/ConvertingPython" rel="nofollow">wiki page for python</a> for s... | 0 | 2016-06-30T07:34:12Z | [
"python",
"rpm",
"rpmbuild"
] |
How to create rpm for a python project | 38,115,437 | <p>I have a python project, that does have a setup.py file. Now I am able to create an rpm using <code>python setup.py bdist_rpm</code>. I installed the several python dependencies using pip. Now when I take the resulted rpm to another machine/host, I am getting several python package related error, like:</p>
<pre><co... | 0 | 2016-06-30T06:26:55Z | 38,122,915 | <p>I highly recommend you pyp2rpm for generating python packages.</p>
<p>Staticaly linked modules -- that is called bundling and it is bad. You will regret it sooner or later. If you want to use dependencies which are not in distribution, you can use <a href="https://copr.fedorainfracloud.org/coprs/g/copr/PyPI2/" rel=... | 0 | 2016-06-30T12:19:49Z | [
"python",
"rpm",
"rpmbuild"
] |
Python: How to print a nested dictionary as a complex table with variable rows? | 38,115,533 | <p>Say I have this nested dictionary:</p>
<pre><code>d = {'Ben': {'wo_mana': ['Strength = 1.10', 'Speed = 1.50'], 'wi_mana': ['Int = 1.20'], 'Skill': 'true', 'Magic': 'false'},
'Tom': {'wi_mana': ['Int = 1.40'], 'wo_mana': ['Agility = 1.60'], 'Skill': 'true', 'Magic': 'true'}}
</code></pre>
<p>The keys and value... | 1 | 2016-06-30T06:33:14Z | 38,116,833 | <p>Here you go(edited):</p>
<pre><code>import csv, itertools
d = {'Ben': {'wo_mana': ['Strength = 1.10'], 'wi_mana': ['Int = 1.20'], 'Skill': 'true', 'Magic': 'false'},
'Tom': {'wi_mana': ['Int = 1.40'], 'wo_mana': ['Agility = 1.60'], 'Skill': 'true', 'Magic': 'true'}}
header = ['Name', 'Skill', 'Magic', 'wo_ma... | 1 | 2016-06-30T07:41:31Z | [
"python",
"python-2.7",
"csv",
"dictionary",
"string-formatting"
] |
Exporting a conda environment with local pip installs | 38,115,569 | <p>I have exported my currently active environment with </p>
<pre><code>conda env export > environment.yml
</code></pre>
<p>This is very convenient since it keeps track of both conda and pip installed packages. However, I have a few packages (shapely and basemap for example) installed locally by pip from a .whl fi... | 8 | 2016-06-30T06:35:11Z | 38,187,246 | <p>There's no way to actually get it to create entries for the <code>.whl</code> file automatically from what I'm aware of.</p>
<p>The simplest way to get this to work is by manually altering the <code>environment.yml</code> file and adding the <code>.whl</code> file in the list under <code>- pip:</code>. I tried this... | 3 | 2016-07-04T14:36:32Z | [
"python",
"windows",
"pip",
"development-environment",
"conda"
] |
python - Getting key with second and third maximum value in dictionary | 38,115,589 | <p>I have a JSON file something like this.</p>
<pre><code>{
"b0:47:bf:af:c1:42":
{
"No. of visits": 10, "cities":
{
"Mumbai": {"count": 5,"last_visited": "5/22/2016"},
"Kolkata": {"count": 2,"last_visited": "5/22/2016"},
"Amritsar":{"count": 3,"last_visited": "5/22/2016"}
}
},
"c0:ee:fb:... | 2 | 2016-06-30T06:36:13Z | 38,115,624 | <p>Instead of using <code>max</code>, you can use <code>sorted</code>. </p>
<p>That way you will get a sorted list based on <code>count</code>:</p>
<pre><code>d = {
"b0:47:bf:af:c1:42":
{
"No. of visits": 10, "cities":
{
"Mumbai": {"count": 5,"last_visited": "5/22/2016"},
"Kolkata": {"count": 2,"las... | 3 | 2016-06-30T06:39:02Z | [
"python",
"python-2.7",
"dictionary"
] |
Tox takes always 30 seconds to run | 38,116,038 | <p>Tox was running fine a couple of weeks ago, but I've come back to a project which uses tox to run the tests, and now it always takes 30 seconds to run. I thought it could be a problem with changes made to a project, but I've tried tox in other projects (even a hello world test) and they all take 30 seconds to run.</... | 0 | 2016-06-30T07:03:06Z | 38,421,650 | <p>Removing old packages installed in $HOME/.tox solved the issue. It seems like the 30 seconds were due to boto timeout, and some of these packages used boto. Don't know why this happened though.</p>
| 0 | 2016-07-17T13:17:38Z | [
"python",
"osx",
"tox"
] |
python sklearnï¼what is the different between "sklearn.preprocessing.normalize(X, norm='l2')" and "sklearn.svm.LinearSVC(penalty='l2')" | 38,116,078 | <p>here is two method of normalize :</p>
<p>1:this one is using in the data Pre-Processing: sklearn.preprocessing.normalize(X, norm='l2')</p>
<p>2:the other method is using in the classify method : sklearn.svm.LinearSVC(penalty='l2')</p>
<p>i want to know ,what is the different between them? and does the two s... | 1 | 2016-06-30T07:04:35Z | 38,124,167 | <p>These 2 are different things and you normally need them both in order to make a good SVC model.</p>
<p>1) The first one means that in order to scale (normalize) the X data matrix you need to divide with the L2 norm of each column, which is just this : <code>sqrt(sum(abs(X[:,j]).^2))</code> , where j is each column ... | 2 | 2016-06-30T13:11:09Z | [
"python",
"scikit-learn"
] |
Tkinter variables | 38,116,199 | <p>I've made a simple GUI in Tkinter.(Code is below)
When I press the "Fetch" botton than I get the text input from the GUI in a Command line.</p>
<p>Let's say that in this example the "user" is putting 0.5 in the "Service Points Won" field and 0.7 in the " Return Points Won" field as input.
When I press the "Fetch" ... | 0 | 2016-06-30T07:10:43Z | 38,116,958 | <p>Since you want to map some fields to others, using a dictionary is a better choice than using a list. </p>
<pre><code>def fetch(variables):
for key, val in variables.items():
print key, val.get()
def makeform(root, fields):
...
variables = {}
for field in fields:
...
variabl... | 1 | 2016-06-30T07:46:59Z | [
"python",
"tkinter",
"python-2.x"
] |
regarding file downloading in python | 38,116,218 | <p>I wrote this code to download an srt subtitle file, but this doesn't work. Please review this problem and help me with the code. I need to find what is the mistake that i'm doing. Thanks.</p>
<pre><code>from urllib import request
srt_url = "https://subscene.com/subtitle/download?mac=LkM2jew_9BdbDSxdwrqLkJl7hDpIL_... | 0 | 2016-06-30T07:11:32Z | 38,116,408 | <p>A number of things are wrong or can be improved.</p>
<ul>
<li>You are missing the <code>return</code> statement on your function.</li>
<li>You are calling the function from within the function so you are not actually calling it at all. You never enter it to begin with.</li>
<li><code>dest_url</code> is not a string... | 1 | 2016-06-30T07:21:24Z | [
"python",
"pycharm",
"pyscripter"
] |
Inline CSS statements for table <td/> in python | 38,116,267 | <p>I am facing an issue with viewing HTML emails and need to format the css to be inline with the HTML script. </p>
<p>I have the following td css used by multiple tables. </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="sni... | 0 | 2016-06-30T07:14:29Z | 38,116,410 | <p>For emails use inline CSS. Because browser-based email applications, such as Gmail, strip out and tags by default, always use inline CSS over embedded CSS. </p>
<p>So just assign it to each element manually in with an attribute <code>style="yourcssgoesgere"</code>.</p>
<p>More info for example here: <a href="htt... | 0 | 2016-06-30T07:21:31Z | [
"python",
"html",
"css",
"formatting",
"inline"
] |
Inline CSS statements for table <td/> in python | 38,116,267 | <p>I am facing an issue with viewing HTML emails and need to format the css to be inline with the HTML script. </p>
<p>I have the following td css used by multiple tables. </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="sni... | 0 | 2016-06-30T07:14:29Z | 38,116,842 | <p>If you familiar with gulp, the <a href="https://www.npmjs.com/package/gulp-inline-css" rel="nofollow">gulp-inline-css</a> module would be your quickest.</p>
<p>Edit: Or you can try the following tools:</p>
<p><a href="https://inliner.cm/" rel="nofollow">https://inliner.cm/</a></p>
<p><a href="http://templates.mai... | 0 | 2016-06-30T07:41:47Z | [
"python",
"html",
"css",
"formatting",
"inline"
] |
How to find the first character of a string and replace all findings of it in the same string in Python? | 38,116,270 | <p>I'm trying to create a method that brings in a string, looks for the first letter of the string and then replaces all occurrences of that letter with another character.</p>
<p>It obviously does not work to use s[letter] to the new character, since letter in this case is not an index. But what solution should be use... | 0 | 2016-06-30T07:14:39Z | 38,116,418 | <p>Always keep the manual at hand. The <code>str</code> type has a method which is even called <a href="https://docs.python.org/3.5/library/stdtypes.html#str.replace" rel="nofollow"><code>replace</code></a>.</p>
<blockquote>
<p><strong>str.replace(old, new[, count])</strong></p>
<p>Return a copy of the string w... | 0 | 2016-06-30T07:22:17Z | [
"python",
"string"
] |
How to find the first character of a string and replace all findings of it in the same string in Python? | 38,116,270 | <p>I'm trying to create a method that brings in a string, looks for the first letter of the string and then replaces all occurrences of that letter with another character.</p>
<p>It obviously does not work to use s[letter] to the new character, since letter in this case is not an index. But what solution should be use... | 0 | 2016-06-30T07:14:39Z | 38,117,032 | <p>You can use the <a href="https://docs.python.org/3.1/library/re.html" rel="nofollow"><code>re</code></a> library:</p>
<pre><code>import re
def fix_start(s):
return re.sub(s[0], "*", s)
print(fix_start("string"))
</code></pre>
<p>Output:</p>
<pre><code>*tring
</code></pre>
<p>another way is this:</p>
<pre>... | 0 | 2016-06-30T07:51:04Z | [
"python",
"string"
] |
Dimension expanding for loop (python) | 38,116,275 | <p>How do I program a for loop in python where each new instance gets assigned to a new dimension/column in python (numpy array)? Say:</p>
<pre><code>y=[0,1,2]
z=numpy.zero(3,3)
for i in range(3):
z[i,:]=sin(i*math.pi*2-y)
</code></pre>
<p>Wouldn't work. I want the output array to be:</p>
<pre><code>1: sin(0*math.pi... | 0 | 2016-06-30T07:14:55Z | 38,116,602 | <p>There are a couple of issues in your code.
The below should work:</p>
<pre><code>import numpy
import math
y=[0,1,2]
z=numpy.zeros((3,3))
for i in range(3):
z[i,:] = math.sin(i*math.pi*2-y[i])
</code></pre>
| 1 | 2016-06-30T07:30:57Z | [
"python",
"for-loop"
] |
read output of php file using python | 38,116,305 | <p>I have a <code>php</code> file on server that prints some data from the <code>mysql</code> database in <code>json</code> format. </p>
<p>When I run my <code>php</code> file in my browser I can see the <code>json</code> array. Now I want to get that <code>json</code> array in a <code>python</code> file. Is there a w... | 1 | 2016-06-30T07:16:20Z | 38,117,035 | <p>Run the code with the following command and store its standard output to a variable:</p>
<pre><code>import subprocess
proc = subprocess.Popen("php /path/to/your/script.php", shell=True, stdout=subprocess.PIPE)
script_response = proc.stdout.read()
</code></pre>
<p>And if you need that data in json in python too:</... | 0 | 2016-06-30T07:51:11Z | [
"python",
"subprocess"
] |
read output of php file using python | 38,116,305 | <p>I have a <code>php</code> file on server that prints some data from the <code>mysql</code> database in <code>json</code> format. </p>
<p>When I run my <code>php</code> file in my browser I can see the <code>json</code> array. Now I want to get that <code>json</code> array in a <code>python</code> file. Is there a w... | 1 | 2016-06-30T07:16:20Z | 38,117,064 | <p>You can achieve this by having your PHP script output the JSON to a file on your server, then have your python script read that JSON in from the file.</p>
<p>You can achieve it like this:</p>
<h2>PHP Script:</h2>
<pre><code><?php
$json = json_encode('your data');
$file = '/tmp/json-file';
file_put_contents($f... | 0 | 2016-06-30T07:52:39Z | [
"python",
"subprocess"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.