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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
pygame.error: Couldn't open mp3 | 38,647,923 | <p>Here's the code for something I was testing out to put in a game I'm creating. I made this code to try to make the music loop over and over again.
Here:</p>
<pre><code>from pygame import mixer
mixer.init()
mixer.music.load('C:\\Users\\owner-\\Dropbox\\Programming\\Zelpha808\\music.mp3')
def play():
timer = 1
mixer.music.play()
timer = 2
if timer == 2:
play()
play()
</code></pre>
<p>and the result:</p>
<pre><code>pygame.error: Couldn't open 'C:\Users\owner-\Dropbox\Programming\Zelpha808\music.mp3'
</code></pre>
<p>I've seen previous posts about this, except they weren't using the 'music' and the answer ended up telling them to use 'music'. But in this case, I AM using 'music'. So what's wrong with it? And if you can, would this code work? As in would the music play in a loop nonstop? If not, how would I make it loop?</p>
| 0 | 2016-07-28T22:44:37Z | 38,648,259 | <p>Try just putting the mp3 in the same directory as your .py file. And about the music looping, if you have a loop that is keeping your window open, you should call <code>pygame.mixer.music.play(loops=-1)</code> before the loop. This tells pygame to keep looping the music contentiously. As the pygame.mixer.music doc says: </p>
<blockquote>
<p>The loops argument controls the number of repeats a music will play....If the loops[argument] is -1 then the music will repeat indefinitely.</p>
</blockquote>
<p>Link to pygame.mixer.music docs: <a href="http://www.pygame.org/docs/ref/music.html#pygame.mixer.music.load" rel="nofollow">http://www.pygame.org/docs/ref/music.html#pygame.mixer.music.load</a></p>
| 0 | 2016-07-28T23:22:23Z | [
"python",
"pygame",
"mp3",
"python-3.5"
] |
pygame.error: Couldn't open mp3 | 38,647,923 | <p>Here's the code for something I was testing out to put in a game I'm creating. I made this code to try to make the music loop over and over again.
Here:</p>
<pre><code>from pygame import mixer
mixer.init()
mixer.music.load('C:\\Users\\owner-\\Dropbox\\Programming\\Zelpha808\\music.mp3')
def play():
timer = 1
mixer.music.play()
timer = 2
if timer == 2:
play()
play()
</code></pre>
<p>and the result:</p>
<pre><code>pygame.error: Couldn't open 'C:\Users\owner-\Dropbox\Programming\Zelpha808\music.mp3'
</code></pre>
<p>I've seen previous posts about this, except they weren't using the 'music' and the answer ended up telling them to use 'music'. But in this case, I AM using 'music'. So what's wrong with it? And if you can, would this code work? As in would the music play in a loop nonstop? If not, how would I make it loop?</p>
| 0 | 2016-07-28T22:44:37Z | 38,648,977 | <p>It turns out that the music file is a .wav file... The original file was a .mp3, and it had like 10 seconds of silence at the beginning of it. So I put it in audacity, and cut it out, and I guess it changed it to a .wav file. I feel so stupid hahaha. But that did it, I did mixer.music.load('C:/Users/owner-/Dropbox/Programming/Zelpha808/music.wav').</p>
| 0 | 2016-07-29T01:03:30Z | [
"python",
"pygame",
"mp3",
"python-3.5"
] |
Sum list of list elements in python like sql group by | 38,647,928 | <p>I have a list of lists (string,integer)</p>
<p>eg:</p>
<pre><code>my_list=[["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]]
</code></pre>
<p>I'd like to sum the same items and finally get this:</p>
<pre><code>my2_list=[["apple",116],["banana",15],["orange",9]]
</code></pre>
| 0 | 2016-07-28T22:45:02Z | 38,647,985 | <pre><code>from collections import defaultdict
my_list= [["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]]
result = defaultdict(int)
for fruit, value in my_list:
result[fruit] += value
result = result.items()
print result
</code></pre>
<p>Or you can keep result as dictionary</p>
| 2 | 2016-07-28T22:51:25Z | [
"python",
"list"
] |
Sum list of list elements in python like sql group by | 38,647,928 | <p>I have a list of lists (string,integer)</p>
<p>eg:</p>
<pre><code>my_list=[["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]]
</code></pre>
<p>I'd like to sum the same items and finally get this:</p>
<pre><code>my2_list=[["apple",116],["banana",15],["orange",9]]
</code></pre>
| 0 | 2016-07-28T22:45:02Z | 38,647,993 | <p>You can use <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> on the <em>sorted</em> list:</p>
<pre><code>from itertools import groupby
my_list=[["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]]
my_list2 = []
for i, g in groupby(sorted(my_list), key=lambda x: x[0]):
my_list2.append([i, sum(v[1] for v in g)])
print(my_list2)
# [['apple', 116], ['banana', 15], ['orange', 9]]
</code></pre>
<hr>
<p>Speaking of SQL <em>Group By</em> and <em>pre-sorting</em>:</p>
<blockquote>
<p>The operation of <code>groupby()</code> is similar to the uniq filter in Unix. It
generates a break or new <strong>group</strong> every time the value of the key
function changes (which is why it is usually necessary to have <strong>sorted</strong>
the data using the same key function). That behavior <strong>differs</strong> from
SQLâs GROUP BY which aggregates common elements regardless of their
input order.</p>
</blockquote>
<p><em>Emphasis Mine</em></p>
| 2 | 2016-07-28T22:51:47Z | [
"python",
"list"
] |
Sum list of list elements in python like sql group by | 38,647,928 | <p>I have a list of lists (string,integer)</p>
<p>eg:</p>
<pre><code>my_list=[["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]]
</code></pre>
<p>I'd like to sum the same items and finally get this:</p>
<pre><code>my2_list=[["apple",116],["banana",15],["orange",9]]
</code></pre>
| 0 | 2016-07-28T22:45:02Z | 38,647,998 | <pre><code>from itertools import groupby
[[k, sum(v for _, v in g)] for k, g in groupby(sorted(my_list), key = lambda x: x[0])]
# [['apple', 116], ['banana', 15], ['orange', 9]]
</code></pre>
| 0 | 2016-07-28T22:52:13Z | [
"python",
"list"
] |
Sum list of list elements in python like sql group by | 38,647,928 | <p>I have a list of lists (string,integer)</p>
<p>eg:</p>
<pre><code>my_list=[["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]]
</code></pre>
<p>I'd like to sum the same items and finally get this:</p>
<pre><code>my2_list=[["apple",116],["banana",15],["orange",9]]
</code></pre>
| 0 | 2016-07-28T22:45:02Z | 38,648,218 | <p>Using Pandas and <code>groupby</code>:</p>
<pre><code>import pandas as pd
>>> pd.DataFrame(my_list, columns=['fruit', 'count']).groupby('fruit').sum()
count
fruit
apple 116
banana 15
orange 9
</code></pre>
| 0 | 2016-07-28T23:17:45Z | [
"python",
"list"
] |
Sum list of list elements in python like sql group by | 38,647,928 | <p>I have a list of lists (string,integer)</p>
<p>eg:</p>
<pre><code>my_list=[["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]]
</code></pre>
<p>I'd like to sum the same items and finally get this:</p>
<pre><code>my2_list=[["apple",116],["banana",15],["orange",9]]
</code></pre>
| 0 | 2016-07-28T22:45:02Z | 38,653,442 | <p>If you dont want the order to preserved, then plz use the below code.</p>
<pre><code>my_list=[["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]]
my_dict1 = {}
for d in my_list:
if d[0] in my_dict1.keys():
my_dict1[d[0]] += d[1]
else:
my_dict1[d[0]] = d[1]
my_list2 = [[k,v] for (k,v) in my_dict1.items()]
</code></pre>
| 0 | 2016-07-29T07:56:34Z | [
"python",
"list"
] |
How to quickly fetch all documents MongoDB pymongo | 38,647,962 | <p>Currently I fetch documents by iterating through cursor in pymongo, for example:</p>
<pre><code>for d in db.docs.find():
mylist.append(d)
</code></pre>
<p>For reference, performing a fetchall on the same set of data (7m records) takes around 20 seconds while the method above takes a few minutes.</p>
<p>Is there a faster way read bulk data in mongo? Sorry I'm new to mongo, please let me know if more information is needed.</p>
| 2 | 2016-07-28T22:49:20Z | 38,661,360 | <p>using the $natural sort will bypass the index and return the documents in the order in which they are stored on disk, meaning that mongo doesn't have to thrash around with random reads on your disk.</p>
<p><a href="https://docs.mongodb.com/manual/reference/method/cursor.sort/#return-natural-order" rel="nofollow">https://docs.mongodb.com/manual/reference/method/cursor.sort/#return-natural-order</a></p>
<p>The performance becomes severely degraded if you want to use a query. You should never rely on FIFO ordering. Mongo allows itself to move documents around within it's storage layer. If you don't care about the order, so be it.</p>
<blockquote>
<p>This ordering is an internal implementation feature, and you should
not rely on any particular structure within i</p>
</blockquote>
<pre><code>for d in db.docs.find().sort( { $natural: 1 } ):
mylist.append(d)
</code></pre>
<p>in python, you also want to use an <strong>EXHAUST</strong> cursor type that tells the mongo server to stream back the results without waiting for the pymongo driver to acknowledge each batch</p>
<p><a href="https://api.mongodb.com/python/current/api/pymongo/cursor.html#pymongo.cursor.CursorType.EXHAUST" rel="nofollow">https://api.mongodb.com/python/current/api/pymongo/cursor.html#pymongo.cursor.CursorType.EXHAUST</a></p>
<p>Mind you, it'll never be as fast as the shell. The slowest aspect of moving data between mongo/bson->pymongo->you is UTF8 string decoding within python. </p>
| 1 | 2016-07-29T14:30:25Z | [
"python",
"mongodb",
"nosql",
"pymongo"
] |
Celery, RabbitMQ, Redis: Celery message enters exchange, but not queue? | 38,647,974 | <p>I'm using Python 2.7 (sigh), celery==3.1.19, librabbitmq==1.6.1, rabbitmq-server-3.5.6-1.noarch, and redis 2.8.24 (from redis-cli info).</p>
<p>I'm attempting to send a message from a celery producer to a celery consumer, and obtain the result back in the producer. There is 1 producer and 1 consumer, but 2 rabbitmq's (as brokers) and 1 redis (for results) in between.</p>
<p>The problem I'm facing is:</p>
<ol>
<li>In the consumer, I get back get an AsyncResult via async_result =
ZipUp.delay(unique_directory), but async_result.ready() never
returns True (at least for 9 seconds it doesn't) - even for a
consumer task that does essentially nothing but return a string.</li>
<li>I can see, in the rabbitmq management web interface, my message
being received by the rabbitmq exchange, but it doesn't show up in
the corresponding rabbitmq queue. Also, a log message sent by the
very beginning of the ZipUp task doesn't appear to be getting
logged.</li>
</ol>
<p>Things work if I don't try to get a result back from the AsyncResult! But I'm kinda hoping to get the result of the call - it's useful :).</p>
<p>Below are configuration specifics.</p>
<p>We're setting up Celery as follows for returns:</p>
<pre><code>CELERY_RESULT_BACKEND = 'redis://%s' % _SHARED_WRITE_CACHE_HOST_INTERNAL
CELERY_RESULT = Celery('TEST', broker=CELERY_BROKER)
CELERY_RESULT.conf.update(
BROKER_HEARTBEAT=60,
CELERY_RESULT_BACKEND=CELERY_RESULT_BACKEND,
CELERY_TASK_RESULT_EXPIRES=100,
CELERY_IGNORE_RESULT=False,
CELERY_RESULT_PERSISTENT=False,
CELERY_ACCEPT_CONTENT=['json'],
CELERY_TASK_SERIALIZER='json',
CELERY_RESULT_SERIALIZER='json',
)
</code></pre>
<p>We have another Celery configuration that doesn't expect a return value, and that works - in the same program. It looks like:</p>
<pre><code>CELERY = Celery('TEST', broker=CELERY_BROKER)
CELERY.conf.update(
BROKER_HEARTBEAT=60,
CELERY_RESULT_BACKEND=CELERY_BROKER,
CELERY_TASK_RESULT_EXPIRES=100,
CELERY_STORE_ERRORS_EVEN_IF_IGNORED=False,
CELERY_IGNORE_RESULT=True,
CELERY_ACCEPT_CONTENT=['json'],
CELERY_TASK_SERIALIZER='json',
CELERY_RESULT_SERIALIZER='json',
)
</code></pre>
<p>The celery producer's stub looks like:</p>
<pre><code>@CELERY_RESULT.task(name='ZipUp', exchange='cognition.workflow.ZipUp_%s' % INTERNAL_VERSION)
def ZipUp(directory): # pylint: disable=invalid-name
""" Task stub """
_unused_directory = directory
raise NotImplementedError
</code></pre>
<p>It's been mentioned that using queue= instead of exchange= in this stub would be simpler. Can anyone confirm that (I googled but found exactly nothing on the topic)? Apparently you can just use queue= unless you want to use fanout or something fancy like that, since not all celery backends have the concept of an exchange.</p>
<p>Anyway, the celery consumer starts out with:</p>
<pre><code>@task(queue='cognition.workflow.ZipUp_%s' % INTERNAL_VERSION, name='ZipUp')
@StatsInstrument('workflow.ZipUp')
def ZipUp(directory): # pylint: disable=invalid-name
'''
Zip all files in directory, password protected, and return the pathname of the new zip archive.
:param directory Directory to zip
'''
try:
LOGGER.info('zipping up {}'.format(directory))
</code></pre>
<p>But "zipping up" doesn't get logged anywhere. I searched every (disk-backed) file on the celery server for that string, and got two hits: /usr/bin/zip, and my celery task's code - and no log messages.</p>
<p>Any suggestions?</p>
<p>Thanks for reading!</p>
| 0 | 2016-07-28T22:50:14Z | 38,662,361 | <p>It appears that using the following task stub in the producer solved the problem:</p>
<pre><code>@CELERY_RESULT.task(name='ZipUp', queue='cognition.workflow.ZipUp_%s' % INTERNAL_VERSION)
def ZipUp(directory): # pylint: disable=invalid-name
""" Task stub """
_unused_directory = directory
raise NotImplementedError
</code></pre>
<p>In short, it's using queue= instead of exchange= .</p>
| 0 | 2016-07-29T15:24:10Z | [
"python",
"redis",
"rabbitmq",
"celery"
] |
eglInitialize failure using ANGLE dll from python 64 bits | 38,648,125 | <p>I've been using the ANGLE dlls for a while to run OpenGLES2.0 code on windows from 32 bit python (pi3d module) However I can't get it to work with 64 bits. I have <a href="https://github.com/paddywwoof/pi3d_windll" rel="nofollow">compiled the libraries</a> and at one stage, on a different laptop to which I don't have access now, it did get further than this. This is a stripped down version of the code that reproduces the point where it currently stops.</p>
<pre><code>import ctypes
import pygame
import os
EGL_DEFAULT_DISPLAY = 0
EGL_NO_DISPLAY = 0
EGL_TRUE = 1
pygame.init()
d = pygame.display.set_mode((0, 0), pygame.DOUBLEBUF | pygame.RESIZABLE | pygame.OPENGL)
info = pygame.display.Info()
width, height = info.current_w, info.current_h
#path = "C:/Program Files (x86)/Google/Chrome/Application/42.0.2311.152"
#path = "C:\\Program Files (x86)\\Google\Chrome\\Application\\42.0.2311.135"
path = "" # compiled ANGLE dll files in same directory
d3dcompiler = ctypes.WinDLL(os.path.join(path, "d3dcompiler_47.dll"))
opengles = ctypes.WinDLL(os.path.join(path, "libglesv2.dll"))
openegl = ctypes.WinDLL(os.path.join(path, "libegl.dll"))
display = openegl.eglGetDisplay(EGL_DEFAULT_DISPLAY)
assert display != EGL_NO_DISPLAY #<<<<<<<<<<<<<<<<<<<<<<
r = openegl.eglInitialize(display, None, None)
print('eglInitialize() returned {}'.format(r))
assert r == EGL_TRUE #<<<<<<<<<<<<<<<<<<<<<<
</code></pre>
| 0 | 2016-07-28T23:04:06Z | 38,654,764 | <p>Probably a 32-bit integer is given as an argument or expected as the type for the returned value instead of a 64-bit unsigned integer. This happens commonly for pointer values (handles) since 64-bit windows has 32-bit integers and 64-bit pointers. Defining <code>argtypes</code> and <code>restypes</code> attributes may help, or at least help to spot the problems.</p>
<pre><code>import ctypes.wintypes as wt
openegl.elgGetDisplay.argtypes = [wt.HDC]
openegl.elgGetDisplay.restype = c_void_p
openegl.eglInitialize.argtypes = [c_void_p, POINTER(c_int32), POINTER(c_int32)]
openegl.eglInitialize.restype = c_uint
</code></pre>
<p>then</p>
<pre><code>display = openegl.eglGetDisplay(None)
assert display.value is not None
r = openegl.eglInitialize(display, None, None)
</code></pre>
<p>might work (I don't have that library installed so I can't verify).</p>
| 1 | 2016-07-29T09:04:31Z | [
"python",
"dll",
"opengl-es",
"ctypes"
] |
Keras low accuracy classification task | 38,648,195 | <p>I was playing around with Keras and a dummy dataset. I wanted to see how much better a neural network would do compared to a standard SVM with a RBF kernel. The task was simple: predict the class for a 20-dim vector in the set {0,1,2}. </p>
<p>I noticed that the neural network does horribly. The SVM gets around 90% correct whereas the neural network flounders at 40%. What am I doing wrong in my code? This is most likely an error on my part but after a few hours of trying various parameters on the NN, I've given up.</p>
<p><strong>Code</strong></p>
<pre><code>from sklearn.datasets import make_multilabel_classification
from sklearn.svm import SVC
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.optimizers import SGD, RMSprop
from keras.utils import np_utils
from keras.datasets import mnist
# generate some data
dummyX, dummyY = make_multilabel_classification(n_samples=4000, n_features=20, n_classes=3)
# neural network
model = Sequential()
model.add(Dense(20, input_dim=20))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(20))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(3))
model.add(Activation('softmax'))
model.compile(loss='mean_squared_error',
optimizer='sgd',
metrics=['accuracy'])
X_train, X_test, y_train, y_test = train_test_split(dummyX, dummyY, test_size=0.20, random_state=42)
model.fit(X_train, y_train,nb_epoch=20, batch_size=30, validation_data=(X_test, y_test))
# Epoch 20/20
# 3200/3200 [==============================] - 0s - loss: 0.2469 - acc: 0.4366 - val_loss: 0.2468 - val_acc: 0.4063
# Out[460]:
# SVM - note that y_train and test are binary label. I haven't included the multi class converter code here for brevity
svm = SVC()
svm.fit(X_train, y_train)
svm.score(X_test, y_test)
# 0.891249
</code></pre>
<p><strong>TL;DR</strong></p>
<p>Made dummy data; neural network sucked; SVM kicked walloped it. Please help</p>
| 1 | 2016-07-28T23:14:15Z | 38,672,367 | <p>After several tries of your example, I figured out that accuracy fluctuates between 0.3 and to 0.9 regardless of learning technique. I believe that this happening because of random and meaningless data â itâs hardly possible to recognize any features inside white noise</p>
<p>I suggest using meaningful datasets like <a href="http://yann.lecun.com/exdb/mnist/" rel="nofollow">MNIST</a> to compare the accuracy of different approaches</p>
<p>About parameters. As it mentioned Matias, itâs better use categorical_crossentropy for this case. Also I suggest using adadelta optimizer if you donât want to do manual tuning of parameters</p>
| 0 | 2016-07-30T09:24:07Z | [
"python",
"neural-network",
"gpu",
"theano",
"keras"
] |
Problems converting string to integer splitting two variables in Python 3 | 38,648,216 | <p>Using Python 3.4 in Idle. Why am I getting this error message... </p>
<pre><code>ValueError: invalid literal for int() with base 10: '4 4'
</code></pre>
<p>when converting my input statement into an integer. I'm trying to put <code>int</code> in my input statement vs using </p>
<pre><code>num1 = int(num1)
num2 = int(num2)
</code></pre>
<p>The first way works, but why doesn't the second way? The second way would work if I ran this code:</p>
<pre><code>number = int(input("Number?"))
print(number)
</code></pre>
<p>So why doesn't it work the second way?</p>
<p><strong>First way works:</strong> </p>
<pre><code>#Ask the user to input 2 values and store them in variables num1 num2
num1, num2 = input("Enter 2 numbers: ").split()
#Convert the strings into regular numbers Integer
num1 = int(num1)
num2 = int(num2)
# Type problems and store in a variable
sum = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2
remainder = num1 % num2
print("{} + {} = {}".format(num1,num2,sum))
print("{} - {} = {}".format(num1,num2,difference))
print("{} * {} = {}".format(num1,num2,product))
print("{} / {} = {}".format(num1,num2,quotient))
print("{} % {} = {}".format(num1,num2,remainder))
</code></pre>
<p>This way doesn't work. I only put this piece of the code to show what I did differently. Besides this line and the other way to convert the string into an integer (num = int) the rest of the code is the same.</p>
<p><strong>2nd way</strong>:</p>
<pre><code>num1, num2 = int(input("Enter 2 numbers: ")).split()
</code></pre>
| 0 | 2016-07-28T23:17:19Z | 38,648,281 | <p>Your second way is trying to convert <code>4 4</code> into an <code>int</code> which it can't do, you need to apply <code>int</code> to each individual number as a string, so your code becomes:</p>
<pre><code>num1, num2 = map(int, input('Enter 2 numbers: ').split())
</code></pre>
<p>On a side note - by calling your variable <code>sum</code> later on you're shadowing the builtin <code>sum</code> which may lead to problems further down the line - I normally use <code>total</code>.</p>
<p>You can also make use of the functions in the <code>operator</code> module to make it a bit simpler:</p>
<pre><code>import operator as op
num1, num2 = map(int, input('Enter 2 numbers: ').split())
for symbol, func in (
('+', op.add), ('-', op.sub), ('*', op.mul),
('/', op.truediv), ('%', op.mod)
):
print('{} {} {} = {}'.format(num1, symbol, num2, func(num1, num2)))
# or print(num1, symbol, num2, '=', func(num1, num2))
</code></pre>
<p>Entering <code>4 4</code> will give you:</p>
<pre><code>4 + 4 = 8
4 - 4 = 0
4 * 4 = 16
4 / 4 = 1.0
4 % 4 = 0
</code></pre>
| 0 | 2016-07-28T23:25:18Z | [
"python",
"python-3.4"
] |
How to call a function for every for iteration of a zip of two lists? | 38,648,220 | <p>I have two lists:
<code>a=[1,2,3]</code>, <code>b=[a,b,c]</code></p>
<p>I want for each <code>zip</code> of those two to call a function, but not to do it in a trivial way inside a for loop. Is there a pythonic way? I tried with a <code>map</code>:</p>
<p><code>map(func(i,v) for i,v in zip(a,b))</code></p>
<p>but it does not work</p>
| 0 | 2016-07-28T23:18:10Z | 38,648,247 | <p>A list comprehension is almost always faster or equivalent to <code>map</code>. If you append the results of the comprehension to a list (as in the example), then a comprehension is also faster than a <code>for loop</code>:</p>
<pre><code>a = [1, 2, 3]
b = ['a', 'b', 'c']
c = []
def foo(x, y):
global c
result = x * y
c.append(result)
return result
>>> c
[]
>>> [foo(x, y) for x, y in zip(a, b)]
['a', 'bb', 'ccc']
>>> c
['a', 'bb', 'ccc']
</code></pre>
| 1 | 2016-07-28T23:20:53Z | [
"python",
"dictionary",
"iterator"
] |
How to call a function for every for iteration of a zip of two lists? | 38,648,220 | <p>I have two lists:
<code>a=[1,2,3]</code>, <code>b=[a,b,c]</code></p>
<p>I want for each <code>zip</code> of those two to call a function, but not to do it in a trivial way inside a for loop. Is there a pythonic way? I tried with a <code>map</code>:</p>
<p><code>map(func(i,v) for i,v in zip(a,b))</code></p>
<p>but it does not work</p>
| 0 | 2016-07-28T23:18:10Z | 38,648,272 | <p>The pythonic way <em>is</em> the for loop:</p>
<pre><code>for i, v in zip(a, b):
func(i, v)
</code></pre>
<p>Clear, concise, readable. What's not to like?</p>
| 5 | 2016-07-28T23:24:24Z | [
"python",
"dictionary",
"iterator"
] |
How to call a function for every for iteration of a zip of two lists? | 38,648,220 | <p>I have two lists:
<code>a=[1,2,3]</code>, <code>b=[a,b,c]</code></p>
<p>I want for each <code>zip</code> of those two to call a function, but not to do it in a trivial way inside a for loop. Is there a pythonic way? I tried with a <code>map</code>:</p>
<p><code>map(func(i,v) for i,v in zip(a,b))</code></p>
<p>but it does not work</p>
| 0 | 2016-07-28T23:18:10Z | 38,648,493 | <p><strong>If</strong> the function <code>func</code> doesn't return anything, you could use:</p>
<pre><code>any(func(i, v) for i,v in zip(a, b))
</code></pre>
<p>Which will return <code>False</code> but not accumulate the results.</p>
<p>This would not be considered "Pythonic" by many since <code>any()</code> is being used for its side-effects, and therefore isn't very explicit.</p>
| 0 | 2016-07-28T23:54:17Z | [
"python",
"dictionary",
"iterator"
] |
In Jupyter Lab, execute editor code in Python console | 38,648,286 | <p>In <a href="https://github.com/jupyter/jupyterlab" rel="nofollow">Jupyter Lab</a>, I want to send code from the editor to the Python console for execution, preferably with a keyboard shortcut. The documentation doesn't seem to offer a way to do this, but it's such a fundamental aspect of an IDE that I imagine it's probably possible. </p>
| 0 | 2016-07-28T23:25:48Z | 39,419,764 | <p>This is planned as a feature for the 1.0 release. See <a href="https://github.com/jupyter/jupyterlab/issues/450" rel="nofollow">https://github.com/jupyter/jupyterlab/issues/450</a> </p>
| 0 | 2016-09-09T21:11:40Z | [
"python",
"anaconda",
"jupyter",
"jupyter-notebook"
] |
In JavaScript code how to get data from a Python JSON variable | 38,648,316 | <p>The following code in Python:</p>
<pre><code>jsVar = (json.dumps(jsPass))
</code></pre>
<p>produces this output: </p>
<pre><code>{
"TT1004": [
[1004, 45.296109039999997, -75.926546579999993,
66.996664760000002, 150, false
]
],
"TT1001": [
[1001, 45.296471220000001, -75.923881289999997, 64.616423409999996, 150, false]
],
"TT1003": [
[1003, 45.296109379999997, -75.926543379999998,
67.240025419999995, 150, false
]
],
"TT1002": [
[1002, 45.29626098, -75.924908610000003, 65.300880480000004, 150, true]
]
}
</code></pre>
<p>The output passes validation on the JSON Formatter & Validator website. </p>
<p>In the JavaScript code Iâve set the following:</p>
<pre><code>var myVar2 = {};
var myVar2 = jsVar;
</code></pre>
<p>When I look at the output of the <code>console.log</code> or <code>.dir</code> methods for the JavaScript variable <code>myVar2</code>, there is no data. It returns <code>Object { }</code> along with an empty <code>__proto__:Object</code>.</p>
<p>In order to test that the Python data that is generated is correct JS, I have manually placed the data into the JavaScript variable which logs the following: </p>
<pre><code>{
TT1004: Array[1],
TT1001: Array[1],
TT1003: Array[1],
TT1002: Array[1]
}
</code></pre>
<p>What I need to learn is how to import the Python JSON jsVar variable into the JavaScript Code.</p>
| 1 | 2016-07-28T23:29:38Z | 38,649,347 | <p><strong>From your original post</strong>:<br></p>
<blockquote>
<p>Python: <code>jsVar = (json.dumps(jsPass))</code></p>
<p>JavaScript code: <code>var myVar2 = jsVar;</code></p>
</blockquote>
<p><strong>Q:</strong> How to access Python JSON variable from Javascript code?</p>
<p><strong>A:</strong>
Python and Javascript are two different languages and you would run them differently, for instance to run Python code you normally use the <code>python</code> binary and to execute Javascript you would use a JS engine like Google's <code>V8</code>.</p>
<p><strong>Note that:</strong> When you run your python and javascript code, that is essentially taken care by 2 different processes. That is, they will have different memory space hence it is not possible for your Javascript process to access memory space of your Python code, unless we are talking about Unix's <code>shared memory</code>. (I won't bother touching on this)</p>
<p>So if you are thinking about directly accessing a variable from 1 language or even process to another process then it is <strong>NOT</strong> possible. </p>
<p>However, keep in mind that a variable is just a reference to your content. What I'm trying to say is - you don't need the variable to be ported across, rather you need the content.</p>
<p>The easiest method for a newbie would be to serialize (layman term: save) the content to a <code>File</code> and then have the Javascript process read out the content and parse it back into an object.</p>
<p>I hope these guides will be useful to you;</p>
<p><strong>Python side:</strong><br>
For writing JSON data to a File using Python - you can refer to this SO post for solution.<br>
<a href="http://stackoverflow.com/questions/12309269/how-do-i-write-json-data-to-a-file-in-python">How do I write JSON data to a file in Python?</a></p>
<p><strong>Javascript side:</strong><br>
For reading JSON data back out from a file you can easily do this through NodeJS.<br>
<a href="http://stackoverflow.com/questions/10011011/using-node-js-how-do-i-read-a-json-object-into-server-memory">Using Node.JS, how do I read a JSON object into (server) memory?</a></p>
| 0 | 2016-07-29T01:56:47Z | [
"javascript",
"python",
"json"
] |
Pulling Data from App Annie API - Python | 38,648,328 | <p>I need to pull some data from App Annie's API using Python. However I am unable to connect. I double checked my API key and the "documentation". Does anyone know how I can connect through their API? I keep getting a 401 unauthorized access error.</p>
<p><a href="https://support.appannie.com/hc/en-us/articles/204208864-3-Authentication" rel="nofollow">https://support.appannie.com/hc/en-us/articles/204208864-3-Authentication</a></p>
<pre><code>import json
import requests
url = 'https://api.appannie.com/v1.2/apps/ios/app/12345678/reviews?start_date=2012-01-01&end_date=2012-02-01&countries=US'
key = 'Authorization: bearer b7e26.........'
response = requests.get(url, key) #After running up to this I get 401
data = json.loads(response.json()) #data is a dictionary
</code></pre>
| 0 | 2016-07-28T23:32:17Z | 38,648,409 | <p>You need to specify your api key in the HTTP header:</p>
<pre><code>response = requests.get(url,
headers={'Authorization':'bearer b7e26.........'})
</code></pre>
| 0 | 2016-07-28T23:43:10Z | [
"python",
"appannie"
] |
Can I call a dict of python objects from with a method of another class? | 38,648,355 | <p>I've created a class called Emp has attributes like employee number, department number, employee type etc. I've used this class to populate a dictionary called emp_dict.</p>
<p>I've done a similar thing for Dept with details of the department, now I want to create a method in the department class to measure the number contractors in this class but do do this I reference the emp_dict. </p>
<pre><code>class Dept():
def __init__(self,deptno, deptname):
self.deptno = deptno
def contractor_count(self,qtr,emp_dict):
contractor_count = 0
if qtr in ['FY14Q1A','FY14Q2A','FY14Q3A','FY14Q4A',\
'FY15Q1A','FY15Q2A','FY15Q3A','FY15Q4A',\
'FY16Q1A','FY16Q2A','FY16Q3A','FY16Q4A',\
'FY17Q1A','FY17Q2A','FY17Q3A','FY17Q4A']:
for worker in self.allo[qtr].keys():
if emp_dict[worker].emptype != "R" :
contractor_count_= 1
return contractor_count
</code></pre>
<p>When I tried using the count_contractor method it returns the initial value: 0
Should I be using another approach?</p>
| 2 | 2016-07-28T23:34:51Z | 38,648,361 | <p>The <code>contractor_count</code> variable is never touched again. You have: </p>
<pre><code>contractor_count_= 1
</code></pre>
<p>Did you mean this?</p>
<pre><code>contractor_count += 1
</code></pre>
<p>I would also recommend using a variable name that is different from the method name, to avoid possible confusion. </p>
| 2 | 2016-07-28T23:36:08Z | [
"python"
] |
Can I call a dict of python objects from with a method of another class? | 38,648,355 | <p>I've created a class called Emp has attributes like employee number, department number, employee type etc. I've used this class to populate a dictionary called emp_dict.</p>
<p>I've done a similar thing for Dept with details of the department, now I want to create a method in the department class to measure the number contractors in this class but do do this I reference the emp_dict. </p>
<pre><code>class Dept():
def __init__(self,deptno, deptname):
self.deptno = deptno
def contractor_count(self,qtr,emp_dict):
contractor_count = 0
if qtr in ['FY14Q1A','FY14Q2A','FY14Q3A','FY14Q4A',\
'FY15Q1A','FY15Q2A','FY15Q3A','FY15Q4A',\
'FY16Q1A','FY16Q2A','FY16Q3A','FY16Q4A',\
'FY17Q1A','FY17Q2A','FY17Q3A','FY17Q4A']:
for worker in self.allo[qtr].keys():
if emp_dict[worker].emptype != "R" :
contractor_count_= 1
return contractor_count
</code></pre>
<p>When I tried using the count_contractor method it returns the initial value: 0
Should I be using another approach?</p>
| 2 | 2016-07-28T23:34:51Z | 38,648,451 | <p>It seems like you have a spelling error, and hit <code>_</code> instead of <code>+</code>:</p>
<p>your code should be:</p>
<pre><code>class Dept():
def __init__(self,deptno, deptname):
self.deptno = deptno
def contractor_count(self,qtr,emp_dict):
contractor_count = 0
if qtr in ['FY14Q1A','FY14Q2A','FY14Q3A','FY14Q4A',\
'FY15Q1A','FY15Q2A','FY15Q3A','FY15Q4A',\
'FY16Q1A','FY16Q2A','FY16Q3A','FY16Q4A',\
'FY17Q1A','FY17Q2A','FY17Q3A','FY17Q4A']:
for worker in self.allo[qtr].keys():
if emp_dict[worker].emptype != "R" :
contractor_count+= 1
return contractor_count
</code></pre>
<p>The correction for the line: <code>contractor_count+= 1</code></p>
| 0 | 2016-07-28T23:49:12Z | [
"python"
] |
OpenCV Hough Circle Transform needs 8-bit image | 38,648,387 | <p>I am working with Hough Circle Transform with my RaspberryPi and when I take a ROI to check for circle like this:</p>
<pre><code>for (x,y,w,h) in trafficLights:
cv2.rectangle(image,(x,y),(x+w,y+h),(0,0,255),2)
roi = image[y:y+h,x:x+w]
roi = cv2.medianBlur(roi,5)
circles = cv2.HoughCircles(roi,cv2.HOUGH_GRADIENT,1,20,
param1=50,param2=60,minRadius=0,maxRadius=0)
circles = numpy.uint16(numpy.around(circles))
for i in circles[0,:]:
if i[2] < 100:
cv2.circle(image,(i[0],i[1]),i[2],(0,255,0),2)
cv2.circle(image,(i[0],i[1]),2,(0,0,255),3)
if i[1] > 315:
print "Green Light"
else:
print "Red Light"
</code></pre>
<p>I get this error</p>
<pre><code>The source image must be 8-bit, single-channel in function cvHoughCircles
</code></pre>
<p><a href="http://i.stack.imgur.com/TeMl6.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/TeMl6.jpg" alt="enter image description here"></a>
How can I transform the ROI to become an 8-bit image or does the error mean something else </p>
<p>Thank you in Advance!</p>
<p>Edit:</p>
<p><a href="http://i.stack.imgur.com/OdwCO.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/OdwCO.jpg" alt="enter image description here"></a></p>
| 0 | 2016-07-28T23:39:50Z | 38,660,785 | <p>Thank you Miki and bpachev for the help!</p>
<p>The first error means that you need to convert it to grayscale like this</p>
<pre><code>gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
</code></pre>
<p>And the NoneType error means that no circles were found so to advoid the error you can add this if statement </p>
<pre><code>if circles is not None:
circles = numpy.round(circles[0, :]).astype("int")
</code></pre>
<p>Then since no circles were found where I knew there were circles I had to play around with the settings of the detector.</p>
| 0 | 2016-07-29T14:00:45Z | [
"python",
"opencv",
"numpy",
"channel",
"hough-transform"
] |
Creating a polling bot | 38,648,468 | <pre><code>import requests
dados = {"action": "polls",
"view":"process",
"poll_id":"2",
"poll_2":"6",
"poll_2_nonce":"e29cc82a53"}
url = "http://soulegal.byethost7.com/wp/wp-admin/admin-ajax.php"
requests.post(url, data=dados)
</code></pre>
<p>The site URL is : <a href="http://soulegal.byethost7.com/wp/2016/07/28/pesquisa-eu-sou-legal" rel="nofollow">http://soulegal.byethost7.com/wp/2016/07/28/pesquisa-eu-sou-legal</a></p>
<p>The wordpress plugin is WP-Polls.</p>
<p>The site is mine (Iâm not testing in third part page )
Still it does not work. I wonder what âs going on?
I can vote manually but not with the code !</p>
| 1 | 2016-07-28T23:51:17Z | 38,648,532 | <p>Wordpress creates an IP/PC/Mac address and sever side keys (similiar to the PHP session id) which is used for loading. As well you might want to check what cookies are going back and forth between your browser and the voting poll page. </p>
| 0 | 2016-07-29T00:00:33Z | [
"python",
"python-requests"
] |
Creating a polling bot | 38,648,468 | <pre><code>import requests
dados = {"action": "polls",
"view":"process",
"poll_id":"2",
"poll_2":"6",
"poll_2_nonce":"e29cc82a53"}
url = "http://soulegal.byethost7.com/wp/wp-admin/admin-ajax.php"
requests.post(url, data=dados)
</code></pre>
<p>The site URL is : <a href="http://soulegal.byethost7.com/wp/2016/07/28/pesquisa-eu-sou-legal" rel="nofollow">http://soulegal.byethost7.com/wp/2016/07/28/pesquisa-eu-sou-legal</a></p>
<p>The wordpress plugin is WP-Polls.</p>
<p>The site is mine (Iâm not testing in third part page )
Still it does not work. I wonder what âs going on?
I can vote manually but not with the code !</p>
| 1 | 2016-07-28T23:51:17Z | 38,648,557 | <p>So you need to do a few things:</p>
<ol>
<li><p>You need to use a <code>requests.Session</code> instance so it can track cookies for you, including the cookie that Wordpress uses to allow you to vote from your poll page (which you have to make a get request to first).</p></li>
<li><p>You need to get the nonce value dynamically</p></li>
<li><p>To vote repeatedly, you need to get rid of the voted cookie after submission.</p></li>
</ol>
| 1 | 2016-07-29T00:03:36Z | [
"python",
"python-requests"
] |
How do I read buffers from Gamemaker Studio in Python 3? | 38,648,502 | <p>I want to write a server in Python 3, I haven't used Python before and I have an idea on how the syntax works. But if I sent data like this through Gamemaker Studio</p>
<pre><code> var buffer = buffer_create(1024,buffer_grow,1);
buffer_seek(buffer,buffer_seek_start,0);
buffer_write(buffer,buffer_s32,5);
buffer_write(buffer,buffer_string,'test');
network_send_raw(socket,buffer,buffer_tell(buffer))
</code></pre>
<p>How would I read it on a Python server, and how would I send data back in this format?</p>
| 2 | 2016-07-28T23:55:05Z | 39,183,856 | <p>Yo can read buffer using <code>struct.unpack</code> on python. here is the documentation <a href="https://docs.python.org/3.1/library/struct.html" rel="nofollow">https://docs.python.org/3.1/library/struct.html</a></p>
| 0 | 2016-08-27T17:25:43Z | [
"python",
"game-maker"
] |
Optimise python function fetching multi-level json attributes | 38,648,535 | <p>I have a 3 level json file. I am fetching the values of some of the attributes from each of the 3 levels of json. At the moment, the execution time of my code is pathetic as it is taking about 2-3 minutes to get the results on my web page. I will be having a much larger json file to deal with in production. </p>
<p>I am new to python and flask and haven't done much of web programming. Please suggest me ways I could optimise my below code! Thanks for help, much appreciated. </p>
<pre><code>import json
import urllib2
import flask
from flask import request
def Backend():
url = 'http://localhost:8080/surveillance/api/v1/cameras/'
response = urllib2.urlopen(url).read()
response = json.loads(response)
components = list(response['children'])
urlComponentChild = []
for component in components:
urlComponent = str(url + component + '/')
responseChild = urllib2.urlopen(urlComponent).read()
responseChild = json.loads(responseChild)
camID = str(responseChild['id'])
camName = str(responseChild['name'])
compChildren = responseChild['children']
compChildrenName = list(compChildren)
for compChild in compChildrenName:
href = str(compChildren[compChild]['href'])
ID = str(compChildren[compChild]['id'])
urlComponentChild.append([href,ID])
myList = []
for each in urlComponentChild:
response = urllib2.urlopen(each[0]).read()
response = json.loads(response)
url = each[0] + '/recorder'
responseRecorder = urllib2.urlopen(url).read()
responseRecorder = json.loads(responseRecorder)
username = str(response['subItems']['surveillance:config']['properties']['username'])
password = str(response['subItems']['surveillance:config']['properties']['password'])
manufacturer = str(response['properties']['Manufacturer'])
model = str(response['properties']['Model'])
status = responseRecorder['recording']
myList.append([each[1],username,password,manufacturer,model,status])
return myList
APP = flask.Flask(__name__)
@APP.route('/', methods=['GET', 'POST'])
def index():
""" Displays the index page accessible at '/'
"""
if request.method == 'GET':
return flask.render_template('index.html', response = Backend())
if __name__ == '__main__':
APP.debug=True
APP.run(port=62000)
</code></pre>
| 1 | 2016-07-29T00:01:02Z | 38,648,809 | <p>Ok, caching. So what we're going to do is start returning values to the user instantly based on data we already have, rather than generating new data every time. This means that the user might get slightly less up to date data than is theoretically possible to get, but it means that the data they do receive they receive as quickly as is possible given the system you're using.</p>
<p>So we'll keep your backend function as it is. Like I said, you could certainly speed it up with multithreading (If you're still interested in that, the 10 second version is that I would use <a href="https://github.com/kennethreitz/grequests" rel="nofollow">grequests</a> to asynchronously get data from a list of urls).</p>
<p>But, rather than call it in response to the user every time a user requests data, we'll just call it routinely every once in a while. This is almost certainly something you'd want to do eventually anyway, because it means you don't have to generate brand new data for each user, which is extremely wasteful. We'll just keep some data on hand in a variable, update that variable as often as we can, and return whatever's in that variable every time we get a new request.</p>
<pre><code>from threading import Thread
from time import sleep
data = None
def Backend():
.....
def main_loop():
while True:
sleep(LOOP_DELAY_TIME_SECONDS)
global data
data = Backend()
APP = flask.Flask(__name__)
@APP.route('/', methods=['GET', 'POST'])
def index():
""" Displays the index page accessible at '/'
"""
if request.method == 'GET':
# Return whatever data we currently have cached
return flask.render_template('index.html', response = data)
if __name__ == '__main__':
data = Backend() # Need to make sure we grab data before we start the server so we never return None to the user
Thread(target=main_loop).start() #Loop and grab new data at every loop
APP.debug=True
APP.run(port=62000)
</code></pre>
<p>DISCLAIMER: I've used Flask and threading before for a few projects, but I am by no means an expert on it or web development, at all. Test this code before using it for anything important (or better yet, find someone who knows that they're doing before using it for anything important)</p>
<p>Edit: data will have to be a global, sorry about that - hence the disclaimer</p>
<hr>
| 0 | 2016-07-29T00:37:24Z | [
"python",
"json",
"python-2.7",
"flask",
"flask-restful"
] |
Open .exe file through .bat file in Flask | 38,648,550 | <p>I am trying to open an .exe file (e.g. Paint) with a html button using Flask, so I wrote a small .bat file that runs it properly when I run it through Python, but does not seem to work when I open it through Flask.</p>
<p>The Python is:</p>
<pre><code>@app.route('/assemblies', methods=['GET', 'POST'])
def assemblies():
if request.method == 'POST':
if request.form['submit'] == 'runFile':
#os.startfile("/static/run.bat")
text = "... running ..."
filepath="/static/run.bat"
p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE)
stdout, stderr = p.communicate()
return render_template('assemblies.html', text=text)
else request.form['submit'] == 'process':
[do other stuff]
elif request.method == 'GET':
return render_template('assemblies.html')
</code></pre>
<p>(Part of) the html file is:</p>
<pre><code><div class="container">
<form action="/assemblies" method="post"> ASSEMBLY <br>
<select name="Layer">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select><br>
<button type="submit" name="submit" value="process"> Process </button>
<button type="submit" name="submit" value="runFile"> Run </button>
</form>
</div>
</code></pre>
<p>And the bat is:</p>
<pre><code>start /d "static\" myFile.exe
</code></pre>
<p>The bat file works outside Flask, but I have tried with the exe and bat both in the 'static' folder and on C:/ and seems to be completely unresponsive (no console feedback), so I assume I might be missing something important?</p>
| 0 | 2016-07-29T00:02:43Z | 38,652,272 | <p>Found a solution after changing:</p>
<pre><code>filepath="/static/run.bat"
p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE)
stdout, = p.communicate()
</code></pre>
<p>for:</p>
<pre><code>subprocess.call(["static/myFile.exe"])
</code></pre>
<p>and now it works. I am bypassing the bat file, but not sure what was the problem with the original script, so any insights are still welcome. </p>
| 0 | 2016-07-29T06:51:39Z | [
"python",
"html",
"windows",
"batch-file",
"flask"
] |
Numpy trouble vectorizing certain kind of aggregation | 38,648,561 | <p>I am having difficulty in vectorizing the below operation:</p>
<pre><code># x.shape = (a,)
# y.shape = (a, b)
# x and y are ordered over a.
# Want to combine x, y into z.shape(num_unique_x, b)
# Below works and illustrates intent but is iterative
z = np.zeros((num_unique_x, b))
for i in range(a):
z[x[i], y[i, :]] += 1
</code></pre>
| 0 | 2016-07-29T00:03:54Z | 38,649,161 | <p>Your use of <code>num_unique_x</code>, and the size of <code>z</code> suggests that this is a case where <code>x</code> and <code>y</code> have repeats, and that some of the <code>z</code> will be larger than 1. In which case we need to use <code>np.add.at</code>. But to set that up I'd have review its documentation, and possibly test some alternatives.</p>
<p>But first a no-repeats case</p>
<pre><code>In [522]: x=np.arange(6)
In [523]: y=np.arange(3)+x[:,None]
In [524]: y
Out[524]:
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[4, 5, 6],
[5, 6, 7]])
</code></pre>
<p>See why I ask for a diagnostic example. I'm guessing as to possible values. I have to make a <code>z</code> with more than 3 columns.</p>
<pre><code>In [529]: z=np.zeros((6,8),dtype=int)
In [530]: for i in range(6):
...: z[x[i],y[i,:]]+=1
In [531]: z
Out[531]:
array([[1, 1, 1, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 1, 1, 1]])
</code></pre>
<p>The vectorized equivalent</p>
<pre><code>In [532]: z[x[:,None],y]
Out[532]:
array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
In [533]: z[x[:,None],y] += 1
In [534]: z
Out[534]:
array([[2, 2, 2, 0, 0, 0, 0, 0],
[0, 2, 2, 2, 0, 0, 0, 0],
[0, 0, 2, 2, 2, 0, 0, 0],
[0, 0, 0, 2, 2, 2, 0, 0],
[0, 0, 0, 0, 2, 2, 2, 0],
[0, 0, 0, 0, 0, 2, 2, 2]])
</code></pre>
<p>The corresponding <code>add.at</code> expression is</p>
<pre><code>In [538]: np.add.at(z,(x[:,None],y),1)
In [539]: z
Out[539]:
array([[3, 3, 3, 0, 0, 0, 0, 0],
[0, 3, 3, 3, 0, 0, 0, 0],
[0, 0, 3, 3, 3, 0, 0, 0],
[0, 0, 0, 3, 3, 3, 0, 0],
[0, 0, 0, 0, 3, 3, 3, 0],
[0, 0, 0, 0, 0, 3, 3, 3]])
</code></pre>
<p>So that works for this no-repeats case.</p>
<p>For repeats in <code>x</code>:</p>
<pre><code>In [542]: x1=np.array([0,1,1,2,3,5])
In [543]: z1=np.zeros((6,8),dtype=int)
In [544]: np.add.at(z1,(x1[:,None],y),1)
In [545]: z1
Out[545]:
array([[1, 1, 1, 0, 0, 0, 0, 0],
[0, 1, 2, 2, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 1]])
</code></pre>
<p>Without <code>add.at</code> we miss the <code>2s</code>.</p>
<pre><code>In [546]: z2=np.zeros((6,8),dtype=int)
In [547]: z2[x1[:,None],y] += 1
In [548]: z2
Out[548]:
array([[1, 1, 1, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 1]])
</code></pre>
| 1 | 2016-07-29T01:29:26Z | [
"python",
"numpy"
] |
Is there a workaround for "try: input() except KeyboardInterrupt:" | 38,648,691 | <p>I've searched this topic to no avail for hours.</p>
<p>Is it possible to do something along the lines of:</p>
<pre><code>try:
input_var = input('> ')
except KeyboardInterrupt:
print("This will not work.")
</code></pre>
<p>But when I try this and do CTRL-C, it just does nothing. </p>
<p>Is there any other way to achieve this?</p>
<p>Using Windows 10, Python 3.5.2, and Powershell</p>
<p>Note: I am not using the input_var for printing, I am doing 3 if/elif/else statements based around it. </p>
| 1 | 2016-07-29T00:20:50Z | 38,648,900 | <p>It sounds like you would be interested in the signal module. </p>
<p><a href="http://stackoverflow.com/a/1112350/4171411">This Answer</a> demonstrates how to use the signal module to capture Ctrl+C, or SIGINT.</p>
<p>For your use case, something along the lines of the following would work :</p>
<pre><code>#!/usr/local/bin/python3
import signal
def signal_handler(signal, frame):
raise KeyboardInterrupt('SIGINT received')
signal.signal(signal.SIGINT, signal_handler)
try :
input_var = input('> ')
except KeyboardInterrupt :
print("CTRL+C Pressed!")
</code></pre>
| 1 | 2016-07-29T00:51:31Z | [
"python",
"powershell",
"windows-10",
"python-3.5",
"try-except"
] |
mysql query failing due to "\" at the of one of string value | 38,648,696 | <p>I am generating queries using excel sheet in python and then executing the query using <code>conn.execute(query)</code>. </p>
<p>However one query is failing because it has <code>\</code> at the end of one of the value string. Look for <code>VALUES ("test", "ABCD\"</code> in the query below:</p>
<pre><code>INSERT INTO S_account(Sub, AccName, AccTeam, Terr, AccOwner,
Level1, GAccount, Customer, City, State, EndCusName, AccID)
VALUES ("test", "ABCD\", "test", "test", "test", "No", "Yes",
"test", "test", "test", "asdasdas")
ON DUPLICATE KEY UPDATE
Sub = VALUES(Sub), AccName = VALUES(AccName), AccTeam = VALUES(AccTeam),
Terr = VALUES(Terr), AccOwner = VALUES(AccOwner), Level1 = VALUES(Level1),
GAccount = VALUES(GAccount), Customer = VALUES(Customer),
City = VALUES(City), State = VALUES(State), EndCusName = VALUES(EndCusName)
</code></pre>
<p>I tried below command but it did not help.</p>
<pre><code>query = re.sub('\$', '' query)
</code></pre>
| 0 | 2016-07-29T00:21:24Z | 38,648,736 | <p>You specified 12 columns in your <code>INSERT</code> statement, but you only included values for 11 columns:</p>
<pre><code>INSERT INTO S_account(Sub, AccName, AccTeam, Terr, AccOwner, Level1,
GAccount, Customer, City, State, EndCusName, AccID)
VALUES ("test", "ABCD\", "test", "test", "test", "No",
"Yes", "test", "test", "test", "asdasdas", MISSING) -- no value for AccID
</code></pre>
<p>I don't think the backslash has anything to do with it. Did your error message actually mention backslash as being a problem?</p>
| 1 | 2016-07-29T00:28:17Z | [
"python",
"mysql"
] |
Scipy.optimize minimize is taking too long | 38,648,727 | <p>I am running a constrained optimization problem with about 1500 variables and it is taking over 30 minutes to run....</p>
<p>If I reduce the tolerance to 1 the minimization will complete in about five minutes, but that doesn't seem like a good way to speed things up. </p>
<pre><code>from scipy.optimize import minimize
results = minimize(objFun, initialVals, method='SLSQP', bounds = bnds, constraints=cons, tol = toler)
print(results)
fun: -868.72033130318198
jac: array([ 0., 0., 0., ..., 0., 0., 0.])
message: 'Optimization terminated successfully.'
nfev: 1459
nit: 1
njev: 1
status: 0
success: True
x: array([ 0., 0., 0., ..., 1., 1., 1.])
</code></pre>
<p>Any suggestions would be appreciated. </p>
| 1 | 2016-07-29T00:26:15Z | 38,656,480 | <p>Here's what I'd do:</p>
<ul>
<li>profile the minimization. From your output it seems that evaluating the function is the bottleneck. Check if it's so. If it is, then:</li>
<li>see if you can compute the jacobian with paper and pencil or a CAS system. Use it instead of finite differences.</li>
<li>see if you can speed up the function itself (mathematical simplifications, numpy vectorization, cython)</li>
</ul>
| 2 | 2016-07-29T10:25:59Z | [
"python",
"optimization",
"scipy",
"minimize"
] |
Scipy.optimize minimize is taking too long | 38,648,727 | <p>I am running a constrained optimization problem with about 1500 variables and it is taking over 30 minutes to run....</p>
<p>If I reduce the tolerance to 1 the minimization will complete in about five minutes, but that doesn't seem like a good way to speed things up. </p>
<pre><code>from scipy.optimize import minimize
results = minimize(objFun, initialVals, method='SLSQP', bounds = bnds, constraints=cons, tol = toler)
print(results)
fun: -868.72033130318198
jac: array([ 0., 0., 0., ..., 0., 0., 0.])
message: 'Optimization terminated successfully.'
nfev: 1459
nit: 1
njev: 1
status: 0
success: True
x: array([ 0., 0., 0., ..., 1., 1., 1.])
</code></pre>
<p>Any suggestions would be appreciated. </p>
| 1 | 2016-07-29T00:26:15Z | 38,657,261 | <p>Your tolerance should be set to whatever tolerance you need. Setting it higher just tells the optimiser to stop sooner and doesn't actually speed it up. That being said, allowing it to go to a greater tollerence might be a waste of your time if not needed.</p>
<p>Possible ways to reduce the time required are as follows:</p>
<ul>
<li>Use a different optimiser</li>
<li>Use a different gradient finding method</li>
<li>Speed up your objective function</li>
<li>Reduce the number of design variables</li>
<li>Choose a better initial guess</li>
<li>Use parallel processing</li>
</ul>
<h1>Gradient methods</h1>
<p>As you are using finite difference, you need (1 + the number of design variables) evaluations of your objective function to get the total sensitivity. </p>
<p>As ev-br said, if you can find the analytical solution to the jacobian then this isn't needed. Based on the fact you have 1500 design variables. Im guessing this isnt easy, though if your objective function allows, automatic differentiation might be an option. Iv had some experience with <a href="https://pythonhosted.org/algopy/" rel="nofollow">AlgoPy</a> which you could look at.</p>
<h1>Objective function speed</h1>
<p>Due to the high number of objective function evaluations, this may be the easiest approach. Once again, see ev-br's answer for things like compiling using <a href="http://cython.org/" rel="nofollow">cython</a>, and general reducing complexity. You could try running parts of the code using <a href="https://docs.python.org/2/library/timeit.html" rel="nofollow">timeit</a> so see if changes are beneficial.</p>
<h1>Design variables</h1>
<p>Reducing the number of design variables linearly lowers the objective function calls needed for the finite difference. Do all your variables change significantly? Could some be fixed at a set value? Can you derive some as a function of others?</p>
<h1>Initial Guess</h1>
<p>Depending on your problem, you may be able to select a better starting point that will mean your optimiser is 'closer' to the final solution. Depending on your problem, you may also be able to 'restart' your optimisation from a previous result.</p>
<h1>Parallelisation</h1>
<p>The finite difference evaluations don't have to be done in order so you could write your own finite difference function and then run the calls in parallel using the <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">multiprocessing</a> class. The effectiveness of this is based on your system and number of cores available.</p>
| 1 | 2016-07-29T11:05:29Z | [
"python",
"optimization",
"scipy",
"minimize"
] |
Why does numpy least squares result diverge from using the direct formula? | 38,648,730 | <p>I want to calculate the least squares estimate for given data.</p>
<p>There are a few ways to do this, one is to use numpy's least squares:</p>
<pre><code>import numpy
np.linalg.lstsq(X,y)[0]
</code></pre>
<p>Where X is a matrix and y a vector of compatible dimension (type float64). Second way is to calculate the result directly using the formula:</p>
<pre><code>import numpy
numpy.linalg.inv(X.T.dot(X)).dot(X.T).dot(y)
</code></pre>
<p>My problem: there are cases where the different formulas give radically different results (although there may be no difference). Sometimes the coefficients grow to be extremely large, using one formula, while the other is much more well behaved. The formulas are the same so why can the results diverge so much? Is this some type of rounding error and how do I minimize it?</p>
| 8 | 2016-07-29T00:26:27Z | 38,648,835 | <p>While those two formulas are mathematically equivalent, they <strong>are not</strong> numerically equivalent! There are better ways to solve a system of linear equations Ax = b than by multiplying both sides by A^(-1), like <a href="https://en.wikipedia.org/wiki/Gaussian_elimination">Gaussian Elimination</a>. <code>numpy.linalg.lstsq</code> uses this (and more sophisticated) methods to solve the underlying linear system, plus it can handle a lot of corner cases. So use it when you can.</p>
<p>Matrix inversion is very numerically unstable. Don't do it unless you have to.</p>
| 5 | 2016-07-29T00:42:04Z | [
"python",
"numpy"
] |
Color between the x axis and the graph in PyPlot | 38,648,770 | <p>I have a graph that was plotted using datetime objects for the x axis and I want to be able to color beneath the graph itself (the y-values) and the x axis. I found this post <a href="http://stackoverflow.com/questions/28091290/matplotlibs-fill-between-doesnt-work-with-plot-date-any-alternatives">Matplotlib's fill_between doesnt work with plot_date, any alternatives?</a> describing a similar problem, but the proposed solutions didn't help me at all.</p>
<p>My code:</p>
<pre><code>import matplotlib.patches as mpatches
import matplotlib.dates
import matplotlib.pyplot as plt
import numpy as np
import csv
from tkinter import *
from datetime import datetime
from tkinter import ttk
columns="YEAR,MONTH,DAY,HOUR,PREC,PET,Q,UZTWC,UZFWC,LZTWC,LZFPC,LZFSC,ADIMC,AET"
data_file="FFANA_000.csv"
UZTWC = np.genfromtxt(data_file,
delimiter=',',
names=columns,
skip_header=1,
usecols=("UZTWC"))
list_of_datetimes = []
skipped_header = False;
with open(data_file, 'rt') as f:
reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
for row in reader:
if skipped_header:
date_string = "%s/%s/%s %s" % (row[0].strip(), row[1].strip(), row[2].strip(), row[3].strip())
dt = datetime.strptime(date_string, "%Y/%m/%d %H")
list_of_datetimes.append(dt)
skipped_header = True
dates = matplotlib.dates.date2num(list_of_datetimes)
fig = plt.figure(1)
#UZTWC
ax1 = fig.add_subplot(111)
plt.plot(dates, UZTWC, '-', color='b', lw=2)
ax1.fill_between(dates, 0, UZTWC)
fig.autofmt_xdate()
plt.title('UZTWC', fontsize=15)
plt.ylabel('MM', fontsize=10)
plt.tick_params(axis='both', which='major', labelsize=10)
plt.tick_params(axis='both', which='minor', labelsize=10)
plt.grid()
plt.show()
</code></pre>
<p>This yields:</p>
<pre><code>Traceback (most recent call last):
File "test_color.py", line 36, in <module>
ax1.fill_between(dates, 0, UZTWC)
File "C:\Users\rbanks\AppData\Local\Programs\Python\Python35-32\lib\site-packages\matplotlib\__init__.py", line 1812, in inner
return func(ax, *args, **kwargs)
File "C:\Users\rbanks\AppData\Local\Programs\Python\Python35-32\lib\site-packages\matplotlib\axes\_axes.py", line 4608, in fill_between
y2 = ma.masked_invalid(self.convert_yunits(y2))
File "C:\Users\rbanks\AppData\Local\Programs\Python\Python35-32\lib\site-packages\numpy\ma\core.py", line 2300, in masked_invalid
condition = ~(np.isfinite(a))
TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
</code></pre>
<p>It seems the issue comes with fill_between not being able to handle my dates being of type 'numpy.ndarray'. Do I need to just convert this to another data type for this to work?</p>
<p>EDIT: After more testing, I've found that I still get this exact error even after trying to use list_of_datetimes, and after converting all of my datetimes to timestamps, so I'm starting to wonder if it is a type issue after all.</p>
<p>Sample data:</p>
<pre><code>%YEAR,MO,DAY,HR,PREC(MM/DT),ET(MM/DT),Q(CMS), UZTWC(MM),UZFWC(MM),LZTWC(MM),LZFPC(MM),LZFSC(MM),ADIMC(MM), ET(MM/DT)
2012, 5, 1, 0, 0.000, 1.250, 0.003, 2.928, 0.000, 3.335, 4.806, 0.000, 6.669, 1.042
2012, 5, 1, 6, 0.000, 1.250, 0.003, 2.449, 0.000, 3.156, 4.798, 0.000, 6.312, 0.987
2012, 5, 1, 12, 0.000, 1.250, 0.003, 2.048, 0.000, 2.970, 4.789, 0.000, 5.940, 0.929
2012, 5, 1, 18, 0.000, 1.250, 0.003, 1.713, 0.000, 2.782, 4.781, 0.000, 5.564, 0.869
2012, 5, 2, 0, 0.000, 1.250, 0.003, 1.433, 0.000, 2.596, 4.772, 0.000, 5.192, 0.809
2012, 5, 2, 6, 0.000, 1.250, 0.003, 1.199, 0.000, 2.414, 4.764, 0.000, 4.829, 0.750
</code></pre>
<p>I am using Python 3.5.0 and matplotlib 1.5.1 on Windows 10 and I gained all of my dependencies through WinPython <a href="https://sourceforge.net/projects/winpython/" rel="nofollow">https://sourceforge.net/projects/winpython/</a></p>
| 2 | 2016-07-29T00:32:38Z | 38,664,967 | <p>I've yet to determine what went wrong in your original code but I got it working with <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a>:</p>
<pre><code>import pandas as pd, matplotlib.pyplot as plt, matplotlib.dates as mdates
df = pd.read_csv('/path/to/yourfile.csv')
df['date'] = df['%YEAR'].astype(str)+'/'+df['MO'].astype(str)+'/'+df['DAY'].astype(str)
df['date'] = pd.to_datetime(df['date'])
dates = [date.to_pydatetime() for date in df['date']]
yyyy_mm_dd_format = mdates.DateFormatter('%Y-%m-%d')
plt.clf()
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot_date(dates,df[' UZTWC(MM)'],'-',color='b',lw=2)
ax.fill_between(dates,0,df[' UZTWC(MM)'])
ax.xaxis.set_major_formatter(yyyy_mm_dd_format)
ax.set_xlim(min(dates), max(dates))
fig.autofmt_xdate()
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/CHMAf.png" rel="nofollow"><img src="http://i.stack.imgur.com/CHMAf.png" alt="enter image description here"></a></p>
| 1 | 2016-07-29T18:04:26Z | [
"python",
"matplotlib"
] |
Sorting with lambda in Python with an additional function | 38,648,814 | <p>I'm baffled by why this doesn't work.</p>
<p>I have a function called <code>value(word)</code> which returns an integer value for any string, e.g.: <code>value('chicken') = 53</code>.</p>
<p>Can <code>value()</code> be used within a lambda expression as a key to sort a list. In other words, can we do:</p>
<pre><code>words = ['chicken', 'tiger', 'bee'] # values : 53, 59, 12
sorted(words, key=lambda x: value(x))
# output: ['tiger', 'chicken', 'bee']
</code></pre>
<p>I defined <code>value</code> as</p>
<pre><code>def value(word):
return sum(ord(c) - 96 for c in word)
</code></pre>
<p>For some reason when I do this nothing is sorted.</p>
| -4 | 2016-07-29T00:37:54Z | 38,648,821 | <p>To get the order you expect, you need to sort in reverse order since the default is ascending order. You can use the <code>reverse</code> key word argument to do so. Also you can remove the <code>lambda</code> since <code>value</code> is <em>already</em> a function</p>
<pre><code>def value(word):
return sum(ord(c) - 96 for c in word)
words = ['chicken', 'tiger', 'bee']
S = sorted(words, key=value, reverse=True)
# ['tiger', 'chicken', 'bee']
</code></pre>
| 0 | 2016-07-29T00:39:30Z | [
"python",
"python-3.x"
] |
Sorting with lambda in Python with an additional function | 38,648,814 | <p>I'm baffled by why this doesn't work.</p>
<p>I have a function called <code>value(word)</code> which returns an integer value for any string, e.g.: <code>value('chicken') = 53</code>.</p>
<p>Can <code>value()</code> be used within a lambda expression as a key to sort a list. In other words, can we do:</p>
<pre><code>words = ['chicken', 'tiger', 'bee'] # values : 53, 59, 12
sorted(words, key=lambda x: value(x))
# output: ['tiger', 'chicken', 'bee']
</code></pre>
<p>I defined <code>value</code> as</p>
<pre><code>def value(word):
return sum(ord(c) - 96 for c in word)
</code></pre>
<p>For some reason when I do this nothing is sorted.</p>
| -4 | 2016-07-29T00:37:54Z | 38,648,868 | <p>Your function is working correctly:</p>
<pre><code>sorted(words, key=lambda x: value(x))
</code></pre>
<p>The issue is likely either with your <code>value</code> function or the sorting order. For instance, if your function is:</p>
<pre><code>def value(s):
return len(s)
</code></pre>
<p>then <code>sorted</code> will return <code>['bee', 'tiger', 'chicken']</code>, since <code>len('bee') = 3</code>, <code>len('tiger') = 5</code>, and <code>len('chicken') = 7</code>. </p>
<p>If you want it in descending order, you would do:</p>
<pre><code>sorted(words, key=lambda x: value(x), reverse=True)
</code></pre>
| 1 | 2016-07-29T00:47:53Z | [
"python",
"python-3.x"
] |
Bokeh Range Set Only 1 Bound | 38,648,896 | <p>I would expect the following code to set only the upper bound of the plot y range, however the lower bound is also inexplicably set to 0:</p>
<pre><code>import bokeh.plotting as bkp
import numpy as np
bkp.output_file("/tmp/test_plot.html")
fig = bkp.figure(y_range=[None, 100]) # plot y range: 0-100
# fig = bkp.figure() # plot y range: 50-100
fig.line(np.linspace(0, 1, 200), np.random.random(200)*50+50) # number range: 50-100
bkp.save(fig)
</code></pre>
<p>Why does this happen? What's the easiest way to set only 1 range bound?</p>
| 0 | 2016-07-29T00:51:04Z | 38,649,535 | <p>The <code>Range1d(start=None, end=100)</code> (as you are also referring to in your comments) is only defining your initial view. It doesn't make sense for a Range to not have both a starting point and an ending point, so if you give it <code>start=None</code>, it will just use its default value which is <code>0</code>.</p>
<p>I think what you are trying to do is something like this:</p>
<p><code>Range1D(start=value1, end=value2, bounds=(None, 100))</code></p>
<p>This will give you an upper bound of 100 and no lower bound.</p>
<p>See <a href="http://bokeh.pydata.org/en/0.11.1/docs/reference/models/ranges.html#bokeh.models.ranges.Range1d" rel="nofollow">docs</a> for more specifications and examples.</p>
<p>Edit: okay, I initially ready your question as though you were trying to set the bounds. You want to use the <code>DataRange1D</code> class instead, then. If you just make sure to not override the <code>start</code>, it will default to "auto".
In other words, this should do what you want:</p>
<p><code>DataRange1D(end=100)</code></p>
| 0 | 2016-07-29T02:17:01Z | [
"python",
"visualization",
"bokeh"
] |
Bokeh Range Set Only 1 Bound | 38,648,896 | <p>I would expect the following code to set only the upper bound of the plot y range, however the lower bound is also inexplicably set to 0:</p>
<pre><code>import bokeh.plotting as bkp
import numpy as np
bkp.output_file("/tmp/test_plot.html")
fig = bkp.figure(y_range=[None, 100]) # plot y range: 0-100
# fig = bkp.figure() # plot y range: 50-100
fig.line(np.linspace(0, 1, 200), np.random.random(200)*50+50) # number range: 50-100
bkp.save(fig)
</code></pre>
<p>Why does this happen? What's the easiest way to set only 1 range bound?</p>
| 0 | 2016-07-29T00:51:04Z | 38,650,362 | <p>You are replacing the auto-ranging default <code>DataRange1d</code> with a "dumb" (non-auto ranging) <code>Range1d</code>. Set the <code>end</code> value of the default range that the plot creates, without replacing the entire range. Or alternatively, replace with a new <code>DataRange1d</code>. </p>
| 1 | 2016-07-29T04:08:23Z | [
"python",
"visualization",
"bokeh"
] |
All rows within a given column must match, for all columns | 38,648,940 | <p>I have a Pandas DataFrame of data in which all rows within a given column must match:</p>
<pre><code>df = pd.DataFrame({'A': [1,1,1,1,1,1,1,1,1,1],
'B': [2,2,2,2,2,2,2,2,2,2],
'C': [3,3,3,3,3,3,3,3,3,3],
'D': [4,4,4,4,4,4,4,4,4,4],
'E': [5,5,5,5,5,5,5,5,5,5]})
In [10]: df
Out[10]:
A B C D E
0 1 2 3 4 5
1 1 2 3 4 5
2 1 2 3 4 5
...
6 1 2 3 4 5
7 1 2 3 4 5
8 1 2 3 4 5
9 1 2 3 4 5
</code></pre>
<p>I would like a quick way to know if there is an variance anywhere in the DataFrame. At this point, I don't need to know which values have varied, since I will be going in to handle those later. I just need a quick way to know if the DataFrame needs further attention or if I can ignore it and move on to the next one.</p>
<p>I can check any given column using</p>
<pre><code>(df.loc[:,'A'] != df.loc[0,'A']).any()
</code></pre>
<p>but my Pandas knowledge limits me to iterating through the columns (I understand iteration is frowned upon in Pandas) to compare all of them:</p>
<pre><code> A B C D E
0 1 2 3 4 5
1 1 2 9 4 5
2 1 2 3 4 5
...
6 1 2 3 4 5
7 1 2 3 4 5
8 1 2 3 4 5
9 1 2 3 4 5
for col in df.columns:
if (df.loc[:,col] != df.loc[0,col]).any():
print("Found a fail in col %s" % col)
break
Out: Found a fail in col C
</code></pre>
<p>Is there an elegant way to return a boolean if any row within any column of a dataframe does not match all the values in the column... possibly without iteration?</p>
| 3 | 2016-07-29T00:57:32Z | 38,648,975 | <p>You can use <code>apply</code> to loop through columns and check if all the elements in the column are the same:</p>
<pre><code>df.apply(lambda col: (col != col[0]).any())
# A False
# B False
# C False
# D False
# E False
# dtype: bool
</code></pre>
| 2 | 2016-07-29T01:03:16Z | [
"python",
"pandas"
] |
All rows within a given column must match, for all columns | 38,648,940 | <p>I have a Pandas DataFrame of data in which all rows within a given column must match:</p>
<pre><code>df = pd.DataFrame({'A': [1,1,1,1,1,1,1,1,1,1],
'B': [2,2,2,2,2,2,2,2,2,2],
'C': [3,3,3,3,3,3,3,3,3,3],
'D': [4,4,4,4,4,4,4,4,4,4],
'E': [5,5,5,5,5,5,5,5,5,5]})
In [10]: df
Out[10]:
A B C D E
0 1 2 3 4 5
1 1 2 3 4 5
2 1 2 3 4 5
...
6 1 2 3 4 5
7 1 2 3 4 5
8 1 2 3 4 5
9 1 2 3 4 5
</code></pre>
<p>I would like a quick way to know if there is an variance anywhere in the DataFrame. At this point, I don't need to know which values have varied, since I will be going in to handle those later. I just need a quick way to know if the DataFrame needs further attention or if I can ignore it and move on to the next one.</p>
<p>I can check any given column using</p>
<pre><code>(df.loc[:,'A'] != df.loc[0,'A']).any()
</code></pre>
<p>but my Pandas knowledge limits me to iterating through the columns (I understand iteration is frowned upon in Pandas) to compare all of them:</p>
<pre><code> A B C D E
0 1 2 3 4 5
1 1 2 9 4 5
2 1 2 3 4 5
...
6 1 2 3 4 5
7 1 2 3 4 5
8 1 2 3 4 5
9 1 2 3 4 5
for col in df.columns:
if (df.loc[:,col] != df.loc[0,col]).any():
print("Found a fail in col %s" % col)
break
Out: Found a fail in col C
</code></pre>
<p>Is there an elegant way to return a boolean if any row within any column of a dataframe does not match all the values in the column... possibly without iteration?</p>
| 3 | 2016-07-29T00:57:32Z | 38,648,997 | <p>Given your example dataframe:</p>
<pre><code>df = pd.DataFrame({'A': [1,1,1,1,1,1,1,1,1,1],
'B': [2,2,2,2,2,2,2,2,2,2],
'C': [3,3,3,3,3,3,3,3,3,3],
'D': [4,4,4,4,4,4,4,4,4,4],
'E': [5,5,5,5,5,5,5,5,5,5]})
</code></pre>
<p>You can use the following:</p>
<pre><code>df.apply(pd.Series.nunique) > 1
</code></pre>
<p>Which gives you:</p>
<pre><code>A False
B False
C False
D False
E False
dtype: bool
</code></pre>
<p>If we then force a couple of errors:</p>
<pre><code>df.loc[3, 'C'] = 0
df.loc[5, 'B'] = 20
</code></pre>
<p>You then get:</p>
<pre><code>A False
B True
C True
D False
E False
dtype: bool
</code></pre>
| 4 | 2016-07-29T01:06:27Z | [
"python",
"pandas"
] |
All rows within a given column must match, for all columns | 38,648,940 | <p>I have a Pandas DataFrame of data in which all rows within a given column must match:</p>
<pre><code>df = pd.DataFrame({'A': [1,1,1,1,1,1,1,1,1,1],
'B': [2,2,2,2,2,2,2,2,2,2],
'C': [3,3,3,3,3,3,3,3,3,3],
'D': [4,4,4,4,4,4,4,4,4,4],
'E': [5,5,5,5,5,5,5,5,5,5]})
In [10]: df
Out[10]:
A B C D E
0 1 2 3 4 5
1 1 2 3 4 5
2 1 2 3 4 5
...
6 1 2 3 4 5
7 1 2 3 4 5
8 1 2 3 4 5
9 1 2 3 4 5
</code></pre>
<p>I would like a quick way to know if there is an variance anywhere in the DataFrame. At this point, I don't need to know which values have varied, since I will be going in to handle those later. I just need a quick way to know if the DataFrame needs further attention or if I can ignore it and move on to the next one.</p>
<p>I can check any given column using</p>
<pre><code>(df.loc[:,'A'] != df.loc[0,'A']).any()
</code></pre>
<p>but my Pandas knowledge limits me to iterating through the columns (I understand iteration is frowned upon in Pandas) to compare all of them:</p>
<pre><code> A B C D E
0 1 2 3 4 5
1 1 2 9 4 5
2 1 2 3 4 5
...
6 1 2 3 4 5
7 1 2 3 4 5
8 1 2 3 4 5
9 1 2 3 4 5
for col in df.columns:
if (df.loc[:,col] != df.loc[0,col]).any():
print("Found a fail in col %s" % col)
break
Out: Found a fail in col C
</code></pre>
<p>Is there an elegant way to return a boolean if any row within any column of a dataframe does not match all the values in the column... possibly without iteration?</p>
| 3 | 2016-07-29T00:57:32Z | 38,649,007 | <p>You can compare the entire DataFrame to the first row like this:</p>
<pre><code>In [11]: df.eq(df.iloc[0], axis='columns')
Out[11]:
A B C D E
0 True True True True True
1 True True True True True
2 True True True True True
3 True True True True True
4 True True True True True
5 True True True True True
6 True True True True True
7 True True True True True
8 True True True True True
9 True True True True True
</code></pre>
<p>then test if all values are true:</p>
<pre><code>In [13]: df.eq(df.iloc[0], axis='columns').all()
Out[13]:
A True
B True
C True
D True
E True
dtype: bool
In [14]: df.eq(df.iloc[0], axis='columns').all().all()
Out[14]: True
</code></pre>
| 4 | 2016-07-29T01:07:06Z | [
"python",
"pandas"
] |
Tastypie detail_uri_name with forignkey's attribute | 38,648,946 | <p>I have a extended the <code>User</code> Django class with my own user class in django:</p>
<pre><code>class MyUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='my_user')
theme = models.IntegerField(default=0)
tags = TaggableManager()
</code></pre>
<p>And a corresponding tastypie resource, that I want to use <code>detail_uri_name</code> with the username from the Django user class. Although, I do not know how.</p>
<pre><code>class MyUserResource(ModelResource):
class Meta:
queryset = User.objects.all()
allowed_methods = ['get']
detail_uri_name = 'user_username'# ????
</code></pre>
<p>Error I have is: <code>'MyUser' object has no attribute 'user__username'</code></p>
<p>How do I access the <code>username</code> from <code>MyUser</code> as an attribute?</p>
<p>The line is:</p>
<pre><code> detail_uri_name = 'user_username'# ????
</code></pre>
<p>From the shell I can do <code>MyUser.objects.all()[0].user.username</code> to get the username of the associated django class. </p>
| 0 | 2016-07-29T00:58:22Z | 38,650,463 | <p>You cannot use other class attribute as a <code>detail_uri_name</code>.</p>
<p>But, in theory:</p>
<pre><code>class MyUserResource(ModelResource):
class Meta:
queryset = User.objects.all().select_related('user')
allowed_methods = ['get']
detail_uri_name = 'user__username'
def get_bundle_detail_data(self, bundle):
attrs = self._meta.detail_uri_name.split('__')
return getattr(getattr(bundle.obj, attrs[0]), attrs[1])
</code></pre>
| 2 | 2016-07-29T04:22:10Z | [
"python",
"mysql",
"django",
"api",
"tastypie"
] |
Tkinter calculator fails to update label | 38,649,048 | <p>I tried making a simple integer sign calculator using tkinter. It has a class with two different functions. The second function is supposed to be initiated when the user presses the "Enter" button. When I run the code the window comes up just as it is supposed to. But when I type and hit "Enter" the second function fails to run and does not update the label. I want for it to update as either "This number is positive.", "This number is 0.", or "This number is negative." Instead it remains blank.</p>
<p>I doubt it is relevant, but I made this program in PyCharm Community Edition 5.0.4, and I am using Python 3.5 (32-bit).</p>
<pre><code>import tkinter
class IntegerSign:
def __init__(self):
self.window = tkinter.Tk()
self.window.title("Integer Sign Calculator")
self.window.geometry("300x150")
self.number_frame = tkinter.Frame(self.window)
self.solution_frame = tkinter.Frame(self.window)
self.button_frame = tkinter.Frame(self.window)
self.number_label = tkinter.Label(self.number_frame, text="Enter an integer:")
self.number_entry = tkinter.Entry(self.number_frame, width=10)
self.number_label.pack(side='left')
self.number_entry.pack(side='left')
self.statement = tkinter.StringVar()
self.solution_label = tkinter.Label(self.solution_frame, textvariable=self.statement)
self.statement = tkinter.Label(self.solution_frame, textvariable=self.statement)
self.solution_label.pack(side='left')
self.calc_button = tkinter.Button(self.button_frame, text='Enter', command=self.calc_answer)
self.quit_button = tkinter.Button(self.button_frame, text='Quit', command=self.window.destroy)
self.calc_button.pack(side='left')
self.quit_button.pack(side='left')
self.number_frame.pack()
self.solution_frame.pack()
self.button_frame.pack()
tkinter.mainloop()
def calc_answer(self):
self.number = int(self.number_entry.get())
self.statement = tkinter.StringVar()
if self.number > 0:
self.statement = "This number is positive."
elif self.number == 0:
self.statement = "This number is 0."
else:
self.statement = "This number is negative."
IntegerSign()
</code></pre>
| 0 | 2016-07-29T01:13:48Z | 38,649,216 | <p>To set the value of a StringVar you need to use the <code>set</code> method.
Right now all you did was re-assign the variable. You can also set a stringvar's (default) value by giving it a value when you first initialize it. e.g. - <code>var = tk.StringVar(value="some value")</code></p>
<p>Edit: Didn't see that you also set self.statement to be the label widget... This would work if you used the method all the way at the bottom of this answer, and disregarded (optionally) stringvar's entirely. But, when you do this you can think of it as sticky notes. You stuck a sticky note that says "this variable holds this value", then you re-assigned the variable put another sticky note over the previous one that says "it now holds this value" as a really loose visual analogy.</p>
<pre><code>>>> import tkinter as tk
>>> root = tk.Tk()
>>> statement = tk.StringVar()
>>> type(statement)
>>> <class 'tkinter.StringVar'>
>>> statement = "This number is positive"
>>> type(statement)
>>> <class 'str'>
>>> statement = tk.StringVar()
>>> statement.set("This number is positive")
>>> statement.get()
'This number is positive'
>>> type(statement)
>>> <class 'tkinter.StringVar'>
</code></pre>
<p>Alternatively you could just change the labels text by doing <code>label_widget['text'] = 'new_text'</code></p>
| 1 | 2016-07-29T01:38:38Z | [
"python",
"user-interface",
"tkinter",
"label",
"calculator"
] |
Tkinter calculator fails to update label | 38,649,048 | <p>I tried making a simple integer sign calculator using tkinter. It has a class with two different functions. The second function is supposed to be initiated when the user presses the "Enter" button. When I run the code the window comes up just as it is supposed to. But when I type and hit "Enter" the second function fails to run and does not update the label. I want for it to update as either "This number is positive.", "This number is 0.", or "This number is negative." Instead it remains blank.</p>
<p>I doubt it is relevant, but I made this program in PyCharm Community Edition 5.0.4, and I am using Python 3.5 (32-bit).</p>
<pre><code>import tkinter
class IntegerSign:
def __init__(self):
self.window = tkinter.Tk()
self.window.title("Integer Sign Calculator")
self.window.geometry("300x150")
self.number_frame = tkinter.Frame(self.window)
self.solution_frame = tkinter.Frame(self.window)
self.button_frame = tkinter.Frame(self.window)
self.number_label = tkinter.Label(self.number_frame, text="Enter an integer:")
self.number_entry = tkinter.Entry(self.number_frame, width=10)
self.number_label.pack(side='left')
self.number_entry.pack(side='left')
self.statement = tkinter.StringVar()
self.solution_label = tkinter.Label(self.solution_frame, textvariable=self.statement)
self.statement = tkinter.Label(self.solution_frame, textvariable=self.statement)
self.solution_label.pack(side='left')
self.calc_button = tkinter.Button(self.button_frame, text='Enter', command=self.calc_answer)
self.quit_button = tkinter.Button(self.button_frame, text='Quit', command=self.window.destroy)
self.calc_button.pack(side='left')
self.quit_button.pack(side='left')
self.number_frame.pack()
self.solution_frame.pack()
self.button_frame.pack()
tkinter.mainloop()
def calc_answer(self):
self.number = int(self.number_entry.get())
self.statement = tkinter.StringVar()
if self.number > 0:
self.statement = "This number is positive."
elif self.number == 0:
self.statement = "This number is 0."
else:
self.statement = "This number is negative."
IntegerSign()
</code></pre>
| 0 | 2016-07-29T01:13:48Z | 38,649,249 | <p>The first problem: in your constructor you initialize a variable named self.statement to a StringVar and then initialize again to a Label. After that second initialization, you have no way of accessing the first object. You need to use two different names.</p>
<p>The second problem: in your event handler, <code>calc_answer</code>, you create a new object named <code>self.statement</code>, but instead you need to <code>set</code> a new value into the old one (see <a href="http:////http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/control-variables.html" rel="nofollow">docs</a>). Here is a modified version of your program that works as intended:</p>
<pre><code>import tkinter
class IntegerSign:
def __init__(self):
self.window = tkinter.Tk()
self.window.title("Integer Sign Calculator")
self.window.geometry("300x150")
self.number_frame = tkinter.Frame(self.window)
self.solution_frame = tkinter.Frame(self.window)
self.button_frame = tkinter.Frame(self.window)
self.number_label = tkinter.Label(self.number_frame, text="Enter an integer:")
self.number_entry = tkinter.Entry(self.number_frame, width=10)
self.number_label.pack(side='left')
self.number_entry.pack(side='left')
self.solution_string = tkinter.StringVar()
self.solution_label = tkinter.Label(self.solution_frame, textvariable=self.solution_string)
self.statement = tkinter.Label(self.solution_frame, textvariable=self.solution_string)
self.solution_label.pack(side='left')
self.calc_button = tkinter.Button(self.button_frame, text='Enter', command=self.calc_answer)
self.quit_button = tkinter.Button(self.button_frame, text='Quit', command=self.window.destroy)
self.calc_button.pack(side='left')
self.quit_button.pack(side='left')
self.number_frame.pack()
self.solution_frame.pack()
self.button_frame.pack()
tkinter.mainloop()
def calc_answer(self):
self.number = int(self.number_entry.get())
if self.number > 0:
self.solution_string.set("This number is positive.")
elif self.number == 0:
self.solution_string.set("This number is 0.")
else:
self.solution_string.set("This number is negative.")
IntegerSign()
</code></pre>
<p>This code works but contains a bad practice that I recommend you fix. The function <code>tkinter.mainloop()</code> is essentially an infinite loop, and you have placed it inside the constructor. Thus the constructor won't return the way a constructor is normally supposed to. Take that statement out of the <code>__init__</code> function and put it at the end, after the call to <code>IntegerSign</code>, and make this a pattern to be used in the future.</p>
| 1 | 2016-07-29T01:44:02Z | [
"python",
"user-interface",
"tkinter",
"label",
"calculator"
] |
How to get the type of a varible | 38,649,081 | <p>I created a function that took a list as a parameter and removed either a space or a number. Code below: </p>
<pre><code>def cleaner(List, filter_out=' '):
if filter_out == ' ':
for i in List:
if i == ' ':
List.remove(' ')
if filter_out == 'int':
for i in List:
if type(i) == int:
List.remove(i)
</code></pre>
<p>I tested it using a list like so:</p>
<pre><code>myList = ['h' ' ', 'g', 1, 2, 3, 4, 5, 'p']
print(cleaner(myList, filter_out='int'))
</code></pre>
<p>I expected to get <code>['h' ' ', 'g', 'p']</code>
but instead printed out <code>['h ', 'g', 2, 4, 'p']</code>
Why did it leave the <code>1</code> and <code>2</code>? I thought that it would filter out all numbers in the list.</p>
| 1 | 2016-07-29T01:18:35Z | 38,649,138 | <p>This would be a proper way to do it for medium sized lists</p>
<pre><code> def cleaner(lst,filter_item = ' '):
if filter_item == ' ':
for i in list(lst):
if i == ' ':
lst.remove(' ')
elif filter_item == 'int':
for i in list(lst):
if type(i) == int:
lst.remove(i)
myList = ['h' ' ', 'g', 1, 2, 3, 4, 5, 'p']
cleaner(myList, 'int')
print(myList)
</code></pre>
<p>or a nicer way:</p>
<pre><code> def cleaner(lst,filter_item = ' '):
retval = None
if filter_item == ' ':
retval = [i for i in lst if i != ' ']
elif filter_item == 'int':
retval = [i for i in lst if type(i) != int]
return retval
myList = ['h' ' ', 'g', 1, 2, 3, 4, 5, 'p']
a=cleaner(myList)
print(a)
#['h ', 'g', 1, 2, 3, 4, 5, 'p']
a=cleaner(myList,'int')
print(a)
#['h ', 'g', 'p']
</code></pre>
| 1 | 2016-07-29T01:26:33Z | [
"python",
"list",
"function",
"types"
] |
How to get the type of a varible | 38,649,081 | <p>I created a function that took a list as a parameter and removed either a space or a number. Code below: </p>
<pre><code>def cleaner(List, filter_out=' '):
if filter_out == ' ':
for i in List:
if i == ' ':
List.remove(' ')
if filter_out == 'int':
for i in List:
if type(i) == int:
List.remove(i)
</code></pre>
<p>I tested it using a list like so:</p>
<pre><code>myList = ['h' ' ', 'g', 1, 2, 3, 4, 5, 'p']
print(cleaner(myList, filter_out='int'))
</code></pre>
<p>I expected to get <code>['h' ' ', 'g', 'p']</code>
but instead printed out <code>['h ', 'g', 2, 4, 'p']</code>
Why did it leave the <code>1</code> and <code>2</code>? I thought that it would filter out all numbers in the list.</p>
| 1 | 2016-07-29T01:18:35Z | 38,649,167 | <p>Removing items from a list while iterating it results in bad consequences:</p>
<pre><code>>>> nums = [1, 2, 3, 4]
>>> for x in nums:
... print x
... nums.remove(x)
...
1
3
</code></pre>
<p>You start at index 0. You print <code>nums[0]</code>, <code>1</code>. You then remove it. The next index is <code>1</code>. Well, <code>[nums[1]</code> is <code>3</code> because now the list is <code>[2, 3, 4]</code>. You print that, and remove it. The list is now <code>[2, 4]</code>, and you are at the third index. Since <code>nums[2]</code> does not exist, the loop ends, skipping two numbers. What you should do is take advantage of the builtin functions:</p>
<pre><code>myList = ...
myList = filter(lambda x: not isinstance(x, int), myList)
</code></pre>
<p>For the example of <code>' '</code>, it would be:</p>
<pre><code>myList = ...
myList = filter(str.strip, myList)
</code></pre>
<p>or</p>
<pre><code>myList = filter(lambda x: x != ' ', myList)
</code></pre>
<p><strong>Note</strong>: The Python 3 <code>filter()</code> function returns a <code>filter</code> object, not a list. That makes it more efficient if you are just iterating, but if you truly need a list, you can use <code>list(filter(...))</code>.</p>
<p>All of these make a copy of the list instead of doing their work in place. If you want it in place, use <code>myList[:] = ...</code> instead of <code>myList = ...</code> (in the <code>filter()</code> line). Note that a Python 3 <code>filter</code> object does not need to be converted to a list for this to work.</p>
| 4 | 2016-07-29T01:30:18Z | [
"python",
"list",
"function",
"types"
] |
import all future features | 38,649,099 | <p>Just curious, I tried <code>from __future__ import *</code>, but I received this error:</p>
<pre class="lang-none prettyprint-override"><code> File "<stdin>", line 1
SyntaxError: future feature * is not defined
</code></pre>
<p>Well, that makes sense. A <code>__future__</code> import is a little special and doesn't follow the normal rules, but it got me to thinking: how <em>can</em> I import all the future features?</p>
| 3 | 2016-07-29T01:20:54Z | 38,649,110 | <p>You can't, and that's by design. This is because more <code>__future__</code> features might be added in the future, and those can break your code.</p>
<p>Imagine that in 2.x, the only <code>__future__</code> feature was <code>division</code>. Then in 2.y, a new <code>__future__</code> feature, <code>print_function</code>, is introduced. All of a sudden my code has broken:</p>
<pre><code>from __future__ import *
print "Hello, World!"
</code></pre>
<p>You <em>can</em>, however, import <code>__future__</code>, and inspect its contents:</p>
<pre><code>>>> import __future__
>>> [x for x in dir(__future__) if x.islower() and x[0] != '_']
['absolute_import', 'all_feature_names', 'division', 'generator_stop', 'generators', 'nested_scopes', 'print_function', 'unicode_literals', 'with_statement']
</code></pre>
<p>Note that these are not features and you should not try to import them. They instead describe which features are available, and from which versions they are.</p>
| 4 | 2016-07-29T01:22:48Z | [
"python",
"import"
] |
Importerror: cannot import name Split | 38,649,129 | <p>I am very new to python and need some help here.
I think it comes from PATH,but I have no clue about fixing it. Please help.</p>
<p><a href="http://i.stack.imgur.com/QDSqq.png" rel="nofollow">Once I type in import split and it keeps popping up</a></p>
<blockquote>
<p>runfile('/Users/zhihaowang/Desktop/untitled1.py',
wdir='/Users/zhihaowang/Desktop') Traceback (most recent call last):</p>
<p>File "", line 1, in
runfile('/Users/zhihaowang/Desktop/untitled1.py', wdir='/Users/zhihaowang/Desktop')</p>
<p>File
"/Users/zhihaowang/anaconda3/lib/python3.5/site-packages/spyderlib/widgets/externalshell/sitecustomize.py",
line 714, in runfile
execfile(filename, namespace)</p>
<p>File
"/Users/zhihaowang/anaconda3/lib/python3.5/site-packages/spyderlib/widgets/externalshell/sitecustomize.py",
line 89, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)</p>
<p>File "/Users/zhihaowang/Desktop/untitled1.py", line 8, in
from string import split</p>
<p>ImportError: cannot import name 'split'</p>
</blockquote>
| -1 | 2016-07-29T01:25:06Z | 39,029,544 | <p>split is part of standard string method not from string module. Without importing also you could just apply split method. your_str.split()</p>
| 0 | 2016-08-19T00:47:50Z | [
"python",
"importerror"
] |
Django CORS X-FirePHP-Version | 38,649,170 | <p>I am getting the following error message when I try to access my endpoints.</p>
<pre><code>Request header field X-FirePHP-Version is not allowed by Access-Control-Allow-Headers in preflight response.
</code></pre>
<p>This is how my settings.py file looks</p>
<pre><code>INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'api.apps.ApiConfig',
'django_server',
'corsheaders', # For Cross-Origin Resource Sharing
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = False
</code></pre>
| 1 | 2016-07-29T01:30:42Z | 38,649,283 | <p>If you have additional headers that are going to be in your requests to a CORS enabled server, you should specify those in the <code>CORS_ALLOW_HEADERS</code> <a href="https://github.com/ottoyiu/django-cors-headers" rel="nofollow">django-cors</a> setting. This should solve it, but I would double check to make sure those headers are supposed to be there.</p>
<pre>
# In your project's settings.py
CORS_ALLOW_HEADERS = (
'x-requested-with',
'content-type',
'accept',
'origin',
'authorization',
'x-csrftoken',
'x-firephp-version', # Added to default list
)
# more settings...
</pre>
<p>Under the hood this simply sets the <code>Access-Control-Request-Headers</code> header on your server's responses.</p>
| 1 | 2016-07-29T01:48:04Z | [
"python",
"django",
"cors",
"django-cors-headers"
] |
Decided the order of the groupby output? | 38,649,415 | <p>After the groupby, the output order of the group is pre-decided. In the following case, the order is A, AAA, B, BBB. </p>
<p>Is there a way to customize this order? I want to order to be AAA,A,BBB,B. I might want it in other orders as well.</p>
<pre><code>import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
data=pd.DataFrame({'Rating':['A','AAA','B','BBB','A','AAA','B','BBB'],
'Score':[2,4,5,6,2,4,5,6,]})
t=data.groupby('Rating', sort=False)['Score'].mean()
t
Rating
A 2
AAA 4
B 5
BBB 6
Name: Score, dtype: int64
</code></pre>
| 0 | 2016-07-29T02:04:36Z | 38,649,483 | <p><code>sort=False</code> just means that it's not guaranteed to be sorted (it may be ordered). My recollection is that this is in the "seen order", but again that's no guaranteed.</p>
<p>To sort the output of a groupby, just do the sort after (by the index):</p>
<pre><code>In [11]: t.sort_index()
Out[11]:
Rating
A 2
AAA 4
B 5
BBB 6
Name: Score, dtype: int64
</code></pre>
| 0 | 2016-07-29T02:11:26Z | [
"python",
"pandas",
"group-by"
] |
Decided the order of the groupby output? | 38,649,415 | <p>After the groupby, the output order of the group is pre-decided. In the following case, the order is A, AAA, B, BBB. </p>
<p>Is there a way to customize this order? I want to order to be AAA,A,BBB,B. I might want it in other orders as well.</p>
<pre><code>import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
data=pd.DataFrame({'Rating':['A','AAA','B','BBB','A','AAA','B','BBB'],
'Score':[2,4,5,6,2,4,5,6,]})
t=data.groupby('Rating', sort=False)['Score'].mean()
t
Rating
A 2
AAA 4
B 5
BBB 6
Name: Score, dtype: int64
</code></pre>
| 0 | 2016-07-29T02:04:36Z | 38,649,484 | <p>You can't change the order returned by groupby/mean (save what's possible with the <code>sort</code> parameter). However, it easy to change the order after the fact using <code>reindex</code>:</p>
<pre><code>In [24]: data.groupby('Rating', sort=False)['Score'].mean().reindex(['AAA', 'A', 'BBB', 'B'])
Out[24]:
Rating
AAA 4
A 2
BBB 6
B 5
Name: Score, dtype: int64
</code></pre>
<hr>
<p>Alternatively, you can control the order returned by <code>groupby/mean</code> by changing <code>Ratings</code> to a <code>Categorical</code>:</p>
<pre><code>import pandas as pd
data = pd.DataFrame({'Rating':['A','AAA','B','BBB','A','AAA','B','BBB'],
'Score':[2,4,5,6,2,4,5,6,]})
data['Rating'] = pd.Categorical(data['Rating'], categories=['AAA','A','BBB','B'],
ordered=True)
result = data.groupby('Rating', sort=False)['Score'].mean()
print(result)
</code></pre>
<p>yields</p>
<pre><code>Rating
AAA 4
A 2
BBB 6
B 5
Name: Score, dtype: int64
</code></pre>
| 2 | 2016-07-29T02:11:32Z | [
"python",
"pandas",
"group-by"
] |
__init__ file doesn't work as expected in python | 38,649,482 | <p>I have some folders and <code>.py</code> files in the following structure:</p>
<pre><code>parent/
__init__.py
test.ipynb
code/
__init__.py
common.py
subcode/
__init__.py
get_data.py
</code></pre>
<p>In the <code>__init__</code> file under the <code>parent</code> folder, I have <code>import code</code> and in the one of <code>code</code>, I have <code>import subcode</code>. But when I tried <code>import code.subcode</code>, I got such an error:</p>
<pre><code>ImportError: No module named 'code.subcode'; 'code' is not a package
</code></pre>
<p>But when I just <code>import code</code>, no error is thrown. However, when I call <code>code.subcode</code>, this error happens:</p>
<pre><code>AttributeError: module 'code' has no attribute 'subcode'
</code></pre>
<p>I try all of those mentioned above in the <code>test.ipynb</code>, which is at the root of the directory.</p>
<p>Do you know what is the reason and how can I fix it? Thanks!</p>
| 4 | 2016-07-29T02:11:23Z | 38,649,808 | <p>The problem is that you are importing another module named <code>code</code> that is installed on your system rather than your own module. You can verify this by checking the module file path in <code>code.__file__</code> after you <code>import code</code>.</p>
<p>The first thing to do is change the name of your module to avoid namespace collisions with the other <code>code</code> package on your system. If your new package name doesn't collide with something else, you should now either successfully be importing it and have it behave as expected, or it fails to import entirely.</p>
<p>If it fails to import, it is most likely because your <code>parent</code> directory is not in your <code>PYTHONPATH</code> environment variable.</p>
<p>There can potentially also be other more technical reasons that a module is not recognized by the interpreter such as old definitions being cached (in which case restarting the interpreter is often enough. Possibly after deleting any precompiled versions of the module). Another problem I have seen ended up being that a module contained a bug that made the interpreter unable to parse it. I am sure there are other odd possibilities out there.</p>
| 3 | 2016-07-29T02:52:51Z | [
"python",
"init"
] |
__init__ file doesn't work as expected in python | 38,649,482 | <p>I have some folders and <code>.py</code> files in the following structure:</p>
<pre><code>parent/
__init__.py
test.ipynb
code/
__init__.py
common.py
subcode/
__init__.py
get_data.py
</code></pre>
<p>In the <code>__init__</code> file under the <code>parent</code> folder, I have <code>import code</code> and in the one of <code>code</code>, I have <code>import subcode</code>. But when I tried <code>import code.subcode</code>, I got such an error:</p>
<pre><code>ImportError: No module named 'code.subcode'; 'code' is not a package
</code></pre>
<p>But when I just <code>import code</code>, no error is thrown. However, when I call <code>code.subcode</code>, this error happens:</p>
<pre><code>AttributeError: module 'code' has no attribute 'subcode'
</code></pre>
<p>I try all of those mentioned above in the <code>test.ipynb</code>, which is at the root of the directory.</p>
<p>Do you know what is the reason and how can I fix it? Thanks!</p>
| 4 | 2016-07-29T02:11:23Z | 38,649,865 | <p>You're on Python 3. You need to perform relative imports explicitly:</p>
<pre><code>from . import code
</code></pre>
<p>The <code>code</code> module you're currently getting is the standard library <a href="https://docs.python.org/3/library/code.html" rel="nofollow"><code>code</code></a> module.</p>
| 1 | 2016-07-29T02:59:50Z | [
"python",
"init"
] |
Python: determine if a string contains math? | 38,649,496 | <p>Given these strings:</p>
<pre><code>"1 + 2"
"apple,pear"
</code></pre>
<p>How can I use Python 3(.5) to determine that the first string contains a math problem and <strong>nothing else</strong> and that the second string does not?</p>
| 1 | 2016-07-29T02:12:48Z | 38,649,579 | <p>Simply use split(), then iterate through the list to check if all instance are either numerical values or operational values. Then use eval.</p>
<pre><code>input = "1 + 2"
for i in input.split():
if i in ['+','-','*','%','.'] or i.isdigit():
pass
# do something
else:
pass
# one element is neither a numerical value or operational value
</code></pre>
| 0 | 2016-07-29T02:22:40Z | [
"python",
"python-3.x",
"math",
"python-3.5"
] |
Python: determine if a string contains math? | 38,649,496 | <p>Given these strings:</p>
<pre><code>"1 + 2"
"apple,pear"
</code></pre>
<p>How can I use Python 3(.5) to determine that the first string contains a math problem and <strong>nothing else</strong> and that the second string does not?</p>
| 1 | 2016-07-29T02:12:48Z | 38,649,713 | <p>Here is a way to do it:</p>
<pre><code>import ast
UNARY_OPS = (ast.UAdd, ast.USub)
BINARY_OPS = (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Mod)
def is_arithmetic(s):
def _is_arithmetic(node):
if isinstance(node, ast.Num):
return True
elif isinstance(node, ast.Expression):
return _is_arithmetic(node.body)
elif isinstance(node, ast.UnaryOp):
valid_op = isinstance(node.op, UNARY_OPS)
return valid_op and _is_arithmetic(node.operand)
elif isinstance(node, ast.BinOp):
valid_op = isinstance(node.op, BINARY_OPS)
return valid_op and _is_arithmetic(node.left) and _is_arithmetic(node.right)
else:
raise ValueError('Unsupported type {}'.format(node))
try:
return _is_arithmetic(ast.parse(s, mode='eval'))
except (SyntaxError, ValueError):
return False
</code></pre>
| 7 | 2016-07-29T02:38:38Z | [
"python",
"python-3.x",
"math",
"python-3.5"
] |
Python: determine if a string contains math? | 38,649,496 | <p>Given these strings:</p>
<pre><code>"1 + 2"
"apple,pear"
</code></pre>
<p>How can I use Python 3(.5) to determine that the first string contains a math problem and <strong>nothing else</strong> and that the second string does not?</p>
| 1 | 2016-07-29T02:12:48Z | 38,649,905 | <p>You can use a parsing library such as <a href="https://fdik.org/pyPEG/" rel="nofollow">pyPEG</a>, although there is room for improvment do more than this you could define a grammar like this:</p>
<pre><code>from pypeg2 import optional, List, Namespace
import re
number = re.compile(r'\d+')
binop = re.compile(r'\+|\*') # Exercise: Extend to other binary operators
class BinOp(Namespace):
grammar = binop
class Number(Namespace):
grammar = number, optional("."), optional(number)
class Expression(Namespace):
grammar = Number, optional(BinOp, Number)
class Equation(List):
grammar = Expression, optional("="), optional(Expression)
</code></pre>
<p>You can handle the error when an invalid expression is passed through and use the parse function to validate expressions:</p>
<pre><code>>>> import pypeg2
>>> f = pypeg2.parse("3=3", Equation)
>>> f = pypeg2.parse("3 = 3", Equation)
>>> f = pypeg2.parse("3 + 3 = 3", Equation)
>>> f = pypeg2.parse("3 * 3 = 3", Equation)
>>> f = pypeg2.parse("3hi", Equation)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/site-packages/pypeg2/__init__.py", line 669, in parse
raise parser.last_error
File "<string>", line 1
3hi
^
SyntaxError: expecting match on \d+
</code></pre>
| 0 | 2016-07-29T03:05:15Z | [
"python",
"python-3.x",
"math",
"python-3.5"
] |
Labeling boxplot in seaborn with median value | 38,649,501 | <p>How can I label each boxplot in a seaborn plot with the median value?</p>
<p>E.g.</p>
<pre><code>import seaborn as sns
sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
ax = sns.boxplot(x="day", y="total_bill", data=tips)
</code></pre>
<p>How do I label each boxplot with the median or average value?</p>
| 3 | 2016-07-29T02:13:10Z | 38,649,932 | <p>Can I just say that I love it when people include sample datasets. A healthy +1 to you!</p>
<pre><code>import seaborn as sns, numpy as np
sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
ax = sns.boxplot(x="day", y="total_bill", data=tips)
medians = tips.groupby(['day'])['total_bill'].median().values
median_labels = [str(np.round(s, 2)) for s in medians]
pos = range(len(medians))
for tick,label in zip(pos,ax.get_xticklabels()):
ax.text(pos[tick], medians[tick] + 0.5, median_labels[tick],
horizontalalignment='center', size='x-small', color='w', weight='semibold')
</code></pre>
<p><a href="http://i.stack.imgur.com/OI4eJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/OI4eJ.png" alt="enter image description here"></a></p>
| 2 | 2016-07-29T03:09:31Z | [
"python",
"matplotlib",
"seaborn"
] |
acess class attribute in another file | 38,649,575 | <p>I'm new to python.</p>
<p>I have a question about accessing attribute in class</p>
<p>t1.py</p>
<pre><code>#!/usr/bin/python
import t2
class A:
flag = False
if __name__ == "__main__":
t2.f()
print(A.flag)
</code></pre>
<p>t2.py</p>
<pre><code>#!/usr/bin/python
import t1
def f():
t1.A.flag = True
print(t1.A.flag)
</code></pre>
<p>excute Result:</p>
<pre><code># ./t1.py
True
False
</code></pre>
<p>I expect that result has to be True, True.</p>
<p>Are A.flag in t1.py and t1.A.flag in t2.py diffrent?</p>
<p>What happends in python when excute this code?</p>
<p>Thank you.</p>
| 1 | 2016-07-29T02:21:38Z | 38,649,902 | <p>Yeah, I can see how this can be a little confusing but it is basically a question of namespaces along with the distinction that the <code>__main__</code> namespace is not considered as part of the list of imported modules. This allows the file that is the point of execution (and thus occupying the <code>__main__</code> namespace) to also be imported as a module. On the other hand, if the same module is imported more than once, the interpreter will simply let all the different imports point to the same memory location</p>
<p>Because of this, in the code you are showing above, you actually have two distinct versions of <code>A</code>: you have <code>__main__.A</code> and you have <code>__main__.t2.t1.A</code>. The second one comes about because <code>__main__</code>is importing <code>t2</code> which in turn is importing <code>t1</code> as a module.</p>
<p>When you are running <code>t2.f()</code>, you are setting <code>__main__.t2.t1.A.flag = True</code> and then printing it. Subsequently, when you call <code>print(A.flag)</code>, you are printing the value in <code>__main__.A.flag</code>, which was never changed.</p>
<p>I hope that makes at least a little sense.</p>
<p>A friend of mine always said that computer science is an experimental science.
Let's invoke the debugger.</p>
<p>I add a <code>pdb.set_trace()</code> to the execution and <code>t1.py</code> now looks like this:</p>
<pre><code>#!/usr/bin/python
import t2
class A:
flag = False
if __name__ == "__main__":
import pdb; pdb.set_trace()
t2.f()
print(A.flag)
</code></pre>
<p>And this is what we get:</p>
<pre><code>$ python t1.py
> /Users/martin/git/temp/t1.py(9)<module>()
-> t2.f()
(Pdb) A
<class __main__.A at 0x10ec9ba78>
(Pdb) t2.t1.A
<class t1.A at 0x10ec9ba10>
(Pdb)
</code></pre>
<p>Please note that the <code>A</code> have separate memory locations associated.</p>
| -1 | 2016-07-29T03:04:55Z | [
"python"
] |
acess class attribute in another file | 38,649,575 | <p>I'm new to python.</p>
<p>I have a question about accessing attribute in class</p>
<p>t1.py</p>
<pre><code>#!/usr/bin/python
import t2
class A:
flag = False
if __name__ == "__main__":
t2.f()
print(A.flag)
</code></pre>
<p>t2.py</p>
<pre><code>#!/usr/bin/python
import t1
def f():
t1.A.flag = True
print(t1.A.flag)
</code></pre>
<p>excute Result:</p>
<pre><code># ./t1.py
True
False
</code></pre>
<p>I expect that result has to be True, True.</p>
<p>Are A.flag in t1.py and t1.A.flag in t2.py diffrent?</p>
<p>What happends in python when excute this code?</p>
<p>Thank you.</p>
| 1 | 2016-07-29T02:21:38Z | 38,649,937 | <p>They are indeed two different objects (explained very well in <a href="http://stackoverflow.com/a/38649968/5827958">user2357112's answer</a>). If you want <code>t2</code> to use the same object, you need to tell Python that you are actually importing the same module that is importing <code>t2</code>. To do that, import <code>__main__</code> instead:</p>
<pre><code>import __main__
def f():
__main__.A.flag = True
print(__main__.A.flag)
</code></pre>
| 0 | 2016-07-29T03:10:05Z | [
"python"
] |
acess class attribute in another file | 38,649,575 | <p>I'm new to python.</p>
<p>I have a question about accessing attribute in class</p>
<p>t1.py</p>
<pre><code>#!/usr/bin/python
import t2
class A:
flag = False
if __name__ == "__main__":
t2.f()
print(A.flag)
</code></pre>
<p>t2.py</p>
<pre><code>#!/usr/bin/python
import t1
def f():
t1.A.flag = True
print(t1.A.flag)
</code></pre>
<p>excute Result:</p>
<pre><code># ./t1.py
True
False
</code></pre>
<p>I expect that result has to be True, True.</p>
<p>Are A.flag in t1.py and t1.A.flag in t2.py diffrent?</p>
<p>What happends in python when excute this code?</p>
<p>Thank you.</p>
| 1 | 2016-07-29T02:21:38Z | 38,649,968 | <p>When you do</p>
<pre><code>./t1.py
</code></pre>
<p>you're executing the <code>t1.py</code> file, but it's not executed as the <code>t1</code> module. It's considered to be the <code>__main__</code> module. (This is what that <code>if __name__ == '__main__'</code> line checks for.) That means that when this line:</p>
<pre><code>import t1
</code></pre>
<p>in <code>t2.py</code> tries to import <code>t1</code>, Python starts executing the <code>t1.py</code> file <em>again</em> to create the <code>t1</code> module. You end up with two versions of the <code>A</code> class, one being <code>__main__.A</code> and one being <code>t1.A</code>. The modification to <code>t1.A</code> doesn't do anything to <code>__main__.A</code>, because even though they came from the same code in the same file, they're not the same class.</p>
| 2 | 2016-07-29T03:14:02Z | [
"python"
] |
acess class attribute in another file | 38,649,575 | <p>I'm new to python.</p>
<p>I have a question about accessing attribute in class</p>
<p>t1.py</p>
<pre><code>#!/usr/bin/python
import t2
class A:
flag = False
if __name__ == "__main__":
t2.f()
print(A.flag)
</code></pre>
<p>t2.py</p>
<pre><code>#!/usr/bin/python
import t1
def f():
t1.A.flag = True
print(t1.A.flag)
</code></pre>
<p>excute Result:</p>
<pre><code># ./t1.py
True
False
</code></pre>
<p>I expect that result has to be True, True.</p>
<p>Are A.flag in t1.py and t1.A.flag in t2.py diffrent?</p>
<p>What happends in python when excute this code?</p>
<p>Thank you.</p>
| 1 | 2016-07-29T02:21:38Z | 38,650,415 | <p>You can find this out yourself:</p>
<h1>t1.py</h1>
<pre><code>#!/usr/bin/python
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.debug('t1 has started')
logger.debug('t2 is being imported')
import t2
logger.debug('A is being "compiled"')
class A:
flag = False
logger.debug('ID A: %r', id(A))
logger.debug('ID A.flag %r', id(A.flag))
logger.debug('What is __name__? %r', __name__)
if __name__ == "__main__":
logger.debug('__name__ was "__main__"')
logger.debug('Calling t2.f()')
t2.f()
logger.debug('t2.f() was called')
logger.debug('ID A.flag: %r', id(A.flag))
print(A.flag)
</code></pre>
<h1>t2.py</h1>
<pre><code>#!/usr/bin/python
import logging
logger = logging.getLogger(__name__)
logger.debug('t2 is being imported')
logger.debug('t2 is now importing t1')
import t1
def f():
logger.debug('f is being called')
t1.A.flag = True
logger.debug('ID t1: %r', id(t1))
logger.debug('ID t1.A: %r', id(t1.A))
logger.debug('ID t1.A.flag: %r', id(t1.A.flag))
print(t1.A.flag)
</code></pre>
<h1>My output</h1>
<p><sup><sub>I'm splitting this up with comments</sub></sup></p>
<pre><code>DEBUG:__main__:t1 has started
DEBUG:__main__:t2 is being imported
DEBUG:t2:t2 is being imported
DEBUG:t2:t2 is now importing t1
</code></pre>
<p>As you can see, the first time around (as others have mentioned) <code>t1</code> actually has the name of <code>__main__</code>. It tries importing <code>t2</code>, but immediately <code>t2</code> tries importing <code>t1</code>. </p>
<pre><code>DEBUG:t1:t1 has started
DEBUG:t1:t2 is being imported
</code></pre>
<p>You can see that none of the <code>t2</code> logging statements run. That's because Python caches imported modules, so it first looks in the cache for <code>t2</code> and says, "Ahah! I've already imported this guy, I just need to return it. Here you go, then!"</p>
<pre><code>DEBUG:t1:A is being "compiled"
DEBUG:t1:ID A: 140377934341704
DEBUG:t1:ID A.flag 4312040768
DEBUG:t1:What is __name__? 't1'
</code></pre>
<p>So, you'll notice that now it has made its way through importing <code>t1</code>. And <code>t2</code></p>
<pre><code>DEBUG:t2:t2 is done being imported
</code></pre>
<p>Execution continues back in the <code>__main__</code> <code>t1</code></p>
<pre><code>DEBUG:__main__:A is being "compiled"
DEBUG:__main__:ID A: 140377934344360
DEBUG:__main__:ID A.flag 4312040768
</code></pre>
<p>Notice that the <code>id</code> for this <code>A</code> and <code>A.flag</code> are different!</p>
<pre><code>DEBUG:__main__:What is __name__? '__main__'
DEBUG:__main__:__name__ was "__main__"
DEBUG:__main__:Calling t2.f()
DEBUG:t2:f is being called
DEBUG:t2:ID t1: 4317998840
DEBUG:t2:ID t1.A: 140377934341704
DEBUG:t2:ID t1.A.flag: 4312040736
</code></pre>
<p>Notice again, that these <code>id</code>s match <code>t1.A</code>'s, and not <code>__main__.A</code>s.</p>
<pre><code>True
DEBUG:__main__:t2.f() was called
DEBUG:__main__:ID A.flag: 4312040768
False
</code></pre>
| 0 | 2016-07-29T04:15:35Z | [
"python"
] |
Keep one method constantly running and another method executing every certain period | 38,649,612 | <p>So currently I am these two method where one reads the RF Data from another device constantly and another method sends that data every so often.</p>
<p>How could I do this? I need the RF Data incoming to be constantly updated and received while the sendData() method just grabs the data from the global variable whenever it can. </p>
<p>Heres the code below so far but it's not working...</p>
<pre><code>import httplib, urllib
import time, sys
import serial
from multiprocessing import Process
key = 'MY API KEY'
rfWaterLevelVal = 0
ser = serial.Serial('/dev/ttyUSB0',9600)
def rfWaterLevel():
global rfWaterLevelVal
rfDataArray = ser.readline().strip().split()
print 'incoming: %s' %rfDataArray
if len(rfDataArray) == 5:
rfWaterLevelVal = float(rfDataArray[4])
print 'RFWater Level1: %.3f cm' % (rfWaterLevelVal)
#rfWaterLevel = 0
def sendData():
global rfWaterLevelVal
params = urllib.urlencode({'field1':rfWaterLevelVal, 'key':key})
headers = {"Content-type" : "application/x-www-form-urlencoded","Accept": "text/plain"}
conn = httplib.HTTPConnection("api.thingspeak.com:80", timeout = 5)
conn.request("POST", "/update", params, headers)
#print 'RFWater Level2: %.3f cm' % (rfWaterLevelVal)
response = conn.getresponse()
print response.status, response.reason
data = response.read()
conn.close()
while True:
try:
rfWaterLevel()
p = Process(target=sendData(), args())
p.start()
p.join()
#Also tried threading...did not work..
#t1 = threading.Thread(target=rfWaterLevel())
#t2 = threading.Thread(target=sendData())
#t1.start()
#t1.join()
#t2.join()
except KeyboardInterrupt:
print "caught keyboard interrupt"
sys.exit()
</code></pre>
<p>Please help!</p>
<p>Just to clarify, I need rfWaterLevel() method to run constantly as the rf data is incoming constantly, and I need sendData() to just be called as soon as it's ready to send again (roughly every 5 seconds or so). But it seems as if, if there is any sort of delay to the incoming rf data then rf data stops updating itself (the received end) and thus the data being sent is not accurate to what is being sent from the rf transmitter.</p>
<p>Thanks in advance!</p>
| 0 | 2016-07-29T02:27:02Z | 38,651,243 | <p>I can't give you a full solution but I can guide you into the right direction.</p>
<p>Your code has three problems.</p>
<ol>
<li><p><code>Process</code> starts (as the name suggests) a new process and not a new thread.
A new process cannot share data with the old process.
You should use mutlithreading instead.
Have a look at <code>threading</code> as explained <a href="http://stackoverflow.com/questions/2905965/creating-threads-in-python">here</a></p></li>
<li><p>You are calling <code>rfWaterLevel()</code> inside the main thread.
You need to start the second thread before entering the while Loop.</p></li>
<li><p>Your are creating the second thread again and again inside the while Loop.
Create it only once and put the while Loop inside the function</p></li>
</ol>
<p>Your basic program structure should be like this:</p>
<pre><code>import time
def thread_function_1():
while True:
rfWaterLevel()
def thread_function_2():
while True:
sendData()
time.sleep(5)
# start thread 1
thread1 = Thread(target = thread_function_1)
thread1.start()
# start thread 2
thread2 = Thread(target = thread_function_2)
thread2.start()
# wait for both threads to finish
thread1.join()
thread2.join()
</code></pre>
| 1 | 2016-07-29T05:41:25Z | [
"python",
"multithreading",
"multiprocessing",
"raspberry-pi2"
] |
facet_grid not working in ggplot for python? | 38,649,657 | <p>I want to create plots based upon summary statistics rather than letting ggplot aggregate for me. After trying and failing with geom_violin() I finally settled on calculating percentiles and creating barplots. Even so I can't seem to produce them. </p>
<p>In R this works:</p>
<pre><code>library(dplyr)
library(ggplot2)
p = seq(0,1,length.out=11)
diaa <- diamonds[,c("cut","color","table")]
diab <- diaa %>% group_by(cut,color) %>% do(data.frame(p=p,stats=quantile(.$table,probs=p)))
ggplot(diab,aes(x=p,weight=stats)) + geom_bar() + facet_grid(cut ~ color)
</code></pre>
<p><a href="http://i.stack.imgur.com/k8Yie.png" rel="nofollow"><img src="http://i.stack.imgur.com/k8Yie.png" alt="enter image description here"></a></p>
<p>But if I try the same thing in python:</p>
<pre><code>from ggplot import *
diaa = diamonds[['cut','color','table']]
diab = diaa.groupby(['cut','color']).quantile([x/100.0 for x in range(0,100,5)])
diab.reset_index(inplace=True)
diab.columns = ['cut','color','p','stats']
ggplot(diab,aes(x='p',weight='stats')) + geom_bar() + facet_grid('color','cut')
</code></pre>
<p>It throws lots of errors. Am I misusing it?</p>
<pre><code>---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/mccarthy/.pyenv/versions/2.7.12/envs/plotting/lib/python2.7/site-packages/IPython/core/formatters.pyc in __call__(self, obj)
668 type_pprinters=self.type_printers,
669 deferred_pprinters=self.deferred_printers)
--> 670 printer.pretty(obj)
671 printer.flush()
672 return stream.getvalue()
/home/mccarthy/.pyenv/versions/2.7.12/envs/plotting/lib/python2.7/site-packages/IPython/lib/pretty.pyc in pretty(self, obj)
381 if callable(meth):
382 return meth(obj, self, cycle)
--> 383 return _default_pprint(obj, self, cycle)
384 finally:
385 self.end_group()
/home/mccarthy/.pyenv/versions/2.7.12/envs/plotting/lib/python2.7/site-packages/IPython/lib/pretty.pyc in _default_pprint(obj, p, cycle)
501 if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs:
502 # A user-provided repr. Find newlines and replace them with p.break_()
--> 503 _repr_pprint(obj, p, cycle)
504 return
505 p.begin_group(1, '<')
/home/mccarthy/.pyenv/versions/2.7.12/envs/plotting/lib/python2.7/site-packages/IPython/lib/pretty.pyc in _repr_pprint(obj, p, cycle)
692 """A pprint that just redirects to the normal repr function."""
693 # Find newlines and replace them with p.break_()
--> 694 output = repr(obj)
695 for idx,output_line in enumerate(output.splitlines()):
696 if idx:
/home/mccarthy/.pyenv/versions/2.7.12/envs/plotting/lib/python2.7/site-packages/ggplot/ggplot.pyc in __repr__(self)
117
118 def __repr__(self):
--> 119 self.make()
120 # this is nice for dev but not the best for "real"
121 if os.environ.get("GGPLOT_DEV"):
/home/mccarthy/.pyenv/versions/2.7.12/envs/plotting/lib/python2.7/site-packages/ggplot/ggplot.pyc in make(self)
600 facet_filter = facetgroup[self.facets.facet_cols].iloc[0].to_dict()
601 for k, v in facet_filter.items():
--> 602 mask = (mask) & (df[k]==v)
603 df = df[mask]
604
TypeError: 'NoneType' object has no attribute '__getitem__'
</code></pre>
| 1 | 2016-07-29T02:31:46Z | 38,710,623 | <p>It looks like it's fixed now in 0.11.1.</p>
<p><a href="https://github.com/yhat/ggplot/issues/515" rel="nofollow">https://github.com/yhat/ggplot/issues/515</a></p>
| 0 | 2016-08-02T01:48:52Z | [
"python",
"ggplot2",
"python-ggplot"
] |
Can the Kivy language access inherited layouts and widgets? | 38,649,664 | <p>Can the kivy language access inherited layouts and widgets? I want to create one basic BoxLayout that contains the styling and title Label for my widget. I want to be able to inherit from this widget and add additional widgets in different positions.</p>
<pre><code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
Builder.load_string('''
<SimpleBar>:
canvas.before:
Color:
rgba: 0, 0.5, 0.5, 1
Rectangle:
pos: self.pos
size: self.size
BoxLayout:
id: my_layout
Label:
text: "hi"
<NewBar>:
Label:
text: "2"
''')
class SimpleBar(BoxLayout):
def log(self, value):
print(value)
class NewBar(SimpleBar):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
print(dir(self))
class GeneralApp(App):
def build(self):
return NewBar()
if __name__ == '__main__':
GeneralApp().run()
</code></pre>
<p>Above is my basic running widget.</p>
<p>I want NewBar's "2" Label to be located before SimpleBar's 'hi' Label like below.</p>
<pre><code><NewBar>:
BoxLayout:
id: my_layout
Label:
text: "2"
Label:
text: "hi"
</code></pre>
<p>I know that - can negate items. However, <code><-NewBar></code> removes all of my styling.</p>
<p>Is there any way to do this in the kivy language?</p>
| 7 | 2016-07-29T02:32:28Z | 39,183,012 | <p>With simple kv no, because if you put something in the widget (e.g. <code>Label: ...</code>), it'll call <code><widget>.add_widget()</code> method and when such a method is called without <a href="https://kivy.org/docs/api-kivy.uix.widget.html#kivy.uix.widget.Widget.add_widget" rel="nofollow">additional</a> parameters, it will by default place the widget after whatever was already placed before it. Therefore you can either search through the <code>kivy/lang/parser.py</code> file and add such a functionality(PR welcome), or do it within python in hm... <code>__init__</code> or wherever you'll like to add the widget (maybe after some event).</p>
<p>To do that within python you can call <code><widget (or self)>.add_widget(<child>, index=<where>)</code> according to the docs. For example:</p>
<pre><code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ListProperty
Builder.load_string('''
#:import Factory kivy.factory.Factory
<Ninja@Label>:
<SimpleBar>:
BoxLayout:
id: my_layout
Label:
text: "hi"
<ChildWithBenefits>:
placebefore:
[(Factory.Label(text='I am the first!'), 0),
(Factory.Ninja(text='No, I am!'), 2)]
''')
class SimpleBar(BoxLayout):
def log(self, value):
print(value)
class ChildWithBenefits(SimpleBar):
placebefore = ListProperty([])
def __init__(self, *args, **kwargs):
super(ChildWithBenefits, self).__init__(*args, **kwargs)
for child, index in self.placebefore:
print child.text
print type(child)
self.add_widget(child, index=index)
self.log('Hello!')
class GeneralApp(App):
def build(self):
return ChildWithBenefits()
if __name__ == '__main__':
GeneralApp().run()
</code></pre>
| 1 | 2016-08-27T15:56:11Z | [
"python",
"kivy",
"kivy-language"
] |
Can the Kivy language access inherited layouts and widgets? | 38,649,664 | <p>Can the kivy language access inherited layouts and widgets? I want to create one basic BoxLayout that contains the styling and title Label for my widget. I want to be able to inherit from this widget and add additional widgets in different positions.</p>
<pre><code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
Builder.load_string('''
<SimpleBar>:
canvas.before:
Color:
rgba: 0, 0.5, 0.5, 1
Rectangle:
pos: self.pos
size: self.size
BoxLayout:
id: my_layout
Label:
text: "hi"
<NewBar>:
Label:
text: "2"
''')
class SimpleBar(BoxLayout):
def log(self, value):
print(value)
class NewBar(SimpleBar):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
print(dir(self))
class GeneralApp(App):
def build(self):
return NewBar()
if __name__ == '__main__':
GeneralApp().run()
</code></pre>
<p>Above is my basic running widget.</p>
<p>I want NewBar's "2" Label to be located before SimpleBar's 'hi' Label like below.</p>
<pre><code><NewBar>:
BoxLayout:
id: my_layout
Label:
text: "2"
Label:
text: "hi"
</code></pre>
<p>I know that - can negate items. However, <code><-NewBar></code> removes all of my styling.</p>
<p>Is there any way to do this in the kivy language?</p>
| 7 | 2016-07-29T02:32:28Z | 39,196,128 | <p>Here's a fun thing: you don't need to specify all classes used in kv lang in the lang itself - you can also add them using <code>Factory.register</code> method later in code. Here's an example:</p>
<pre><code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.factory import Factory
from functools import partial
Builder.load_string('''
<MyWidget>:
Foo
Bar
''')
class MyWidget(BoxLayout):
pass
class MyApp(App):
def build(self):
Factory.register('Foo', cls=partial(Label, text='foo'))
Factory.register('Bar', cls=partial(Label, text='bar'))
return MyWidget()
if __name__ == '__main__':
MyApp().run()
</code></pre>
<p>Let's use it to create a template base widget we later fill with various content. We use a placeholder that we later replace with another widget:</p>
<pre><code><BaseWidget>:
orientation: 'vertical'
Label:
size_hint: None, 0.1
text: 'title'
Placeholder
</code></pre>
<p>In the Python code we register a placeholder class in the <code>__init__</code> method of this base template class.</p>
<pre><code>class BaseWidget(BoxLayout):
def __init__(self, **args):
# unregister if already registered...
Factory.unregister('Placeholder')
Factory.register('Placeholder', cls=self.placeholder)
super(BaseWidget, self).__init__(**args)
</code></pre>
<p>Now let's define a content class.</p>
<pre><code><TwoButtonWidget>:
Button:
text: 'button 1'
Button:
text: 'button 2'
</code></pre>
<p>And finally create a customized class that use our base class as a template and replaces its placeholder with a content class. This class don't have its own kivy rules (these are moved into content class) so when we inherite from our base template, no extra widgets are inserted.</p>
<pre><code># content class
class TwoButtonWidget(BoxLayout):
pass
# Base class subclass
class CustomizedWidget(BaseWidget):
placeholder = TwoButtonWidget # set contetnt class
</code></pre>
<p>A full example:</p>
<pre><code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.factory import Factory
Builder.load_string('''
<BaseWidget>:
orientation: 'vertical'
widget_title: widget_title
placeholder: placeholder
Label:
size_hint: None, 0.1
id: widget_title
Placeholder
id: placeholder
<TwoButtonWidget>:
button1: button1
Button:
text: 'button 1'
id: button1
Button:
text: 'button 2'
<ThreeButtonWidget>:
orientation: 'vertical'
Button:
text: 'button a'
Button:
text: 'button b'
Button:
text: 'button c'
''')
class BaseWidget(BoxLayout):
def __init__(self, **args):
# unregister if already registered...
Factory.unregister('Placeholder')
Factory.register('Placeholder', cls=self.placeholder)
super(BaseWidget, self).__init__(**args)
class TwoButtonWidget(BoxLayout):
pass
class ThreeButtonWidget(BoxLayout):
pass
class CustomizedWidget1(BaseWidget):
placeholder = TwoButtonWidget
class CustomizedWidget2(BaseWidget):
placeholder = ThreeButtonWidget
class MyApp(App):
def build(self):
layout = BoxLayout()
c1 = CustomizedWidget1()
# we can access base widget...
c1.widget_title.text = 'First'
# we can access placeholder
c1.placeholder.button1.text = 'This was 1 before'
c2 = CustomizedWidget2()
c2.widget_title.text = 'Second'
layout.add_widget(c1)
layout.add_widget(c2)
return layout
if __name__ == '__main__':
MyApp().run()
</code></pre>
<p>You can easily extend it and for example, have multiple placeholders.</p>
<p>Applying this to your case:</p>
<pre><code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.factory import Factory
from functools import partial
Builder.load_string('''
<SimpleBar>:
canvas.before:
Color:
rgba: 0, 0.5, 0.5, 1
Rectangle:
pos: self.pos
size: self.size
BoxLayout:
Placeholder
Label:
text: "hi"
<NewBarContent>:
Label:
text: "2"
''')
class SimpleBar(BoxLayout):
def __init__(self, **args):
# unregister if already registered...
Factory.unregister('Placeholder')
Factory.register('Placeholder', cls=self.placeholder)
super(SimpleBar, self).__init__(**args)
class NewBarContent(BoxLayout):
pass
class NewBar(SimpleBar):
placeholder = NewBarContent
class MyApp(App):
def build(self):
return NewBar()
if __name__ == '__main__':
MyApp().run()
</code></pre>
| 1 | 2016-08-28T21:52:16Z | [
"python",
"kivy",
"kivy-language"
] |
How would I create a new line in Python? | 38,649,755 | <p>I am using Python 2.7 and this is what I am working with </p>
<pre><code>print( "Massa: ", line.count("massa"))
# trying to create a new line between these two lines
print( "Lorem: ",line.count("lorem")+1)
</code></pre>
<p>I tried this </p>
<pre><code>print( "Massa: ", line.count("massa"))\n( "Lorem: ", line.count("lorem")+1)
</code></pre>
<p>and did not get the results I was looking for</p>
| 0 | 2016-07-29T02:45:34Z | 38,649,811 | <p>I think you can just use:</p>
<pre><code>print ""
</code></pre>
<p>to print a newline</p>
| 0 | 2016-07-29T02:53:02Z | [
"python",
"python-2.7",
"newline"
] |
How would I create a new line in Python? | 38,649,755 | <p>I am using Python 2.7 and this is what I am working with </p>
<pre><code>print( "Massa: ", line.count("massa"))
# trying to create a new line between these two lines
print( "Lorem: ",line.count("lorem")+1)
</code></pre>
<p>I tried this </p>
<pre><code>print( "Massa: ", line.count("massa"))\n( "Lorem: ", line.count("lorem")+1)
</code></pre>
<p>and did not get the results I was looking for</p>
| 0 | 2016-07-29T02:45:34Z | 38,649,825 | <p>If you mean that you want to print it with a single print statement, this will do it. </p>
<pre><code>print "Massa: ", line.count("massa"), "\n", "Lorem: ", line.count("lorem")+1
</code></pre>
<p>Since you are using Python 2.7 I removed the enclosing brackets, otherwise the strings are treated as elements of a tuple. I have also added a new line character <code>\n</code> in the middle to separate the output into 2 lines.</p>
<p>If you print the itmes as 2 separate print statements a new line will appear between them:</p>
<pre><code>print "Massa: ", line.count("massa")
print "Lorem: ", line.count("lorem")+1
</code></pre>
| 1 | 2016-07-29T02:54:17Z | [
"python",
"python-2.7",
"newline"
] |
How would I create a new line in Python? | 38,649,755 | <p>I am using Python 2.7 and this is what I am working with </p>
<pre><code>print( "Massa: ", line.count("massa"))
# trying to create a new line between these two lines
print( "Lorem: ",line.count("lorem")+1)
</code></pre>
<p>I tried this </p>
<pre><code>print( "Massa: ", line.count("massa"))\n( "Lorem: ", line.count("lorem")+1)
</code></pre>
<p>and did not get the results I was looking for</p>
| 0 | 2016-07-29T02:45:34Z | 38,650,849 | <p><code>\n</code> creates a line break. You can pass it as a single string and use <a href="https://docs.python.org/2.7/library/string.html#formatstrings" rel="nofollow"><code>format</code></a> to place your parameters.</p>
<pre><code>print("Massa: {0}\nLorem: {1}".format(line.count("massa"), line.count("lorem")+1))
</code></pre>
| 0 | 2016-07-29T05:04:48Z | [
"python",
"python-2.7",
"newline"
] |
NOT NULL constraint failed: stores_store.merchant_id | 38,649,975 | <p>I am using djano rest framework for designing an API for store listing, and creation. The concept of my app is a linkage between merchant and buyer. A merchant can have multiple store of various categories.I have a model of Merchant which contains about merchant information,product which contains a list of product of certain categories and Store which contains information about store.I could list the store using API and also could show the form for Store creation. However i get following error when trying to create a new store.</p>
<p><strong>IntegrityError at /api/stores/create/ NOT NULL constraint failed: stores_store.merchant_id</strong></p>
<p><strong>my models.py</strong></p>
<pre><code>class Merchant(models.Model):
user = models.ForeignKey(User)
phone = models.PositiveIntegerField(null=True,blank=True)
class Store(models.Model):
merchant = models.ForeignKey(Merchant)
name_of_legal_entity = models.CharField(max_length=250)
class Product(models.Model):
store = models.ForeignKey(Store)
image = models.ForeignKey('ProductImage',blank=True,null=True)
name_of_product = models.CharField(max_length=120)
class ProductImage(models.Model):
image = models.ImageField(upload_to='products/images/')
class StoreCategory(models.Model):
product = models.ForeignKey(Product,null=True, on_delete=models.CASCADE,related_name="store_category")
store_category = models.CharField(choices=STORE_CATEGORIES, default='GROCERY', max_length=10)
</code></pre>
<p><strong>Serializers.py</strong></p>
<pre><code>User = get_user_model()
class UserSerializer(ModelSerializer):
class Meta:
model = User
fields = ("username","first_name","last_name","email",)
class MerchantSerializer(serializers.ModelSerializer):
user = UserSerializer()
class Meta:
model = Merchant
fields = ["id","user","phone","address","city",]
class ProductImageSerializer(ModelSerializer):
class Meta:
model = ProductImage
fields = ( 'id','imageName','image', )
class ProductSerializers(ModelSerializer):
image = ProductImageSerializer()
class Meta:
model = Product
fields=('id','image','name_of_product','description','price','active',)
class StoreCategorySerializer(ModelSerializer):
product = ProductSerializers()
class Meta:
model = StoreCategory
# fields=["id","store_category",]
class StoreSerializer(ModelSerializer):
# url = HyperlinkedIdentityField(view_name='stores_detail_api')
store_categories = StoreCategorySerializer(many=True)
merchant = MerchantSerializer()
class Meta:
model = Store
fields=("id",
# "url",
"merchant",
"store_categories",
"name_of_legal_entity",
"pan_number",
"registered_office_address",
"name_of_store",
"store_contact_number",
"store_long",
"store_lat",
"store_start_time",
"store_end_time",
"store_off_day",
)
class StoreCreateSerializer(ModelSerializer):
store_categories = StoreCategorySerializer()
merchant = MerchantSerializer()
class Meta:
model = Store
fields=("id",
"merchant",
"store_categories",
"name_of_legal_entity",
"pan_number",
"registered_office_address",
"name_of_store",
"store_contact_number",
"store_long",
"store_lat",
"store_start_time",
"store_end_time",
"store_off_day",
)
def create(self,validated_data):
store_categories_data = validated_data.pop('store_categories')
merchant_data = validated_data.pop('merchant')
store = Store.objects.create(**validated_data)
for store_categories in store_categories_data:
store_categories, created = StoreCategory.objects.get_or_create(pan_number=store_categories['pan_number'])
store.store_categories.add(store_categories)
for merchant in merchant_data:
merchant, created = Merchant.objects.get_or_create(user=merchant['user'])
store.merchant.add(merchant)
return store
</code></pre>
<p><strong>Views.py</strong></p>
<pre><code>class StoreCreateAPIView(CreateAPIView):
queryset = Store.objects.all()
serializer_class = StoreCreateSerializer
parser_classes = (FormParser,MultiPartParser,)
</code></pre>
<p><strong>Merchant object looks like this</strong></p>
<pre><code> "merchant": {
"id": 6,
"username": "sans",
"first_name": "sans",
"last_name": "bas",
"email": "sans@gmail.com"
},
</code></pre>
| 1 | 2016-07-29T03:15:14Z | 38,675,642 | <p>there is problem with StroreCreateSerializer. your are trying to create instance of Store without merchant thats why you are getting error. If you want to create store without merchant you need to make merchant foreign key Null true. I hope this help.</p>
<p>Moreover you are using add() with foreign key. add() method works with Many to Many relation. </p>
<pre><code>class StoreCreateSerializer(ModelSerializer):
store_categories = StoreCategorySerializer()
merchant = MerchantSerializer()
class Meta:
model = Store
fields=("id",
"merchant",
"store_categories",
"name_of_legal_entity",
"pan_number",
"registered_office_address",
"name_of_store",
"store_contact_number",
"store_long",
"store_lat",
"store_start_time",
"store_end_time",
"store_off_day",
)
def create(self,validated_data):
store_categories_data = validated_data.pop('store_categories')
merchant_data = validated_data.pop('merchant')
for merchant in merchant_data:
merchant, created = Merchant.objects.get_or_create(user=merchant['user']['email'], default=merchant['user'])
validated_data["merchant"] = merchant
store = Store.objects.create(**validated_data)
for store_categories in store_categories_data:
store_categories, created = StoreCategory.objects.get_or_create(pan_number=store_categories['pan_number'])
store_categories.product.store = store
store_categories.save()
return store
</code></pre>
<p>To make this work you need JSON Should be like below:</p>
<pre><code>{
merchant:{
"user":{
"first_name":"ABC",
"last_name": "xyz",
"email":"xyz@abc.com"
}
}
}
</code></pre>
| 0 | 2016-07-30T15:36:22Z | [
"python",
"django",
"api",
"python-3.x",
"django-rest-framework"
] |
How to Prevent Triplicates in Pandas DataFrame | 38,649,993 | <p>I have the following code:</p>
<pre><code>stim_df = pd.concat([block1,block2,bloc3,block4], axis=0, ignore_index=True).sample(frac=1).reset_index(drop=True)
stim_df.columns = ["Word","Condition"]
#Check for triplicates:
for j in xrange(len(stim_df)):
if j == 0 or j == 1:
pass
else:
if stim_df["Condition"][j] == stim_df["Condition"][j-1] == stim_df["Condition"][j-2]:
stim_df[j-2:j+3] = stim_df[j-2:j+3].reindex([j-2,j-1,j+2,j,j+1])
</code></pre>
<p>What I'm trying to prevent from happening is three adjacent rows with the same "Conditions" value appearing together. So if my conditions are "1","2",and "3", I want to prevent an order like 1,1,2,2,2,1,3,1 from occurring, where the condition value 2 appears three times in a row. </p>
<p>Here's a quick sample of a portion of the df:</p>
<pre><code> Condition Word
0 1 neut
1 2 pos
2 3 neg
3 3 neg
4 3 neg
5 2 pos
6 1 neut
7 2 pos
8 2 pos
9 2 pos
10 2 pos
</code></pre>
<p>My code doesn't solve the issue. Would it be better to create a pseudo-randomization function, rather than trying to deal with this after I've already randomly mixed the dataframe? Any assistance or suggestions would really help.</p>
| -1 | 2016-07-29T03:17:56Z | 38,664,855 | <p>Are you looking to generate a sequence with no repetitions, or just remove the a sequence like <code>2,2,2</code>?</p>
<p>If you're looking for the latter, try using <code>diff</code> to remove repeating sequences.</p>
<pre><code>df[~(df.Condition.diff() == 0)]
Condition Word
0 1 neut
1 2 pos
2 3 neg
5 2 pos
6 1 neut
7 2 pos
</code></pre>
| 0 | 2016-07-29T17:57:49Z | [
"python",
"pandas",
"random",
"dataframe"
] |
How to speed up wait wake-up from notify_all? | 38,650,008 | <p>Platform: Python 2.6 on CentOS 6</p>
<p>I've got 2 threads using the same object. Thread 1 feeds the object data and when the correct data is found, it does a <code>threading.Condition.notify_all()</code>.</p>
<p>Thread 2, via the object, calls <code>threading.Condition.wait()</code> on the same condition variable.</p>
<p>I'm grabbing <code>datetime.datetime.now()</code> before the <code>notify_all()</code> call, and after the <code>wait()</code> call. The time difference between the two varies between 9 and 45 ms. That's an eternity!</p>
<p>What I've tried: I've called <code>os.nice()</code> to decrease the priority of Thread1, hoping that it would force an immediate context switch [ I call <code>os.nice()</code> inside Thread 1's <code>threading.Thread()</code> target ]. No love. Also no love by adding a <code>time.sleep(0.001)</code> after the call to <code>notify_all()</code>.</p>
<p>I should also note this is a multi-process application, these 2 threads are in one of about 5 processes. I'm running on a Xeon with 8 hyper-threaded cores and 32 GB of RAM. So the processor pipe should be phenomenal. </p>
<p>Suggestions? Questions that I need to be asking that I may not have asked myself yet? I expect some context-switching time, but 45 ms seems absolutely ludicrous. It truly is an eternity.</p>
<p>EDIT: the code that uses the condition variable.</p>
<pre><code>def ProcessEvent( self, event ):
with self.__conditionVar:
if self.__testEvent( event ):
self.__notifyTime = datetime.now()
self.__conditionVar.notify_all()
def WaitForEvent( self, timeout_sec ):
with self.__conditionVar:
if not self.__alreadyFound():
self.__conditionVar.wait( timeout_sec )
delta = datetime.now() - self.__notifyTime
print "Wake-up time =", delta
</code></pre>
| 0 | 2016-07-29T03:19:55Z | 38,650,021 | <p>To speed the wake up from <code>notify_all</code>, hold the lock for less time after <code>wait</code> returns. It's the lock that's preventing the other thread from making progress.</p>
<p>If this doesn't make the solution to your problem obvious, there's a very good chance that you are misusing conditions. If so, explain why you are using conditions.</p>
| 0 | 2016-07-29T03:21:44Z | [
"python",
"multithreading",
"multiprocessing"
] |
the assertionerror when run py-faster-rcnn | 38,650,014 | <p>When I tried to run the py-faster-rcnn followed the README.md in Githubï¼
./experiments/scripts/faster_rcnn_alt_opt.sh 0 VGG_CNN_M_1024 pascal_voc</p>
<p>And it stuck in stage like this:
AssertionError: Path does not exist: /home/jiaxin/py-faster-rcnn/data/VOCdevkit2007/VOC2007/ImageSets/Main/trainval.txt</p>
<pre><code>+ set -e
+ export PYTHONUNBUFFERED=True
+ PYTHONUNBUFFERED=True
+ GPU_ID=0
+ NET=VGG_CNN_M_1024
+ NET_lc=vgg_cnn_m_1024
+ DATASET=pascal_voc
+ array=($@)
+ len=3
+ EXTRA_ARGS=
+ EXTRA_ARGS_SLUG=
+ case $DATASET in
+ TRAIN_IMDB=voc_2007_trainval
+ TEST_IMDB=voc_2007_test
+ PT_DIR=pascal_voc
+ ITERS=40000
++ date +%Y-%m-%d_%H-%M-%S
+ LOG=experiments/logs/faster_rcnn_alt_opt_VGG_CNN_M_1024_.txt.2016-07-30_19-36-05
+ exec
++ tee -a experiments/logs/faster_rcnn_alt_opt_VGG_CNN_M_1024_.txt.2016-07-30_19-36-05
+ echo Logging output to experiments/logs/faster_rcnn_alt_opt_VGG_CNN_M_1024_.txt.2016-07-30_19-36-05
Logging output to experiments/logs/faster_rcnn_alt_opt_VGG_CNN_M_1024_.txt.2016-07-30_19-36-05
+ ./tools/train_faster_rcnn_alt_opt.py --gpu 0 --net_name VGG_CNN_M_1024 --weights data/imagenet_models/VGG_CNN_M_1024.v2.caffemodel --imdb voc_2007_trainval --cfg experiments/cfgs/faster_rcnn_alt_opt.yml
Called with args:
Namespace(cfg_file='experiments/cfgs/faster_rcnn_alt_opt.yml', gpu_id=0, imdb_name='voc_2007_trainval', net_name='VGG_CNN_M_1024', pretrained_model='data/imagenet_models/VGG_CNN_M_1024.v2.caffemodel', set_cfgs=None)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Stage 1 RPN, init from ImageNet model
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Init model: data/imagenet_models/VGG_CNN_M_1024.v2.caffemodel
Using config:
{'DATA_DIR': '/home/jiaxin/py-faster-rcnn/data',
'DEDUP_BOXES': 0.0625,
'EPS': 1e-14,
'EXP_DIR': 'faster_rcnn_alt_opt',
'GPU_ID': 0,
'MATLAB': 'matlab',
'MODELS_DIR': '/home/jiaxin/py-faster-rcnn/models/pascal_voc',
'PIXEL_MEANS': array([[[ 102.9801, 115.9465, 122.7717]]]),
'RNG_SEED': 3,
'ROOT_DIR': '/home/jiaxin/py-faster-rcnn',
'TEST': {'BBOX_REG': True,
'HAS_RPN': True,
'MAX_SIZE': 1000,
'NMS': 0.3,
'PROPOSAL_METHOD': 'selective_search',
'RPN_MIN_SIZE': 16,
'RPN_NMS_THRESH': 0.7,
'RPN_POST_NMS_TOP_N': 300,
'RPN_PRE_NMS_TOP_N': 6000,
'SCALES': [600],
'SVM': False},
'TRAIN': {'ASPECT_GROUPING': True,
'BATCH_SIZE': 128,
'BBOX_INSIDE_WEIGHTS': [1.0, 1.0, 1.0, 1.0],
'BBOX_NORMALIZE_MEANS': [0.0, 0.0, 0.0, 0.0],
'BBOX_NORMALIZE_STDS': [0.1, 0.1, 0.2, 0.2],
'BBOX_NORMALIZE_TARGETS': True,
'BBOX_NORMALIZE_TARGETS_PRECOMPUTED': False,
'BBOX_REG': False,
'BBOX_THRESH': 0.5,
'BG_THRESH_HI': 0.5,
'BG_THRESH_LO': 0.0,
'FG_FRACTION': 0.25,
'FG_THRESH': 0.5,
'HAS_RPN': True,
'IMS_PER_BATCH': 1,
'MAX_SIZE': 1000,
'PROPOSAL_METHOD': 'gt',
'RPN_BATCHSIZE': 256,
'RPN_BBOX_INSIDE_WEIGHTS': [1.0, 1.0, 1.0, 1.0],
'RPN_CLOBBER_POSITIVES': False,
'RPN_FG_FRACTION': 0.5,
'RPN_MIN_SIZE': 16,
'RPN_NEGATIVE_OVERLAP': 0.3,
'RPN_NMS_THRESH': 0.7,
'RPN_POSITIVE_OVERLAP': 0.7,
'RPN_POSITIVE_WEIGHT': -1.0,
'RPN_POST_NMS_TOP_N': 2000,
'RPN_PRE_NMS_TOP_N': 12000,
'SCALES': [600],
'SNAPSHOT_INFIX': 'stage1',
'SNAPSHOT_ITERS': 10000,
'USE_FLIPPED': True,
'USE_PREFETCH': False},
'USE_GPU_NMS': True}
Process Process-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "./tools/train_faster_rcnn_alt_opt.py", line 122, in train_rpn
roidb, imdb = get_roidb(imdb_name)
File "./tools/train_faster_rcnn_alt_opt.py", line 61, in get_roidb
imdb = get_imdb(imdb_name)
File "/home/jiaxin/py-faster-rcnn/tools/../lib/datasets/factory.py", line 38, in get_imdb
return __sets[name]()
File "/home/jiaxin/py-faster-rcnn/tools/../lib/datasets/factory.py", line 20, in <lambda>
__sets[name] = (lambda split=split, year=year: pascal_voc(split, year))
File "/home/jiaxin/py-faster-rcnn/tools/../lib/datasets/pascal_voc.py", line 38, in __init__
self._image_index = self._load_image_set_index()
File "/home/jiaxin/py-faster-rcnn/tools/../lib/datasets/pascal_voc.py", line 82, in _load_image_set_index
'Path does not exist: {}'.format(image_set_file)
AssertionError: Path does not exist: /home/jiaxin/py-faster-rcnn/data/VOCdevkit2007/VOC2007/ImageSets/Main/trainval.txt
</code></pre>
<p>What should I do? I checked the trainval.txt file before I built the symbolic link, it existed. I don't know what happened after I built the symbolic link, I cannot open this file any more.</p>
<p>And I changed my command like this:
./experiments/scripts/faster_rcnn_alt_opt.sh 0 VGG_CNN_M_1024 pascal_voc --set EXP_DIR foobar RNG_SEED 42 TRAIN.SCALES "[400, 500, 600, 700]"</p>
<p>It stuck with another AssertionError again:</p>
<ul>
<li>set -e</li>
<li>export PYTHONUNBUFFERED=True</li>
<li>PYTHONUNBUFFERED=True</li>
<li>GPU_ID=0</li>
<li>NET=VGG_CNN_M_1024</li>
<li>NET_lc=vgg_cnn_m_1024</li>
<li>DATASET=pascal_voc</li>
<li>array=($@)</li>
<li>len=13</li>
<li>EXTRA_ARGS='--set EXP_DIR foobar RNG_SEED 42 TRAIN.SCALES [400, 500, 600, 700]'</li>
<li>EXTRA_ARGS_SLUG='--set_EXP_DIR_foobar_RNG_SEED_42_TRAIN.SCALES_[400,_500,_600,_700]'</li>
<li>case $DATASET in</li>
<li>TRAIN_IMDB=voc_2007_trainval</li>
<li>TEST_IMDB=voc_2007_test</li>
<li>PT_DIR=pascal_voc</li>
<li>ITERS=40000
++ date +%Y-%m-%d_%H-%M-%S</li>
<li>LOG='experiments/logs/faster_rcnn_alt_opt_VGG_CNN_M_1024_--set_EXP_DIR_foobar_RNG_SEED_42_TRAIN.SCALES_[400,_500,_600,_700].txt.2016-07-30_19-41-43'</li>
<li>exec
++ tee -a 'experiments/logs/faster_rcnn_alt_opt_VGG_CNN_M_1024_--set_EXP_DIR_foobar_RNG_SEED_42_TRAIN.SCALES_[400,_500,_600,_700].txt.2016-07-30_19-41-43'</li>
<li>echo Logging output to 'experiments/logs/faster_rcnn_alt_opt_VGG_CNN_M_1024_--set_EXP_DIR_foobar_RNG_SEED_42_TRAIN.SCALES_[400,_500,_600,_700].txt.2016-07-30_19-41-43'
Logging output to experiments/logs/faster_rcnn_alt_opt_VGG_CNN_M_1024_--set_EXP_DIR_foobar_RNG_SEED_42_TRAIN.SCALES_[400,_500,_600,_700].txt.2016-07-30_19-41-43</li>
<li>./tools/train_faster_rcnn_alt_opt.py --gpu 0 --net_name VGG_CNN_M_1024 --weights data/imagenet_models/VGG_CNN_M_1024.v2.caffemodel --imdb voc_2007_trainval --cfg experiments/cfgs/faster_rcnn_alt_opt.yml --set EXP_DIR foobar RNG_SEED 42 TRAIN.SCALES '[400,' 500, 600, '700]'
Called with args:
Namespace(cfg_file='experiments/cfgs/faster_rcnn_alt_opt.yml', gpu_id=0, imdb_name='voc_2007_trainval', net_name='VGG_CNN_M_1024', pretrained_model='data/imagenet_models/VGG_CNN_M_1024.v2.caffemodel', set_cfgs=['EXP_DIR', 'foobar', 'RNG_SEED', '42', 'TRAIN.SCALES', '[400,', '500,', '600,', '700]'])
Traceback (most recent call last):
File "./tools/train_faster_rcnn_alt_opt.py", line 212, in
cfg_from_list(args.set_cfgs)
File "/home/jiaxin/py-faster-rcnn/tools/../lib/fast_rcnn/config.py", line 268, in cfg_from_list
assert len(cfg_list) % 2 == 0
AssertionError</li>
</ul>
<p>What should I do? Please help me! </p>
| 0 | 2016-07-29T03:20:49Z | 38,927,839 | <p>I just googled the solution for the second error. The credit comes from @faschinj <a href="https://github.com/rbgirshick/py-faster-rcnn/issues/132" rel="nofollow">https://github.com/rbgirshick/py-faster-rcnn/issues/132</a>. </p>
<p>Make sure there are no spaces after the commas otherwise they are parsed as separate arguments like so TRAIN.SCALES "[400,500,600,700]"</p>
| 0 | 2016-08-12T23:46:02Z | [
"python",
"github"
] |
web crawler in python (multiple website ) | 38,650,034 | <p>I used <code>requests</code> and <code>bs4</code>. In the circle, I found that it's only the last 'soup' is right when i get every 'soup'.the other 'soup' is different with HTML source. Please help me. Thanks.</p>
<pre><code>for eachLine in files:
addr = 'http://neuromorpho.org/neuron_info.jsp?neuron_name='+eachLine
print addr
st = []
st1 = []
r2 = requests.get(addr)
soup2 = bs4.BeautifulSoup(r2.text,"lxml")
print soup2
</code></pre>
| 1 | 2016-07-29T03:23:07Z | 38,650,130 | <p>The request object has content parameter which has all content of the site and you can parse it using BS4</p>
<pre><code>for eachLine in files:
addr = 'http://neuromorpho.org/neuron_info.jsp?neuron_name='+eachLine
r2 = requests.get(addr)
content = r2.content
soup2 = bs4.BeautifulSoup(content)
print soup2
</code></pre>
| 0 | 2016-07-29T03:37:06Z | [
"python",
"html",
"web-crawler"
] |
Google Trends "An error has been detected" | 38,650,126 | <p>I have the following code which I used a code sample from dominolab:</p>
<pre><code>from pytrends.pyGTrends import pyGTrends
import time
from random import randint
from IPython.display import display
from pprint import pprint
import urllib
import sys
import os
google_username = "myusername"
google_password = "mypassword"
path = "csv_files"
if not os.path.exists(path):
os.makedirs(path)
base_keyword = "/m/0k44x" #Image Processing
terms = [
"Image Processing",
"Signal Processing",
"Computer Vision",
"Machine Learning",
"Information Retrieval",
"Data Mining"
]
advanced_terms = [
"/m/07844",
"/m/0yk6",
"/m/05kx1v",
"/m/04zv0zl",
"/m/017chx",
"/m/0cqyr9",
"/m/0121sb",
"/m/07844",
"/m/06dq9"
]
# connect to Google Trends API
connector = pyGTrends(google_username, google_password)
for label, keyword in zip(terms, advanced_terms):
print(label)
sys.stdout.flush()
keyword_string = '"{0}, {1}"'.format(keyword, base_keyword)
connector.request_report(keyword_string, geo="US", date="01/2014 65m")
# wait a random amount of time between requests to avoid bot detection
time.sleep(randint(5, 10))
# download file
connector.save_csv(path, label)
for term in terms:
data = connector.get_suggestions(term)
pprint(data)
</code></pre>
<p>However, I see these in the saved CSV files:</p>
<pre><code><div id="report">
<div class="errorTitle">An error has been detected</div>
<div class="errorSubTitle">This page is currently unavailable. Please try again later.<br/> Please make sure your query is valid and try again.<br/> If you're experiencing long delays, consider reducing your comparison items.<br/> Thanks for your patience.</div>
</div>
</code></pre>
<p>What has gone wrong and how can this be fixed?
I get the data from Google Trend and here's <a href="http://pastebin.com/BggfgKHF" rel="nofollow">an example</a>.</p>
| 0 | 2016-07-29T03:36:38Z | 38,650,265 | <p>I think the problem is the date query, <code>date = "01/2014 65m"</code>, you're asking it for 65 months after January 2014 ... but that's in the future!</p>
<p>Hence this is the correct format for date:</p>
<pre><code>connector.request_report(keyword_string, geo="US", date="01/2014 5m")
</code></pre>
| 2 | 2016-07-29T03:55:43Z | [
"python",
"csv",
"ipython",
"jupyter",
"google-trends"
] |
Python how to implement code to GUI | 38,650,139 | <p>Im very new to making GUI in python and I have searched everywhere but cant find what im looking for. I simply want to have a program where the user inputs a radius and the program prints out the area of that radius in a label with the help of either a button click or enter. Thanks in advance :)</p>
<pre><code>import Tkinter, math
class calc_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
self.entryVariable = Tkinter.DoubleVar()
self.entry = Tkinter.Entry(self,textvariable=self.entryVariable)
self.entry.grid(column=0,row=0,sticky='EW')
self.entry.bind("<Return>", self.OnPressEnter)
self.entryVariable.set(u"Radius")
button = Tkinter.Button(self,text=u"Click to convert",command=self.OnButtonClick)
button.grid(column=1,row=0)
self.labelVariable = Tkinter.StringVar()
label = Tkinter.Label(self,textvariable=self.labelVariable,anchor="w",fg="white",bg="gray")
label.grid(column=0,row=1,columnspan=2,sticky='EW')
self.labelVariable.set(u"Please enter a radius.")
self.grid_columnconfigure(0,weight=1)
self.resizable(True,False)
self.update()
self.geometry(self.geometry())
self.entry.focus_set()
self.entry.selection_range(0, Tkinter.END)
def OnButtonClick(self):
self.labelVariable.set( self.convertVariable.get() )
self.entry.focus_set()
self.entry.selection_range(0, Tkinter.END)
def OnPressEnter(self,event):
self.converter()
self.labelVariable.set( self.convertVariable.get() )
self.entry.focus_set()
self.entry.selection_range(0, Tkinter.END)
def converter(self):
self.convertVariable(math.pi * self.entryVariable.get()**2)
if __name__ == "__main__":
app = calc_tk(None)
app.title('Radius Converter')
app.mainloop()
</code></pre>
| -1 | 2016-07-29T03:38:39Z | 38,650,560 | <p>I have modified your code little bit. Now code will display area on the label as you mentioned.Check the code.If I am wrong let me know.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import Tkinter, math
class calc_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
self.entryVariable = Tkinter.StringVar()
self.entry = Tkinter.Entry(self,textvariable=self.entryVariable)
self.entry.grid(column=0,row=0,sticky='EW')
self.entry.bind("<Return>", self.OnPressEnter)
self.entryVariable.set(u"Radius")
button = Tkinter.Button(self,text=u"Click to convert",command=self.OnButtonClick)
button.grid(column=1,row=0)
self.labelVariable = Tkinter.StringVar()
label = Tkinter.Label(self,textvariable=self.labelVariable,anchor="w",fg="white",bg="gray")
label.grid(column=0,row=1,columnspan=2,sticky='EW')
self.labelVariable.set(u"Please enter a radius.")
self.grid_columnconfigure(0,weight=1)
self.resizable(True,False)
self.update()
self.geometry(self.geometry())
self.entry.focus_set()
self.entry.selection_range(0, Tkinter.END)
def OnButtonClick(self):
self.labelVariable.set( str(self.converter())+" is the area." )
self.entry.focus_set()
self.entry.selection_range(0, Tkinter.END)
def OnPressEnter(self,event):
self.labelVariable.set( str(self.converter())+" is the area." )
self.entry.focus_set()
self.entry.selection_range(0, Tkinter.END)
def converter(self):
print self.entryVariable.get()
return (math.pi * (float(self.entryVariable.get()) * float(self.entryVariable.get())))
if __name__ == "__main__":
app = calc_tk(None)
app.title('Radius Converter')
app.mainloop()</code></pre>
</div>
</div>
</p>
| 1 | 2016-07-29T04:33:38Z | [
"python",
"python-2.7",
"user-interface",
"tkinter"
] |
Call a child variable in a mother class python | 38,650,235 | <p>I'm trying to access the "Table_Name variable" of the Child class to make the "Load_Data" method do different stuff depending on the child who cast the parent Class.<br>
Also, is there method to know the child who summoned the parent class? </p>
<pre><code>class DataBaseClass(obj):
..
def Load_Data():
if Table_Name?? == Child1.Table_Name:
load_Child1_Data
if Table_Name == Child2.Table_Name:
load_Child2_Data
..
class Child1(DataBaseClass):
..
Table_Name = TableName1
..
class Child2(DataBaseClass):
..
Table_Name = TableName2
..
import *
..
Child1.Load_Data()
Child2.Load_Data()
</code></pre>
| 0 | 2016-07-29T03:52:04Z | 38,650,426 | <p>Just implement the <code>load_data</code> on child classes. Something like this:</p>
<pre><code>class Child1(Base):
...
def load_data():
# CHILD1's OWN LOGIC
class Child2(Base):
...
def load_data():
# CHILD2's OWN LOGIC
</code></pre>
<hr>
<p>(Update as per your comment.)</p>
<p>If all of the child classes require different logic then you have to write that logic per child. However, if you only have some exceptions then you can override the method only for those. </p>
<p>But if there are only a couple of known possibilities, then you can define a class attribute and only change that attribute on child objects like so:</p>
<pre><code>class Base(obj):
custom_attribute = 'default_value'
def load_data(self):
if self.custom_attribute == SOMETHING:
pass
else:
pass
class Child1(Base):
custom_attribute = 'child1_value'
...
class Child2(Base):
custom_attribute = 'child2_value'
...
</code></pre>
| 0 | 2016-07-29T04:17:27Z | [
"python",
"class"
] |
Call a child variable in a mother class python | 38,650,235 | <p>I'm trying to access the "Table_Name variable" of the Child class to make the "Load_Data" method do different stuff depending on the child who cast the parent Class.<br>
Also, is there method to know the child who summoned the parent class? </p>
<pre><code>class DataBaseClass(obj):
..
def Load_Data():
if Table_Name?? == Child1.Table_Name:
load_Child1_Data
if Table_Name == Child2.Table_Name:
load_Child2_Data
..
class Child1(DataBaseClass):
..
Table_Name = TableName1
..
class Child2(DataBaseClass):
..
Table_Name = TableName2
..
import *
..
Child1.Load_Data()
Child2.Load_Data()
</code></pre>
| 0 | 2016-07-29T03:52:04Z | 38,650,446 | <p>The correct way to achieve this functionality is <a href="http://stackoverflow.com/questions/3724110/practical-example-of-polymorphism">polymorphism</a></p>
<p>You need to override the <code>Load_data</code> method in the child classes</p>
<pre><code>class DataBaseClass(object):
def Load_Data(self):
raise NotImplementedError("Subclass must implement abstract method")
class Child1(DataBaseClass):
def Load_Data(self):
# implement load_data for Child1
print('Child1')
class Child2(DataBaseClass):
def Load_Data(self):
# implement load_data for Child2
print('Child2')
Child1 = Child1()
Child2 = Child2()
Child1.Load_Data()
Child2.Load_Data()
</code></pre>
<p>Output</p>
<pre><code>Child1
Child2
</code></pre>
| 1 | 2016-07-29T04:20:02Z | [
"python",
"class"
] |
Call a child variable in a mother class python | 38,650,235 | <p>I'm trying to access the "Table_Name variable" of the Child class to make the "Load_Data" method do different stuff depending on the child who cast the parent Class.<br>
Also, is there method to know the child who summoned the parent class? </p>
<pre><code>class DataBaseClass(obj):
..
def Load_Data():
if Table_Name?? == Child1.Table_Name:
load_Child1_Data
if Table_Name == Child2.Table_Name:
load_Child2_Data
..
class Child1(DataBaseClass):
..
Table_Name = TableName1
..
class Child2(DataBaseClass):
..
Table_Name = TableName2
..
import *
..
Child1.Load_Data()
Child2.Load_Data()
</code></pre>
| 0 | 2016-07-29T03:52:04Z | 38,650,511 | <p>I think what you are trying to do is something like this:</p>
<pre><code>class BaseClass(object):
@classmethod
def load_data(cls):
try:
return some_external_load_function(cls.DATA_FILE_NAME)
except AttributeError:
raise NotImplementedError(
'It seems you forgot to define the DATA_FILE_NAME attribute '
'on you child class.')
class Child1(BaseClass):
DATA_FILE_NAME = 'my_one_data_file.data'
class Child2(BaseClass):
DATA_FILE_NAME = 'my_other_data_file.data'
</code></pre>
<p>This pattern is completely acceptable in some cases but it is very hard to judge from your pseudo code example if what you are trying to do is one of those cases.</p>
| 1 | 2016-07-29T04:27:38Z | [
"python",
"class"
] |
How to Compare Values of two Dataframes in Pandas? | 38,650,273 | <p>I have two dataframes <code>df</code> and <code>df2</code> like this</p>
<pre><code> id initials
0 100 J
1 200 S
2 300 Y
name initials
0 John J
1 Smith S
2 Nathan N
</code></pre>
<p>I want to compare the values in the <code>initials</code> columns found in (<code>df</code> and <code>df2</code>) and copy the name (in <code>df2</code>) which its initial is matching to the initial in the first dataframe (<code>df</code>)</p>
<pre><code>import pandas as pd
for i in df.initials:
for j in df2.initials:
if i == j:
# copy the name value of this particular initial to df
</code></pre>
<p>The output should be like this:</p>
<pre><code> id name
0 100 Johon
1 200 Smith
2 300
</code></pre>
<p>Any idea how to solve this problem?</p>
| 1 | 2016-07-29T03:56:12Z | 38,650,318 | <p>How about?:</p>
<pre><code>df3 = df.merge(df2,on='initials',
how='outer').drop(['initials'],axis=1).dropna(subset=['id'])
>>> df3
id name
0 100.0 John
1 200.0 Smith
2 300.0 NaN
</code></pre>
<p>So the 'initials' column is dropped and so is anything with <code>np.nan</code> in the 'id' column.</p>
<p>If you don't want the <code>np.nan</code> in there tack on a <code>.fillna()</code>:</p>
<pre><code>df3 = df.merge(df2,on='initials',
how='outer').drop(['initials'],axis=1).dropna(subset=['id']).fillna('')
>>> df3
id name
0 100.0 John
1 200.0 Smith
2 300.0
</code></pre>
| 1 | 2016-07-29T04:01:46Z | [
"python",
"pandas",
"dictionary",
"dataframe"
] |
How to Compare Values of two Dataframes in Pandas? | 38,650,273 | <p>I have two dataframes <code>df</code> and <code>df2</code> like this</p>
<pre><code> id initials
0 100 J
1 200 S
2 300 Y
name initials
0 John J
1 Smith S
2 Nathan N
</code></pre>
<p>I want to compare the values in the <code>initials</code> columns found in (<code>df</code> and <code>df2</code>) and copy the name (in <code>df2</code>) which its initial is matching to the initial in the first dataframe (<code>df</code>)</p>
<pre><code>import pandas as pd
for i in df.initials:
for j in df2.initials:
if i == j:
# copy the name value of this particular initial to df
</code></pre>
<p>The output should be like this:</p>
<pre><code> id name
0 100 Johon
1 200 Smith
2 300
</code></pre>
<p>Any idea how to solve this problem?</p>
| 1 | 2016-07-29T03:56:12Z | 38,654,434 | <pre><code>df1
id initials
0 100 J
1 200 S
2 300 Y
df2
name initials
0 John J
1 Smith S
2 Nathan N
</code></pre>
<p>Use Boolean masks: <code>df2.initials==df1.initials</code> will tell you which values in the two <code>initials</code> columns are the same. </p>
<pre><code>0 True
1 True
2 False
</code></pre>
<p>Use this mask to create a new column:</p>
<pre><code>df1['name'] = df2.name[df2.initials==df1.initials]
</code></pre>
<p>Remove the <code>initials</code> column in <code>df1</code>:</p>
<pre><code>df1.drop('initials', axis=1)
</code></pre>
<p>Replace the <code>NaN</code> using <code>fillna(' ')</code></p>
<pre><code>df1.fillna('', inplace=True) #inplace to avoid creating a copy
id name
0 100 John
1 200 Smith
2 300
</code></pre>
| 1 | 2016-07-29T08:48:28Z | [
"python",
"pandas",
"dictionary",
"dataframe"
] |
Django: How to use FilePathField to get file size | 38,650,340 | <p>I work in a postproduction company, we have our media files on a server. Through the site running on a second server, the user would point to a file, perform some operations (calculating checksums for example) and save the results in the database.</p>
<p>I'm looking for a "best practices" example on how to use FilePathField to get the size of a file. I've read tutorials and searched in the docs, but I'm having trouble putting the pieces together for my needs.</p>
<p>Some relevant code (<strong>EDIT:</strong> corrected the views, #1 and #3 are printed):</p>
<p>models.py</p>
<pre><code> class AssetTest(models.Model):
file_path = models.FilePathField(path=r"", default="")
file_name = models.CharField(max_length=250, default="")
file_size = models.IntegerField(default=0)
def __str__(self):
return self.file_path
</code></pre>
<p>forms.py</p>
<pre><code>class AssetTestForm(forms.ModelForm):
class Meta:
model = AssetTest
fields = ("file_name", "file_size")
</code></pre>
<p>views.py</p>
<pre><code>def asset_select(request):
if request.method == 'POST':
print("1")
form = AssetTestForm(request.POST)
if form.is_valid():
print("2")
form.save(commit=False)
form.file_name = request.FILES['file'].name
form.file_size = request.FILES['file'].size
form.save()
return HttpResponseRedirect('/assetmanage/assets/')
print("3")
else:
print("4")
form = AssetTestForm()
return render(request, 'assetmanage/asset_select.html', {'form': form})
</code></pre>
<p>asset_select.html</p>
<pre><code>{% extends "assetmanage/base.html" %}
{% block title %}Add Asset{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-7">
<div class="panel panel-default">
<div class="panel-body">
<form class="form-horizontal" name="asset_select" action="/assetmanage/asset/test/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label class="control-label col-sm-2">Select a file:</label>
<input type="file" name="asset_file">
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
</code></pre>
| 1 | 2016-07-29T04:04:12Z | 38,650,487 | <p>In your FilePathField give the correct path name </p>
<pre><code>FilePathField(path="/home/simon/",..)
</code></pre>
<p><code>cleaned_data</code> of <code>FilePathField</code> will give you the exact path so using that to get the file name and file size of it... </p>
<pre><code>form = AssetTestForm(request.POST)
if form.is_valid():
form.save(commit=False)
temp_file_obj = TemporaryFileUploadHandler(form.cleaned_data['file_path'])
form.instance.file_size = temp_file_obj.chunk_size
form.instance.file_name = form.cleaned_data['file_path'].split("/")[-1]
form.save()
</code></pre>
| 1 | 2016-07-29T04:25:10Z | [
"python",
"django"
] |
How to rename a bunch of files using python? | 38,650,533 | <p>I am a complete beginner in python. I need to rename a bunch of files with dates in the name. The names all look like:</p>
<ul>
<li><code>front 7.25.16</code></li>
<li><code>left 7.25.16</code></li>
<li><code>right 7.25.16</code></li>
</ul>
<p>I would like them to start with the date rather then <em>front</em>, <em>left</em>, or <em>right</em>, so that <code>front 7.25.16</code> becomes <code>7.25.16 front</code>.</p>
<p>I have tried using <em>regular expressions</em> and <em>os.walk</em> and I have run into troubles with both. Right now I am just trying to print the file names to prove <em>os.walk</em> is working. Right now my code looks like this:</p>
<pre class="lang-python prettyprint-override"><code>import re, shutil, os
K = re.compile(r"(\d+.\d+.\d+)")
RE_Date = K.search("front 7.25.16")
for root, dirs, filenames in os.walk("path"):
for filename in filenames:
print ("the filename is: " + filename)
print ("")
</code></pre>
<p>Any advice would be greatly appreciated.</p>
| 2 | 2016-07-29T04:30:01Z | 38,650,794 | <p>Check this example to rename file as per your need.</p>
<pre><code>import os
filenames = ["front 7.25.16.jpg", "left 7.25.16.jpg", "right 7.25.16.jpg"]
for file_name in filenames:
x = file_name.split(' ')[0]
y = file_name.split(' ')[1]
new_name = '{} {}{}'.format(os.path.splitext(y)[0], x, os.path.splitext(y)[-1])
print new_name
</code></pre>
<p>output:</p>
<pre><code>7.25.16 front.jpg
7.25.16 left.jpg
7.25.16 right.jpg
</code></pre>
<p>In your code your can use <a href="https://docs.python.org/2/library/os.html" rel="nofollow">os.rename</a> for rename files</p>
<pre><code>import os
for root, dirs, filenames in os.walk("path"):
for file_name in filenames:
x = file_name.split(' ')[0]
y = file_name.split(' ')[1]
new_name = '{} {}{}'.format(os.path.splitext(y)[0], x, os.path.splitext(y)[-1])
file_path = os.path.join(root, file_name)
new_path = os.path.join(root, new_name)
os.rename(file_name, new_path)
</code></pre>
| 1 | 2016-07-29T04:59:28Z | [
"python"
] |
Media List in Python VLC | 38,650,544 | <p>I need to write a program in Python that will play video files from a folder in the VLC player, using the Linux OS. These files must be in the playlist. Code:</p>
<pre><code>import vlc
mrl1 = '....1.3gp'
mrl2 = '....2.3gp'
Instance = vlc.Instance('--input-repeat=-1', '--fullscreen', '--mouse-hide-timeout=0')
MediaList = Instance.media_list_new()
MediaList.add_media(Instance.media_new(mrl2))
MediaList.add_media(Instance.media_new(mrl1))
list_player = Instance.media_list_player_new()
list_player.set_media_list(MediaList)
list_player.next()
player.play()
</code></pre>
<p>The problem is that after running the first video, the player closes. I think that it does not add the second video to the list.</p>
<ol>
<li>How to add a video to a playlist in Python's binding for LibVLC?</li>
<li>Is there a utility function that plays all the videos in a folder?
UPD: I've created a playlist, and ran it to test in VLC player. Playing only the first video. After VLC is also closed. What is rhe problem?</li>
</ol>
| 0 | 2016-07-29T04:31:13Z | 38,651,007 | <p>Use while/for loop which will iterate through media list one by one. May be in this case pointer is pointing to only first video.</p>
<p>Edit 1:</p>
<p>[Use of For Loop] (<a href="http://stackoverflow.com/questions/28440708/python-vlc-binding-playing-a-playlist">Python VLC binding- playing a playlist</a>) Refer answer section of this question. For loop is used to iterate through url's (which is media list in this case). </p>
| 0 | 2016-07-29T05:21:04Z | [
"python",
"vlc",
"libvlc"
] |
Media List in Python VLC | 38,650,544 | <p>I need to write a program in Python that will play video files from a folder in the VLC player, using the Linux OS. These files must be in the playlist. Code:</p>
<pre><code>import vlc
mrl1 = '....1.3gp'
mrl2 = '....2.3gp'
Instance = vlc.Instance('--input-repeat=-1', '--fullscreen', '--mouse-hide-timeout=0')
MediaList = Instance.media_list_new()
MediaList.add_media(Instance.media_new(mrl2))
MediaList.add_media(Instance.media_new(mrl1))
list_player = Instance.media_list_player_new()
list_player.set_media_list(MediaList)
list_player.next()
player.play()
</code></pre>
<p>The problem is that after running the first video, the player closes. I think that it does not add the second video to the list.</p>
<ol>
<li>How to add a video to a playlist in Python's binding for LibVLC?</li>
<li>Is there a utility function that plays all the videos in a folder?
UPD: I've created a playlist, and ran it to test in VLC player. Playing only the first video. After VLC is also closed. What is rhe problem?</li>
</ol>
| 0 | 2016-07-29T04:31:13Z | 38,654,205 | <p>You should to put it into a loop, which waits for each song to finish playing. For example, try this code</p>
<pre><code>import vlc
import time
mrl1 = '....1.3gp'
mrl2 = '....2.3gp'
song_list=[mrl1,mrl2]
Instance = vlc.Instance('--input-repeat=-1', '--fullscreen', '--mouse-hide-timeout=0')
for song in song_list:
player=instance.media_player_new()
media=instance.media_new(song)
media.get_mrl()
player.set_media(media)
player.play()
playing = set([1,2,3,4])
time.sleep(1)
duration = player.get_length() / 1000
mm, ss = divmod(duration, 60)
while True:
state = player.get_state()
if state not in playing:
break
continue
</code></pre>
| 0 | 2016-07-29T08:36:01Z | [
"python",
"vlc",
"libvlc"
] |
Can't get y-axis on Matplotlib histogram to display probabilities | 38,650,550 | <p>I have data (pd Series) that looks like (daily stock returns, n = 555):</p>
<pre><code>S = perf_manual.returns
S = S[~((S-S.mean()).abs()>3*S.std())]
2014-03-31 20:00:00 0.000000
2014-04-01 20:00:00 0.000000
2014-04-03 20:00:00 -0.001950
2014-04-04 20:00:00 -0.000538
2014-04-07 20:00:00 0.000764
2014-04-08 20:00:00 0.000803
2014-04-09 20:00:00 0.001961
2014-04-10 20:00:00 0.040530
2014-04-11 20:00:00 -0.032319
2014-04-14 20:00:00 -0.008512
2014-04-15 20:00:00 -0.034109
...
</code></pre>
<p>I'd like to generate a probability distribution plot from this. Using:</p>
<pre><code>print stats.normaltest(S)
n, bins, patches = plt.hist(S, 100, normed=1, facecolor='blue', alpha=0.75)
print np.sum(n * np.diff(bins))
(mu, sigma) = stats.norm.fit(S)
print mu, sigma
y = mlab.normpdf(bins, mu, sigma)
plt.grid(True)
l = plt.plot(bins, y, 'r', linewidth=2)
plt.xlim(-0.05,0.05)
plt.show()
</code></pre>
<p>I get the following: </p>
<pre><code>NormaltestResult(statistic=66.587382579416982, pvalue=3.473230376732532e-15)
1.0
0.000495624926242 0.0118790391467
</code></pre>
<p><a href="http://i.stack.imgur.com/octCY.png" rel="nofollow"><img src="http://i.stack.imgur.com/octCY.png" alt="graph"></a></p>
<p><strong>I have the impression the y-axis is a count, but I'd like to have probabilities instead. How do I do that?</strong> I've tried a whole lot of StackOverflow answers and can't figure this out. </p>
| 1 | 2016-07-29T04:31:41Z | 38,657,671 | <p>There is no easy way (that I know of) to do that using <code>plt.hist</code>. But you can simply bin the data using <code>np.histogram</code> and then normalize the data any way you want. If I understood you correctly, you want the data to display the probability to find a point in a given bin, NOT the probability distribution. That means you have to scale your data that the sum over all bins is 1. That can simply be done by doing <code>bin_probability = n/float(n.sum())</code>.</p>
<p>You will then not have a properly normalized probability distribution function (pdf) anymore, meaning that the integral over an interval will not be a probability! That is the reason, why you have to rescale your <code>mlab.normpdf</code> to have the same norm as your histogram. The factor needed is just the bin width, because when you start from the properly normalized binned pdf the sum over all bins times their respective width is 1. Now you want to have just the sum of bins equal to 1. So the scaling factor is the bin width.</p>
<p>Therefore, the code you end up with is something along the lines of:</p>
<pre><code>import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
# Produce test data
S = np.random.normal(0, 0.01, size=1000)
# Histogram:
# Bin it
n, bin_edges = np.histogram(S, 100)
# Normalize it, so that every bins value gives the probability of that bin
bin_probability = n/float(n.sum())
# Get the mid points of every bin
bin_middles = (bin_edges[1:]+bin_edges[:-1])/2.
# Compute the bin-width
bin_width = bin_edges[1]-bin_edges[0]
# Plot the histogram as a bar plot
plt.bar(bin_middles, bin_probability, width=bin_width)
# Fit to normal distribution
(mu, sigma) = stats.norm.fit(S)
# The pdf should not normed anymore but scaled the same way as the data
y = mlab.normpdf(bin_middles, mu, sigma)*bin_width
l = plt.plot(bin_middles, y, 'r', linewidth=2)
plt.grid(True)
plt.xlim(-0.05,0.05)
plt.show()
</code></pre>
<p>And the resulting picture will be:</p>
<p><a href="http://i.stack.imgur.com/hMlZc.png" rel="nofollow"><img src="http://i.stack.imgur.com/hMlZc.png" alt="enter image description here"></a></p>
| 1 | 2016-07-29T11:26:51Z | [
"python",
"matplotlib",
"histogram",
"probability-density"
] |
lambda,map on object arrays in python - Return List of objects | 38,650,558 | <p>How to return a list of objects and not list here.
I want to return a list of test objects and not a list of str..</p>
<pre><code>class test:
val = ""
def __init__(self,v):
self.val = v
def tolower(self,k):
k = k.val.lower()
return k
def test_run():
tests_lst = []
tests_lst.append(test("TEST-0"))
tests_lst.append(test("TEST-1"))
tests_lst.append(test("TEST-2"))
i_want_object_of_test = map(lambda x:x.val.lower(),tests_lst)
if __name__ == '__main__':
test_run()
</code></pre>
<p>OUTPUT:
['test-0', 'test-1', 'test-2']</p>
<p>i want a list of test objects where each object's val has changed to lower case.</p>
| 0 | 2016-07-29T04:33:20Z | 38,651,037 | <p>The question is unclear. I'll answer by what I understand.</p>
<p>What I understand is that you are trying to create a new list of test objects, with the values as lower case.</p>
<p>You can do this either by changing the state of each of the objects in a for loop (changing state is usually not recommended):</p>
<pre><code>for test_obj in test_lst:
test_obj.val = test_obj.val.lower()
</code></pre>
<p>A way to do it through a list comprehension is to create new test instances:</p>
<pre><code>i_want_object_of_test = [test(test_obj.val.lower()) for test_obj in test_lst]
</code></pre>
<p>Besides, there are a few problems with your test class:</p>
<ul>
<li>It is an old style class, you should always inherit from object in your classes: <code>class test(object):</code></li>
<li>You define a class variable by putting <code>val = ""'</code> in your class defenition, you then override it in each instance.</li>
<li>Your tolower method gets another test instance (k) and returns its value as lower case. I assume you want to either return a new test object or change the current one in place. Either way the method should only use <code>self</code>.</li>
</ul>
| 0 | 2016-07-29T05:23:24Z | [
"python",
"python-2.7"
] |
passing the output of one .py script to another in GDB | 38,650,566 | <p>How to pass the output of one .py script which I executed in GDB using below command:</p>
<pre><code>(gdb)source myfilename.py
</code></pre>
<p>to another .py script myfilename2.py</p>
<p>E.g: On running myfile myfilename.py in GDB I get the below results</p>
<pre><code>(gdb)source myfilename.py
(gdb)print $function("input")
(gdb)$1 = someoutput`
</code></pre>
<p>If I want to pass $1 as input to another .py script how do I do it.</p>
<p>Thanks for the help.</p>
| 2 | 2016-07-29T04:34:11Z | 38,708,157 | <p>You cannot use contents of GDB variable $1 for your program input, since program launch is performed by shell, not by gdb. </p>
<p>You can store your script output in file, launch gdb for your executable and use command</p>
<pre><code>(gdb)run <outputfile
</code></pre>
<p>Or use a named pipe, as suggested <a href="https://stackoverflow.com/questions/1456253/gdb-debugging-with-pipe">in this answer</a>.</p>
| 0 | 2016-08-01T21:08:42Z | [
"python",
"gdb"
] |
passing the output of one .py script to another in GDB | 38,650,566 | <p>How to pass the output of one .py script which I executed in GDB using below command:</p>
<pre><code>(gdb)source myfilename.py
</code></pre>
<p>to another .py script myfilename2.py</p>
<p>E.g: On running myfile myfilename.py in GDB I get the below results</p>
<pre><code>(gdb)source myfilename.py
(gdb)print $function("input")
(gdb)$1 = someoutput`
</code></pre>
<p>If I want to pass $1 as input to another .py script how do I do it.</p>
<p>Thanks for the help.</p>
| 2 | 2016-07-29T04:34:11Z | 38,722,335 | <p>I'm not sure if you can run other python programs output to another in gdb, but of course you can pass output of a command like this.</p>
<pre><code> (gdb) run "`python -c 'print "\xff\xff\xff\xff"'`"
</code></pre>
<p>May be you can try passing the second .py file instead of the command for its output to be passed into first .py.</p>
| 2 | 2016-08-02T13:49:05Z | [
"python",
"gdb"
] |
django rest framework add user and create data in db | 38,650,611 | <p>every one,I now using django rest framework(3.4) on my project(django 1.8+),I can create new user but I can not use new user to create data in db(I can do it in forms ok), however,I can create data in db by admin. I have to make the new user to create data in db,how can I do that?thanks for any one who reply. </p>
<blockquote>
<p>models.py</p>
</blockquote>
<pre><code>class ProductsTbl(models.Model):
model_number = models.CharField(
max_length=255,
blank=True,
unique=True,
error_messages={
'unique': "é model number å·²ç¶è¢«è¨»åäº ."
}
)
name = models.CharField(max_length=255, blank=True, null=True)
material = models.CharField(max_length=255, blank=True, null=True)
color = models.CharField(max_length=255, blank=True, null=True)
feature = models.TextField(blank=True, null=True)
created = models.DateTimeField(editable=False)
modified = models.DateTimeField(auto_now=True)
release = models.DateTimeField(blank=True, null=True)
twtime = models.DateTimeField(blank=True, null=True)
hktime = models.DateTimeField(blank=True, null=True)
shtime = models.DateTimeField(blank=True, null=True)
jptime = models.DateTimeField(blank=True, null=True)
suggest = models.TextField(blank=True, null=True)
description = models.TextField(blank=True, null=True)
cataloggroup = models.ManyToManyField(CatalogGroup)
place = models.ManyToManyField(Place)
scale = models.ManyToManyField(Scale)
slug = models.SlugField(unique=True)
user = models.ForeignKey(User, blank=True, null=True)
useredit = models.CharField(max_length=32, blank=True, null=True)
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created = timezone.now()
return super(ProductsTbl, self).save(*args, **kwargs)
</code></pre>
<blockquote>
<p>api/serializers.py</p>
</blockquote>
<pre><code>from rest_framework import serializers
from ..models import *
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
UserModel = get_user_model()
class ProductsTblSerializer(serializers.ModelSerializer):
class Meta:
model = ProductsTbl
fields = ('model_number',
'created',
'name',
'release',
'twtime',
'hktime',
'shtime',
'jptime',
'feature',
'material',
'suggest',
'description',
'cataloggroup',
'place',
'scale',
'slug',
'user')
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
def create(self, validated_data):
user = UserModel.objects.create(
username=validated_data['username']
)
user.set_password(validated_data['password'])
user.save()
return user
class Meta:
model = UserModel
</code></pre>
<blockquote>
<p>api/urls.py</p>
</blockquote>
<pre><code>from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^productsTbls/$', views.ProductsTblListView.as_view(), name='productsTbls_list'),
url(r'^productsTbls/(?P<pk>\d+)/$', views.ProductsTblDetailView.as_view(), name='productsTbls_detail'),
url(r'^productsTbls/pdelete/(?P<id>[-\w]+)/$',views.api_delete_product,name='api_delete_p'),
url(r'^productsTbls/register/$', views.CreateUserView.as_view(), name='productsTbls_register'),
]
</code></pre>
<blockquote>
<p>api/views.py</p>
</blockquote>
<pre><code>from rest_framework import generics
from ..models import *
from .serializers import ProductsTblSerializer
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponse
from django.shortcuts import render, redirect
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from django.views.decorators.csrf import csrf_exempt
from django.forms import modelformset_factory
from django.template.defaultfilters import slugify
from rest_framework import permissions
from rest_framework.generics import CreateAPIView
from django.contrib.auth import get_user_model
from .serializers import UserSerializer
class ProductsTblListView(generics.ListCreateAPIView):
queryset = ProductsTbl.objects.order_by('-created')
serializer_class = ProductsTblSerializer
class ProductsTblDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = ProductsTbl.objects.all()
serializer_class = ProductsTblSerializer
class CreateUserView(CreateAPIView):
model = get_user_model()
permission_classes = [
permissions.AllowAny # Or anon users can't register
]
serializer_class = UserSerializer
@csrf_exempt
@login_required
def api_delete_product(request, id):
# grab the image
dp = ProductsTbl.objects.get(id=id)
# security check
if dp.user != request.user:
raise Http404
# delete the image
dp.delete()
# refresh the edit page
return redirect('/api/productsTbls/')
</code></pre>
<blockquote>
<p>settings.py</p>
</blockquote>
<pre><code>........
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
</code></pre>
| 0 | 2016-07-29T04:39:28Z | 38,652,489 | <p>I changed the <code>settings.py</code> then it can work</p>
<blockquote>
<p>settings.py</p>
</blockquote>
<pre><code>......
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
#'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
</code></pre>
| 1 | 2016-07-29T07:04:22Z | [
"python",
"django",
"django-rest-framework"
] |
django rest framework add user and create data in db | 38,650,611 | <p>every one,I now using django rest framework(3.4) on my project(django 1.8+),I can create new user but I can not use new user to create data in db(I can do it in forms ok), however,I can create data in db by admin. I have to make the new user to create data in db,how can I do that?thanks for any one who reply. </p>
<blockquote>
<p>models.py</p>
</blockquote>
<pre><code>class ProductsTbl(models.Model):
model_number = models.CharField(
max_length=255,
blank=True,
unique=True,
error_messages={
'unique': "é model number å·²ç¶è¢«è¨»åäº ."
}
)
name = models.CharField(max_length=255, blank=True, null=True)
material = models.CharField(max_length=255, blank=True, null=True)
color = models.CharField(max_length=255, blank=True, null=True)
feature = models.TextField(blank=True, null=True)
created = models.DateTimeField(editable=False)
modified = models.DateTimeField(auto_now=True)
release = models.DateTimeField(blank=True, null=True)
twtime = models.DateTimeField(blank=True, null=True)
hktime = models.DateTimeField(blank=True, null=True)
shtime = models.DateTimeField(blank=True, null=True)
jptime = models.DateTimeField(blank=True, null=True)
suggest = models.TextField(blank=True, null=True)
description = models.TextField(blank=True, null=True)
cataloggroup = models.ManyToManyField(CatalogGroup)
place = models.ManyToManyField(Place)
scale = models.ManyToManyField(Scale)
slug = models.SlugField(unique=True)
user = models.ForeignKey(User, blank=True, null=True)
useredit = models.CharField(max_length=32, blank=True, null=True)
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created = timezone.now()
return super(ProductsTbl, self).save(*args, **kwargs)
</code></pre>
<blockquote>
<p>api/serializers.py</p>
</blockquote>
<pre><code>from rest_framework import serializers
from ..models import *
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
UserModel = get_user_model()
class ProductsTblSerializer(serializers.ModelSerializer):
class Meta:
model = ProductsTbl
fields = ('model_number',
'created',
'name',
'release',
'twtime',
'hktime',
'shtime',
'jptime',
'feature',
'material',
'suggest',
'description',
'cataloggroup',
'place',
'scale',
'slug',
'user')
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
def create(self, validated_data):
user = UserModel.objects.create(
username=validated_data['username']
)
user.set_password(validated_data['password'])
user.save()
return user
class Meta:
model = UserModel
</code></pre>
<blockquote>
<p>api/urls.py</p>
</blockquote>
<pre><code>from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^productsTbls/$', views.ProductsTblListView.as_view(), name='productsTbls_list'),
url(r'^productsTbls/(?P<pk>\d+)/$', views.ProductsTblDetailView.as_view(), name='productsTbls_detail'),
url(r'^productsTbls/pdelete/(?P<id>[-\w]+)/$',views.api_delete_product,name='api_delete_p'),
url(r'^productsTbls/register/$', views.CreateUserView.as_view(), name='productsTbls_register'),
]
</code></pre>
<blockquote>
<p>api/views.py</p>
</blockquote>
<pre><code>from rest_framework import generics
from ..models import *
from .serializers import ProductsTblSerializer
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponse
from django.shortcuts import render, redirect
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from django.views.decorators.csrf import csrf_exempt
from django.forms import modelformset_factory
from django.template.defaultfilters import slugify
from rest_framework import permissions
from rest_framework.generics import CreateAPIView
from django.contrib.auth import get_user_model
from .serializers import UserSerializer
class ProductsTblListView(generics.ListCreateAPIView):
queryset = ProductsTbl.objects.order_by('-created')
serializer_class = ProductsTblSerializer
class ProductsTblDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = ProductsTbl.objects.all()
serializer_class = ProductsTblSerializer
class CreateUserView(CreateAPIView):
model = get_user_model()
permission_classes = [
permissions.AllowAny # Or anon users can't register
]
serializer_class = UserSerializer
@csrf_exempt
@login_required
def api_delete_product(request, id):
# grab the image
dp = ProductsTbl.objects.get(id=id)
# security check
if dp.user != request.user:
raise Http404
# delete the image
dp.delete()
# refresh the edit page
return redirect('/api/productsTbls/')
</code></pre>
<blockquote>
<p>settings.py</p>
</blockquote>
<pre><code>........
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
</code></pre>
| 0 | 2016-07-29T04:39:28Z | 38,656,076 | <p>I think from admin portal you need to provide permissions to user you have created for each method PUT,POST,GET or provide AllowAny permission(Which will give access to all your created user for any request). For more details refer <a href="http://www.django-rest-framework.org/api-guide/permissions/" rel="nofollow">this</a> </p>
| 1 | 2016-07-29T10:06:46Z | [
"python",
"django",
"django-rest-framework"
] |
sending dynamic html email containing javascript via a python script | 38,650,665 | <ol>
<li>at the first place, I could not help myself with the correct search terms on this.</li>
<li>secondly, I couldnt pretty much make it working with standard smtplib or email package in python.</li>
</ol>
<p>The question is, I have a normal html page(basically it contains a that is generated from bokeh package in python, and all it does is generating an html page the javascript within renders a nice zoomable plot when viewed in a browser.</p>
<p>My aim is to send that report (the html basically) over to recipients in a mail. </p>
| 0 | 2016-07-29T04:43:51Z | 38,650,801 | <p>Sorry, but you'll not be able to send an email with JavaScript embedded. That is a security risk. If you're lucky, an email provider will strip it before rendering, if you're unlucky, you'll be sent directly to spam and the provider will distrust your domain.</p>
<p>You're better off sending an email with a link to the chart.</p>
| 1 | 2016-07-29T05:00:15Z | [
"javascript",
"python",
"email",
"bokeh",
"smtplib"
] |
I want to append 4 text variables into a variable called job and print the text of job variable | 38,650,679 | <p>I am currently scraping Linkedin Job directory using selenium in python shell</p>
<p>from selenium import webdriver</p>
<p>from selenium.webdriver.common.keys import Keys</p>
<p>driver = webdriver.Firefox()</p>
<pre><code>driver.get('https://www.linkedin.com/jobs/search?
locationId=sg%3A0&f_TP=1%2C2&orig=FCTD&trk=jobs_jserp_posted_one_week')
a = driver.find_elements_by_class_name('job-title-text')
b = driver.find_elements_by_class_name('company-name-text')
c = driver.find_elements_by_class_name('job-location')
d = driver.find_elements_by_class_name('job-description')
#There are 50 pages of jobs therefore I specified a range of 55
for e in range(55):
for g in a:
print(g.text)
for h in b:
print(h.text)
for i in c:
print(i.text)
for j in d:
print(j.text)
k = driver.find_element_by_class_name('next-btn')
k.click()
Job = []
Job.append(a)
Job.append(b)
Job.append(c)
Job.append(d)
for l in Job:
print(l.text)
</code></pre>
<p>This code is not working and I have been struggling and tried various methods of solving this issue. It will be great if I can get the correct solution. </p>
| 1 | 2016-07-29T04:45:26Z | 38,652,931 | <pre><code>for e in range(55):
for g in a:
print(g.text)
job.append(g)
for h in b:
print(h.text)
job.append(h)
for i in c:
print(i.text)
job.append(i)
for j in d:
print(j.text)
job.append(j)
</code></pre>
<p>Maybe you should get job list like this.</p>
| 0 | 2016-07-29T07:27:47Z | [
"python",
"selenium"
] |
I want to append 4 text variables into a variable called job and print the text of job variable | 38,650,679 | <p>I am currently scraping Linkedin Job directory using selenium in python shell</p>
<p>from selenium import webdriver</p>
<p>from selenium.webdriver.common.keys import Keys</p>
<p>driver = webdriver.Firefox()</p>
<pre><code>driver.get('https://www.linkedin.com/jobs/search?
locationId=sg%3A0&f_TP=1%2C2&orig=FCTD&trk=jobs_jserp_posted_one_week')
a = driver.find_elements_by_class_name('job-title-text')
b = driver.find_elements_by_class_name('company-name-text')
c = driver.find_elements_by_class_name('job-location')
d = driver.find_elements_by_class_name('job-description')
#There are 50 pages of jobs therefore I specified a range of 55
for e in range(55):
for g in a:
print(g.text)
for h in b:
print(h.text)
for i in c:
print(i.text)
for j in d:
print(j.text)
k = driver.find_element_by_class_name('next-btn')
k.click()
Job = []
Job.append(a)
Job.append(b)
Job.append(c)
Job.append(d)
for l in Job:
print(l.text)
</code></pre>
<p>This code is not working and I have been struggling and tried various methods of solving this issue. It will be great if I can get the correct solution. </p>
| 1 | 2016-07-29T04:45:26Z | 40,101,749 | <p>i am not really understand your question. maybe u can get some ideas from enumerate(list)</p>
<p>for example:</p>
<pre><code>word_list=['go','have', 'fun', 'good']
name_list=['1.txt','2.txt','3.txt','4.txt']
for i, word in enumerate(word_list):
print i ### it is the position of each element
print word ### it is the each element of word_list
print name_list[i] ### it is the each element of name_list
</code></pre>
<h3>for further, u may modify the lists such as join the lists, append....</h3>
| 0 | 2016-10-18T07:09:16Z | [
"python",
"selenium"
] |
Is it better to derive from Gtk.Widget or directly from a specific widget? | 38,650,893 | <p>When I create a UI class for my app, I often wonder if it's better to derive my class from <code>Gtk.Widget</code> and then add explicitly the widgets I need or to derive directly from a specific widget.</p>
<p>Here is two examples, which one is the best?</p>
<pre class="lang-py prettyprint-override"><code>class MyComponent(Gtk.Widget):
def __init__(self):
Gtk.Widget.__init__(self)
box = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 6)
button1 = Gtk.Button.new_with_label("Awesome Button1")
button2 = Gtk.Button.new_with_label("Awesome Button2")
button3 = Gtk.Button.new_with_label("Awesome Button3")
box.pack_start(button1, True, True, 0)
box.pack_start(button2, True, True, 0)
box.pack_start(button3, True, True, 0)
self.add(box)
</code></pre>
<pre class="lang-py prettyprint-override"><code>class MyComponent(Gtk.Box):
def __init__(self):
Gtk.Box.__init__(self, Gtk.Orientation.HORIZONTAL, 6)
button1 = Gtk.Button.new_with_label("Awesome Button1")
button2 = Gtk.Button.new_with_label("Awesome Button2")
button3 = Gtk.Button.new_with_label("Awesome Button3")
self.pack_start(button1, True, True, 0)
self.pack_start(button2, True, True, 0)
self.pack_start(button3, True, True, 0)
</code></pre>
<p>It seems to me that the first version is better since my component isn't technically a <code>Gtk.Box</code>, it's a widget that is using a <code>Gtk.Box</code>, but it could as well use a <code>Gtk.Grid</code> or a <code>Gtk.DrawingArea</code>.</p>
<p>So it seems right on a design stand point, but maybe there's some technicalities that I don't see. What's your advice?</p>
| 1 | 2016-07-29T05:08:11Z | 38,678,401 | <p>I fail to see why you think the first is better. Just Subclass what you actually want. A Gtk.Box <em>is</em> a Gtk.Widget so wherever you can use the latter you can use the former.</p>
| 0 | 2016-07-30T20:53:43Z | [
"python",
"gtk"
] |
Is it better to derive from Gtk.Widget or directly from a specific widget? | 38,650,893 | <p>When I create a UI class for my app, I often wonder if it's better to derive my class from <code>Gtk.Widget</code> and then add explicitly the widgets I need or to derive directly from a specific widget.</p>
<p>Here is two examples, which one is the best?</p>
<pre class="lang-py prettyprint-override"><code>class MyComponent(Gtk.Widget):
def __init__(self):
Gtk.Widget.__init__(self)
box = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 6)
button1 = Gtk.Button.new_with_label("Awesome Button1")
button2 = Gtk.Button.new_with_label("Awesome Button2")
button3 = Gtk.Button.new_with_label("Awesome Button3")
box.pack_start(button1, True, True, 0)
box.pack_start(button2, True, True, 0)
box.pack_start(button3, True, True, 0)
self.add(box)
</code></pre>
<pre class="lang-py prettyprint-override"><code>class MyComponent(Gtk.Box):
def __init__(self):
Gtk.Box.__init__(self, Gtk.Orientation.HORIZONTAL, 6)
button1 = Gtk.Button.new_with_label("Awesome Button1")
button2 = Gtk.Button.new_with_label("Awesome Button2")
button3 = Gtk.Button.new_with_label("Awesome Button3")
self.pack_start(button1, True, True, 0)
self.pack_start(button2, True, True, 0)
self.pack_start(button3, True, True, 0)
</code></pre>
<p>It seems to me that the first version is better since my component isn't technically a <code>Gtk.Box</code>, it's a widget that is using a <code>Gtk.Box</code>, but it could as well use a <code>Gtk.Grid</code> or a <code>Gtk.DrawingArea</code>.</p>
<p>So it seems right on a design stand point, but maybe there's some technicalities that I don't see. What's your advice?</p>
| 1 | 2016-07-29T05:08:11Z | 38,818,000 | <p>It depends on the abstraction in your mind. Ask yourself: is your component merely a customised <em>box</em> or something <em>more</em>?</p>
<p>Moreover, do you <em>actually</em> need inheritance here? Perhaps you can just do away with a free factory-function that creates a group of Gtk.Widgets to your liking.</p>
| 1 | 2016-08-07T19:59:23Z | [
"python",
"gtk"
] |
How do I add multiple markers to a stripplot in seaborn? | 38,650,895 | <p>I would like to know how I could get multiple markers in the same strip plot.</p>
<pre><code>tips = sns.load_dataset("tips")
coldict={'Sun':'red','Thur':'blue','Sat':'yellow','Fri':'green'}
markdict={'Sun':'x','Thur':'o','Sat':'o','Fri':'o'}
tips['color']=tips.day.apply(lambda x: coldict[x])
tips['marker']=tips.day.apply(lambda x: markdict[x])
m=sns.stripplot('size','total_bill',hue='color',\
marker='marker',data=tips, jitter=0.1, palette="Set1",\
split=True,linewidth=2,edgecolor="gray")
</code></pre>
<p>This doesn't seem to work as marker only accepts a single value.</p>
<p>Also preferably I would like to make the corresponding 'Sun' values as transparent red triangles. Any idea how this could be achieved?</p>
<p>Thank you.</p>
<p>Edit:
So a much better way to do it was to declare a my_ax = plt.axes()
and pass my_ax to each stripplot(ax=my_ax). I believe this is the way it should be done.</p>
| 1 | 2016-07-29T05:08:20Z | 38,651,415 | <p>Caution it's a little hacky but here ya go:</p>
<pre><code>import sns
tips = sns.load_dataset("tips")
plt.clf()
thu_fri_sat = tips[(tips['day']=='Thur') | (tips['day']=='Fri') | (tips['day']=='Sat')]
colors = ['blue','yellow','green','red']
m = sns.stripplot('size','total_bill',hue='day',
marker='o',data=thu_fri_sat, jitter=0.1,
palette=sns.xkcd_palette(colors),
split=True,linewidth=2,edgecolor="gray")
sun = tips[tips['day']=='Sun']
n = sns.stripplot('size','total_bill',color='red',hue='day',alpha='0.5',
marker='^',data=sun, jitter=0.1,
split=True,linewidth=0)
handles, labels = n.get_legend_handles_labels()
n.legend(handles[:4], labels[:4])
plt.savefig('/path/to/yourfile.png')
</code></pre>
<p><a href="http://i.stack.imgur.com/xkTo0.png" rel="nofollow"><img src="http://i.stack.imgur.com/xkTo0.png" alt="enter image description here"></a></p>
| 1 | 2016-07-29T05:53:53Z | [
"python",
"pandas",
"matplotlib",
"seaborn"
] |
Decoding ISO-8859-1 and Encoding to UTF-8 before MySQL query | 38,650,968 | <p>I'm kinda stuck if I'm doing it right. </p>
<p>I have a file which is ISO-8859-1 (pretty certain). My MySQL db is in utf-8 encoding. Which is why I want to convert the file to UTF-8 encoded characters before I can send it as a query. For instance, First I rewrite every line of the <strong>file.txt</strong> into <strong>file_new.txt</strong> using.</p>
<pre><code>line = line.decode('ISO-8859-1').encode('utf-8')
</code></pre>
<p>And then I save it. Next, I create a MySQL connection and create a cursor with the following query so that all the data is received as utf-8.</p>
<pre><code>query = 'SET NAMES "utf8"'
cursor.execute(query)
</code></pre>
<p>Following this, I reopen <strong>file_new.txt</strong> and enter each line into MySQL. Is this the right approach to get the table in MySQL utf-8 encoding? Or Am I missing any crucial part? </p>
<p>Now to receive this data. I use <code>'SET NAMES "utf8""</code> as well. But the received data is giving me question marks � when I set the header content type to </p>
<pre><code>header("Content-Type: text/html; charset=utf-8");
</code></pre>
<p>On the other hand, when I set </p>
<pre><code>header("Content-Type: text/html; charset=ISO-8859-1");
</code></pre>
<p>It works fine, but other utf-8 encoded data from the database is getting scrambled. So I'm guessing the data from <strong>file.txt</strong> is still NOT getting encoded to utf-8. Can any one explain why?</p>
<p>PS: Before I read everyline, I replace a character and save the <strong>file.txt</strong> to <strong>file.txt.tmp</strong>. I then read this file to get <strong>file_new.txt</strong>. I don't know if it causes any problem to the original file encoding.</p>
<pre><code>f1 = codecs.open(tsvpath, 'rb',encoding='iso-8859-1')
f2 = codecs.open(tsvpath + '.tmp', 'wb',encoding='utf8')
for line in f1:
f2.write(line.replace('\"', '\''))
f1.close()
f2.close()
</code></pre>
<p>In the below example, I've utf-8 encoded persian data which is right but the other non-enlgish text is coming out to be in "question marks". This is precisely my problem.</p>
<p><strong>Example :</strong> Removed.</p>
| 0 | 2016-07-29T05:16:23Z | 38,651,095 | <p>Try this instead:</p>
<pre><code>line = line.decode('ISO-8859-1').encode('utf-8-sig')
</code></pre>
<p>From the docs:</p>
<blockquote>
<p>As UTF-8 is an 8-bit encoding no BOM is required and any U+FEFF
character in the decoded string (even if itâs the first character) is
treated as a ZERO WIDTH NO-BREAK SPACE.</p>
<p>Without external information itâs impossible to reliably determine
which encoding was used for encoding a string. Each charmap encoding
can decode any random byte sequence. However thatâs not possible with
UTF-8, as UTF-8 byte sequences have a structure that doesnât allow
arbitrary byte sequences. To increase the reliability with which a
UTF-8 encoding can be detected, Microsoft invented a variant of UTF-8
(that Python 2.5 calls "utf-8-sig") for its Notepad program: Before
any of the Unicode characters is written to the file, a UTF-8 encoded
BOM (which looks like this as a byte sequence: 0xef, 0xbb, 0xbf) is
written. As itâs rather improbable that any charmap encoded file
starts with these byte values (which would e.g. map to</p>
<p>LATIN SMALL LETTER I WITH DIAERESIS RIGHT-POINTING DOUBLE ANGLE
QUOTATION MARK INVERTED QUESTION MARK in iso-8859-1), this increases
the probability that a utf-8-sig encoding can be correctly guessed
from the byte sequence. So here the BOM is not used to be able to
determine the byte order used for generating the byte sequence, but as
a signature that helps in guessing the encoding. On encoding the
utf-8-sig codec will write 0xef, 0xbb, 0xbf as the first three bytes
to the file. On decoding utf-8-sig will skip those three bytes if they
appear as the first three bytes in the file. In UTF-8, the use of the
BOM is discouraged and should generally be avoided.</p>
</blockquote>
<p>Source: <a href="https://docs.python.org/3.5/library/codecs.html" rel="nofollow">https://docs.python.org/3.5/library/codecs.html</a></p>
<p><strong>EDIT:</strong></p>
<p>Sample:
<code>"Hello World".encode('utf-8')</code> yields <code>b'Hello World'</code> while <code>"Hello World".encode('utf-8-sig')</code> yields <code>b'\xef\xbb\xbfHello World'</code> highlighting the docs:</p>
<blockquote>
<p>On encoding the
utf-8-sig codec will write 0xef, 0xbb, 0xbf as the first three bytes
to the file. On decoding utf-8-sig will skip those three bytes if they
appear as the first three bytes in the file.</p>
</blockquote>
<p><strong>Edit:</strong>
I have made a similar function before that converts a file to utf-8 encoding. Here is a snippet:</p>
<pre><code>def convert_encoding(src, dst, unicode='utf-8-sig'):
return open(dst, 'w').write(open(src, 'rb').read().decode(unicode, 'ignore'))
</code></pre>
<p>Based on your example, try this:</p>
<pre><code>convert_encoding('file.txt.tmp', 'file_new.txt')
</code></pre>
| 1 | 2016-07-29T05:28:35Z | [
"php",
"python",
"mysql",
"utf-8",
"character-encoding"
] |
Decoding ISO-8859-1 and Encoding to UTF-8 before MySQL query | 38,650,968 | <p>I'm kinda stuck if I'm doing it right. </p>
<p>I have a file which is ISO-8859-1 (pretty certain). My MySQL db is in utf-8 encoding. Which is why I want to convert the file to UTF-8 encoded characters before I can send it as a query. For instance, First I rewrite every line of the <strong>file.txt</strong> into <strong>file_new.txt</strong> using.</p>
<pre><code>line = line.decode('ISO-8859-1').encode('utf-8')
</code></pre>
<p>And then I save it. Next, I create a MySQL connection and create a cursor with the following query so that all the data is received as utf-8.</p>
<pre><code>query = 'SET NAMES "utf8"'
cursor.execute(query)
</code></pre>
<p>Following this, I reopen <strong>file_new.txt</strong> and enter each line into MySQL. Is this the right approach to get the table in MySQL utf-8 encoding? Or Am I missing any crucial part? </p>
<p>Now to receive this data. I use <code>'SET NAMES "utf8""</code> as well. But the received data is giving me question marks � when I set the header content type to </p>
<pre><code>header("Content-Type: text/html; charset=utf-8");
</code></pre>
<p>On the other hand, when I set </p>
<pre><code>header("Content-Type: text/html; charset=ISO-8859-1");
</code></pre>
<p>It works fine, but other utf-8 encoded data from the database is getting scrambled. So I'm guessing the data from <strong>file.txt</strong> is still NOT getting encoded to utf-8. Can any one explain why?</p>
<p>PS: Before I read everyline, I replace a character and save the <strong>file.txt</strong> to <strong>file.txt.tmp</strong>. I then read this file to get <strong>file_new.txt</strong>. I don't know if it causes any problem to the original file encoding.</p>
<pre><code>f1 = codecs.open(tsvpath, 'rb',encoding='iso-8859-1')
f2 = codecs.open(tsvpath + '.tmp', 'wb',encoding='utf8')
for line in f1:
f2.write(line.replace('\"', '\''))
f1.close()
f2.close()
</code></pre>
<p>In the below example, I've utf-8 encoded persian data which is right but the other non-enlgish text is coming out to be in "question marks". This is precisely my problem.</p>
<p><strong>Example :</strong> Removed.</p>
| 0 | 2016-07-29T05:16:23Z | 38,651,661 | <p>Welcome to the wonderful world of unicode and windows. I've found this site very helpful in understanding what is going wrong with my strings <a href="http://www.i18nqa.com/debug/utf8-debug.html" rel="nofollow">http://www.i18nqa.com/debug/utf8-debug.html</a>. The other thing you need is a hex editor like <a href="https://mh-nexus.de/en/hxd/" rel="nofollow">HxD</a>. There are many places where things can go wrong. For example, if you are viewing your files in a text editor - it may be trying to be helpful and is silently changing your encoding. </p>
<p>Start with your original data, view it in HxD and see what the encoding is. View your results in Hxd and see if the changes you expect are being made. Repeat through the steps in your process.</p>
<p>Without your full code and sample data, its hard to say where the problem is. My guess is your replacing the double quote with single quote on binary files is the culprit.</p>
<p>Also check out <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow">The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
by Joel Spolsky</a></p>
| 1 | 2016-07-29T06:11:48Z | [
"php",
"python",
"mysql",
"utf-8",
"character-encoding"
] |
Decoding ISO-8859-1 and Encoding to UTF-8 before MySQL query | 38,650,968 | <p>I'm kinda stuck if I'm doing it right. </p>
<p>I have a file which is ISO-8859-1 (pretty certain). My MySQL db is in utf-8 encoding. Which is why I want to convert the file to UTF-8 encoded characters before I can send it as a query. For instance, First I rewrite every line of the <strong>file.txt</strong> into <strong>file_new.txt</strong> using.</p>
<pre><code>line = line.decode('ISO-8859-1').encode('utf-8')
</code></pre>
<p>And then I save it. Next, I create a MySQL connection and create a cursor with the following query so that all the data is received as utf-8.</p>
<pre><code>query = 'SET NAMES "utf8"'
cursor.execute(query)
</code></pre>
<p>Following this, I reopen <strong>file_new.txt</strong> and enter each line into MySQL. Is this the right approach to get the table in MySQL utf-8 encoding? Or Am I missing any crucial part? </p>
<p>Now to receive this data. I use <code>'SET NAMES "utf8""</code> as well. But the received data is giving me question marks � when I set the header content type to </p>
<pre><code>header("Content-Type: text/html; charset=utf-8");
</code></pre>
<p>On the other hand, when I set </p>
<pre><code>header("Content-Type: text/html; charset=ISO-8859-1");
</code></pre>
<p>It works fine, but other utf-8 encoded data from the database is getting scrambled. So I'm guessing the data from <strong>file.txt</strong> is still NOT getting encoded to utf-8. Can any one explain why?</p>
<p>PS: Before I read everyline, I replace a character and save the <strong>file.txt</strong> to <strong>file.txt.tmp</strong>. I then read this file to get <strong>file_new.txt</strong>. I don't know if it causes any problem to the original file encoding.</p>
<pre><code>f1 = codecs.open(tsvpath, 'rb',encoding='iso-8859-1')
f2 = codecs.open(tsvpath + '.tmp', 'wb',encoding='utf8')
for line in f1:
f2.write(line.replace('\"', '\''))
f1.close()
f2.close()
</code></pre>
<p>In the below example, I've utf-8 encoded persian data which is right but the other non-enlgish text is coming out to be in "question marks". This is precisely my problem.</p>
<p><strong>Example :</strong> Removed.</p>
| 0 | 2016-07-29T05:16:23Z | 38,653,078 | <p>Alright guys, so my encoding was right. The file was getting encoding to utf-8 just as needed. All the queries were right. It turns out that the other dataset that was in Arabic was in ISO-8859-1. Therefore, only 1 of them was working. No matter what I did.</p>
<p>The Hexeditors did help. But in the end I just used sublime text to recheck if my encoded data was utf-8. It turns out the python script and the sublime editor did the same. So the code is fine. :)</p>
| 0 | 2016-07-29T07:36:02Z | [
"php",
"python",
"mysql",
"utf-8",
"character-encoding"
] |
Decoding ISO-8859-1 and Encoding to UTF-8 before MySQL query | 38,650,968 | <p>I'm kinda stuck if I'm doing it right. </p>
<p>I have a file which is ISO-8859-1 (pretty certain). My MySQL db is in utf-8 encoding. Which is why I want to convert the file to UTF-8 encoded characters before I can send it as a query. For instance, First I rewrite every line of the <strong>file.txt</strong> into <strong>file_new.txt</strong> using.</p>
<pre><code>line = line.decode('ISO-8859-1').encode('utf-8')
</code></pre>
<p>And then I save it. Next, I create a MySQL connection and create a cursor with the following query so that all the data is received as utf-8.</p>
<pre><code>query = 'SET NAMES "utf8"'
cursor.execute(query)
</code></pre>
<p>Following this, I reopen <strong>file_new.txt</strong> and enter each line into MySQL. Is this the right approach to get the table in MySQL utf-8 encoding? Or Am I missing any crucial part? </p>
<p>Now to receive this data. I use <code>'SET NAMES "utf8""</code> as well. But the received data is giving me question marks � when I set the header content type to </p>
<pre><code>header("Content-Type: text/html; charset=utf-8");
</code></pre>
<p>On the other hand, when I set </p>
<pre><code>header("Content-Type: text/html; charset=ISO-8859-1");
</code></pre>
<p>It works fine, but other utf-8 encoded data from the database is getting scrambled. So I'm guessing the data from <strong>file.txt</strong> is still NOT getting encoded to utf-8. Can any one explain why?</p>
<p>PS: Before I read everyline, I replace a character and save the <strong>file.txt</strong> to <strong>file.txt.tmp</strong>. I then read this file to get <strong>file_new.txt</strong>. I don't know if it causes any problem to the original file encoding.</p>
<pre><code>f1 = codecs.open(tsvpath, 'rb',encoding='iso-8859-1')
f2 = codecs.open(tsvpath + '.tmp', 'wb',encoding='utf8')
for line in f1:
f2.write(line.replace('\"', '\''))
f1.close()
f2.close()
</code></pre>
<p>In the below example, I've utf-8 encoded persian data which is right but the other non-enlgish text is coming out to be in "question marks". This is precisely my problem.</p>
<p><strong>Example :</strong> Removed.</p>
| 0 | 2016-07-29T05:16:23Z | 38,665,348 | <p>You should <em>not</em> need to do any explicit encode or decode. <code>SET NAMES ...</code> should match what the <em>client</em> encoding is (for <code>INSERTing</code>) or should become (for <code>SELECTing</code>).</p>
<p>MySQL will convert between the client encoding and the columns's <code>CHARACTER SET</code>.</p>
| 0 | 2016-07-29T18:28:42Z | [
"php",
"python",
"mysql",
"utf-8",
"character-encoding"
] |
XPath not working as I'd expect it to | 38,651,048 | <p>Hopefully, you don't need the entire set of code here, but I have an issue where I'm parsing HTML, using XPath and I'm not getting what I'd expect:</p>
<pre><code># here is the current set of tags I'm interested in
html = '''<div style="padding-top: 10px; clear: both; width: 100%;">
<a href="http://www.amazon.com/review/R41M1I2K413NG/ref=cm_aya_cmt?ie=UTF8&ASIN=B013IZY7RU#wasThisHelpful" ><img src="http://g-ecx.images-amazon.com/images/G/01/x-locale/communities/discussion_boards/comment-sm._CB192250344_.gif" width="16" alt="Comment" hspace="3" align="absmiddle" height="16" border="0" /></a>&nbsp;<a href="http://www.amazon.com/review/R41M1I2K413NG/ref=cm_aya_cmt?ie=UTF8&ASIN=B013IZY7RU#wasThisHelpful" >Comment</a>&nbsp;|&nbsp;<a href="http://www.amazon.com/review/R41M1I2K413NG/ref=cm_cr_rdp_perm" >Permalink</a>'''
</code></pre>
<p>I'm trying to get the <code>href</code> value of the first <code>a</code> tag, which is a long URL. To do so I'm using the following code</p>
<pre><code>from lxml import etree
import StringIO
parser = etree.HTMLParser(encoding="utf-8")
tree = etree.parse(StringIO.StringIO(html), parser)
style = 'padding-top: 10px; clear: both; width: 100%;'
xpath = "//div[@style='%s']" % style
xpath += "/a[1]/@href"
# use the XPath expression above to pull out the href value
tree.xpath(xpath)
['http://www.amazon.com/review/R41M1I2K413NG/ref=cm_aya_cmt?ie=UTF8&ASIN=B013IZY7RU#wasThisHelpful']
</code></pre>
<p>This works when I pull out the part I'm working with and paste it as a string. This doesn't work exactly the same with the <code>tree</code> I've built using a <code>request.get()</code> call and I cannot figure out why? What it returns is:</p>
<pre><code>['http://www.amazon.com/review/R41M1I2K413NG]
</code></pre>
<p>And I cannot figure out why. I understand I'm shooting in the dark here, but I'm just hoping someone has come across a "XPath return value of attribute truncated" issue.</p>
<p><strong>EDIT:</strong></p>
<p>Here's the full code that I'm currently using, but it doesn't work. It returns the truncated value above.</p>
<pre><code>from lxml import etree
import requests
import StringIO
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
session = requests.Session()
retries = Retry(total=5, backoff_factor=1, status_forcelist=[502, 503, 504])
session.mount('http://www.amazon.com', HTTPAdapter(max_retries=retries))
parser = etree.HTMLParser(encoding=encoding)
url = "http://www.amazon.com/gp/cdp/member-reviews/ARPJ98Y7U8K5H?ie=UTF8&display=public&page=3&sort_by=MostRecentReview"
page = session.get(url, timeout=5)
tree = etree.parse(StringIO.StringIO(page.text), parser)
style = 'padding-top: 10px; clear: both; width: 100%;'
xpath = "//div[@style='%s']" % style
xpath += "/a[1]/@href"
# use the XPath expression above to pull out the href value
tree.xpath(xpath)
</code></pre>
<p><strong>EDIT 2:</strong></p>
<p>This does work for some reason. Rather than creating a <code>session</code> object and, using that to submit a <code>get</code> request, then pass that to the <code>parser</code>, simply passing the <code>url</code> string to the <code>parser</code> works:</p>
<pre><code>url = "http://www.amazon.com/gp/cdp/member-reviews/ARPJ98Y7U8K5H?ie=UTF8&display=public&page=3&sort_by=MostRecentReview"
tree = etree.parse(url, parser)
for e in tree.xpath("//div[@style='padding-top: 10px; clear: both; width: 100%;']/a[1]/@href"):
print e
</code></pre>
<p>As I understand it, when looping through multiple url's the session object will persist connection attributes that speed up the process. If I use the <code>etree.parse(url, parser)</code> method, I'm worried I'll lose efficiency. </p>
| 2 | 2016-07-29T05:24:45Z | 38,660,682 | <p>With the URL you provided, the following Python code:</p>
<pre><code>url = "http://www.amazon.com/gp/cdp/member-reviews/ARPJ98Y7U8K5H?ie=UTF8&display=public&page=3&sort_by=MostRecentReview"
from lxml import etree
parser = etree.HTMLParser(encoding="utf-8")
tree = etree.parse(url, parser)
for e in tree.xpath("//div[@style='padding-top: 10px; clear: both; width: 100%;']/a[1]/@href"):
print e
</code></pre>
<p>Results in the following output:</p>
<pre><code>> python ~/test.py
http://www.amazon.com/review/RM8YYCQ57K2CL/ref=cm_aya_cmt/159-5911033-5890330?ie=UTF8&ASIN=B00J9PAZIO#wasThisHelpful
http://www.amazon.com/review/R41M1I2K413NG/ref=cm_aya_cmt/159-5911033-5890330?ie=UTF8&ASIN=B013IZY7RU#wasThisHelpful
http://www.amazon.com/review/R3DT6VUDGIT9SK/ref=cm_aya_cmt/159-5911033-5890330?ie=UTF8&ASIN=B000VYD0MA#wasThisHelpful
http://www.amazon.com/review/RGFW1JM4151MW/ref=cm_aya_cmt/159-5911033-5890330?ie=UTF8&ASIN=B00TQQN5G0#wasThisHelpful
http://www.amazon.com/review/R3I9FFX0MVF1BW/ref=cm_aya_cmt/159-5911033-5890330?ie=UTF8&ASIN=B0048A7NF8#wasThisHelpful
http://www.amazon.com/review/R24TTSQY34VME8/ref=cm_aya_cmt/159-5911033-5890330?ie=UTF8&ASIN=B0115ZHH68#wasThisHelpful
http://www.amazon.com/review/R3C49WWMNQZ007/ref=cm_aya_cmt/159-5911033-5890330?ie=UTF8&ASIN=B00ABAWHJ6#wasThisHelpful
http://www.amazon.com/review/R37724EHW829NB/ref=cm_aya_cmt/159-5911033-5890330?ie=UTF8&ASIN=B00TO5Y3FK#wasThisHelpful
http://www.amazon.com/review/RQKGM5FRXVYSX/ref=cm_aya_cmt/159-5911033-5890330?ie=UTF8&ASIN=B0051QUWKG#wasThisHelpful
http://www.amazon.com/review/R1DW61PMGUDMDJ/ref=cm_aya_cmt/159-5911033-5890330?ie=UTF8&ASIN=B000N8Q2P6#wasThisHelpful
</code></pre>
<p>Using the sample code you provided results in:</p>
<pre><code>http://www.amazon.com/review/RM8YYCQ57K2CL
http://www.amazon.com/review/R41M1I2K413NG
http://www.amazon.com/review/R3DT6VUDGIT9SK
http://www.amazon.com/review/RGFW1JM4151MW
http://www.amazon.com/review/R3I9FFX0MVF1BW
http://www.amazon.com/review/R24TTSQY34VME8
http://www.amazon.com/review/R3C49WWMNQZ007
http://www.amazon.com/review/R37724EHW829NB
http://www.amazon.com/review/RQKGM5FRXVYSX
http://www.amazon.com/review/R1DW61PMGUDMDJ
</code></pre>
<p>This is due to the fact that none of the URLs in the HTML page returned by <code>session.get()</code> have any GET parameters; either because the server doesn't return URLs with GET parameters in this case or because <code>requests</code> strips off the GET parameters.</p>
| 0 | 2016-07-29T13:55:26Z | [
"python",
"python-2.7",
"xpath",
"python-requests",
"lxml"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.