我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用builtins.int()。
def _sort_names(names): ''' Sort peeker names by index and alphabetically. For example, the peeker names would be sorted as a[0], b[0], a[1], b[1], ... ''' def index_key(lbl): '''Index sorting.''' m = re.match('.*\[(\d+)\]$', lbl) # Get the bracketed index. if m: return int(m.group(1)) # Return the index as an integer. return -1 # No index found so it comes before everything else. def name_key(lbl): '''Name sorting.''' m = re.match('^([^\[]+)', lbl) # Get name preceding bracketed index. if m: return m.group(1) # Return name. return '' # No name found. srt_names = sorted(names, key=name_key) srt_names = sorted(srt_names, key=index_key) return srt_names
def __init__(self, delimiter=None, comments=asbytes('#'), autostrip=True): self.comments = comments # Delimiter is a character if isinstance(delimiter, unicode): delimiter = delimiter.encode('ascii') if (delimiter is None) or _is_bytes_like(delimiter): delimiter = delimiter or None _handyman = self._delimited_splitter # Delimiter is a list of field widths elif hasattr(delimiter, '__iter__'): _handyman = self._variablewidth_splitter idx = np.cumsum([0] + list(delimiter)) delimiter = [slice(i, j) for (i, j) in zip(idx[:-1], idx[1:])] # Delimiter is a single integer elif int(delimiter): (_handyman, delimiter) = ( self._fixedwidth_splitter, int(delimiter)) else: (_handyman, delimiter) = (self._delimited_splitter, None) self.delimiter = delimiter if autostrip: self._handyman = self.autostrip(_handyman) else: self._handyman = _handyman #
def _strict_call(self, value): try: # We check if we can convert the value using the current function new_value = self.func(value) # In addition to having to check whether func can convert the # value, we also have to make sure that we don't get overflow # errors for integers. if self.func is int: try: np.array(value, dtype=self.type) except OverflowError: raise ValueError # We're still here so we can now return the new value return new_value except ValueError: if value.strip() in self.missing_values: if not self._status: self._checked = False return self.default raise ValueError("Cannot convert string '%s'" % value) #
def __str__(self): """ >>> str(FloatTextRecord(float('-inf'))) '-INF' >>> str(FloatTextRecord(-0.0)) '-0' >>> str(FloatTextRecord(1.337)) '1.337' """ try: if self.value == int(self.value): return '%.0f' % self.value else: return str(self.value) except: return str(self.value).upper()
def explode(collapsed): '''Explode references like 'C1-C3,C7,C10-C13' into [C1,C2,C3,C7,C10,C11,C12,C13]''' if collapsed == '': return [] individual_refs = [] if isinstance(collapsed, str) or isinstance(collapsed, basestring): range_refs = re.split(',|;', collapsed) for r in range_refs: mtch = re.match( '^\s*(?P<part_prefix>\D+)(?P<range_start>\d+)\s*[-:]\s*\\1(?P<range_end>\d+)\s*$', r) if mtch is None: individual_refs.append(r.strip()) else: part_prefix = mtch.group('part_prefix') range_start = int(mtch.group('range_start')) range_end = int(mtch.group('range_end')) for i in range(range_start, range_end + 1): individual_refs.append(part_prefix + str(i)) logger.log(DEBUG_OBSESSIVE, 'Exploding {} => {}.'.format(collapsed, individual_refs)) return individual_refs
def __prompt_for_role(account_name, role_names): border = "" spaces = "" for index in range(len(account_name)): border = "-" + border spaces = " " + spaces print('{}#------------------------------------------------{}#'.format(Colors.lblue,border)) print('# {}You have access to the following roles in {}{}{} #'.format(Colors.white,Colors.yellow,account_name,Colors.lblue)) print('# {}Which role would you like to assume?{}{} #'.format(Colors.white,Colors.lblue,spaces)) print('#------------------------------------------------{}#{}'.format(border,Colors.normal)) for index, role_name in enumerate(role_names): if role_name == "AccountAdministrator": print("\t{}{} {}{}".format(Colors.red, str(index).rjust(2), role_name,Colors.normal)) else: print("\t{}{}{} {}{}".format(Colors.white, str(index).rjust(2), Colors.cyan, role_name, Colors.normal)) while True: choice = input('{}Select role: {}'.format(Colors.lblue, Colors.normal)) try: return role_names[int(choice)] except: maximum = len(role_names) - 1 print('{}Please enter an integer between 0 and {}{}'.format(Colors.lred, maximum, Colors.normal))
def _find_min_max_pins(self): """ Return the minimum and maximum pin numbers for the part. """ pin_nums = [] try: for p in self.pins: try: pin_nums.append(int(p.num)) except ValueError: pass except AttributeError: # This happens if the part has no pins. pass try: return min(pin_nums), max(pin_nums) except ValueError: # This happens if the part has no integer-labeled pins. return 0, 0
def data(self, value): if isinstance(value, bool): self._data_type = bool self._pb.bool_data = value elif isinstance(value, int): self._data_type = int self._pb.int64_data = value elif isinstance(value, float): self._data_type = float self._pb.float64_data = value elif isinstance(value, basestring): self._data_type = str self._pb.string_data = value elif isinstance(value, bytes): self._data_type = bytes self._pb.bytes_data = value else: raise TypeError("Unsupported data type '{}'. (Supported: " "int, long, float, str and bool)".format(value))
def collect(self, metrics): for metric in metrics: metric.timestamp = time.time() metric.version = 2 if "bytes" in metric.config and metric.config["bytes"] is True: metric.data = b'qwerty' elif "string" in metric.config and metric.config["string"] is True: metric.data = "qwerty" elif "int32" in metric.config and metric.config["int32"] is True: metric.data = 99 elif "int64" in metric.config and metric.config["int64"] is True: metric.data = bigint(99) elif "bool" in metric.config and metric.config["bool"] is True: metric.data = True else: metric.data = 99.9 return metrics
def handle_elif(self, span, cond): '''Should be called to signalize an elif directive. Args: span (tuple of int): Start and end line of the directive. cond (str): String representation of the branching condition. ''' self._check_for_open_block(span, 'elif') block = self._open_blocks[-1] directive, _, spans = block[0:3] self._check_if_matches_last(directive, 'if', spans[-1], span, 'elif') conds, contents = block[3:5] conds.append(cond) contents.append(self._curnode) spans.append(span) self._curnode = []
def handle_enddef(self, span, name): '''Should be called to signalize an enddef directive. Args: span (tuple of int): Start and end line of the directive. name (str): Name of the enddef statement. Could be None, if enddef was specified without name. ''' self._check_for_open_block(span, 'enddef') block = self._open_blocks.pop(-1) directive, fname, spans = block[0:3] self._check_if_matches_last(directive, 'def', spans[-1], span, 'enddef') defname, argexpr, dummy = block[3:6] if name is not None and name != defname: msg = "wrong name in enddef directive "\ "(expected '{0}', got '{1}')".format(defname, name) raise FyppFatalError(msg, fname, span) spans.append(span) block = (directive, fname, spans, defname, argexpr, self._curnode) self._curnode = self._path.pop(-1) self._curnode.append(block)
def handle_nextarg(self, span, name): '''Should be called to signalize a nextarg directive. Args: span (tuple of int): Start and end line of the directive. name (str or None): Name of the argument following next or None if it should be the next positional argument. ''' self._check_for_open_block(span, 'nextarg') block = self._open_blocks[-1] directive, fname, spans = block[0:3] self._check_if_matches_last( directive, 'call', spans[-1], span, 'nextarg') args, argnames = block[5:7] args.append(self._curnode) spans.append(span) if name is not None: argnames.append(name) elif argnames: msg = 'non-keyword argument following keyword argument' raise FyppFatalError(msg, fname, span) self._curnode = []
def test_wiener(tries=10): print("\nTest: wiener") for _ in range(tries): n_size = 1024 p = random_prime(n_size / 2) q = random_prime(n_size / 2) n = p*q phi = (p-1)*(q-1) while True: d = random.getrandbits(n_size / 4) if gmpy2.gcd(phi, d) == 1 and 81 * pow(d, 4) < n: break e = invmod(d, phi) key = RSAKey.construct(int(n), int(e)) key_recovered = wiener(key.publickey()) if key_recovered: assert key_recovered.d == d else: print("Not recovered")
def crt(a, n): """Solve chinese remainder theorem from: http://rosettacode.org/wiki/Chinese_remainder_theorem#Python Args: a(list): remainders n(list): modules Returns: long: solution to crt """ if len(a) != len(n): log.critical_error("Different number of remainders({}) and modules({})".format(len(a), len(n))) prod = product(n) sum_crt = 0 for n_i, a_i in zip(n, a): p = prod / n_i sum_crt += a_i * invmod(p, n_i) * p return int(sum_crt % prod)
def add_text_pair(self, ciphertext=None, plaintext=None): """Args: ciphertext(int), plaintext(int)""" if not ciphertext and not plaintext: log.error("Can't add None ciphertext and None plaintext") return text_pair = {} if ciphertext: if not isinstance(ciphertext, Number): log.error("Ciphertext to add have to be number") else: text_pair['cipher'] = ciphertext if plaintext: if not isinstance(plaintext, Number): log.error("Plaintext to add have to be number") else: text_pair['plain'] = plaintext self.texts.append(text_pair)
def common_primes(keys): """Find common prime in keys modules Args: keys(list): RSAKeys Returns: list: RSAKeys for which factorization of n was found """ priv_keys = [] for pair in itertools.combinations(keys, 2): prime = gmpy2.gcd(pair[0].n, pair[1].n) if prime != 1: log.success("Found common prime in: {}, {}".format(pair[0].identifier, pair[1].identifier)) for key_no in range(2): if pair[key_no] not in priv_keys: d = int(invmod(pair[key_no].e, (prime - 1) * (pair[key_no].n / prime - 1))) new_key = RSAKey.construct(int(pair[key_no].n), int(pair[key_no].e), int(d), identifier=pair[key_no].identifier + '-private') new_key.texts = pair[key_no].texts[:] priv_keys.append(new_key) else: log.debug("Key {} already in priv_keys".format(pair[key_no].identifier)) return priv_keys
def _set_array_types(): ibytes = [1, 2, 4, 8, 16, 32, 64] fbytes = [2, 4, 8, 10, 12, 16, 32, 64] for bytes in ibytes: bits = 8*bytes _add_array_type('int', bits) _add_array_type('uint', bits) for bytes in fbytes: bits = 8*bytes _add_array_type('float', bits) _add_array_type('complex', 2*bits) _gi = dtype('p') if _gi.type not in sctypes['int']: indx = 0 sz = _gi.itemsize _lst = sctypes['int'] while (indx < len(_lst) and sz >= _lst[indx](0).itemsize): indx += 1 sctypes['int'].insert(indx, _gi.type) sctypes['uint'].insert(indx, dtype('P').type)
def parse(self, chunksize = 0): if not isinstance(self.dep, dict): raise MalformedDEPException(_('Malformed DEP root')) if 'Belege-Gruppe' not in self.dep: raise MissingDEPElementException('Belege-Gruppe') bg = self.dep['Belege-Gruppe'] if not isinstance(bg, list) or len(bg) <= 0: raise MalformedDEPElementException('Belege-Gruppe') if self.nparts > 1 and not chunksize: nrecs = totalRecsInDictDEP(self.dep) chunksize = int(ceil(float(nrecs) / self.nparts)) got_something = False for chunk in self._groupChunkGen(chunksize, bg): yield chunk got_something = True if not got_something: raise MalformedDEPException(_('No receipts found'))
def __init__(self, registerId, lastReceiptSig, turnoverCounter, key, turnoverCounterSize=8): """ Creates a new cash register with the specified data. :param registerId: The ID of the register as a string. :param lastReceiptSig: The last receipt as a JWS string or None if no previous receipts exist. :param turnoverCounter: The initial value of the turnover counter. :param key: The AES key to encrypt the turnover counter as a byte list. :param turnoverCounterSize: The number of bytes used to represent the turnover counter as an int. Must be between 5 and 16 (inclusive). """ if turnoverCounterSize < 5 or turnoverCounterSize > 16: raise Exception(_("Invalid turnover counter size.")) self.registerId = registerId self.lastReceiptSig = lastReceiptSig self.turnoverCounter = int(turnoverCounter) self.turnoverCounterSize = turnoverCounterSize self.key = key
def write_header(self, buf): self.header += buf # TODO: forward headers?, this is possibly unneeded, # when we just parse valid 200 headers as first chunk, # we will parse the headers if not self.range and self.header.endswith(os.linesep * 2): self.parse_header() # ftp file size parsing elif (not self.range and buf.startswith("150") and "data connection" in buf): size = re.search(r"(\d+) bytes", buf) if size is not None: self.p._size = int(size.group(1)) self.p.chunk_support = True self.header_parsed = True
def parse_header(self): """ Parse data from received header. """ for orgline in self.decode_response(self.header).splitlines(): line = orgline.strip().lower() if line.startswith("accept-ranges") and "bytes" in line: self.p.chunk_support = True if 'content-disposition' in line: m = self._RE_FILENAME.search(orgline.strip()) if m is not None: name = purge.name(m.groupdict()['name']) self.p._name = name self.log.debug("Content-Disposition: {0}".format(name)) if not self.resume and line.startswith('content-length'): self.p._size = int(line.split(":")[1]) self.header_parsed = True
def test_setMinimumMaximum(self, spinbox): spinbox.setMinimum(0) spinbox.setMinimum(int(0)) spinbox.setMinimum(1) spinbox.setMinimum(int(1)) spinbox.setMinimum(-1) spinbox.setMinimum(int(-1)) with pytest.raises(TypeError) as excinfo: spinbox.setMinimum('') assert "int or long" in str(excinfo.value) spinbox.setMaximum(0) spinbox.setMaximum(int(0)) spinbox.setMaximum(1) spinbox.setMaximum(int(1)) spinbox.setMaximum(-1) spinbox.setMaximum(int(-1)) with pytest.raises(TypeError) as excinfo: spinbox.setMaximum('') assert "int or long" in str(excinfo.value)
def sort(self, columnId, order=Qt.AscendingOrder): """ Sorts the model column After sorting the data in ascending or descending order, a signal `layoutChanged` is emitted. :param: columnId (int) the index of the column to sort on. :param: order (Qt::SortOrder, optional) descending(1) or ascending(0). defaults to Qt.AscendingOrder """ self.layoutAboutToBeChanged.emit() self.sortingAboutToStart.emit() column = self._dataFrame.columns[columnId] self._dataFrame.sort(column, ascending=not bool(order), inplace=True) self.layoutChanged.emit() self.sortingFinished.emit()
def setValue(self, value): """setter function to _lineEdit.text. Sets minimum/maximum as new value if value is out of bounds. Args: value (int/long): new value to set. Returns True if all went fine. """ if value >= self.minimum() and value <= self.maximum(): self._lineEdit.setText(str(value)) elif value < self.minimum(): self._lineEdit.setText(str(self.minimum())) elif value > self.maximum(): self._lineEdit.setText(str(self.maximum())) return True
def accept(self): super(AddAttributesDialog, self).accept() newColumn = self.columnNameLineEdit.text() dtype = SupportedDtypes.dtype(self.dataTypeComboBox.currentText()) defaultValue = self.defaultValueLineEdit.text() try: if dtype in SupportedDtypes.intTypes() + SupportedDtypes.uintTypes(): defaultValue = int(defaultValue) elif dtype in SupportedDtypes.floatTypes(): defaultValue = float(defaultValue) elif dtype in SupportedDtypes.boolTypes(): defaultValue = defaultValue.lower() in ['t', '1'] elif dtype in SupportedDtypes.datetimeTypes(): defaultValue = Timestamp(defaultValue) if isinstance(defaultValue, NaTType): defaultValue = Timestamp('') else: defaultValue = dtype.type() except ValueError as e: defaultValue = dtype.type() self.accepted.emit(newColumn, dtype, defaultValue)
def get_value(self, time): '''Get the trace value at an arbitrary time.''' # Return the signal value immediately BEFORE the insertion index. return int(self[max(0, self.get_index(time)-1)].value)
def wavejson_to_wavedrom(wavejson, width=None, skin='default'): ''' Create WaveDrom display from WaveJSON data. This code is from https://github.com/witchard/ipython-wavedrom. Inputs: width: Width of the display window in pixels. If left as None, the entire waveform will be squashed into the width of the page. To prevent this, set width to a large value. The display will then become scrollable. skin: Selects the set of graphic elements used to draw the waveforms. Allowable values are 'default' and 'narrow'. ''' # Set the width of the waveform display. style = '' if width != None: style = ' style="width: {w}px"'.format(w=str(int(width))) # Generate the HTML from the JSON. htmldata = '<div{style}><script type="WaveDrom">{json}</script></div>'.format( style=style, json=json.dumps(wavejson)) DISP.display_html(DISP.HTML(htmldata)) # Trigger the WaveDrom Javascript that creates the graphical display. DISP.display_javascript( DISP.Javascript( data='WaveDrom.ProcessAll();', lib=[ 'http://wavedrom.com/wavedrom.min.js', 'http://wavedrom.com/skins/{skin}.js'.format(skin=skin) ])) # The following allows the display of WaveDROM in the HTML files generated by nbconvert. # It's disabled because it makes Github's nbconvert freak out. setup = ''' <script src="http://wavedrom.com/skins/{skin}.js" type="text/javascript"></script> <script src="http://wavedrom.com/wavedrom.min.js" type="text/javascript"></script> <body onload="WaveDrom.ProcessAll()"> '''.format(skin=skin) #DISP.display_html(DISP.HTML(setup))
def get_trades(self, order_id): """ get all trades of a particular order """ if not isinstance(order_id, int): raise TypeError("Required parameter order_id not of type int") return self.api_call_helper('tradesInfo', PyCurlVerbs.GET, {'order_id' : order_id}, None)
def cancel_order(self, order_id): # if not isinstance(order_id, int): # raise TypeError("Required parameter order_id not of type int") return self.api_call_helper('cancelOrder', PyCurlVerbs.DELETE, {'order_id' : order_id}, None)
def cancel_all_orders(self): # if not isinstance(order_id, int): # raise TypeError("Required parameter order_id not of type int") return self.api_call_helper('cancelAllOrders', PyCurlVerbs.DELETE, None, None)
def validate_value(self, key, value): if int(value) != value: raise ValueError('Invalid non-integer insulin value at {}: {}'.format(self.time, value)) if value < 1: raise ValueError('Invalid insulin value at {}: {} < 1'.format(self.time, value)) return value
def _evalname(name): k = 0 for ch in name: if ch in '0123456789': break k += 1 try: bits = int(name[k:]) except ValueError: bits = 0 base = name[:k] return base, bits
def _add_aliases(): for a in typeinfo.keys(): name = english_lower(a) if not isinstance(typeinfo[a], tuple): continue typeobj = typeinfo[a][-1] # insert bit-width version for this class (if relevant) base, bit, char = bitname(typeobj) if base[-3:] == 'int' or char[0] in 'ui': continue if base != '': myname = "%s%d" % (base, bit) if ((name != 'longdouble' and name != 'clongdouble') or myname not in allTypes.keys()): allTypes[myname] = typeobj sctypeDict[myname] = typeobj if base == 'complex': na_name = '%s%d' % (english_capitalize(base), bit//2) elif base == 'bool': na_name = english_capitalize(base) sctypeDict[na_name] = typeobj else: na_name = "%s%d" % (english_capitalize(base), bit) sctypeDict[na_name] = typeobj sctypeNA[na_name] = typeobj sctypeDict[na_name] = typeobj sctypeNA[typeobj] = na_name sctypeNA[typeinfo[a][0]] = na_name if char != '': sctypeDict[char] = typeobj sctypeNA[char] = na_name
def _add_integer_aliases(): _ctypes = ['LONG', 'LONGLONG', 'INT', 'SHORT', 'BYTE'] for ctype in _ctypes: val = typeinfo[ctype] bits = val[2] charname = 'i%d' % (bits//8,) ucharname = 'u%d' % (bits//8,) intname = 'int%d' % bits UIntname = 'UInt%d' % bits Intname = 'Int%d' % bits uval = typeinfo['U'+ctype] typeobj = val[-1] utypeobj = uval[-1] if intname not in allTypes.keys(): uintname = 'uint%d' % bits allTypes[intname] = typeobj allTypes[uintname] = utypeobj sctypeDict[intname] = typeobj sctypeDict[uintname] = utypeobj sctypeDict[Intname] = typeobj sctypeDict[UIntname] = utypeobj sctypeDict[charname] = typeobj sctypeDict[ucharname] = utypeobj sctypeNA[Intname] = typeobj sctypeNA[UIntname] = utypeobj sctypeNA[charname] = typeobj sctypeNA[ucharname] = utypeobj sctypeNA[typeobj] = Intname sctypeNA[utypeobj] = UIntname sctypeNA[val[0]] = Intname sctypeNA[uval[0]] = UIntname
def issubclass_(arg1, arg2): """ Determine if a class is a subclass of a second class. `issubclass_` is equivalent to the Python built-in ``issubclass``, except that it returns False instead of raising a TypeError if one of the arguments is not a class. Parameters ---------- arg1 : class Input class. True is returned if `arg1` is a subclass of `arg2`. arg2 : class or tuple of classes. Input class. If a tuple of classes, True is returned if `arg1` is a subclass of any of the tuple elements. Returns ------- out : bool Whether `arg1` is a subclass of `arg2` or not. See Also -------- issubsctype, issubdtype, issctype Examples -------- >>> np.issubclass_(np.int32, np.int) True >>> np.issubclass_(np.int32, np.float) False """ try: return issubclass(arg1, arg2) except TypeError: return False
def issubsctype(arg1, arg2): """ Determine if the first argument is a subclass of the second argument. Parameters ---------- arg1, arg2 : dtype or dtype specifier Data-types. Returns ------- out : bool The result. See Also -------- issctype, issubdtype,obj2sctype Examples -------- >>> np.issubsctype('S8', str) True >>> np.issubsctype(np.array([1]), np.int) True >>> np.issubsctype(np.array([1]), np.float) False """ return issubclass(obj2sctype(arg1), obj2sctype(arg2))
def flatten_dtype(ndtype, flatten_base=False): """ Unpack a structured data-type by collapsing nested fields and/or fields with a shape. Note that the field names are lost. Parameters ---------- ndtype : dtype The datatype to collapse flatten_base : {False, True}, optional Whether to transform a field with a shape into several fields or not. Examples -------- >>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float), ... ('block', int, (2, 3))]) >>> np.lib._iotools.flatten_dtype(dt) [dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32')] >>> np.lib._iotools.flatten_dtype(dt, flatten_base=True) [dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32'), dtype('int32'), dtype('int32'), dtype('int32'), dtype('int32'), dtype('int32')] """ names = ndtype.names if names is None: if flatten_base: return [ndtype.base] * int(np.prod(ndtype.shape)) return [ndtype.base] else: types = [] for field in names: info = ndtype.fields[field] flat_dt = flatten_dtype(info[0], flatten_base) types.extend(flat_dt) return types
def parse(cls, fp): r""" >>> from io import BytesIO >>> fp = BytesIO(b'\xff\xff\xff\xff\xff\xff\xff\xff') >>> int(UInt64TextRecord.parse(fp).value) 18446744073709551615 """ return cls(struct.unpack(b'<Q', fp.read(8))[0])
def __prompt_for_account(account_names): print('{}#--------------------------------------------------#'.format(Colors.lblue)) print('# {}To which account would you like to login?{} #'.format(Colors.white,Colors.lblue)) print('#--------------------------------------------------#{}'.format(Colors.normal)) for index, account_name in enumerate(account_names): print("\t{}{}{} {}{}".format(Colors.white,str(index).rjust(2), Colors.yellow,account_name,Colors.normal)) while True: choice = input('{}Select account:{} '.format(Colors.lblue,Colors.normal)) try: return account_names[int(choice)] except: maximum = len(account_names) - 1 print('{}Please enter an integer between 0 and {}{}'.format(Colors.lred,maximum,Colors.normal))
def get_session_duration(self): aws_session_duration = default_session_duration # Retrieve session duration for element in self.get_decoded_assertion().findall( './/{*}Attribute[@Name="https://aws.amazon.com/SAML/Attributes/SessionDuration"]/{*}AttributeValue'): aws_session_duration = int(element.text) return aws_session_duration
def __init__(self, header, payload, label=None, target=None): self.header = header self.payload = int(payload) self.label = label self.target = target