本文整理汇总了Python中iter函数的典型用法代码示例。如果您正苦于以下问题:Python iter函数的具体用法?Python iter怎么用?Python iter使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了iter函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_admin_setup
def test_admin_setup(self):
# PUTs for account and 16 .hash's
self.test_origin.app = FakeApp(iter(
[('204 No Content', {}, '') for i in xrange(102)]))
resp = Request.blank('/origin/.prep',
environ={'REQUEST_METHOD': 'PUT'},
headers={'X-Origin-Admin-User': '.origin_admin',
'X-Origin-Admin-Key': 'unittest'}).get_response(
self.test_origin)
self.assertEquals(resp.status_int, 204)
self.assertEquals(self.test_origin.app.calls, 101)
self.test_origin.app = FakeApp(iter(
[('404 Not Found', {}, '')]))
req = Request.blank('/origin/.prep',
environ={'REQUEST_METHOD': 'PUT'},
headers={'X-Origin-Admin-User': '.origin_admin',
'X-Origin-Admin-Key': 'unittest'})
self.assertRaises(Exception, req.get_response, self.test_origin)
self.test_origin.app = FakeApp(iter(
[('204 No Content', {}, ''), ('404 Not Found', {}, '')]))
req = Request.blank('/origin/.prep',
environ={'REQUEST_METHOD': 'PUT'},
headers={'X-Origin-Admin-User': '.origin_admin',
'X-Origin-Admin-Key': 'unittest'})
self.assertRaises(Exception, req.get_response, self.test_origin)
示例2: select_map
def select_map(self, latitude, longitude):
"""
Find and display a nearby track by latitude / longitude
The selection will favor a previously selected track in the nearby area
:param latitude
:type latitude float
:param longitude
:type longitude float
:returns the selected track, or None if there are no nearby tracks
:type Track
"""
if not latitude or not longitude:
return None
point = GeoPoint.fromPoint(latitude, longitude)
nearby_tracks = self.track_manager.find_nearby_tracks(point)
saved_tracks = self.get_pref_track_selections()
saved_nearby_tracks = [t for t in nearby_tracks if t.track_id in saved_tracks]
# select the saved nearby track or just a nearby track
track = next(iter(saved_nearby_tracks), None)
track = next(iter(nearby_tracks), None) if track is None else track
if self.track != track:
# only update the trackmap if it's changing
self._select_track(track)
return track
示例3: test_bison_lalr_repr_automaton_lr0
def test_bison_lalr_repr_automaton_lr0():
ex = grammar_examples.lr0.ex_minimal1
grammar = ex.grammar
automaton = compute_automaton(grammar)
assert repr(automaton) == '<Automaton with 4 states>'
assert repr(automaton._data) == '''
[<StateData #0 with 1 actions, 1 gotos
<bison.ItemSet #0, size 2
< $accept → • Root $eof ∥ >
< Root → • term ∥ >
>>, <StateData #1 with 1 actions, 0 gotos
<bison.ItemSet #1, size 1
< Root → term • ∥ { $eof } >
>>, <StateData #2 with 1 actions, 0 gotos
<bison.ItemSet #2, size 1
< $accept → Root • $eof ∥ >
>>, <StateData #3 with 2 actions, 0 gotos
<bison.ItemSet #3, size 1
< $accept → Root $eof • ∥ >
>>]
'''.strip().replace('•', _mdot).replace('∥', _parallel)
assert repr(automaton._data[0]._id) == '''
<StateId for <StateData #0 with 1 actions, 1 gotos
<bison.ItemSet #0, size 2
< $accept → • Root $eof ∥ >
< Root → • term ∥ >
>>>
'''.strip().replace('•', _mdot).replace('∥', _parallel)
assert repr(next(iter(automaton._data[0]._actions.values()))) == 'Shift(<state 1>)'
assert repr(next(iter(automaton._data[1]._actions.values()))) == 'Reduce(<rule 1>)'
assert repr(next(iter(automaton._data[0]._gotos.values()))) == 'Goto(<state 2>)'
示例4: __reduce__
def __reduce__(self):
return (__newobj__, # callable
(PickleProtocol2ReduceNewobj, 'yam', 1), # args
None, # state
iter([]), # listitems
iter([]), # dictitems
)
示例5: test_count
def test_count():
assert count((1, 2, 3)) == 3
assert count([]) == 0
assert count(iter((1, 2, 3, 4))) == 4
assert count("hello") == 5
assert count(iter("hello")) == 5
示例6: train
def train(self, inp, out, training_weight=1.):
inp = np.mat(inp).T
out = np.mat(out).T
deriv = []
val = inp
vals = [val]
# forward calculation of activations and derivatives
for weight,bias in self.__weights:
val = weight*val
val += bias
deriv.append(self.__derivative(val))
vals.append(self.__activation(val))
deriv = iter(reversed(deriv))
weights = iter(reversed(self.__weights))
errs = []
errs.append(np.multiply(vals[-1]-out, next(deriv)))
# backwards propagation of errors
for (w,b),d in zip(weights, deriv):
errs.append(np.multiply(np.dot(w.T, errs[-1]), d))
weights = iter(self.__weights)
for (w,b),v,e in zip(\
self.__weights,\
vals, reversed(errs)):
e *= self.__learning_rate*training_weight
w -= e*v.T
b -= e
tmp = vals[-1]-out
return np.dot(tmp[0].T,tmp[0])*.5*training_weight
示例7: tag_info_chart
def tag_info_chart (self):
""" Make the taginfo.txt plot """
## TODO: human chrs on hg19. How will this work with GRCh genome or other, non human, genomes?
# nice if they are ordered by size
ucsc = ["chr" + str(i) for i in range(1,23)].append([ "chrX", "chrY", "chrM"])
ensembl = list(range(1,23)).append([ "X", "Y", "MT"])
pconfig = {
'id': 'tagInfo',
'title': 'Homer: Tag Info Distribution',
'ylab': 'Tags',
'cpswitch_counts_label': 'Number of Tags'
}
## check if chromosomes starts with "chr" (UCSC) or "#" (ensembl)
sample1 = next(iter(self.tagdir_data['taginfo_total']))
chrFormat = next(iter(self.tagdir_data['taginfo_total'][sample1]))
if ("chr" in chrFormat):
chrs = ucsc
else:
chrs = ensembl
return bargraph.plot(self.tagdir_data['taginfo_total'], chrs, pconfig)
示例8: open_moinpage_part
def open_moinpage_part(self, elem):
type = elem.get(moin_page.content_type, u"").split(u';')
if len(type) == 2:
if type[0] == u"x-moin/macro":
if len(elem) and iter(elem).next().tag.name == "arguments":
alt = u"<<{0}({1})>>".format(type[1].split(u'=')[1], u','.join(
[u''.join(c.itertext()) for c in iter(elem).next() if c.tag.name == "argument"]))
else:
alt = u"<<{0}()>>".format(type[1].split(u'=')[1])
obj = u".. |{0}| macro:: {1}".format(alt, alt)
self.objects.append(obj)
return u" |{0}| ".format(alt)
elif type[0] == u"x-moin/format":
elem_it = iter(elem)
ret = u"\n\n.. parser:{0}".format(type[1].split(u'=')[1])
if len(elem) and elem_it.next().tag.name == "arguments":
args = []
for arg in iter(elem).next():
if arg.tag.name == "argument":
args.append(u"{0}=\"{1}\"".format(arg.get(moin_page.name, u""), u' '.join(arg.itertext())))
ret = u'{0} {1}'.format(ret, u' '.join(args))
elem = elem_it.next()
ret = u"{0}\n {1}".format(ret, u' '.join(elem.itertext()))
return ret
return elem.get(moin_page.alt, u'') + u"\n"
示例9: __init__
def __init__(self, iterator, unit=None, computer_prefix=None, display=MULTI_LINE):
"""Create a new progress display.
'iterator' is the iterator containing the work to be done.
'unit' is the unit to be displayed to the user.
'computer_prefix' should be set to True if this unit requires prefix
increments of 1024 instead of the traditional 1000. If it is not set,
then the class tries to guess based on 'unit'.
'display' defaults to MULTI_LINE to print a new line for every update,
or can be SINGLE_LINE to keep updating a single status line.
"""
if hasattr(iterator, "__len__"):
# This may be an expensive operation, for instance on a
# hypothetical os.walk() which implements __len__.
length = len(iterator)
self.iterator = iter(iterator)
else:
list = []
# TODO: isn't there some kind of builtin expand operation?
for i in iterator:
list.append(i)
length = len(list)
self.iterator = iter(list)
self.progress = Progress(length, unit, computer_prefix)
self.display = display
# The first call to next is before the work actually starts, so we
# shouldn't increment() at that point.
self.first = True
示例10: __iter__
def __iter__(self):
# Avoid usage of zip() below since it will consume one item too many.
it1, it2 = iter(self.reader1), iter(self.reader2)
while True:
try:
r1 = next(it1)
except StopIteration:
# End of file 1. Make sure that file 2 is also at end.
try:
next(it2)
raise FormatError("Reads are improperly paired. There are more reads in file 2 than in file 1.")
except StopIteration:
pass
break
try:
r2 = next(it2)
except StopIteration:
raise FormatError("Reads are improperly paired. There are more reads in file 1 than in file 2.")
name1 = r1.name.split(None, 1)[0]
name2 = r2.name.split(None, 1)[0]
if name1[-2:-1] == '/':
name1 = name1[:-2]
if name2[-2:-1] == '/':
name2 = name2[:-2]
if name1 != name2:
raise FormatError("Reads are improperly paired. Read name '{0}' in file 1 not equal to '{1}' in file 2.".format(name1, name2))
yield (r1, r2)
示例11: test_cdn_get_regex
def test_cdn_get_regex(self):
prev_data = json.dumps({'account': 'acc', 'container': 'cont',
'ttl': 1234, 'logs_enabled': True, 'cdn_enabled': True})
def check_urls(req):
vrs, acc, cont, obj = utils.split_path(req.path, 1, 4)
self.assertEquals(acc, 'acc')
self.assertEquals(cont, 'cont')
self.assertEquals(obj, 'obj1.jpg')
self.test_origin.app = FakeApp(iter([
('204 No Content', {}, prev_data), # call to _get_cdn_data
('304 No Content', {}, '', check_urls)])) #call to get obj
req = Request.blank('http://1234.r3.origin_cdn.com:8080/obj1.jpg',
environ={'REQUEST_METHOD': 'GET'})
resp = req.get_response(self.test_origin)
self.assertEquals(resp.status_int, 304)
self.test_origin.app = FakeApp(iter([
('204 No Content', {}, prev_data), # call to _get_cdn_data
('304 No Content', {}, '', check_urls)])) #call to get obj
req = Request.blank('http://r3.origin_cdn.com:8080/nohash/obj1.jpg',
environ={'REQUEST_METHOD': 'GET'})
resp = req.get_response(self.test_origin)
self.assertEquals(resp.status_int, 404)
示例12: test_cdn_get_no_content
def test_cdn_get_no_content(self):
prev_data = json.dumps({'account': 'acc', 'container': 'cont',
'ttl': 1234, 'logs_enabled': True, 'cdn_enabled': True})
self.test_origin.app = FakeApp(iter([
('204 No Content', {}, prev_data), # call to _get_cdn_data
('304 No Content', {}, '')])) #call to get obj
req = Request.blank('http://1234.r34.origin_cdn.com:8080/obj1.jpg',
environ={'REQUEST_METHOD': 'HEAD',
'swift.cdn_hash': 'abcd',
'swift.cdn_object_name': 'obj1.jpg'})
resp = req.get_response(self.test_origin)
self.assertEquals(resp.status_int, 304)
self.test_origin.app = FakeApp(iter([
('204 No Content', {}, prev_data), # call to _get_cdn_data
('404 No Content', {}, '')])) #call to get obj
req = Request.blank('http://1234.r34.origin_cdn.com:8080/obj1.jpg',
environ={'REQUEST_METHOD': 'HEAD',
'swift.cdn_hash': 'abcd',
'swift.cdn_object_name': 'obj1.jpg'})
resp = req.get_response(self.test_origin)
self.assertEquals(resp.status_int, 404)
self.test_origin.app = FakeApp(iter([
('204 No Content', {}, prev_data), # call to _get_cdn_data
('416 No Content', {}, '')])) #call to get obj
req = Request.blank('http://1234.r34.origin_cdn.com:8080/obj1.jpg',
environ={'REQUEST_METHOD': 'HEAD',
'swift.cdn_hash': 'abcd',
'swift.cdn_object_name': 'obj1.jpg'})
resp = req.get_response(self.test_origin)
self.assertEquals(resp.status_int, 416)
示例13: test_origin_db_post_fail
def test_origin_db_post_fail(self):
self.test_origin.app = FakeApp(iter([
('204 No Content', {}, ''), # call to _get_cdn_data
('404 Not Found', {}, ''), # put to .hash
]))
req = Request.blank('http://origin_db.com:8080/v1/acc/cont',
environ={'REQUEST_METHOD': 'PUT'})
resp = req.get_response(self.test_origin)
self.assertEquals(resp.status_int, 500)
self.test_origin.app = FakeApp(iter([
('204 No Content', {}, ''), # call to _get_cdn_data
('204 No Content', {}, ''), # put to .hash
('404 Not Found', {}, ''), # HEAD check to list container
('404 Not Found', {}, ''), # PUT to list container
]))
req = Request.blank('http://origin_db.com:8080/v1/acc/cont',
environ={'REQUEST_METHOD': 'PUT'})
resp = req.get_response(self.test_origin)
self.assertEquals(resp.status_int, 500)
self.test_origin.app = FakeApp(iter([
('204 No Content', {}, ''), # call to _get_cdn_data
('204 No Content', {}, ''), # put to .hash
('204 No Content', {}, ''), # HEAD check to list container
('404 Not Found', {}, ''), # PUT to list container
]))
req = Request.blank('http://origin_db.com:8080/v1/acc/cont',
environ={'REQUEST_METHOD': 'PUT'})
resp = req.get_response(self.test_origin)
self.assertEquals(resp.status_int, 500)
示例14: run
def run(self):
container_loaded.wait()
container_loaded.clear()
link = Link.from_string(sys.argv[3])
if link.type() == Link.LINK_TRACK:
track = link.as_track()
itrack = iter([track])
elif link.type() == Link.LINK_PLAYLIST:
playlist = link.as_playlist()
print('loading playlist...')
while not playlist.is_loaded():
time.sleep(0.1)
print('done')
itrack = iter(playlist)
session = self.ripper.session
for track in itrack:
self.ripper.load_track(track)
rip_init(session, track)
self.ripper.play()
end_of_track.wait()
end_of_track.clear()
rip_terminate(session, track)
rip_id3(session, track)
self.ripper.disconnect()
示例15: GetEntries
def GetEntries(self, parser_mediator, match=None, **unused_kwargs):
"""Extract device information from the iPod plist.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS.
"""
devices = match.get('Devices', {})
for device_identifier, device_information in iter(devices.items()):
datetime_value = device_information.get('Connected', None)
if not datetime_value:
continue
event_data = IPodPlistEventData()
event_data.device_id = device_identifier
# TODO: refactor.
for key, value in iter(device_information.items()):
if key == 'Connected':
continue
attribute_name = key.lower().replace(' ', '_')
setattr(event_data, attribute_name, value)
event = time_events.PythonDatetimeEvent(
datetime_value, definitions.TIME_DESCRIPTION_LAST_CONNECTED)
parser_mediator.ProduceEventWithEventData(event, event_data)