FAQ Database Discussion Community


multiple iteration of the same list

python,python-2.7,python-3.x,numpy,shapely
I have one list of data as follows: from shapely.geometry import box data = [box(1,2,3,4), box(4,5,6,7), box(1,2,3,4)] sublists = [A,B,C] The list 'data' has following sub-lists: A = box(1,2,3,4) B = box(4,5,6,7) C = box(1,2,3,4) I have to check if sub-lists intersect. If intersect they should put in one tuple;...

Benefit of using os.mkdir vs os.system(“mkdir”)

python,python-2.7
Simple question that I can't find an answer to: Is there a benefit of using os.mkdir("somedir") over os.system("mkdir somedir") or subprocess.call(), beyond code portability? Answers should apply to Python 2.7. Edit: the point was raised that a hard-coded directory versus a variable (possibly containing user-defined data) introduces the question of...

RTC to Git Migration using rtc2git - https://github.com/WtfJoke/rtc2git

git,python-2.7,python-3.x,rtc
I need to migrate the source code from RTC SCM to Git along with the history. I have seen a post put in this link and tried downloading it from GitHub and I get compilation error when I execute the "migration.py" script. First I tried to Insatll Python version 3...

python - how to properly evaluate a value from a system command

python,python-2.7
I'm just learning python (using 2.7.8) and i'm trying to figure out what is the best way to evaluate the output of a system command. I've read to use subprocess. For example, I need to run this IF statment and evaluate for anything > 0, then process it. Example of...

Is there a way to say for every x values, do this?

python,python-2.7
Before I start, I am new to Python, so any low-level description would be incredibly helpful! I have a list of lets say 60 values (representing one hour, from 8:00-9:00) and I want to run average, maximums, minimums, and standard deviation for each set of 15. (I already have the...

summing string and integers in list in python

python,python-2.7
I am trying to write a blackjack code in python 2.7 and can't figure out how to sum my c1 and c2 once an output is given. This is what I have so far: def blackjackTips(c1,c2): print "Welcome to Blackjack!" print "Your cards are", name[c1-1],"&",name[c2-1] total= sum ([c1]+[c2]) print "Your...

Simulating Fibonacci's Rabbits with multiple offsprings using python

python,python-2.7,dynamic-programming
Suppose I start with one pair of rabbit and each pair reproduces 3 pairs of rabbits. Let new rabbit pair be N and mature rabbit pair be M: N 0 M 1 MNNN 4 MNNN MMM MMM MMM 19 So the series is 0 1 4 19 How do we...

'ls' is not recognized in Anaconda Python 2.7 Spyder

python-2.7,anaconda,spyder
I run my codes in Anaconda Spyder Python 2.7 for Windows 7 64bits. But when I run this code: !ls -lh ./training3.crfsuite I received this error: 'ls' is not recognized as an internal or external command, operable program or batch file. Does anyone know why? Thank you....

Slicing a Python OrderedDict

python-2.7,slice,ordereddictionary
In my code I frequently need to take a subset range of keys+values from a Python OrderedDict (from collections package). Slicing doesn't work (throws TypeError: unhashable type) and the alternative, iterating, is cumbersome: from collections import OrderedDict o = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)]) # want to...

Stopping list selection in Python 2.7

python,list,python-2.7
Imagine that I have an order list of tuples: s = [(0,-1), (1,0), (2,-1), (3,0), (4,0), (5,-1), (6,0), (7,-1)] Given a parameter X, I want to select all the tuples that have a first element equal or greater than X up to but not including the first tuple that has...

Update label's text when pressing a button in Kivy for Python

python,python-2.7,button,label,kivy
Here is my code: I want to make a game where the main_label changes text when you press a button but I've looked everywhere for a week and still don't understand how to do it. I looked on Kivy's website but I don't understand. As you can see I'm new...

how to fetch a column in browse_record_list in orm browse method in openERP

python-2.7,orm,openerp-7
I'm beginner in openERP. I'm trying to get a column in a table. While using ORM browse method and iterating that object i got the result in browse_record_list as browse_record(table.name,21). I want to fetch that particular id 21 alone through that browse method but instead im getting same browse_record as...

Concatenate a list of series into a uid

python,python-2.7,pandas,py.test
I have a Pandas data frame with several columns that together make up a unique identifier. I want to write a generic test case that allows me to concatenate those columns together into a single column (uid) and test that column for uniqueness. I have the following code as a...

Count function counting only last line of my list

python,python-2.7
Count function counting only last line of my list N = int(raw_input()) cnt = [] for i in range(N): string = raw_input() for j in range(1,len(string)): if string[j] =='K': cnt.append('R') elif string[j] =='R': cnt.append('R') if string[0] == 'k': cnt.append('k') elif string[0] == 'R': cnt.append('R') print cnt.count('R') if I am giving...

PySerial client unable to write data

python,python-2.7,pyserial
I'm trying to write a python program which can communicate over a serial interface using PySerial module as follows: import serial if __name__ == '__main__': port = "/dev/tnt0" ser = serial.Serial(port, 38400) print ser.name print ser.isOpen() x = ser.write('hello') ser.close() print "Done!" But if I execute the above I get...

Adding time/duration from CSV file

python,python-2.7,csv,datetime
I am trying to add time/duration values from a CSV file that I have but I have failed so far. Here's the sample csv that I'm trying to add up. Is getting this output possible? Output: I have been trying to add up the datetime but I always fail: finput...

Python initialize strings as variable

python,python-2.7
I have a calculation schema as string calc = "((k+m+46)/2)" and some strings containing variable like m = 2 k = m*2 all only strings. Now I want to initialize them into Python. my goal is it to calculate with the calculating schema the varible values. calc should return 26...

Compare 2 csv files and output different rows to a 3rd CSV file using Python 2.7

python,python-2.7,csv,compare
I am trying to compare two csv files and find the rows that are different using python 2.7. The rows are considered different when all columns are not the same. The files will be the same format with all the same columns and will be in this format. oldfile.csv ID...

Python code not executing in order? MySQLdb UPDATE commits in unexpected order

python,python-2.7,threadpool,mysql-python
I've got a Python 2.7 script I'm working on that retrieves rows from a MySQL table, loops through the data to process it, then is supposed to do the following things in this order: UPDATE the table rows we just got previously to set a locked value in each row...

Calculate, Sort and rearrange components

python,python-2.7
Iimport list is a list with different components. The scripts calculates how many same components are there. I'm trying to sort them and put "part" in front of them. Code: Using code from @MagunRa Input File (new): Part Value Package Library Position (mm) Orientation C1 100n C0402 rcl (117.65 40.75)...

Reading inputs written in different lines from a file and storing each input inside a list

python,python-2.7
I'm trying to read a file named one.txt which contains the following: hat cow Zu6 This is a sentence and I'm trying to store each string written on each line inside a list. For example, my output list should contain the following elements: ['hat', 'cow', 'Zu6', 'This is a sentence']...

Compare 2 seperate csv files and write difference to a new csv file - Python 2.7

python,python-2.7,csv,compare
I am trying to compare two csv files in python and save the difference to a third csv file in python 2.7. import csv f1 = open ("olddata/file1.csv") oldFile1 = csv.reader(f1) oldList1 = [] for row in oldFile1: oldList1.append(row) f2 = open ("newdata/file2.csv") oldFile2 = csv.reader(f2) oldList2 = [] for...

Open a file from user input in python 2.7

python,python-2.7,user-interface,user-input
How would I open a file by asking for user input? After raw_input("PROMPT") requests filename.txt from the user, I get the error code: TypeError: coercing to Unicode: need string or buffer, file found which tells me I need to convert the user input to a string, or format it a...

Python: Exiting python.exe after Popen?

python,python-2.7
Small nagging issue: I have a python script that is working as expected, except when I select a menu option to Popen another python script: myPath = r"c:\Python27\myScript.py" cmd = r"c:\Python27\python.exe '{}'".format(myPath) py_process = Popen(cmd, stdout=PIPE, stdin=PIPE, stderr=STDOUT) When I run that snippet (in windows), the child process is kicked-off...

Pass function call as a function argument

python,python-2.7,python-3.x
Code: def function1(a,b): return a-1,b-1 def function2(c,d): return c+1,d+1 print function1(function2(1,2)) Error: Traceback (most recent call last): File "C:\Users\sony\Desktop\Python\scripts\twitter_get_data.py", line 6, in <module> print function1(function2(1,2)) TypeError: function1() takes exactly 2 arguments (1 given) [Finished in 0.1s with exit code 1] Why the above error? ...

Use NamedTemporaryFile to read from stdout via subprocess on Linux

python-2.7,subprocess,temporary-files
import subprocess import tempfile fd = tempfile.NamedTemporaryFile() print(fd) print(fd.name) p = subprocess.Popen("date", stdout=fd).communicate() print(p[0]) fd.close() This returns: <open file '<fdopen>', mode 'w' at 0x7fc27eb1e810> /tmp/tmp8kX9C1 None Instead, I would like it to return something like: Tue Jun 23 10:23:15 CEST 2015 I tried adding mode="w", as well as delete=False, but...

Replacing string in script from another script

python,python-2.7
I have a Python script with a string, I want to replace the string using another script. I am not allowed to modify anything else in the original script other than the string in question. script.py string1 = 'OriginalValue' replaceString.py string1 = 'newValue' script.py string1 = 'newValue' Is this possible,...

Issue while sharing semaphore objects between process in parallel python

python,python-2.7,multiprocessing,parallel-python
I am facing issue while passsing any semaphore objects or synchronizing objects like Events, pipes , queues etc to a child process when used with parallel python I am getting following error when i passed a Queue to child process. ' through inheritance' % type(self).__name__ RuntimeError: Queue objects should only...

Problems with tk entry and optionmenu widget in currency converter

python,python-2.7,tkinter
I am currently having problems with my currency converter program in my python class. I am trying to convert an amount, the entry widget, from the starting currency, the first option menu, to the desired currency, the second option menu. I have spent hours reading the documentation, so I hope...

Python: Terminate subprocess = Success, but it's still running (?)

python,python-2.7
I have a simple script that calls another python script as a subprocess. I can confirm the subprocess is started and I can grab its PID. When I attempt to terminate the subprocess (in win), I get the SUCCESS message against the correct PID, but Windows task manager shows the...

How to specify string variables as unicode strings for pattern and text in regex matching?

regex,python-2.7,unicode
>>> import re >>> re.match(u'^[一二三四五六七]、', u'一、') If the pattern and the text are stored in variables (for example, they were read from text files), >>> myregex='^[一二三四五六七]、' >>> mytext='一、' How shall I specify myregex and mytext to re.match, in the same way as re.match(u'^[一二三四五六七]、', u'一、')? Thanks....

Zero out portion of multidim numpy array

python-2.7,image-processing,numpy
I have an numpy array with dimensions (200, 200, 3). It is an RGB image. I also have the (xmin,ymin,xmax,ymax) coordinates of a region of this image that I would like to set to zero. This region should be zero in all three channels. I can of course solve this...

Scrapy running from python script processes only start url

python,python-2.7,scrapy
I have written a Scrapy CrawlSpider. class SiteCrawlerSpider(CrawlSpider): name = 'site_crawler' def __init__(self, start_url, **kw): super(SiteCrawlerSpider, self).__init__(**kw) self.rules = ( Rule(LinkExtractor(allow=()), callback='parse_start_url', follow=True), ) self.start_urls = [start_url] self.allowed_domains = tldextract.extract(start_url).registered_domain def parse_start_url(self, response): external_links = LinkExtractor(allow=(), deny=self.allowed_domains).extract_links(response) for link in external_links: i =...

monosubstitution cypher : decryption in python 2.7 list trouble

python-2.7
I'm currently coding a simple monosubsubstitution cypher in python. The encryption goes this way: first a key to encypher is produce this way def non_random_key(key_name): my_alphabet = [] for char in alphabet: my_alphabet.append(char) my_key_alphabet = list(key_name) for char in key_name: my_alphabet.remove(char) return my_key_alphabet + my_alphabet Then a message is encrypted...

Instagram API Comments Created using Python (ERROR: AttributeError)

python,api,python-2.7,instagram,instagram-api
Hello I trying out Instagram API using python and I am new to it. Hope you guys could take a look at it & help me out. I am wondering how to collect the date & time from users that have commented for each media id. I have tried using...

Identifying the nearest grid point

python,python-2.7,numpy
I have three arrays lat=[15,15.25,15.75,16,....30] long=[91,91.25,91.75,92....102] data= array([[ 0. , 0. , 0. , ..., 0. , 0. , 0. ], [ 0. , 0. , 0. , ..., 0. , 0. , 0. ], [ 0. , 0. , 0. , ..., 0. , 0. , 0. ], ...,...

Import on class instanciation

python,python-2.7
I'm creating a module with several classes in it. My problem is that some of these classes need to import very specific modules that needs to be manually compiled or need specific hardware to work. There is no interest in importing every specific module up front, and as some modules...

django-admin startproject not working with python3 on OS X

python,django,osx,python-2.7,python-3.x
I have python3 installed with Django 1.8.2 on Mac OS. There is also python 2.7 installed by default with the OS. When trying to run startproject I get - $ django-admin startproject mysite Traceback (most recent call last): File "/usr/local/bin/django-admin", line 7, in <module> from django.core.management import execute_from_command_line ImportError: No...

Using OR operator in NumPy Array to Append multiple items

python-2.7,numpy,arcgis,arcpy
I am using a NumPy array to feature class in Esri ArcGIS. I have a tuple of items that I am appending to a NumPy array. One field/column should be able to use multiple values depnding on the proxy input, i.e. if the category is a bulky item then the...

python class factory inherit random parent

python,python-2.7,inheritance,factory
I have some code like this: class Person(object): def drive(self, f, t): raise NotImplementedError class John(Person): def drive(self, f, t): print "John drove from %s to %s" % (f,t) class Kyle(Person): def drive(self, f, t): print "Kyle drove from %s to %s" % (f,t) class RandomPerson(Person): # instansiate either John...

Python: Non repeating random values from list [duplicate]

python,string,python-2.7,random
This question already has an answer here: How to generate random numbers that are different? [duplicate] 3 answers I am trying to write a program in python 2.7 that has to choose more than one random variable and print it out. But the variable can't be the same as...

Python PodSixNet Error

python,python-2.7,pygame,multiplayer
I'm trying to use a multiplayer module called PodSixNet to use in one of my games, but I get an error in assyncore.py when trying to run the client. However, the server works flawlessly. I developed simple test client and server programs, but I still get the same error when...

'unicode' object has no attribute 'get' Django beginner

django,python-2.7,django-forms
I have a very simple code in Django and I've this error which comes everytime. The content of the form is well saved in the model but this error shows up when I want to use reverse: 'unicode' object has no attribute 'get' There is my code: views.py: class PastaView(View):...

delete data from mysql table based on multiple conditions

php,mysql,python-2.7
i need to delete rows from MySQL table which is very huge.I have multiple conditions check before deleting the data. my table looks like: data(table name): name mobile email address source xyz 871 a@y.com 1.txt bac 123 null 2.XLS TST 456 B@C.COM 3.xls yup 897 null abcde web null D@gmail.com...

Sort List of Numbers according to Custom Number Sequence

list,python-2.7,sorting
Question :A set of numbers will be passed as input. Also the redefined relationship of the digits 0-9 in ascending order will be passed as input. Based on the redefined relationship, the set of numbers must be listed in ascending order. Input Format: The first line will contain the the...

lambda for RDD query with if statement

python-2.7,pyspark
I'm creating an RDD which queries access logs. I want to extract all 404 errors (the logs are objects which can be queried. I'm using this code, but it seems I can't use pass in a lambda statement: badRecords = (access_logs.map(lambda log: log if log.response_code == 404 else pass)) print...

Scrapy Memory Error (too many requests) Python 2.7

python,django,python-2.7,memory,scrapy
I've been running a crawler in Scrapy to crawl a large site I'd rather not mention. I use the tutorial spider as a template, then I created a series of starting requests and let it crawl from there, using something like this: def start_requests(self): f = open('zipcodes.csv', 'r') lines =...

I need to make sure that only certain characters are in a list?

python,regex,string,list,python-2.7
I have this to get input and put it in a list: def start(): move_order=[raw_input("Enter your moves: ").split()] And I only want the characters A, D, S, C, H (it's for a game >_>) to be allowed. I've tried using the regular expressions stuff: if re.match('[ADSCH]+', [move_order]) is False: print...

Concatenation of strings array issues in Python: Str(ArrayOfString[1])+“ ”+Str(ArrayOfString[2]) doesn't seem to work

string,python-2.7,concatenation,slice,string-length
Hi I have a problem with a python script, I don't manage to do a concatenation of 2 arrays of strings it returns- SyntaxError: can't assign to function call Here's my script: import os, sys, MySQLdb # connecting to a database db = MySQLdb.connect(host="localhost", user="MyUser", passwd="MyPassword",db="MyDB") cursor = db.cursor() cursor.execute("SELECT...

Why am I getting a (NameError: name 'self' is not defined ) here using Kivy for Python?

python,python-2.7,kivy,self,nameerror
I'm making a game and I'm working on the screen switching. I want the screen to switch when I press the "play" button but I get a NameError instead. Here's the code: class menu_screen(Screen): def __init__(self, **kwargs): super (menu_screen,self).__init__(**kwargs) menu_layout = FloatLayout logo_label = Label(text = "GAME", size_hint=(.6, .2),pos_hint={'x':.2, 'y':.65})...

Syntax Error (FROM) in Python, I do not want to use it as function but rather use it as to print something

python,python-2.7
I am trying to print out usernames from Instagram. When I type in print i.from.username, there will be syntax error because Python thinks that I am using from function, which i actually not. for i in a: print i.from.username Is there anyway to troubleshoot it? I tried using making a...

Reading strings written in multiple lines from a file and storing each string in a different variable

python,python-2.7
I have a text file called one.txt, which contains the following string, each in a different line: hat cow Zu6 This is a sentence Now, I want to store each string from each line in a different variable. For example: a = 'hat' b = 'cow' c = 'Zu6' d...

Keep strings that occur N times or more

python,python-2.7,counter
I have a list that is mylist = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd'] And I used Counter from collections on this list to get the result: from collection import Counter counts = Counter(mylist) #Counter({'a': 3, 'c': 2, 'b': 2, 'd': 1}) Now I want to subset this...

Appending lines for existing file in python [duplicate]

python,file,python-2.7,io
This question already has an answer here: How do you append to a file in Python? 6 answers I want to add lines to an existing file in python. I wrote the following two files print_lines.py while True: curr_file = open('myfile',r) lines = curr_file.readlines() for line in lines: print...

What is the difference between <> and == in python?

python-2.7
In [142]: (MON,TUE,WED,THR,FRI,SAT,SUN)<>range(7) Out[142]: True In [143]: (MON,TUE,WED,THR,FRI,SAT,SUN)==range(7) Out[143]: False ...

How do I copy a row from one pandas dataframe to another pandas dataframe?

python,python-2.7,pandas,dataframes
I have a dataframe of data that I am trying to append to another dataframe. I have tried various ways with .append() and there has been no successful way. When I print the data from iterrows. I provide 2 possible ways I tried to solve the issue below, one creates...

Strange Behavior: Floating Point Error after Appending to List

python,python-2.7,behavior
I am writing a simple function to step through a range with floating step size. To keep the output neat, I wrote a function, correct, that corrects the floating point error that is common after an arithmetic operation. That is to say: correct(0.3999999999) outputs 0.4, correct(0.1000000001) outputs 0.1, etc. Here's...

How to print words from a word list that have 5 letters or less Python 2.7?

python,list,python-2.7
I'm sorta new to python, which you can probably see by my crappy coding below. If you were to play this game, you would probably find that it's really hard, so to make it easier, I want to make it so it only gives the user 5 letter words or...

Installing Python to a home directory

python,python-2.7
I'm using Python 2.6.6 and I'm getting errors when connecting over https with urllib.request.build_opener(...).open(request) urlopen error [Errno 1] _ssl.c:504: error:14077438:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert internal error I've found that there is problem with TLS SNI, which was added in version 2.7.9. I tried pyOpenSSL (just copied it to my *.py script directory)...

Iterate over all links/sub-links with Scrapy run from script

python,windows,python-2.7,web-scraping,scrapy
I want to run Scrapy Spider from my script, but it works only for 1 request. I cannot execute the procedure self.parse_product from scrapy.http.Request(product_url, callback=self.parse_product). I guess it's being due the command crawler.signals.connect(callback, signal=signals.spider_closed). Please advise how correctly go over all links and sub-links. Whole script is shown below. import...

Python Popen - wait vs communicate vs CalledProcessError

python,python-2.7,error-handling,popen
Continuing from my previous question I see that to get the error code of a process I spawned via Popen in python I have to call either wait() or communicate() (which can be used to access the Popen stdout and stderr attributes): app7z = '/path/to/7z.exe' command = [app7z, 'a', dstFile.temp,...

How to remove structure with python from this case?python,python-2.7
How to remove "table" from HTML using python? I had case like this: paragraph = ''' <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quidem molestiae consequuntur officiis corporis sint.<br /><br /> <table> <tr> <td> text title </td> <td> text title 2 </td> </tr> </table> <p> lorem ipsum</p> ''' how...

Why does `for lst in lst:` work? [duplicate]

python,python-2.7
This question already has an answer here: Why can I use the same name for iterator and sequence in a Python for loop? 6 answers The following code lst = ['foo', 'bar', 'baz'] for lst in lst: print lst gives me this output foo bar baz I would expect...

Problems with MySQLdb python

python,python-2.7,tkinter,mysql-python
When I try connect to mysql with user "root", my application returns "Access denied for user *"ODBC"@"localhost" (using password:NO)"*. I dnt know why this appear. Im using Tkinter like GUI, I tested only Connection's script, its Okay. Code Connection import MySQLdb class Conexao(): def __init__(self, host,user,passwd,db): self.host = host self.user...

List of tuples from (a, all b) to (b, all a)

python,list,python-2.7,tuples
I am starting with a list of tuples (a,all b). I want to end with a list of tuples (b,all a). For example: FROM (a1,[b1,b2,b3]) (a2,[b2]) (a3,[b1,b2]) TO (b1,[a1,a3]) (b2[a1,a2,a3]) (b3,[a1] How do I do this using Python 2? Thank you for your help....

Parse text from a .txt file using csv module

python,python-2.7,parsing,csv
I have an email that comes in everyday and the format of the email is always the same except some of the data is different. I wrote a VBA Macro that exports the email to a text file. Now that it is a text file I want to parse the...

Datastructure choice issue

python,list,python-2.7,data-structures,tuples
I'm new to python. I need a datastructure to contain a tuple of two elements: date and file path. I need to be able to change their values from time to time, hence I'm not sure a tuple is a good idea as it is immutable, and every time I...

Who calls the metaclass

python,python-2.7,metaclass
This actually stems from a discussion here on SO. Short version def meta(name, bases, class_dict) return type(name, bases, class_dict) class Klass(object): __metaclass__ = meta meta() is called when Klass class declaration is executed. Which part of the (python internal) code actually calls meta()? Long version When the class is declared,...

Identify that a string could be a datetime object

python,regex,algorithm,python-2.7,datetime
If I knew the format in which a string represents date-time information, then I can easily use datetime.datetime.strptime(s, fmt). However, without knowing the format of the string beforehand, would it be possible to determine whether a given string contains something that could be parsed as a datetime object with the...

using configparser in python

python,python-2.7
Sorry, I am a newbie in Python and trying to work on the ConfigParser module. Here is one script which is used to read multiple sections and values from a .ini file and print them as below (Current output). Now, I would like to store each of these values of...

Python split by comma delimiter and strip

python,python-2.7
I am trying to open a file in python in read mode then write striped and split data to an output file. I am unsure how to split and strip the same data. Do I need to create a different line? Do I need to write the data out first?...

How to extract efficientely content from an xml with python?

python,xml,python-2.7,pandas,lxml
I have the following xml: <?xml version="1.0" encoding="UTF-8" standalone="no"?><author id="user23"> <document><![CDATA["@username: That boner came at the wrong time ???? http://t.co/5X34233gDyCaCjR" HELP I'M DYING ]]></document> <document><![CDATA[Ugh ]]></document> <document><![CDATA[YES !!!! WE GO FOR IT. http://t.co/fiI23324E83b0Rt ]]></document> <document><![CDATA[@username Shout out to me???? ]]></document> </author> What is the most efficient...

random.randint not generating random values

python,python-2.7,random
I am working on importing random in Python 2.7. I would like for this code to generate two random cards. The current code does not generate random cards. If I request cards (9,11) the code generates cards (9,J) totaling to 19. There is nothing random about the output. def blackjack(A,B):...

Operational error while using stripe with profile app

django,python-2.7,django-templates,stripe-payments
I am trying to embed Stripe in custom profile app and using django-registration package for registering users. I need to get users registered and then generate a Stripe ID for new users but getting the error below: OperationalError at /accounts/login/ no such table: profiles_userstripe My complete code for Profile app...

Python: matplotlib - probability mass function as histogram

python,python-2.7,matplotlib,plot,histogram
I want to draw a histogram and a line plot at the same graph. However, to do that I need to have my histogram as a probability mass function, so I want to have on the y-axis a probability values. However, I don't know how to do that, because using...

How to create dict from date (in strings) range? [duplicate]

python,python-2.7
This question already has an answer here: Print all day-dates between two dates 5 answers I have two dates as strings: start = '2015-01-01' end = '2015-03-23' And I want to create dict like this (I use OrderedDict): date_dict = { '2015-01-01': [something], '2015-01-02': [something], '2015-01-03': [something], '2015-01-04': [something],...

Reference a table column by its column header in Python

python-2.7
Is there a Pythonic way to refer to columns of 2D lists by name? I import a lot of tables from the web so I made a general purpose function that creates 2 dimensional lists out of various HTML tables. So far so good. But the next step is often...

How to check for multiple attributes in a list

python,python-2.7
I am making a TBRPG game using Python 2.7, and i'm currently making a quest system. I wanted to make a function that checks all of the quests in a list, in this case (quests), and tells you if any of of the quests in the list have the same...

iterate using yield of a dictionary of dictionaries

python-2.7
Suppose we have this dictionary and I need to walk through its branches and yields everything found in files a={'files': {'file root':'some root path', 'other file': 'other path'}, 'directories':{'directory1':{'files':{'file1':'some path'}, 'directories':{'directory2':{'files':{}, 'directories': {}}}}, 'folder1':{'files':{}, 'directories':{'folder2': {'files': {}, 'directories': {}}, 'archive1':{'files': {'empty':None}, 'directories':{}}}}} } my implementation looks like this def walk_directory_files(directory):...

How can I resolve my variable's unexpected output?

django,python-2.7
I have a variable in django named optional_message. If I debug the variable then it says Swenskt but when I try to print the variable on my page the following comes out: (u'Swenskt',) and the variable can't be tested for its length etc. What should I do if I only...

Python do a lookup between 2 dictionaries

python-2.7,dictionary,lookup
I am trying to summarise two dictionaries as follows: mydict = {41100: 'Health Grant', 50050: 'Salaries', 50150: 'Salaries', 50300: 'Salaries'}; mytb = {'': '', 41100: -3,450,200.40, 50050: 1,918,593.96, 50150: 97.50, 50300: 8,570.80} My output should be: { 'Health Grant': -3450200.40, 'Salaries': 1927262.26 } Can you help with coding the for...

How to find longest consistent increment in a python list?

python-2.7
possible_list = [] bigger_list = [] new_list= [0, 25, 2, 1, 14, 1, 14, 1, 4, 6, 6, 7, 0, 10, 11] for i in range(0,len(new_list)): # if the next index is not greater than the length of the list if (i + 1) < (len(new_list)): #if the current value...

Anaconda site-packages

python,python-2.7,pip,anaconda
After installing a package in an anaconda environment, I'll like to make some changes to the code in that package. Where can I find the site-packages directory containing the installed packages? I do not find a directory /Users/username/anaconda/lib/python2.7/site-packages...

Python - Terminate Child Process or PID?

python-2.7
I have a script (simplified below) that initiates another python process. I know the process name and PID for the current and child processes. When I attempt to terminate the child process - menu option (2) - I get the message "local variable 'py_process' referenced before assignment." Suggestions to terminate...

How can I detect a URL really exists despite a 301 or 302 redirect?

python-2.7,url
I am looking to write a function in python to confirm the existence of files that might exist on a remote server. Some of the downloads I am checking, however, are behind 301 or 302 redirects. I have tried using the requests module as follows: def exists(path): r = requests.head(path)...

'NoneType' object is not iterable - looping w/returned value

python,python-2.7
The purpose of this code is to find the longest string in alphabetical order that occurs first and return that subset. I can execute the code once, but when I try to loop it I get 'NoneType' object is not iterable (points to last line). I have made sure that...

How to skip a function

function,python-2.7
I am learning python and trying to make a little game. So my question is can you define a function but skip it and use it later. EX. def func() print"1,2,3,4" func() def func2() print "counting" func() func2() How would I skip func but still be able to print it...

Data parsing, the pythonic way

python,python-2.7
Inside fixtures.txt is the content of Premier League's fixtures for the next season. Data looks like this: foo@ubuntu:~/Desktop$ less fixtures.txt |head -n 4 8 August 2015 AFC Bournemouth v Aston Villa    #BOUAVL Arsenal v West Ham United    #ARSWHU Chelsea v Swansea City    #CHESWA I'd like to rank the fixtures for...

Python root logger messages not being logged via handler configured with fileConfig

python,python-2.7,logging,configuration-files
The Problem: Given a logging config and a logger that employs that config, I see log messages from the script in which the log handler is configured, but not from the root logger, to which the same handler is assigned. Details: (Using Python 2.7) I have a module my_mod which...

SSLV3_ALERT_HANDSHAKE_FAILURE with SNI using Tornado 4.2 in Python 2.9.10

python,python-2.7,ssl,tornado,sni
I have an issue setting the SNI flag correctly using ssl.SSLContext in Python 2.7.10, the handshake fails every time and I can't figure out why. Here is how I tried to do it: import ssl import socket if ssl.HAS_SNI: print "SNI is available" print(ssl.OPENSSL_VERSION) context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.load_cert_chain('cacrt.pem', 'cakey.pem', 'password')...

Pandas Dataframe Complex Calculation

python,python-2.7,pandas,dataframes
I have the following dataframe,df: Year totalPubs ActualCitations 0 1994 71 191.002034 1 1995 77 2763.911781 2 1996 69 2022.374474 3 1997 78 3393.094951 I want to write code that would do the following: Citations of currentyear / Sum of totalPubs of the two previous years I want something to...

How to collect data from text file to dict in Python?

python,python-2.7,csv,dictionary
I have the following table generated in a text file,"fasta.txt" A C G T 0 0.195965417867 0.322766570605 0.35446685879 0.126801152738 A1 0.25 0.1875 0.3125 0.25 C1 0.25 0.475 0.225 0.05 G1 0.135135135135 0.243243243243 0.405405405405 0.216216216216 T1 0.142857142857 0.285714285714 0.285714285714 0.285714285714 A2 0.125 0.208333333333 0.625 0.0416666666667 C2 0.0833333333333 0.416666666667 0.305555555556 0.194444444444 G2...

Parsing Google Custom Search API for Elasticsearch Documents

json,python-2.7,elasticsearch,google-search-api
After retrieving results from the Google Custom Search API and writing it to JSON, I want to parse that JSON to make valid Elasticsearch documents. You can configure a parent - child relationship for nested results. However, this relationship seems to not be inferred by the data structure itself. I've...

lookbehind for start of string or a character

regex,python-2.7,regex-lookarounds
The command re.compile(ur"(?<=,| |^)(?:next to|near|beside|opp).+?(?=,|$)", re.IGNORECASE) throws a sre_constants.error: look-behind requires fixed-width pattern error in my program but regex101 shows it to be fine. What I'm trying to do here is to match landmarks from addresses (each address is in a separate string) like: "Opp foobar, foocity" --> Must match...

Need workaround to treat float values as tuples when updating “list” of float values

python-2.7,matplotlib,computer-science,floating-point-conversion
I am finding errors with the last line of the for loop where I am trying to update the curve value to a list containing the curve value iterations. I get errors like "can only concatenate tuple (not "float) to tuple" and "tuple object has no attribute 'append'". Does anyone...

Common elements between two lists of lists (intersection of nested lists) [duplicate]

python,python-2.7,numpy,nested-lists
This question already has an answer here: Get intersecting rows across two 2D numpy arrays 3 answers I have two large lists of points in 2D and I want to find their common sublists, if they have some. Both of the lists are quite large and efficiency is an...

wxPython: Dynamically Flow Buttons to Next Row on Window-Resize

python,python-2.7,wxpython
The following wxPython sample code is meant to create some buttons and then add them to a horizontal panel in such a way that the buttons should flow to a new row when they no longer fit in the panel. In addition, the buttons should change position (increase/decrease the number...

from x(defined in program) import y(defined in program) python

python,python-2.7,import,filenames
I need some assitance since I really have no idea how I can fix this: x="test" y="test2" When I try to import y from x , it says that there is no file with the name "x" (from x import y) Is there any way to import test2 from test...

Return html code of dynamic page using selenium

python,python-2.7,selenium,selenium-webdriver,web-scraping
I'm trying to crawl this website, problem is it's dynamically loaded. Basically I want what I can see from the browser console, not what I see when I right click > show sources. I've tried some selenium examples but I can't get what I need. The code below uses selenium...

How to find Unused Security Groups of all AWS Security Groups?

python-2.7,amazon-web-services,amazon-ec2,amazon-s3,boto
How to find all the used security groups attached with all the aws resources using Boto? Currently the following script which is giving only ec2 instances- sec_grps = ec2_conn.get_all_security_groups() for group in sec_grps: print group, " Instances attached ", group.instances() Is there any way to get all security groups which...