I'd like a good method that matches the interface of subprocess.check_call -- ie, it throws CalledProcessError when it fails, is synchronous, &c -- but instead of returning the return code of the command (if it even does that) returns the program's output, either only stdout, or a tuple of (stdout, stderr).
Does somebody have a method that does this?
I'm working on a number of Pyramid (former Pylons) projects, and often I have the need to display a list of some content (let's say user accounts, log entries or simply some other data). A user should be able to paginate through the list, click on a row and get a form where he/she can edit the contents of that row.
Right now I'm always re-inventing the wheel by having Mako templates which use webhelpers for the pagination, Jquery UI for providing a dialog and I craft the editor form and AJAX requests on the client and server side by hand.
As you may know, this eats up painfully much time.
So what I'm wondering is: Is there a better way of providing lists, editor dialog and server/client communication about this, without having to re-invent the wheel every time?
I heard Django takes off a big load of that by providing user accounts and other stuff out of the box; but in my case it's not just about user accounts, it can be any kind of data that is stored on the server-side in a SQL database, which should be able to be edited by a user.
Thanks in advance!
I'm stuck on how to formulate this problem properly and the following is:
What if we had the following values:
{('A','B','C','D'):3,
('A','C','B','D'):2,
('B','D','C','A'):4,
('D','C','B','A'):3,
('C','B','A','D'):1,
('C','D','A','B'):1}
When we sum up the first place values: [5,4,2,3] (5 people picked for A first, 4 people picked for B first, and so on like A = 5, B = 4, C = 2, D = 3)
The maximum values for any alphabet is 5, which isn't a majority (5/14 is less than half), where 14 is the sum of total values.
So we remove the alphabet with the fewest first place picks. Which in this case is C.
I want to return a dictionary where {'A':5, 'B':4, 'C':2, 'D':3} without importing anything.
This is my work:
def popular(letter):
'''(dict of {tuple of (str, str, str, str): int}) -> dict of {str:int}
'''
my_dictionary = {}
counter = 0
for (alphabet, picks) in letter.items():
if (alphabet[0]):
my_dictionary[alphabet[0]] = picks
else:
my_dictionary[alphabet[0]] = counter
return my_dictionary
This returns duplicate of keys which I cannot get rid of.
Thanks.
I'm currently using regular expressions to search through RSS feeds to find if certain words and phrases are mentioned, and would then like to extract the text on either side of the match as well. For example:
String = "This is an example sentence, it is for demonstration only"
re.search("is", String)
I'd like to know where the is was found so that I can extract and output something like this:
1 match found: "This is an example sentence"
I know that it would be easy to do with splits, but I'd need to know what the index of first character of the match was in the string, which I don't know how to find
I can not figure out why my code does not filter out lists from a predefined list.
I am trying to remove specific list using the following code.
data = [[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,1],[2,1,2],[2,2,1],[2,2,2]]
data = [x for x in data if x[0] != 1 and x[1] != 1]
print data
My result:
data = [[2, 2, 1], [2, 2, 2]]
Expected result:
data = [[1,2,1],[1,2,2],[2,1,1],[2,1,2],[2,2,1],[2,2,2]]
Is there a way to have a function raise an error if it takes longer than a certain amount of time to return? I want to do this without using signal (because I am not in the main thread) or by spawning more threads, which is cumbersome.
I need to compare two strings, containing HTML text. The test should return true if the html strings are equivalent, i.e. differ only in whitespace and comments.
Is there any module that can be used for this task?
How do i use the with statement in this case?
f_spam = open(spam,'r')
f_bar = open(eggs,'r')
...
do something with these files
...
f_spam.close()
f_bar.close()
For instance, if I have:
C:\42\main.py
and
C:\42\info.txt
and I want to read info.txt from main.py, I have to input "C:\42\info.txt" instad of just "info.txt".
Is it supposed to be like that?
If not, how can I fix it?
I want to take two lists and find the values that appear in both.
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
would return [5], for instance.
I'm getting a KeyError for an out of dictionary key, even though I know the key IS in fact in the dictionary. Any ideas as to what might be causing this?
print G.keys()
returns the following:
['24', '25', '20', '21', '22', '23', '1', '3', '2', '5', '4', '7', '6', '9', '8', '11', '10', '13', '12', '15', '14', '17', '16', '19', '18']
but when I try to access a value in the dictionary on the next line of code...
for w in G[v]: #note that in this example, v = 17
I get the following error message:
KeyError: 17
Any help, tips, or advice are all appreciated. Thanks.
To make the question clear, I'll use a specific example.
I have a list of college courses, and each course has a few fields (all of which are strings). The user gives me a string of search terms, and I return a list of courses that match all of the search terms. This can be done in a single list comprehension or a few nested for loops.
Here's the implementation. First, the Course class:
class Course:
def __init__(self, date, title, instructor, ID, description, instructorDescription, *args):
self.date = date
self.title = title
self.instructor = instructor
self.ID = ID
self.description = description
self.instructorDescription = instructorDescription
self.misc = args
Every field is a string, except misc, which is a list of strings.
Here's the search as a single list comprehension. courses is the list of courses, and query is the string of search terms, for example "history project".
def searchCourses(courses, query):
terms = query.lower().strip().split()
return tuple(course for course in courses if all(
term in course.date.lower() or
term in course.title.lower() or
term in course.instructor.lower() or
term in course.ID.lower() or
term in course.description.lower() or
term in course.instructorDescription.lower() or
any(term in item.lower() for item in course.misc)
for term in terms))
You'll notice that a complex list comprehension is difficult to read.
I implemented the same logic as nested for loops, and created this alternative:
def searchCourses2(courses, query):
terms = query.lower().strip().split()
results = []
for course in courses:
for term in terms:
if (term in course.date.lower() or
term in course.title.lower() or
term in course.instructor.lower() or
term in course.ID.lower() or
term in course.description.lower() or
term in course.instructorDescription.lower()):
break
for item in course.misc:
if term in item.lower():
break
else:
continue
break
else:
continue
results.append(course)
return tuple(results)
That logic can be hard to follow too. I have verified that both methods return the correct results.
Both methods are nearly equivalent in speed, except in some cases. I ran some tests with timeit, and found that the former is three times faster when the user searches for multiple uncommon terms, while the latter is three times faster when the user searches for multiple common terms. Still, this is not a big enough difference to make me worry.
So my question is this: which is better? Are list comprehensions always the way to go, or should complicated statements be handled with nested for loops? Or is there a better solution altogether?
Hi this must be a very simple solution that has eluded me this last hour. I've tried to build this test function where the return value of the test_cases list should match the values in the test_case_answers list but for some reason, test case 1 and test case 2 fail. When i print the return values for the test cases they return the correct answers, but for some reason test case 1 and test case 2 return False.
Thanks for your help!
import math
test_cases = [1, 9, -3]
test_case_answers = [1, 3, 0]
def custom_sqrt(num):
for i in range(len(test_cases)):
if test_cases[i] >= 0:
return math.sqrt(test_cases[i])
else:
return 0
for i in range(len(test_cases)):
if custom_sqrt(test_cases[i]) != test_case_answers[i]:
print "Test Case #", i, "failed!"
custom_sqrt(test_cases)
I've made a couple of scripts. One is a stock screener that can search through every stock. Another creates a heatmap that tells you what's performed well and badly over the past day. They aren't really that useful, just did them to work on my programming skills. I was able to throw some SQL in my scripts too. Would you call that intermediate? Thanks? How do you guys list your programming skills on your resume? Maybe there's a better way of putting it on my resume than "intermediate" or "beginner."
What's a correct and good way to implement hash()?
I am talking about the function that returns a hashcode that is then used to insert objects into hashtables aka dictionaries.
As hash() returns an integer and is used for "binning" objects into hashtables I assume that the values of the returned integer should be uniformly distributed for common data (to minimize collisions).
What's a good practice to get such values? Are collisions a problem?
In my case I have a small class which acts as a container class holding some ints, some floats and a string.
I coded in Java for many years and after i saw this beauty:
with open("spam.egg") as f:
for line in f:
print line
i said to myself, i can't use Java's StreamVerboseCrapByteOpenBuffer stuff anymore.
What's your snippet?
I am trying to find a frequency of each symbol in any given text using an algorithm of O(n) complexity. My algorithm looks like:
s = len(text)
P = 1.0/s
freqs = {}
for char in text:
try:
freqs[char]+=P
except:
freqs[char]=P
but I doubt that this dictionary-method is fast enough, because it depends on the underlying implementation of the dictionary methods. Is this the fastest method?
I've been using this little snippet to select random images. However I would like to change it to select only images of a certain size. I'm running into trouble checking against image size. If I use get_image_dimensions() I need to use a conditional statement, which then requires that I allow exceptions. So, I guess I need some pointers on just limiting by image dimensions. Thanks.
import os
import random
import posixpath
from django import template
from django.conf import settings
register = template.Library()
def is_image_file(filename):
"""Does `filename` appear to be an image file?"""
img_types = [".jpg", ".jpeg", ".png", ".gif"]
ext = os.path.splitext(filename)[1]
return ext in img_types
@register.simple_tag
def random_image(path):
"""
Select a random image file from the provided directory
and return its href. `path` should be relative to MEDIA_ROOT.
Usage: <img src='{% random_image "images/whatever/" %}'>
"""
fullpath = os.path.join(settings.MEDIA_ROOT, path)
filenames = [f for f in os.listdir(fullpath) if is_image_file(f)]
pick = random.choice(filenames)
return posixpath.join(settings.MEDIA_URL, path, pick)
First of all, I should explain what I'm trying to do first.
I'm creating a dungeon crawler-like game, and I'm trying to program the movement of computer characters/monsters in the map. The map is basically a Cartesian coordinate grid.
The locations of characters are represented by tuples of the x and y values, (x,y).
The game works by turns, and in a turn a character can only move up, down, left or right 1 space. I'm creating a very simple movement system where the character will simply make decisions to move on a turn by turn basis. Essentially a 'forgetful' movement system.
A basic flow chart of what I'm intending to do:
Find direction towards destination
Make a priority list of movements to be done using the direction eg.('r','u','d','l') means it would try to move right first, then up, then down, then left.
Try each of the possibilities following the priority order. If the first movement fails (blocked by obstacle etc.), then it would successively try the movements until the first one that is successful, then it would stop.
At step 3, the way I'm trying to do it is like this:
def move(direction,location):
try:
-snip- # Tries to move, raises the exception Movementerror if cannot move in the direction
return 1 # Indicates movement successful
except Movementerror:
return 0 # Indicates movement unsuccessful (thus character has not moved yet)
prioritylist = ('r','u','d','l')
if move('r',location): pass
elif move('u',location): pass
elif move('d',location): pass
elif move('l',location): pass
else: pass
In the if/else block, the program would try the first movement on the priority on the priority list. At the move function, the character would try to move. If the character is not blocked and does move, it returns 1, leading to the pass where it would stop. If the character is blocked, it returns 0, then it tries the next movement.
However, this results in 2 problems:
How do I edit a variable passed into a function inside the function itself, while returning if the edit is successful?
I have been told that you can't edit a variable inside a function as it won't really change the value of the variable, it just makes the variable inside the function refer to something else while the original variable remain unchanged. So, the solution is to return the value and then assign the variable to the returned value. However, I want it to return another value indicating if this edit is successful, so I want to edit this variable inside the function itself. How do I do so?
How do I change the order of the if/else statements to follow the order of the priority list? It needs to be able to change during runtime as the priority list can change resulting in a different order of movement to try.
Basically, I have a file like this:
Url/Host: www.example.com
Login: user
Password: password
How can I use RegEx to separate the details to place them into variables?
Sorry if this is a terrible question, I can just never grasp RegEx. So another question would be, can you provide the RegEx, but kind of explain what each part of it is for?
The id() inbuilt function gives...
an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime.
The is operator, instead, gives...
object identity
So why is it possible to have two objects that have the same id but return False to an is check? Here is an example:
>>> class Test():
... def test():
... pass
>>> a = Test()
>>> b = Test()
>>> id(a.test) == id(b.test)
True
>>> a.test is b.test
False
A more troubling example: (continuing the above)
>>> b = a
>>> b is a
True
>>> b.test is a.test
False
>>> a.test is a.test
False