Python bisect.bisect_right() Examples

The following are 30 code examples of bisect.bisect_right(). 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 also want to check out all available functions/classes of the module bisect , or try the search function .
Example #1
Source File: sortedlist.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def bisect_right(self, value):
        """Return an index to insert `value` in the sorted-key list.

        Similar to `bisect_left`, but if `value` is already present, the
        insertion point with be after (to the right of) any existing values.

        Similar to the `bisect` module in the standard library.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> from operator import neg
        >>> skl = SortedList([5, 4, 3, 2, 1], key=neg)
        >>> skl.bisect_right(1)
        5

        :param value: insertion index of value in sorted-key list
        :return: index

        """
        return self._bisect_key_right(self._key(value)) 
Example #2
Source File: source.py    From py with MIT License 6 votes vote down vote up
def get_statement_startend2(lineno, node):
    import ast
    # flatten all statements and except handlers into one lineno-list
    # AST's line numbers start indexing at 1
    l = []
    for x in ast.walk(node):
        if isinstance(x, _ast.stmt) or isinstance(x, _ast.ExceptHandler):
            l.append(x.lineno - 1)
            for name in "finalbody", "orelse":
                val = getattr(x, name, None)
                if val:
                    # treat the finally/orelse part as its own statement
                    l.append(val[0].lineno - 1 - 1)
    l.sort()
    insert_index = bisect_right(l, lineno)
    start = l[insert_index - 1]
    if insert_index >= len(l):
        end = None
    else:
        end = l[insert_index]
    return start, end 
Example #3
Source File: sortedlist.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def bisect_right(self, value):
        """Return an index to insert `value` in the sorted-key list.

        Similar to `bisect_left`, but if `value` is already present, the
        insertion point with be after (to the right of) any existing values.

        Similar to the `bisect` module in the standard library.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> from operator import neg
        >>> skl = SortedList([5, 4, 3, 2, 1], key=neg)
        >>> skl.bisect_right(1)
        5

        :param value: insertion index of value in sorted-key list
        :return: index

        """
        return self._bisect_key_right(self._key(value)) 
Example #4
Source File: size_detector.py    From gaps with MIT License 6 votes vote down vote up
def _find_nearest_size(self, size_candidate):
        index = bisect.bisect_right(self._possible_sizes, size_candidate)

        if index == 0:
            return self._possible_sizes[0]

        if index >= len(self._possible_sizes):
            return self._possible_sizes[-1]

        right_size = self._possible_sizes[index]
        left_size = self._possible_sizes[index - 1]

        if abs(size_candidate - right_size) < abs(size_candidate - left_size):
            return right_size
        else:
            return left_size 
Example #5
Source File: events.py    From mars with Apache License 2.0 6 votes vote down vote up
def query_by_time(self, category, time_start=None, time_end=None):
        self._purge_old_events(category)

        class ItemWrapper(object):
            def __init__(self, tl):
                self._l = tl

            def __getitem__(self, item):
                return self._l[item][0]

            def __len__(self):
                return len(self._l)

        timeline = self._event_timelines[category]
        left_pos = 0 if time_start is None \
            else bisect.bisect_left(ItemWrapper(timeline), time_start)
        right_pos = len(timeline) if time_end is None \
            else bisect.bisect_right(ItemWrapper(timeline), time_end)
        return [it[1] for it in itertools.islice(timeline, left_pos, right_pos)] 
Example #6
Source File: source.py    From python-netsurv with MIT License 6 votes vote down vote up
def get_statement_startend2(lineno, node):
    import ast
    # flatten all statements and except handlers into one lineno-list
    # AST's line numbers start indexing at 1
    l = []
    for x in ast.walk(node):
        if isinstance(x, _ast.stmt) or isinstance(x, _ast.ExceptHandler):
            l.append(x.lineno - 1)
            for name in "finalbody", "orelse":
                val = getattr(x, name, None)
                if val:
                    # treat the finally/orelse part as its own statement
                    l.append(val[0].lineno - 1 - 1)
    l.sort()
    insert_index = bisect_right(l, lineno)
    start = l[insert_index - 1]
    if insert_index >= len(l):
        end = None
    else:
        end = l[insert_index]
    return start, end 
Example #7
Source File: source.py    From python-netsurv with MIT License 6 votes vote down vote up
def get_statement_startend2(lineno, node):
    import ast

    # flatten all statements and except handlers into one lineno-list
    # AST's line numbers start indexing at 1
    values = []
    for x in ast.walk(node):
        if isinstance(x, (ast.stmt, ast.ExceptHandler)):
            values.append(x.lineno - 1)
            for name in ("finalbody", "orelse"):
                val = getattr(x, name, None)
                if val:
                    # treat the finally/orelse part as its own statement
                    values.append(val[0].lineno - 1 - 1)
    values.sort()
    insert_index = bisect_right(values, lineno)
    start = values[insert_index - 1]
    if insert_index >= len(values):
        end = None
    else:
        end = values[insert_index]
    return start, end 
Example #8
Source File: sortedlist.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def bisect_right(self, value):
        """Return an index to insert `value` in the sorted-key list.

        Similar to `bisect_left`, but if `value` is already present, the
        insertion point with be after (to the right of) any existing values.

        Similar to the `bisect` module in the standard library.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> from operator import neg
        >>> skl = SortedList([5, 4, 3, 2, 1], key=neg)
        >>> skl.bisect_right(1)
        5

        :param value: insertion index of value in sorted-key list
        :return: index

        """
        return self._bisect_key_right(self._key(value)) 
Example #9
Source File: source.py    From python-netsurv with MIT License 6 votes vote down vote up
def get_statement_startend2(lineno, node):
    import ast
    # flatten all statements and except handlers into one lineno-list
    # AST's line numbers start indexing at 1
    l = []
    for x in ast.walk(node):
        if isinstance(x, _ast.stmt) or isinstance(x, _ast.ExceptHandler):
            l.append(x.lineno - 1)
            for name in "finalbody", "orelse":
                val = getattr(x, name, None)
                if val:
                    # treat the finally/orelse part as its own statement
                    l.append(val[0].lineno - 1 - 1)
    l.sort()
    insert_index = bisect_right(l, lineno)
    start = l[insert_index - 1]
    if insert_index >= len(l):
        end = None
    else:
        end = l[insert_index]
    return start, end 
Example #10
Source File: sortedlist.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def bisect_right(self, value):
        """Return an index to insert `value` in the sorted-key list.

        Similar to `bisect_left`, but if `value` is already present, the
        insertion point with be after (to the right of) any existing values.

        Similar to the `bisect` module in the standard library.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> from operator import neg
        >>> skl = SortedList([5, 4, 3, 2, 1], key=neg)
        >>> skl.bisect_right(1)
        5

        :param value: insertion index of value in sorted-key list
        :return: index

        """
        return self._bisect_key_right(self._key(value)) 
Example #11
Source File: eval_util.py    From tsinfer with GNU General Public License v3.0 6 votes vote down vote up
def get_ancestral_haplotypes(ts):
    """
    Returns a numpy array of the haplotypes of the ancestors in the
    specified tree sequence.
    """
    tables = ts.dump_tables()
    nodes = tables.nodes
    flags = nodes.flags[:]
    flags[:] = 1
    nodes.set_columns(time=nodes.time, flags=flags)

    sites = tables.sites.position
    tsp = tables.tree_sequence()
    B = tsp.genotype_matrix().T

    A = np.full((ts.num_nodes, ts.num_sites), tskit.MISSING_DATA, dtype=np.int8)
    for edge in ts.edges():
        start = bisect.bisect_left(sites, edge.left)
        end = bisect.bisect_right(sites, edge.right)
        if sites[end - 1] == edge.right:
            end -= 1
        A[edge.parent, start:end] = B[edge.parent, start:end]
    A[: ts.num_samples] = B[: ts.num_samples]
    return A 
Example #12
Source File: tasks.py    From aumfor with GNU General Public License v3.0 6 votes vote down vote up
def find_module(modlist, mod_addrs, addr):
    """Uses binary search to find what module a given address resides in.

    This is much faster than a series of linear checks if you have
    to do it many times. Note that modlist and mod_addrs must be sorted
    in order of the module base address.
    
    NOTE: the mod_addrs and addr parameters must already be masked for 
    the address space"""

    pos = bisect_right(mod_addrs, addr) - 1
    if pos == -1:
        return None
    mod = modlist[mod_addrs[pos]]

    if (mod.obj_vm.address_compare(addr, mod.DllBase) != -1 and
            mod.obj_vm.address_compare(addr, mod.DllBase + mod.SizeOfImage) == -1):
        return mod
    else:
        return None 
Example #13
Source File: linux_strings.py    From aumfor with GNU General Public License v3.0 6 votes vote down vote up
def find_module(cls, modlist, mod_addrs, addr_space, vpage):
        """Determine which module owns a virtual page. 

        :param      modlist     | <list>
                    mod_addrs   | <list>
                    addr_space  | <addrspace.AbstractVirtualAddressSpace>
                    vpage       | <int> 
        
        :returns    <module> || None
        """

        pos = bisect_right(mod_addrs, vpage) - 1
        if pos == -1:
            return None
        mod = modlist[mod_addrs[pos]]

        compare = mod.obj_vm.address_compare
        if (compare(vpage, mod.module_core) != -1 and
                compare(vpage, mod.module_core + mod.core_size) == -1):
            return mod
        else:
            return None 
Example #14
Source File: mac_strings.py    From aumfor with GNU General Public License v3.0 6 votes vote down vote up
def find_module(cls, modlist, mod_addrs, addr_space, vpage):
        """Determine which module owns a virtual page. 

        :param      modlist     | <list>
                    mod_addrs   | <list>
                    addr_space  | <addrspace.AbstractVirtualAddressSpace>
                    vpage       | <int> 
        
        :returns    <module> || None
        """

        pos = bisect_right(mod_addrs, vpage) - 1
        if pos == -1:
            return None
        mod = modlist[mod_addrs[pos]]

        compare = mod.obj_vm.address_compare
        if (compare(vpage, mod.address) != -1 and
                compare(vpage, mod.address + mod.m('size')) == -1):
            return mod
        else:
            return None 
Example #15
Source File: source.py    From python-netsurv with MIT License 6 votes vote down vote up
def get_statement_startend2(lineno, node):
    import ast

    # flatten all statements and except handlers into one lineno-list
    # AST's line numbers start indexing at 1
    values = []
    for x in ast.walk(node):
        if isinstance(x, (ast.stmt, ast.ExceptHandler)):
            values.append(x.lineno - 1)
            for name in ("finalbody", "orelse"):
                val = getattr(x, name, None)
                if val:
                    # treat the finally/orelse part as its own statement
                    values.append(val[0].lineno - 1 - 1)
    values.sort()
    insert_index = bisect_right(values, lineno)
    start = values[insert_index - 1]
    if insert_index >= len(values):
        end = None
    else:
        end = values[insert_index]
    return start, end 
Example #16
Source File: result_ranker.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def Add(self, score):
    """Add a score into the last N scores.

    If needed, drops the score that is furthest away from the given score.
    """
    num_sampled_scores = len(self.scores)
    if num_sampled_scores < self.MAX_NUM_SAMPLED_SCORES:
      bisect.insort(self.scores, score)
    else:
      index_left = bisect.bisect_left(self.scores, score)
      index_right = bisect.bisect_right(self.scores, score)
      index_center = index_left + (index_right - index_left) / 2
      self.scores.insert(index_left, score)
      if index_center < num_sampled_scores / 2:
        self.scores.pop()
      else:
        self.scores.pop(0)
    self.num_scores += 1
    RankerCacher.CachePut(self) 
Example #17
Source File: local_scores.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def Add(self, score):
    """Add a score into the last N scores.

    If needed, drops the score that is furthest away from the given score.
    """
    num_sampled_scores = len(self.scores)
    if num_sampled_scores < self.MAX_NUM_SAMPLED_SCORES:
      bisect.insort(self.scores, score)
    else:
      index_left = bisect.bisect_left(self.scores, score)
      index_right = bisect.bisect_right(self.scores, score)
      index_center = index_left + (index_right - index_left) / 2
      self.scores.insert(index_left, score)
      if index_center < num_sampled_scores / 2:
        self.scores.pop()
      else:
        self.scores.pop(0)
    self.num_scores += 1 
Example #18
Source File: fullmoon.py    From Watson with MIT License 6 votes vote down vote up
def get_last_full_moon(d):
    """
    Returns the last full moon for d

    Raises ValueError if the d value is not between 2000 - 2099
    """

    now = d.timestamp
    idx = bisect.bisect_right(fullmoons, now)
    if idx in [0, len(fullmoons)]:
        raise ValueError(
            u'watson has only full moon dates from year 2000 to 2099, not {}'
            .format(d.year))

    last = fullmoons[idx - 1]
    return arrow.get(last) 
Example #19
Source File: dataset_wrappers.py    From mmdetection with Apache License 2.0 6 votes vote down vote up
def get_cat_ids(self, idx):
        """Get category ids of concatenated dataset by index.

        Args:
            idx (int): Index of data.

        Returns:
            list[int]: All categories in the image of specified index.
        """

        if idx < 0:
            if -idx > len(self):
                raise ValueError(
                    'absolute value of index should not exceed dataset length')
            idx = len(self) + idx
        dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx)
        if dataset_idx == 0:
            sample_idx = idx
        else:
            sample_idx = idx - self.cumulative_sizes[dataset_idx - 1]
        return self.datasets[dataset_idx].get_cat_ids(sample_idx) 
Example #20
Source File: util.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def iterate_from(self, start_tok):
        piecenum = bisect.bisect_right(self._offsets, start_tok)-1

        while piecenum < len(self._pieces):
            offset = self._offsets[piecenum]
            piece = self._pieces[piecenum]

            # If we've got another piece open, close it first.
            if self._open_piece is not piece:
                if self._open_piece is not None:
                    self._open_piece.close()
                self._open_piece = piece

            # Get everything we can from this piece.
            for tok in piece.iterate_from(max(0, start_tok-offset)):
                yield tok

            # Update the offset table.
            if piecenum+1 == len(self._offsets):
                self._offsets.append(self._offsets[-1] + len(piece))

            # Move on to the next piece.
            piecenum += 1 
Example #21
Source File: tzinfo.py    From script.tvguide.fullscreen with GNU General Public License v2.0 5 votes vote down vote up
def fromutc(self, dt):
        '''See datetime.tzinfo.fromutc'''
        if (dt.tzinfo is not None
            and getattr(dt.tzinfo, '_tzinfos', None) is not self._tzinfos):
            raise ValueError('fromutc: dt.tzinfo is not self')
        dt = dt.replace(tzinfo=None)
        idx = max(0, bisect_right(self._utc_transition_times, dt) - 1)
        inf = self._transition_info[idx]
        return (dt + inf[0]).replace(tzinfo=self._tzinfos[inf]) 
Example #22
Source File: concat_dataset.py    From fairseq with MIT License 5 votes vote down vote up
def attr(self, attr: str, index: int):
        dataset_idx = bisect.bisect_right(self.cumulative_sizes, index)
        return getattr(self.datasets[dataset_idx], attr, None) 
Example #23
Source File: tzinfo.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def fromutc(self, dt):
        '''See datetime.tzinfo.fromutc'''
        if (dt.tzinfo is not None
            and getattr(dt.tzinfo, '_tzinfos', None) is not self._tzinfos):
            raise ValueError('fromutc: dt.tzinfo is not self')
        dt = dt.replace(tzinfo=None)
        idx = max(0, bisect_right(self._utc_transition_times, dt) - 1)
        inf = self._transition_info[idx]
        return (dt + inf[0]).replace(tzinfo=self._tzinfos[inf]) 
Example #24
Source File: dimension.py    From LSDMappingTools with MIT License 5 votes vote down vote up
def calculate_preferred(self, value, units):
        if units not in self._units:
            raise ValueError('Unknown units: %s' % units)
        base_value = value * self._units[units]

        units_factor = sorted(self._units.items(), key=itemgetter(1))
        factors = [item[1] for item in units_factor]
        index = bisect.bisect_right(factors, base_value)
        newunits, factor = units_factor[index - 1]

        return base_value / factor, newunits 
Example #25
Source File: lr_scheduler.py    From SegmenTron with Apache License 2.0 5 votes vote down vote up
def get_lr(self) -> List[float]:
        warmup_factor = _get_warmup_factor_at_iter(
            self.warmup_method, self.last_epoch, self.warmup_iters, self.warmup_factor
        )
        return [
            base_lr * warmup_factor * self.gamma ** bisect_right(self.milestones, self.last_epoch)
            for base_lr in self.base_lrs
        ] 
Example #26
Source File: tz.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _find_last_transition(self, dt, in_utc=False):
        # If there's no list, there are no transitions to find
        if not self._trans_list:
            return None

        timestamp = _datetime_to_timestamp(dt)

        # Find where the timestamp fits in the transition list - if the
        # timestamp is a transition time, it's part of the "after" period.
        trans_list = self._trans_list_utc if in_utc else self._trans_list
        idx = bisect.bisect_right(trans_list, timestamp)

        # We want to know when the previous transition was, so subtract off 1
        return idx - 1 
Example #27
Source File: thief.py    From discord_cogs with GNU General Public License v3.0 5 votes vote down vote up
def criminal_level(level):
        status = ["Greenhorn", "Renegade", "Veteran", "Commander", "War Chief", "Legend",
                  "Immortal"]
        breakpoints = [1, 10, 25, 50, 75, 100]
        return status[bisect.bisect_right(breakpoints, level)] 
Example #28
Source File: dataset.py    From EMANet with GNU General Public License v3.0 5 votes vote down vote up
def __getitem__(self, idx):
        dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx)
        if dataset_idx == 0:
            sample_idx = idx
        else:
            sample_idx = idx - self.cumulative_sizes[dataset_idx - 1]
        return self.datasets[dataset_idx][sample_idx] 
Example #29
Source File: tzinfo.py    From recruit with Apache License 2.0 5 votes vote down vote up
def fromutc(self, dt):
        '''See datetime.tzinfo.fromutc'''
        if (dt.tzinfo is not None and
                getattr(dt.tzinfo, '_tzinfos', None) is not self._tzinfos):
            raise ValueError('fromutc: dt.tzinfo is not self')
        dt = dt.replace(tzinfo=None)
        idx = max(0, bisect_right(self._utc_transition_times, dt) - 1)
        inf = self._transition_info[idx]
        return (dt + inf[0]).replace(tzinfo=self._tzinfos[inf]) 
Example #30
Source File: build.py    From R2CNN.pytorch with MIT License 5 votes vote down vote up
def _quantize(x, bins):
    bins = copy.copy(bins)
    bins = sorted(bins)
    quantized = list(map(lambda y: bisect.bisect_right(bins, y), x))
    return quantized