working on ubuntu 12.04, python 2.7
I have the error 'list' object has no attribute 'items' when I call the print_to_screen function.
could someone explain me please how to manage the dictionary which is created?
Thanks
class median_uniq:
def init(self):
self.median_number_list = []
def print_to_screen(self, words_dict, is_reverse = False):
words = words_dict.items()
words.sort(key = lambda(a,b):(a,b), reverse = is_reverse)
print("[Words tweeted: %d]" % len(words)).center(60,"=")
print("%-25s | %25s" % ("Words", "count"))
print BANNER
for w, c in words:
print("%-25s | %25d" % (w, c))
def Median_number(self, file_name):
file_object = open(file_name, "r")
number_word_list = []
for line in file_object:
unique_words_per_tweet = sorted(set(line.rstrip().split(" ")))
number_word_list.append(len(Counter((unique_words_per_tweet))))
self.median_number_list.append(numpy.median(numpy.array(number_word_list)))
print self.median_number_list
return self.median_number_list
to call function, I do this:
med = median_uniq() med_list = med.Median_number(input_file)
med.print_to_screen(med_list, is_reverse = False)
on command line knowing that my input_file is a .txt file. thanks
I have seen similar post, but don't well understand. An explanation with simply words would be really helpful.
Thanks
"words_dict" in your code is a list, but your attempt to use a python dictionary method (items())
I would need a working example to be able to propose a customized solution.
Related
I need to test a call to gzip.open, but I need it to supply it with an actual test file with test data in it to read. I've seen several very similar questions, but none of them work as expected.
This is the code I'm testing:
with gzip.open(local_file_path,'r') as content:
for line in content:
try:
if line.startswith('#'):
continue
line_data = line.split('\t')
request_key = line_data[LINE_FORMAT['date']]
request_key += '-' + line_data[LINE_FORMAT['time']][:-3]
request_key += '-' + line_data[LINE_FORMAT['source_ip']]
if request_key in result.keys():
result[request_key] += 1
else:
result[request_key] = 1
num_requests += 1
except Exception, e:
print ("[get_outstanding_requesters] \t\tError to process line: %s"%line)
I think the problem is related to the issues discussed here because the code treats the file as an iterator, but none of the workarounds discussed have worked for me.
I've tried variations on this:
test_data = open('test_access_log').read()
m = mock.mock_open(read_data=test_data)
m.return_value.__iter__ = lambda self:self
m.return_value.__next__ = lambda self: self.readline()
with mock.patch('gzip.open', m):
with gzip.open('asdf') as f:
for i in f:
print i
Which results in:
TypeError: iter() returned non-iterator of type 'MagicMock'
I'm using Python 2.7. I'm tearing my hair out over this one. Is my only solution to forget trying to use an iterator (actual files can be very large, which is why I'm trying to avoid doing so?)
This is working:
import unittest
import mock
test_data = open('test_access_log').read()
m = mock.mock_open(read_data=test_data)
m.return_value.__iter__.return_value = test_data.splitlines()
with mock.patch('gzip.open', m):
with gzip.open('test_access_log') as f:
for i in f:
print i
Thanks to bash-shell.net
I'm Inheriting Function in Account Voucher (def voucher_move_line_create) using new api style odoo8.
Here's my Code:
#api.model
def voucher_move_line_create(self, line_total, move_id, company_currency, current_currency):
res = super(AccountVoucher, self).voucher_move_line_create(line_total, move_id, company_currency, current_currency)
_logger.info('\n\n\n Return: %s \n\n\n'%(str(res)))
for i in res[1]:
_logger.info('\n\n\nRes Return: %s \n\n\n'%(str(i)))
return res
and I Got this Error:
File "/opt/odoo8/odoo8-server/openerp/api.py", line 769, in new
self.cr, self.uid, self.context = self.args = (cr, uid, frozendict(context))
ValueError: dictionary update sequence element #0 has length 1; 2 is required.
Thank you!
It's seems that you forgot an argument while you're inheriting this function.
You missed voucher_id argument so the inherited function should be like :
#api.model
def voucher_move_line_create(self, voucher_id, line_total, move_id, company_currency, current_currency):
res = super(account_voucher, self).voucher_move_line_create(voucher_id, line_total, move_id, company_currency, current_currency)
I hope this helps, and thank you for your question.
How can I create a Dictionary from my while loop below? infile reads from a file called input, which has the following content:
min:1,23,62,256
max:24,672,5,23
sum:22,14,2,3,89
P90:23,30,45.23
P70:12,23,24,57,32
infile = open("input.txt", "r")
answers = open("output.txt", "w")
while True:
line = infile.readline()
if not line: break
opType = line[0:3]
numList = (line[4:len(line)])
numList = numList.split(',')
What I'm trying to do is basically 2 lists, one that has the operation name (opType) and the other that has the numbers. From there I want to create a dictionary that looks like this
myDictionary = {
'min': 1,23,62,256,
'max': 24,672,5,23,
'avg': 22,14,2,3,89,
'P90': 23,30,45.23,
'P70': 12,23,24,57,32,
}
The reason for this is that I need to call the operation type to a self-made function, which will then carry out the operation. I'll figure this part out. I currently just need help making the dictionary from the while loop.
I'm using python 2.7
Try the following code.
I believe, you would need the 'sum' also in the dictionary. If not, just add a condition to remove it.
myDictionary = {}
with open('input.txt','r') as f:
for line in f:
x = line.split(':')[1].rstrip().split(',')
for i in xrange(len(x)):
try:
x[i] = int(x[i])
except ValueError:
x[i] = float(x[i])
myDictionary[line.split(':')[0]] = x
print myDictionary
I am trying figure out if I'm having an issue with my classes, or calling variables/lists from another function.
Below is a function I have being called from a button I press(inside a class that is my main window):
def analyzeRNA(self):
self.p = self.textbox.get("1.0", END)
protein_assignment(self.p)
self.data = primary_structure
self.databox.insert(END, self.data)
It reads from my textbox just fine. It performs my function protein_assignment on it and prints the results to the python shell as in the function does. It prints a list I make in protein_assignment that function called primary_structure. Now, how do put this information into my databox (which is also a "textbox" so to speak)
My error:
line 86, in analyzeRNA
self.data = primary_structure
NameError: global name 'primary_structure' is not defined
Protein assignment outline:
def protein_assignment(sequence):
x = 0
primary_structure = []
single_letter_assignment = []
three_letter_code = []
chemical_properties = []
while True:
blah, blah, blah adding amino acids to the list, running through sequence
"if nothing else in sequence, print lists and break"
return primary_structure #(Not sure if this is needed)
return primary_structure #(Not sure what I'm doing here either)
If more is needed, glad to help. Running off to work right now. Will respond later. Please and thank you!
primary_structure is returned by protein_assignment so to keep a reference to it in analyzeRNA you just need to do this:
def analyzeRNA(self):
self.p = self.textbox.get("1.0", END)
returned_value = protein_assignment(self.p)
self.data = returned_value
self.databox.insert(END, self.data)
or since you are just setting it to self.data anyway:
def analyzeRNA(self):
self.p = self.textbox.get("1.0", END)
self.data = protein_assignment(self.p)
self.databox.insert(END, self.data)
recently I've started to use the excellent boost::unordered_map on my system, but got one drawback: I couldn't figure how to inspect its contents. Printing it on gdb gives me a table_ and a buckets_, but haven't found where are the items. Anyone has a clue about this?
For the ones that wanted a printer, I've managed to create one. Here is Code:
class BoostUnorderedMapPrinter:
"prints a boost::unordered_map"
class _iterator:
def __init__ (self, fields):
type_1 = fields.val.type.template_argument(0)
type_2 = fields.val.type.template_argument(1)
self.buckets = fields.val['table_']['buckets_']
self.bucket_count = fields.val['table_']['bucket_count_']
self.current_bucket = 0
pair = "std::pair<%s const, %s>" % (type_1, type_2)
self.pair_pointer = gdb.lookup_type(pair).pointer()
self.base_pointer = gdb.lookup_type("boost::unordered_detail::value_base< %s >" % pair).pointer()
self.node_pointer = gdb.lookup_type("boost::unordered_detail::hash_node<std::allocator< %s >, boost::unordered_detail::ungrouped>" % pair).pointer()
self.node = self.buckets[self.current_bucket]['next_']
def __iter__(self):
return self
def next(self):
while not self.node:
self.current_bucket = self.current_bucket + 1
if self.current_bucket >= self.bucket_count:
raise StopIteration
self.node = self.buckets[self.current_bucket]['next_']
iterator = self.node.cast(self.node_pointer).cast(self.base_pointer).cast(self.pair_pointer).dereference()
self.node = self.node['next_']
return ('%s' % iterator['first'], iterator['second'])
def __init__(self, val):
self.val = val
def children(self):
return self._iterator(self)
def to_string(self):
return "boost::unordered_map"
In a typical hash table implementation, the buckets contain the head of a linked list which actually contains the values corresponding to this particular hash. Thus I would bet on buckets_.
Another option: there are various python pretty printer libraries for gdb now, and I think that you could find one that works with C++0x and inspect where it looks for the values.