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
sequence |
---|---|---|---|---|---|---|---|---|---|
Trying to update position of lines in Tkinter based off of text file | 40,034,044 | <p>I am creating a Tkinter program that creates a canvas that shows a vehicles position according to an angle that is saved to a text file. The problem that I have is that the program only reads the text file when it starts and doesn't continue checking. I know that it should be fairly simple but I have looked at many sites and cannot find a way to do this. Here is my code </p>
<pre><code> from Tkinter import *
import math
import time
root = Tk()
root.geometry("800x480")
root.configure(background='darkgrey')
content = Frame(root,)
#Dimensions of Window
w = 800
h = 480
#Get Angle
file_angle = open("current_angle.txt")
#read file and remove "/n" from the end of the string
string_angle = ((file_angle.read())[:-2])
#Convert string to a number
read_angle = float(string_angle)
if read_angle > 90 or read_angle <-90:
deg_angle = read_angle - 180
else:
deg_angle = read_angle
angle = math.radians(deg_angle)
swath_width = w / 5
if deg_angle > -90 and deg_angle < 90:
#Center Line
centertopx = (w/2) + ((h / 1.5) * math.tan(angle))
centertopy = 0
centerbottomx = (w/2) + ((h - (h / 1.5)) * math.tan(-1 * angle))
centerbottomy = h
if deg_angle == 90 or deg_angle == -90:
centertopx = 0
centertopy = h / 2
centerbottomx = w
centerbottomy = h / 2
#Create Guidance Map
livemap = Canvas(root, width=w, height=h)
#Outline of map
livemap.create_rectangle(0,0,w,h, outline="black", width=5, fill="#9E9E9E")
#Drawing lines
livemap.create_line(centertopx, centertopy, centerbottomx, centerbottomy, fill="red", width=4)
#stationary parts of map
#Triangle that represents vehicle
livemap.create_polygon(
((w/2)-(w * 0.04)),((h / 1.5)+(h * 0.1)),((w/2)+(w * 0.04)),((h / 1.5)+(h * 0.1)),(w/2),(h / 1.5),
outline="black", fill="darkorange", width=2)
livemap.create_line((w/2),((h / 1.5)+(h*0.07)),(w/2),(h / 1.5),fill="black", width=2)
livemap.create_polygon(((w/2)-(w * 0.04)),((h / 1.5)+(h * 0.1)),((w/2)+(w * 0.04)),((h / 1.5)+(h * 0.1)),(w/2),((h / 1.5)+(h*0.07)),
outline="black", fill="darkorange", width=2)
#Put canvas into window
livemap.grid(column=0, row=0, columnspan=4, rowspan=4)
root.mainloop()
</code></pre>
| 0 | 2016-10-14T02:36:27Z | 40,037,206 | <p>Use <code>root.after(miliseconds, function_name)</code> to run periodically function which will read file again and move line on canvas. </p>
<p>In code I create line only once (before vehicle) and later I change only line position.</p>
<pre><code>from Tkinter import *
import math
import time
w = 800
h = 480
# --- functions ---
def update_line():
deg_angle = open("current_angle.txt")
deg_angle = deg_angle.read()[:-2]
deg_angle = float(deg_angle)
if deg_angle > 90 or deg_angle <-90:
deg_angle -= 180
if deg_angle == 90 or deg_angle == -90: # you need
centertopx = 0
centertopy = h / 2
centerbottomx = w
centerbottomy = h / 2
else: # deg_angle > -90 and deg_angle < 90:
angle = math.radians(deg_angle)
#Center Line
centertopx = (w/2) + ((h/1.5)*math.tan(angle))
centertopy = 0
centerbottomx = (w/2) + ((h - (h/1.5))*math.tan(-angle))
centerbottomy = h
# move line
livemap.coords(line, centertopx, centertopy, centerbottomx, centerbottomy)
# repeat after 200 ms (0.2s)
root.after(200, update_line)
# --- main ---
root = Tk()
root.geometry("800x480")
root.configure(background='darkgrey')
content = Frame(root,)
livemap = Canvas(root, width=w, height=h)
livemap.create_rectangle(0, 0, w, h, outline="black", width=5, fill="#9E9E9E")
# create line (without angle) before vehicle
line = livemap.create_line(w/2, 0, w/2, h, fill="red", width=4)
#Triangle that represents vehicle
livemap.create_polygon(
(w/2)-(w*0.04), (h/1.5)+(h*0.1),
(w/2)+(w*0.04), (h/1.5)+(h*0.1),
w/2, h/1.5,
outline="black", fill="darkorange", width=2)
livemap.create_line(w/2, (h/1.5)+(h*0.07), w/2, h/1.5, fill="black", width=2)
livemap.create_polygon(
(w/2)-(w*0.04), (h/1.5)+(h*0.1),
(w/2)+(w*0.04), (h/1.5)+(h*0.1),
w/2, (h/1.5)+(h*0.07),
outline="black", fill="darkorange", width=2)
livemap.grid(column=0, row=0, columnspan=4, rowspan=4)
# update line first time
update_line()
root.mainloop()
</code></pre>
| 0 | 2016-10-14T07:19:13Z | [
"python",
"tkinter",
"tkinter-canvas"
] |
How do I resolve issues when everything in my mac messed up? | 40,034,048 | <p>my command line tools is set up by homebrew + pip. However, I installed macport trying to get some software but then turns out everything is messed up even after I removed macport... How could I re-set up my Mac for scientific computations including all the necessary command line tools (like vi, bash, they all have errors now and I do not want to solve them one by one)...</p>
<p>I am installing conda though trying to resolve this issue...</p>
<p>Errors include:</p>
<pre><code>$Bash
dyld: Library not loaded: /usr/local/opt/readline/lib/libreadline.6.dylib
Referenced from: /usr/local/bin/bash
Reason: image not found
Trace/BPT trap: 5
</code></pre>
<p>I do not want to list all errors and solve one by one... I just want to reinstall and reset up...</p>
| 1 | 2016-10-14T02:37:01Z | 40,034,231 | <p>This isn't a python question...</p>
<p>For future reference, just use the anaconda distribution of python. Don't bother with homebrew or macports. You'll never have to mess with this</p>
| 0 | 2016-10-14T03:00:13Z | [
"python",
"bash",
"osx"
] |
How do I resolve issues when everything in my mac messed up? | 40,034,048 | <p>my command line tools is set up by homebrew + pip. However, I installed macport trying to get some software but then turns out everything is messed up even after I removed macport... How could I re-set up my Mac for scientific computations including all the necessary command line tools (like vi, bash, they all have errors now and I do not want to solve them one by one)...</p>
<p>I am installing conda though trying to resolve this issue...</p>
<p>Errors include:</p>
<pre><code>$Bash
dyld: Library not loaded: /usr/local/opt/readline/lib/libreadline.6.dylib
Referenced from: /usr/local/bin/bash
Reason: image not found
Trace/BPT trap: 5
</code></pre>
<p>I do not want to list all errors and solve one by one... I just want to reinstall and reset up...</p>
| 1 | 2016-10-14T02:37:01Z | 40,034,697 | <p>Try this.</p>
<pre><code>brew update
brew upgrade
brew cleanup
brew unlinkapps
brew linkapps
</code></pre>
<p>Also there is</p>
<pre><code>brew doctor
</code></pre>
<p>Which shows if there are some problems/confilicts</p>
| 2 | 2016-10-14T03:56:31Z | [
"python",
"bash",
"osx"
] |
Python setattr() not assigning value to class member | 40,034,054 | <p>I'm trying to set up a simple test example of <code>setattr()</code> in Python, but it fails to assign a new value to the member. </p>
<pre><code>class Foo(object):
__bar = 0
def modify_bar(self):
print(self.__bar)
setattr(self, "__bar", 1)
print(self.__bar)
</code></pre>
<p>Here I tried variable assignment with <code>setattr(self, "bar", 1)</code>, but was unsuccessful:</p>
<pre><code>>>> foo = Foo()
>>> foo.modify_bar()
0
0
</code></pre>
<p>Can someone explain what is happening under the hood. I'm new to python, so please forgive my elementary question.</p>
| 0 | 2016-10-14T02:37:24Z | 40,034,125 | <p>A leading double underscore invokes python <a href="https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references" rel="nofollow">name-mangling</a>.</p>
<p>So:</p>
<pre><code>class Foo(object):
__bar = 0 # actually `_Foo__bar`
def modify_bar(self):
print(self.__bar) # actually self._Foo__bar
setattr(self, "__bar", 1)
print(self.__bar) # actually self._Foo__bar
</code></pre>
<p>Name mangling <em>only</em> applies to identifiers, not strings, which is why the <code>__bar</code> in the <code>setattr</code> function call is unaffected.</p>
<pre><code>class Foo(object):
_bar = 0
def modify_bar(self):
print(self._bar)
setattr(self, "_bar", 1)
print(self._bar)
</code></pre>
<p>should work as expected.</p>
<p>Leading double underscores are generally not used very frequently in most python code (because their use is typically discouraged). There are a few valid use-cases (mainly to avoid name clashes when subclassing), but those are rare enough that name mangling is generally avoided in the wild.</p>
| 0 | 2016-10-14T02:46:09Z | [
"python",
"reflection",
"setattr"
] |
New Coder simple time clock | 40,034,159 | <p>I need help trying to solve this problem in python</p>
<p>You must write a program asking for the current time <code>(hours only)</code> and an amount of hours in the future. Use the modulo <code>%</code> operator to tell the time traveler the future hour to which they will be traveling.</p>
<p>the tricky part for me is how do you make the time reset after 24</p>
<p>edit</p>
<pre><code>`#TODO 1: Ask for user input
hour=input("what time is it?")
time_traveled=input("how many hours would you like to travel")
hr=int(hour)
tt=int(time_traveled)`
`#TODO 2: Calculate the future hour
futurehr=hr+tt
if futurehr%24 == 0:
finalHr=futurehr
else:annoyinghr=futurehr
days=annoyinghr%24*24
if annoyinghr%24 > 0:
finalHr=annoyinghr-days`
</code></pre>
<p>sorry about not posting the code, I think my problem is I dont understand the <code>%</code> well enough </p>
<p>thank you in advance</p>
| -2 | 2016-10-14T02:52:13Z | 40,036,042 | <p>It seems like you're making your code more complicated than necessary:</p>
<pre><code># TODO 1: Ask for user input
hour = int(input("What time is it? "))
time_traveled = int(input("How many hours would you like to travel? "))
#TODO 2: Calculate the future hour
future_hour = (hour + time_traveled) % 24
print("You will arrive in the future at", future_hour, "o'clock")
</code></pre>
<p>If the above isn't sufficient, please edit your description to say what further processing needs to be done to the result. If it is sufficient, the above isn't finished code -- it really should handle possible bad, non-numeric or out of range input via explicit tests and <code>try ... except</code> clauses.</p>
| 0 | 2016-10-14T06:07:52Z | [
"python"
] |
AWS SDK for Python - Boto - KeyPair Creation Confusion | 40,034,228 | <p>I am trying to create a EC2 key-pair using the create_key_pair() method, something like:</p>
<pre><code>key_name = 'BlockChainEC2InstanceKeyPair-1'
def create_new_key_pair(key_name):
newKey = objEC2.create_key_pair(key_name)
newKey.save(dir_to_save_new_key)
</code></pre>
<p>The keys are created as I can fetch these using the get_all_key_pairs() method like below:</p>
<pre><code>def get_all_keypairs():
try:
key= objEC2.get_all_key_pairs()
except:
raise
</code></pre>
<p>get_all_key_pairs() returns the result like below showing that the keypair exists:</p>
<pre><code><DescribeKeyPairsResponse xmlns="http://ec2.amazonaws.com/doc/2014-10-01/">
<requestId>8d3faa7d-70c2-4b7c-ad18-810f23230c22</requestId>
<keySet>
<item>
<keyName>BlockChainEC2InstanceKeyPair-1</keyName>
<keyFingerprint>30:51:d4:19:a5:ba:11:dc:7e:9d:ca:49:10:01:30:34:b5:7e:9b:8a</keyFingerprint>
</item>
<item>
<keyName>BlockChainEC2InstanceKeyPair-1.pem</keyName>
<keyFingerprint>18:7e:ba:2c:44:67:44:a7:06:c4:68:3a:47:00:88:8f:31:98:27:e6</keyFingerprint>
</item>
</keySet>
</DescribeKeyPairsResponse>
</code></pre>
<p>My problem is when I log into my AWS console for the same account whose access keys I used to create the keypairs - I don't get to find the keys.</p>
<p><strong>Question is</strong>: Where in my AWS console can I see the key-pair I created using the create_key_pair() method.</p>
| 0 | 2016-10-14T02:59:50Z | 40,035,301 | <p>The <code>keypairs</code> are for each region. I suspect you are creating the keypair in one region using boto and you are checking for the keypair in a different region in your AWS console.</p>
<p>Make sure you default region in boto ( .aws/config ) and check your AWS dashboard is in the same region. If not change the region in the dashboard to match your boto default region and your keypair will appear there.</p>
<p>Or pass the region parameter when creating the EC2 object.</p>
| 1 | 2016-10-14T05:07:36Z | [
"python",
"amazon-web-services",
"amazon-ec2",
"boto"
] |
How to replace a dot with a string in a python list | 40,034,246 | <pre><code>my_list = ['b','.','.']
expected_list = ['b','.','w']
</code></pre>
<p>May be simple, moving into python recently so any suggestions would be fine</p>
| -1 | 2016-10-14T03:01:40Z | 40,034,640 | <p>If you are replacing every occurrence of '.' with 'w' then I would just suggest:</p>
<pre><code>for n, i in enumerate(my_list):
if i == '.':
my_list[n] = 'w'
</code></pre>
<p>Here is the documentation for how to use the enumerate() function: <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow">https://docs.python.org/2/library/functions.html#enumerate</a></p>
| 0 | 2016-10-14T03:49:49Z | [
"python",
"python-2.7"
] |
How to replace a dot with a string in a python list | 40,034,246 | <pre><code>my_list = ['b','.','.']
expected_list = ['b','.','w']
</code></pre>
<p>May be simple, moving into python recently so any suggestions would be fine</p>
| -1 | 2016-10-14T03:01:40Z | 40,034,794 | <blockquote>
<p>You can do this by using list comprehension also</p>
</blockquote>
<pre><code>l = ['w' if i == '.' else i for i in my_list]
</code></pre>
| 1 | 2016-10-14T04:10:54Z | [
"python",
"python-2.7"
] |
Using data from one file to create two appended lists to a new file | 40,034,275 | <p>I am trying to take data from one file and create two lists which are both written to a new file. One of the lists contains names 6 characters or less and the second list contains a list with names that do not contain "a" or "e." I have the code done that will form both lists, I have tried them both separately and they work but, I cannot make them both append to a new list at the same time. Whichever list I do first will be the only one that gets appended to the new file. Any help would be much appreciated!</p>
<h1>Code</h1>
<pre><code>main_file = open("words.txt", "r")
#loops to find lists
lists = open('test.txt')
lists.read()
with open("test.txt", "a") as lists:
for names in main_file:
if len(names) <= 6:
lists.write(names)
line = True
for line in main_file:
if "a" in line or "e" in line or "A" in line:
line = False
else:
lists.write(line)
</code></pre>
<h1>Both lists need to be appended to a new and the SAME file</h1>
| 0 | 2016-10-14T03:05:22Z | 40,034,529 | <p>If I understand your qn correctly</p>
<pre><code>import re
l1 = []
l2 = []
lists = open('test.txt','w')
with open('words.txt') as f:
for line in f.read().split('\n'):
if len(line) <= 6:
l1.append(line)
if not re.search(r'a|e', line):
l2.append(line)
lists.write('\n'.join( l1+l2 ) )
lists.close()
</code></pre>
| 0 | 2016-10-14T03:36:12Z | [
"python",
"list",
"file",
"boolean",
"append"
] |
Django Allauth and urls | 40,034,300 | <p>I have a dev environment for a test of Django. I am running Python 3.5.2 out of a "local" <code>pyenv</code> install. I have Django 1.10.2. I discovered the <code>allauth</code> registration plugin yesterday and have been playing with it but have hit a snag.</p>
<p>My site is "dev.my.domain.com". The intent is that there will not be any "public" information on the production version of this site. The production version will be called something like: "members.my.domain.com". So, I wonder if it is possible for the "allauth" plugin to have all non-/adomn inbound requests check for auth?</p>
<p>So, requests to: </p>
<ul>
<li>dev.my.domain.com</li>
<li>dev.my.domain.com/foo</li>
<li>dev.my.domain.com/foo/../bar/...</li>
</ul>
<p>should all be checked for auth. If not there then I assume "allauth" will redirect to a login/signup page.</p>
<p>I have tried setting the <code>Members/urls.py</code> file as:</p>
<pre><code>from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^$', include('allauth.urls')),
url(r'^admin/', admin.site.urls),
]
</code></pre>
<p>but that bombs with a Page Not Found error and the <code>DEBUG</code> message:</p>
<pre><code> Using the URLconf defined in Members.urls, Django tried these URL patterns, in this order:
^$ ^ ^signup/$ [name='account_signup']
^$ ^ ^login/$ [name='account_login']
^$ ^ ^logout/$ [name='account_logout']
^$ ^ ^password/change/$ [name='account_change_password']
^$ ^ ^password/set/$ [name='account_set_password']
^$ ^ ^inactive/$ [name='account_inactive']
^$ ^ ^email/$ [name='account_email']
^$ ^ ^confirm-email/$ [name='account_email_verification_sent']
^$ ^ ^confirm-email/(?P<key>[-:\w]+)/$ [name='account_confirm_email']
^$ ^ ^password/reset/$ [name='account_reset_password']
^$ ^ ^password/reset/done/$ [name='account_reset_password_done']
^$ ^ ^password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/$ [name='account_reset_password_from_key']
^$ ^ ^password/reset/key/done/$ [name='account_reset_password_from_key_done']
^$ ^social/
^$ ^google/
^$ ^facebook/
^$ ^facebook/login/token/$ [name='facebook_login_by_token']
^admin/
The current URL, , didn't match any of these.
</code></pre>
<p>I bowed to my ignorance and went back to the allauth docs and used their default <code>urls</code> setting:</p>
<pre><code>from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^accounts/', include('allauth.urls')),
url(r'^admin/', admin.site.urls),
]
</code></pre>
<p>but that also bombs with a Page Not Found and a different message:</p>
<pre><code> Using the URLconf defined in Members.urls, Django tried these URL patterns, in this order:
^accounts/
^admin/
The current URL, , didn't match any of these.
</code></pre>
<p>I think the rest of the "allauth" install was done correctly but I am missing something.</p>
<p>Ideas?</p>
| 1 | 2016-10-14T03:08:04Z | 40,036,524 | <p>In your <em>view.py</em> file, you just need to do a little "filter" before giving away the page to see if the user is authenticated.</p>
<p>An example for this will be:</p>
<pre><code>def myview(request):
if request.user.is_authenticated():
# do something if the user is authenticated, like showing a page.
else:
# do somthing else
</code></pre>
<p>Regrading the urls structure - just try to add /accounts/ to the url and the 404 page will show you all the end points if you are on Debug mode (DEBUG = True).
You can also find all urls for endpoints on the documentation.</p>
<p>Hope I understood your problem correctly :)</p>
| 0 | 2016-10-14T06:40:08Z | [
"python",
"django",
"django-allauth"
] |
Using compression library to estimate information complexity of an english sentence? | 40,034,334 | <p>I'm trying to write an algorithm that can work out the 'unexpectedness' or 'information complexity' of a sentence. More specifically I'm trying to sort a set of sentences so the least complex come first. </p>
<p>My thought was that I could use a compression library, like zlib?, 'pre train' it on a large corpus of text in the same language (call this the 'Corpus') and then append to that corpus of text the different sentences.</p>
<p>That is I could define the complexity measure for a sentence to be how many more bytes it requires to compress the whole corpus with that sentence appended, versus the whole corpus with a different sentence appended. (The fewer extra bytes, the more predictable or 'expected' that sentence is, and therefore the lower the complexity). Does that make sense?</p>
<p>The problem is with trying to find the right library that will let me do this, preferably from python.</p>
<p>I could do this by literally appending sentences to a large corpus and asking a compression library to compress the whole shebang, but if possible, I'd much rather halt the processing of the compression library at the end of the corpus, take a snapshot of the relevant compression 'state', and then, with all that 'state' available try to compress the final sentence. (I would then roll back to the snapshot of the state at the end of the corpus and try a different sentence).</p>
<p>Can anyone help me with a compression library that might be suitable for this need? (Something that lets me 'freeze' its state after 'pre training'.)</p>
<p>I'd prefer to use a library I can call from Python, or Scala. Even better if it is pure python (or pure scala)</p>
| 0 | 2016-10-14T03:12:02Z | 40,046,686 | <p>All this is going to do is tell you whether the words in the sentence, and maybe phrases in the sentence, are in the dictionary you supplied. I don't see how that's complexity. More like grade level. And there are better tools for that. Anyway, I'll answer your question.</p>
<p>Yes, you can preset the zlib compressor a dictionary. All it is is up to 32K bytes of text. You don't need to run zlib on the dictionary or "freeze a state" -- you simply start compressing the new data, but permit it to look back at the dictionary for matching strings. However 32K isn't very much. That's as far back as zlib's deflate format will look, and you can't load much of the English language in 32K bytes.</p>
<p>LZMA2 also allows for a preset dictionary, but it can be much larger, up to 4 GB. There is a Python binding for the LZMA2 library, but you may need to extend it to provide the dictionary preset function.</p>
| 1 | 2016-10-14T15:20:27Z | [
"python",
"scala",
"compression",
"information-theory"
] |
Logarithm of a pandas series/dataframe | 40,034,378 | <p>In short: How can I get a logarithm of a column of a pandas dataframe?
I thought <code>numpy.log()</code> should work on it, but it isn't. I suspect it's because I have some <code>NaN</code>s in the dataframe?</p>
<p>My whole code is below. It may seem a bit chaotic, basically my ultimate goal (a little exaggerated) is to plot different rows of different selected columns in several selected columns into several subplots (hence the three embedded for loops iterating between different groups... if you suggest a more elegant solution, I will appreciate it but it is not the main thing that's pressing me). I need to plot a logarithm of some values from one dataframe + 1 versus some values of the other dataframe. And here is the problem, on the plotting line with np.log I get this error: <code>AttributeError: 'float' object has no attribute 'log'</code> (and if I use math instead of np, I get this: <code>TypeError: cannot convert the series to <type 'float'></code>)
What may I do about it?</p>
<p>Thank you.
Here is the code:</p>
<pre><code>import numpy as np
import math
import pandas as pd
import matplotlib.pyplot as plt
hf = pd.DataFrame({'Z':np.arange(0,100,1),'A':(10*np.random.rand(100)), 'B':(10*np.random.rand(100)),'C':(10*np.random.rand(100)),'D':(10*np.random.rand(100)),'E':(10*np.random.rand(100)),'F':(10*np.random.rand(100))})
df = pd.DataFrame({'Z':np.arange(0,100,1),'A':(10*np.random.rand(100)), 'B':(10*np.random.rand(100)),'C':(10*np.random.rand(100)),'D':(10*np.random.rand(100)),'E':(10*np.random.rand(100)),'F':(10*np.random.rand(100))})
hf.loc[0:5,'A']=np.nan
df.loc[0:5,'A']=np.nan
hf.loc[53:58,'B']=np.nan
df.loc[53:58,'B']=np.nan
hf.loc[90:,'C']=np.nan
df.loc[90:,'C']=np.nan
I = ['A','B']
II = ['C','D']
III = ['E','F']
IV = ['F','A']
runs = [I,II,III,IV]
inds = [10,20,30,40]
fig = plt.figure(figsize=(6,4))
for r in runs:
data = pd.DataFrame(index=df.index,columns=r)
HF = pd.DataFrame(index=hf.index,columns=r)
#pdb.set_trace()
for i in r:
data.loc[:,i] = df.loc[:,i]
HF.loc[:,i] = hf.loc[:,i]
for c,z in enumerate(inds):
ax=fig.add_subplot()
ax = plt.plot(math.log1p(HF.loc[z]),Tdata.loc[z],linestyle=":",marker="o",markersize=5,label=inds[c].__str__())
# or the other version
#plt.plot(np.log(1 + HF.loc[z]),Tdata.loc[z],linestyle=":",marker="o",markersize=5,label=inds[c].__str__())
</code></pre>
<p>As @Jason pointed out, <a href="http://stackoverflow.com/a/16968491/5553319">this answer</a> did the trick! Thank you!</p>
| 0 | 2016-10-14T03:16:32Z | 40,034,471 | <p>The problem isn't that you have <code>NaN</code> values, it's that you <em>don't</em> have <code>NaN</code> values, you have <strong>strings</strong> <code>"NaN"</code> which the <code>ufunc</code> np.log doesn't know how to deal with. Replace the beginning of your code with:</p>
<pre><code>hf = pd.DataFrame({'Z':np.arange(0,100,1),'A':(10*np.random.rand(100)), 'B':(10*np.random.rand(100)),'C':(10*np.random.rand(100)),'D':(10*np.random.rand(100)),'E':(10*np.random.rand(100)),'F':(10*np.random.rand(100))})
df = pd.DataFrame({'Z':np.arange(0,100,1),'A':(10*np.random.rand(100)), 'B':(10*np.random.rand(100)),'C':(10*np.random.rand(100)),'D':(10*np.random.rand(100)),'E':(10*np.random.rand(100)),'F':(10*np.random.rand(100))})
hf.loc[0:5,'A'] = np.nan
df.loc[0:5,'A'] = np.nan
hf.loc[53:58,'B'] = np.nan
df.loc[53:58,'B'] = np.nan
hf.loc[90:,'C'] = np.nan
df.loc[90:,'C'] = np.nan
</code></pre>
<p>And everything should work nicely with <code>np.log</code></p>
| 4 | 2016-10-14T03:28:42Z | [
"python",
"pandas",
"numpy",
"matplotlib"
] |
Requiring tensorflow with Python 2.7.11 occurs ImportError | 40,034,570 | <p>I tried <code>pip install tensorflow</code> on OS X El Capitan and it succeeded.
However, if I tried to import tensorflow, ImportError occured.
Please tell me when you know.</p>
<pre><code>>>> import tensorflow
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/tensorflow/__init__.py", line 23, in <module>
from tensorflow.python import *
File "/usr/local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 49, in <module>
from tensorflow.python import pywrap_tensorflow
File "/usr/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
_pywrap_tensorflow = swig_import_helper()
File "/usr/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
_mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
ImportError: dlopen(/usr/local/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow.so, 10): no suitable image found. Did find:
/usr/local/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow.so: unknown file type, first eight bytes: 0x7F 0x45 0x4C 0x46 0x02 0x01 0x01 0x03
>>>
</code></pre>
<hr>
| 4 | 2016-10-14T03:40:57Z | 40,039,137 | <p>I got the same question.
Try to follow the [official instruction] to install tensorflow: <a href="https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#pip-installation" rel="nofollow">https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#pip-installation</a></p>
<pre><code># Mac OS X
$ sudo easy_install pip
$ sudo easy_install --upgrade six
</code></pre>
<p>Then, select the correct binary to install:</p>
<pre><code># Ubuntu/Linux 64-bit, CPU only, Python 2.7
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.11.0rc0-cp27-none-linux_x86_64.whl
# Ubuntu/Linux 64-bit, GPU enabled, Python 2.7
# Requires CUDA toolkit 7.5 and CuDNN v5. For other versions, see "Install from sources" below.
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.11.0rc0-cp27-none-linux_x86_64.whl
# Mac OS X, CPU only, Python 2.7:
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.11.0rc0-py2-none-any.whl
# Mac OS X, GPU enabled, Python 2.7:
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/gpu/tensorflow-0.11.0rc0-py2-none-any.whl
# Ubuntu/Linux 64-bit, CPU only, Python 3.4
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.11.0rc0-cp34-cp34m-linux_x86_64.whl
# Ubuntu/Linux 64-bit, GPU enabled, Python 3.4
# Requires CUDA toolkit 7.5 and CuDNN v5. For other versions, see "Install from sources" below.
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.11.0rc0-cp34-cp34m-linux_x86_64.whl
# Ubuntu/Linux 64-bit, CPU only, Python 3.5
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.11.0rc0-cp35-cp35m-linux_x86_64.whl
# Ubuntu/Linux 64-bit, GPU enabled, Python 3.5
# Requires CUDA toolkit 7.5 and CuDNN v5. For other versions, see "Install from sources" below.
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.11.0rc0-cp35-cp35m-linux_x86_64.whl
# Mac OS X, CPU only, Python 3.4 or 3.5:
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.11.0rc0-py3-none-any.whl
# Mac OS X, GPU enabled, Python 3.4 or 3.5:
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/gpu/tensorflow-0.11.0rc0-py3-none-any.whl
</code></pre>
<p>Install TensorFlow:</p>
<pre><code># Python 2
$ sudo pip install --upgrade $TF_BINARY_URL
# Python 3
$ sudo pip3 install --upgrade $TF_BINARY_URL
</code></pre>
| 3 | 2016-10-14T09:02:27Z | [
"python",
"python-2.7",
"tensorflow"
] |
fast interpolation of a (50000,3000) numpy array along axis=-1 | 40,034,623 | <p>I have a 2D array of seismic data of shape (50000, 3000)</p>
<p>I need to 1d interpolate everything in axis=-1</p>
<p>If z=values, t0=value times, tx= new times, I'm currently doing </p>
<pre><code>for i in range(dataset.size):
result[i,:] = np.interp(tx[i,:], t0[i,:], z[i,:])
</code></pre>
<p>not surprisingly it takes hours.</p>
<ul>
<li><p>t0 is sorted but irregularly sampled</p></li>
<li><p>tx is sorted and regularly sampled</p></li>
</ul>
<p>any suggestions on significantly speeding up the code?</p>
<p>am limited to numpy/scipy solutions only</p>
| 0 | 2016-10-14T03:47:50Z | 40,034,879 | <p>Depends on what you're trying to achieve. You can use array slicing to interpolate just a small subset of your data, if you know where the interesting region is. Or you may want to see the big picture by using statistical metrics.</p>
<p>I don't think there is a way to significantly speed up the <code>np.interp()</code> itself, since it essentially traverses all the points in your data. You can try <code>interp1d()</code> from <code>scipy.interpolate</code>, but again I think there will be no significant performance difference.</p>
| 0 | 2016-10-14T04:22:01Z | [
"python",
"numpy",
"scipy"
] |
Error trying to add +1 to value returned from list | 40,034,655 | <p>I have a list of lists I am trying to use as a matrix. In the last line of code when I add '+ 1' to the first argument in the min() function I get an error 'TypeError: can only concatenate list (not "int") to list'. Can someone help me with the correct way to add one to the value I am calling from the list to compare? Thanks! </p>
<pre><code> matrix = []
for j in range(0,j+1):
matrix.append([])
j = len(t)
for j in range(0,j+1):
i = len(s)
for i in range(0,i+1):
matrix[j].append([i])
matrix[j][i] = matrix[j-1][i-1]
j = len(s)
for j in range(1,j+1):
i = len(t)
for i in range(1,j+1):
matrix[j][i]= min((matrix[j-1][i] +1), (matrix[j][i-1]))
</code></pre>
| -1 | 2016-10-14T03:51:20Z | 40,034,775 | <p>Probably, you should replace:</p>
<pre><code>matrix[j].append([i])
</code></pre>
<p>with</p>
<pre><code>matrix[j].append(i)
</code></pre>
<p>You want to append integers to list, one matrix row to be:</p>
<pre><code>[0, 1, 2, 3, ...]
</code></pre>
<p>While you append lists to the list, which creates a row in the matrix as </p>
<pre><code>[[0], [1], [2], ...]
</code></pre>
| 0 | 2016-10-14T04:06:46Z | [
"python",
"list",
"python-3.x"
] |
Using urllib2 to download text to be used to evaluate a variable | 40,034,696 | <p>Am downloading a text page, c.txt, from a webserver. c.txt only contains the letter 'c' . Able to download file fine and print its contents, the character 'c'. Cannot, however, use its contents in the code below:</p>
<pre><code>import urllib2
req = urllib2.Request('http://localhost/c.txt')
response = urllib2.urlopen(req)
result = str(response.read())
print(result) # prints 'c' just fine
furl = "c"
furl = str(furl)
if result == furl: # Does not work
print('Correct')
</code></pre>
<p>No errors are incurred. Just will not work</p>
| 0 | 2016-10-14T03:56:30Z | 40,034,971 | <p>There is most likely an extra white space character in the <code>result</code>. You can check for it by printing characters on either side.</p>
<pre><code>print '>%s<' % result
</code></pre>
<p>If the result looks like <code>>c <</code> you've got a trailing white space (including newline characters).</p>
<p>To remove the leading and trailing white space from a string, you can use the <a href="https://docs.python.org/2/library/string.html#string.strip" rel="nofollow"><code>strip()</code></a> method on the string.</p>
<pre><code>result = str(response.read()).strip()
</code></pre>
<p>Or you can do it right at the point of comparison.</p>
<pre><code>if result.strip() == furl:
print 'correct'
</code></pre>
| 1 | 2016-10-14T04:32:54Z | [
"python",
"urllib2"
] |
Can't load Boost.Python module - undefined symbols | 40,034,745 | <p>I have a library that I wrote in C and need to access from Python, so I wrapped it using Boost.Python. I can compile my library into a Boost .so file with no problems, but when I try to load it into Python (with <code>import tropmodboost</code>), I get the following error:</p>
<pre><code>ImportError: ./tropmodboost.so: undefined symbol: _Z12simplex_freeP7simplex
</code></pre>
<p>I <a href="http://stackoverflow.com/questions/17671912/cannot-import-module-using-boost-python">found</a> out that this is a <a href="http://stackoverflow.com/questions/1780003/import-error-on-boost-python-hello-program">common</a> error, and that it can often be fixed be reordering the <code>-l</code> directives in my g++ linker call, but as fa as I can tell mine are already okay.</p>
<p>Here's the text of my Makefile, which is running on Ubuntu:</p>
<pre><code># location of the Python header files
PYTHON_VERSION = 2.7
PY_VER2 = 27
# various include directories, used separately in different compiler tasks
PYN_INC = /usr/include/python$(PYTHON_VERSION)
IGH_INC = /usr/local/include/igraph
BST_INC = /usr/include
# library locations for linking
LS = -L/usr/lib/x86_64-linux-gnu -L/usr/local/lib -L/usr/lib/python$(PYTHON_VERSION)/config
lS = -lboost_python-py$(PY_VER2) -lpython$(PYTHON_VERSION)
# source files for different compiler tasks
CORE_SRC = permutation_src.c permutation_parity.c split.c simplex.c simplex_src.c build_complex.c
TEST_SRC = main.c tests/tests.c -ligraph -lm
# objects for linking the core to the boost module
CORE_OBJS = permutation_src.o permutation_parity.o split.o simplex.o simplex_src.o build_complex.o
.PHONY: clean tests
main: tropmod.boost.o
g++ -shared -Wl,--export-dynamic tropmod.boost.o $(LS) $(lS) $(CORE_OBJS) -o tropmodboost.so
tropmod.boost.o: tropmod.boost.cpp tmstuff
g++ -I$(PYN_INC) -I$(BST_INC) -I$(IGH_INC) -fPIC -c tropmod.boost.cpp
tmstuff: main.c permutation_src.c permutation_parity.c split.c simplex.c simplex_src.c tests/tests.c
gcc -I. -I=$(IGH_INC) -fPIC -c $(CORE_SRC)
debug: main.c permutation_src.c permutation_parity.c split.c simplex.c simplex_src.c tests/tests.c
gcc -I. -I=$(IGH_INC) -g -fPIC -c $(CORE_SRC)
tests:
gcc -I. -I=$(IGH_INC) -g -o tmtest $(CORE_SRC) $(TEST_SRC) -L/usr/local/lib -ligraph -lm
clean:
rm *.o *.so
</code></pre>
<p>Calling <code>ldd tropmodboost.so</code> outputs:</p>
<pre><code>linux-vdso.so.1 => (0x00007ffff79a3000)
libpython2.7.so.1.0 => /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0 (0x00007f34ea732000)
libboost_python-py27.so.1.58.0 => /usr/lib/x86_64-linux-gnu/libboost_python-py27.so.1.58.0 (0x00007f34ea4e6000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f34ea163000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f34e9f4d000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f34e9b84000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f34e9966000)
libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007f34e974c000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f34e9548000)
libutil.so.1 => /lib/x86_64-linux-gnu/libutil.so.1 (0x00007f34e9344000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f34e903b000)
/lib64/ld-linux-x86-64.so.2 (0x0000561fcfee3000)
</code></pre>
<p>Here's an except from an .hpp file shows the Boost wrapper code itself:</p>
<pre><code>#include <boost/python/class.hpp>
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <boost/python/list.hpp>
#include <boost/python/object.hpp>
[...]
BOOST_PYTHON_MODULE(tropmodboost) {
using namespace boost::python;
class_<ConfigSpace>("ConfigSpace", init<int, int>())
.def("destroy", &ConfigSpace::destroy)
.def("getTraceOfPerm", &ConfigSpace::getTraceOfPerm)
;
}
</code></pre>
| 0 | 2016-10-14T04:03:36Z | 40,048,144 | <p>After running <code>nm</code> on a few of my object files, I found that in the undefined symbol <code>_Z12simplex_freeP7simplex</code> was defined in simplex.o as just <code>simplex_free</code>, presumably because it was compiled from simplex.c using gcc. In other words, I think gcc and g++ were naming things differently from one another, so I switched everything to g++ and compiled my C code as C++, and that resolved the issue.</p>
| 0 | 2016-10-14T16:42:49Z | [
"python",
"c++",
"python-2.7",
"linker",
"boost-python"
] |
Converting to a for loop | 40,034,749 | <p>I'm curious as to how this can be rewritten as a for loop? </p>
<pre><code>def decode (lst):
i=0
result=[]
while i<len(lst):
result+=([lst[i]]*lst[i+1])
i+=2
return(result)
print(decode([4,6,2,1,9,5,5,2,4,2]))
</code></pre>
| -2 | 2016-10-14T04:04:05Z | 40,034,856 | <p>Loop would look like:</p>
<pre><code>for x in range(0, len(lst), 2):
result+=(lst[i]*lst[i+1])
</code></pre>
<p>You may also use <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">list comprehension</a> and simplify this.</p>
<p>Refer: <a href="https://wiki.python.org/moin/ForLoop" rel="nofollow">For Loop</a></p>
| 0 | 2016-10-14T04:18:50Z | [
"python",
"loops",
"for-loop",
"while-loop"
] |
Converting to a for loop | 40,034,749 | <p>I'm curious as to how this can be rewritten as a for loop? </p>
<pre><code>def decode (lst):
i=0
result=[]
while i<len(lst):
result+=([lst[i]]*lst[i+1])
i+=2
return(result)
print(decode([4,6,2,1,9,5,5,2,4,2]))
</code></pre>
| -2 | 2016-10-14T04:04:05Z | 40,034,861 | <p>Assuming that this is Python code (as it looks like) you can just specify the step in the range function.</p>
<pre><code>def decode (lst):
result = []
#More common syntax if not using python for(i = 0; i < len(lst); i += 2):
for i in range(0, len(lst), 2):
result += ([lst[i]] * lst[i+1])
return result
print(decode([4,6,2,1,9,5,5,2,4,2]))
</code></pre>
<p>You will also want to add some error checking to make sure that your array has an even number of elements or this and your original example will fail.</p>
| 0 | 2016-10-14T04:19:42Z | [
"python",
"loops",
"for-loop",
"while-loop"
] |
django - How to customise Model save method when a specified field is changed | 40,034,780 | <p>I have a model, let's save A, the definition is as below:</p>
<pre><code>class A(models.Model):
name = models.CharField('name', max_length=10)
enabled = models.BooleanField('enabled', default=False)
field1 = models.CharField('field1', max_length=10)
field2 = models.CharField('field2', max_length=10)
field3 = models.CharField('field3', max_length=10)
parent = models.ForeignKey('self', null=True, blank=True) # hierarchy
</code></pre>
<p>and some object instances of this model, a, b, c, d. the hierarchy is represented by the parent field.</p>
<pre><code>a
|-- b
|-- c
|-- d
</code></pre>
<p>So, what I need to do is, when <code>b.enabled</code> change from <code>False</code> to <code>True</code>, or vice versa, I need to update <code>c.enabled</code> and <code>d.enabled</code> to value: <code>b.enabled</code>.</p>
<p>That's say, I need to broadcast the change to the children instances when the parent's <code>enabled</code> field was changed.</p>
<p>For performance consideration, I only need to broadcast the changes when <code>enabled</code> field is really changed. And don't want to always update the child instance whenever the parent is save, e.g. only updating field1 or field2.</p>
<p>So, do anyone knows, what is the best way to implement this logic? Thanks in advance.</p>
| 0 | 2016-10-14T04:08:10Z | 40,034,868 | <p>In short â no. But you can do it manually overloading the save method.</p>
<pre><code>class B(models.Model):
...
def save(self, *args, **kwargs):
if self.pk is not None:
original = B.objects.get(pk=self.pk)
if original.enabled != self.enabled:
C.enabled = self.enabled
C.save()
D.enabled = self.enabled
D.save()
super(B, self).save(*args, **kw)
</code></pre>
| 1 | 2016-10-14T04:20:38Z | [
"python",
"django",
"save"
] |
django - How to customise Model save method when a specified field is changed | 40,034,780 | <p>I have a model, let's save A, the definition is as below:</p>
<pre><code>class A(models.Model):
name = models.CharField('name', max_length=10)
enabled = models.BooleanField('enabled', default=False)
field1 = models.CharField('field1', max_length=10)
field2 = models.CharField('field2', max_length=10)
field3 = models.CharField('field3', max_length=10)
parent = models.ForeignKey('self', null=True, blank=True) # hierarchy
</code></pre>
<p>and some object instances of this model, a, b, c, d. the hierarchy is represented by the parent field.</p>
<pre><code>a
|-- b
|-- c
|-- d
</code></pre>
<p>So, what I need to do is, when <code>b.enabled</code> change from <code>False</code> to <code>True</code>, or vice versa, I need to update <code>c.enabled</code> and <code>d.enabled</code> to value: <code>b.enabled</code>.</p>
<p>That's say, I need to broadcast the change to the children instances when the parent's <code>enabled</code> field was changed.</p>
<p>For performance consideration, I only need to broadcast the changes when <code>enabled</code> field is really changed. And don't want to always update the child instance whenever the parent is save, e.g. only updating field1 or field2.</p>
<p>So, do anyone knows, what is the best way to implement this logic? Thanks in advance.</p>
| 0 | 2016-10-14T04:08:10Z | 40,035,144 | <p>The best way to do this is using django signals <a href="https://docs.djangoproject.com/es/1.10/ref/signals/" rel="nofollow">https://docs.djangoproject.com/es/1.10/ref/signals/</a></p>
<p>You will call the method change_status when your model call the method <code>save()</code></p>
<pre><code>from django.db.models.signals import pre_save
def change_status(sender, instance, **kwargs):
# instance object is the model that you have called the method save
a = A.objects.get(id=instance.id) # or B or C model
if instance.enable:
a.enable = False
# my code.....
pre_save.connect(change_status, sender=A)
# sender is the model that will be called every time you call the method save
</code></pre>
<p>And That's it
Remember that the object instance is your model before be changed, so
if you have <code>a.enable=True</code> and call the method <code>save()</code> in change_status signal you can make a query without this change of <code>a.enable=True</code>
<code>intance.enable >> True</code>, <code>a.enable >> False</code> because a is not saved yet.</p>
| 1 | 2016-10-14T04:52:14Z | [
"python",
"django",
"save"
] |
Convert strings of assignments to dicts in Python | 40,034,846 | <p>I have the following strings - they are assignment commands:</p>
<pre><code>lnodenum = 134241
d1 = 0.200000
jobname = 'hcalfzp'
</code></pre>
<p>Is there a way to convert this string, containing variables and values, to keys and values of a dictionary? It'd be equivalent to executing the below command:</p>
<pre><code>my_dict = dict(lnodenum = 134241, d1 = 0.200000, jobname = 'hcalfzp')
</code></pre>
<p>I guess this is one way to do it:</p>
<pre><code>my_str = """lnodenum = 134241
d1 = 0.200000
jobname = 'hcalfzp' """
exec('my_dict = dict(%s)' % ','.join(my_str.split('\n')))
</code></pre>
<p>Not sure whether anyone would think of a more concise way?</p>
<p>Note: I am using my own code for scientific computing, so I don't mind having code with safety concerns like malicious input data. But, I do prefer to have code that is shorter and easier to read :)</p>
| 0 | 2016-10-14T04:17:41Z | 40,034,883 | <p>There's no need for <code>exec</code>. Just use a regular assignment with the <code>dict</code> function.</p>
<pre><code>my_str = """lnodenum = 134241
d1 = 0.200000
jobname = 'hcalfzp' """
my_dict = dict(pair for pair in (line.strip().split(' = ') for line in my_str.splitlines()))
</code></pre>
<p>Result:</p>
<pre><code>>>> my_dict
{'d1': '0.200000', 'lnodenum': '134241', 'jobname': "'hcalfzp'"}
</code></pre>
<p>Or, if you'd like to parse each object, use <code>ast.literal_eval</code> with a comprehension:</p>
<pre><code>import ast
my_dict = {k:ast.literal_eval(v) for k,v in (line.strip().split(' = ') for line in my_str.splitlines())}
</code></pre>
<p>Result:</p>
<pre><code>>>> my_dict
{'d1': 0.2, 'lnodenum': 134241, 'jobname': 'hcalfzp'}
</code></pre>
| 2 | 2016-10-14T04:22:37Z | [
"python",
"dictionary"
] |
Heroku Django Migrate Not Working | 40,034,892 | <p>I am in my way learning python with django, and when I tried to sync with Heroku, there's an error showing I haven't migrated them yet. I am pretty sure have done it, but the console still saying so.</p>
<p>Iam sure I left an obvious part. But still can't find which one.</p>
<p><a href="https://i.stack.imgur.com/QJeGg.jpg" rel="nofollow">This image reflected exactly what I am talking about</a></p>
| 0 | 2016-10-14T04:24:02Z | 40,037,028 | <p>You cannot use sqlite on Heroku. You must use the postgres add-on.</p>
<p>Sqlite stores its db on the filesystem, but on Heroku the filesystem is ephemeral and not shared between dynos. Running a command spins up a whole new dyno, with its own database file which is migrated, but then thrown away. The next command - or the web dyno itself - won't see that db.</p>
| 0 | 2016-10-14T07:08:50Z | [
"python",
"django",
"heroku"
] |
How to make replacement in python's dict? | 40,034,950 | <p>The goal I want to achieve is to exchange all items whose form is <code>#item_name#</code> to the from <code>(item_value)</code> in the dict. I use two <code>dict</code> named <code>test1</code> and <code>test2</code> to test my function. Here is the code:</p>
<pre><code>test1={'integer_set': '{#integer_list#?}', 'integer_list': '#integer_range#(?,#integer_range#)*', 'integer_range': '#integer#(..#integer#)?', 'integer': '[+-]?\\d+'}
test2={'b': '#a#', 'f': '#e#', 'c': '#b#', 'e': '#d#', 'd': '#c#', 'g': '#f#', 'a': 'correct'}
def change(pat_dict:{str:str}):
print('Expanding: ',pat_dict)
num=0
while num<len(pat_dict):
inv_pat_dict = {v: k for k, v in pat_dict.items()}
for value in pat_dict.values():
for key in pat_dict.keys():
if key in value:
repl='#'+key+'#'
repl2='('+pat_dict[key]+')'
value0=value.replace(repl,repl2)
pat_dict[inv_pat_dict[value]]=value0
num+=1
print('Result: ',pat_dict)
change(test1)
change(test2)
</code></pre>
<p>sometimes I can get correct result like:</p>
<pre><code>Expanding: {'integer': '[+-]?\\d+', 'integer_list': '#integer_range#(?,#integer_range#)*', 'integer_set': '{#integer_list#?}', 'integer_range': '#integer#(..#integer#)?'}
Result: {'integer': '[+-]?\\d+', 'integer_list': '(([+-]?\\d+)(..([+-]?\\d+))?)(?,(([+-]?\\d+)(..([+-]?\\d+))?))*', 'integer_set': '{((([+-]?\\d+)(..([+-]?\\d+))?)(?,(([+-]?\\d+)(..([+-]?\\d+))?))*)?}', 'integer_range': '([+-]?\\d+)(..([+-]?\\d+))?'}
Expanding: {'c': '#b#', 'f': '#e#', 'e': '#d#', 'b': '#a#', 'g': '#f#', 'd': '#c#', 'a': 'correct'}
Result: {'c': '((correct))', 'f': '(((((correct)))))', 'e': '((((correct))))', 'b': '(correct)', 'g': '((((((correct))))))', 'd': '(((correct)))', 'a': 'correct'}
</code></pre>
<p>But most of time I get wrong results like that:</p>
<pre><code>Expanding: {'integer_range': '#integer#(..#integer#)?', 'integer': '[+-]?\\d+', 'integer_set': '{#integer_list#?}', 'integer_list': '#integer_range#(?,#integer_range#)*'}
Result: {'integer_range': '([+-]?\\d+)(..([+-]?\\d+))?', 'integer': '[+-]?\\d+', 'integer_set': '{(#integer_range#(?,#integer_range#)*)?}', 'integer_list': '#integer_range#(?,#integer_range#)*'}
Expanding: {'f': '#e#', 'a': 'correct', 'd': '#c#', 'g': '#f#', 'b': '#a#', 'c': '#b#', 'e': '#d#'}
Result: {'f': '(((((correct)))))', 'a': 'correct', 'd': '(((correct)))', 'g': '((((((correct))))))', 'b': '(correct)', 'c': '((correct))', 'e': '((((correct))))'}
</code></pre>
<p>How could I update my code to achieve my goal?</p>
| 3 | 2016-10-14T04:30:43Z | 40,035,729 | <p>Your problem is caused by the fact that python dictionaries are unordered. Try using a <a href="https://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="nofollow">OrderedDict</a> instead of <code>dict</code> and you should be fine. The OrderedDict works just like a normal <code>dict</code> but with ordering retained, at a small performance cost.</p>
<p>Note that while you could create an OrderedDict from a dict literal (like I did here at first), that dict would be unordered, so the ordering might not be guaranteed. Using a list of <code>(key, value)</code> pairs preserves the ordering in all cases.</p>
<pre><code>from collections import OrderedDict
test1=OrderedDict([('integer_set', '{#integer_list#?}'), ('integer_list', '#integer_range#(?,#integer_range#)*'), ('integer_range', '#integer#(..#integer#)?'), ('integer', '[+-]?\\d+')])
test2=OrderedDict([('b', '#a#'), ('f', '#e#'), ('c', '#b#'), ('e', '#d#'), ('d', '#c#'), ('g', '#f#'), ('a', 'correct')])
def change(pat_dict:{str:str}):
print('Expanding: ',pat_dict)
num=0
while num<len(pat_dict):
inv_pat_dict = {v: k for k, v in pat_dict.items()}
for value in pat_dict.values():
for key in pat_dict.keys():
if key in value:
repl='#'+key+'#'
repl2='('+pat_dict[key]+')'
value0=value.replace(repl,repl2)
pat_dict[inv_pat_dict[value]]=value0
num+=1
print('Result: ',pat_dict)
change(test1)
change(test2)
</code></pre>
| 0 | 2016-10-14T05:44:19Z | [
"python",
"dictionary"
] |
How to make replacement in python's dict? | 40,034,950 | <p>The goal I want to achieve is to exchange all items whose form is <code>#item_name#</code> to the from <code>(item_value)</code> in the dict. I use two <code>dict</code> named <code>test1</code> and <code>test2</code> to test my function. Here is the code:</p>
<pre><code>test1={'integer_set': '{#integer_list#?}', 'integer_list': '#integer_range#(?,#integer_range#)*', 'integer_range': '#integer#(..#integer#)?', 'integer': '[+-]?\\d+'}
test2={'b': '#a#', 'f': '#e#', 'c': '#b#', 'e': '#d#', 'd': '#c#', 'g': '#f#', 'a': 'correct'}
def change(pat_dict:{str:str}):
print('Expanding: ',pat_dict)
num=0
while num<len(pat_dict):
inv_pat_dict = {v: k for k, v in pat_dict.items()}
for value in pat_dict.values():
for key in pat_dict.keys():
if key in value:
repl='#'+key+'#'
repl2='('+pat_dict[key]+')'
value0=value.replace(repl,repl2)
pat_dict[inv_pat_dict[value]]=value0
num+=1
print('Result: ',pat_dict)
change(test1)
change(test2)
</code></pre>
<p>sometimes I can get correct result like:</p>
<pre><code>Expanding: {'integer': '[+-]?\\d+', 'integer_list': '#integer_range#(?,#integer_range#)*', 'integer_set': '{#integer_list#?}', 'integer_range': '#integer#(..#integer#)?'}
Result: {'integer': '[+-]?\\d+', 'integer_list': '(([+-]?\\d+)(..([+-]?\\d+))?)(?,(([+-]?\\d+)(..([+-]?\\d+))?))*', 'integer_set': '{((([+-]?\\d+)(..([+-]?\\d+))?)(?,(([+-]?\\d+)(..([+-]?\\d+))?))*)?}', 'integer_range': '([+-]?\\d+)(..([+-]?\\d+))?'}
Expanding: {'c': '#b#', 'f': '#e#', 'e': '#d#', 'b': '#a#', 'g': '#f#', 'd': '#c#', 'a': 'correct'}
Result: {'c': '((correct))', 'f': '(((((correct)))))', 'e': '((((correct))))', 'b': '(correct)', 'g': '((((((correct))))))', 'd': '(((correct)))', 'a': 'correct'}
</code></pre>
<p>But most of time I get wrong results like that:</p>
<pre><code>Expanding: {'integer_range': '#integer#(..#integer#)?', 'integer': '[+-]?\\d+', 'integer_set': '{#integer_list#?}', 'integer_list': '#integer_range#(?,#integer_range#)*'}
Result: {'integer_range': '([+-]?\\d+)(..([+-]?\\d+))?', 'integer': '[+-]?\\d+', 'integer_set': '{(#integer_range#(?,#integer_range#)*)?}', 'integer_list': '#integer_range#(?,#integer_range#)*'}
Expanding: {'f': '#e#', 'a': 'correct', 'd': '#c#', 'g': '#f#', 'b': '#a#', 'c': '#b#', 'e': '#d#'}
Result: {'f': '(((((correct)))))', 'a': 'correct', 'd': '(((correct)))', 'g': '((((((correct))))))', 'b': '(correct)', 'c': '((correct))', 'e': '((((correct))))'}
</code></pre>
<p>How could I update my code to achieve my goal?</p>
| 3 | 2016-10-14T04:30:43Z | 40,035,870 | <p>Try this one. Your problem is due to mutating starting dict. You need to change its copy.</p>
<pre><code>test1={'integer_set': '{#integer_list#?}', 'integer_list': '#integer_range#(?,#integer_range#)*', 'integer_range': '#integer#(..#integer#)?', 'integer': '[+-]?\\d+'}
test2={'b': '#a#', 'f': '#e#', 'c': '#b#', 'e': '#d#', 'd': '#c#', 'g': '#f#', 'a': 'correct'}
def change(d):
new_d = d.copy()
for k in d.keys():
for nk, v in new_d.items():
if k in v:
new_d[nk] = v.replace('#{}#'.format(k), '({})'.format(new_d[k]))
return new_d
test1 = change(test1)
test2 = change(test2)
</code></pre>
| 0 | 2016-10-14T05:55:36Z | [
"python",
"dictionary"
] |
Python: How to fix an [errno 2] when trying to open a text file? | 40,034,968 | <p>I'm trying to learn Python in my free time, and my textbook is not covering anything about my error, so I must've messed up badly somewhere. When I try to open and read a text file through notepad (on Windows) with my code, it produces the error. My code is:</p>
<pre><code>def getText():
infile = open("C:/Users/****/AppData/Local/Programs/Python/Python35-32/lib/book.txt" , "r")
allText = infile.read()
return allText
</code></pre>
<p>If it's necessary, here is the rest of my code so far:</p>
<pre><code>def inspectWord(theWord,wList,fList):
tempWord = theWord.rstrip("\"\'.,`;:-!")
tempWord = tempWord.lstrip("\"\'.,`;:-!")
tempWord = tempWord.lower()
if tempWord in wList:
tIndex = wList.index(tempWord)
fList[tIndex]+=1
else:
wList.append(tempWord)
fList.append(1)
def main():
myText = getText()
print(myText)
main()
</code></pre>
<p>I'd greatly appreciate any advice, etc.; I cannot find any help for this. Thanks to anyone who responds.</p>
| 0 | 2016-10-14T04:32:28Z | 40,035,260 | <p>To open a unicode file, you can do the following</p>
<pre><code>import codecs
def getText():
with codecs.open("C:/Users/****/AppData/Local/Programs/Python/Python35-32/lib/book.txt" , "r", encoding='utf8') as infile:
allText = infile.read()
return allText
</code></pre>
<p>See also: <a href="http://stackoverflow.com/questions/147741/character-reading-from-file-in-python">Character reading from file in Python</a></p>
| 1 | 2016-10-14T05:03:02Z | [
"python",
"error-handling"
] |
Python: How to fix an [errno 2] when trying to open a text file? | 40,034,968 | <p>I'm trying to learn Python in my free time, and my textbook is not covering anything about my error, so I must've messed up badly somewhere. When I try to open and read a text file through notepad (on Windows) with my code, it produces the error. My code is:</p>
<pre><code>def getText():
infile = open("C:/Users/****/AppData/Local/Programs/Python/Python35-32/lib/book.txt" , "r")
allText = infile.read()
return allText
</code></pre>
<p>If it's necessary, here is the rest of my code so far:</p>
<pre><code>def inspectWord(theWord,wList,fList):
tempWord = theWord.rstrip("\"\'.,`;:-!")
tempWord = tempWord.lstrip("\"\'.,`;:-!")
tempWord = tempWord.lower()
if tempWord in wList:
tIndex = wList.index(tempWord)
fList[tIndex]+=1
else:
wList.append(tempWord)
fList.append(1)
def main():
myText = getText()
print(myText)
main()
</code></pre>
<p>I'd greatly appreciate any advice, etc.; I cannot find any help for this. Thanks to anyone who responds.</p>
| 0 | 2016-10-14T04:32:28Z | 40,035,396 | <p>First of all, I recommend you to use relative path, not absolute path. It is simpler and will make your life easier especially now that you just started to learn Python. If you know how to deal with commandline, run a new commandline and move to the directory where your source code is located. Make a new text file there and now you can do something like</p>
<pre><code> f = open("myfile.txt")
</code></pre>
<p><br/></p>
<p>Your error indicates that there is something wrong with path you passed to builtin function <b>open</b>. Try this in an interactive mode,</p>
<pre><code>>> import os
>> os.path.exists("C:/Users/****/AppData/Local/Programs/Python/Python35-32/lib/book.txt")
</code></pre>
<p>If this returns False, there is nothing wrong with your <b>getText</b> fuction. Just pass a correct path to <b>open</b> function.</p>
| 0 | 2016-10-14T05:16:20Z | [
"python",
"error-handling"
] |
How to get element-wise matrix multiplication (Hadamard product) in numpy? | 40,034,993 | <p>I have two matrices </p>
<pre><code>a = [[1,2][3,4]]
b = [[5,6][7,8]]
</code></pre>
<p>I want to get the element-wise prodcut which will be <code>[[1*5,2*6][3*7,4*8]]</code> equals to </p>
<p><code>[[5,12][21,32]]</code></p>
<p>I tried with numpy </p>
<pre><code>print(np.dot(x,y))
</code></pre>
<p>and</p>
<pre><code>print(x*y)
</code></pre>
<p>result: <code>[[19 22][43 50]]</code></p>
<p>which gives me the matrix multiplication result not element-wise product. How can I get the the element-wise product aka. Hadamard product using built-in functions ?</p>
| 0 | 2016-10-14T04:35:47Z | 40,035,077 | <p>just do this:</p>
<pre><code>import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
a * b
</code></pre>
| 3 | 2016-10-14T04:44:22Z | [
"python",
"numpy",
"matrix",
"matrix-multiplication",
"elementwise-operations"
] |
How to get element-wise matrix multiplication (Hadamard product) in numpy? | 40,034,993 | <p>I have two matrices </p>
<pre><code>a = [[1,2][3,4]]
b = [[5,6][7,8]]
</code></pre>
<p>I want to get the element-wise prodcut which will be <code>[[1*5,2*6][3*7,4*8]]</code> equals to </p>
<p><code>[[5,12][21,32]]</code></p>
<p>I tried with numpy </p>
<pre><code>print(np.dot(x,y))
</code></pre>
<p>and</p>
<pre><code>print(x*y)
</code></pre>
<p>result: <code>[[19 22][43 50]]</code></p>
<p>which gives me the matrix multiplication result not element-wise product. How can I get the the element-wise product aka. Hadamard product using built-in functions ?</p>
| 0 | 2016-10-14T04:35:47Z | 40,035,266 | <p>Try this,</p>
<pre><code>import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
np.multiply(a,b)
</code></pre>
<p><strong>Result</strong> </p>
<pre><code>array([[ 5, 12],
[21, 32]])
</code></pre>
| 3 | 2016-10-14T05:04:28Z | [
"python",
"numpy",
"matrix",
"matrix-multiplication",
"elementwise-operations"
] |
Finding string in the format of TEXT-###, e.g SFS-444 inside of another string | 40,035,002 | <p>Pretty much as the statement states, I'm trying to figure out how to find text that follows this format TEXT-### inside of another string. However, there may be a lot of words or multiple numbers, such as,</p>
<pre><code>FRS-44215
SLMP-44
AG-1
</code></pre>
<p>So for example I have this text.</p>
<pre><code>"Lorem ipsum dolor sit amet, adversarium suscipiantur
has ea, duo at alia assum, eu ius hinc
aliquip percipitur SGF-7852 Nec ne
nisl duis volutpat"
</code></pre>
<p>The code would pick out <code>SGF-7852</code></p>
| 0 | 2016-10-14T04:37:04Z | 40,035,060 | <p>Use a regular expression to define the pattern that you are looking for, and then search the string for it.</p>
<pre><code>>>> s = '''"Lorem ipsum dolor sit amet, adversarium suscipiantur
... has ea, duo at alia assum, eu ius hinc
... aliquip percipitur SGF-7852 Nec ne
... nisl duis volutpat"'''
>>> e = r'[A-Z]+-\d+'
>>> import re
>>> re.findall(e, s)
['SGF-7852']
</code></pre>
<p>Here the pattern is:</p>
<ul>
<li><code>[A-Z]+</code> (one or more capital letters)</li>
<li><code>-</code> followed by a dash</li>
<li><code>\d+</code> followed by one or more numbers</li>
</ul>
| 1 | 2016-10-14T04:43:06Z | [
"python",
"string",
"subset"
] |
Unintended Notched Boxplot from Matplotlib, Error from Seaborn | 40,035,048 | <p>Using sklearn, and tried to do a boxplot using matplotlib. </p>
<pre><code>nps = np.array(all_s)
npd = [dd for dd in all_d]
plt.boxplot(nps.T, npd)
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/X6RoK.png" rel="nofollow"><img src="https://i.stack.imgur.com/X6RoK.png" alt="enter image description here"></a></p>
<p>But it comes out notched, and the upper or lower bounds turn out odd. Also, when I try to plot it in Seaborn, I get the following error: <code>Buffer has wrong number of dimensions (expected 1, got 2)</code>
What am I missing here? </p>
<p>Edit: added data</p>
<pre><code>all_d = range(1,11)
all_s =
[[0.31111111111111112,
0.38333333333333336,
0.2722222222222222,
0.29999999999999999,
0.32222222222222224,
0.32777777777777778,
0.3888888888888889,
0.36312849162011174,
0.37430167597765363,
0.37430167597765363],
[0.57222222222222219,
0.6333333333333333,
0.6166666666666667,
0.62777777777777777,
0.68333333333333335,
0.62777777777777777,
0.69444444444444442,
0.61452513966480449,
0.6033519553072626,
0.6033519553072626],
[0.73333333333333328,
0.82222222222222219,
0.68888888888888888,
0.7055555555555556,
0.77777777777777779,
0.73333333333333328,
0.81666666666666665,
0.73743016759776536,
0.72625698324022347,
0.72067039106145248],
[0.81666666666666665,
0.89444444444444449,
0.87222222222222223,
0.87777777777777777,
0.87777777777777777,
0.78888888888888886,
0.85555555555555551,
0.84916201117318435,
0.84916201117318435,
0.82681564245810057],
[0.90555555555555556,
0.93888888888888888,
0.87777777777777777,
0.91666666666666663,
0.90555555555555556,
0.87222222222222223,
0.90555555555555556,
0.88268156424581001,
0.87709497206703912,
0.8994413407821229],
[0.89444444444444449,
0.97222222222222221,
0.83888888888888891,
0.91666666666666663,
0.89444444444444449,
0.84444444444444444,
0.92777777777777781,
0.92737430167597767,
0.8938547486033519,
0.92178770949720668],
[0.90555555555555556,
0.96111111111111114,
0.93888888888888888,
0.91666666666666663,
0.91666666666666663,
0.90000000000000002,
0.93333333333333335,
0.95530726256983245,
0.8994413407821229,
0.92737430167597767],
[0.90555555555555556,
0.96111111111111114,
0.92222222222222228,
0.92222222222222228,
0.91666666666666663,
0.93888888888888888,
0.93333333333333335,
0.96648044692737434,
0.92737430167597767,
0.92737430167597767],
[0.93333333333333335,
0.97777777777777775,
0.94999999999999996,
0.93888888888888888,
0.94444444444444442,
0.97777777777777775,
0.94999999999999996,
0.98882681564245811,
0.95530726256983245,
0.94413407821229045],
[0.91666666666666663,
0.97777777777777775,
0.94999999999999996,
0.94444444444444442,
0.92777777777777781,
0.98333333333333328,
0.94999999999999996,
0.97765363128491622,
0.96089385474860334,
0.94413407821229045]]
</code></pre>
| 0 | 2016-10-14T04:41:22Z | 40,035,132 | <p>The second argument to <code>boxplot</code> is <code>notch</code>. By passing a nonempty list, you're passing a true value, so notches are shown. I'm not sure what your intent is with passing <code>npd</code> there.</p>
| 2 | 2016-10-14T04:50:25Z | [
"python",
"matplotlib",
"machine-learning",
"scikit-learn",
"seaborn"
] |
Unintended Notched Boxplot from Matplotlib, Error from Seaborn | 40,035,048 | <p>Using sklearn, and tried to do a boxplot using matplotlib. </p>
<pre><code>nps = np.array(all_s)
npd = [dd for dd in all_d]
plt.boxplot(nps.T, npd)
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/X6RoK.png" rel="nofollow"><img src="https://i.stack.imgur.com/X6RoK.png" alt="enter image description here"></a></p>
<p>But it comes out notched, and the upper or lower bounds turn out odd. Also, when I try to plot it in Seaborn, I get the following error: <code>Buffer has wrong number of dimensions (expected 1, got 2)</code>
What am I missing here? </p>
<p>Edit: added data</p>
<pre><code>all_d = range(1,11)
all_s =
[[0.31111111111111112,
0.38333333333333336,
0.2722222222222222,
0.29999999999999999,
0.32222222222222224,
0.32777777777777778,
0.3888888888888889,
0.36312849162011174,
0.37430167597765363,
0.37430167597765363],
[0.57222222222222219,
0.6333333333333333,
0.6166666666666667,
0.62777777777777777,
0.68333333333333335,
0.62777777777777777,
0.69444444444444442,
0.61452513966480449,
0.6033519553072626,
0.6033519553072626],
[0.73333333333333328,
0.82222222222222219,
0.68888888888888888,
0.7055555555555556,
0.77777777777777779,
0.73333333333333328,
0.81666666666666665,
0.73743016759776536,
0.72625698324022347,
0.72067039106145248],
[0.81666666666666665,
0.89444444444444449,
0.87222222222222223,
0.87777777777777777,
0.87777777777777777,
0.78888888888888886,
0.85555555555555551,
0.84916201117318435,
0.84916201117318435,
0.82681564245810057],
[0.90555555555555556,
0.93888888888888888,
0.87777777777777777,
0.91666666666666663,
0.90555555555555556,
0.87222222222222223,
0.90555555555555556,
0.88268156424581001,
0.87709497206703912,
0.8994413407821229],
[0.89444444444444449,
0.97222222222222221,
0.83888888888888891,
0.91666666666666663,
0.89444444444444449,
0.84444444444444444,
0.92777777777777781,
0.92737430167597767,
0.8938547486033519,
0.92178770949720668],
[0.90555555555555556,
0.96111111111111114,
0.93888888888888888,
0.91666666666666663,
0.91666666666666663,
0.90000000000000002,
0.93333333333333335,
0.95530726256983245,
0.8994413407821229,
0.92737430167597767],
[0.90555555555555556,
0.96111111111111114,
0.92222222222222228,
0.92222222222222228,
0.91666666666666663,
0.93888888888888888,
0.93333333333333335,
0.96648044692737434,
0.92737430167597767,
0.92737430167597767],
[0.93333333333333335,
0.97777777777777775,
0.94999999999999996,
0.93888888888888888,
0.94444444444444442,
0.97777777777777775,
0.94999999999999996,
0.98882681564245811,
0.95530726256983245,
0.94413407821229045],
[0.91666666666666663,
0.97777777777777775,
0.94999999999999996,
0.94444444444444442,
0.92777777777777781,
0.98333333333333328,
0.94999999999999996,
0.97765363128491622,
0.96089385474860334,
0.94413407821229045]]
</code></pre>
| 0 | 2016-10-14T04:41:22Z | 40,035,348 | <p>I ended up figuring it out! Thanks to BrenBarn for pointing out that the second argument of <code>.boxplot</code> is <code>notch</code>. I did the following: </p>
<pre><code>nps = np.array(all_s)
npd = [dd for dd in all_d]
box=sns.boxplot(data=nps.T)
box.set_xticklabels(npd)
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/cfnra.png" rel="nofollow"><img src="https://i.stack.imgur.com/cfnra.png" alt="enter image description here"></a></p>
| 0 | 2016-10-14T05:11:55Z | [
"python",
"matplotlib",
"machine-learning",
"scikit-learn",
"seaborn"
] |
Django django.test django.db.models.fields.related_descriptors.ManyRelatedManager | 40,035,240 | <p>Please assert type: 'django.db.models.fields.related_descriptors.ManyRelatedManager'. </p>
<p>In other words, how to import the module in order to assert that the field 'user.groups' is of type 'django.db.models.fields.related_descriptors.ManyRelatedManager'?</p>
<pre><code>from django.db.models.fields import related_descriptors
# AttributeError: 'module' object has no attribute 'ManyRelatedManager'
self.assertIsInstance(user.groups, related_descriptors.ManyRelatedManager)
print(type(dummy_user.groups)) # <class 'django.db.models.fields.related_descriptors.ManyRelatedManager'>
</code></pre>
<p>Here's the error:
AttributeError: 'module' object has no attribute 'ManyRelatedManager</p>
<p>Thanks</p>
| 0 | 2016-10-14T05:01:52Z | 40,036,963 | <p>You cannot make such an assertion on <code>user.groups</code> and <code>related_descriptors.ManyRelatedManager</code>. </p>
<p>The <code>ManyRelatedManager</code> class is not accessible using import like <code>from django.db.models.fields import related_descriptors</code> because if you look at the source code of django, the <code>ManyRelatedManager</code> lives inside of <code>create_forward_many_to_many_manager</code> function.</p>
<p>P.S. I do not see any reasons why you want to check the type of <code>user.groups</code>. It is always the same and tested by django tests already.</p>
| 1 | 2016-10-14T07:04:59Z | [
"python",
"django"
] |
Adding arrays to dataframe column | 40,035,276 | <p>Let's assume I have this dataframe <code>df</code>:</p>
<pre><code> 'Location' 'Rec ID' 'Duration'
0 Houston 126 17
1 Chicago 338 19.3
</code></pre>
<p>I would like to add a column with arrays corresponding to my recordings like:</p>
<pre><code> 'Location' 'Rec ID' 'Duration' 'Rec'
0 Houston 126 17 [0.2, 0.34, 0.45, ..., 0.28]
1 Chicago 338 19.3 [0.12, 0.3, 0.41, ..., 0.39]
</code></pre>
<p>When I do the <code>df.set_value()</code> command I get the following error:</p>
<p><strong><em>ValueError: setting an array element with a sequence.</em></strong></p>
| 3 | 2016-10-14T05:05:40Z | 40,035,425 | <p>I think the easiest is to assign <code>list</code> of <code>lists</code>, only you need same length of <code>lists</code> as <code>length</code> of <code>DataFrame</code>:</p>
<pre><code>arr = [[0.2, 0.34, 0.45, 0.28], [0.12, 0.3, 0.41, 0.39]]
print (arr)
[[0.2, 0.34, 0.45, 0.28], [0.12, 0.3, 0.41, 0.39]]
print (len(arr))
2
print (len(df))
2
df["'Rec'"] = arr
print (df)
'Location' 'Rec ID' 'Duration' 'Rec'
0 0 Houston 126 17.0 [0.2, 0.34, 0.45, 0.28]
1 1 Chicago 338 19.3 [0.12, 0.3, 0.41, 0.39]
</code></pre>
<hr>
<p>If use <code>numpy array</code>, first convert <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html" rel="nofollow"><code>tolist</code></a>:</p>
<pre><code>arr = np.array([[0.2, 0.34, 0.45, 0.28], [0.12, 0.3, 0.41, 0.39]])
print (arr)
[[ 0.2 0.34 0.45 0.28]
[ 0.12 0.3 0.41 0.39]]
df["'Rec'"] = arr.tolist()
print (df)
'Location' 'Rec ID' 'Duration' 'Rec'
0 0 Houston 126 17.0 [0.2, 0.34, 0.45, 0.28]
1 1 Chicago 338 19.3 [0.12, 0.3, 0.41, 0.39]
</code></pre>
| 1 | 2016-10-14T05:19:33Z | [
"python",
"arrays",
"pandas",
"dataframe"
] |
Is it possible to retrieve a Javascript file from a server? | 40,035,331 | <p>In Python, I can retrieve Javascript from an HTML document using the following code.</p>
<pre><code>import urllib2, jsbeautifier
from bs4 import BeautifulSoup
f = urllib2.urlopen("http://www.google.com.ph/")
soup = BeautifulSoup(f, "lxml")
script_raw = str(soup.script)
script_pretty = jsbeautifier.beautify(script_raw)
print(script_pretty)
</code></pre>
<p>But how about if the script comes from a Javascript file on the server, like:</p>
<pre><code><script src="some/directory/example.js" type="text/javascript">
</code></pre>
<p>Is it possible to retrieve "example.js"? If so, how?</p>
<p>Context: I'm examining the Javascript of phishing web pages.</p>
| 1 | 2016-10-14T05:10:13Z | 40,035,480 | <pre><code><script src="some/directory/example.js" type="text/javascript">
</code></pre>
<p>the code above will get <code>some/directory/example.js</code> from server
you just make folders and file structure follow the pattern above</p>
| 1 | 2016-10-14T05:23:47Z | [
"javascript",
"python"
] |
Is it possible to retrieve a Javascript file from a server? | 40,035,331 | <p>In Python, I can retrieve Javascript from an HTML document using the following code.</p>
<pre><code>import urllib2, jsbeautifier
from bs4 import BeautifulSoup
f = urllib2.urlopen("http://www.google.com.ph/")
soup = BeautifulSoup(f, "lxml")
script_raw = str(soup.script)
script_pretty = jsbeautifier.beautify(script_raw)
print(script_pretty)
</code></pre>
<p>But how about if the script comes from a Javascript file on the server, like:</p>
<pre><code><script src="some/directory/example.js" type="text/javascript">
</code></pre>
<p>Is it possible to retrieve "example.js"? If so, how?</p>
<p>Context: I'm examining the Javascript of phishing web pages.</p>
| 1 | 2016-10-14T05:10:13Z | 40,035,526 | <p>If you want to load at run time, like some part of your javascript is dependent on other javascript, then for loading javascript at run time, you can use require.js .</p>
| 0 | 2016-10-14T05:27:10Z | [
"javascript",
"python"
] |
Is it possible to retrieve a Javascript file from a server? | 40,035,331 | <p>In Python, I can retrieve Javascript from an HTML document using the following code.</p>
<pre><code>import urllib2, jsbeautifier
from bs4 import BeautifulSoup
f = urllib2.urlopen("http://www.google.com.ph/")
soup = BeautifulSoup(f, "lxml")
script_raw = str(soup.script)
script_pretty = jsbeautifier.beautify(script_raw)
print(script_pretty)
</code></pre>
<p>But how about if the script comes from a Javascript file on the server, like:</p>
<pre><code><script src="some/directory/example.js" type="text/javascript">
</code></pre>
<p>Is it possible to retrieve "example.js"? If so, how?</p>
<p>Context: I'm examining the Javascript of phishing web pages.</p>
| 1 | 2016-10-14T05:10:13Z | 40,035,535 | <p>The easiest way is to right click on that page in your browser, choose <code>page script</code>, click on that <code>.js</code> link, and it will be there.</p>
| 1 | 2016-10-14T05:27:36Z | [
"javascript",
"python"
] |
How do I convert float decimal to float octal/binary? | 40,035,361 | <p>I have been searched everywhere to find a way to convert float to octal or binary. I know about the <code>float.hex</code> and <code>float.fromhex</code>. Is theres a modules which can do the same work for octal/binary values?</p>
<p>For example: I have a float <code>12.325</code> and I should get float octal <code>14.246</code>. Tell me, how I can do this? Thanks in advance.</p>
| 2 | 2016-10-14T05:12:46Z | 40,050,134 | <p>You could write your own, if you only care about three decimal places then set n to 3:</p>
<pre><code>def frac_to_oct(f, n=4):
# store the number before the decimal point
whole = int(f)
rem = (f - whole) * 8
int_ = int(rem)
rem = (rem - int_) * 8
octals = [str(int_)]
count = 1
# loop until 8 * rem gives you a whole num or n times
while rem and count < n:
count += 1
int_ = int(rem)
rem = (rem - int_) * 8
octals.append(str(int_))
return float("{:o}.{}".format(whole, "".join(octals)))
</code></pre>
<p>Using your input <em>12.325</em>:</p>
<pre><code>In [9]: frac_to_oct(12.325)
Out[9]: 14.2463
In [10]: frac_to_oct(121212.325, 4)
Out[10]: 354574.2463
In [11]: frac_to_oct(0.325, 4)
Out[11]: 0.2463
In [12]: frac_to_oct(2.1, 4)
Out[12]: 2.0631
In [13]: frac_to_oct(0)
Out[13]: 0.0
In [14]: frac_to_oct(33)
Out[14]: 41.0
</code></pre>
| 1 | 2016-10-14T18:48:36Z | [
"python",
"binary",
"floating-point",
"octal"
] |
How do I convert float decimal to float octal/binary? | 40,035,361 | <p>I have been searched everywhere to find a way to convert float to octal or binary. I know about the <code>float.hex</code> and <code>float.fromhex</code>. Is theres a modules which can do the same work for octal/binary values?</p>
<p>For example: I have a float <code>12.325</code> and I should get float octal <code>14.246</code>. Tell me, how I can do this? Thanks in advance.</p>
| 2 | 2016-10-14T05:12:46Z | 40,050,158 | <p>Here's the solution, explanation below:</p>
<pre><code>def ToLessThanOne(num): # Change "num" into a decimal <1
while num > 1:
num /= 10
return num
def FloatToOctal(flo, places=8): # Flo is float, places is octal places
main, dec = str(flo).split(".") # Split into Main (integer component)
# and Dec (decimal component)
main, dec = int(main), int(dec) # Turn into integers
res = oct(main)[2::]+"." # Turn the integer component into an octal value
# while removing the "ox" that would normally appear ([2::])
# Also, res means result
# NOTE: main and dec are being recycled here
for x in range(places):
main, dec = str((ToLessThanOne(dec))*8).split(".") # main is integer octal
# component
# dec is octal point
# component
dec = int(dec) # make dec an integer
res += main # Add the octal num to the end of the result
return res # finally return the result
</code></pre>
<p>So you can do <code>print(FloatToOctal(12.325))</code> and it shall print out <code>14.246314631</code></p>
<p>Finally, if you want less octal places (decimal places but in octal) simply add the <code>places</code> argument: <code>print(FloatToOctal(12.325, 3))</code> which returns <code>14.246</code> as is correct according to this website: <a href="http://coderstoolbox.net/number/" rel="nofollow">http://coderstoolbox.net/number/</a></p>
| 0 | 2016-10-14T18:49:51Z | [
"python",
"binary",
"floating-point",
"octal"
] |
convert a list to dict with key equal to every unique item and value equal to the indices of the item in the list | 40,035,429 | <p>For example, I have a list of <code>a = ['a', 'b', 'a']</code>, what is the best code to convert it to <code>b = {'a': [0, 2], 'b': [1]}</code>?</p>
| 0 | 2016-10-14T05:19:45Z | 40,035,465 | <p>You can use <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a> with <code>list</code> default factory:</p>
<pre><code>>>> from collections import defaultdict
>>> a = ['a', 'b', 'a']
>>> res = defaultdict(list)
>>> for i, s in enumerate(a):
... res[s].append(i)
...
>>> res
defaultdict(<type 'list'>, {'a': [0, 2], 'b': [1]})
</code></pre>
<p>Parameter given to <code>defaultdict</code> is a function that will be called to provide initial value in case that given key doesn't exist. Since original list is being iterated once and time complexity of <code>list.append</code> is <strong>O(1)</strong> the total time complexity is <strong>O(n)</strong>.</p>
<p><strong>Update</strong> Performance comparison of different solutions:</p>
<pre><code>from collections import defaultdict
def test1(l):
b = dict.fromkeys(set(l), [])
for i, val in enumerate(l):
b[val] = b.get(val)+[i]
def test2(l):
res = defaultdict(list)
for i, s in enumerate(l):
res[s].append(i)
if __name__ == '__main__':
import timeit
print(timeit.timeit("test1(['a'] * 1000)", setup="from __main__ import test1", number=10))
print(timeit.timeit("test2(['a'] * 1000)", setup="from __main__ import test2", number=10))
</code></pre>
<p>Output:</p>
<pre><code>0.03234261799661908
0.000929353991523385
</code></pre>
| 3 | 2016-10-14T05:22:38Z | [
"python"
] |
convert a list to dict with key equal to every unique item and value equal to the indices of the item in the list | 40,035,429 | <p>For example, I have a list of <code>a = ['a', 'b', 'a']</code>, what is the best code to convert it to <code>b = {'a': [0, 2], 'b': [1]}</code>?</p>
| 0 | 2016-10-14T05:19:45Z | 40,035,525 | <pre><code>a = ['a', 'b', 'a']
b = dict.fromkeys(set(a), []) # {'a': [], 'b': []}
for i, val in enumerate(a):
b[val] = b.get(val)+[i]
print (b)
</code></pre>
<p>gives:</p>
<pre><code>{'a': [0, 2], 'b': [1]}
</code></pre>
| 2 | 2016-10-14T05:27:06Z | [
"python"
] |
Delete the row as soon as a column reaches a specific value | 40,035,446 | <p>If this be my model:</p>
<pre><code>class Entity(Base):
id = Column(Integer, primary_key=True)
count = Column(Integer, default=0)
</code></pre>
<p>I want to delete any rows that reach <code>count</code> value of 3 (or any number).
How can I do that?
should I implement such deletion in the Controller of my web application and every time <code>count</code> is incremented, I check if it's value is 3 or not? How should I care about the concurrent requests that are changing the value? What is the best solution? </p>
| 1 | 2016-10-14T05:21:28Z | 40,035,682 | <blockquote>
<p>Should I implement the deletion in the controller of my web application?</p>
</blockquote>
<p>Yes. You should implement it in your controller. Just make sure you have a view that will be able to access your <code>delete</code> function in the controller.</p>
<blockquote>
<p>Who [how] can I do that?</p>
</blockquote>
<p>Simple. In your controller, create a function that will handle the deletion. The delete function body should look like this:</p>
<pre><code>limit = 3 # The value of this variable is arbitrary.
Entity.query.filter(Entity.count == limit).delete()
# The two statements above can be simplified to
# Entity.query.filter(Entity.count == 3).delete()
db.session.commit()
</code></pre>
<p>Better yet, add a function parameter that will accept a value that will be the maximum value of a column in a row. It could look like this:</p>
<pre><code>def delete_entity(limit=3): # I set `limit` to 3 since that is what you have stated earlier in the question
Entity.query.filter(Entity.count == limit).delete()
db.session.commit()
</code></pre>
<blockquote>
<p>Every time count is incremented, I check if the value is 3 or not? What is the best solution?</p>
</blockquote>
<p>It depends on what you want your application to do.</p>
| -2 | 2016-10-14T05:40:02Z | [
"python",
"postgresql",
"concurrency",
"sqlalchemy",
"locking"
] |
Delete the row as soon as a column reaches a specific value | 40,035,446 | <p>If this be my model:</p>
<pre><code>class Entity(Base):
id = Column(Integer, primary_key=True)
count = Column(Integer, default=0)
</code></pre>
<p>I want to delete any rows that reach <code>count</code> value of 3 (or any number).
How can I do that?
should I implement such deletion in the Controller of my web application and every time <code>count</code> is incremented, I check if it's value is 3 or not? How should I care about the concurrent requests that are changing the value? What is the best solution? </p>
| 1 | 2016-10-14T05:21:28Z | 40,053,192 | <p>After sometime pondering and consulting with experts I figured out that solution to this matter is either implementing a lock in database or using redis. Since locking may cause performance problems in multitude requests, It's better to store the value of <code>count</code> in a redis database and try updating the <code>count</code> value in the object-relational database in specific periods of time.</p>
| 1 | 2016-10-14T23:04:07Z | [
"python",
"postgresql",
"concurrency",
"sqlalchemy",
"locking"
] |
Python connecting to an HTTP server | 40,035,567 | <p>In my program, I am trying to access <code>https://api.dropbox.com/1/oauth2/token</code>. In order to do that, I was trying to use <code>http.client.HTTPSConnection()</code>. However, I am receiving a 400 statement from the server, even though when I send the same request through my browser, I get an actual response:</p>
<p><code>{"error": "Call requires one of the following methods: POST, OPTIONS. Got GET."}</code></p>
<p>I believe that this happens for subdomains, since I also tested the function for <code>https://docs.python.org/3/</code>, and the result is very similar.</p>
<p>Here is my code (Python3):</p>
<pre><code>conn = http.client.HTTPSConnection('docs.python.org')
conn.request('get', '/3/')
response = conn.getresponse().read()
print(response)
</code></pre>
<p>How should I use the <code>http.client</code> library to send the proper request?</p>
| 0 | 2016-10-14T05:30:33Z | 40,064,234 | <p>TL;DR: Change the lowercase 'get' to uppercase 'GET' should resolve the problem.</p>
<p>The reason: according to section 5.1.1, <a href="https://www.w3.org/Protocols/rfc2616/rfc2616.txt" rel="nofollow">RFC2616</a>:</p>
<blockquote>
<p>The Method token indicates the method to be performed on the
resource identified by the Request-URI. The method is case-sensitive.</p>
</blockquote>
<p>RFC2616 also defined 8 methods which are "OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", and "CONNECT". All of them are uppercase.</p>
<p>We do know some HTTP clients like <code>python-requests</code> and <code>jQuery.ajax</code> also support lowercase methods but they are just not the standard way defined by the RFC for using those methods. To prevent issues, use uppercase ones first.</p>
| 2 | 2016-10-15T21:08:41Z | [
"python",
"http",
"dropbox"
] |
Python 3 Index Error | 40,035,724 | <p>Consider the following code:</p>
<pre><code>def anadist(string1, string2):
string1_list = []
string2_list = []
for i in range(len(string1)):
string1_list.append(string1[i])
for i in range(len(string2)):
string2_list.append(string2[i])
# Test returns for checking
# return (string1_list,string2_list)
# return len(string1_list)
# return len(string2_list)
for i in range(0,len(string1_list)):
try:
if (string1_list[i]) in string2_list:
com = string1_list.pop(i)
com_index = string2_list.index(com)
string2_list.pop(com_index)
else:
pass
except ValueError:
pass
return string1_list
def main():
str1 = input("Enter string #1 >>> ")
str2 = input("Enter string #2 >>> ")
result = anadist(str1, str2)
print(result)
#Boilerplate Check
if __name__ == "__main__":
main()
</code></pre>
<p>Running in Python 3.5.2 raises an IndexError:</p>
<pre><code>Traceback (most recent call last):
File "E:\CSE107L\Practice\anadist.py", line 34, in <module>
main()
File "E:\CSE107L\Practice\anadist.py", line 29, in main
result = anadist(str1, str2)
File "E:\CSE107L\Practice\anadist.py", line 15, in anadist
if (string1_list[i]) in string2_list:
IndexError: list index out of range
</code></pre>
<p>And I can't find what is going wrong. I wrote another code similar and that works:</p>
<pre><code>def main():
lst = [1,2,3,4,5]
lst2 = [5,6,7,8,9]
for i in range(len(lst)):
if lst[i] in lst2:
com = lst.pop(i)
lst2_index = lst2.index(com)
lst2.pop(lst2_index)
else:
pass
print(lst)
if __name__ == "__main__":
main()
</code></pre>
<p>I feel the error is coming from the way I am forming <code>string1_list</code>. This code is for how many steps it takes to form an anagram of a pair of words.</p>
| 0 | 2016-10-14T05:43:37Z | 40,035,798 | <p>In some cases, you are shortening <code>string_list1</code> while you're iterating over it:</p>
<pre><code>if (string1_list[i]) in string2_list:
com = string1_list.pop(i) # string1_list gets shorter here
</code></pre>
<p>However, your <code>range</code> doesn't change. It's still going to go from <code>0</code> until it counts up to the <em>original</em> length of <code>string1_list</code> (exclusive). This will cause the <code>IndexError</code> any time <code>string1_list.pop(i)</code> is called.</p>
<p>One possible solution would be to use a <code>while</code> loop instead:</p>
<pre><code>i = 0
while i < len(string1_list):
try:
if string1_list[i] in string2_list:
com = string1_list.pop(i)
com_index = string2_list.index(com)
string2_list.pop(com_index)
else:
pass
except ValueError:
pass
i += 1
</code></pre>
<p>This will cause the loop termination condition to be checked after each iteration. If you remove some elements from <code>string1_list</code>, it'll still be OK because the loop will terminate before <code>i</code> gets big enough to overrun the bounds of it's container.</p>
| 3 | 2016-10-14T05:50:07Z | [
"python",
"list",
"python-3.5",
"anagram"
] |
Python 3 Index Error | 40,035,724 | <p>Consider the following code:</p>
<pre><code>def anadist(string1, string2):
string1_list = []
string2_list = []
for i in range(len(string1)):
string1_list.append(string1[i])
for i in range(len(string2)):
string2_list.append(string2[i])
# Test returns for checking
# return (string1_list,string2_list)
# return len(string1_list)
# return len(string2_list)
for i in range(0,len(string1_list)):
try:
if (string1_list[i]) in string2_list:
com = string1_list.pop(i)
com_index = string2_list.index(com)
string2_list.pop(com_index)
else:
pass
except ValueError:
pass
return string1_list
def main():
str1 = input("Enter string #1 >>> ")
str2 = input("Enter string #2 >>> ")
result = anadist(str1, str2)
print(result)
#Boilerplate Check
if __name__ == "__main__":
main()
</code></pre>
<p>Running in Python 3.5.2 raises an IndexError:</p>
<pre><code>Traceback (most recent call last):
File "E:\CSE107L\Practice\anadist.py", line 34, in <module>
main()
File "E:\CSE107L\Practice\anadist.py", line 29, in main
result = anadist(str1, str2)
File "E:\CSE107L\Practice\anadist.py", line 15, in anadist
if (string1_list[i]) in string2_list:
IndexError: list index out of range
</code></pre>
<p>And I can't find what is going wrong. I wrote another code similar and that works:</p>
<pre><code>def main():
lst = [1,2,3,4,5]
lst2 = [5,6,7,8,9]
for i in range(len(lst)):
if lst[i] in lst2:
com = lst.pop(i)
lst2_index = lst2.index(com)
lst2.pop(lst2_index)
else:
pass
print(lst)
if __name__ == "__main__":
main()
</code></pre>
<p>I feel the error is coming from the way I am forming <code>string1_list</code>. This code is for how many steps it takes to form an anagram of a pair of words.</p>
| 0 | 2016-10-14T05:43:37Z | 40,035,803 | <p>Your issue is that you are mutating the <code>string1_list</code> within the <code>for</code> loop by performing <code>string1_list.pop(i)</code>. The length of the list is being reduced within the <code>for</code> loop by doing <code>string1_list.pop(i)</code>, but you are still iterating over the length of the original list. </p>
<p>Your second lot of code works only because you only <code>pop</code> on the last iteration of the loop.</p>
| 1 | 2016-10-14T05:50:25Z | [
"python",
"list",
"python-3.5",
"anagram"
] |
Python 3 Index Error | 40,035,724 | <p>Consider the following code:</p>
<pre><code>def anadist(string1, string2):
string1_list = []
string2_list = []
for i in range(len(string1)):
string1_list.append(string1[i])
for i in range(len(string2)):
string2_list.append(string2[i])
# Test returns for checking
# return (string1_list,string2_list)
# return len(string1_list)
# return len(string2_list)
for i in range(0,len(string1_list)):
try:
if (string1_list[i]) in string2_list:
com = string1_list.pop(i)
com_index = string2_list.index(com)
string2_list.pop(com_index)
else:
pass
except ValueError:
pass
return string1_list
def main():
str1 = input("Enter string #1 >>> ")
str2 = input("Enter string #2 >>> ")
result = anadist(str1, str2)
print(result)
#Boilerplate Check
if __name__ == "__main__":
main()
</code></pre>
<p>Running in Python 3.5.2 raises an IndexError:</p>
<pre><code>Traceback (most recent call last):
File "E:\CSE107L\Practice\anadist.py", line 34, in <module>
main()
File "E:\CSE107L\Practice\anadist.py", line 29, in main
result = anadist(str1, str2)
File "E:\CSE107L\Practice\anadist.py", line 15, in anadist
if (string1_list[i]) in string2_list:
IndexError: list index out of range
</code></pre>
<p>And I can't find what is going wrong. I wrote another code similar and that works:</p>
<pre><code>def main():
lst = [1,2,3,4,5]
lst2 = [5,6,7,8,9]
for i in range(len(lst)):
if lst[i] in lst2:
com = lst.pop(i)
lst2_index = lst2.index(com)
lst2.pop(lst2_index)
else:
pass
print(lst)
if __name__ == "__main__":
main()
</code></pre>
<p>I feel the error is coming from the way I am forming <code>string1_list</code>. This code is for how many steps it takes to form an anagram of a pair of words.</p>
| 0 | 2016-10-14T05:43:37Z | 40,035,808 | <p>Your second attempt works simply because a "match" is found only in the last element <code>5</code> and as such when you mutate your list <code>lst</code> it is during the <em>last iteration</em> and has no effect.</p>
<p>The problem with your first attempt is that you might remove from the beginning of the list. The counter doesn't get updated and at some point might reach a value that no longer exists in the list (it has been popped). Try running it with no matches in the input and see that it works.</p>
<p>In general, <em>don't mutate your list while iterating through it</em>. Instead of the: </p>
<pre><code>for i in range(len(lst)):
# mutate list
</code></pre>
<p>'idiom', you should opt for the: </p>
<pre><code>for i in list(list_object): # or for i in list_object[:]:
</code></pre>
<p>which makes a copy first and allows you to mutate the original <code>list_object</code> by keeping mutating and looping separate.</p>
| 1 | 2016-10-14T05:50:55Z | [
"python",
"list",
"python-3.5",
"anagram"
] |
How to create AMI at runtime using AWS Lambda? | 40,035,818 | <p>Scenario -
Running AWS EC2 with AutoScaling to host web servers. Code is hosted on BitBucket.</p>
<p>Requirements - </p>
<ol>
<li>Integrate BitBucket with CodeDeploy for automated deployments.</li>
<li>After every successful deployment, create AMI of the running healthy instance.</li>
<li>Create a new Launch Configuration for the new AMI.</li>
<li>Update existing AutoScaling group.</li>
</ol>
| 0 | 2016-10-14T05:51:47Z | 40,035,902 | <p>I went through above scenario and the challenging part was that Web Servers were running using IIS since it was a .NET app, which means I had to automated configuration part of .NET as well.</p>
<p>If you are also into similar situation, then I have written a post of that. Just click on the link below. It works for all kind of environmennts.</p>
<p><a href="http://www.kblearningacademy.com/using-aws-lambda-function-to-create-ami-at-runtime/" rel="nofollow">http://www.kblearningacademy.com/using-aws-lambda-function-to-create-ami-at-runtime/</a></p>
| 0 | 2016-10-14T05:57:42Z | [
"python",
"amazon-web-services",
"bitbucket",
"aws-lambda"
] |
Python and Pip not in sync | 40,035,830 | <p>I am working on a remote linux server with python 2.7.6 pre-installed. I want to <strong>upgrade to python 2.7.12</strong> (because I am not able to install some libraries on the 2.7.6 due to some <strong>ssl error</strong> shown below).</p>
<p>I downloaded and compiled from source and installed 2.7.12 and <code>python2.7</code> opens 2.7.12. However, I still get an update python version warning while using pip. It seems the pip has not synced with 2.7.12 and continues to serve 2.7.6 and I am not able to find other installations of pip in system.</p>
<p>I just want a working version of python2.7.x with pip/pip2/pip2.7 working properly.</p>
<pre><code> /usr/local/lib/python2.7/dist-packages/pip-8.1.2-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning.
SNIMissingWarning
/usr/local/lib/python2.7/dist-packages/pip-8.1.2-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
</code></pre>
| 1 | 2016-10-14T05:52:54Z | 40,036,183 | <p>Upgrade (and automatically reinstall) pip this way: </p>
<pre><code>/path/to/python2.7.12 -m pip install pip --upgrade
</code></pre>
<p>The <code>-m</code> flag loads the corresponding module, and in the case of pip will execute <code>pip</code> (thanks to <a href="https://docs.python.org/3/library/__main__.html" rel="nofollow">the power of the <code>__main__</code> module inside the package</a>).</p>
<p>After installation, your current <code>pip</code> should also be up-to-date.</p>
<hr>
<p>Alternatively, you could run </p>
<pre><code>/path/to/python2.7.12 /path/to/pip2 install pip --upgrade
</code></pre>
<hr>
<p>NB: be wary about which <code>pip</code> and <code>python2</code> you're running: there'll probably be a <code>/usr/bin/python</code> and /usr/bin/pip<code>next to the ones you installed in</code>/usr/local/<code>. The ones in</code>/usr/bin` should just be updated following the standard system updates, if at all.</p>
| 1 | 2016-10-14T06:15:33Z | [
"python",
"linux",
"python-2.7",
"pip"
] |
Python and Pip not in sync | 40,035,830 | <p>I am working on a remote linux server with python 2.7.6 pre-installed. I want to <strong>upgrade to python 2.7.12</strong> (because I am not able to install some libraries on the 2.7.6 due to some <strong>ssl error</strong> shown below).</p>
<p>I downloaded and compiled from source and installed 2.7.12 and <code>python2.7</code> opens 2.7.12. However, I still get an update python version warning while using pip. It seems the pip has not synced with 2.7.12 and continues to serve 2.7.6 and I am not able to find other installations of pip in system.</p>
<p>I just want a working version of python2.7.x with pip/pip2/pip2.7 working properly.</p>
<pre><code> /usr/local/lib/python2.7/dist-packages/pip-8.1.2-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning.
SNIMissingWarning
/usr/local/lib/python2.7/dist-packages/pip-8.1.2-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
</code></pre>
| 1 | 2016-10-14T05:52:54Z | 40,036,342 | <p>Thanks @Evert , just before looking into your solution I tried,</p>
<pre><code>curl -O https://bootstrap.pypa.io/get-pip.py
python27 get-pip.py
</code></pre>
<p>This fixed my issue and I was able to install libraries to <code>2.7.12</code> using <code>pip/pip2.7</code></p>
<p>I was earlier trying <code>python2.7 -m pip install package-name</code> and I was getting <code>pip not found</code>.</p>
| 0 | 2016-10-14T06:26:49Z | [
"python",
"linux",
"python-2.7",
"pip"
] |
python-RequestParser is not returning error when different datatype is sent in request | 40,035,872 | <p>I have created Flask application in that i am using RequestParser to check datatype of input fields like below</p>
<pre><code>parser = reqparse.RequestParser()
parser.add_argument('article_id',type=str,required=True, help='SUP-REQ-ARTICLEID')
parser.add_argument('description',type=str,required=True, help='SUP-REQ-DESCRIPTION')
parser.add_argument('userid',type=str,required=True, help='SUP-REQ-USERID')
</code></pre>
<p>my json input from postman is like below </p>
<pre><code>{
"article_id": 2,
"description":"some description",
"userid":1
}
</code></pre>
<p>so in json request first and third field is integer and in request parser the datatype i have mentioned as "str" </p>
<p>when i ran the application and send the request from postman -request is getting processed and not throwing any error in RequestParser validation </p>
| 1 | 2016-10-14T05:55:52Z | 40,036,127 | <p>At first, Postman creates a regular HTTP post from your data. And HTTP posts looks like this:</p>
<pre class="lang-none prettyprint-override"><code>article_id=2&description=some%20description&userid=1
</code></pre>
<p>There is no type information, that's plain old URL encoding. <em>Everything</em> is a string in a URL, with <code>&</code> and <code>=</code> as the separators.</p>
<p>All RequestParser can do is convert types for you, from string to something else. That's also why <code>type=str</code> is the default. The parser will simply give you strings for <code>article_id</code> and <code>userid</code> and that's it. </p>
<p>The errors occur when an argument <em>can't</em> be converted to the target type. Set <code>type=int</code> for <code>description</code> and it will give you an error.</p>
| 3 | 2016-10-14T06:12:17Z | [
"python",
"json",
"parsing",
"flask-restful"
] |
Python Script to SSH | 40,036,052 | <p>I am a beginner trying to do SSH writing a basic code, I have tried everything not able to debug this , My code is as follows :</p>
<pre><code>import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print ("1")
ssh.connect('196.5.5.6', username='abc', password='abc')
print ("2")
stdin, stdout, stderr = ssh.exec_command('show version')
print ("3")
output= stdout.readlines()
print ("4")
print(output)
</code></pre>
<p>Output I get is 1<br>
2<br>
3
<br>
At 4 it get's stuck somewhere , there is problem that I am not able to fetch the data , Please help anyone. Code just hangs at the output step. Everywhere the solution is totally same.</p>
| 1 | 2016-10-14T06:08:16Z | 40,036,398 | <p>You don't need to do <code>readlines(</code>) on <code>stdin</code>. You can print it directly. <code>readlines()</code> expect a file to be opened and read from the file. Whereas <code>stdin</code>, <code>stdout</code>, <code>stderr</code> are not files, rather a block of strings ( or string buffer used in paramiko channel). If you check the type of <code>stdin</code>, <code>stdout</code>, <code>stderr</code>, you will find <code><class 'paramiko.channel.ChannelFile'></code>, which are not exactly files, but are file like objects created to store the buffers in paramiko channel. </p>
<pre><code>import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print 1
ssh.connect('196.5.5.6', username='abc', password='abc')
print 2
stdin, stdout, stderr = ssh.exec_command('show version')
print 3
output= stdin
print 4
print(output)
print '---', stdout
print '---==', stderr
</code></pre>
| 0 | 2016-10-14T06:31:14Z | [
"python",
"shell",
"ssh"
] |
Python Script to SSH | 40,036,052 | <p>I am a beginner trying to do SSH writing a basic code, I have tried everything not able to debug this , My code is as follows :</p>
<pre><code>import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print ("1")
ssh.connect('196.5.5.6', username='abc', password='abc')
print ("2")
stdin, stdout, stderr = ssh.exec_command('show version')
print ("3")
output= stdout.readlines()
print ("4")
print(output)
</code></pre>
<p>Output I get is 1<br>
2<br>
3
<br>
At 4 it get's stuck somewhere , there is problem that I am not able to fetch the data , Please help anyone. Code just hangs at the output step. Everywhere the solution is totally same.</p>
| 1 | 2016-10-14T06:08:16Z | 40,036,448 | <p>You should enter commands try this </p>
<pre><code>import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print ("1")
ssh.connect('ip', username='user', password='pass')
print ("2")
stdin, stdout, stderr = ssh.exec_command('show version')
print ("3")
stdin,stdout,stderr = ssh.exec_command("ls /")
print stdout.readlines()
</code></pre>
| 0 | 2016-10-14T06:34:13Z | [
"python",
"shell",
"ssh"
] |
Spark - PySpark sql error | 40,036,060 | <p>I have a simple pyspark code but i can't run it. I try to run it on Ubuntu system and I use PyCharm IDE. I would like to connect to Oracle XE Database and I want to print my test table. </p>
<p>Here comes my spark python code: </p>
<pre><code>from pyspark import SparkContext
from pyspark.sql import SQLContext
sc = SparkContext()
sqlContext = SQLContext(sc)
demoDf = sqlContext.read.format("jdbc").options(
url="jdbc:oracle:thin:@10.10.10.10:1521:XE",
driver="oracle.jdbc.driver.OracleDriver",
table="tst_table",
user="xxx",
password="xxx").load()
demoDf.show()
</code></pre>
<p>And this is my trace:</p>
<pre><code>Traceback (most recent call last):
File "/home/kebodev/PycharmProjects/spark_tst/cucc_spark.py", line 13, in <module>
password="xxx").load()
File "/home/kebodev/spark-2.0.1/python/pyspark/sql/readwriter.py", line 153, in load
return self._df(self._jreader.load())
File "/home/kebodev/spark-2.0.1/python/lib/py4j-0.10.3-src.zip/py4j/java_gateway.py", line 1133, in __call__
File "/home/kebodev/spark-2.0.1/python/pyspark/sql/utils.py", line 63, in deco
return f(*a, **kw)
File "/home/kebodev/spark-2.0.1/python/lib/py4j-0.10.3-src.zip/py4j/protocol.py", line 319, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o27.load.
: java.lang.RuntimeException: Option 'dbtable' not specified
at scala.sys.package$.error(package.scala:27)
at org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions$$anonfun$2.apply(JDBCOptions.scala:30)
at org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions$$anonfun$2.apply(JDBCOptions.scala:30)
at scala.collection.MapLike$class.getOrElse(MapLike.scala:128)
at org.apache.spark.sql.execution.datasources.CaseInsensitiveMap.getOrElse(ddl.scala:117)
at org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions.<init>(JDBCOptions.scala:30)
at org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider.createRelation(JdbcRelationProvider.scala:33)
at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:330)
at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:149)
at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:122)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:237)
at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
at py4j.Gateway.invoke(Gateway.java:280)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:214)
at java.lang.Thread.run(Thread.java:745)
Process finished with exit code 1
</code></pre>
<p>Can Anybody help me? </p>
| 0 | 2016-10-14T06:08:36Z | 40,036,227 | <p>Change to <code>dbtable</code> from <code>table</code> like this,</p>
<pre><code>demoDf = sqlContext.read.format("jdbc").options(
url="jdbc:oracle:thin:@10.10.10.10:1521:XE",
driver="oracle.jdbc.driver.OracleDriver",
dbtable="tst_table",
user="xxx",
password="xxx").load()
</code></pre>
| 2 | 2016-10-14T06:18:43Z | [
"python",
"apache-spark",
"pyspark"
] |
python script encountering error when reading from database and data is empty | 40,036,163 | <p>I am reading data from data table in database. The method is throwing an exception when there is no data in table in database. </p>
<pre><code>def readData(table):
"""Read the database table, parse it according to the field map, and return list of parsed lines"""
cmd = GETTABLE + ' ' + table
records = []
try:
result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
data = result.communicate()[0]
except subprocess.CalledProcessError, e:
errorExit( 'Unable to read ' + table + ': ' + str(e))
if (result.returncode > 0):
errorExit( 'Unable to read ' + table + ': ' + data)
lines = data.split('\n')
# Get rid of all the blank lines
lines = [line for line in lines if len(line)>0]
# Pop the first line of the data and use it to parse the column names into a map
header = lines.pop(0)
fieldmap = createFieldMap(header)
for line in lines:
records.append(getFieldMap(line, fieldmap))
return records
</code></pre>
<p><strong>The error is thrown at line <code>header = lines.pop(0)</code> since there is no data in the table.</strong></p>
<p>Kindly suggest me how to handle empty data handling over here gracefully.</p>
<p>Following error is seen on execution of this script:</p>
<blockquote>
<p>Traceback (most recent call last):
File "./dumpLineSegments", line
204, in gnrMemberMap, gnrGroupMap =
getGenericMemberMap('PPWR_GNR_MEM') File "./dumpLineSegments", line
119, in getGenericMemberMap for gnrMember in readData(tablename): File
"./dumpLineSegments", line 78, in readData header = lines.pop(0)
IndexError: pop from empty list</p>
</blockquote>
| 0 | 2016-10-14T06:14:40Z | 40,036,730 | <p>First I would edit the code in a way that indentation is preserved and show the error message. As in the comment by smarx given you just need to check if you have something in lines left to pop. But the next lines are also error prone and should handle problems. Eg. if a line is there, but it is not a legal header, this could issues a warning (in my example). However raising some meaningful exception is also a good idea.
But it is also a good idea to check for lines that are empty except for white space. The second part of the code gives then:</p>
<pre><code>lines = data.split('\n')
# Get rid of all the blank lines, stripping whitespace. Test for
# an empty string can be done as if line
lines = [line.strip() for line in lines if line.strip()]
# Pop the first line of the data and use it to parse the column names into a map
if lines: # check if you have any lines
header = lines.pop(0)
try: # I guess you parse the header somehow, which can fail
fieldmap = createFieldMap(header)
except FieldmapError: # or whatever error is raised when the parsing of the header fails
warning.warn('{} is not a valid header'.format(header))
return None
else:
for line in lines:
records.append(getFieldMap(line, fieldmap))
return records
else:
return None
</code></pre>
<p>If you have no data, None is silently returned, in case of a wrong header a warning is raised.
However, if possible I would query the database with a python database driver instead of a system call. </p>
| 0 | 2016-10-14T06:52:09Z | [
"python"
] |
Calling defintions from inside a class | 40,036,261 | <p>I am currently having an issue with calling on definitions from inside a class, how do I fix the issue of <code>slideShow()</code> in line 32 not opening the slideshow sequence?</p>
<pre><code>import tkinter as tk
from itertools import cycle
root = ""
#create a splash screen, 80% of display screen size, centered,
#quickly diplaying a cycle of images, disapearing after 10 seconds
#lists the images that will be cycled
images = ["pic1.gif", "pic2.gif", "pic3.gif", "pic.gif", "pic5.gif", "pic6.gif"]
photos = cycle(tk.PhotoImage(file=image) for image in images)
class splashscreen():
def slideShow():
img = next(photos)
displayCanvas.config(image=img)
#after 0.05 seconds, begin the slideshow
root.after(1, slideShow)
#creates the canvas for the image to go on
global root
root = tk.Tk()
root.overrideredirect(True)
width = root.winfo_screenwidth()
height = root.winfo_screenwidth()
#sets the size of the splash screen, and its distance from the sides of the screen
root.geometry('%dx%d+%d+%d' % (1536, 864, width/10, height/20))
displayCanvas = tk.Label(root)
displayCanvas.pack()
#after 10 milliseconds, the slideshow will begin, and after 10 seconds, be destroyed
#this is the thing that isnt working
root.after(10, lambda: slideShow())
root.after(10000, root.destroy)
</code></pre>
<p>Why doesn't <code>slideshow()</code> open the <code>def slideShow()</code>? It says that name slideshow is undefined, how do I fix this issue so my code works?</p>
| -1 | 2016-10-14T06:20:41Z | 40,036,386 | <p>You have to use <code>self.</code> inside class. </p>
<pre><code>def slideShow(self):
</code></pre>
<p>and </p>
<pre><code>root.after(1, self.slideShow)
</code></pre>
<p>But probably you have problem with second <code>after</code> too. You have to create instance of class <code>splashscreen</code></p>
<pre><code>my_slides = splashscreen()
</code></pre>
<p>and then you can use <code>splashscreen.slideShow</code></p>
<pre><code>root.after(10, splashscreen.slideShow)
</code></pre>
<p>You have mess in code so I'm not sure which part is inside class and which not.</p>
<hr>
<p>BTW: to make code more readable use <code>CamelCase</code> names for classes - <code>SplashScreen</code> - <code>lower_case</code> namese for variables and functions - <code>display_canvas</code>, <code>show_slide</code></p>
| 0 | 2016-10-14T06:30:23Z | [
"python",
"tkinter"
] |
Multi Indexing and masks with logic pandas | 40,036,532 | <p>I have 4 indexes. Mun, loc, geo and block. And I need to create masks to operate with them so I can create masks and perform operations that will look like this:</p>
<pre><code> data1 data2
mun loc geo block
0 0 0 0 12 12
1 0 0 0 20 20
1 1 0 0 10 10
1 1 1 0 10 10
1 1 1 1 3 3/4
1 1 1 2 4 4/4
1 1 2 0 30 30
1 1 2 1 1 1/3
1 1 2 2 3 3/3
1 1 0 0 4 4
1 2 1 1 10 10/12
1 2 1 2 12 12/12
2 0 0 0 60 60
2 1 1 1 123 123/123
2 1 1 2 7 7/123
2 1 2 1 6 6/6
2 1 2 2 1 1/6
</code></pre>
<pre><code> data1 data2
mun loc geo block
0 0 0 0 12 12
1 0 0 0 20 20
1 1 0 0 10 10
1 1 1 0 10 10/30
1 1 1 1 4 4
1 1 2 0 30 30/30
1 2 1 0 2 2/3
1 2 2 0 3 3/3
1 2 3 0 1 1/3
2 0 0 0 60 60
2 1 1 0 12 12/88
2 1 1 1 1 1
2 1 2 0 88 88/88
2 1 2 1 9 9
</code></pre>
<pre><code> data1 data2
mun loc geo block
0 0 0 0 14 14
1 0 0 0 12 12
1 1 0 0 20 20/20
1 1 1 0 10 10
1 1 1 1 31 31
1 2 0 0 15 15/20
1 2 1 1 11 11
2 0 0 0 80 80
2 1 0 0 100 100/100
2 1 1 2 7 7
2 2 0 0 11 11/100
data1 data2
mun loc geo block
0 0 0 0 55 55
1 0 0 0 70 70/70
1 1 0 0 12 12
1 1 1 0 13 13
2 0 0 0 60 60/70
2 1 1 1 12 12
2 1 2 1 6 6
3 0 0 0 12 12/70
</code></pre>
<p>That is, take the max value inside the hierarchy and divide each element by it. I got help in <a href="http://stackoverflow.com/q/40012740/2901002">another question</a> regarding the first problem, but I'm having a lot of problems getting grasp of multi index. Any help will me appreciated.</p>
| 1 | 2016-10-14T06:40:47Z | 40,041,683 | <p>It was not easy. But mainly use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_level_values.html" rel="nofollow"><code>get_level_values</code></a> for select values for condition:</p>
<p>Level <strong><code>block</code></strong>:</p>
<pre><code>print (df)
data1 data2
mun loc geo block
0 0 0 0 12 12
1 0 0 0 20 20
1 0 0 10 10
1 0 10 10
1 3 3/4
2 4 4/4
2 0 30 30
1 1 1/3
2 3 3/3
0 0 4 4
2 1 1 10 10/12
2 12 12/12
2 0 0 0 60 60
1 1 1 123 123/123
2 7 7/123
2 1 6 6/6
2 1 1/6
mask3 = (df.index.get_level_values('mun') != 0) & \
(df.index.get_level_values('loc') != 0 ) & \
(df.index.get_level_values('geo') != 0) & \
(df.index.get_level_values('block') != 0 )
print (mask3)
[False False False False True True False True True False True True
False True True True True]
df2 = df.ix[mask3, 'data1'].groupby(level=['mun','loc','geo']).max()
#print (df2)
df2 = df2.reindex(df.reset_index(level=3, drop=True).index).mask(~mask3).fillna(1)
#print (df2)
</code></pre>
<pre><code>print (df['data1'].div(df2.values,axis=0))
mun loc geo block
0 0 0 0 12.000000
1 0 0 0 20.000000
1 0 0 10.000000
1 0 10.000000
1 0.750000
2 1.000000
2 0 30.000000
1 0.333333
2 1.000000
0 0 4.000000
2 1 1 0.833333
2 1.000000
2 0 0 0 60.000000
1 1 1 1.000000
2 0.056911
2 1 1.000000
2 0.166667
dtype: float64
</code></pre>
<hr>
<p>Level <strong><code>geo</code></strong>:</p>
<pre><code>print (df)
data1 data2
mun loc geo block
0 0 0 0 12 12
1 0 0 0 20 20
1 0 0 10 10
1 0 10 10/30
1 4 4
2 0 30 30/30
2 1 0 2 2/3
2 0 3 3/3
3 0 1 1/3
2 0 0 0 60 60
1 1 0 12 12/88
1 1 1
2 0 88 88/88
1 9 9
df1 = df.reset_index(drop=True, level='block')
mask3 = (df.index.get_level_values('mun') != 0) & \
(df.index.get_level_values('loc') != 0 ) & \
(df.index.get_level_values('geo') != 0) & \
(df.index.get_level_values('block') == 0 )
print (mask3)
[False False False True False True True True True False True False
True False]
df2 = df1.ix[mask3, 'data1'].groupby(level=['mun','loc']).max()
df2=df2.reindex(df.reset_index(level=['geo','block'], drop=True).index).mask(~mask3).fillna(1)
print (df2)
df['new'] = df['data1'].div(df2.values,axis=0)
</code></pre>
<pre><code>print (df)
data1 data2 new
mun loc geo block
0 0 0 0 12 12 12.000000
1 0 0 0 20 20 20.000000
1 0 0 10 10 10.000000
1 0 10 10/30 0.333333
1 4 4 4.000000
2 0 30 30/30 1.000000
2 1 0 2 2/3 0.666667
2 0 3 3/3 1.000000
3 0 1 1/3 0.333333
2 0 0 0 60 60 60.000000
1 1 0 12 12/88 0.136364
1 1 1 1.000000
2 0 88 88/88 1.000000
1 9 9 9.000000
</code></pre>
<hr>
<p>Level <strong><code>loc</code></strong>:</p>
<pre><code>print (df)
data1 data2
mun loc geo block
0 0 0 0 14 14
1 0 0 0 12 12
1 0 0 20 20/20
1 0 10 10
1 31 31
2 0 0 15 15/20
1 1 11 11
2 0 0 0 80 80
1 0 0 100 100/100
1 2 7 7
2 0 0 11 11/100
df1 = df.reset_index(drop=True, level=['block', 'geo'])
mask3 = (df.index.get_level_values('mun') != 0) & \
(df.index.get_level_values('loc') != 0 ) & \
(df.index.get_level_values('geo') == 0) & \
(df.index.get_level_values('block') == 0 )
print (mask3)
[False False True False False True False False True False True]
df2 = df1.ix[mask3, 'data1'].groupby(level=['mun']).max()
#print (df2)
df2 =df2.reindex(df.reset_index(level=['geo','block', 'loc'], drop=True).index).mask(~mask3).fillna(1)
#print (df2)
</code></pre>
<pre><code>print (df['data1'].div(df2.values,axis=0))
mun loc geo block
0 0 0 0 14.00
1 0 0 0 12.00
1 0 0 1.00
1 0 10.00
1 31.00
2 0 0 0.75
1 1 11.00
2 0 0 0 80.00
1 0 0 1.00
1 2 7.00
2 0 0 0.11
dtype: float64
</code></pre>
<hr>
<p>Level <strong><code>mun</code></strong>:</p>
<pre><code>print (df)
data1 data2
mun loc geo block
0 0 0 0 55 55
1 0 0 0 70 70/70
1 0 0 12 12
1 0 13 13
2 0 0 0 60 60/70
1 1 1 12 12
2 1 6 6
3 0 0 0 12 12/70
mask3 = (df.index.get_level_values('mun') != 0) & \
(df.index.get_level_values('loc') == 0 ) & \
(df.index.get_level_values('geo') == 0) & \
(df.index.get_level_values('block') == 0 )
print (mask3)
[False True False False True False False True]
df2 = df.ix[mask3, 'data1'].max()
#print (df2)
df2 = pd.Series(df2, index=df.index).mask(~mask3).fillna(1)
#print (df2)
</code></pre>
<pre><code>print (df['data1'].div(df2.values,axis=0))
mun loc geo block
0 0 0 0 55.000000
1 0 0 0 1.000000
1 0 0 12.000000
1 0 13.000000
2 0 0 0 0.857143
1 1 1 12.000000
2 1 6.000000
3 0 0 0 0.171429
dtype: float64
</code></pre>
| 2 | 2016-10-14T11:08:35Z | [
"python",
"pandas",
"indexing",
"division",
"multi-index"
] |
Is it Pythonic to passed in arguments in a function that will be used by a function inside it? | 40,036,600 | <p>Is there a better way to do this? Like I'm passing in arguments to <code>func</code> that will be used in <code>inside_func</code> function? </p>
<pre><code>def inside_func(arg1,arg2):
print arg1, arg2
return
def func(arg1, arg2):
inside_func(arg1,arg2)
return
</code></pre>
| 0 | 2016-10-14T06:45:01Z | 40,036,650 | <p>Of course it is.</p>
<p>Your outer function provides a service, and to do its job it may need inputs to work with. <em>How it uses those inputs</em> is up to the function. If it needs another function to do their job and they pass in the arguments verbatim, is an implementation detail.</p>
<p>You are doing nothing more than standard encapsulation and modularisation here. This would be correct programming practice in any language, not just Python.</p>
<p>The Python standard library is full of examples; it is often used to provide a simpler interface for quick use-cases. The <a href="https://hg.python.org/cpython/file/v3.5.2/Lib/textwrap.py#l369" rel="nofollow"><code>textwrap.wrap()</code> function</a> for example:</p>
<pre><code>def wrap(text, width=70, **kwargs):
"""Wrap a single paragraph of text, returning a list of wrapped lines.
Reformat the single paragraph in 'text' so it fits in lines of no
more than 'width' columns, and return a list of wrapped lines. By
default, tabs in 'text' are expanded with string.expandtabs(), and
all other whitespace characters (including newline) are converted to
space. See TextWrapper class for available keyword args to customize
wrapping behaviour.
"""
w = TextWrapper(width=width, **kwargs)
return w.wrap(text)
</code></pre>
<p>This does nothing else but pass the arguments on to other callables, just so your code doesn't have to remember how to use the <code>TextWrapper()</code> class for a quick one-off text wrapping job.</p>
| 6 | 2016-10-14T06:47:28Z | [
"python",
"function"
] |
How can I decrease the number on a button? | 40,036,654 | <p>I'm trying to create a GUI that has only one button. Each time the button is pressed the number on the button should decrease. So I wrote this:</p>
<pre><code>import Tkinter
def countdown(x):
x -= 1
top = Tkinter.Tk()
def helloCallBack():
countdown(x)
B = Tkinter.Button(top, text=x, command=helloCallBack )
B.pack()
top.mainloop()
</code></pre>
<p>I want that button's text to be like 5 4 3 2 1, so where should I put the <code>x=5</code>?</p>
| 0 | 2016-10-14T06:47:42Z | 40,037,108 | <p>As described in the "Button" section of <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/control-variables.html" rel="nofollow">http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/control-variables.html</a>, you need to create a special <code>StringVar</code> to make the button dynamically update. You can pass the <code>StringVar</code> into the <code>textvariable</code> variable of the <code>Button</code> constructor and update the <code>StringVar</code> value inside the <code>countdown()</code> function. <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/button.html" rel="nofollow">http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/button.html</a> states that <code>textvariable</code> is </p>
<blockquote>
<p>An instance of StringVar() that is associated with the text on this button. If the variable is changed, the new value will be displayed on the button.</p>
</blockquote>
| 0 | 2016-10-14T07:13:13Z | [
"python",
"python-2.7",
"tkinter"
] |
How can I decrease the number on a button? | 40,036,654 | <p>I'm trying to create a GUI that has only one button. Each time the button is pressed the number on the button should decrease. So I wrote this:</p>
<pre><code>import Tkinter
def countdown(x):
x -= 1
top = Tkinter.Tk()
def helloCallBack():
countdown(x)
B = Tkinter.Button(top, text=x, command=helloCallBack )
B.pack()
top.mainloop()
</code></pre>
<p>I want that button's text to be like 5 4 3 2 1, so where should I put the <code>x=5</code>?</p>
| 0 | 2016-10-14T06:47:42Z | 40,037,813 | <p>You can create global variable and use it in function <code>countdown</code> (but you have to use <code>global</code>) and then you can use <code>config(text=...)</code> to change text on button.</p>
<pre><code>import Tkinter as tk
# --- functions ---
def countdown():
global x # use global variable
x -= 1
B.config(text=x)
# --- main ---
# create global variable (can be in any place - before/after function, before/after Tk())
x = 5
top = tk.Tk()
B = tk.Button(top, text=x, command=countdown)
B.pack()
top.mainloop()
</code></pre>
<p>Or you can use <code>IntVar()</code> and <code>textvariable</code> - so you don't need <code>config(text=...)</code> and <code>global</code>. </p>
<pre><code>import Tkinter as tk
# --- functions ---
def countdown():
x.set( x.get()-1 )
# --- main ---
top = tk.Tk()
# create global variable (have to be after Tk())
x = tk.IntVar()
x.set(5)
# use `textvariable` and `lambda` to run `countdown` with `x`
B = tk.Button(top, textvariable=x, command=countdown)
B.pack()
top.mainloop()
</code></pre>
<p>I use <code>lambda</code> to run <code>countdown()</code> with <code>x</code> so I can use <code>countdown</code> with many buttons with different <code>IntVar</code>. (you can't do the same in first example when you use <code>int</code>)</p>
<pre><code>import Tkinter as tk
# --- functions ---
def countdown(var):
var.set( var.get()-1 )
# --- main ---
top = tk.Tk()
# create global variable (have to be after Tk())
x = tk.IntVar()
x.set(5)
y = tk.IntVar()
y.set(5)
# use `textvariable` and `lambda` to run `countdown` with `x`
B1 = tk.Button(top, textvariable=x, command=lambda:countdown(x))
B1.pack()
B2 = tk.Button(top, textvariable=y, command=lambda:countdown(y))
B2.pack()
top.mainloop()
</code></pre>
<hr>
<p>BTW: you can use <code>after(miliseconds, functio_name)</code> to run function <code>countdown</code> every 1s and countdown without clicking :)</p>
<pre><code>import Tkinter as tk
# --- functions ---
def countdown(var):
var.set( var.get()-1 )
# run again time after 1000ms (1s)
top.after(1000, lambda:countdown(var))
# --- main ---
top = tk.Tk()
# create global variable (have to be after Tk())
x = tk.IntVar()
x.set(5)
# use `textvariable` and `lambda` to run `countdown` with `x`
B = tk.Button(top, textvariable=x)
B.pack()
# run first time after 1000ms (1s)
top.after(1000, lambda:countdown(x))
top.mainloop()
</code></pre>
| 2 | 2016-10-14T07:51:52Z | [
"python",
"python-2.7",
"tkinter"
] |
Django - What is the best way to have multi level status before login | 40,036,710 | <p>I have one scenario, there is a user registration and it should have multiple status(may be is_active - but this is boolean by default)</p>
<ol>
<li>List item Code - 0 -> Pending for Email Confirmation</li>
<li>List item Code - 1 -> Account Activated/Active(Only after email confirmed admin will approve it)</li>
<li>List item Code - 2 -> Email Confirmed</li>
</ol>
<p>I am using django allauth, I was browsing to achieve it, but unable to find some close match of it. For your info I also have <code>Profile OnetoOne model for User model</code></p>
<p><strong>Updated</strong> </p>
<pre><code>class CustomConfirmEmailView(ConfirmEmailView):
def get(self):
raise Exception('GET')
def post(self,*args,**kwargs):
raise Exception('POST')
</code></pre>
<p><strong>Settings file</strong></p>
<pre><code>ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
</code></pre>
| 0 | 2016-10-14T06:50:50Z | 40,037,520 | <p>You should create custom <code>User</code> or custom <code>Profile</code>(i believe that it's better with custom <code>Profile</code>, to avoid messing with django <code>User</code>):</p>
<pre><code>from itertools import compress
class CustomProfile(Profile):
is_confirmed = models.BooleanField(default=False)
@property
def status(self):
return next(compress(['Pending', 'Active', 'Confirmed'],
[not self.is_confirmed, not self.is_confirmed and self.user.is_active, self.confirmed and self.user.is_active]))
</code></pre>
<p>You can see that i added <code>@property</code> that would answer your question about user status.</p>
<p>But for setting <code>is_confirmed</code> you need to look at the sources, <a href="http://django-allauth.readthedocs.io/en/latest/views.html#e-mail-verification" rel="nofollow">docs</a> lead you to <a href="https://github.com/pennersr/django-allauth/blob/master/allauth/account/views.py#L225" rel="nofollow"><code>allauth.account.views.ConfirmEmailView</code></a> view.</p>
<p>And i think that you need to override <code>post</code> method.</p>
<pre><code>class CustomConfirmEmailView(ConfirmEmailView):
def post(self, *args, **kwargs):
self.object = confirmation = self.get_object()
confirmation.confirm(self.request)
get_adapter(self.request).add_message(
self.request,
messages.SUCCESS,
'account/messages/email_confirmed.txt',
{'email': confirmation.email_address.email})
if app_settings.LOGIN_ON_EMAIL_CONFIRMATION:
resp = self.login_on_confirm(confirmation)
if resp is not None:
return resp
profile = confirmation.email_address.user.profile
profile.is_confirmed = True
profile.save()
redirect_url = self.get_redirect_url()
if not redirect_url:
ctx = self.get_context_data()
return self.render_to_response(ctx)
return redirect(redirect_url)
</code></pre>
<p>And then you need to put that View in url.</p>
<p>That's it. Sure i didn't run it. But the logic is here.</p>
| 1 | 2016-10-14T07:35:37Z | [
"python",
"django"
] |
Django - What is the best way to have multi level status before login | 40,036,710 | <p>I have one scenario, there is a user registration and it should have multiple status(may be is_active - but this is boolean by default)</p>
<ol>
<li>List item Code - 0 -> Pending for Email Confirmation</li>
<li>List item Code - 1 -> Account Activated/Active(Only after email confirmed admin will approve it)</li>
<li>List item Code - 2 -> Email Confirmed</li>
</ol>
<p>I am using django allauth, I was browsing to achieve it, but unable to find some close match of it. For your info I also have <code>Profile OnetoOne model for User model</code></p>
<p><strong>Updated</strong> </p>
<pre><code>class CustomConfirmEmailView(ConfirmEmailView):
def get(self):
raise Exception('GET')
def post(self,*args,**kwargs):
raise Exception('POST')
</code></pre>
<p><strong>Settings file</strong></p>
<pre><code>ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
</code></pre>
| 0 | 2016-10-14T06:50:50Z | 40,038,644 | <p>You can use <code>decorators</code> for these kinds of scenarios. Decorators are just methods that accepts another method as argument. What you have to do is to <code>pass the get/post or any other methods together with its arguments to decorator</code> then check for email confirmation/account active. </p>
<pre><code>from functools import wraps
from .permissions import is_admin_or_manager
from .utils import get_user_on_user_identifier
def is_manager(method):
@wraps(method)
def wrapper(self, *args, **kwargs):
user_identifier = kwargs.get('user_identifier') if kwargs.get('user_identifier') else args[0]
user = get_user_on_user_identifier(user_identifier)
if user:
if is_admin_or_manager(user):
return method(self, *args, **kwargs)
else:
return {'status': 403, 'description': 'Only Manager/Admin roles can create items.'}
else:
return {'status': 404, 'description': 'No user with given username/email exists.'}
return wrapper
class PermissionException(Exception):
pass
</code></pre>
<p>And in your views,</p>
<pre><code>class Home(View):
@is_manager
def get(self, request):
...
</code></pre>
<p>Above code exemplifies on usage of decorators. In your case, pass method with args. get user from request arg passed to decorator, then check if email is confirmed/ account is activated. If not return message using <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/messages/" rel="nofollow">django messages framework</a> json/string can be also be used to pass maessages.</p>
<p>In case you want to use the same with class based views consider <a href="https://docs.djangoproject.com/en/1.10/topics/class-based-views/mixins/" rel="nofollow">mixins</a>. You can override <code>dispatch(self, request, *args, **kwargs)</code> method. I think using decorators/mixins will be better since you do your checks on every views that you write with one line of code.</p>
| 0 | 2016-10-14T08:36:01Z | [
"python",
"django"
] |
Django - Errors not showing on page, connection timeout error thrown after a while | 40,036,717 | <p>I'm having this issue that suddenly appeared with no obvious reasons. Initially, the errors and exceptions were being displayed both on the page and the console. However, whenever I get or reproduce any kind of error and refresh the page to see the results, the page loads for too long and nothing appear in the python server console. After few minutes, I get this error on the page <code>A server error occurred. Please contact the administrator</code>. </p>
<p>And this in the console: </p>
<pre><code>Django version 1.7.1, using settings 'snb_mail.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Traceback (most recent call last):
File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
self.result = application(self.environ, self.start_response)
File "/home/hamza/envsite/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 64, in __call__
return self.application(environ, start_response)
File "/home/hamza/envsite/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 187, in __call__
response = self.get_response(request)
File "/home/hamza/envsite/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 199, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/home/hamza/envsite/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 231, in handle_uncaught_exception
'request': request
File "/usr/lib/python2.7/logging/__init__.py", line 1193, in error
self._log(ERROR, msg, args, **kwargs)
File "/usr/lib/python2.7/logging/__init__.py", line 1286, in _log
self.handle(record)
File "/usr/lib/python2.7/logging/__init__.py", line 1296, in handle
self.callHandlers(record)
File "/usr/lib/python2.7/logging/__init__.py", line 1336, in callHandlers
hdlr.handle(record)
File "/usr/lib/python2.7/logging/__init__.py", line 759, in handle
self.emit(record)
File "/home/hamza/envsite/local/lib/python2.7/site-packages/django/utils/log.py", line 132, in emit
connection=self.connection())
File "/home/hamza/envsite/local/lib/python2.7/site-packages/django/core/mail/__init__.py", line 98, in mail_admins
mail.send(fail_silently=fail_silently)
File "/home/hamza/envsite/local/lib/python2.7/site-packages/django/core/mail/message.py", line 286, in send
return self.get_connection(fail_silently).send_messages([self])
File "/home/hamza/envsite/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 92, in send_messages
new_conn_created = self.open()
File "/home/hamza/envsite/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 50, in open
self.connection = connection_class(self.host, self.port, **connection_params)
File "/usr/lib/python2.7/smtplib.py", line 256, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 316, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 291, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/lib/python2.7/socket.py", line 575, in create_connection
raise err
error: [Errno 110] Connection timed out
[14/Oct/2016 06:36:44] "GET /collections/recommended-for-you/ HTTP/1.1" 500 59
</code></pre>
<p>I haven't done any modification on the settings.py file or the database. This issue only started happening when I opened a page containing a very large set of unpaginated data. Since then, no Syntax error / typeerror or anything appear. The page just keep loading and until the error(s) above appear.</p>
<p>Here is my view.py code: </p>
<pre><code>@csrf_exempt
def store(request, url_name):
blablabla*&21cv34&* # To force syntax error
try:
store = item_inspired.models.ItemInspired.objects.get(url=url_name)
except:
response = render_to_response('404.html', {'user': request.the_user})
return response
response = render_to_response('store.html', {
'user': request.the_user,
'store': store
})
return response
</code></pre>
| 0 | 2016-10-14T06:51:20Z | 40,123,801 | <p>I discovered the source of the issue, which turned out to be from settings.py file. This piece of code was causing the breakage. Once removed, I was able to view the errors:</p>
<pre><code>LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s',
#'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt' : "%d/%b/%Y %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'log/log_file_sh_v3_mail.log',
'formatter': 'verbose'
},
'console': {
'level': 'INFO',
'filters': ['require_debug_false'],
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
#'filters': ['special']
},
},
'loggers': {
'django': {
'handlers': ['file', 'mail_admins'],
'propagate': True,
#'level':'DEBUG',
},
'django.request': {
'handlers': ['file', 'mail_admins'],
'level': 'ERROR',
'propagate': False,
},
'myproject.custom': {
'handlers': ['file', 'console', 'mail_admins'],
'level': 'INFO',
#'filters': ['special']
}
}
}
</code></pre>
| 0 | 2016-10-19T06:30:03Z | [
"python",
"django"
] |
httplib post call error | 40,036,814 | <p>I am trying to automate few http requests where, I have following POST call data which i captured from the web : </p>
<p>Method: POST
Request Header : </p>
<p>POST /cgi-bin/auto_dispatch.cgi HTTP/1.1
Host: 10.226.45.6
Connection: keep-alive
Content-Length: 244
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryhwDXAifvLs48E95A
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,<em>/</em>;q=0.8
Referer: <a href="http://10.226.45.6/auto_dispatch.html" rel="nofollow">http://10.226.45.6/auto_dispatch.html</a>
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,kn;q=0.6
Cookie: TWIKISID=dce9a6aa10e33b708f5bbc2912f781ab</p>
<p>payload : </p>
<p>------WebKitFormBoundaryhwDXAifvLs48E95A
Content-Disposition: form-data; name="taskid"</p>
<p>123
------WebKitFormBoundaryhwDXAifvLs48E95A
Content-Disposition: form-data; name="Submit"</p>
<p>Submit Form
------WebKitFormBoundaryhwDXAifvLs48E95A--</p>
<p>MY script is as follows : </p>
<pre><code> import httplib, urllib
def printText(txt):
lines = txt.split('\n')
for line in lines:
print line.strip()
params = urllib.urlencode({'@taskid': 12524, '@Submit': 'Submit Form'})
headers = {"Content-type": "multipart/form-data", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"}
conn = httplib.HTTPConnection("10.226.45.6", 80)
conn.request("POST", "auto_dispatch.html", params, headers)
response = conn.getresponse()
print response.status, response.reason
printText (response.read())
conn.close()
</code></pre>
<p>I am getting the following error : </p>
<p>400 Bad Request
400 Bad Request
Bad Request
Your browser sent a request that this server could not understand.</p>
<p>Please help me to form a proper request . </p>
| 0 | 2016-10-14T06:56:10Z | 40,121,820 | <p>I Tried with the curl commands which worked for me : </p>
<p>curl --request POST '<a href="http://10.226.45.6/cgi-bin/auto_dispatch.cgi" rel="nofollow">http://10.226.45.6/cgi-bin/auto_dispatch.cgi</a> HTTP/1.1' --data 'taskid=111&submit=submit'</p>
<p>curl --request POST '<a href="http://10.226.45.6/cgi-bin/auto_free.cgi" rel="nofollow">http://10.226.45.6/cgi-bin/auto_free.cgi</a> HTTP/1.1' --data 'submit=submit'</p>
| 0 | 2016-10-19T03:54:22Z | [
"python",
"apache",
"httplib"
] |
Running a Python program with arguments from within the Visual Studio Code | 40,036,942 | <p>I am running a Python program that takes some command line arguments. How can I provide these arguments when I am building a program within the Visual Studio Code?</p>
| 0 | 2016-10-14T07:03:44Z | 40,041,828 | <p>You can pass in the arguments into the program by defining the arguments in the <code>args</code> setting of launch.json as defined below:</p>
<p><code>json
{
"name": "Python",
"type": "python",
"pythonPath":"${config.python.pythonPath}",
"request": "launch",
"stopOnEntry": true,
"console": "none",
"program": "${file}",
"cwd": "${workspaceRoot}",
"args":["arg1", "arg2"],
"env": {"name":"value"}
}
</code></p>
<p>Further information can be found on the documentation site here: <a href="https://github.com/DonJayamanne/pythonVSCode/wiki/Debugging#args" rel="nofollow">https://github.com/DonJayamanne/pythonVSCode/wiki/Debugging#args</a></p>
| 1 | 2016-10-14T11:15:39Z | [
"python",
"build",
"vscode"
] |
Python How to Change Value in Loop | 40,036,957 | <p>There's a code I'm attempting to reverse-engineer for an assignment. The program asks you to enter an integer and it'll loop the words "Line (loop it's on) Hello World" as many times as the number you entered. On the first loop, it said 'Line 1', on the second, it said 'Line 2' and on the third, it said 'Line 3' etc all the while repeating the Hello World right after.</p>
<p>How would I achieve the effect of changing the number each loop? Also, how do I make it loop as many times as the number inputted? My version is Python 3.4.</p>
| -2 | 2016-10-14T07:04:20Z | 40,036,991 | <p>Something like this?</p>
<pre><code>for n in range(int(input())):
print("Line", n+1, "Hello World")
</code></pre>
<p>The <code>range</code> function gives you an iterator with a value <code>0</code>, <code>1</code>, <code>2</code>, ..., <code>n-1</code>. </p>
| 0 | 2016-10-14T07:06:48Z | [
"python",
"loops"
] |
Python How to Change Value in Loop | 40,036,957 | <p>There's a code I'm attempting to reverse-engineer for an assignment. The program asks you to enter an integer and it'll loop the words "Line (loop it's on) Hello World" as many times as the number you entered. On the first loop, it said 'Line 1', on the second, it said 'Line 2' and on the third, it said 'Line 3' etc all the while repeating the Hello World right after.</p>
<p>How would I achieve the effect of changing the number each loop? Also, how do I make it loop as many times as the number inputted? My version is Python 3.4.</p>
| -2 | 2016-10-14T07:04:20Z | 40,037,106 | <p>If this is what you want?</p>
<pre><code>>>> while 1:
... for n in range(int(input())):
... print("Hello World")
...
</code></pre>
<p>The output like this:</p>
<pre><code>1
Hello World
2
Hello World
Hello World
4
Hello World
Hello World
Hello World
Hello World
</code></pre>
| -1 | 2016-10-14T07:13:09Z | [
"python",
"loops"
] |
Cannot load customized op shared lib in tensorflow | 40,037,053 | <p>I tried to add a customized op to tensorflow, but I cannot load it from python. The question is similar to the closed <a href="https://github.com/tensorflow/tensorflow/issues/2455" rel="nofollow">issue</a> in github, but the solution there did not solve my problem.</p>
<p>Operating System: macOS 10.12</p>
<p>Installed version of CUDA and cuDNN: None</p>
<p>TensorFlow 0.11.0 installed from source.</p>
<p>I followed the <a href="https://www.tensorflow.org/versions/r0.11/how_tos/adding_an_op/index.html" rel="nofollow">add new op</a> tutorial, adding zero_out.cc file:</p>
<pre><code>#include "tensorflow/core/framework/op.h"
REGISTER_OP("ZeroOut")
.Input("to_zero: int32")
.Output("zeroed: int32");
#include "tensorflow/core/framework/op_kernel.h"
using namespace tensorflow;
class ZeroOutOp : public OpKernel {
public:
explicit ZeroOutOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
// Grab the input tensor
const Tensor& input_tensor = context->input(0);
auto input = input_tensor.flat<int32>();
// Create an output tensor
Tensor* output_tensor = NULL;
OP_REQUIRES_OK(context, context->allocate_output(0, input_tensor.shape(),
&output_tensor));
auto output = output_tensor->flat<int32>();
// Set all but the first element of the output tensor to 0.
const int N = input.size();
for (int i = 1; i < N; i++) {
output(i) = 0;
}
// Preserve the first input value if possible.
if (N > 0) output(0) = input(0);
}
};
REGISTER_KERNEL_BUILDER(Name("ZeroOut").Device(DEVICE_CPU), ZeroOutOp);
</code></pre>
<p>and bazel BUILD file:</p>
<pre><code>load("//tensorflow:tensorflow.bzl", "tf_custom_op_library")
tf_custom_op_library(
name = "zero_out.so",
srcs = ["zero_out.cc"]
)
</code></pre>
<p>then I run:</p>
<pre><code>bazel build -c opt //tensorflow/core/user_ops:zero_out.so
</code></pre>
<p>output:</p>
<pre><code>INFO: Waiting for response from Bazel server (pid 28589)...
INFO: Found 1 target...
Target //tensorflow/core/user_ops:zero_out.so up-to-date:
bazel-bin/tensorflow/core/user_ops/zero_out.so
INFO: Elapsed time: 5.115s, Critical Path: 0.00s
</code></pre>
<p>The generated shared library located in bazel-bin. When I tried to load it like this:</p>
<pre><code>tf.load_op_library('/Users/dtong/code/data/tensorflow/bazel-bin/tensorflow/core/user_ops/zero_out.so')
</code></pre>
<p>the result:</p>
<pre><code>python(41716,0x7fffb7e123c0) malloc: *** error for object 0x7f9e9cd2de18: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
</code></pre>
| 0 | 2016-10-14T07:10:05Z | 40,062,428 | <p>Well, I found a solution. Instead of building user op by bazel, use g++.</p>
<pre><code>g++ -v -std=c++11 -shared zero_out.cc -o zero_out.so -fPIC -I $TF_INC -O2 -undefined dynamic_lookup -D_GLIBCXX_USE_CXX11_ABI=0
</code></pre>
<p>It will work. The reason seems like that my gcc version is too high (v6.2.0).</p>
<p>The <code>-D_GLIBCXX_USE_CXX11_ABI=0</code> is from the notion of <a href="https://www.tensorflow.org/versions/r0.11/how_tos/adding_an_op/index.html" rel="nofollow">official site</a> in 'Building the Op library' section.</p>
<p>But I still cannot find a solution using bazel. I fired an <a href="https://github.com/tensorflow/tensorflow/issues/4989" rel="nofollow">issue</a> in GitHub.</p>
| 0 | 2016-10-15T18:00:55Z | [
"python",
"tensorflow"
] |
Different marker colors for start and end points in pyplot | 40,037,070 | <p>I am trying to plot lines on a plot between two point tuples. I have following arrays:</p>
<pre><code>start_points = [(54.6, 35.2), (55.5, 32.7), (66.5, 23.7), (75.5, 47.8), (89.3, 19.7)]
end_points = [(38.9, 44.3), (46.7, 52.2), (72.0, 1.4), (62.3, 18.9), (80.8, 26.2)]
</code></pre>
<p>So what I am trying to do is drawing lines between points at same index like a line from (54.6, 35.2) to (38.9, 44.3), another line from (55.5, 32.7) to (46.7, 52.2) and so on.</p>
<p>I achieved this by plotting <code>zip(start_points[:5], end_points[:5])</code>, but I want different marker styles for start and end points of lines. I want start_points to be green circle, and end_points to be blue x for example. Is this possible?</p>
| -1 | 2016-10-14T07:10:48Z | 40,037,422 | <p>The trick is to first plot the line (<code>plt.plot</code>) and then plot the markers using a scatter plot (<code>plt.scatter</code>).</p>
<pre><code>import numpy as np
from matplotlib import pyplot as plt
start_points = [(54.6, 35.2), (55.5, 32.7), (66.5, 23.7), (75.5, 47.8), (89.3, 19.7)]
end_points = [(38.9, 44.3), (46.7, 52.2), (72.0, 1.4), (62.3, 18.9), (80.8, 26.2)]
for line in zip(start_points, end_points):
line = np.array(line)
plt.plot(line[:, 0], line[:, 1], color='black', zorder=1)
plt.scatter(line[0, 0], line[0, 1], marker='o', color='green', zorder=2)
plt.scatter(line[1, 0], line[1, 1], marker='x', color='red', zorder=2)
</code></pre>
| 1 | 2016-10-14T07:29:52Z | [
"python",
"matplotlib"
] |
Not able to install package because pip is not installed | 40,037,107 | <p>I am running Ubuntu and have both python 2.7 and python 3.5 on my system</p>
<p>I have tweaked the settings so that when I do</p>
<pre><code>python test.py
</code></pre>
<p>python3 runs</p>
<p>I wanted to install the module pyperclip in python3..</p>
<pre><code>pip install pyperclip
</code></pre>
<p>installed it for python 2</p>
<p>Quick google search suggested to use </p>
<pre><code>pip3 install pyperclip
</code></pre>
<p>but I get</p>
<pre><code>pip3 is currently not installed . You can install it by typing
sudo apt install python3-pip
</code></pre>
<p>When I run this command I get the following:</p>
<pre><code>The following packages have unmet dependencies:
python3-pip : Depends: python-pip-whl (= 8.1.1-2) but 8.1.1- 2ubuntu0.2 is to be installed
Recommends: python3-dev (>= 3.2) but it is not going to be installed
Recommends: python3-setuptools but it is not going to be installed
Recommends: python3-wheel but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
</code></pre>
<p>What should I do?</p>
| 0 | 2016-10-14T07:13:10Z | 40,037,852 | <p>It seems like it could be an error in your path. If you installed Python 3.5 it should come with pip, so try doing <code>python -m pip</code> and this should run Python 3.5's pip. To install something, simply use the normal pip commands as you have, for example <code>python -m pip install pyperclip</code>.</p>
| 1 | 2016-10-14T07:54:03Z | [
"python",
"python-3.x",
"pip"
] |
Python. Find all possible combinations of numbers with set length | 40,037,118 | <p>I have a list of numbers: [0, 0, 1, 1, 2, 2]</p>
<p>I want to have all combinations of 2 numbers, I tried to do it with itertools:</p>
<pre><code>import itertools
a = [0, 0, 1, 1, 2, 2]
combinations = set(itertools.permutations(a, 2))
print(combinations)
# {(0, 1), (1, 2), (0, 0), (2, 1), (2, 0), (1, 1), (2, 2), (1, 0), (0, 2)}
</code></pre>
<p>I want to use all numbers in list to combinations, but itertools didn't do it.</p>
<p>So, I want to get result like this:</p>
<pre><code>(0, 0), (0, 1), (0, 1), (1, 0), (1, 0) ...
</code></pre>
<p>So, since we have two 0 and two 1 we will have two (0, 1) combinations and etc.</p>
| 1 | 2016-10-14T07:13:28Z | 40,037,165 | <p>A set is a data structure without duplicates. Use a list:</p>
<pre><code>import itertools
a = [0, 0, 1, 1, 2, 2]
combinations = list(itertools.permutations(a, 2))
print(combinations)
</code></pre>
| 3 | 2016-10-14T07:16:33Z | [
"python",
"algorithm",
"combinations"
] |
Python. Find all possible combinations of numbers with set length | 40,037,118 | <p>I have a list of numbers: [0, 0, 1, 1, 2, 2]</p>
<p>I want to have all combinations of 2 numbers, I tried to do it with itertools:</p>
<pre><code>import itertools
a = [0, 0, 1, 1, 2, 2]
combinations = set(itertools.permutations(a, 2))
print(combinations)
# {(0, 1), (1, 2), (0, 0), (2, 1), (2, 0), (1, 1), (2, 2), (1, 0), (0, 2)}
</code></pre>
<p>I want to use all numbers in list to combinations, but itertools didn't do it.</p>
<p>So, I want to get result like this:</p>
<pre><code>(0, 0), (0, 1), (0, 1), (1, 0), (1, 0) ...
</code></pre>
<p>So, since we have two 0 and two 1 we will have two (0, 1) combinations and etc.</p>
| 1 | 2016-10-14T07:13:28Z | 40,037,169 | <p>Just use <code>itertools.product</code>, it gives all possible combinations:</p>
<pre><code>from itertools import product
a = [0, 0, 1, 1, 2, 2]
print (list(product(a, repeat=2)))
</code></pre>
<p>gives:</p>
<pre><code>[(0, 0), (0, 0), (0, 1), (0, 1),
(0, 2), (0, 2), (0, 0), (0, 0),
(0, 1), (0, 1), (0, 2), (0, 2),
(1, 0), (1, 0), (1, 1), (1, 1),
(1, 2), (1, 2), (1, 0), (1, 0),
(1, 1), (1, 1), (1, 2), (1, 2),
(2, 0), (2, 0), (2, 1), (2, 1),
(2, 2), (2, 2), (2, 0), (2, 0),
(2, 1), (2, 1), (2, 2), (2, 2)]
</code></pre>
| 5 | 2016-10-14T07:16:41Z | [
"python",
"algorithm",
"combinations"
] |
Retrieving log message within curly braces using Regex with Python | 40,037,174 | <p>I am trying to parse some logs which return some responses in a key-pair format. I only want they value contained by the last key-pair (Rs: {".."}). The information I want are enclosed inside the curly braces.</p>
<p>What I have done is to use regex to match anything inside the curly braces like this:</p>
<pre><code>import re
log = '2016-10-13 17:04:50 - info - uri:"GET x/y/z" ip:1.1.1.1 Rs:{"data": "blah blah"}'
text = re.compile("Rs\:{(.*)\}").search(log).group(1)
print (text)
>>> "data": "blah blah"
# Desired results
>>> {"data": "blah blah"}
</code></pre>
<p>However there are some issues doing it this way:</p>
<ol>
<li><p>I also wanted the starting curly braces and closing curly braces.</p></li>
<li><p>This method doesn't work if there other opening ("{") or closing ("}:) curly braces before or inside the Rs values.</p></li>
</ol>
<p>Is there a better way to do this?</p>
| 1 | 2016-10-14T07:17:10Z | 40,037,337 | <p>It seems that you need two things: re-adjust the first capturing group boundaries to include curly braces, and use a lazy version of <code>.*</code> (in case there are multiple values in the string). I also recommend checking if there is a match first if you are using <code>re.search</code>, or just use <code>re.findall</code></p>
<pre><code>import re
log = '2016-10-13 17:04:50 - info - uri:"GET x/y/z" ip:1.1.1.1 Rs:{"data": "blah blah"}'
text = re.compile(r"Rs:({[^}]*})").search(log)
if text:
print (text.group(1))
# or
print(re.findall(r"Rs:({[^}]*})", log))
</code></pre>
<p>See the <a href="https://ideone.com/XW2ots" rel="nofollow">Python demo online</a></p>
<p><strong>Pattern details</strong>:</p>
<ul>
<li><code>Rs:</code> - a whole word <code>Rs</code> and a <code>:</code></li>
<li><code>({[^}]*})</code> - Group 1 capturing
<ul>
<li><code>{</code> - a literal <code>{</code></li>
<li><code>[^}]*</code> - 0+ chars other than <code>}</code> (see <a href="http://www.regular-expressions.info/charclass.html#negated" rel="nofollow">more details on <em>Negated Character Classes</em> here</a>)</li>
<li><code>}</code> - a literal <code>}</code>.</li>
</ul></li>
</ul>
| 0 | 2016-10-14T07:25:44Z | [
"python",
"regex"
] |
Retrieving log message within curly braces using Regex with Python | 40,037,174 | <p>I am trying to parse some logs which return some responses in a key-pair format. I only want they value contained by the last key-pair (Rs: {".."}). The information I want are enclosed inside the curly braces.</p>
<p>What I have done is to use regex to match anything inside the curly braces like this:</p>
<pre><code>import re
log = '2016-10-13 17:04:50 - info - uri:"GET x/y/z" ip:1.1.1.1 Rs:{"data": "blah blah"}'
text = re.compile("Rs\:{(.*)\}").search(log).group(1)
print (text)
>>> "data": "blah blah"
# Desired results
>>> {"data": "blah blah"}
</code></pre>
<p>However there are some issues doing it this way:</p>
<ol>
<li><p>I also wanted the starting curly braces and closing curly braces.</p></li>
<li><p>This method doesn't work if there other opening ("{") or closing ("}:) curly braces before or inside the Rs values.</p></li>
</ol>
<p>Is there a better way to do this?</p>
| 1 | 2016-10-14T07:17:10Z | 40,037,372 | <p>The first part is easy: just move the capturing parens out a little bit use this as your regex:</p>
<pre><code>"Rs:(\{.*\})"
</code></pre>
<p>The other problem is more complicated - if you want the rest of the line (starting at <code>{</code>), then </p>
<pre><code>r'Rs:(\{.*)\Z'
</code></pre>
<p>would get you what you want.</p>
| 1 | 2016-10-14T07:27:18Z | [
"python",
"regex"
] |
UnicodeDecodeError when ssh from OS X | 40,037,191 | <p>My Django app loads some files on startup (or when I execute management command). When I ssh from one of my Arch or Ubuntu machines all works fine, I am able to successfully run any commands and migrations.</p>
<p>But when I ssh from OS X (I have El Capital) and try to do same things I get this error: </p>
<pre><code>UnicodeDecodeError: 'ASCII' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
</code></pre>
<p>To open my files I use <code>with open(path_to_file) as f: ...</code></p>
<p>The error happens when sshing from both iterm and terminal. I found out that reason was <code>LC_CTYPE</code> environment variable. It wasn't set on my other Linux machines but on mac it was <code>UTF-8</code> so after I ssh to the server it was set the same. The error was fixed after I unset <code>LC_CTYPE</code>.</p>
<p>So the actual question is what has happened and how to avoid this further? I can unset this variable in my local machine but will it take some negative effects? And what is the best way of doing this?</p>
| 0 | 2016-10-14T07:18:16Z | 40,037,801 | <p>Your terminal at your local machine uses a character encoding. The encoding it uses appears to be UTF-8. When you log on to your server (BTW, what OS does it run?) the programs that run there need to know what encoding your terminal supports so that they display stuff as needed. They get this information from <code>LC_CTYPE</code>. <code>ssh</code> correctly sets it to UTF-8, because that's what your terminal supports.</p>
<p>When you unset <code>LC_CTYPE</code>, then your programs use the default, <code>ASCII</code>. The programs now display in <code>ASCII</code> instead of <code>UTF-8</code>, which works because <code>UTF-8</code> is backward compatible with <code>ASCII</code>. However, if a program needs to display a special character that does not exist in <code>ASCII</code>, it won't work.</p>
<p>Although from the information you give it's not entirely clear to me why the system behaves in this way, I can tell you that unsetting <code>LC_CTYPE</code> is a bad workaround. To avoid problems in the future, it would be better to make sure that all your terminals in all your machines use UTF-8, and get rid of ASCII.</p>
<p>When you try to <code>open</code> a file, Python uses the terminal's (i.e. <code>LC_CTYPE</code>'s) character set. I've never quite understood why it's made this way; why should the character set of your terminal indicate the encoding a file has? However, that's the way it's made and the way to fix the problem correctly is to use the <code>encoding</code> parameter of <code>open</code> if you are using Python 3, or the <code>codecs</code> standard library module if you are using Python 2.</p>
| 0 | 2016-10-14T07:51:00Z | [
"python",
"django",
"osx",
"ssh",
"locale"
] |
Calling dir function on a module | 40,037,253 | <p>When I did a dir to find the list of methods in boltons I got the below output</p>
<pre><code>>>> import boltons
>>> dir(boltons)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
</code></pre>
<p>When I explicitly did </p>
<pre><code>>>> from boltons.strutils import camel2under
>>> dir(boltons)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'strutils']
</code></pre>
<p>found that strutils getting added to attribute of boltons</p>
<p>Why is <strong>strutils</strong> not showing before explicit import?</p>
| 1 | 2016-10-14T07:21:45Z | 40,039,019 | <p>From the <a href="https://docs.python.org/3/library/functions.html#dir" rel="nofollow">docs</a> on what dir does:</p>
<blockquote>
<p>With an argument, attempt to return a list of valid attributes for
that object.</p>
</blockquote>
<p>When we import the boltons package we can see that strutils is not an attribute on the boltons object. Therefore we do not expect it to show up in <code>dir(boltons)</code>.</p>
<pre><code>>>>import boltons
>>>getattr(boltons, 'strutils')
AttributeError: module 'boltons' has no attribute 'strutils'
</code></pre>
<p>The <a href="https://docs.python.org/3/reference/import.html#submodules" rel="nofollow">docs</a> on importing submodules say:</p>
<blockquote>
<p>For example, if package spam has a submodule foo, after importing spam.foo, spam will have an attribute foo which is bound to the submodule.</p>
</blockquote>
<p>Importing a submodule creates an attribute on the package. In your example:</p>
<pre><code>>>>import boltons
>>>getattr(boltons, 'strutils')
AttributeError: module 'boltons' has no attribute 'strutils'
>>>from boltons.strutils import camel2under
>>>getattr(boltons, 'strutils')
<module 'boltons.strutils' from '/usr/local/lib/python3.5/site-packages/boltons/strutils.py'>
</code></pre>
<p>Therefore in this case we do expect strutils to show up in <code>dir(boltons)</code></p>
| 2 | 2016-10-14T08:56:02Z | [
"python",
"python-2.7"
] |
Python: Dynamically importing a script in another folder from a string | 40,037,569 | <p>I need to import and run a script from a string (path) which is located in another folder. The input needs to be completely dynamic. The code below works when the file is in the same folder but I can't seem to get it working when the file is located elsewhere.</p>
<p>main.py</p>
<pre><code>path = 'bin\TestScript'
module = __import__(path)
my_class = getattr(module, '__main__')
instance = my_class(3,16)
print(instance)
</code></pre>
<p>TestScript.py</p>
<pre><code>def __main__(a,b):
return(a*b)
</code></pre>
<p>Get the errror:
ImportError: No module named 'bin\\TestScript'</p>
<p>on windows os</p>
| -1 | 2016-10-14T07:37:59Z | 40,038,075 | <p>You need to separate the directory from the module name and add that to the module search path. For example:</p>
<pre><code>import os.path
import sys
path = 'bin\\TestScript'
mdir = os.path.dirname(path)
modname = os.path.basename(path)
sys.path.append(mdir)
module = __import__(modname)
my_class = getattr(module, '__main__')
instance = my_class(3,16)
print(instance)
</code></pre>
<p>An alternative is to make the directory "bin" a package.</p>
| 1 | 2016-10-14T08:06:19Z | [
"python"
] |
Sequence Recognition using fsm in python | 40,037,580 | <p>What is the best way to detect a sequence of characters in python?</p>
<p>I'm trying to use transitions package by Tal yarkoni for creating fsm's based on input sequences. Then i want to use the created fsms for new sequence recognition.
I'm storing the created fsm in a dict with sequence number as key. </p>
<p>All the fsms from the dictionary should make transition as per input chars. The one which reaches end state is the required sequence and the function should return the key. </p>
<p>Problem is that there is no concept of end state in the transitions fsm model.
Is it possible to do this using transitions package?</p>
| 0 | 2016-10-14T07:38:33Z | 40,037,938 | <p>There is no concept of end state, but you can define a state 'end' on each fsm and check for it (see 'checking state' in the git readme), or you could add a 'on enter' reference on the 'end' state and that function will be called when the 'end' state is entered.</p>
<p>Haven't seen transitions before, looks very nice, I like being able to produce the diagrams.</p>
| 0 | 2016-10-14T07:58:30Z | [
"python",
"transitions"
] |
Read cvs file to Dictionary python | 40,037,615 | <p>Please, I need to read CSV file and convert the result to a dictionary.</p>
<p>File input:</p>
<p><a href="https://i.stack.imgur.com/4h26Q.png" rel="nofollow"><img src="https://i.stack.imgur.com/4h26Q.png" alt="enter image description here"></a></p>
<p>The required object after reading like below:</p>
<pre><code>defaultdict(<type 'dict'>, {âBookâ: {âBookâ: 1.0, âAfnanâ: 0, âLocationâ: 0, âLoveâ: 0}, âAfnanâ: {âBookâ: 0, âAfnanâ: 1.0, âLocationâ: 0.71, âLoveâ: 0}, âLocationâ: {âBookâ: 0, 'Afnanâ: 0.71, âLocationâ: 1.0, âLoveâ: 0}, âLoveâ: {âBookâ: 0, âAfnanâ: 0, âLocationâ: 0, âLoveâ: 1.0}})
</code></pre>
<p>I write below code but is not working as what I want. Please help.</p>
<pre><code>reader = unicode_csv_reader(open('cos3.csv'))
x=list(reader)
for i in x:
if isinstance(i,float):
arr=np.array(x).astype('float')
else:
arr=np.array(x).astype('string')
d=defaultdict(dict)
for a in arr:
for b in arr:
d[a][b]=arr(a)
</code></pre>
| 0 | 2016-10-14T07:40:57Z | 40,038,356 | <p>I always use <code>csv.DictReader</code> and then build the dictionary in the format you want like so:</p>
<p><a href="https://i.stack.imgur.com/weNmx.png" rel="nofollow"><img src="https://i.stack.imgur.com/weNmx.png" alt="enter image description here"></a></p>
<pre><code>import csv
import os
cwd = os.getcwd()
d_out = {}
with open(cwd+'\\example.csv', 'rb') as file_in:
reader = csv.DictReader(file_in, restkey=None, restval=None, dialect='excel')
for row in reader:
d_out.setdefault(row['Key'], {'Book':row['Book'], 'Afnan':row['Afnan'], 'Location':row['Location'], 'Love':row['Love']})
print d_out
</code></pre>
<p>Hope this helps!</p>
| 0 | 2016-10-14T08:20:29Z | [
"python",
"csv",
"dictionary"
] |
Adding reference to .net assembly which has dots in name and namespace | 40,037,684 | <p>I am trying to refer to assembly which has dots in the namespace.</p>
<pre class="lang-python prettyprint-override"><code>sys.path.append(assemblyPath)
clr.FindAssembly(r"isc.Eng.Hov")
clr.AddReference(r"isc.Eng.Hov")
print 'isc.Eng.Hov' in clr.ListAssemblies(False)
from isc.Eng.Hov import *
</code></pre>
<p>Interpreter raises an error:</p>
<pre><code>Traceback (most recent call last):
True
File "/mnt/86f8c6c8-9099-4f32-be68-486a12918546/GoogleDrive/__BACKLOG/RMK_API_LIB/rmkSuppliersDLLswrappers/scr/Hoval/__phex_hoval_dllwrapper.py", line 14, in <module>
from isc.Eng.Hov import *
ImportError: No module named isc.Eng.Hov
</code></pre>
<p>How to troubleshoot?</p>
| 1 | 2016-10-14T07:44:43Z | 40,099,662 | <p>the solution was to use <a href="http://ilspy.net/" rel="nofollow">ILSPY</a> to investigate the DLL and find dependencies (right click recursively for each DLL and click on add dependencies). Then I copied all the dependencies to the same folder where the main DLL was. After that, I ran:</p>
<pre class="lang-python prettyprint-override"><code>print [a for a in clr.ListAssemblies(False)
</code></pre>
<p>and get the list of dependencies which are actually involved:</p>
<pre class="lang-python prettyprint-override"><code>u'isc.Eng.Hov', u'Microsoft.VisualBasic', u'System.Windows.Forms', u'System.Drawing', u'Accessibility'
</code></pre>
<p>and left them in the folder.
After doing so the part of code:</p>
<pre class="lang-python prettyprint-override"><code>sys.path.append(assemblyPath)
clr.AddReference("isc.Eng.Hov")
import isc.Eng.Hov as isk
from isk import *
</code></pre>
<p>started work.</p>
<p>Thank you all, especially @denfromufa for help!</p>
| 1 | 2016-10-18T04:43:10Z | [
"python",
".net",
".net-assembly",
"python.net"
] |
Can't make python files executable in os x | 40,037,785 | <p>I want to put the path to the python file first in the file to run it without having to type python before it. Here is the output of the terminal that comfiuses me</p>
<pre><code>[Wolfie@Wolfies-MacBook-Pro] [08:54:28] [/Applications/MAMP/cgi-bin]
$python test.py
blaaaaa
[Wolfie@Wolfies-MacBook-Pro] [08:54:32] [/Applications/MAMP/cgi-bin]
$which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
[Wolfie@Wolfies-MacBook-Pro] [08:54:39] [/Applications/MAMP/cgi-bin]
$cat test.py
#!/Library/Frameworks/Python.framework/Versions/2.7/bin/python
print "blaaaaa"
[Wolfie@Wolfies-MacBook-Pro] [08:54:45] [/Applications/MAMP/cgi-bin]
$ls -l test.py
-rwxr-xr-x 1 Wolfie admin 83 Oct 14 08:53 test.py
[Wolfie@Wolfies-MacBook-Pro] [08:54:49] [/Applications/MAMP/cgi-bin]
$./test.py
: No such file or directoryry/Frameworks/Python.framework/Versions/2.7/bin/python
./test.py: line 2: print: command not found
</code></pre>
<p>On Ubuntu, Debian and Red Hat this way works. I also tried with "/usr/bin/python" and "/usr/local/bin/python3" which work when I put it before the filename in the terminal and run it but not when I put it first in the file then chmod +x it.</p>
| 0 | 2016-10-14T07:50:21Z | 40,037,907 | <p>With any programming language, I'll use <code>#!/usr/bin/env [language]</code> and in this case replace <code>[language]</code> with <code>python</code>.</p>
| 1 | 2016-10-14T07:56:44Z | [
"python",
"osx"
] |
python scrapy shell exception: address "'http:" not found: [Errno 11001] getaddrinfo failed | 40,037,897 | <p>Actually it's a sample of scrapy tutorial in <strong>Extracting data</strong> of <a href="https://doc.scrapy.org/en/latest/intro/tutorial.html" rel="nofollow">scrapy</a>. Everything goes well until the sample of scrapy shell, when I type the command in Windows cmd:</p>
<pre><code>scrapy shell 'http://quotes.toscrape.com/page/1/'
</code></pre>
<p>I got an exception like</p>
<pre><code>twisted.internet.error.DNSLookupError: DNS lookup failed: address "'http:" not found: [Errno 11001] getaddrinfo failed.
</code></pre>
<p>Exception in thread Thread-1 (most likely raised during interpreter shutdown):</p>
<p>in detail it's like:
[<img src="https://i.stack.imgur.com/9RwwX.png" alt="scrapy shell exception]">
and I have searched the <code>stackoverflow</code> and find a similar problem like <a href="http://stackoverflow.com/q/35062932/6653189">question</a>
and one answer is try another terminal,and I tried the terminal of Pycharm but it fails with the same exception.</p>
<p>PS: I work on windows and Python 2.7.12, Anaconda 4.0.0 (64-bit)</p>
<p>I'm quite new to scrapy so any help is appreciated, thank you.</p>
| 0 | 2016-10-14T07:56:12Z | 40,038,161 | <p>Well,it may be related to the quotation, I tried to use <code>"</code> to enclose the urls and it works, I do not know if this command differs in different OS since the original tutorial commmand code use the <code>'</code> to enclose the urls.</p>
<hr>
<p>I also post this issue on the scrapy and as @kmike said, it works well with <code>'</code> on other OS like (MAC and Linux or Unix) (<a href="https://github.com/scrapy/scrapy/issues/2325#issuecomment-253737415" rel="nofollow">github</a>)</p>
| 1 | 2016-10-14T08:11:35Z | [
"python",
"shell",
"scrapy"
] |
How should I read/write a data structure containing large arrays? | 40,037,998 | <p>I fetch a big array of data from a server. I store it in a combination of a dictionary and multi-dimensional array, and it will be used for a simple plot. It looks like:</p>
<pre><code>>> print(data)
{'intensity_b2': [array([ 1.46562588e+09, 1.46562588e+09, 1.46562588e+09, ...,
1.46566369e+09, 1.46566369e+09, 1.46566369e+09]), array([ 0., 0., 0., ..., 0., 0., 0.])]}
>> print(len(data['intensity_b2'][0]))
37071
</code></pre>
<p>To avoid fetching the data every time I run the script I want to save this data structure to a file. I try to store the data as</p>
<pre><code>with open("data.dat", 'w') as f:
f.write(str(data))
</code></pre>
<p>and read it with</p>
<pre><code>with open(data_store, 'r') as f:
data = ast.literal_eval(f.read())
</code></pre>
<p>as suggested <a href="http://stackoverflow.com/questions/11026959/python-writing-dict-to-txt-file-and-reading-dict-from-txt-file">here</a>. However, I get an error</p>
<blockquote>
<p>ValueError: malformed node or string: <_ast.Call object at 0x108fce5f8></p>
</blockquote>
<p>which I suspect is due to the fact that the data gets stored with the <code>...</code> as was shown in the first printout (i.e. the first <code>print(data)</code> above is literally how the data looks in the file). How do I write a dictionary with a big array to a file and read it subsequently?</p>
| 0 | 2016-10-14T08:01:52Z | 40,038,099 | <p>Your problem is that <code>str</code> is not a suitable way to serialise data. Typically, objects will have a string representation that would let a human understand what they are. For primitive objects, it would be a format that you could even <code>eval</code> to get back an equivalent object, but this isn't true generally.</p>
<p>You need to decide how you want to serialise the data. You could use something like <a href="https://docs.python.org/2/library/json.html" rel="nofollow">JSON</a>, but then you'd need to figure out how to convert object too/from primitive data types anyway, and I think it's already clear that you're not using just primitive data types.</p>
<p>You probably want to use <a href="https://docs.python.org/2/library/pickle.html" rel="nofollow">pickle</a> to create a serialised version of the data which which you will be able to unpickle later and get the same data types back.</p>
| 1 | 2016-10-14T08:07:56Z | [
"python",
"arrays",
"dictionary",
"file-io"
] |
How should I read/write a data structure containing large arrays? | 40,037,998 | <p>I fetch a big array of data from a server. I store it in a combination of a dictionary and multi-dimensional array, and it will be used for a simple plot. It looks like:</p>
<pre><code>>> print(data)
{'intensity_b2': [array([ 1.46562588e+09, 1.46562588e+09, 1.46562588e+09, ...,
1.46566369e+09, 1.46566369e+09, 1.46566369e+09]), array([ 0., 0., 0., ..., 0., 0., 0.])]}
>> print(len(data['intensity_b2'][0]))
37071
</code></pre>
<p>To avoid fetching the data every time I run the script I want to save this data structure to a file. I try to store the data as</p>
<pre><code>with open("data.dat", 'w') as f:
f.write(str(data))
</code></pre>
<p>and read it with</p>
<pre><code>with open(data_store, 'r') as f:
data = ast.literal_eval(f.read())
</code></pre>
<p>as suggested <a href="http://stackoverflow.com/questions/11026959/python-writing-dict-to-txt-file-and-reading-dict-from-txt-file">here</a>. However, I get an error</p>
<blockquote>
<p>ValueError: malformed node or string: <_ast.Call object at 0x108fce5f8></p>
</blockquote>
<p>which I suspect is due to the fact that the data gets stored with the <code>...</code> as was shown in the first printout (i.e. the first <code>print(data)</code> above is literally how the data looks in the file). How do I write a dictionary with a big array to a file and read it subsequently?</p>
| 0 | 2016-10-14T08:01:52Z | 40,038,251 | <p>You can use <code>pickle</code> to handle serialization properly:</p>
<pre><code>In [23]: a
Out[23]:
{'intensity_b2': [array('f', [1465625856.0, 1465625856.0, 1465625856.0]),
array('f', [1465663744.0, 1465663744.0, 1465663744.0])]}
In [24]: pickle.dump(a, open('foo.p', 'wb'))
In [25]: aa = pickle.load(open('foo.p', 'rb'))
In [26]: aa
Out[26]:
{'intensity_b2': [array('f', [1465625856.0, 1465625856.0, 1465625856.0]),
array('f', [1465663744.0, 1465663744.0, 1465663744.0])]}
</code></pre>
<p>This does exactly what you want to do: saves your data structure to a file, and then reads it from the file.</p>
<p>However, it looks like you're reinventing the wheel here. You may want to have a look at <code>numpy</code> and <code>pandas</code>.</p>
| 1 | 2016-10-14T08:15:04Z | [
"python",
"arrays",
"dictionary",
"file-io"
] |
Python import modules in same directory for Flask | 40,038,042 | <p>I am trying to create a Flask application. I would like to include a separate module in my application to separate logic into distinct units. The separate module is called 'validator' and my current directory structure looks like this:</p>
<pre><code>src/
validation-api/
__init__.py
api.py
validator/
__init__.py
validator.py
validation-form/
...
updater/
...
</code></pre>
<p>My Flask application is in <code>api.py</code> and I am trying to do <code>from validator import ValidationOptions, ValidationResult, ValidationRun</code> where <code>ValidationOptions</code>, <code>ValidationResult</code>, and <code>ValidationRun</code> are classes in <code>validator</code>. </p>
<p>I am getting the error </p>
<blockquote>
<p>ImportError: No module named validator </p>
</blockquote>
<p>If I try <code>from .validator...</code> or <code>from ..validator</code> I get the error </p>
<blockquote>
<p>ValueError: Attempted relative import in non-package</p>
</blockquote>
<p>I don't quite understand how modules and packages work in Python. Any suggestions?</p>
<hr>
<p>Contents of api.py:</p>
<pre><code>from flask import Flask, request
from validator.validator import ValidationOptions, ValidationResult, ValidationRun
app = Flask(__name__)
@app.route("/validate", methods=["POST"])
def validate(self):
pass
if __name__ == '__main__':
app.run(debug=True)
</code></pre>
<p>I am starting Flask using the following three commands:</p>
<pre><code>set FLASK_APP=api
set FLASK_DEBUG=1
python -m flask run
</code></pre>
| 0 | 2016-10-14T08:03:58Z | 40,038,307 | <p>Thanks to @Daniel-Roseman, I've figured out what's going on. I changed the <code>FLASK_APP</code> environment variable to <code>validation-api.api</code>, and ran the <code>python -m flask run</code> command from <code>src</code>. All imports are working now!</p>
| 1 | 2016-10-14T08:17:19Z | [
"python",
"flask"
] |
fatal error:pyconfig.h:No such file or directory when pip install cryptography | 40,038,134 | <p>I wanna set up scrapy cluster follow this link <a href="http://scrapy-cluster.readthedocs.io/en/latest/topics/introduction/quickstart.html#cluster-quickstart" rel="nofollow">scrapy-cluster</a>,Everything is ok before I run this command:</p>
<pre><code>pip install -r requirements.txt
</code></pre>
<p>The requirements.txt looks like:</p>
<pre><code>cffi==1.2.1
characteristic==14.3.0
ConcurrentLogHandler>=0.9.1
cryptography==0.9.1
...
</code></pre>
<p>I guess the above command means to install packages in requirements.txt.But I don't want it to specify the version,So I change it to this:</p>
<pre><code>cat requirements.txt | while read line; do pip install ${line%%[>=]*} --user;done
</code></pre>
<p>When install cryptography,it gives me the error:</p>
<pre><code>build/temp.linux-x86_64-2.7/_openssl.c:12:24:fatal error:pyconfig.h:No such file or directory
#include <pyconfig.h>
</code></pre>
<p>I don't know how to solved this , I have tried a lot of methods ,but failed. my system is centos 7, and the version of python is 2.7.5(default).
Besides, Is there any other scrapy frame which is appliable for a large number of urls . Thanks in advance</p>
| -1 | 2016-10-14T08:09:51Z | 40,040,895 | <p>I have solved it by myself. for the default python of centos, there is only a file named pyconfg-64.h in usr/include/python2.7/,So run the command</p>
<pre><code>yum install python-devel
</code></pre>
<p>Then it works.</p>
| 1 | 2016-10-14T10:25:55Z | [
"python",
"cryptography",
"centos",
"scrapy",
"pip"
] |
Pandas: timestamp to datetime | 40,038,169 | <p>I have dataframe and column with dates looks like</p>
<pre><code> date
1476329529
1476329530
1476329803
1476329805
1476329805
1476329805
</code></pre>
<p>I use <code>df['date'] = pd.to_datetime(df.date, format='%Y-%m-%d %H:%M:%S')</code>
to convert that, but I'm get strange result</p>
<pre><code> date
1970-01-01 00:00:01.476329529
1970-01-01 00:00:01.476329530
1970-01-01 00:00:01.476329803
1970-01-01 00:00:01.476329805
1970-01-01 00:00:01.476329805
1970-01-01 00:00:01.476329805
</code></pre>
<p>Maybe I did anything wrong</p>
| 1 | 2016-10-14T08:12:02Z | 40,038,277 | <p>Something like this maybe:</p>
<pre><code>import datetime
date = datetime.datetime.fromtimestamp(1476329529)
date
# gives
# datetime.datetime(2016, 10, 13, 5, 32, 9)
str(date) # '2016-10-13 05:32:09'
</code></pre>
| 1 | 2016-10-14T08:16:07Z | [
"python",
"datetime",
"pandas"
] |
Pandas: timestamp to datetime | 40,038,169 | <p>I have dataframe and column with dates looks like</p>
<pre><code> date
1476329529
1476329530
1476329803
1476329805
1476329805
1476329805
</code></pre>
<p>I use <code>df['date'] = pd.to_datetime(df.date, format='%Y-%m-%d %H:%M:%S')</code>
to convert that, but I'm get strange result</p>
<pre><code> date
1970-01-01 00:00:01.476329529
1970-01-01 00:00:01.476329530
1970-01-01 00:00:01.476329803
1970-01-01 00:00:01.476329805
1970-01-01 00:00:01.476329805
1970-01-01 00:00:01.476329805
</code></pre>
<p>Maybe I did anything wrong</p>
| 1 | 2016-10-14T08:12:02Z | 40,038,308 | <p>This looks look epoch timestamps which is number of seconds since 1st January 1970 :</p>
<pre><code>In [71]:
pd.to_datetime(df['date'], unit='s')
â
Out[71]:
0 2016-10-13 03:32:09
1 2016-10-13 03:32:10
2 2016-10-13 03:36:43
3 2016-10-13 03:36:45
4 2016-10-13 03:36:45
5 2016-10-13 03:36:45
Name: date, dtype: datetime64[ns]
</code></pre>
| 2 | 2016-10-14T08:17:25Z | [
"python",
"datetime",
"pandas"
] |
How do I write web-scraped text into csv using python? | 40,038,175 | <p>I've been working on a practice web-scraper that gets written reviews and writes them to a csv file, with each review given its own row. I've been having trouble with it as:</p>
<ol>
<li>I can't seem to <strong>strip out the html</strong> and get only the text (i.e. the written review and nothing else)</li>
<li>There are a lot of <strong>weird spaces between and within even my review text</strong> (i.e. a row of space between lines etc.)</li>
</ol>
<p>Thanks for your help!</p>
<p>Code below:</p>
<pre><code>#! python3
import bs4, os, requests, csv
# Get URL of the page
URL = ('https://www.tripadvisor.com/Attraction_Review-g294265-d2149128-Reviews-Gardens_by_the_Bay-Singapore.html')
# Looping until the 5th page of reviews
pagecounter = 0
while pagecounter != 5:
# Request get the first page
res = requests.get(URL)
res.raise_for_status
# Download the html of the first page
soup = bs4.BeautifulSoup(res.text, "html.parser")
reviewElems = soup.select('.partial_entry')
if reviewElems == []:
print('Could not find clue.')
else:
#for i in range(len(reviewElems)):
#print(reviewElems[i].getText())
with open('GardensbytheBay.csv', 'a', newline='') as csvfile:
for row in reviewElems:
writer = csv.writer(csvfile, delimiter=' ', quoting=csv.QUOTE_ALL)
writer.writerow(row)
print('Writing page')
# Find URL of next page and update URL
if pagecounter == 0:
nextLink = soup.select('a[data-offset]')[0]
elif pagecounter != 0:
nextLink = soup.select('a[data-offset]')[1]
URL = 'http://www.tripadvisor.com' + nextLink.get('href')
pagecounter += 1
print('Download complete')
csvfile.close()
</code></pre>
| 0 | 2016-10-14T08:12:20Z | 40,109,064 | <p>You can use <code>row.get_text(strip=True)</code> to get the text from your selected <code>p.partial_entry</code>. Try the following:</p>
<pre><code>import bs4, os, requests, csv
# Get URL of the page
URL = ('https://www.tripadvisor.com/Attraction_Review-g294265-d2149128-Reviews-Gardens_by_the_Bay-Singapore.html')
with open('GardensbytheBay.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=' ')
# Looping until the 5th page of reviews
for pagecounter in range(6):
# Request get the first page
res = requests.get(URL)
res.raise_for_status
# Download the html of the first page
soup = bs4.BeautifulSoup(res.text, "html.parser")
reviewElems = soup.select('p.partial_entry')
if reviewElems:
for row in reviewElems:
review_text = row.get_text(strip=True).encode('utf8', 'ignore').decode('latin-1')
writer.writerow([review_text])
print('Writing page', pagecounter + 1)
else:
print('Could not find clue.')
# Find URL of next page and update URL
if pagecounter == 0:
nextLink = soup.select('a[data-offset]')[0]
elif pagecounter != 0:
nextLink = soup.select('a[data-offset]')[1]
URL = 'http://www.tripadvisor.com' + nextLink.get('href')
print('Download complete')
</code></pre>
| 0 | 2016-10-18T13:02:57Z | [
"python",
"csv",
"web-scraping",
"beautifulsoup"
] |
Invalid datetime format in python-mysql query | 40,038,181 | <p>I wanted to fetch a record from database which is having the <code>datetime</code> field a part of primary key. I am querying from <code>python</code> using <code>mysqldb package</code> which is resulting in error </p>
<blockquote>
<p>Invalid datetime format</p>
</blockquote>
<p>wherein the same query is working fine when executed through command line and mysql workbench.</p>
<p>My code looks like this.</p>
<pre><code>def get_all_list(table_name, modify_dt, params):
cursr = connections['default'].cursor()
stmt = 'select * from ' + table_name + ' where ' + params
cursr.execute(stmt)
data = cursr.fetchall()
</code></pre>
<p>the params is the string which contains my primary key value.</p>
<p>for instance </p>
<pre><code>params is "join_date = '2016-09-08 00:00:00+00:00'"
</code></pre>
<p>my final query looks similiar to this</p>
<pre><code>select * from employee where join_date = '2016-09-08 00:00:00+00:00'
</code></pre>
<p>When executed, the same is providing result in mysql workbench while when executed through my program , I am getting error as </p>
<blockquote>
<p>Incorrect datetime value: '2016-09-08 00:00:00+00:00' for column
'join_date' at row 1</p>
</blockquote>
| 0 | 2016-10-14T08:12:35Z | 40,038,274 | <p>Date format should be</p>
<pre><code>'2016-09-08 00:00:00'
</code></pre>
<p>if you need to set time zone, you need a separate SQL query</p>
<pre><code>set time_zone='+00:00';
</code></pre>
<p>See also: <a href="http://stackoverflow.com/questions/930900/how-to-set-time-zone-of-mysql">How to set time zone of mysql?</a></p>
<hr>
<p>If you are using django, you can set time_zone for the entire app in the settings file:</p>
<pre><code>DATABASES['default'] = {
'ENGINE': 'your_db_engine',
'NAME': 'my_database',
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': 3306,
'OPTIONS': {
"init_command": "SET storage_engine=InnoDB; set time_zone='+00:00';",
},
}
</code></pre>
| 0 | 2016-10-14T08:16:02Z | [
"python",
"mysql",
"python-2.7",
"datetime"
] |
Python - Guess Who game - Im not getting my expected output | 40,038,231 | <p>This is a small portion of my guess who game im developing that assigns the AI Opponents randomly chosen character with its linked features, and assigns those features to the feature variables. When the user asks the question the if statements will respond with a yes or no based on whether it has the features asked off, but i am not getting an expected output. I may not be able to reply with any further questions about this until i get back from college later today thanks.</p>
<p>I do not get any errors, but every response is a "No" even when the AI opponent 100% definetely has that feature. Heres the output im getting:</p>
<blockquote>
<p>What is your question for your AI opponent?
Does your character have short hair?
AI Opponent: No
What is your question for your AI opponent?
Does your character have long hair?
AI Opponent: No
What is your question for your AI opponent?
Is your character Bald?
AI Opponent: No
What is your question for your AI opponent?
Is your character male?
AI Opponent: No
What is your question for your AI opponent?
Is your character female?
AI Opponent: No</p>
</blockquote>
<pre><code>#This assigns a random character name to the variable 'AICharacterChoice'
AICharacterChoice = random.choice(["Greg", "Chris", "Jason", "Clancy", "Betty", "Selena", "Helen", "Jacqueline"])
#This simpy defines these feature variables
AIChoiceFeatureHairLength = "Unassigned"
AIChoiceFeatureHairColour = "Unassigned"
AIChoiceFeatureFacialHair = "Unassigned"
AIChoiceFeatureJewellery = "Unassigned"
AIChoiceFeatureHat = "Unassigned"
AIChoiceFeatureLipstick = "Unassigned"
AIChoiceGender = "Unassigned"
#This assigns the feature variables with features linked to that characters name
if AICharacterChoice == "Greg":
AIChoiceFeatureHairLength == "Short"
AIChoiceFeatureHairColour == "Brown"
AIChoiceFeatureFacialHair == "Yes"
AIChoiceFeatureJewellery == "Yes"
AIChoiceFeatureHat == "No"
AIChoiceFeatureLipstick == "No"
AIChoiceGender == "Male"
if AICharacterChoice == "Chris":
AIChoiceFeatureHairLength == "Long"
AIChoiceFeatureHairColour == "Blonde"
AIChoiceFeatureFacialHair == "No"
AIChoiceFeatureJewellery == "No"
AIChoiceFeatureHat == "Yes"
AIChoiceFeatureLipstick == "Yes"
AIChoiceGender == "Male"
if AICharacterChoice == "Jason":
AIChoiceFeatureHairLength == "Short"
AIChoiceFeatureHairColour == "Brown"
AIChoiceFeatureFacialHair == "Yes"
AIChoiceFeatureJewellery == "No"
AIChoiceFeatureHat == "Yes"
AIChoiceFeatureLipstick == "No"
AIChoiceGender == "Male"
if AICharacterChoice == "Clancy":
AIChoiceFeatureHairLength == "Bald"
AIChoiceFeatureHairColour == "Red"
AIChoiceFeatureFacialHair == "Yes"
AIChoiceFeatureJewellery == "No"
AIChoiceFeatureHat == "No"
AIChoiceFeatureLipstick == "No"
AIChoiceGender == "Male"
if AICharacterChoice == "Betty":
AIChoiceFeatureHairLength == "Bald"
AIChoiceFeatureHairColour == "Blonde"
AIChoiceFeatureFacialHair == "No"
AIChoiceFeatureJewellery == "Yes"
AIChoiceFeatureHat == "Yes"
AIChoiceFeatureLipstick == "Yes"
AIChoiceGender == "Female"
if AICharacterChoice == "Selena":
AIChoiceFeatureHairLength == "Long"
AIChoiceFeatureHairColour == "Brown"
AIChoiceFeatureFacialHair == "No"
AIChoiceFeatureJewellery == "Yes"
AIChoiceFeatureHat == "No"
AIChoiceFeatureLipstick == "No"
AIChoiceGender == "Female"
if AICharacterChoice == "Helen":
AIChoiceFeatureHairLength == "Short"
AIChoiceFeatureHairColour == "Brown"
AIChoiceFeatureFacialHair == "No"
AIChoiceFeatureJewellery == "No"
AIChoiceFeatureHat == "No"
AIChoiceFeatureLipstick == "Yes"
AIChoiceGender == "Female"
if AICharacterChoice == "Jacqueline":
AIChoiceFeatureHairLength == "Long"
AIChoiceFeatureHairColour == "Red"
AIChoiceFeatureFacialHair == "Yes"
AIChoiceFeatureJewellery == "Yes"
AIChoiceFeatureHat == "No"
AIChoiceFeatureLipstick == "No"
AIChoiceGender == "Female"
#This loops the questions to ask the AI opponent
x = 1
while x == 1:
#This asks the user what question they would like to ask the AI opponent, when they ask the question the if statements will reply with a "yes" or "no" based on whether is has that feature
QuestionForAI = input("What is your question for your AI opponent? ").upper()
if QuestionForAI == "DOES YOUR CHARACTER HAVE SHORT HAIR?" and "DOES YOUR CHARACTER HAVE SHORT HAIR":
if AIChoiceFeatureHairLength == "Short":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "DOES YOUR CHARACTER HAVE LONG HAIR?" and "DOES YOUR CHARACTER HAVE LONG HAIR":
if AIChoiceFeatureHairLength == "Long":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "DOES YOUR CHARACTER HAVE FACIAL HAIR?" and "DOES YOUR CHARACTER HAVE FACIAL HAIR":
if AIChoiceFeatureHairColour == "Yes":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "IS YOUR CHARACTER MALE?" and "IS YOUR CHARACTER MALE":
if AIChoiceGender == "Male":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "IS YOUR CHARACTER FEMALE?" and "IS YOUR CHARACTER FEMALE":
if AIChoiceGender == "Female":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "DOES YOUR CHARACTER WEAR A HAT?" and "DOES YOUR CHARACTER WEAR A HAT":
if AIChoiceFeatureHat == "Yes":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "DOES YOUR CHARACTER WEAR LIPSTICK?" and "DOES YOUR CHARACTER WEAR LIPSTICK":
if AIChoiceFeatureLipstick == "Yes":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "DOES YOUR CHARACTER WEAR JEWELLERY?" and "DOESYOURCHARACTERWEARJEWELLERY?":
if AIChoiceFeatureJewellery == "Yes":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "IS YOUR CHARACTER BLONDE HAIRED?" and "IS YOUR CHARACTER BLONDE HAIRED":
if AIChoiceFeatureHairColour == "Blonde":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "IS YOUR CHARACTER BROWN HAIRED?" and "IS YOUR CHARACTER BROWN HAIRED":
if AIChoiceFeatureHairColour == "Brown":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "IS YOUR CHARACTER BALD?" and "ISYOURCHARACTERBALD?":
if AIChoiceFeatureHairLength == "Bald":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "IS YOUR CHARACTER RED HAIRED?" and "IS YOUR CHARACTER RED HAIRED":
if AIChoiceFeatureHairColour == "Red":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
</code></pre>
| 0 | 2016-10-14T08:14:21Z | 40,038,413 | <p>You're not <em>assigning</em> inside the conditional name check bit:</p>
<pre><code>AIChoiceFeatureHairLength == "Short"
</code></pre>
<p>should be:</p>
<pre><code>AIChoiceFeatureHairLength = "Short"
</code></pre>
<p>Also - I would seriously think about reading up a bit on Object-Oriented Programming. If you make your characters an object, with some associated methods - it will save you a lot of typing. I'll try and put together something for you this morning to demonstrate.</p>
<hr>
<p>EDIT - as promised. I got a bit carried away learning about <a href="http://www.nltk.org/" rel="nofollow">NLTK</a>, so for my code to work, you'll have to make sure you've got NLTK on your python distribution (you will also need <a href="http://www.numpy.org/" rel="nofollow">numpy</a> if you don't already have it):</p>
<ol>
<li>Navigate to your <code>Scripts</code> folder (i.e. <code>C:\Python27\Scripts</code>) in a command prompt (NB: assuming that you're using Windows and Python 2.7 - if not, tell me and I'll adjust answer)</li>
<li>Then type <code>pip install nltk</code></li>
</ol>
<p>I've also used a simple statistical language parser <a href="https://github.com/emilmont/pyStatParser" rel="nofollow">pyStatParser</a>. To add this to python:</p>
<ol>
<li>Download the package from <a href="https://github.com/emilmont/pyStatParser" rel="nofollow">github</a></li>
<li>Unzip into your <code>Lib</code> folder of python (i.e. <code>C:\Python27\Lib</code>) - this is just good practice</li>
<li>Navigate to folder in cmd and run the file named <code>Setup.py</code> by typing <code>python Setup.py install</code></li>
</ol>
<p>This should be all the setup you need to get the code working. Installing and playing with these packages will make your game more interesting and challenging for you to develop (in my opinion). It should also make for a more 'updatable' game.</p>
<p>Here is my code. It sets up your <code>Character</code> as a <strong>class</strong>, which you can then make instances of (an <strong>object</strong>). Classes allow you to grow your code over time - whilst having minimal impact on the code already functioning correctly:</p>
<pre><code>from stat_parser import Parser
import nltk
parser = Parser()
class Character(object):
def __init__(self, HairLen, HairCol, FacialHair, Jewel, Hat, Lipstick, Gender):
self.gender = Gender.lower()
self.hair = [HairLen.lower(), HairCol.lower()]
if FacialHair.lower() == "yes":
self.hair.append("facial")
self.extras = []
if Jewel.lower() == "yes":
self.extras.append("jewellery")
if Hat.lower() == "yes":
self.extras.append("hat")
if Lipstick.lower() == "yes":
self.extras.append("lipstick")
def answer(self, subject, adjective = ""):
# print "subject, adj: ", subject, adjective
subject = subject.lower()
adjective = adjective.lower()
if subject in ("male", "female"):
return (subject == self.gender)
elif subject == "hair":
return (adjective in self.hair)
elif subject in ("hat", "jewellery", "lipstick"):
return (subject in self.extras)
def ask_question(question, character):
pq = parser.parse(question)
tokens = nltk.word_tokenize(question)
tagged = nltk.pos_tag(tokens)
start = ' '.join(tokens[:3])
if start.lower() not in ("does your character", "is your character"):
print "Error: Question needs to start with DOES/IS YOUR CHARACTER."
ask_question(raw_input("Restate question: "))
SQ = pq[0]
if SQ.label() == "SQ":#on the right track
if SQ[-1].label() == "VP": #verb phrase (i.e. 'have short hair')
VP = SQ[-1].flatten()
if VP[0] == "have":
return character.answer(VP[2], VP[1])
elif VP[0] == "wear":
return character.answer(VP[-1])
elif SQ[-1].label() == "ADJP": #adjective phrase (i.e. 'short haired')
ADJP = SQ[-1].flatten()
return character.answer(ADJP[1][:-2], ADJP[0]) #really hacky
elif SQ[-1].label() == "NP": #noun phrase (i.e. 'your character female')
NP = SQ[-1].flatten()
if NP[-1].lower() == "bald": #special case
return character.answer("hair", NP[-1])
return character.answer(NP[-1])
else:
print "Error: Question not in correct form. Try something like:"
print " - Does your character have short hair?"
print " - Is your character short haired?"
ask_question(raw_input("Restate question: "))
def question_loop(character):
question = raw_input("Ask me a question (q to quit): ")
if question != "q":
print ask_question(question, Dave)
question_loop(character)
#I'm calling __init__ here
Dave = Character("long", "blonde", "yes", "yes", "yes", "no", "male")
question_loop(Dave)
</code></pre>
<p>The class <code>Character</code> has two associated methods (special name for functions inside classes):</p>
<ol>
<li><code>__init__</code> - this is a special python function that <strong>initialises</strong> your object. It takes a number of arguments, the first once being <code>self</code>. It can then manipulate these parameters. In my version - I set up a number of internal variables.</li>
<li><code>answer</code> - this is called in the function <code>ask_question</code> (which takes your question text and a Character instance as arguments). When you call this function, you access it as a member function of the created object <code>Dave</code> by typing <code>character.answer(arg1, arg2)</code>. This automatically passes <code>self</code> (in this example; <code>character</code>) into the function. <code>answer</code> interrogates the variables set up in <code>__init__</code> and should return the answers to your questions.</li>
</ol>
<p>The code works on the test cases you included in your answer. As parsing natural language is complicated, you might have to tweek it to accept different forms of answers.</p>
<p>Let me know if you have any questions / problems. I hope this helps. I've certainly learnt some things in answering your question anyway.</p>
| 1 | 2016-10-14T08:23:51Z | [
"python",
"output"
] |
Python - Guess Who game - Im not getting my expected output | 40,038,231 | <p>This is a small portion of my guess who game im developing that assigns the AI Opponents randomly chosen character with its linked features, and assigns those features to the feature variables. When the user asks the question the if statements will respond with a yes or no based on whether it has the features asked off, but i am not getting an expected output. I may not be able to reply with any further questions about this until i get back from college later today thanks.</p>
<p>I do not get any errors, but every response is a "No" even when the AI opponent 100% definetely has that feature. Heres the output im getting:</p>
<blockquote>
<p>What is your question for your AI opponent?
Does your character have short hair?
AI Opponent: No
What is your question for your AI opponent?
Does your character have long hair?
AI Opponent: No
What is your question for your AI opponent?
Is your character Bald?
AI Opponent: No
What is your question for your AI opponent?
Is your character male?
AI Opponent: No
What is your question for your AI opponent?
Is your character female?
AI Opponent: No</p>
</blockquote>
<pre><code>#This assigns a random character name to the variable 'AICharacterChoice'
AICharacterChoice = random.choice(["Greg", "Chris", "Jason", "Clancy", "Betty", "Selena", "Helen", "Jacqueline"])
#This simpy defines these feature variables
AIChoiceFeatureHairLength = "Unassigned"
AIChoiceFeatureHairColour = "Unassigned"
AIChoiceFeatureFacialHair = "Unassigned"
AIChoiceFeatureJewellery = "Unassigned"
AIChoiceFeatureHat = "Unassigned"
AIChoiceFeatureLipstick = "Unassigned"
AIChoiceGender = "Unassigned"
#This assigns the feature variables with features linked to that characters name
if AICharacterChoice == "Greg":
AIChoiceFeatureHairLength == "Short"
AIChoiceFeatureHairColour == "Brown"
AIChoiceFeatureFacialHair == "Yes"
AIChoiceFeatureJewellery == "Yes"
AIChoiceFeatureHat == "No"
AIChoiceFeatureLipstick == "No"
AIChoiceGender == "Male"
if AICharacterChoice == "Chris":
AIChoiceFeatureHairLength == "Long"
AIChoiceFeatureHairColour == "Blonde"
AIChoiceFeatureFacialHair == "No"
AIChoiceFeatureJewellery == "No"
AIChoiceFeatureHat == "Yes"
AIChoiceFeatureLipstick == "Yes"
AIChoiceGender == "Male"
if AICharacterChoice == "Jason":
AIChoiceFeatureHairLength == "Short"
AIChoiceFeatureHairColour == "Brown"
AIChoiceFeatureFacialHair == "Yes"
AIChoiceFeatureJewellery == "No"
AIChoiceFeatureHat == "Yes"
AIChoiceFeatureLipstick == "No"
AIChoiceGender == "Male"
if AICharacterChoice == "Clancy":
AIChoiceFeatureHairLength == "Bald"
AIChoiceFeatureHairColour == "Red"
AIChoiceFeatureFacialHair == "Yes"
AIChoiceFeatureJewellery == "No"
AIChoiceFeatureHat == "No"
AIChoiceFeatureLipstick == "No"
AIChoiceGender == "Male"
if AICharacterChoice == "Betty":
AIChoiceFeatureHairLength == "Bald"
AIChoiceFeatureHairColour == "Blonde"
AIChoiceFeatureFacialHair == "No"
AIChoiceFeatureJewellery == "Yes"
AIChoiceFeatureHat == "Yes"
AIChoiceFeatureLipstick == "Yes"
AIChoiceGender == "Female"
if AICharacterChoice == "Selena":
AIChoiceFeatureHairLength == "Long"
AIChoiceFeatureHairColour == "Brown"
AIChoiceFeatureFacialHair == "No"
AIChoiceFeatureJewellery == "Yes"
AIChoiceFeatureHat == "No"
AIChoiceFeatureLipstick == "No"
AIChoiceGender == "Female"
if AICharacterChoice == "Helen":
AIChoiceFeatureHairLength == "Short"
AIChoiceFeatureHairColour == "Brown"
AIChoiceFeatureFacialHair == "No"
AIChoiceFeatureJewellery == "No"
AIChoiceFeatureHat == "No"
AIChoiceFeatureLipstick == "Yes"
AIChoiceGender == "Female"
if AICharacterChoice == "Jacqueline":
AIChoiceFeatureHairLength == "Long"
AIChoiceFeatureHairColour == "Red"
AIChoiceFeatureFacialHair == "Yes"
AIChoiceFeatureJewellery == "Yes"
AIChoiceFeatureHat == "No"
AIChoiceFeatureLipstick == "No"
AIChoiceGender == "Female"
#This loops the questions to ask the AI opponent
x = 1
while x == 1:
#This asks the user what question they would like to ask the AI opponent, when they ask the question the if statements will reply with a "yes" or "no" based on whether is has that feature
QuestionForAI = input("What is your question for your AI opponent? ").upper()
if QuestionForAI == "DOES YOUR CHARACTER HAVE SHORT HAIR?" and "DOES YOUR CHARACTER HAVE SHORT HAIR":
if AIChoiceFeatureHairLength == "Short":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "DOES YOUR CHARACTER HAVE LONG HAIR?" and "DOES YOUR CHARACTER HAVE LONG HAIR":
if AIChoiceFeatureHairLength == "Long":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "DOES YOUR CHARACTER HAVE FACIAL HAIR?" and "DOES YOUR CHARACTER HAVE FACIAL HAIR":
if AIChoiceFeatureHairColour == "Yes":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "IS YOUR CHARACTER MALE?" and "IS YOUR CHARACTER MALE":
if AIChoiceGender == "Male":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "IS YOUR CHARACTER FEMALE?" and "IS YOUR CHARACTER FEMALE":
if AIChoiceGender == "Female":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "DOES YOUR CHARACTER WEAR A HAT?" and "DOES YOUR CHARACTER WEAR A HAT":
if AIChoiceFeatureHat == "Yes":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "DOES YOUR CHARACTER WEAR LIPSTICK?" and "DOES YOUR CHARACTER WEAR LIPSTICK":
if AIChoiceFeatureLipstick == "Yes":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "DOES YOUR CHARACTER WEAR JEWELLERY?" and "DOESYOURCHARACTERWEARJEWELLERY?":
if AIChoiceFeatureJewellery == "Yes":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "IS YOUR CHARACTER BLONDE HAIRED?" and "IS YOUR CHARACTER BLONDE HAIRED":
if AIChoiceFeatureHairColour == "Blonde":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "IS YOUR CHARACTER BROWN HAIRED?" and "IS YOUR CHARACTER BROWN HAIRED":
if AIChoiceFeatureHairColour == "Brown":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "IS YOUR CHARACTER BALD?" and "ISYOURCHARACTERBALD?":
if AIChoiceFeatureHairLength == "Bald":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
if QuestionForAI == "IS YOUR CHARACTER RED HAIRED?" and "IS YOUR CHARACTER RED HAIRED":
if AIChoiceFeatureHairColour == "Red":
print("AI Opponent: Yes")
else:
print("AI Opponent: No")
</code></pre>
| 0 | 2016-10-14T08:14:21Z | 40,039,408 | <p><code>AIChoiceFeatureHairLength == "Short"</code> is a conditional statement, it will evaluate to either <code>True</code>or <code>False</code>. </p>
<p>What you want to do is a assignement like this: <code>AIChoiceFeatureHairLength = "Short"</code></p>
<p>I would also recomment using dictionaries like:</p>
<pre><code>Greg = {"HairLength":"Short", "HairColour":"Brown", "FacialHair":"Yes", "Jewellery":"Yes", "FeatureHat":"No", "Lipstick":"No","Gender":"Male"}`
</code></pre>
<p>You can put the dictionaries in a list (<code>[Greg, Chris, etc]</code>) and use the <code>random.choice()</code> function on that.</p>
<p>You can acces an entry in a dictionary with <code>Greg["HairLenght"]</code> and it will return <code>"Short"</code>.</p>
<p>This will shorten the code a lot and you also don't need to introduce the variables as <code>="unassigned"</code></p>
| 0 | 2016-10-14T09:16:14Z | [
"python",
"output"
] |
select identical entries in two pandas dataframe | 40,038,255 | <p>I have two dataframes. (a,b,c,d ) and (i,j,k) are the name columns dataframes</p>
<pre><code>df1 =
a b c d
0 1 2 3
0 1 2 3
0 1 2 3
df2 =
i j k
0 1 2
0 1 2
0 1 2
</code></pre>
<p>I want to select the entries that df1 is df2
I want to obtain</p>
<pre><code> df1=
a b c
0 1 2
0 1 2
0 1 2
</code></pre>
| 0 | 2016-10-14T08:15:22Z | 40,038,717 | <p>Doing a column-wise comparison would give the desired result:</p>
<pre><code>df1 = df1[(df1.a == df2.i) & (df1.b == df2.j) & (df1.c == df2.k)][['a','b','c']]
</code></pre>
<p>You get only those rows from <code>df1</code> where the values of the first three columns are identical to those of <code>df2</code>.</p>
<p>Then you just select the rows <code>'a','b','c'</code> from <code>df1</code>.</p>
| 0 | 2016-10-14T08:38:50Z | [
"python",
"pandas",
"dataframe"
] |
select identical entries in two pandas dataframe | 40,038,255 | <p>I have two dataframes. (a,b,c,d ) and (i,j,k) are the name columns dataframes</p>
<pre><code>df1 =
a b c d
0 1 2 3
0 1 2 3
0 1 2 3
df2 =
i j k
0 1 2
0 1 2
0 1 2
</code></pre>
<p>I want to select the entries that df1 is df2
I want to obtain</p>
<pre><code> df1=
a b c
0 1 2
0 1 2
0 1 2
</code></pre>
| 0 | 2016-10-14T08:15:22Z | 40,038,777 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html" rel="nofollow"><code>isin</code></a> for compare <code>df1</code> with each column of <code>df2</code>:</p>
<pre><code>dfs = []
for i in range(len(df2.columns)):
df = df1.isin(df2.iloc[:,i])
dfs.append(df)
</code></pre>
<p>Then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> all mask together:</p>
<pre><code>mask = pd.concat(dfs).groupby(level=0).sum()
print (mask)
a b c d
0 True True True False
1 True True True False
2 True True True False
</code></pre>
<p>Apply <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>print (df1.ix[:, mask.all()])
a b c
0 0 1 2
1 0 1 2
2 0 1 2
</code></pre>
| 1 | 2016-10-14T08:42:31Z | [
"python",
"pandas",
"dataframe"
] |
Create output in Array list | 40,038,257 | <p>An example of my input is:</p>
<pre><code>3->0 0->1 1->2 2->3
</code></pre>
<p>I need to produce output in an array list </p>
<pre><code>{3,0,1,2}
</code></pre>
<p>How can I achieve this?</p>
| -2 | 2016-10-14T08:15:25Z | 40,038,735 | <p>If you want the numbers located before the "arrows" (<code>-></code>), here is a solution using <a href="https://docs.python.org/3/library/re.html" rel="nofollow"><code>re</code></a> :</p>
<pre><code>>>> list(map(int, re.findall('[0-9](?=->)', '3->0 0->1 1->2 2->3')))
[3, 0, 1, 2]
</code></pre>
<p>I'm using <a href="https://docs.python.org/3/library/functions.html#map" rel="nofollow"><code>map</code></a> to convert the strings to int.</p>
<p><strong>More informations on the regex used :</strong></p>
<p>I'm using a lookahead expression (<code>(?=-></code>)) to match only something located before this string : <code>'->'</code>.
And what I am looking for is a number between 0 and 9, thanks to the set of characters <code>[0-9]</code>.</p>
<p>Please note that this won't match <code>10</code> for example. In this case, I need to change the regex to the following : <code>[0-9]+(?=->)</code>, to match 1 or more numbers.</p>
| 0 | 2016-10-14T08:40:24Z | [
"python"
] |
Data buffering/storage - Python | 40,038,258 | <p>I am writing an embedded application that reads data from a set of sensors and uploads to a central server. This application is written in Python and runs on a Rasberry Pi unit. </p>
<p>The data needs to be collected every 1 minute, however, the Internet connection is unstable and I need to buffer the data to a non volatile storage (SD-card) etc. whenever there is no connection. The buffered data should be uploaded as and when the connection comes back.</p>
<p>Presently, I'm thinking about storing the buffered data in a SQLite database and writing a cron job that can read the data from this database continuously and upload.</p>
<p>Is there a python module that can be used for such feature? </p>
| 0 | 2016-10-14T08:15:28Z | 40,038,345 | <p>This is only database work. You can create a master and slave databases in different locations and if one is not on the network, will run with the last synched info.</p>
<p>And when the connection came back hr merge all the data.</p>
<p>Take a look in this <a href="http://stackoverflow.com/questions/2366018/how-to-re-sync-the-mysql-db-if-master-and-slave-have-different-database-incase-o">answer</a> and search for master and slave database</p>
| -1 | 2016-10-14T08:19:58Z | [
"python",
"offline",
"buffering"
] |
Data buffering/storage - Python | 40,038,258 | <p>I am writing an embedded application that reads data from a set of sensors and uploads to a central server. This application is written in Python and runs on a Rasberry Pi unit. </p>
<p>The data needs to be collected every 1 minute, however, the Internet connection is unstable and I need to buffer the data to a non volatile storage (SD-card) etc. whenever there is no connection. The buffered data should be uploaded as and when the connection comes back.</p>
<p>Presently, I'm thinking about storing the buffered data in a SQLite database and writing a cron job that can read the data from this database continuously and upload.</p>
<p>Is there a python module that can be used for such feature? </p>
| 0 | 2016-10-14T08:15:28Z | 40,038,445 | <p>If you mean a module to work with SQLite database, check out <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>.</p>
<p>If you mean a module which can do what cron does, check out <a href="https://docs.python.org/3/library/sched.html" rel="nofollow">sched</a>, a python event scheduler.</p>
<p>However, this looks like a perfect place to implemet a task queue --using a dedicated task broker (rabbitmq, redis, zeromq,..), or python's <a href="https://docs.python.org/3/library/threading.html" rel="nofollow">threads</a> and <a href="https://docs.python.org/2/library/queue.html" rel="nofollow">queues</a>. In general, you want to submit an upload task, and worker thread will pick it up and execute, while the task broker handles retries and failures. All this happens asynchronously, without blocking your main app.</p>
<p>UPD: Just to clarify, you don't need the database if you use a task broker, because a task broker stores the tasks for you. </p>
| 0 | 2016-10-14T08:25:45Z | [
"python",
"offline",
"buffering"
] |
Data buffering/storage - Python | 40,038,258 | <p>I am writing an embedded application that reads data from a set of sensors and uploads to a central server. This application is written in Python and runs on a Rasberry Pi unit. </p>
<p>The data needs to be collected every 1 minute, however, the Internet connection is unstable and I need to buffer the data to a non volatile storage (SD-card) etc. whenever there is no connection. The buffered data should be uploaded as and when the connection comes back.</p>
<p>Presently, I'm thinking about storing the buffered data in a SQLite database and writing a cron job that can read the data from this database continuously and upload.</p>
<p>Is there a python module that can be used for such feature? </p>
| 0 | 2016-10-14T08:15:28Z | 40,038,789 | <blockquote>
<p>Is there a python module that can be used for such feature? </p>
</blockquote>
<p>I'm not aware of any readily available module, however it should be quite straight forward to build one. Given your requirement:</p>
<blockquote>
<p>the Internet connection is unstable and I need to buffer the data to a non volatile storage (SD-card) etc. whenever there is no connection. The buffered data should be uploaded as and when the connection comes back.</p>
</blockquote>
<p>The algorithm looks something like this (pseudo code):</p>
<pre><code># buffering module
data = read(sensors)
db.insert(data)
# upload module
# e.g. scheduled every 5 minutes via cron
data = db.read(created > last_successful_upload)
success = upload(data)
if success:
last_successful_upload = max(data.created)
</code></pre>
<p>The key is to seperate the buffering and uploading concerns. I.e. when reading data from the sensor don't attempt to immediately upload, always upload from the scheduled module. This keeps the two modules simple and stable.</p>
<p>There are a few edge cases however that you need to concern yourself with to make this work reliably:</p>
<ol>
<li>insert data while uploading is in progress</li>
<li>SQLlite doesn't support being accessed from multiple processes well</li>
</ol>
<p>To solve this, you might want to consider another database, or create multiple SQLite databases or even flat files for each batch of uploads. </p>
| 0 | 2016-10-14T08:43:10Z | [
"python",
"offline",
"buffering"
] |
Matplotlib : single line chart with different markers | 40,038,470 | <p>I have a list for markers on my time series depicting a trade. First index in each each list of the bigger list is the index where i want my marker on the line chart. Now I want a different marker for buy and sell</p>
<pre><code>[[109, 'sell'],
[122, 'buy'],
[122, 'sell'],
[127, 'buy'],
[131, 'sell'],
[142, 'buy'],
[142, 'sell'],
[150, 'buy']]
</code></pre>
<p>code:</p>
<pre><code>fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot(1,1,1)
ax.set_ylim( min(timeSeriesList_1)-0.5, max(timeSeriesList_1)+0.5)
start, end = 0, len(timeSeriesList_index)
stepsize = 10
ax.xaxis.set_ticks(np.arange(start, end, stepsize))
ax.set_xticklabels(timeSeriesList_index2, rotation=50)
## change required here:
ax.plot(timeSeriesList_1, '-gD', markevery= [ x[0] for x in markers_on_list1])
</code></pre>
<p>This is how my chart looks:</p>
<p><a href="https://i.stack.imgur.com/MCvrv.png" rel="nofollow"><img src="https://i.stack.imgur.com/MCvrv.png" alt="enter image description here"></a></p>
<p>Please tell me, how I can have different markers for buy and sell.</p>
| 0 | 2016-10-14T08:26:54Z | 40,038,728 | <p>Create two new arrays, one buy-array and one sell-array and plot them individually, with different markers. To create the two arrays you can use list-comprehension</p>
<pre><code>buy = [x[0] for x in your_array if x[1]=='buy']
sell = [x[0] for x in your_array if x[1]=='sell']
</code></pre>
| 0 | 2016-10-14T08:39:48Z | [
"python",
"matplotlib",
"time-series"
] |
I have a numpy array, and an array of indexs, how can I access to these positions at the same time | 40,038,557 | <p>for example, I have the numpy arrays like this</p>
<pre><code>a =
array([[1, 2, 3],
[4, 3, 2]])
</code></pre>
<p>and index like this to select the max values</p>
<pre><code>max_idx =
array([[0, 2],
[1, 0]])
</code></pre>
<p>how can I access there positions at the same time, to modify them.
like "a[max_idx] = 0" getting the following</p>
<pre><code>array([[1, 2, 0],
[0, 3, 2]])
</code></pre>
| 1 | 2016-10-14T08:31:36Z | 40,038,640 | <p>Simply use <code>subscripted-indexing</code> -</p>
<pre><code>a[max_idx[:,0],max_idx[:,1]] = 0
</code></pre>
<p>If you are working with higher dimensional arrays and don't want to type out slices of <code>max_idx</code> for each axis, you can use <code>linear-indexing</code> to assign <code>zeros</code>, like so -</p>
<pre><code>a.ravel()[np.ravel_multi_index(max_idx.T,a.shape)] = 0
</code></pre>
<p>Sample run -</p>
<pre><code>In [28]: a
Out[28]:
array([[1, 2, 3],
[4, 3, 2]])
In [29]: max_idx
Out[29]:
array([[0, 2],
[1, 0]])
In [30]: a[max_idx[:,0],max_idx[:,1]] = 0
In [31]: a
Out[31]:
array([[1, 2, 0],
[0, 3, 2]])
</code></pre>
| 1 | 2016-10-14T08:35:57Z | [
"python",
"arrays",
"numpy"
] |
Subsets and Splits