Example #1
0
from sortedcontainers import SortedList  # http://www.grantjenks.com/docs/sortedcontainers/

for case in range(int(input())):
    N, K = map(int, input().split())
    lst = SortedList([N])

    for _ in range(K - 1):
        s = lst.pop()
        l, r = s // 2, (s - 1) // 2
        if l != 0:
            lst.add(l)
        if r != 0:
            lst.add(r)

    s = lst.pop()
    l, r = s // 2, (s - 1) // 2
    ans1 = max(l, r)
    ans2 = min(l, r)

    print('Case #%d: %s %s' % (case + 1, ans1, ans2))
Example #2
0
def test_setitem_valueerror2():
    slt = SortedList(range(10))
    slt[0] = 10
Example #3
0
def test_reversed():
    slt = SortedList(range(10000))
    rev = reversed(slt)
    assert all(tup[0] == tup[1] for tup in zip(range(9999, -1, -1), rev))
Example #4
0
def test_setitem_slice_bad2():
    slt = SortedList(range(100))
    slt._reset(17)
    slt[20:30] = range(10, 20)
Example #5
0
def test_setitem_extended_slice_bad2():
    slt = SortedList(range(100))
    slt._reset(17)
    slt[40:90:5] = list(range(10))
Example #6
0
def test_setitem_slice_aliasing():
    slt = SortedList([0])
    slt[1:1] = slt
    assert slt == [0, 0]
Example #7
0
def test_setitem_slice_bad():
    slt = SortedList(range(100))
    slt._reset(17)
    slt[:10] = list(reversed(range(10)))
Example #8
0
def generate_drums():
    """Generate a new drum groove by querying the model."""
    global drums_bundle
    global generated_drums
    global playable_notes
    global seed_drum_sequence
    global num_steps
    global qpm
    global total_seconds
    global temperature
    drums_config_id = drums_bundle.generator_details.id
    drums_config = drums_rnn_model.default_configs[drums_config_id]
    generator = drums_rnn_sequence_generator.DrumsRnnSequenceGenerator(
        model=drums_rnn_model.DrumsRnnModel(drums_config),
        details=drums_config.details,
        steps_per_quarter=drums_config.steps_per_quarter,
        checkpoint=melody_rnn_generate.get_checkpoint(),
        bundle=drums_bundle)
    generator_options = generator_pb2.GeneratorOptions()
    generator_options.args['temperature'].float_value = temperature
    generator_options.args['beam_size'].int_value = 1
    generator_options.args['branch_factor'].int_value = 1
    generator_options.args['steps_per_iteration'].int_value = 1
    if seed_drum_sequence is None:
        primer_drums = magenta.music.DrumTrack([frozenset([36])])
        primer_sequence = primer_drums.to_sequence(qpm=qpm)
        local_num_steps = num_steps
    else:
        primer_sequence = seed_drum_sequence
        local_num_steps = num_steps * 2
        tempo = primer_sequence.tempos.add()
        tempo.qpm = qpm
    step_length = 60. / qpm / 4.0
    total_seconds = local_num_steps * step_length
    # Set the start time to begin on the next step after the last note ends.
    last_end_time = (max(
        n.end_time
        for n in primer_sequence.notes) if primer_sequence.notes else 0)
    generator_options.generate_sections.add(start_time=last_end_time +
                                            step_length,
                                            end_time=total_seconds)
    generated_sequence = generator.generate(primer_sequence, generator_options)
    generated_sequence = sequences_lib.quantize_note_sequence(
        generated_sequence, 4)
    if seed_drum_sequence is not None:
        i = 0
        while i < len(generated_sequence.notes):
            if generated_sequence.notes[i].quantized_start_step < num_steps:
                del generated_sequence.notes[i]
            else:
                generated_sequence.notes[i].quantized_start_step -= num_steps
                generated_sequence.notes[i].quantized_end_step -= num_steps
                i += 1
    drum_pattern = [(n.pitch, n.quantized_start_step, n.quantized_end_step)
                    for n in generated_sequence.notes]
    # First clear the last drum pattern.
    if len(playable_notes) > 0:
        playable_notes = SortedList(
            [x for x in playable_notes if x.type != 'drums'],
            key=lambda x: x.onset)
    for p, s, e in drum_pattern:
        playable_notes.add(
            PlayableNote(type='drums',
                         note=[],
                         instrument=DRUM_MAPPING[p],
                         onset=s))
Example #9
0
def cc_event(addr, tags, args, source):
    """Handler for `/ccevent` messages from SuperCollider.

  Logic for dealine with the volume knob in the iRig mini
  keyboard.
  - If in lowest position (0): mode = 'tap'.
  - Else if in lower half of range, mode = 'bass'.
  - Else if in upper half (but not max), mode = 'chords'.
  - Else if at highest position (127): mode = 'improv'.

  Args:
    addr: Address message sent to.
    tags: Tags in message.
    args: Arguments passed in message.
    source: Source of sender.
  """
    global nanokontrol_id
    global mode
    global playable_instruments
    global time_signature
    global qpm
    global last_tap_onset
    global beat_length
    global last_first_beat_for_record
    global bass_line
    global playable_notes
    global seed_drum_sequence
    global temperature
    global bass_volume
    global num_bars
    global chords_volume
    global improv_volume
    global play_loop
    if not args:
        return
    cc_num, cc_chan, cc_src, cc_args = args
    if nanokontrol_id is None:
        nanokontrol_id = cc_args
        return
    if cc_args == nanokontrol_id:
        channel_name = nanokontrolmap.cc_messages[cc_chan][0]
        lowest_value = nanokontrolmap.cc_messages[cc_chan][2][0]
        highest_value = nanokontrolmap.cc_messages[cc_chan][2][1]
        # Logic for setting tempo, time signature, and looper.
        if channel_name == 'play' and cc_num == highest_value:
            play_loop = True
        elif channel_name == 'stop' and cc_num == highest_value:
            play_loop = False
        elif channel_name == 'track1_mute' and cc_num == highest_value:
            if 'click' in playable_instruments:
                playable_instruments.remove('click')
            else:
                playable_instruments.add('click')
        elif channel_name == 'track1_solo' and cc_num == highest_value:
            if last_tap_onset is None:
                last_tap_onset = time.time()
                return
            curr_time = time.time()
            time_delta = curr_time - last_tap_onset
            last_tap_onset = curr_time
            if time_delta > MAX_TAP_DELAY:
                return
            if beat_length is None:
                beat_length = time_delta
            else:
                beat_length += time_delta
                beat_length /= 2
            qpm = 60.0 / beat_length
        elif channel_name == 'track1_knob':
            qpm = 300 * cc_num / float(highest_value)
        elif channel_name == 'track_left' and cc_num == highest_value:
            time_signature.numerator = max(2, time_signature.numerator - 1)
            set_click()
        elif channel_name == 'track_right' and cc_num == highest_value:
            time_signature.numerator += 1
            set_click()
        elif channel_name == 'marker_left' and cc_num == highest_value:
            time_signature.denominator = max(4, time_signature.denominator / 2)
            set_click()
        elif channel_name == 'marker_right' and cc_num == highest_value:
            time_signature.denominator = min(16,
                                             time_signature.denominator * 2)
            set_click()
        elif channel_name == 'rew' and cc_num == highest_value:
            num_bars = max(1, num_bars - 1)
            set_click()
        elif channel_name == 'ff' and cc_num == highest_value:
            num_bars = min(4, num_bars + 1)
            set_click()
        # Logic for controlling the bass.
        elif channel_name == 'track2_slider':
            bass_volume = 5.0 * cc_num / float(highest_value)
            print_status()
        elif channel_name == 'track2_mute' and cc_num == highest_value:
            if 'bass' in playable_instruments:
                playable_instruments.remove('bass')
            else:
                playable_instruments.add('bass')
        elif channel_name == 'track2_record' and cc_num == highest_value:
            mode = 'bass'
            last_first_beat_for_record = None
            # Clear off last bass line.
            playable_notes = SortedList(
                [x for x in playable_notes if x.type != 'bass'],
                key=lambda x: x.onset)
            bass_line = []
        # Logic for controlling drums.
        elif channel_name == 'track3_solo' and cc_num == highest_value:
            mode = 'free'
            # Clear off last drum groove.
            playable_notes = SortedList(
                [x for x in playable_notes if x.type != 'drums'],
                key=lambda x: x.onset)
            seed_drum_sequence = music_pb2.NoteSequence()
            # First add a kick on each downbeat and hi-hats for each click.
            for playable_note in playable_notes:
                if playable_note.type != 'click':
                    continue
                drum_note = seed_drum_sequence.notes.add()
                pitch = 42 if playable_note.instrument == 'click2' else 36
                drum_note.pitch = pitch
                drum_note.quantized_start_step = playable_note.onset
                drum_note.quantized_end_step = playable_note.onset + 4
                drum_note.is_drum = True
                playable_notes.add(
                    PlayableNote(type='drums',
                                 note=[],
                                 instrument=DRUM_MAPPING[pitch],
                                 onset=playable_note.onset))
            # Now add snare hits that match the bass line.
            for bass_note in bass_line:
                drum_note = seed_drum_sequence.notes.add()
                pitch = 38
                drum_note.pitch = pitch
                drum_note.quantized_start_step = bass_note.onset
                drum_note.quantized_end_step = bass_note.onset + 4  # A quarter note.
                drum_note.is_drum = True
                playable_notes.add(
                    PlayableNote(type='drums',
                                 note=[],
                                 instrument='snare',
                                 onset=bass_note.onset))
        elif channel_name == 'track3_mute' and cc_num == highest_value:
            if 'drums' in playable_instruments:
                playable_instruments.remove('drums')
            else:
                playable_instruments.add('drums')
        elif channel_name == 'track3_record' and cc_num == highest_value:
            mode = 'free'
            dt = threading.Thread(target=generate_drums)
            dt.start()
        elif channel_name == 'track3_knob':
            temperature = max(0.01, cc_num / float(highest_value) * 5.0)
        # Logic for controlling chords.
        elif channel_name == 'track4_slider':
            chords_volume = 5.0 * cc_num / float(highest_value)
            print_status()
        elif channel_name == 'track4_mute' and cc_num == highest_value:
            if 'chords' in playable_instruments:
                playable_instruments.remove('chords')
            else:
                playable_instruments.add('chords')
        elif channel_name == 'track4_record' and cc_num == highest_value:
            mode = 'chords'
            # Clear off last chords line.
            playable_notes = SortedList(
                [x for x in playable_notes if x.type != 'chords'],
                key=lambda x: x.onset)
            last_first_beat_for_record = None
        # Logic for controlling improv.
        elif channel_name == 'track5_slider':
            improv_volume = 5.0 * cc_num / float(highest_value)
            print_status()
        elif channel_name == 'track5_solo' and cc_num == highest_value:
            mode = 'free'
        elif channel_name == 'track5_record' and cc_num == highest_value:
            mode = 'improv'
    print_status()
Example #10
0
        segment = {'img_id': img_id,
                   'top': lines[i],
                   'bottom': lines[j],
                   'height': lines[j] - lines[i],
                   'ann_ids': annids}

        if lines[i] == 0:
            top_segs.append(segment)
        elif lines[j] == 2048:
            bot_segs.append(segment)
        else:
            mid_segs.append(segment)

        i=j+1

top_segs = SortedList(top_segs, key=lambda seg: seg['height'])
bot_segs = SortedList(bot_segs, key=lambda seg: seg['height'])
mid_segs = SortedList(mid_segs, key=lambda seg: seg['height'])
mid_tot=len(mid_segs)

mid_heights = np.array([seg['height'] for seg in mid_segs])
mid_weights = np.sqrt(mid_heights)
prefix_sum = np.array(mid_weights)
for i in range(1, mid_tot):
    prefix_sum[i] = prefix_sum[i - 1] + prefix_sum[i]


def cut_image(gen_image, segment, img_id, ann_id, current_height):
    image_info = img_info[segment['img_id']]
    ori_anns = coco.load_anns(segment['ann_ids'])
    anns=copy.deepcopy(ori_anns)
Example #11
0

class TimeSignature:
    numerator = 7
    denominator = 8


time_signature = TimeSignature()
qpm = magenta.music.DEFAULT_QUARTERS_PER_MINUTE
num_bars = 2
num_steps = int(num_bars * time_signature.numerator * 16 /
                time_signature.denominator)

PlayableNote = collections.namedtuple('playable_note',
                                      ['type', 'note', 'instrument', 'onset'])
playable_notes = SortedList(key=lambda x: x.onset)

play_loop = False
seed_drum_sequence = None
last_tap_onset = None
beat_length = None
last_first_beat = 0.0  # Last time we passed the first beat during playback.
# Last first beat from the moment the bass started playing.
last_first_beat_for_record = None
bass_line = []
bass_volume = 1.0
chords_volume = 1.0
improv_volume = 1.0
MAX_TAP_DELAY = 5.0
# Robot improv specific variables.
min_primer_length = 20
Example #12
0
from enum import Enum
from sortedcontainers import SortedList
from sortiton import *
import random
from pprint import pprint
import numpy as np
import ecdsa
import hashlib
import secrets
import pickle
import sys
import os.path
from keygen import *
import config

eventQ = SortedList()
allNodes = []
delays = []
blockDelays=[]
sk_List = []
pk_List = []
w_list = []
ctx_Weight = {}

INVOKE_BA_START_COUNT_VOTE_ONE = 1

INVOKE_BA_START_COUNT_VOTE_TWO = 2

INVOKE_BA_START_COUNT_VOTE_THREE = 3

DO_NOT_INVOKE_ANY_MORE_COUNT_VOTE = 0
 def __init__(self, m: int, k: int):
     from sortedcontainers import SortedList
     self.m, self.k = m, k
     self.queue = deque()
     self.sl = SortedList()
     self.total = self.left_k = self.right_k = 0
Example #14
0
from datetime import datetime
import logging
import threading
import tbapy
from sortedcontainers import SortedList

# Define variables
logger = logging.getLogger('FRCMatchFinderLogger')
tba = tbapy.TBA(
    '9YP15wdwpFPjJri1tGj6BGwWCkHxNVaM9xKmv2Z0aYikXOXOKtOKol9gD5yntLJ5')
sync_cond = threading.Condition()
watcher_lock = threading.Condition()

# Needed lists
teams = []
matches = SortedList()
current = []
upcoming = []

# Range in seconds to check current matches within
MATCH_RANGE = 150

# Range in seconds to check upcoming matches within
UPCOMING_RANGE = 3600

# file for default teams to find
TEAMS_FILE = 'teams.txt'


def main():
    try:
Example #15
0
def test_getitem_indexerror2():
    slt = SortedList(range(100))
    slt[200]
 def __init__(self, n: int):
     self.data = SortedList((i, i) for i in range(1, n+1))
Example #17
0
def test_getitem_indexerror3():
    slt = SortedList(range(100))
    slt[-101]
Example #18
0
    # find the 25 closest users to user i
    movies_i = user2movie[i]
    movies_i_set = set(movies_i)

    # calculate avg and deviation
    ratings_i = {movie: usermovie2rating[(i, movie)] for movie in movies_i}
    avg_i = np.mean(list(ratings_i.values()))
    dev_i = {movie: (rating - avg_i) for movie, rating in ratings_i.items()}
    dev_i_values = np.array(list(dev_i.values()))
    sigma_i = np.sqrt(dev_i_values.dot(dev_i_values))

    # save these for later use
    averages.append(avg_i)
    deviations.append(dev_i)

    sl = SortedList()
    for j in range(N):
        # don't include yourself
        if j != i:
            movies_j = user2movie[j]
            movies_j_set = set(movies_j)
            common_movies = (movies_i_set & movies_j_set)  # intersection
            if len(common_movies) > limit:
                # calculate avg and deviation
                ratings_j = {
                    movie: usermovie2rating[(j, movie)]
                    for movie in movies_j
                }
                avg_j = np.mean(list(ratings_j.values()))
                dev_j = {
                    movie: (rating - avg_j)
Example #19
0
def test_setitem_empty_slice():
    sl = SortedList(['a'])
    sl[1:0] = ['b']
    assert sl == ['a', 'b']
Example #20
0
def test_remove_valueerror1():
    slt = SortedList()
    slt.remove(0)
Example #21
0
def test_setitem_slice_bad1():
    slt = SortedList(range(100))
    slt._reset(17)
    slt[10:20] = range(20, 30)
Example #22
0
def test_remove_valueerror2():
    slt = SortedList(range(100))
    slt._reset(10)
    slt.remove(100)
Example #23
0
def test_setitem_extended_slice_bad1():
    slt = SortedList(range(100))
    slt._reset(17)
    slt[20:80:3] = list(range(10))
Example #24
0
def test_remove_valueerror3():
    slt = SortedList([1, 2, 2, 2, 3, 3, 5])
    slt.remove(4)
Example #25
0
def test_setitem_valueerror1():
    slt = SortedList(range(10))
    slt[9] = 0
Example #26
0
def test_getitem_slicezero():
    slt = SortedList(range(100))
    slt._reset(17)
    slt[::0]
Example #27
0
def test_iter():
    slt = SortedList(range(10000))
    itr = iter(slt)
    assert all(tup[0] == tup[1] for tup in zip(range(10000), itr))
Example #28
0
def test_getitem_indexerror1():
    slt = SortedList()
    slt[5]
Example #29
0
def test_reverse():
    slt = SortedList(range(10000))
    slt.reverse()
Example #30
0
import time
from sortedcontainers import SortedList
# This opens a handle to your file, in 'r' read mode
file_handle = open('input.txt', 'r')

lines_list = file_handle.readlines()

int_list = []
for val in lines_list:
    int_list.append(int(val))

#int_list = [+3, +3, +4, -2, -4]
print(sum(int_list))

sum_list = SortedList([])
temp_value = int_list[0]
index = 1

start = time.time()
while temp_value not in sum_list:
    sum_list.add(temp_value)
    temp_value += int_list[index]
    index += 1
    if index == len(int_list):
        index = 0
        #print(len(sum_list))
end = time.time()

print(f"value: {temp_value}")
print(f"time: {end - start}")