I have a program (temptrack) where I need to download weather data every x minutes for x amount of hours. I have figured out how to download every x minutes using time.sleep(x*60) but I have no clue how to repeat this process for a certain amount of hours.
Thanks.
Hi, I'm working a script that will upload videos to YouTube with different accounts. Is there a way to use HTTPS or SOCKS proxies to filter all the requests. My client doesn't want to leave any footprints for Google. The only way I found was to set the proxy environment variable beforehand but this seems cumbersome. Is there some way I'm missing?
Thanks :)
Hello. I'm having trouble getting my list to return in my code. Instead of returning the list, it keeps returning None, but if I replace the return with print in the elif statement, it prints the list just fine. How can I repair this?
def makeChange2(amount, coinDenomination, listofcoins = None):
#makes a list of coins from an amount given by using a greedy algorithm
coinDenomination.sort()
#reverse the list to make the largest position 0 at all times
coinDenomination.reverse()
#assigns list
if listofcoins is None:
listofcoins = []
if amount >= coinDenomination[0]:
listofcoins = listofcoins + [coinDenomination[0]]
makeChange2((amount - coinDenomination[0]), coinDenomination, listofcoins)
elif amount == 0:
return listofcoins
else:
makeChange2(amount, coinDenomination[1:], listofcoins)
I'm working on a class that basically allows for method chaining, for setting some attrbutes for different dictionaries stored.
The syntax is as follows:
d = Test()
d.connect().setAttrbutes(Message=Blah, Circle=True, Key=True)
But there can also be other instances, so, for example:
d = Test()
d.initialise().setAttrbutes(Message=Blah)
Now I believe that I can overwrite the "setattrbutes" function; I just don't want to create a function for each of the dictionary. Instead I want to capture the name of the previous chained function. So in the example above I would then be given "connect" and "initialise" so I know which dictionary to store these inside.
I hope this makes sense. Any ideas would be greatly appreciated :)
have an excel based CSV file with two columns (or rows, Pythonically) that I am working on. What I need to do is to perform some operations so that I can compare the two data entries in each 'row'. To be more precise, one column has constant numbers all the way down, whereas the other column has varying values. So I need to count the number of times the varying column data entry values crosses the constant value on the other column.
For example, fro the csv file i have two columns:
Varying Column; Constant Column
24 25
26 25 crossed
27 25
26 25
25.5 25
23 25 crossed
26 25 crossed
Thus, the varying column data entries have crossed 25 three times. I need to generate a code that can count the number of the crosses. Please do help out, Thanks.
Is there anything like this in the standard library? I've looked but haven't found it.
It needs to be like a list (preserves order) but also like a set (elements can only appear once).
So if you give it ['a', 'b', 'a'] it should return ['a', 'b']
Thanks!
Hi
I have a number of processes running which are controlled by remote clients. A tcp server controls access to these processes, only one client per process. The processes are given an id number in the range of 0 - n-1. Were 'n' is the number of processes. I use a dictionary to map this id to the client sockets file descriptor. On startup I populate the dictionary with the ids as keys and socket fd of 'None' for the values, i.e no clients and all pocesses are available
When a client connects, I map the id to the sockets fd. When a client disconnects I set the value for this id to None, i.e. process is available. So everytime a client connects I have to check each entry in the dictionary for a process which has a socket fd entry of None. If there are then the client is allowed to connect.
This solution does not seem very elegant, are there other data structures which would be more suitable for solving this?
Thanks
This code works well in Mac/Linux, but not in Windows.
import mmap
import os
map = mmap.mmap(-1, 13)
map.write("Hello world!")
pid = os.fork()
if pid == 0: # In a child process
print 'child'
map.seek(0)
print map.readline()
map.close()
else:
print 'parent'
What's the equivalent function of os.fork() on Windows?
So if I have a matrix (list of lists) of unique words as my column headings, document ids as my row headings, and a 0 or 1 as the values if the word exists in that particular document.
What I'd like to know is how to determine all the possible combinations of words and documents where more than one word is in common with more than one document.
So something like:
[[Docid_3, Docid_5], ['word1', 'word17', 'word23']], [[Docid_3, Docid_9, Docid_334], ['word2', 'word7', 'word23', 'word68', 'word982']], and so on for each possible combination. Would love a solution that provides the complete set of combinations and one that yields only the combinations that are not a subset of another, so from the example, not [[Docid_3, Docid_5], ['word1', 'word17']] since it's a complete subset of the first example.
I feel like there is an elegant solution that just isn't coming to mind and the beer isn't helping.
Thanks.
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.
This is the piece of code I have:
choice = ""
while choice != "1" and choice != "2" and choice != "3":
choice = raw_input("pick 1, 2 or 3")
if choice == "1":
print "1 it is!"
elif choice == "2":
print "2 it is!"
elif choice == "3":
print "3 it is!"
else:
print "You should choose 1, 2 or 3"
While it works, I feel that it's really clumsy, specifically the while clause. What if I have more acceptable choices? Is there a better way to make the clause?
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]]
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?
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?
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)
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?
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!