Python sys.maxsize() Examples

The following are 30 code examples for showing how to use sys.maxsize(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module sys , or try the search function .

Example 1
Project: mx   Author: graalvm   File: mx_gate.py    License: GNU General Public License v2.0 6 votes vote down vote up
def parse_tags_argument(tags_arg, exclude):
    pattern = re.compile(r"^(?P<tag>[^:]*)(?::(?P<from>\d+):(?P<to>\d+)?)?$")
    tags = tags_arg.split(',')
    Task.tags = []
    for tag_spec in tags:
        m = pattern.match(tag_spec)
        if not m:
            mx.abort('--tags option requires the format `name[:from:[to]]`: {0}'.format(tag_spec))
        (tag, t_from, t_to) = m.groups()
        if t_from:
            if exclude:
                mx.abort('-x option cannot be used tag ranges: {0}'.format(tag_spec))
            frm = int(t_from)
            to = int(t_to) if t_to else sys.maxsize
            # insert range tuple
            Task.tags_range[tag] = (frm, to)
            # sanity check
            if to <= frm:
                mx.abort('`from` must be less than `to` for tag ranges: {0}'.format(tag_spec))
            # init counter
            Task.tags_count[tag] = 0
        Task.tags.append(tag) 
Example 2
Project: pymoo   Author: msu-coinlab   File: reference_direction.py    License: Apache License 2.0 6 votes vote down vote up
def map_onto_unit_simplex(rnd, method):
    n_points, n_dim = rnd.shape

    if method == "sum":
        ret = rnd / rnd.sum(axis=1)[:, None]

    elif method == "kraemer":
        M = sys.maxsize

        rnd *= M
        rnd = rnd[:, :n_dim - 1]
        rnd = np.column_stack([np.zeros(n_points), rnd, np.full(n_points, M)])

        rnd = np.sort(rnd, axis=1)

        ret = np.full((n_points, n_dim), np.nan)
        for i in range(1, n_dim + 1):
            ret[:, i - 1] = rnd[:, i] - rnd[:, i - 1]
        ret /= M

    else:
        raise Exception("Invalid unit simplex mapping!")

    return ret 
Example 3
Project: tensortrade   Author: tensortrade-org   File: matplotlib_trading_chart.py    License: Apache License 2.0 6 votes vote down vote up
def _render_trades(self, step_range, trades):
        trades = [trade for sublist in trades.values() for trade in sublist]

        for trade in trades:
            if trade.step in range(sys.maxsize)[step_range]:
                date = self.df.index.values[trade.step]
                close = self.df['close'].values[trade.step]
                color = 'green'

                if trade.side is TradeSide.SELL:
                    color = 'red'

                self.price_ax.annotate(' ', (date, close),
                                       xytext=(date, close),
                                       size="large",
                                       arrowprops=dict(arrowstyle='simple', facecolor=color)) 
Example 4
Project: Advanced-Data-Structures-with-Python   Author: bhavinjawade   File: Dijsktra Algo.py    License: MIT License 6 votes vote down vote up
def dijkstra(self, src):
        dist = [sys.maxsize] * self.vert
        dist[src] = 0
        self.pathlist[0].append(src)
        sptSet = [False] * self.vert
        for cout in range(self.vert):
            u = self.findmindist(dist, sptSet)
            #if u == 225 :
            #  break
            sptSet[u] = True
            for v in range(self.vert):
                if self.graph[u][v] > 0 and sptSet[v] == False and dist[v] > dist[u] + self.graph[u][v]:
                        dist[v] = dist[u] + self.graph[u][v]
                        self.pathlist[v] = self.pathlist[u] + [v]
                        #print(dist,"Changing")
        #print("bhavin")
        self.printshortestgraph(dist) 
Example 5
Project: Advanced-Data-Structures-with-Python   Author: bhavinjawade   File: DijkstraShortestReach.py    License: MIT License 6 votes vote down vote up
def printshortestgraph(self, dist,src):
        f = open('somefile.txt', 'a')
        #print("Vertex tDistance from Source")
        for node in range(self.vert):
          if(node == src):
            continue
          if(node == self.vert - 1):
            if(dist[node] != sys.maxsize):
                print(dist[node],file = f)
            else:
                print(-1,file = f)
          elif(dist[node] != sys.maxsize):
            #print("From 0 to ", node ," - >",dist[node],end = " ")
            #print(self.pathlist[node])
            print(dist[node],end = ' ',file = f)
            #f.write(dist[node] + " ")
          elif(dist[node] == sys.maxsize):
            #print("From 0 to ", node ," - >",-1,end = " ")
            print(-1,end = ' ',file = f)
            #f.write(-1 + " ")
        #print('\n')
        #f.write("\n") 
Example 6
Project: Advanced-Data-Structures-with-Python   Author: bhavinjawade   File: DijkstraShortestReach.py    License: MIT License 6 votes vote down vote up
def dijkstra(self, src):
        dist = [sys.maxsize] * self.vert
        src = src - 1
        dist[src] = 0
        self.pathlist[0].append(src)
        sptSet = [False] * self.vert
        for cout in range(self.vert):
            u = self.findmindist(dist, sptSet)
            #if u == 225 :
            #  break
            sptSet[u] = True
            for v in range(self.vert):
                if self.graph[u][v] > 0 and sptSet[v] == False and dist[v] > dist[u] + self.graph[u][v]:
                        dist[v] = dist[u] + self.graph[u][v]
                        self.pathlist[v] = self.pathlist[u] + [v]
                        #print(dist,"Changing")
        #print("bhavin")
        self.printshortestgraph(dist,src) 
Example 7
Project: jawfish   Author: war-and-code   File: _sre.py    License: MIT License 6 votes vote down vote up
def findall(self, string, pos=0, endpos=sys.maxsize):
        """Return a list of all non-overlapping matches of pattern in string."""
        matchlist = []
        state = _State(string, pos, endpos, self.flags)
        while state.start <= state.end:
            state.reset()
            state.string_position = state.start
            if not state.search(self._code):
                break
            match = SRE_Match(self, state)
            if self.groups == 0 or self.groups == 1:
                item = match.group(self.groups)
            else:
                item = match.groups("")
            matchlist.append(item)
            if state.string_position == state.start:
                state.start += 1
            else:
                state.start = state.string_position
        return matchlist 
Example 8
Project: razzy-spinner   Author: rafasashi   File: generate.py    License: GNU General Public License v3.0 6 votes vote down vote up
def generate(grammar, start=None, depth=None, n=None):
    """
    Generates an iterator of all sentences from a CFG.

    :param grammar: The Grammar used to generate sentences.
    :param start: The Nonterminal from which to start generate sentences.
    :param depth: The maximal depth of the generated tree.
    :param n: The maximum number of sentences to return.
    :return: An iterator of lists of terminal tokens.
    """
    if not start:
        start = grammar.start()
    if depth is None:
        depth = sys.maxsize

    iter = _generate_all(grammar, [start], depth)

    if n:
        iter = itertools.islice(iter, n)

    return iter 
Example 9
Project: verge3d-blender-addon   Author: Soft8Soft   File: generator.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _make_boundary(cls, 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.maxsize)
        boundary = ('=' * 15) + (_fmt % token) + '=='
        if text is None:
            return boundary
        b = boundary
        counter = 0
        while True:
            cre = cls._compile_re('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
            if not cre.search(text):
                break
            b = boundary + '.' + str(counter)
            counter += 1
        return b 
Example 10
Project: H3DNet   Author: zaiweizhang   File: pc_util.py    License: MIT License 6 votes vote down vote up
def bbox_corner_dist_measure(crnr1, crnr2):
    """ compute distance between box corners to replace iou
    Args:
        crnr1, crnr2: Nx3 points of box corners in camera axis (y points down)
        output is a scalar between 0 and 1        
    """
    
    dist = sys.maxsize
    for y in range(4):
        rows = ([(x+y)%4 for x in range(4)] + [4+(x+y)%4 for x in range(4)])
        d_ = np.linalg.norm(crnr2[rows, :] - crnr1, axis=1).sum() / 8.0            
        if d_ < dist:
            dist = d_

    u = sum([np.linalg.norm(x[0,:] - x[6,:]) for x in [crnr1, crnr2]])/2.0

    measure = max(1.0 - dist/u, 0)
    print(measure)
    
    
    return measure 
Example 11
Project: uplink   Author: prkumar   File: ratelimit.py    License: MIT License 6 votes vote down vote up
def __init__(
        self,
        calls=15,
        period=900,
        raise_on_limit=False,
        group_by=BY_HOST_AND_PORT,
        clock=now,
    ):
        self._max_calls = max(1, min(sys.maxsize, math.floor(calls)))
        self._period = period
        self._clock = clock
        self._limiter_cache = {}
        self._group_by = utils.no_op if group_by is None else group_by

        if utils.is_subclass(raise_on_limit, Exception) or isinstance(
            raise_on_limit, Exception
        ):
            self._create_limit_reached_exception = raise_on_limit
        elif raise_on_limit:
            self._create_limit_reached_exception = (
                self._create_rate_limit_exceeded
            )
        else:
            self._create_limit_reached_exception = None 
Example 12
Project: misp42splunk   Author: remg427   File: generator.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def _make_boundary(cls, 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.maxsize)
        boundary = ('=' * 15) + (_fmt % token) + '=='
        if text is None:
            return boundary
        b = boundary
        counter = 0
        while True:
            cre = cls._compile_re('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
            if not cre.search(text):
                break
            b = boundary + '.' + str(counter)
            counter += 1
        return b 
Example 13
Project: misp42splunk   Author: remg427   File: generator.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def _make_boundary(cls, 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.maxsize)
        boundary = ('=' * 15) + (_fmt % token) + '=='
        if text is None:
            return boundary
        b = boundary
        counter = 0
        while True:
            cre = cls._compile_re('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
            if not cre.search(text):
                break
            b = boundary + '.' + str(counter)
            counter += 1
        return b 
Example 14
Project: plugin.video.kmediatorrent   Author: jmarth   File: platform.py    License: GNU General Public License v3.0 6 votes vote down vote up
def platform():
    ret = {
        "arch": sys.maxsize > 2**32 and "x64" or "x86",
    }

    if xbmc.getCondVisibility("system.platform.android"):
        ret["os"] = "android"
        if "arm" in os.uname()[4]:
            ret["arch"] = "arm"
    elif xbmc.getCondVisibility("system.platform.linux"):
        ret["os"] = "linux"
        if "arm" in os.uname()[4]:
            ret["arch"] = "arm"
    elif xbmc.getCondVisibility("system.platform.xbox"):
        system_platform = "xbox"
        ret["arch"] = ""
    elif xbmc.getCondVisibility("system.platform.windows"):
        ret["os"] = "windows"
    elif xbmc.getCondVisibility("system.platform.osx"):
        ret["os"] = "darwin"
    elif xbmc.getCondVisibility("system.platform.ios"):
        ret["os"] = "ios"
        ret["arch"] = "arm"

    return ret 
Example 15
Project: ratelimit   Author: tomasbasham   File: decorators.py    License: MIT License 6 votes vote down vote up
def __init__(self, calls=15, period=900, clock=now(), raise_on_limit=True):
        '''
        Instantiate a RateLimitDecorator with some sensible defaults. By
        default the Twitter rate limiting window is respected (15 calls every
        15 minutes).

        :param int calls: Maximum function invocations allowed within a time period.
        :param float period: An upper bound time period (in seconds) before the rate limit resets.
        :param function clock: An optional function retuning the current time.
        :param bool raise_on_limit: A boolean allowing the caller to avoiding rasing an exception.
        '''
        self.clamped_calls = max(1, min(sys.maxsize, floor(calls)))
        self.period = period
        self.clock = clock
        self.raise_on_limit = raise_on_limit

        # Initialise the decorator state.
        self.last_reset = clock()
        self.num_calls = 0

        # Add thread safety.
        self.lock = threading.RLock() 
Example 16
Project: linter-pylama   Author: AtomLinter   File: base.py    License: MIT License 6 votes vote down vote up
def leave_module(self, node): # pylint: disable=unused-argument
        for all_groups in six.itervalues(self._bad_names):
            if len(all_groups) < 2:
                continue
            groups = collections.defaultdict(list)
            min_warnings = sys.maxsize
            for group in six.itervalues(all_groups):
                groups[len(group)].append(group)
                min_warnings = min(len(group), min_warnings)
            if len(groups[min_warnings]) > 1:
                by_line = sorted(groups[min_warnings],
                                 key=lambda group: min(warning[0].lineno for warning in group))
                warnings = itertools.chain(*by_line[1:])
            else:
                warnings = groups[min_warnings][0]
            for args in warnings:
                self._raise_name_warning(*args) 
Example 17
Project: plugin.video.emby   Author: MediaBrowser   File: rrule.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __getitem__(self, item):
        if self._cache_complete:
            return self._cache[item]
        elif isinstance(item, slice):
            if item.step and item.step < 0:
                return list(iter(self))[item]
            else:
                return list(itertools.islice(self,
                                             item.start or 0,
                                             item.stop or sys.maxsize,
                                             item.step or 1))
        elif item >= 0:
            gen = iter(self)
            try:
                for i in range(item+1):
                    res = advance_iterator(gen)
            except StopIteration:
                raise IndexError
            return res
        else:
            return list(iter(self))[item] 
Example 18
Project: moler   Author: nokia   File: lsof.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _proper_position_value(self, header_index, value_position):
        ret = False
        if header_index < len(self._headers):
            current_header_pos = self._header_pos[header_index]
            if current_header_pos == value_position:
                ret = True
            else:
                prev_header_pos = -1
                if header_index > 0:
                    prev_header_pos = self._header_pos[header_index - 1]
                next_header_pos = sys.maxsize  # larger value than any column
                if header_index < len(self._headers) - 1:
                    next_header_pos = self._header_pos[header_index] + len(self._headers[header_index])
                if value_position > prev_header_pos and value_position < next_header_pos:
                    ret = True
        return ret 
Example 19
Project: indras_net   Author: gcallah   File: space.py    License: GNU General Public License v3.0 5 votes vote down vote up
def calc_heat(self, group, coord):
        heat_strength = 0
        for heat in group:
            distance = sqrt(
                ((coord[X] - group[heat].get_x()) ** 2)
                + ((coord[Y] - group[heat].get_y()) ** 2)
            )
            if distance != 0:
                heat_strength += 1 / ((distance) ** 2)
            else:
                heat_strength += sys.maxsize
        heat_strength *= -1
        return heat_strength 
Example 20
Project: indras_net   Author: gcallah   File: bacteria.py    License: GNU General Public License v3.0 5 votes vote down vote up
def calc_toxin(group, agent):
    """
    Calculate the strength of a toxin / nutrient field for an agent.
    We will use an inverse square law.
    """
    toxin_strength = 0
    for toxin in group:
        if distance(group[toxin], agent) != 0:
            toxin_strength += 1 / (distance(group[toxin], agent) ** 2)
        else:
            toxin_strength += sys.maxsize
    toxin_strength *= -1
    return toxin_strength 
Example 21
Project: indras_net   Author: gcallah   File: bacteria.py    License: GNU General Public License v3.0 5 votes vote down vote up
def calc_nutrient(group, agent):
    nutrient_strength = 0
    for nutrient in group:
        if distance(group[nutrient], agent) != 0:
            nutrient_strength += 1 / (distance(group[nutrient], agent) ** 2)
        else:
            nutrient_strength += sys.maxsize
    return nutrient_strength 
Example 22
Project: aegea   Author: kislyuk   File: pricing.py    License: Apache License 2.0 5 votes vote down vote up
def get_instance_type_sort_key(args):
    def instance_type_sort_key(row):
        instance_type = re.match(r"(.+)\.(\d*)(.+)", row[args.columns.index("instanceType")])
        family, mx, size = instance_type.groups() if instance_type else (0, 0, 0)
        if size == "metal":
            mx = sys.maxsize
        size_order = ["nano", "micro", "small", "medium", "large", "xlarge"]
        return family, int(mx) if mx else 1, size_order.index(size) if size in size_order else sys.maxsize
    return instance_type_sort_key 
Example 23
Project: multibootusb   Author: mbusb   File: gen.py    License: GNU General Public License v2.0 5 votes vote down vote up
def sys_64bits():
    """
    Detect if the host system is 64 bit.
    :return:    True if system is 64 bit.
    """
    return sys.maxsize > 2**32 
Example 24
Project: CAMISIM   Author: CAMI-challenge   File: fastaanonymizer.py    License: Apache License 2.0 5 votes vote down vote up
def _get_seed():
		return random.randint(0, sys.maxsize) 
Example 25
Project: CAMISIM   Author: CAMI-challenge   File: readsimulationwrapper.py    License: Apache License 2.0 5 votes vote down vote up
def _get_seed():
        return random.randint(0, sys.maxsize) 
Example 26
Project: CAMISIM   Author: CAMI-challenge   File: strainsimulationwrapper.py    License: Apache License 2.0 5 votes vote down vote up
def _get_seed():
		return random.randint(0, sys.maxsize) 
Example 27
Project: botbuilder-python   Author: microsoft   File: azure_bdist_wheel.py    License: MIT License 5 votes vote down vote up
def get_tag(self):
        # bdist sets self.plat_name if unset, we should only use it for purepy
        # wheels if the user supplied it.
        if self.plat_name_supplied:
            plat_name = self.plat_name
        elif self.root_is_pure:
            plat_name = "any"
        else:
            plat_name = self.plat_name or get_platform()
            if (
                plat_name in ("linux-x86_64", "linux_x86_64")
                and sys.maxsize == 2147483647
            ):
                plat_name = "linux_i686"
        plat_name = plat_name.replace("-", "_").replace(".", "_")

        if self.root_is_pure:
            if self.universal:
                impl = "py2.py3"
            else:
                impl = self.python_tag
            tag = (impl, "none", plat_name)
        else:
            impl_name = get_abbr_impl()
            impl_ver = get_impl_ver()
            # PEP 3149
            abi_tag = str(get_abi_tag()).lower()
            tag = (impl_name + impl_ver, abi_tag, plat_name)
            supported_tags = pep425tags.get_supported(
                supplied_platform=plat_name if self.plat_name_supplied else None
            )
            # XXX switch to this alternate implementation for non-pure:
            assert tag == supported_tags[0], "%s != %s" % (tag, supported_tags[0])
        return tag 
Example 28
Project: audio   Author: pytorch   File: utils.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def unicode_csv_reader(unicode_csv_data: TextIOWrapper, **kwargs: Any) -> Any:
    r"""Since the standard csv library does not handle unicode in Python 2, we need a wrapper.
    Borrowed and slightly modified from the Python docs:
    https://docs.python.org/2/library/csv.html#csv-examples
    Args:
        unicode_csv_data (TextIOWrapper): unicode csv data (see example below)

    Examples:
        >>> from torchaudio.datasets.utils import unicode_csv_reader
        >>> import io
        >>> with io.open(data_path, encoding="utf8") as f:
        >>>     reader = unicode_csv_reader(f)
    """

    # Fix field larger than field limit error
    maxInt = sys.maxsize
    while True:
        # decrease the maxInt value by factor 10
        # as long as the OverflowError occurs.
        try:
            csv.field_size_limit(maxInt)
            break
        except OverflowError:
            maxInt = int(maxInt / 10)
    csv.field_size_limit(maxInt)

    for line in csv.reader(unicode_csv_data, **kwargs):
        yield line 
Example 29
Project: audio   Author: pytorch   File: utils.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, generator: Iterable, maxsize: int) -> None:
        threading.Thread.__init__(self)
        self.queue: Queue = Queue(maxsize)
        self.generator = generator
        self.daemon = True
        self.start() 
Example 30
Project: audio   Author: pytorch   File: utils.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def bg_iterator(iterable: Iterable, maxsize: int) -> Any:
    return _ThreadedIterator(iterable, maxsize=maxsize)