def handleargs(arglist):
"""Take list of arguments and extract/create proper start, stop, and step
values and return in a tuple"""
try:
if len(arglist) == 1:
return 0, int(arglist[0]), 1
elif len(arglist) == 2:
return int(arglist[0]), int(arglist[1]), 1
elif len(arglist) == 3:
if arglist[2] == 0:
raise ValueError("step argument must not be zero")
return tuple(int(x) for x in arglist)
else:
raise TypeError("range() accepts 1-3 arguments, given", len(arglist))
except TypeError:
raise TypeError("range() arguments must be numbers or strings "
"representing numbers")
python类range()的实例源码
def elements(self):
'''Iterator over elements repeating each as many times as its count.
>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']
If an element's count has been set to zero or is a negative number,
elements() will ignore it.
'''
for elem, count in iteritems(self):
for _ in range(count):
yield elem
# Override dict methods where the meaning changes for Counter objects.
def intervals(_min, _max=None, size=1):
"""
RETURN (min, max) PAIRS OF GIVEN SIZE, WHICH COVER THE _min, _max RANGE
THE LAST PAIR MAY BE SMALLER
Yes! It's just like range(), only cooler!
"""
if _max == None:
_max = _min
_min = 0
_max = int(Math.ceiling(_max))
_min = int(Math.floor(_min))
output = ((x, min(x + size, _max)) for x in __builtin__.range(_min, _max, size))
return output
def __init__(self, N):
self.edges = []
self.alignments = []
self.affines = [ Affine() for i in range(N) ]
def get_reference_radecs(self):
return [self.affines[fieldi].getReferenceRadec()
for fieldi in range(len(self.affines))]
def get_all_dradec(self, apply=False):
alldra = []
allddec = []
for ei in range(len(self.edges)):
(ra,dec,dra,ddec) = self.get_edge_dradec_arcsec(ei, corrected=apply)
alldra.append(dra)
allddec.append(ddec)
return np.hstack(alldra), np.hstack(allddec)
def add_edge(self, *args):
S = args[12]
good = np.zeros_like(S)
fore = args[15]
good[S] = (fore > 0.5)
G = [args[i][good] for i in range(2,6)]
bad = np.logical_not(good)
B = [args[i][bad] for i in range(2,6)]
self.edges.append(args + tuple(G) + tuple(B) + (good, bad))
def plotallmatches(self):
for ei in range(len(self.edges)):
self.plotmatchedstars(ei)
# one plot per edge
def get_mags(self, TT, apply, magcol='mag1', magerrcol='mag1_err'):
alldd = []
allmagI = []
allmagJ = []
allmagerrI = []
allmagerrJ = []
for ei in range(len(self.edges)):
good = self.edge_good(ei)
ii,jj = self.edge_ij(ei)
I,J = self.edge_IJ(ei)
(r,d, dra,ddec) = self.get_edge_dradec_arcsec(ei, corrected=apply,
goodonly=True)
dd = np.sqrt(dra**2 + ddec**2)
alldd.append(dd)
# 'I' is an int array
# 'good' is a bool array of size == size(I)
# number of True elements in 'good' == len(dra)
magI = TT[ii][I][good].get(magcol)
magJ = TT[jj][J][good].get(magcol)
allmagI.append(magI)
allmagJ.append(magJ)
if magerrcol in TT[ii].columns():
allmagerrI.append(TT[ii].get(magerrcol)[I][good])
allmagerrJ.append(TT[jj].get(magerrcol)[J][good])
alldd = np.hstack(alldd)
allmagI = np.hstack(allmagI)
allmagJ = np.hstack(allmagJ)
allmagerrI = np.hstack(allmagerrI)
allmagerrJ = np.hstack(allmagerrJ)
return (allmagI, allmagJ, alldd, magcol, allmagerrI, allmagerrJ)
def magmagplot(self, TT, magcol, filtname, weighted=True):
plt.clf()
m1 = []
m2 = []
ww = []
for ei in range(self.nedges()):
i,j = self.edge_ij(ei)
I,J = self.edge_IJ(ei)
Ti = TT[i][I]
Tj = TT[j][J]
mag1 = Ti.get(magcol)
mag2 = Tj.get(magcol)
weights = self.get_edge_all_weights(ei)
K = (mag1 < 50) * (mag2 < 50)
m1.append(mag1[K])
m2.append(mag2[K])
ww.append(weights[K])
m1 = np.hstack(m1)
m2 = np.hstack(m2)
ww = np.hstack(ww)
if weighted:
loghist(m1, m2, weights=ww)
else:
loghist(m1, m2)
plt.xlabel('%s (mag)' % filtname)
plt.ylabel('%s (mag)' % filtname)
return ww
def n_sip_terms(sip_order):
assert(sip_order >= 2)
n = 0
for order in range(2, sip_order+1):
n += 2 * (order + 1)
return n
# for parallelization of matching in 'intrabrickshift'...
def oldrange(*args, **kwargs):
return list(builtins.range(*args, **kwargs))
def lrange(*args, **kwargs):
return list(range(*args, **kwargs))
def __init__(self, whatrange): ## range example --> "23-56"
try:
ran = whatrange.split("-")
self.minimum = int(ran[0])
self.maximum = int(ran[1])
self.__count = self.maximum - self.minimum + 1
self.width = len(ran[0])
self.current = self.minimum
except:
raise FuzzException(FuzzException.FATAL, "Bad range format (eg. \"23-56\")")
def __init__(self, prange): ## range example --> "0-ffa"
try:
ran = prange.split("-")
self.minimum = int(ran[0],16)
self.maximum = int(ran[1],16)
self.__count = self.maximum - self.minimum + 1
self.current = self.minimum
except:
raise Exception, "Bad range format (eg. \"0-ffa\")"
def __init__(self, prange): ## range example --> "0-ffa"
try:
ran = prange.split("-")
self.minimum=int(ran[0],16)
self.maximum=int(ran[1],16)
self.__count=-1
except:
raise Exception, "Bad range format (eg. \"0-ffa\")"
def __init__(self, l):
if l.find("\\") >= 0:
l = l.replace("\\-", "$SEP$")
l = l.replace("\\\\", "$SCAP$")
self.l = l.split("-")
for i in __builtin__.range(len(self.l)):
self.l[i] = self.l[i].replace("$SEP$", "-")
self.l[i] = self.l[i].replace("$SCAP$", "\\")
else:
self.l = l.split("-")
self.__count = len(self.l)
self.current = 0
def __iterate__():
'''Iterate through all enumeration ids defined in the database.'''
for n in __builtin__.range(idaapi.get_enum_qty()):
yield idaapi.getn_enum(n)
return
def range():
'''Return the total address range of the database.'''
return config.bounds()
def __new__(cls):
'''Returns a list of all of the functions in the current database (ripped from idautils).'''
left,right = range()
# find first function chunk
ch = idaapi.get_fchunk(left) or idaapi.get_next_fchunk(left)
while ch and ch.startEA < right and (ch.flags & idaapi.FUNC_TAIL) != 0:
ch = idaapi.get_next_fchunk(ch.startEA)
# iterate through the rest of the functions in the database
result = []
while ch and ch.startEA < right:
result.append(ch.startEA)
ch = idaapi.get_next_func(ch.startEA)
return result
def __iterate__(cls):
'''Iterates through all of the functions in the current database (ripped from idautils).'''
left,right = range()
# find first function chunk
ch = idaapi.get_fchunk(left) or idaapi.get_next_fchunk(left)
while ch and ch.startEA < right and (ch.flags & idaapi.FUNC_TAIL) != 0:
ch = idaapi.get_next_fchunk(ch.startEA)
# iterate through the rest of the functions in the database
while ch and ch.startEA < right:
yield ch.startEA
ch = idaapi.get_next_func(ch.startEA)
return
def __iterate__(cls, **type):
if not type: type = {'predicate':lambda n: True}
res = __builtin__.range(idaapi.get_nlist_size())
for k,v in type.iteritems():
res = __builtin__.list(cls.__matcher__.match(k, v, res))
for n in res: yield n
def __iterate__(cls, **type):
if not type: type = {'predicate':lambda n: True}
res = __builtin__.range(idaapi.get_entry_qty())
for k,v in type.iteritems():
res = __builtin__.list(cls.__matcher__.match(k, v, res))
for n in res: yield n
def __index__(cls, ea):
'''Returns the index of the entry-point at the specified ``address``.'''
f = utils.compose(idaapi.get_entry_ordinal, idaapi.get_entry)
iterable = itertools.imap(utils.compose(utils.fap(f, lambda n:n), __builtin__.tuple), __builtin__.range(idaapi.get_entry_qty()))
filterable = itertools.ifilter(utils.compose(utils.first, functools.partial(operator.eq, ea)), iterable)
result = itertools.imap(utils.second, filterable)
return __builtin__.next(result, None)
def array(cls, ea):
'''Return the values of the array at address ``ea``.'''
ea = interface.address.within(ea)
numerics = {
idaapi.FF_BYTE : 'B',
idaapi.FF_WORD : 'H',
idaapi.FF_DWRD : 'L',
idaapi.FF_QWRD : 'Q',
idaapi.FF_FLOAT : 'f',
idaapi.FF_DOUBLE : 'd',
}
strings = {
1 : 'c',
2 : 'u',
}
fl = type.flags(ea)
elesize = idaapi.get_full_data_elsize(ea, fl)
if fl & idaapi.FF_ASCI == idaapi.FF_ASCI:
t = strings[elesize]
elif fl & idaapi.FF_STRU == idaapi.FF_STRU:
t, size = type.structure.id(ea), idaapi.get_item_size(ea)
return [ cls.struc(ea, id=t) for ea in __builtin__.range(ea, ea+size, structure.size(t)) ]
else:
ch = numerics[fl & idaapi.DT_TYPE]
t = ch.lower() if fl & idaapi.FF_SIGN == idaapi.FF_SIGN else ch
res = array.array(t, read(ea, type.array.size(ea)))
if len(res) != type.array.length(ea):
logging.warn("{:s}.get({:x}) : Unexpected length : ({:d} != {:d})".format('.'.join((__name__, cls.__name__)), ea, len(res), type.array.length(ea)))
return res
def genrange(*a):
"""Function to implement 'range' as a generator"""
start, stop, step = handleargs(a)
value = start
while value < stop:
yield value
value += step
def __init__(self, *a):
""" Initialize start, stop, and step values along with calculating the
nubmer of values (what __len__ will return) in the range"""
self.start, self.stop, self.step = handleargs(a)
self.len = max(0, (self.stop - self.start) // self.step)
def __repr__(self):
"""implement repr(x) which is also used by print"""
return 'range(%r, %r, %r)' % (self.start, self.stop, self.step)
def __getitem__(self, i):
"""implement x[i]"""
if 0 <= i <= self.len:
return self.start + self.step * i
else:
raise IndexError, 'range[i] index out of range'
def lrange(*args, **kwargs):
return list(range(*args, **kwargs))