Menu
  • HOME
  • TAGS

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

python,python-2.7,button,label,kivy

Well! there was a real need for improvement in your code. (I understand it as you are not experienced.) Improvement: 1 An application can be built if you return a widget on build(), or if you set self.root.(You shouldn't make all of the gui in build function itself.) def build(self):...

django-admin startproject not working with python3 on OS X

python,django,osx,python-2.7,python-3.x

Recommended: Try using virtualenv and initiate your environment with Python3. Or a quicker solution is to use python interpreter directly to execute django-admin: <path-to-python3>/python /usr/local/bin/django-admin startproject mysite ...

Instagram API Comments Created using Python (ERROR: AttributeError)

python,api,python-2.7,instagram,instagram-api

Unfortunately, Instagram is not very consistent in their API. The creation time of a media object is called created_time, but for a comment it is created_at. Also note there's no need to request the comments separately: they are already available for each media object, in media.comments....

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

regex,python-2.7,unicode

simply use re.match(myregex.decode('utf-8'), mytext.decode('utf-8')) ...

Datastructure choice issue

python,list,python-2.7,data-structures,tuples

Sounds like you're describing a dictionary (dict) # Creating a dict >>> d = {'Date': "12.6.15", 'FilePath': "C:\somewhere\only\we\know"} # Accessing a value based on a key >>> d['Date'] '12.6.15' # Changing the value associated with that key >>> d['Date'] = '12.15.15' # Displaying the representation of the updated dict >>>...

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

python,python-2.7

Two processes are created because you call Popen with shell=True. It looks like the only reason you need to use a shell is so you make use of the file association with the interpreter. To resolve your issue you could also try: from subprocess Popen, PIPE, STDOUT pyTivoPath = "c:\pyTivo\pyTivo.py"...

Parse text from a .txt file using csv module

python,python-2.7,parsing,csv

How about using Regular Expression def get_info(string_to_search): res_dict = {} import re find_type = re.compile("Type:[\s]*[\w]*") res = find_type.search(string_to_search) res_dict["Type"] = res.group(0).split(":")[1].strip() find_Status = re.compile("Status:[\s]*[\w]*") res = find_Status.search(string_to_search) res_dict["Status"] = res.group(0).split(":")[1].strip() find_date = re.compile("Date:[\s]*[/0-9]*") res = find_date.search(string_to_search) res_dict["Date"] = res.group(0).split(":")[1].strip() res_dict["description"] =...

random.randint not generating random values

python,python-2.7,random

You seem to be confused between defining a function and calling it and how parameters work. def blackjack(A,B): print "Welcome to Blackjack!" print "Your cards are",name[A-1],"&",name[B-1] total = value[A-1] + value[B-1] print "Your card total is",total In your function A and B are place holders. They will be replaced by...

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

python-2.7

The operator "<>" means 'not equal to', and the operator "==" means 'equal to'. The former evaluates to true if two things being compared are not equal, and the latter evaluates to true if two things being compared are equal. http://www.tutorialspoint.com/python/comparison_operators_example.htm...

Slicing a Python OrderedDict

python-2.7,slice,ordereddictionary

The ordered dict in the standard library, doesn't provide that functionality. Even though libraries existed for a few years before collections.OrderedDict that have this functionality (and provide essentially a superset of OrderedDict): voidspace odict and ruamel.ordereddict (I am the author of the latter package, which a reimplementation of odict in...

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

python,python-2.7,threadpool,mysql-python

A finally clause is guaranteed to execute, even if the try clause raises an exception. What is probably happening here is that an exception is being raised, preventing the update from being committed, but the threads are triggered anyway. This doesn't really seen to be an appropriate use of try/finally....

Problems with tk entry and optionmenu widget in currency converter

python,python-2.7,tkinter

My answer didn't satisfy me so I solved your problem. Changes: Added self keyword to currAmount1, currAmount2, and reflected this change everywhere in the script. (currAmount1 -> self.currAmount1) Called .get() on the Tkinter variables at the start of curr_search(): cur1 = self.curr_start1.get() cur2 = self.curr_start2.get() amount = self.currAmount1.get() Instead of...

Adding time/duration from CSV file

python,python-2.7,csv,datetime

Use datetime.timedelta() objects to model the durations, and pass in the 3 components as seconds, minutes and hours. Parse your file with the csv module; no point in re-inventing the character-separated-values-parsing wheel here. Use a dictionary to track In and Out values per user; using a collections.defaultdict() object will make...

PySerial client unable to write data

python,python-2.7,pyserial

Obviously, /dev/tnt0 is not a serial device, or there is something wrong with that. Otherwise, your code looks valid.

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

python,python-2.7,logging,configuration-files

A potential problem is that you are importing the module before you set up the logger configuration. That way, the module requests a logger before the logging is setup. Looking a fileConfig()'s documentation, the reason subsequent logging to the pre-obtained loggers fails is the default value for its disable_existing_loggers argument:...

Open a file from user input in python 2.7

python,python-2.7,user-interface,user-input

The issue is in the lines - selectfile = file(raw_input("Enter Filename: "), 'r') with open(selectfile, 'r') as inF: You need to open the filename (which is inputted from user) directly, as below - with open(raw_input("Enter Filename: "),'r') as inF: Also, there seems to be an indentation issue in your code,...

Return html code of dynamic page using selenium

python,python-2.7,selenium,selenium-webdriver,web-scraping

You need to explicitly wait for the search results to appear before getting the page source: from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC wd = webdriver.Firefox() wd.get("https://www.leforem.be/particuliers/offres-emploi-recherche-par-criteres.html?exParfullText=&exPar_search_=true& exParGeographyEdi=true") wd.switch_to.frame("cible") wait = WebDriverWait(wd, 10)...

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

python,windows,python-2.7,web-scraping,scrapy

Your spider is being blocked from visiting pages after the start page by your allowed_domains specification. The value should include just the domain, not the protocol. Try allowed_domains = ["www.WebStore.com"] Also the line desc_out = Join() in your WebStoreItemLoader definition may give an error as you have no desc field....

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

python-2.7,url

Use the steps outlined in diveintopython (copied and slightly cleaned bellow) if you want to use stdlib only. Otherwise, use something more nuanced (like Mechanize) to follow redirects. class SmartRedirectHandler(urllib2.HTTPRedirectHandler): def http_error_301(self, req, fp, code, msg, headers): result = urllib2.HTTPRedirectHandler.http_error_301( self, req, fp, code, msg, headers) result.status = code return...

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

python-2.7,amazon-web-services,amazon-ec2,amazon-s3,boto

This is a slightly difficult request because Security Groups are used by many different resources, including: Amazon EC2 instances Amazon RDS instances VPC Elastic Network Interfaces (ENIs) Amazon Redshift clusters Amazon ElastiCache clusters Amazon Elastic MapReduce clusters Amazon Workspaces ...and most probably other services, too To obtain a list of...

Scrapy Memory Error (too many requests) Python 2.7

python,django,python-2.7,memory,scrapy

You can process your urls by batch by only queueing up a few at time every time the spider idles. This avoids having a lot of requests queued up in memory. The example below only reads the next batch of urls from your database/file and queues them as requests only...

Identify that a string could be a datetime object

python,regex,algorithm,python-2.7,datetime

What about fuzzyparsers: Sample inputs: jan 12, 2003 jan 5 2004-3-5 +34 -- 34 days in the future (relative to todays date) -4 -- 4 days in the past (relative to todays date) Example usage: >>> from fuzzyparsers import parse_date >>> parse_date('jun 17 2010') # my youngest son's birthday datetime.date(2010,...

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

Just change your first attempt to following: if len(str(row[1])) >= 16: row[2] = str(row[1])+" "+str(row[2]) row[1] = str(row[1][0:16]) My answer is freely adapted from comment by @phylogenesis. Update: The above answer wont work because row is a tuple and hence it is immutable. You will need to assign the values...

Zero out portion of multidim numpy array

python-2.7,image-processing,numpy

Use array slicing. If xmin, xmax, ymin and ymax are the indices of area of the array you want to set to zero, then: a[xmin:xmax,ymin:ymax,:] = 0. ...

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

python,python-2.7,numpy,nested-lists

Lists are not hashable so we need to convert the inner list to tuple then we can use set intersection to find common element t1 = [[3, 41], [5, 82], [10, 31], [11, 34], [14, 54]] t2 = [[161, 160], [169, 260], [187, 540], [192, 10], [205, 23], [3,41]] nt1...

delete data from mysql table based on multiple conditions

php,mysql,python-2.7

Delete from table_xyz where right(lower(source),4) not in ('.txt','.xls','xlsx') ...

summing string and integers in list in python

python,python-2.7

You need: total = value[c1-1]+value[c2-1] ...

Python: Non repeating random values from list [duplicate]

python,string,python-2.7,random

you can use random.sample() random.sample(population, k) Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement. In [13]: "+".join(random.sample(sentences,3)) Out[13]: 'a+b+c' ...

Issue while sharing semaphore objects between process in parallel python

python,python-2.7,multiprocessing,parallel-python

You're having this issue because you're passing the queue object when you submit the job: job = jobServer.submit(startt,(e,),(),("time", ), globals = globals()) # ^ here Two things to note: The queue is already global. You don't need to pass it as an argument. You can pass the queue as an...

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

python,python-2.7

Try something like the below code to generate the keys - from datetime import datetime as dt, timedelta as td start = '2015-01-01' end = '2015-03-23' sd = dt.strptime(start,'%Y-%m-%d') ed = dt.strptime(end,'%Y-%m-%d') delta = ed - sd for i in range(delta.days+1): dict[sd + td(days=i)] = <something> ...

Identifying the nearest grid point

python,python-2.7,numpy

You can use numpy.searchsorted for this: import numpy as np lat=np.linspace(15,30,61) long=np.linspace(91,102,45) def find_index(x,y): xi=np.searchsorted(lat,x) yi=np.searchsorted(long,y) return xi,yi thisLat, thisLong = find_index(16.3,101.6) print thisLat, thisLong >>> 6, 43 # You can then access the `data` array like so: print data[thisLat,thisLong] NOTE: This will find the index of the lat and...

Python do a lookup between 2 dictionaries

python-2.7,dictionary,lookup

Just iterate the keys and values of the first dict and add the values from the second dict corresponding to the same key. mydict = {41100: 'Health Grant', 50050: 'Salaries', 50150: 'Salaries', 50300: 'Salaries'}; mytb = {'': '', 41100: -3450200.40, 50050: 1918593.96, 50150: 97.50, 50300: 8570.80} result = {} for...

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

python,python-2.7

You need to use subprocess.check_output: mycat = int(subprocess.check_output(cmd, shell=True)) ...

SSLV3_ALERT_HANDSHAKE_FAILURE with SNI using Tornado 4.2 in Python 2.9.10

python,python-2.7,ssl,tornado,sni

It is very hard to tell without having ore information about the server, but I'll try: OpenSSL 0.9.8zd 8 Jan 2015 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) You are restricting the protocol to TLS 1.0. It might be that the server expects TLS 1.2 or TLS 1.1 or SSL 3.0. Note that TLS...

'ls' is not recognized in Anaconda Python 2.7 Spyder

python-2.7,anaconda,spyder

ls is a *nix command, and is not installed under Windows by default. Use dir and its appropriate options instead.

Calculate, Sort and rearrange components

python,python-2.7

A counter dict is not the best approach for your problem, if you want to associate the value with the first part you encounter you can use the following approach which use a tuple of (Value, Package) as the key and sets the part to the first part we encounter...

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

python-2.7,orm,openerp-7

You can access all the fields of that table from the browsable object. id = browse_record.id name = browse_record.name Similarly you can access all the relational tables data as well, like customer in sale order. partner_id = sale_order_object.partner_id.id partner_name = sale_order_object.partner_id.name You can also update tables data through that browsable...

Reference a table column by its column header in Python

python-2.7

I think you'll really like the pandas module! http://pandas.pydata.org/ Put your list into a DataFrame This could also be done directly from html, csv, etc. df = pd.DataFrame(table[1:], columns=table[0]).astype(str) Access columns df['Column A'] Access first row by index df.iloc[0] Process row by row df.apply(lambda x: '_'.join(x), axis=0) for index,row in...

Replacing string in script from another script

python,python-2.7

The following replaceString.py should do it: with open('script.py') as myFile: content = myFile.readlines() with open('script.py', 'w') as myFile: for line in content: newLine = line.replace("string1 = 'OriginalValue'", "string1 = 'newValue'") myFile.write(newLine) ...

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

python,list,python-2.7,tuples

You can use collections.defaultdict: tups = [ ('a1',['b1','b2','b3']), ('a2',['b2']), ('a3',['b1','b2']) ] d = collections.defaultdict(list) for a, bs in tups: for b in bs: d[b].append(a) Then: >>> d.items() [('b1', ['a1', 'a3']), ('b2', ['a1', 'a2', 'a3']), ('b3', ['a1'])] ...

Stopping list selection in Python 2.7

python,list,python-2.7

You can simply filter the tuples from the list as a generator expression and then you can stop taking the values from the generator expression when you get the first tuple whose second element is -1, like this >>> s = [(0,-1), (1,0), (2,-1), (3,0), (4,0), (5,-1), (6,0), (7,-1)] >>>...

Count function counting only last line of my list

python,python-2.7

I don't know what you are exactly trying to achieve but if you are trying to count R and K in the string there are more elegant ways to achieve it. But for your reference I had modified your code. N = int(raw_input()) s = [] for i in range(N):...

How to find longest consistent increment in a python list?

python-2.7

One problem (but not the only one) with your code is that you are always adding the elements to the same possible_list, thus the lists in bigger_list are in fact all the same list! Instead, I suggest using [-1] to access the last element of the list of subsequences (i.e....

Simulating Fibonacci's Rabbits with multiple offsprings using python

python,python-2.7,dynamic-programming

The process for a single step is to replace all 'M's with 'MNNN' and all 'N's with 'M', so: def step(state): return ''.join(['MNNN' if s == 'M' else 'M' for s in state]) For example: >>> s = 'N' >>> for _ in range(5): print s, len(s) s = step(s)...

Python: matplotlib - probability mass function as histogram

python,python-2.7,matplotlib,plot,histogram

As far as I know, matplotlib does not have this function built-in. However, it is easy enough to replicate import numpy as np heights,bins = np.histogram(data,bins=50) heights = heights/sum(heights) plt.bar(bins[:-1],heights,width=(max(bins) - min(bins))/len(bins), color="blue", alpha=0.5) Edit: Here is another approach from a similar question: weights = np.ones_like(data)/len(data) plt.hist(data, bins=50, weights=weights, color="blue",...

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

git,python-2.7,python-3.x,rtc

Python 3.3.5 installation fixed this issue for me. Downloaded from - https://www.python.org/downloads/release/python-335/

Data parsing, the pythonic way

python,python-2.7

What is best depends on how much data you have to process. Half the problem in this case is that the data retrieval and the printing are all jumbled up. Unless you are working with really large amounts of data it is advisable to split them up. If the data...

Python Popen - wait vs communicate vs CalledProcessError

python,python-2.7,error-handling,popen

about the deadlock: It is safe to use stdout=PIPE and wait() together iff you read from the pipe. .communicate() does the reading and calls wait() for you about the memory: if the output can be unlimited then you should not use .communicate() that accumulates all output in memory. what...

Parsing Google Custom Search API for Elasticsearch Documents

json,python-2.7,elasticsearch,google-search-api

here is a possible answer to your problem. def myfunk( inHole, outHole): for keys in inHole.keys(): is_list = isinstance(inHole[keys],list); is_dict = isinstance(inHole[keys],dict); if is_list: element = inHole[keys]; new_element = {keys:element}; outHole.append(new_element); if is_dict: element = inHole[keys].keys(); new_element = {keys:element}; outHole.append(new_element); myfunk(inHole[keys], outHole); if not(is_list or is_dict): new_element = {keys:inHole[keys]}; outHole.append(new_element);...

Python - Terminate Child Process or PID?

python-2.7

Yes, it's a variable scoping issue. py_process doesn't exist on your subsequent invocations of exec_menu (after you have set it in the choice=='1'). Make it global and then it will be available when you want to stop....

Problems with MySQLdb python

python,python-2.7,tkinter,mysql-python

Like Bryan said, that may be the issue with your code, instead of making the button call conn.getConnection() directly, try an approach, where you save the entry variables into 'self' and then when the button is invoked, you create the connection at that time. The code would look something like...

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

python-2.7,matplotlib,computer-science,floating-point-conversion

You can't append to a tuple at all (tuples are immutable), and extending to a list with + requires another list. Make curveList a list by declaring it with: curveList = [] and use: curveList.append(curve) to add an element to the end of it. Or (less good because of the...

Appending lines for existing file in python [duplicate]

python,file,python-2.7,io

The issue is in the code - curr_file = open('myfile',w) curr_file.write('hello world') curr_file.close() The second argument should be a string, which indicates the mode in which the file should be openned, you should use a which indicates append . curr_file = open('myfile','a') curr_file.write('hello world') curr_file.close() w mode indicates write ,...

Using OR operator in NumPy Array to Append multiple items

python-2.7,numpy,arcgis,arcpy

Instead of doing the "OR" inside the append, you'll need to do an if statement: if category == 'bulky item': items.append((Address, x, y, x, y, ReasonCode, SRNumber, SRNumber, FullName, ResolutionCode, HomePhone, CreatedDate, UpdatedDate, BulkyItemInfo, k_bulky_comm, ServiceDate, CYLA_DISTRICT, SCCatDesc, # ServiceNotes, Prior_Resolution_Code, CYLA_DISTRICT, )) elif category == 'e-waste': items.append((Address, x, y,...

Pandas Dataframe Complex Calculation

python,python-2.7,pandas,dataframes

I believe the following does what you want: In [24]: df['New_Col'] = df['ActualCitations']/pd.rolling_sum(df['totalPubs'].shift(), window=2) df Out[24]: Year totalPubs ActualCitations New_Col 0 1994 71 191.002034 NaN 1 1995 77 2763.911781 NaN 2 1996 69 2022.374474 13.664692 3 1997 78 3393.094951 23.240376 So the above uses rolling_sum and shift to generate the...

Pass function call as a function argument

python,python-2.7,python-3.x

The functions are returning tuples, because return only gives back one item. You can "unpack" the tuple returned by prepending it with an asterisk. The syntax will look like this: print function1(*function2(1,2)) ...

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

python,python-2.7

Correctness Think about what happens if your directory name contains spaces: mkdir hello world ...creates two directories, hello and world. And if you just blindly substitute in quotes, that won't work if your filename contains that quoting type: 'mkdir "' + somedir + '"' ...does very little good when somedir...

How to extract efficientely content from an xml with python?

python,xml,python-2.7,pandas,lxml

There are several things wrong here. (Asking questions on selecting a library is against the rules here, so I'm ignoring that part of the question). You need to pass in a file handle, not a file name. That is: y = BeautifulSoup(open(x)) You need to tell BeautifulSoup that it's dealing...

multiple iteration of the same list

python,python-2.7,python-3.x,numpy,shapely

Without downloading shapely, I think what you want to do with lists can be replicated with strings (or integers): In [221]: data=['one','two','three'] In [222]: data1=['one','four','two'] In [223]: results=[[],[]] In [224]: for i in data1: if i in data: results[0].append(i) else: results[1].append(i) .....: In [225]: results Out[225]: [['one', 'two'], ['four']] Replace...

Keep strings that occur N times or more

python,python-2.7,counter

[s for s, c in counts.iteritems() if c >= 2] # => ['a', 'c', 'b'] ...

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

python,python-2.7,csv,dictionary

I think I understand the table that you have, but if the following does not work let me know. I have tried to make this code as generic as possible (i.e. reading in the header line and not assuming 4 bases as header so this could work for say a...

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

python,python-2.7

print list(open("my_text.txt")) is probably a pretty easy way to do it ... ofc people are gonna come screaming about dangling pointers so for the sake of good habits with open("my_text.txt") as f: print list(f) alternatively f.readlines() you might need to strip off some newline characters [line.strip() for line in f]...

Concatenate a list of series into a uid

python,python-2.7,pandas,py.test

Suppose you want to select columns two and three to add: col_to_add = ['two', 'three'] Use sum(axis=1) to concatenate these columns: df['uid'] = df[col_to_add].sum(axis=1) ...

How to skip a function

function,python-2.7

If I you're asking what I think you're asking, then yes. In fact, that's the whole point. Functions are sections of reusable code that you define first (they don't run when they're defined!) and then you call that function later. For example, you can define a function, helloworld like this:...

How to remove structure with python from this case?

python,python-2.7

It's complicated to use regex, a stupid way I suggested: def remove_table(s): left_index = s.find('<table>') if -1 == left_index: return s right_index = s.find('</table>', left_index) return s[:left_index] + remove_table(s[right_index + 8:]) There may be some blank lines inside the result....

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

python,python-2.7,pandas,dataframes

Use .loc to enlarge the current df. See the example below. import pandas as pd import numpy as np date_rng = pd.date_range('2015-01-01', periods=200, freq='D') df1 = pd.DataFrame(np.random.randn(100, 3), columns='A B C'.split(), index=date_rng[:100]) Out[410]: A B C 2015-01-01 0.2799 0.4416 -0.7474 2015-01-02 -0.4983 0.1490 -0.2599 2015-01-03 0.4101 1.2622 -1.8081 2015-01-04 1.1976...

Use NamedTemporaryFile to read from stdout via subprocess on Linux

python-2.7,subprocess,temporary-files

Unless stdout=PIPE; p[0] will always be None in your code. To get output of a command as a string, you could use check_output(): #!/usr/bin/env python from subprocess import check_output result = check_output("date") check_output() uses stdout=PIPE and .communicate() internally. To read output from a file, you should call .read() on the...

Installing Python to a home directory

python,python-2.7

It is possible to install any Python version assuming your server has a compiler (GCC) installed you can use. Download Python source code here. Apply basic UNIX command knowledge to download and extract Gzip archive to a folder inside your home holder. Follow instructions to compile Python. Please note that...

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

python,python-2.7

If you do lst[<start>:<end>] it would give the elements from <start> index (not value) inclusive, to <end> (end index) exclusive. An example might be able to explain this better - >>> lst = [1,2,3,4,5,6,7,8,9,10] >>> lst[0:5] [1, 2, 3, 4, 5] >>> lst[5:10] [6, 7, 8, 9, 10] Additionally, if...

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

python,python-2.7,wxpython

What you are looking for is the wx.WrapSizer. I updated your code a bit to use it instead: import wx words = ['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipisicing', 'elit', 'sed', 'do', 'eiusmod', 'tempor', 'incididunt', 'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua', 'ut', 'enim', 'ad', 'minim', 'veniam', 'quis', 'nostrud', 'exercitation', 'ullamco',...

Python split by comma delimiter and strip

python,python-2.7

I think you want this: for line in lines: for value in line.split(','): value = value.strip() Hope it helps....

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

python,python-2.7

In Python, when you say for identifier in iterable: first an iterator will be created from the iterable. So, the actual object will not be used in the looping. Then the iterator will be iterated and the current value will be bound to the name identifier. Quoting the official documentation...

How can I resolve my variable's unexpected output?

django,python-2.7

Remove the comma on your first line of code, this turns it into a tuple optional_message = form.cleaned_data['optional_message'], should be optional_message = form.cleaned_data['optional_message'] ...

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

python,python-2.7

You can store all the lines in an array f = open('one.txt') text = f.readlines() f.close() lines = [] [lines.append(line) for line in text] print(lines) ...

Sort List of Numbers according to Custom Number Sequence

list,python-2.7,sorting

This matches your input/output examples, but I had to use descending numbers to get the example answers. Are you sure your explanation is correct? If not, just use 0123456789 instead of 9876543210 in the code below. The algorithm is to provide a sorting key based on translating the digits of...

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

python,python-2.7,csv,compare

What do you mean by difference? The answer to that gives you two distinct possibilities. If a row is considered same when all columns are same, then you can get your answer via the following code: import csv f1 = open ("olddata/file1.csv") oldFile1 = csv.reader(f1) oldList1 = [] for row...

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

python,python-2.7

prog is returning None. The error you get is when you try to unpack the result into the tuple (s, best) You need to fix your logic so that prog is guaranteed to not return None. It will return None if your code never executes the else clause in the...

iterate using yield of a dictionary of dictionaries

python-2.7

You forgot to recursively yield. for k,d in dict.items(directories): for e in walk_directory_files(d): yield e Note that Python 3.3 adds additional syntax specifically for this: for k,d in dict.items(directories): yield from walk_directory_files(d) # Python 3.3+ only! ...

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

print getattr(i, 'from').username ...

lookbehind for start of string or a character

regex,python-2.7,regex-lookarounds

re.compile(ur"(?:^|(?<=[, ]))(?:next to|near|beside|opp).+?(?=,|$)", re.IGNORECASE) You can club 3 conditions using [] and |.See demo. https://regex101.com/r/vA8cB3/2#python...

Who calls the metaclass

python,python-2.7,metaclass

You can find the answer relatively easily. First, lets find the opcode for building a class. >>> def f(): class A(object): __metaclass__ = type >>> import dis >>> dis.dis(f) 2 0 LOAD_CONST 1 ('A') 3 LOAD_GLOBAL 0 (object) 6 BUILD_TUPLE 1 9 LOAD_CONST 2 (<code object A at 0000000001EBDA30, file...

monosubstitution cypher : decryption in python 2.7 list trouble

python-2.7

There are two problems that I have noticed: In encrypt function: elif char == 'U': encrypted_message.append(key[20]) elif char == 'U': encrypted_message.append(key[21]) Change it to: elif char == 'U': encrypted_message.append(key[20]) elif char == 'V': encrypted_message.append(key[21]) In decrypt function: Doing decrypted_message = decrypted_message.replace(key[i], alphabet[i]) for i in range(0,25), this might replace the...

Operational error while using stripe with profile app

django,python-2.7,django-templates,stripe-payments

It's kind of weird. But when I followed "No Such Table error" and tested DB it was still empty. So this time I deleted DB but also migrations. Problem is fixed and its just working fine.

using configparser in python

python,python-2.7

from ConfigParser import SafeConfigParser parser = SafeConfigParser() parser.read('file.ini') config_dict = {} for element in parser.sections(): print 'Section:', element config_dict[element] = {} print ' Options:', parser.options(element) for name, value in parser.items(element): print ' %s = %s' % (name, value) config_dict[element][name] = value print config_dict ...

Import on class instanciation

python,python-2.7

It is possible to import a module at instantiation: class SpecificClassThatNeedRandomModule(object): def __init__(self): import randomModule self.random = randomModule.Random() However, this is a bad practice because it makes it hard to know when the import is done. You might want to modify your module so that it doesn't raise an exception,...

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

python,list,python-2.7

WORDS = txt.splitlines() WORDS_5_or_less = list(filter(lambda x: len(x) <= 5, WORDS)) then just pick from WORDS_5_or_less instead of WORDS...

Python initialize strings as variable

python,python-2.7

#!/usr/bin/python m = 2 k = m*2 calc = "((k+m+46)/2)" result = eval(calc) print result Result 26 ...

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

python,python-2.7,kivy,self,nameerror

You've mixed tabs and spaces: When you do that, Python gets confused about how things are supposed to be indented, because it doesn't interpret tabs the same way your editor does. Don't mix tabs and spaces; stick to one or the other, and turn on "show whitespace" in your editor...

lambda for RDD query with if statement

python-2.7,pyspark

Maybe filter will help? badRecords = access_logs.filter(lambda log: log.response_code == 404) I think the problem with the way you wrote it is: When using map, you can't drop rows, every row is mapped to some other row. So there is no "pass" and the number of rows will not change....

Strange Behavior: Floating Point Error after Appending to List

python,python-2.7,behavior

Short answer: your correct doesn't work. Long answer: The binary floating-point formats in ubiquitous use in modern computers and programming languages cannot represent most numbers like 0.1, just like no terminating decimal representation can represent 1/3. Instead, when you write 0.1 in your source code, Python automatically translates this to...

Scrapy running from python script processes only start url

python,python-2.7,scrapy

When you override the default parse_start_url for a crawl spider, the method has to yield Requests for the spider to follow, otherwise it can't go anywhere. You are not required to implement this method when subclassing CrawlSpider, and from the rest of your code, it looks like you really don't...

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

django,python-2.7,django-forms

Your post method is returning the result of reverse, which is a string, ie the URL. You actually need to return a redirect response. The redirect shortcut can do this for you directly: from django.shortcuts import redirect ... def post(self, request, *args, **kwargs): ... return redirect('detail_pasta', hash=item.url) ...

Python: Exiting python.exe after Popen?

python,python-2.7

If you want to first communicate to the started process and then leave it alone to run further, you have a few options: Handle SIGPIPE in your long-running process, do not die on it. Live without stdin after the launcher process exits. Pass whatever you wanted using arguments, environment, or...

How to check for multiple attributes in a list

python,python-2.7

You can create a set holding the different IDs and then compare the size of that set to the total number of quests. The difference tells you how many IDs are duplicated. Same for names. Something like this (untested): def test_quests(quests): num_total = len(quests) different_ids = len(set((q.ID for q in...

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

python,python-2.7,import,filenames

You can't use a variable for an import statement. from x import y will try to find a module literally called y. In your case, that probably means you want a file in the same directory called y.py. It will then try to find a variable (including, eg, a function...