예제 #1
0
 def addChildren(self, *kids):
     """
     adds ScopeMatcher(s) to the list of children,
     keeping it sorted.
     """
     for k in kids:
         insort_right(self._children, k)
예제 #2
0
 def addChildren(self, *kids):
     """
     adds ScopeMatcher(s) to the list of children,
     keeping it sorted.
     """
     for k in kids:
         insort_right(self._children, k)
예제 #3
0
 def addSorted(self, item):
     """
     Insert item into the items, keeping sort
     """
     bisect.insort_right(self.items, item)
     if self.items.index(item) < self.rotation:
         self.rotation = self.rotation + 1
예제 #4
0
 def handle_event(self, ts):
     rawline = self.f.readline()
     if rawline == '':  # empty read
         return False # remove from loop => exit
     self.in_dbg_log.write(rawline)
     self.in_dbg_log.flush()
     rawline = rawline.strip()
     words = rawline.split()
     if len(words) == 0:
         return
     first = words[0]
     if not self.started:
         if first == 'LOGSTART':
             self.started = True
     else:
         if first == 'LOGDEF':
             prefix = words[2]
             logdef = (prefix, dict(
                 stream = words[1],
                 sep = words[3],
                 formatting = ' '.join(words[4:])))
             insort_right(self.logdefs, logdef)
         elif first == 'LOGVAR':
             self.logvars[words[1]] = words[2]
         elif len(self.logdefs) > 0:
             # adding a char ('*') ensures that i will point
             # after the matching prefix, even if (rawline == prefix)
             i = bisect_right(self.logdefs, (rawline + '*',))
             if i > 0 and rawline.startswith(self.logdefs[i-1][0]):
                 d = self.logdefs[i-1][1]
                 self.forward_log(ts=ts, rawline=rawline, **d)
예제 #5
0
파일: eventManager.py 프로젝트: colshag/ANW
def postEvent(gid, action, delay, args):
    """Post an event to be processed. insert in sorted order
    """
    event = GameEvent(gid, action, gEventTimer + delay, args)
    insort_right(gEvents, event)
    #print gid, action
    return event
예제 #6
0
 def reversePairs(self, nums: List[int]) -> int:
     arr = []
     res = 0
     for num in nums:
         res += len(arr) - bisect.bisect_right(arr, num * 2)
         bisect.insort_right(arr, num)
     return res
예제 #7
0
def minimum_loss(n, ar):
    minimum = ar[0]
    maximum = ar[0]
    min_diff = None
    seen = [maximum]

    for i in range(1, n):
        item = ar[i]
        if item < minimum:
            diff = minimum - item
            minimum = item
            if min_diff is None or diff < min_diff:
                min_diff = diff
        elif item > maximum:
            maximum = item
        elif minimum < item < maximum:
            position = bisect.bisect_right(seen, item)
            bisect.insort_right(seen, item)
            diff = seen[position + 1] - item
            if min_diff is None or diff < min_diff:
                min_diff = diff
            continue
        bisect.insort(seen, item)

    return min_diff
예제 #8
0
def dijkstra_search(gr: Graph, v_start: int) -> list:
    """
    Find the SHORTEST paths from 'v_start' to all vertices in the given 'graph'
    :param gr: a graph to examine
    :param v_start: a vertex index to start search from
    :return: a list of path lengths. The vertices' layout is the same as in the original 'graph'

    The implicit assumption of this algorithm is that the graph is acyclic
    """
    paths = [None for _ in range(gr.h * gr.w)]
    paths[v_start] = 0

    examine_list = [
        (0, v_start),
    ]

    while len(examine_list) > 0:
        _, v_curr = examine_list.pop(0)
        dist_curr = paths[v_curr]
        for v_next in gr.g[v_curr].adj:
            if paths[v_next.i] is None:
                paths[v_next.i] = dist_curr + v_next.d
            else:
                paths[v_next.i] = min(paths[v_next.i], dist_curr + v_next.d)
            bisect.insort_right(examine_list, (dist_curr + v_next.d, v_next.i))

    return paths
예제 #9
0
    def proc_file_event(self, event, filename):
        """Handles the file events.

        Used as a callback registered on the file tracker. This method will link newly created 
        files and remove deleted files.
        
        Args:
            event (MilkProcFileTracker.Event): The event type that occured.
            filename (str): Filename of the file that triggered the event.

        """
        if event == MilkProcFileTracker.Event.FILE_CREATED:
            self.log.info("File created event received by {}. File: {}".format(repr(self), filename))
            if filename not in self.process_info:
                try:
                    info = KrakenProcessInfo(filename)
                    self.process_info[filename] = info
                    # Insert the key into the sorted list
                    bisect.insort_right(self.process_info_keys, filename)
                    self.log.debug("Created new KrakenProcessInfo for {}.".format(filename))
                except ValueError as error:
                    self.log.exception("Failed to create new KrakenProcessInfo for {}. {}.".format(filename, error))
                
        elif event == MilkProcFileTracker.Event.FILE_DELETED:
            self.log.info("File deleted event received by {}. File: {}".format(repr(self), filename))
            if filename in self.process_info:
                del self.process_info[filename]
                self.process_info_keys.remove(filename)
                self.log.debug("Removed KrakenProcessInfo for {}.".format(filename))
예제 #10
0
파일: structure.py 프로젝트: ws0406/python
def use_bisect_2(): # 耗时 0.001062596042174846
    '''对use_bisect_1的优化,不在原列表中操作,在新列表中做插入操作'''
    ran_list = [96, 14, 86, 13, 91, 94, 10, 50, 86, 76, 57, 11, 26, 15, 20, 45, 15, 
    81, 88, 41, 41, 87, 22, 44, 29, 11, 27, 75, 56, 38]*10
    new_list = []
    for i in range(0, len(ran_list)):
        bisect.insort_right(new_list, ran_list[i])   
예제 #11
0
    def external_links(self) -> List['ExternalLink']:
        """Return a list of found external link objects.

        Note:
            Templates adjacent to external links are considered part of the
            link. In reality, this depends on the contents of the template:

            >>> WikiText(
            ...    'http://example.com{{dead link}}'
            ...).external_links[0].url
            'http://example.com{{dead link}}'

            >>> WikiText(
            ...    '[http://example.com{{space template}} text]'
            ...).external_links[0].url
            'http://example.com{{space template}}'
        """
        external_links = []  # type: List['ExternalLink']
        external_links_append = external_links.append
        type_to_spans = self._type_to_spans
        lststr = self._lststr
        ss, se = self._span
        spans = type_to_spans.setdefault('ExternalLink', [])
        span_tuple_to_span_get = {(s[0], s[1]): s for s in spans}.get
        for m in EXTERNAL_LINK_FINDITER(self._ext_link_shadow):
            s, e = m.span()
            span = s, e = [s + ss, e + ss]
            old_span = span_tuple_to_span_get((s, e))
            if old_span is None:
                insort_right(spans, span)
            else:
                span = old_span
            external_links_append(
                ExternalLink(lststr, type_to_spans, span, 'ExternalLink'))
        return external_links
예제 #12
0
 def handle_event(self, ts):
     rawline = self.f.readline()
     if rawline == '':  # empty read
         return False # remove from loop => exit
     self.in_dbg_log.write(rawline)
     self.in_dbg_log.flush()
     rawline = rawline.strip()
     words = rawline.split()
     if len(words) == 0:
         return
     first = words[0]
     if not self.started:
         if first == 'LOGSTART':
             self.started = True
     else:
         if first == 'LOGDEF':
             prefix = words[2]
             logdef = (prefix, dict(
                 stream = words[1],
                 sep = words[3],
                 formatting = ' '.join(words[4:])))
             insort_right(self.logdefs, logdef)
         elif first == 'LOGVAR':
             self.logvars[words[1]] = words[2]
         elif len(self.logdefs) > 0:
             # adding a char ('*') ensures that i will point
             # after the matching prefix, even if (rawline == prefix)
             i = bisect_right(self.logdefs, (rawline + '*',))
             if i > 0 and rawline.startswith(self.logdefs[i-1][0]):
                 d = self.logdefs[i-1][1]
                 self.forward_log(ts=ts, rawline=rawline, **d)
예제 #13
0
 def right(self, deprel):
     """(σ|i|j, β, A) ⇒ (σ|i, B, A ∪ {(i, l, j)})"""
     j = self.stack.pop()
     i = self.stack[-1]
     insort_right(self.graph[i], j)
     # i -deprel-> j
     self.deprel[j] = deprel
예제 #14
0
    def add(self, location: Location) -> None:
        content_id, location_id = location
        content_distance = compute_distance(self.center_id, content_id)

        index: List[SortableNodeID]
        try:
            index = self._indices[content_id]
        except KeyError:
            index = []
            self._indices[content_id] = index
            bisect.insort_right(
                self._indices_by_distance,
                SortableNodeID(content_id, content_distance),
            )

        location_distance = compute_distance(self.center_id, location_id)

        index_value = SortableNodeID(location_id, location_distance)
        index_location = bisect.bisect_left(index, index_value)

        # Check if the value is already in the index, if so, we can return
        # early.
        try:
            if index[index_location] == index_value:
                return
        except IndexError:
            pass

        bisect.insort_right(index, index_value)

        self.capacity -= 1
        self._enforce_capacity()
예제 #15
0
    def refresh_item_by_oss(self, list_item_config):
        res = 1

        try:
            for _group in self.groups_sorted:
                _group.item_list = []

            for dict_config in list_item_config:
                _group_id, _shop_id, _item_type, _item_id, _item_num, _description, _orig_credits, _credits, _limit = \
                        int(dict_config['GroupID']), int(dict_config['ID']), int(dict_config['ItemType']), int(dict_config['ItemID']), \
                        int(dict_config['Count']), dict_config['Information'], int(dict_config['OriginalPrice']), \
                        int(dict_config['CurrentPrice']), int(dict_config['LimitNum'])

                for _group in self.groups_sorted:
                    if _group.group_id == _group_id:
                        _group.append_item(_shop_id, _item_type, _item_id, _item_num, _description, _orig_credits, _credits, _limit)
                        break
                else:
                    _now = int(time())
                    _begin_t, _end_t = _now, _now
                    _group = ItemGroup(_group_id, _begin_t, _end_t)
                    _group.append_item(_shop_id, _item_type, _item_id, _item_num, _description, _orig_credits, _credits, _limit)

                    insort_right(self.groups_sorted, _group)
                    redis.lpush(LIST_TIME_LIMITED_GROUP, dumps((_group_id, _begin_t, _end_t)))

            self.sync()
        except:
            log.exception('list_item_config:{0}'.format(list_item_config))
            res = OSS_TIME_LIMITED_SHOP_GROUP_EXCEPTION

        return res
 def mincostToHireWorkers(self, quality, wage, K):
     """
     :type quality: List[int]
     :type wage: List[int]
     :type K: int
     :rtype: float
     """
     n = len(quality)
     rate = list(map(lambda x, y, z: (y / x, z, x), quality, wage,
                     range(n)))
     rate.sort()
     print(rate)
     r = 10**9
     rr = []
     start = K - 1
     smallest = []
     for i in range(K - 1):
         smallest.append(rate[i][2])
     smallest.sort()
     # print(smallest)
     while start < n:
         ls = smallest[:K - 1:]
         cur = rate[start][2]
         print("r============", rate[start][0], rate[start][2], ls, sum(ls))
         all_sum = rate[start][0] * sum(
             ls) + rate[start][0] * rate[start][2]
         ls.append(cur)
         rr.append(ls)
         print("all_sum", all_sum)
         r = all_sum if all_sum < r else r
         bisect.insort_right(smallest, cur)
         print("sm", smallest, rate[start][2])
         start += 1
     print(rr)
     return round(r, 5)
예제 #17
0
def parse_runner_book(book):
    back_levels = []
    lay_levels = []
    order_book = {'batb': [], 'batl': []}
    for level in book:
        for side, order in level.items():
            if order:
                side = price_side_map.get(side)
                if side == 'back':
                    bisect.insort(back_levels, floatify(order.get('Price')))
                    order_book['batb'].append([
                        floatify(order.get('Price')),
                        floatify(order.get('Stake'))
                    ])
                elif side == 'lay':
                    bisect.insort_right(lay_levels,
                                        floatify(order.get('Price')))
                    order_book['batl'].append([
                        floatify(order.get('Price')),
                        floatify(order.get('Stake'))
                    ])
    back_levels.reverse()
    order_book['batb'] = [[back_levels.index(x[0]), x[0], x[1]]
                          for x in order_book['batb']]
    order_book['batl'] = [[lay_levels.index(x[0]), x[0], x[1]]
                          for x in order_book['batl']]
    return order_book
예제 #18
0
    def add(self, delay):
        """Add a delay to the list.

        :param Delay delay:
            The delay to add.
        """
        bisect.insort_right(self, delay)
예제 #19
0
 def ping_callback(self, address, result):
     # Pessimistic: Fail if any ping failed
     # status = bool(len(result) == len([r for r in result if r is not None]))
     # Optimistic: Fail if all pings failed
     status = len([r for r in result if r is not None]) > 0
     if address in self.running_pings:
         # Return to schedule
         self.running_pings.remove(address)
         bisect.insort_right(self.ping_time,
                             (self.get_next_ping_time(address), address))
     old_status = self.object_status.get(address)
     if old_status is False and status is True:
         # Reset failures count
         self.ping_failures[address] = 0
     elif old_status is True and status is False:
         # Check failure threshold
         self.ping_failures[address] += 1
         if self.ping_failures[address] < self.ping_failure_threshold:
             status = True  # Failure confirmation needed
     self.debug("PING %s: Result %s [%s -> %s]" %
                (address, result, old_status, status))
     if status != old_status:
         # Status changed
         self.object_status[address] = status
         self.queue_status_change(address, status)
예제 #20
0
파일: caching.py 프로젝트: CaptainAL/Spyder
 def add_partition(self, key, group):
     """Add sharding information for a group"""
     if self.shard_type == 'RANGE':
         key = int(key)
     elif self.shard_type == 'RANGE_DATETIME':
         try:
             if ':' in key:
                 key = datetime.strptime(key, "%Y-%m-%d %H:%M:%S")
             else:
                 key = datetime.strptime(key, "%Y-%m-%d").date()
         except:
             raise ValueError(
                 "RANGE_DATETIME key could not be parsed, was: {0}".format(
                     key
                 ))
     elif self.shard_type == 'RANGE_STRING':
         pass
     elif self.shard_type == "HASH":
         pass
     else:
         raise ValueError("Unsupported sharding type {0}".format(
             self.shard_type
         ))
     self.partitioning[key] = {
         'group': group,
     }
     self.reset_ttl()
     bisect.insort_right(self.keys, key)
     insort_right_rev(self.keys_reversed, key)
예제 #21
0
    def enqueue(self, key: TKey, queue_at: float = None) -> None:
        if queue_at is None:
            queue_at = time.monotonic()

        if key in self._key_queue_times:
            current_queue_at = self._key_queue_times[key]
            if current_queue_at <= queue_at:
                # The item currently in the queue is queued to come up sooner
                # than this one so discard it
                return
            else:
                # The item in the queue is older than this one so evict the
                # current one to be replaced by this one.
                self._key_queue_times.pop(key)
                current_queue_index = bisect.bisect_left(
                    self._queue,
                    QueueItem(key, current_queue_at),
                )
                current_queue_item = self._queue[current_queue_index]
                self._queue.remove(current_queue_item)
                if current_queue_item.key != key:
                    raise Exception("Invariant")

        bisect.insort_right(self._queue, QueueItem(key, queue_at))
        self._key_queue_times[key] = queue_at
        self._has_content.set()
        self._queue_changed.set()
        self._queue_changed = trio.Event()
예제 #22
0
 def __schedule(self, job, dateTime, interval):
     if self.__nextCall is not None:
         self.__nextCall.cancel()
         self.__nextCall = None
     bisect.insort_right(self.__jobs, (dateTime, job, interval))
     if not self.__firing:
         self.__fire()
예제 #23
0
 def _files_mapping(self):
     dct = defaultdict(list)
     for f in self.files:
         dirname = f.parent.name
         filename = f.name
         insort_right(dct[dirname], filename)
     return dct
예제 #24
0
    def remove_dependencies(self, event):
        depending_events = self.blocks[event]
        for depending_event in depending_events:
            self.num_depends[depending_event] -= 1

            if self.num_depends[depending_event] == 0:
                bisect.insort_right(self.free_events, depending_event)
예제 #25
0
 def left(self, deprel):
     """(σ|i|j, β, A) ⇒ (σ|j, β, A ∪ {(j, l, i)})"""
     j = self.stack[-1]
     i = self.stack.pop(-2)
     insort_right(self.graph[j], i)
     # i <-deprel- j
     self.deprel[i] = deprel
예제 #26
0
    def _update_transceiver_sensor_cache(self, interface):
        """
        Update sensor data for single transceiver
        :param: interface: Interface name associated with transceiver
        """

        ifalias = self.if_alias_map.get(interface.encode(), b"").decode()
        ifindex = port_util.get_index_from_str(interface)

        # get transceiver sensors from transceiver dom entry in STATE DB
        transceiver_dom_entry = Namespace.dbs_get_all(self.statedb, mibs.STATE_DB,
                                                     mibs.transceiver_dom_table(interface))

        if not transceiver_dom_entry:
            return

        # go over transceiver sensors
        for sensor in map(bytes.decode, transceiver_dom_entry):
            if sensor not in SENSOR_NAME_MAP:
                continue
            sensor_sub_id = mibs.get_transceiver_sensor_sub_id(ifindex, sensor)
            sensor_description = get_transceiver_sensor_description(sensor, ifalias)

            self.physical_classes_map[sensor_sub_id] = PhysicalClass.SENSOR
            self.physical_description_map[sensor_sub_id] = sensor_description

            # add to available OIDs list
            insort_right(self.physical_entities, sensor_sub_id)
예제 #27
0
 def oddEvenJumps(self, A):
     n = len(A)
     odd_jump = [False] * n
     even_jump = [False] * n
     bst = []
     # base case
     odd_jump[n - 1] = True
     even_jump[n - 1] = True
     bisect.insort_right(bst, A[n - 1])
     # general case
     for i in range(n - 2, -1, -1):
         # odd跳的结果 (比它大的里面找最小的)
         next_node = bisect.bisect_right(bst, A[i])
         odd_jump[i] = next_node != len(bst) and even_jump[next_node]
         # even跳的结果(比它小的里面找最大的)
         pre_node = bisect.bisect_left(bst, A[i])
         even_jump[i] = pre_node != 0 and odd_jump[pre_node]
         # 把cur加入当前bst
         bisect.insort_left(bst, A[i])
     result = 0
     # 看每个起点的odd跳的结果
     for i in range(0, n):
         if odd_jump[i]:
             result += 1
     return result
예제 #28
0
def g_p_transactions():
    global blockchain
    global transactions
    if request.method == 'GET':

        return pickle.dumps(transactions)

    if request.method == 'POST':
        new_transaction = request.data
        new_transaction = pickle.loads(new_transaction)

        time_stamp = blockchain.data[-1].timestamp
        transaction_is_valid = new_transaction.verify(
            time_stamp)  #true or false

        if transaction_is_valid:
            #insert new_transaction into a sorted list
            #https://stackoverflow.com/questions/26840413/insert-a-custom-object-in-a-sorted-list
            bisect.insort_right(transactions, new_transaction)
            #print for check
            for i in transactions:
                print(
                    str(i.author.n)[-10:] + " " +
                    str(i.timestamped_msg.timestamp))

            return "success"
        else:
            return "failed"
예제 #29
0
def median(i_a, i_x):
    r = []
    n = len(i_a)
    for POS in xrange(n):
        if i_a[POS] == 'a':
            bisect.insort_right(r, i_x[POS])
            l = len(r)
            if l % 2 == 1:
                print r[l // 2]
            else:
                v = r[l // 2 - 1] + r[l // 2]
                print v // 2 if v % 2 == 0 else v / 2
        else:
            if i_x[POS] not in r:
                print 'Wrong!'
            else:
                r.remove(i_x[POS])
                l = len(r)
                if l % 2 == 1:
                    print r[l // 2]
                elif r:
                    v = r[l // 2 - 1] + r[l // 2]
                    print v // 2 if v % 2 == 0 else v / 2
                else:
                    print 'Wrong!'
예제 #30
0
    def insert(self, index: int, string: str) -> None:
        """Insert the given string before the specified index.

        This method has the same effect as ``self[index:index] = string``;
        it only avoids some condition checks as it rules out the possibility
        of the key being an slice, or the need to shrink any of the sub-spans.
        """
        ss, se = self._span
        lststr = self._lststr
        lststr0 = lststr[0]
        if index < 0:
            index += se - ss
            if index < 0:
                index = 0
        elif index > se - ss:  # Note that it is not >=. Index can be new.
            index = se - ss
        index += ss
        # Update lststr
        lststr[0] = lststr0[:index] + string + lststr0[index:]
        string_len = len(string)
        # Update spans
        self._insert_update(index=index, length=string_len)
        # Remember newly added spans by the string.
        type_to_spans = self._type_to_spans
        for type_, spans in parse_to_spans(
                bytearray(string, 'ascii', 'replace')).items():
            for s, e in spans:
                insort_right(type_to_spans[type_], [index + s, index + e])
예제 #31
0
    def add(self, delay):
        """Add a delay to the list.

        :param Delay delay:
            The delay to add.
        """
        bisect.insort_right(self, delay)
예제 #32
0
def add_transaction():
    global total_points
    request_data = request.get_json()

    # data validation
    if not request_data:
        return ('invalid no data', 400)
    elif not 'payer' in request_data or request_data['payer'] == '':
        return ('no payer information')
    elif not 'points' in request_data:
        return ('no point value', 400)
    elif request_data['points'] <= 0:
        return ('invalid amount of points', 400)
    elif not 'timestamp' in request_data or request_data['timestamp'] <= 0:
        return ('invalid date', 400)
    else:
        given_transaction = Transaction(request_data['payer'],
                                        request_data['points'],
                                        request_data['timestamp'])
        if binary_search(transactions, given_transaction) > -1 or \
           binary_search(used_transactions, given_transaction) > -1:
            return ('transaction already recorded', 400)
        bisect.insort_right(transactions, given_transaction)
        payers[given_transaction.payer] += given_transaction.inital_points
        total_points += given_transaction.inital_points

    date = datetime.utcfromtimestamp(given_transaction.timestamp)
    date_time = date.strftime("%m/%d/%Y, %H:%M:%S")
    return ('Recieved Transaction for time: ' + str(date_time))
예제 #33
0
def summary(path):
    dfs = []
    product_infos = {}
    with open('product_info.json', 'r') as f:
        product_infos = json.load(f)
    for f in os.listdir(path):
        events = []
        read_file(os.path.join(path, f), events)
        instrument = os.path.splitext(f)[0]
        product_code = instrument.strip('0123456789')
        assert product_code in product_infos, product_code
        account = FutureAccount(
            product_infos[product_code]['contract_multiple'])
        datetime_from = datetime.date(2016, 12, 5)
        datetime_to = datetime.date(2017, 11, 23)
        for i in range((datetime_to - datetime_from).days + 1):
            day = datetime_from + datetime.timedelta(days=i)
            dt = datetime.datetime.combine(day, datetime.time(15, 0, 0))
            dt = dt + datetime.timedelta(hours=8)  # utc
            ts = time.mktime(dt.timetuple())
            bisect.insort_right(events, DailySettle(int(ts * 1000)))

        assert (all(events[i] <= events[i + 1]
                    for i in range(len(events) - 1)))
        for event in events:
            event.do(account)

        df = account.to_df()
        df['instrument'] = instrument
        dfs.append(df)
    return pd.concat(dfs)
    def maxSumSubmatrix(self, matrix, k):
        """
        :type matrix: List[List[int]]
        :type k: int
        :rtype: int
        """
        if not matrix:
            return 0

        m = min(len(matrix), len(matrix[0]))
        n = max(len(matrix), len(matrix[0]))
        result = float("-inf")

        for i in range(m):  #这个是针对行,进行列的求和
            sums = [0] * n
            for j in range(i, m):  # 往下走
                for l in range(n):  # 往右走
                    sums[l] += matrix[j][l] if m == len(
                        matrix) else matrix[l][j]

                # Find the max subarray no more than K. 返回最接近K的值 这个地方有问题
                accu_sum_set, accu_sum = [0], 0
                for sum in sums:
                    accu_sum += sum
                    it = bisect_left(
                        accu_sum_set, accu_sum - k
                    )  # Time: O(logn) 放置于左边,求左边的index, accu_sum - k 就是 sum-k
                    if it != len(accu_sum_set):
                        result = max(
                            result, accu_sum - accu_sum_set[it]
                        )  # accu_sum_set[it]就是序列中最接近sum-k的数,这里有个减号,就是想让x最小
                    insort_right(accu_sum_set, accu_sum)  # Time: O(n) 放置于右边

        return result
예제 #35
0
 def add_partition(self, key, group):
     """Add sharding information for a group"""
     if self.shard_type == 'RANGE':
         key = int(key)
     elif self.shard_type == 'RANGE_DATETIME':
         try:
             if ':' in key:
                 key = datetime.strptime(key, "%Y-%m-%d %H:%M:%S")
             else:
                 key = datetime.strptime(key, "%Y-%m-%d").date()
         except:
             raise ValueError(
                 "RANGE_DATETIME key could not be parsed, was: {0}".format(
                     key))
     elif self.shard_type == 'RANGE_STRING':
         pass
     elif self.shard_type == "HASH":
         pass
     else:
         raise ValueError("Unsupported sharding type {0}".format(
             self.shard_type))
     self.partitioning[key] = {
         'group': group,
     }
     self.reset_ttl()
     bisect.insort_right(self.keys, key)
     insort_right_rev(self.keys_reversed, key)
예제 #36
0
    def book(self, start, end):
        """
        :type start: int
        :type end: int
        :rtype: int
        """
        from bisect import insort_right, insort_left
        insort_right(self.books, [start, 1])
        insort_left(self.books, [end, -1])

        res = 0
        temp = 0
        for a, e in self.books:
            temp += e
            if temp > res:
                res = temp
        return res


        


# Your MyCalendarThree object will be instantiated and called as such:
# obj = MyCalendarThree()
# param_1 = obj.book(start,end)

# 因为数据范围是 The number of calls to MyCalendarThree.book per test case will be at most 400
# 所以我们不用担心复杂度的问题,不需要什么 fansy 的数据结构。
예제 #37
0
파일: databasics.py 프로젝트: dlobue/nara
 def do_insort(x):
     '''
     Use bisect to put new messages into our message list in the correct order
     the first time so we never have to waste time using sort later.
     '''
     insort_right(self.messages, x)
     self.muuids.extend(x.muuid)
예제 #38
0
파일: event_queue.py 프로젝트: d1zzy/gogbot
 def RecordEvent(self, ev):
     # Keep the event queue ordered by timestamp. Usually this insert
     # happens at the end since events will tend to be added in chronological
     # order.
     bisect.insort_right(self._events, ev)
     # Keep events ordered by timestamp in the payload based map.
     bisect.insort_right(self._idx_data.setdefault(ev.data, []), ev)
예제 #39
0
def trouve_inclusions(liste_poly):
    """
    renvoie le vecteur des inclusions
    la ieme case contient l'indice du polygone
    contenant le ieme polygone (-1 si aucun).
    (voir le sujet pour plus d'info)
    """

    for i, p in enumerate(liste_poly):
        liste_poly[i] = (p, p.bounding_quadrant())

    vecteur_reponse = [-1] * len(liste_poly)

    liste_y = []

    for i, poly in enumerate(liste_poly):
        max_y = -float('Inf')
        for point in poly[0].points:
            if point.coordinates[1] > max_y:
                max_y = point.coordinates[1]
        insort_right(liste_y, (max_y, i))

    for i, triplet in enumerate(liste_y):
        for j in range(i + 1, len(liste_y)):
            if not quad_is_included(liste_poly[triplet[1]][1],
                                    liste_poly[liste_y[j][1]][1]):
                continue
            if wn_PnPoly(liste_poly[triplet[1]],
                         liste_poly[liste_y[j][1]]) != 0:
                vecteur_reponse[triplet[1]] = liste_y[j][1]
                break

    return vecteur_reponse
예제 #40
0
    def update(self):
        references = {}
        service = getUtility(IReferenceService)
        get_icon = IIconResolver(self.request).get_tag
        for reference in service.get_references_to(self.context):
            source = reference.source
            source_versions = []
            if IVersion.providedBy(source):
                source_versions.append(source.id)
                source = source.get_silva_object()

            url = getMultiAdapter((source, self.request), IContentURL)
            edit_url = str(url) + '/edit'
            if edit_url in references and source_versions:
                previous_versions = references[edit_url]['versions']
                if previous_versions[-1] > source_versions[0]:
                    bisect.insort_right(
                        previous_versions, source_versions[0])
                    continue
                else:
                    source_versions = previous_versions + source_versions

            source_title = source.get_title_or_id()
            references[edit_url] = {
                'title': source_title,
                'path': self.view.get_content_path(source),
                'icon': get_icon(source),
                'versions': source_versions}

        self.references = references.values()
        self.references.sort(key=lambda info: info['title'].lower())

        for info in self.references:
            if info['versions']:
                info['title'] += ' (' + ', '.join(info['versions']) + ')'
예제 #41
0
파일: deque.py 프로젝트: alefnula/perart
 def push_back(self, item):
     '''Add an element to the right side of the Deque'''
     LOG_VERBOSE('Deque.push_back(%s)' % item)
     with self.__lock:
         if self.__priority_deque:
             bisect.insort_right(self.__deque, ComparatorProxy(item=item, comparator=self.__comparator))
         else:
             self.__deque.append(item)
예제 #42
0
 def insertTask(self, priority, itm):
     self.lock.acquire()
     p = PQTask()
     p.pri = priority
     p.item = itm
     bisect.insort_right(self.queue, p)
     self.queueCmd.put('task')
     self.lock.release()
예제 #43
0
 def addEvent(self, relativeTime, callback, data = ()):
     assert relativeTime >= 0
     result = self.eventCount
     newClock = self.clock+relativeTime
     bisect.insort_right(
         self.queue, (newClock, self.eventCount, callback, data, result))
     self.eventCount += 1
     return result
예제 #44
0
    def __handle_hunk(self, hunk_dict):
        if not self._active_patch:
            raise PatchSyntaxError('Missing current patch')

        a_range = (int(hunk_dict['a1']), int(hunk_dict['a2']), )
        b_range = (int(hunk_dict['b1']), int(hunk_dict['b2']), )
        self._active_hunk = Hunk(a_range, b_range, hunk_dict.get('comment'))
        bisect.insort_right(self._active_patch.hunks, self._active_hunk)
예제 #45
0
 def _setInfo( self, nodeInfo ) :
     self.nodeDict[nodeInfo.nodeAddr] = nodeInfo
     insort_right( self.nodeList, nodeInfo )
     if len(self.nodeList) <= MAX_NODES : return
     extra = self.nodeList[MAX_NODES:]
     del self.nodeList[MAX_NODES:]
     for info in extra :
         del self.nodeDict[info.nodeAddr]
예제 #46
0
 def test_keyword_args(self):
     data = [10, 20, 30, 40, 50]
     self.assertEqual(bisect_left(a=data, x=25, lo=1, hi=3), 2)
     self.assertEqual(bisect_right(a=data, x=25, lo=1, hi=3), 2)
     self.assertEqual(bisect(a=data, x=25, lo=1, hi=3), 2)
     insort_left(a=data, x=25, lo=1, hi=3)
     insort_right(a=data, x=25, lo=1, hi=3)
     insort(a=data, x=25, lo=1, hi=3)
     self.assertEqual(data, [10, 20, 25, 25, 25, 30, 40, 50])
예제 #47
0
    def add_node(self, node):
        ''' Given a node, add it to the circle

        :param node: The node to add to the circle
        '''
        for idx in range(self.replicas):
            key = self.hasher("{}:{}".format(node, idx))
            self.mapping[key] = node
            insort_right(self.circle, key)
예제 #48
0
 def add_chunk(self, key, val):
     evict = (None, None)
     if not self.cache.has_key(key) and self.quota > 0:
         if len(self.llist) >= self.quota:
             # well, run of space now
             _, _, oldkey = self.llist[0]
             evict = self.del_chunk(oldkey)
         self.cache[key] = val
         bisect.insort_right(self.llist, [1+self.clock,time.time(),key])
     return evict
예제 #49
0
    def add_timer(self, callback, when, interval):
        """
        Add timer to the queue
        """

        timer = Timer(callback, when, interval)
        with self._lock:
            bisect.insort_right(self._timers, timer)
        self._wakeup()
        return timer
예제 #50
0
 def add(self, htsDP):
     """Adds the given htsDP to the list if it isn't already
     present. Returns True if added; otherwise returns False."""
     if id(htsDP) in self.__htsDPFromId:
         return False
     Key = self.key(htsDP.subject, htsDP.day, htsDP.time)
     bisect.insort_right(self.__hts, [Key, htsDP])
     self.__htsDPFromId[id(htsDP)] = htsDP
     self.__dirty = True
     return True
def test_bisect():
    import bisect

    a = [(0, 100), (150, 220), (500, 1000)]

    bisect.insort_right(a, (250, 400))
    bisect.insort_right(a, (399, 450))
    print a  # [(0, 100), (150, 220), (250, 400), (500, 1000)]

    print bisect.bisect(a, (550, 1200))  # 5
예제 #52
0
파일: pool.py 프로젝트: dsuch/gevent
 def _inext(self):
     while True:
         if self.waiting and self.waiting[0][0] <= self.index:
             _, value = self.waiting.pop(0)
         else:
             index, value = self.queue.get()
             if index > self.index:
                 insort_right(self.waiting, (index, value))
                 continue
         self.index += 1
         return value
예제 #53
0
 def register(self, upgrader, version=None, meta_type=None):
     assert IUpgrader.providedBy(upgrader)
     if not version:
         version = upgrader.version
     if not meta_type:
         meta_type = upgrader.meta_type
     if isinstance(meta_type, str) or meta_type is AnyMetaType:
         meta_type = [meta_type,]
     for type_ in meta_type:
         registry = self.__registry.setdefault(version, {}).setdefault(
             type_, [])
         insort_right(registry, upgrader)
예제 #54
0
def add_action(source, action, pulse, callback, priority=0):

    pulse_key = ev.current_pulse + pulse
    current_diff = pulse
    sys_action = SystemAction(source, action, priority, callback)

    try:
        pulse_actions = _pulse_map[pulse_key]
    except KeyError:
        _pulse_map[pulse_key] = pulse_actions = []
        ev.register_once(process_actions, current_diff, kwargs={'pulse_key': pulse_key})
    bisect.insort_right(pulse_actions, sys_action)
예제 #55
0
파일: datalgo.py 프로젝트: trtikm/E2
def merge_sorted_lists_of_events(list_of_lists_of_events):
    assert isinstance(list_of_lists_of_events, list)
    assert all(is_sorted_list_of_events(events) for events in list_of_lists_of_events)

    result = []
    for events in list_of_lists_of_events:
        for event in events:
            bisect.insort_right(result, event)

    assert is_sorted_list_of_events(result)
    assert len(result) == sum(len(events) for events in list_of_lists_of_events)
    return result
예제 #56
0
 def add_addable(self, meta_type, priority, content_type):
     """Allow adding an addable to silva without using the
     registerClass shortcut method.
     """
     meta_type = _get_product_meta_type(meta_type)
     if content_type is not None:
         content_type = _get_product_meta_type(content_type)
     else:
         content_type = meta_type
     if meta_type is not None and content_type is not None:
         insort_right(
             self._silva_addables,
             Addable(meta_type, content_type, priority))
예제 #57
0
 def functiongrabber(func):
     #The magic is actually done here: self.signatures is always in
     #sorted order, so that when we iterate through it it's just a
     #matter of checking if the signature matches or not. Of course,
     #this means we need to -maintain- sorted order, so bisect.insort
     #is used to do the algorithmic lifting.
     if sig not in self.signatures:
         #If it's already in there, it'll be at the correct index.
         bisect.insort_right(self.signatures, sig)
         #but, its signature won't be in the s2fs dict if it's not
         self.s2fs[sig] = []
     self.s2fs[sig].append(func)
     return self
예제 #58
0
파일: image.py 프로젝트: helenwarren/Willow
    def register_loader(cls, image_format, backend, priority=0):
        # If format is a list or tuple, call this method for each one
        if isinstance(image_format, (list, tuple)):
            for ext in image_format:
                cls.register_loader(ext, backend, priority=priority)
            return

        # Register format in loaders
        if image_format not in cls.loaders:
            cls.loaders[image_format] = []

        # Add the backend
        bisect.insort_right(cls.loaders[image_format], (priority, backend))
예제 #59
0
파일: pool.py 프로젝트: Apolot/gevent
 def next(self):
     while True:
         if self.waiting and self.waiting[0][0] <= self.index:
             index, value = self.waiting.pop(0)
         else:
             index, value = self.queue.get()
             if index > self.index:
                 insort_right(self.waiting, (index, value))
                 continue
         self.index += 1
         if isinstance(value, Failure):
             raise value.exc
         return value