我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sys.maxint()。
def malloc(self, size): # return a block of right size (possibly rounded up) assert 0 <= size < sys.maxint if os.getpid() != self._lastpid: self.__init__() # reinitialize after fork self._lock.acquire() try: size = self._roundup(max(size,1), self._alignment) (arena, start, stop) = self._malloc(size) new_stop = start + size if new_stop < stop: self._free((arena, new_stop, stop)) block = (arena, start, new_stop) self._allocated_blocks.add(block) return block finally: self._lock.release() # # Class representing a chunk of an mmap -- can be inherited #
def _make_boundary(text=None): # Craft a random boundary. If text is given, ensure that the chosen # boundary doesn't appear in the text. token = random.randrange(sys.maxint) boundary = ('=' * 15) + (_fmt % token) + '==' if text is None: return boundary b = boundary counter = 0 while True: cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE) if not cre.search(text): break b = boundary + '.' + str(counter) counter += 1 return b
def rename(src, dst): # Try atomic or pseudo-atomic rename if _rename(src, dst): return # Fall back to "move away and replace" try: os.rename(src, dst) except OSError as e: if e.errno != errno.EEXIST: raise old = "%s-%08x" % (dst, random.randint(0, sys.maxint)) os.rename(dst, old) os.rename(src, dst) try: os.unlink(old) except Exception: pass
def _create_html_table(self, content, files): table = ElementTree.fromstring(CPPCHECK_HTML_TABLE) for name, val in files.items(): f = val['htmlfile'] s = '<tr><td colspan="4"><a href="%s">%s</a></td></tr>\n' % (f,name) row = ElementTree.fromstring(s) table.append(row) errors = sorted(val['errors'], key=lambda e: int(e['line']) if e.has_key('line') else sys.maxint) for e in errors: if not e.has_key('line'): s = '<tr><td></td><td>%s</td><td>%s</td><td>%s</td></tr>\n' % (e['id'], e['severity'], e['msg']) else: attr = '' if e['severity'] == 'error': attr = 'class="error"' s = '<tr><td><a href="%s#line-%s">%s</a></td>' % (f, e['line'], e['line']) s+= '<td>%s</td><td>%s</td><td %s>%s</td></tr>\n' % (e['id'], e['severity'], attr, e['msg']) row = ElementTree.fromstring(s) table.append(row) content.append(table)
def __generateRandomVarValue(cls, iVar): # 1- Get the definition domain of the variable defDomain = cls.VARIABLES_RANGES[iVar] if defDomain is None: randFloat = random.uniform(-sys.maxint-1, sys.maxint) else: # 2- Check the open/closed bounds includeFirst = defDomain[0] == '[' includeLast = defDomain[-1] == ']' # 3- Get a random number in the domain defDomain = eval('[' + defDomain[1:-1] + ']') randFloat = random.random()*(defDomain[1]-defDomain[0]) + defDomain[0] # 4- Check the bounds while (randFloat == defDomain[0] and not includeFirst) or\ (randFloat == defDomain[1] and not includeLast): randFloat = random.random()*(defDomain[1]-defDomain[0]) + defDomain[0] # 5- Cast the variable type return cls.VARIABLES_TYPE(randFloat) # ----------------------
def numSquares1(n): dp = [-1 for i in range(n + 1)] dp[1] = 1 for i in range(2, n + 1): j = 1 m = sys.maxint while j * j <= i: if j * j == i: m = 1 break m = min(m, dp[i - j * j] + 1) j += 1 dp[i] = m return dp[n] # print(numSquares1(10234))
def numSquares2(n): dp = [sys.maxint for i in range(n + 1)] dp[0] = 0 for i in range(0, n + 1): for j in range(1, int(math.sqrt(n - i)) + 1): if i + j * j <= n: dp[i + j * j] = min(dp[i + j * j], dp[i] + 1) return dp[n] # print(numSquares2(4)) # ??, ????????, ??????????????? # ??: ????????: # 1. ?????????????????????4????????????????4?????????????????????1,2,3?4????? # 2. ???????????4????????4?????????????2?8,3?12?? # 3. ???????8?7?????????4???????? # 4. ???????????????????????????1?2?????????????0
def base36_to_int(s): """ Converts a base 36 string to an ``int``. Raises ``ValueError` if the input won't fit into an int. """ # To prevent overconsumption of server resources, reject any # base36 string that is long than 13 base36 digits (13 digits # is sufficient to base36-encode any 64-bit integer) if len(s) > 13: raise ValueError("Base36 input too large") value = int(s, 36) # ... then do a final check that the value will fit into an int to avoid # returning a long (#15067). The long type was removed in Python 3. if six.PY2 and value > sys.maxint: raise ValueError("Base36 input too large") return value
def int_to_base36(i): """ Converts an integer to a base36 string """ char_set = '0123456789abcdefghijklmnopqrstuvwxyz' if i < 0: raise ValueError("Negative base36 conversion input.") if six.PY2: if not isinstance(i, six.integer_types): raise TypeError("Non-integer base36 conversion input.") if i > sys.maxint: raise ValueError("Base36 conversion input too large.") if i < 36: return char_set[i] b36 = '' while i != 0: i, n = divmod(i, 36) b36 = char_set[n] + b36 return b36
def malloc(self, size): # return a block of right size (possibly rounded up) assert 0 <= size < sys.maxint if os.getpid() != self._lastpid: self.__init__() # reinitialize after fork self._lock.acquire() self._free_pending_blocks() try: size = self._roundup(max(size,1), self._alignment) (arena, start, stop) = self._malloc(size) new_stop = start + size if new_stop < stop: self._free((arena, new_stop, stop)) block = (arena, start, new_stop) self._allocated_blocks.add(block) return block finally: self._lock.release() # # Class representing a chunk of an mmap -- can be inherited #
def _make_boundary(text=None): #some code taken from python stdlib # Craft a random boundary. If text is given, ensure that the chosen # boundary doesn't appear in the text. token = random.randrange(sys.maxint) boundary = ('=' * 10) + (_fmt % token) + '==' if text is None: return boundary b = boundary counter = 0 while True: cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE) if not cre.search(text): break b = boundary + '.' + str(counter) counter += 1 return b
def _sliced_list(self, selector): """For slice selectors operating on lists, we need to handle them differently, depending on ``skipmissing``. In explicit mode, we may have to expand the list with ``default`` values. """ if self.skipmissing: return self.obj[selector] # TODO: can be optimized by observing list bounds keys = xrange(selector.start or 0, selector.stop or sys.maxint, selector.step or 1) res = [] for key in keys: self._append(self.obj, key, res, skipmissing=False) return res
def detect_cycles(): for root_edge in roots: reset_graph() # Mark ignored classes as already visited for ignore in args.ignore_classes: name = ignore.find("::") > 0 and ignore or ("blink::" + ignore) node = graph.get(name) if node: node.visited = True src = graph[root_edge.src] dst = graph.get(root_edge.dst) if src.visited: continue if root_edge.dst == "WTF::String": continue if dst is None: print "\nPersistent root to incomplete destination object:" print root_edge set_reported_error(True) continue # Find the shortest path from the root target (dst) to its host (src) shortest_path(dst, src) if src.cost < sys.maxint: report_cycle(root_edge)
def __getitem__(self, i): if isinstance(i, slice): start = i.start or 0 stop = i.stop db = self.db if start < 0: pos0 = '(%s - %d)' % (self.len(), abs(start) - 1) else: pos0 = start + 1 maxint = sys.maxint if PY2 else sys.maxsize if stop is None or stop == maxint: length = self.len() elif stop < 0: length = '(%s - %d - %s)' % (self.len(), abs(stop) - 1, pos0) else: length = '(%s - %s)' % (stop + 1, pos0) return Expression(db, self._dialect.substring, self, (pos0, length), self.type) else: return self[i:i + 1]
def first_child_matching_class(self, childclass, start=0, end=sys.maxint): """ Return the index of the first child whose class exactly matches. Parameters: - `childclass`: A `Node` subclass to search for, or a tuple of `Node` classes. If a tuple, any of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, tuple): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self[index], c): return index return None
def first_child_not_matching_class(self, childclass, start=0, end=sys.maxint): """ Return the index of the first child whose class does *not* match. Parameters: - `childclass`: A `Node` subclass to skip, or a tuple of `Node` classes. If a tuple, none of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, tuple): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self.children[index], c): break else: return index return None
def version_str_to_tuple(version_str): import re import sys if version_str == 'HEAD': return (sys.maxint, sys.maxint, sys.maxint, sys.maxint) m = re.match(r'(\d+)\.(\d+)(\.(\d+))?(b(\d+))?', version_str) if m is None: raise ValueError("Bad version string %r" % version_str) major = int(m.group(1)) minor = int(m.group(2)) patch = int(m.group(4) or 0) beta = int(m.group(6) or sys.maxint) return (major, minor, patch, beta)
def read(self, size=None): """Read data from RAW file. Args: size: Number of bytes to read as integer. Actual number of bytes read is always equal to size unless end if file was reached. Returns: A string with data read. """ if size is None: size = sys.maxint data_list = [] while True: result = self.__readBuffer(size) data_list.append(result) size -= len(result) if size == 0 or self._eof: return ''.join(data_list) self.__refillBuffer()
def __init__(self, output_directory, base_name, maximum_size=sys.maxint): self.base_name = base_name self.output_directory = os.path.normpath(output_directory) self.maximum_size = maximum_size if not os.path.exists(self.output_directory): os.makedirs(self.output_directory) elif not os.path.isdir(self.output_directory): raise JarWriteError('Not a directory: %s' % self.output_directory) self.current_jar = None self.current_jar_size = 0 self.jar_suffix = 0
def __init__(self, objectid=None, minfo=None): if minfo is None: minfo = {} super(ExchangeOfferObject, self).__init__(objectid, minfo) self.CreatorID = minfo.get('creator', '**UNKNOWN**') self.InputID = minfo.get('input', '**UNKNOWN**') self.OutputID = minfo.get('output', '**UNKNOWN**') self.Ratio = float(minfo.get('ratio', 0)) self.Description = minfo.get('description', '') self.Name = minfo.get('name', '') self.Minimum = int(minfo.get('minimum', 1)) self.Maximum = int(minfo.get('maximum', sys.maxint)) self.Execution = minfo.get('execution', 'Any') self.ExecutionState = {'ParticipantList': []} # the minimum must be high enough so that at least 1 asset # is transferred out of the holding as a result of executing the offer if self.Ratio < 0: self.Minimum = max(self.Minimum, int(1.0 / self.Ratio)) if self.Minimum * self.Ratio < 1.0: self.Minimum += 1
def _test(self, filepath): def vcf_row_to_test(vcf_row): return ( vcf_row['info']['TRANSCRIPT'][0], ( vcf_row['chromosome'], vcf_row['start'], vcf_row['reference_allele'], vcf_row['alternate_alleles'][0] ), [x for x in vcf_row['info'].get('REQUIRED', []) if x], [x for x in vcf_row['info'].get('DISALLOWED', []) if x] ) with VcfReader(self.get_absolute_filepath(filepath)) as reader: for row in islice(reader, sys.maxint): self.assertTest(vcf_row_to_test(row))
def createDataRowsFromCSV(csvFilePath, csvParseFunc, DATA_PATH, limit = sys.maxint): ''' Returns a list of DataRow from CSV files parsed by csvParseFunc, DATA_PATH is the prefix to add to the csv file names, limit can be used to parse only partial file rows. ''' data = [] # the array we build validObjectsCounter = 0 with open(csvFilePath, 'r') as csvfile: reader = csv.reader(csvfile, delimiter=' ') for row in reader: d = csvParseFunc(row, DATA_PATH) if d is not None: data.append(d) validObjectsCounter += 1 if (validObjectsCounter > limit ): # Stop if reached to limit return data return data