Ejemplo n.º 1
0
    def create_widgets(self):
        self.base_var = tk.IntVar()
        self.base_slider = Slider("Base Value",
                                  from_=10,
                                  to_=50,
                                  master=self,
                                  variable=self.base_var)
        self.base_slider.grid(row=0, column=0)

        self.extra_var = tk.IntVar()
        self.extra_slider = Slider("Extra Value",
                                   from_=0,
                                   to_=40,
                                   master=self,
                                   variable=self.extra_var)
        self.extra_slider.grid(row=0, column=1)

        self.accA_var = tk.IntVar()
        self.accA_slider = Slider("Acceleration A",
                                  from_=10,
                                  to_=50,
                                  master=self,
                                  variable=self.accA_var)
        self.accA_slider.grid(row=1, column=0)

        self.accB_var = tk.IntVar()
        self.accB_slider = Slider("Acceleration B",
                                  from_=10,
                                  to_=50,
                                  master=self,
                                  variable=self.accB_var)
        self.accB_slider.grid(row=1, column=1)
Ejemplo n.º 2
0
    def sliders(self):

        randCols = [0, 50, 200, 250]

        self.startSlider = Slider(
            self.scr,
            pos_size=[200, 100, 160, 40],
            steps=10,
            colour=(randCols[random.randint(0, 3)],
                    randCols[random.randint(0,
                                            3)], randCols[random.randint(0,
                                                                         3)]),
            secondary_colour=(randCols[random.randint(0, 2)],
                              randCols[random.randint(0, 2)],
                              randCols[random.randint(0, 2)]),
        )

        self.startSlider2 = Slider(
            self.scr,
            pos_size=[200, 50, 160, 40],
            steps=100,
            colour=(randCols[random.randint(0, 3)],
                    randCols[random.randint(0,
                                            3)], randCols[random.randint(0,
                                                                         3)]),
            secondary_colour=(randCols[random.randint(0, 2)],
                              randCols[random.randint(0, 2)],
                              randCols[random.randint(0, 2)]),
        )
Ejemplo n.º 3
0
    def create_sliders(self):
        left_pos = (L_GOAL_LINE + SLIDER_DISTX, self.field.rect.centery)
        self.left_slider = Slider(self.field.surface,
                                  left_pos,
                                  group=self.sprites,
                                  color='red')
        self.sliders.append(self.left_slider)

        right_pos = (R_GOAL_LINE - SLIDER_DISTX, self.field.rect.centery)
        self.right_slider = Slider(self.field.surface,
                                   right_pos,
                                   group=self.sprites,
                                   color='blue')
        self.sliders.append(self.right_slider)
Ejemplo n.º 4
0
    def __init__(self):
        pygame.init()

        self.outputs = Outputs()
        self.stream = Stream(channels=1,
                             sample_rate=60 * 10**3,
                             sample_size=2**11)

        self.mouse_frequency = 0.0

        # visual params
        self.background_color = pygame.Color(50, 50, 50)
        self.colorA = pygame.Color("#ff0000")
        self.colorB = pygame.Color("#0000ff")
        self.num_bars = self.outputs.get_divisor()

        # surface params
        self.height = 1000
        self.dimensions = numpy.array([self.outputs.get_width(), self.height])
        self.surface_flags = pygame.HWSURFACE | pygame.DOUBLEBUF
        self.surface = pygame.display.set_mode(self.dimensions,
                                               self.surface_flags)
        self.time_surface = pygame.Surface(self.dimensions //
                                           numpy.array([1, 2]))
        self.freq_surface = pygame.Surface(self.dimensions //
                                           numpy.array([1, 2]))
        self.control_surface = pygame.Surface(self.dimensions // 2)
        self.control_surface.set_colorkey(self.background_color)

        self.controls = Controls(self.control_surface)

        self.sliders = {
            'pull':
            Slider(self.control_surface,
                   pygame.Rect(300, 46, 100, 10),
                   10,
                   15,
                   value=0.5),
            'smooth':
            Slider(self.control_surface,
                   pygame.Rect(300, 66, 100, 10),
                   10,
                   15,
                   value=0.5)
        }

        # smoothing history array
        self.t_history = numpy.full(self.num_bars, 0.5)
        self.f_history = numpy.full(self.num_bars, 0.0)
    def sliderMoved(self, active_slider):
        """
            update slider values and label texts according to slider coupling
        """
        alt_slider_list = []
        slide1 = Slider(slider=self.finger_slider_1,
                        label_val=self.value_slider_1,
                        tick=self.tick_f1.isChecked())
        slide2 = Slider(slider=self.finger_slider_2,
                        label_val=self.value_slider_2,
                        tick=self.tick_f2.isChecked())
        slide3 = Slider(slider=self.finger_slider_3,
                        label_val=self.value_slider_3,
                        tick=self.tick_f3.isChecked())
        slide4_tick = self.tick_f4.isChecked() if self.tick_f4.isVisible(
        ) else False
        slide4 = Slider(slider=self.finger_slider_4,
                        label_val=self.value_slider_4,
                        tick=slide4_tick)
        slide5 = Slider(slider=self.finger_slider_5,
                        label_val=self.value_slider_5,
                        tick=False)
        if active_slider == 1:
            this_slider = slide1
            alt_slider_list = [slide2, slide3,
                               slide4]  #slider 5 cant be coupled
        elif active_slider == 2:
            this_slider = slide2
            alt_slider_list = [slide1, slide3,
                               slide4]  #slider 5 cant be coupled
        elif active_slider == 3:
            this_slider = slide3
            alt_slider_list = [slide1, slide2,
                               slide4]  #slider 5 cant be coupled
        elif active_slider == 4:
            this_slider = slide4
            alt_slider_list = [slide1, slide2,
                               slide3]  #slider 5 cant be coupled
        elif active_slider == 5:
            this_slider = slide5

        curr_value = float(this_slider.getVal())
        float_value = curr_value / 100.0
        this_slider.setLabel("%2.2f" % float_value)
        if this_slider.getTickCheck():
            for slide in alt_slider_list:
                if slide.getTickCheck():
                    slide.setLabel("%2.2f" % float_value)
                    slide.setSlider(this_slider.getVal())
Ejemplo n.º 6
0
    def on_layout(self, winsize):
        width, height = self.image.size
        display_width = Window.width / 3.5
        self.image_rect.pos = (Window.width - display_width) / 20, (
            Window.height - 1 / self.w_h_ratio * display_width) // 2
        self.image_rect.size = (display_width,
                                1 / self.w_h_ratio * display_width)
        self.pixelate_rect.pos = (Window.width - display_width) / 2, (
            Window.height - 1 / self.w_h_ratio * display_width) // 2
        self.pixelate_rect.size = (display_width,
                                   1 / self.w_h_ratio * display_width)
        self.domino_rect.pos = 19 * (Window.width - display_width) / 20, (
            Window.height - 1 / self.w_h_ratio * display_width) // 2
        self.domino_rect.size = (display_width,
                                 1 / self.w_h_ratio * display_width)

        self.generate_button.pos = (
            Window.width - 0.75 * display_width) / 2, self.pixelate_rect.pos[
                1] - Window.height // 10 - 0.75 * display_width / 4.24
        self.generate_button.size = (0.75 * display_width,
                                     0.75 * display_width / 4.24)

        if self.pixel_slider in self.canvas.children:
            self.canvas.remove(self.pixel_slider)

        self.pixel_slider = Slider(1, self.pixelate_rect.pos,
                                   self.pixelate_rect.size)
        self.canvas.add(self.pixel_slider)

        self.label.center_x = Window.width / 2
        self.label.center_y = (Window.height + 1 / self.w_h_ratio *
                               display_width) // 2 + Window.height / 20
        self.label.font_size = str(Window.width // 170) + 'sp'

        self.color_switch.on_layout()
    def __init__(self):
        self.tk = Tk()
        #self.tk.configure(background='black')
        #self.topFrame = Frame(self.tk, background='black')
        #self.bottomFrame = Frame(self.tk, background='black')
        #self.topFrame.pack(side=TOP, fill=BOTH, expand=YES)
        #self.bottomFrame.pack(side=BOTTOM, fill=BOTH, expand=YES)
        #self.state = False
        self.tk.geometry("{0}x{1}+0+0".format(self.tk.winfo_screenwidth(),
                                              self.tk.winfo_screenheight()))
        self.tk.attributes('-fullscreen', True)
        self.fname = 'assets/rpi_bg.png'  #'assets/rpi_bg.png'
        self.bg_image = ImageTk.PhotoImage(file=self.fname)
        self.cv = Canvas(width=self.tk.winfo_screenwidth(),
                         height=self.tk.winfo_screenheight(),
                         highlightthickness=0)
        self.cv.pack(side=TOP, fill=BOTH, expand=YES)
        self.cv.create_image(0, 0, image=self.bg_image, anchor=NW)

        self.topFrame = Frame(self.cv, background='')
        self.bottomFrame = Frame(self.cv, background='')
        self.topFrame.pack(side=TOP, fill=BOTH, expand=YES)
        self.bottomFrame.pack(side=BOTTOM, fill=BOTH, expand=YES)

        #Clock
        self.clock = Clock(self.topFrame)
        self.clock.pack(side=RIGHT, anchor=N, padx=100, pady=60)

        #Slider
        self.slider = Slider(self.bottomFrame)
        self.slider.pack(side=BOTTOM, anchor=CENTER)

        #Weather
        self.weather = Weather(self.topFrame)
        self.weather.pack(side=LEFT, anchor=N, padx=100, pady=60)
Ejemplo n.º 8
0
    def __init__(self, pos, planet_from, planet_to, on_order):
        super().__init__(pos, planet_from)
        self.planet_from = planet_from
        self.planet_to = planet_to
        self.on_order = on_order

        self.tab = {'text': "Send Ships", 'color': PICO_PINK}

        ships = {**self.planet_from.ships}
        ships['colonist'] = self.planet_from.population

        y = 0
        self.sliders = {}
        for ship in ships.keys():
            if ships[ship]:
                if ship == "colonist":
                    name = "Worker"
                else:
                    name = ship.title()

                self.add(SimpleSprite((0, 0), 'assets/i-%s.png' % ship),
                         V2(0, y))
                self.add(
                    Text("%ss" % name, "small", (0, 0), PICO_WHITE, False),
                    V2(14, y + 2))
                slider = Slider(V2(0, 0), 80, 0, ships[ship])
                self.add(slider, V2(0, y + 12))
                self.sliders[ship] = slider
                y += 45

        self.add(Button(V2(0, 0), "LAUNCH", "small", self.on_launch_click),
                 V2(20, y))

        self.redraw()
Ejemplo n.º 9
0
def settings():
    screen.fill([245, 245, 220])
    screen.blit(menu2.image, menu2.rect)
    start = True

    saves = open(os.path.join('data', 'lvl.txt'))
    c = saves.read().split()
    if c[4] == '0':
        hiden = f3.render('Привет я рада что ты сюда заглянул) Как тебе музыка?^-^', True, (80, 150, 80))
        screen.blit(hiden, (0, 600))
    c[4] = '1'
    copy = ' '.join(c)
    saves.close()
    f = open('data\lvl.txt', 'w')
    f.write(copy)
    f.close()

    info1 = f1.render("to move forvard print space or enter :3", True, (138, 43, 226))
    screen.blit(info1, (0, 268))
    info2 = f1.render("to back to menu click esc ", True, (138, 43, 226))
    screen.blit(info2, (0, 320))
    info3 = f1.render("BUT don't forget save your progress", True, (138, 43, 226))
    screen.blit(info3, (0, 372))
    info4 = f1.render("thanks for playing ;)", True, (138, 43, 226))
    screen.blit(info4, (0, 428))

    ex = f3.render('you still need esc to exit to menu', True, (215, 24, 104))
    screen.blit(ex, (0, 676))

    music = Slider("Music Volume", 300, 300, 1, (20, 20), (400, 70), f2)

    off = Button.Button()
    off.create_button(screen, (90, 255, 100), 30, 150, 200, 50, 0, 'off', (68, 45, 37))

    while start:
        music.draw(screen)
        pygame.display.flip()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                start = False
                pygame.quit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    start = False
                    startWindow()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                if music.button_rect.collidepoint(pos):
                    music.hit = True
                    pygame.mixer.music.set_volume(int(music.get_value()) / 300)
                if off.pressed(pos):
                    pygame.mixer.music.set_volume(0)
            elif event.type == pygame.MOUSEBUTTONUP:
                music.hit = False
        if music.hit:
            music.move()

    pygame.quit()
Ejemplo n.º 10
0
    def __init__(self, pos, planet_from, planet_to, on_order):
        super().__init__(pos, planet_to)
        self.planet_from = planet_from
        self.planet_to = planet_to
        self.on_order = on_order

        siegers_only = isinstance(self.planet_to, asteroid.Asteroid)

        self.tab = {'text': "Send Ships", 'color': PICO_PINK}

        ships = {**self.planet_from.ships}
        ships['colonist'] = self.planet_from.population

        y = 0
        self.sliders = {}
        for ship in ships.keys():
            if ships[ship]:
                if ship == "colonist":
                    name = "Worker"
                else:
                    name = SHIPS_BY_NAME[ship].get_display_name()

                color = PICO_WHITE
                disabled = False
                if siegers_only and not SHIPS_BY_NAME[ship].BOMBS:
                    disabled = True
                    color = PICO_DARKGRAY
                self.add(SimpleSprite((0, 0), 'assets/i-%s.png' % ship),
                         V2(0, y))
                self.add(Text("%ss" % name, "small", (0, 0), color, False),
                         V2(14, y + 2))
                disable_nums = None
                if self.planet_from.owning_civ.worker_loss > 0:
                    disable_nums = list(
                        range(1, self.planet_from.owning_civ.worker_loss + 1))
                slider = Slider(V2(0, 0),
                                80,
                                0,
                                ships[ship],
                                disabled=disabled,
                                disable_nums=disable_nums)
                self.add(slider, V2(0, y + 12))
                self.sliders[ship] = slider
                y += 45

        if not self.sliders:
            self.add(Text("No ships!", "small", V2(0, 0)), V2(0, 0))
            y += 25

        t = "LAUNCH"
        if game.Game.inst.input_mode == "joystick":
            t = "[*x*] LAUNCH"
        if not self.sliders:
            t = "BACK"
            if game.Game.inst.input_mode == "joystick":
                t = "[*circle*] BACK"
        self.add(Button(V2(0, 0), t, "small", self.on_launch_click), V2(20, y))

        self.redraw()
Ejemplo n.º 11
0
def sliderThread(name, frame, boxes):
    logging.info("Thread %s : starting...", name)
    for (x, y, window) in Slider(frame, name, stepSize=16, windowSize = (64, 64)):# name is a numerical value that determines what row this thread should handle
        ex_features, ex_hog_image = hog(window, orientations=8, pixels_per_cell=(16, 16), cells_per_block=(1, 1), visualize=True, multichannel = True)
        arr = ex_features.reshape(1, -1)
        if(arr.shape == (1, 128)):
            if bc.predict(arr):
                boxes.append((x, y, window))
Ejemplo n.º 12
0
 def __init__(self):
     self.running = True
     self.numLoops = 300  # the number of times to loop around the circle
     self.step = 0.05  # take little steps
     self.spinAngle = 0.0
     self.controls: Dict[str, Control] = {
         "lblNumerator": Label((10, 14), "Numerator:"),
         "Numerator": Slider((150, 20), 1, 10, 4.3, 0.1),
         "lblDenominator": Label((10, 44), "Denominator:"),
         "Denominator": Slider((150, 50), 1, 10, 7.6, 0.1),
         "lblSpinning": Label((10, 80), "Spin?"),
         "Spinning": Checkbox((150, 80), True),
         "lblSpeed": Label((10, 104), "Spin speed:"),
         "Speed": Slider((150, 110), 1, 50, 3, 1),
         "lblScale": Label((10, 144), "Scale:"),
         "Scale": Slider((150, 150), 50, 380, 200, 10),
         "Color": Button((150, 200), "Change Color", Program.ChangeColor),
     }
Ejemplo n.º 13
0
    def __init__(self, data_path, params, search_params, threshold):
        # initialize helpers class
        self.FE = FeatureExtraction(params)
        self.Tr = Train(self.FE, data_path)
        self.SL = Slider(self.FE, search_params)
        self.Hr = Heater(threshold)

        # initialize the model and scaler
        self.clf, self.scaler = self.Tr.run()
Ejemplo n.º 14
0
def startGame():
    global ticks 
    global mapWidth
    global mapHeight
    global pps
    global window
    global isPlaying 
    global subText
    global snakeHead
    global isPlayer
    global data
    global highScore
    global score
    global controls
    global sliders
    global preTraining
    global border
    global buttons
    
    
    reset()
    controls = pygame.image.load(dir_path+ '\imgs\controls.png')
    
    buttons = []
    
    buttons.append(Button(0, 480, 481, 60, "Pause", subText, (255,255,255), "pause"))
    buttons.append(Button(0, 541, 481, 60, "Menu", subText, (255,255,255), "menu"))
    if (not (isPlayer) and sliders == []):
        sliders.append(Slider(500, 20, 300, 20, 'ticks', (100, 40), 'Ticks', subText))
    
    
    
    border = pygame.Rect(0-borderWidth, 0-borderWidth, mapWidth*pps+(2*borderWidth), mapHeight*pps+(2*borderWidth))
    isPlaying = True
    
    clock = pygame.time.Clock()
    window.fill((0,0,0))
    
    update(buttons, sliders)
    if (not preTraining):
        snakeHead.addTail(direction)
    while isPlaying:
        if (preTraining or not isPlayer):
            isPlaying = False
            return 
        else:
            clock.tick(ticks)
            update(buttons, sliders)
        
    if (not preTraining):
        lost = subText.render('GAME OVER', True, (200,200,200))
        if (score > highScore):
            highScore = score
        window.blit(lost, (180, 200))
        pygame.display.update()
        titleScreen()
    return
Ejemplo n.º 15
0
def test_cases_with_html(tmpdir, name):
    slider = Slider()

    pages = slider.parse(os.path.join('cases', '{}.md'.format(name)))
    with open(os.path.join('cases', 'dom', '{}.json'.format(name))) as fh:
        assert pages == json.load(fh)

    target_dir = str(tmpdir)
    print(target_dir)
    slider.generate_html_files(target_dir)
    compare_dirs(target_dir, os.path.join('cases', 'html', name), name)
Ejemplo n.º 16
0
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        self.defaultVideoCapture = VideoCapture(0)

        self.webcamCanvas = Canvas(self.parent, self.defaultVideoCapture)
        self.maskCanvas = Canvas(self.parent, self.defaultVideoCapture)

        self.lowHueSlider = Slider(self.parent, "Low Hue", 10, 0, 180)
        self.highHueSlider = Slider(self.parent, "High Hue", 25, 0, 180)
        self.lowSaturationSlider = Slider(self.parent, "Low Saturation", 100,
                                          0, 255)
        self.highSaturationSlider = Slider(self.parent, "High Saturation", 255,
                                           0, 255)
        self.lowValueSlider = Slider(self.parent, "Low Value", 20, 0, 255)
        self.highValueSlider = Slider(self.parent, "High Value", 255, 0, 255)

        self.button = tk.Button(self.parent,
                                text="Get histogram",
                                fg="blue",
                                command=self.drawHSVHHistogram)
        self.button.pack(anchor=tk.CENTER)

        self.updateFrame()
Ejemplo n.º 17
0
    def __init__(self, filepath, **kwargs):
        super(Homepage, self).__init__(**kwargs)

        self.filepath = filepath
        self.filename = filepath.replace('.', '/').split('/')[-2]

        Window.clearcolor = (0.2, 0.2, 0.2, 1)
        self.color_switch = Switch()
        self.canvas.add(self.color_switch)

        # LEFT IMAGE #
        im = Image.open(filepath).convert("RGBA")
        self.image = im.copy()
        width, height = self.image.size
        self.w_h_ratio = width / height
        self.image_rect = Rectangle(texture=CoreImage(self.filepath).texture)
        self.canvas.add(self.image_rect)

        # CENTER PIXELATED IMAGE & SLIDER #
        self.pixeate_image = im.copy()
        self.pixelate_rect = Rectangle()
        self.canvas.add(self.pixelate_rect)
        self.value = None
        self.pixel_slider = Slider(
            1, ((Window.width - self.image_rect.size[0]) // 2,
                (Window.height - self.image_rect.size[1]) // 2),
            self.pixelate_rect.size)

        self.generate_pressed = False
        self.generate_button = Rectangle(
            texture=CoreImage('./buttons/generate_button.png').texture)
        self.canvas.add(self.generate_button)

        # RIGHT DOMINO IMAGE #
        self.domino_image = Image.new(mode='RGBA',
                                      size=(width, height),
                                      color=(235, 74, 90, 150))
        data = BytesIO()
        self.domino_image.save(data, format='png')
        data.seek(0)
        self.domino_rect = Rectangle(
            texture=CoreImage(BytesIO(data.read()), ext='png').texture)
        self.canvas.add(self.domino_rect)

        self.label = Label()
        self.add_widget(self.label)

        self.imgSmall = None

        self.on_update()
        self.on_layout((Window.width, Window.height))
Ejemplo n.º 18
0
    def __init__(self, ctl_settings, screen, label, top_y, wall_index):
        super().__init__(ctl_settings, screen, label, top_y)
        self.wall_index = wall_index
        self.wall_label = "Wall " + str(wall_index + 1)

        # sensor reading

        self.sensor_reading = DisplayValue(ctl_settings,
                                           self.screen,
                                           40,
                                           self.rect.bottom - self.padding,
                                           wall_index=wall_index,
                                           title='Sensor')

        self.slider_spacing = 50  # distance between sliders

        # fix the way wall number is added to message (move to slider.py?)
        self.slider_bottom = self.rect.bottom - self.padding

        micGainSL = Slider(self.ctl_settings, self.screen, 0, 1,
                           self.sensor_reading.rect.right + 10,
                           self.slider_bottom, '/micGain', wall_index, 'log')
        hpCutoffSL = Slider(self.ctl_settings, self.screen, 0, 10000,
                            micGainSL.rect.right + self.slider_spacing,
                            self.slider_bottom, '/hpCutoff', wall_index, 'exp')
        lpCutoffSL = Slider(self.ctl_settings, self.screen, 0, 20000,
                            hpCutoffSL.rect.right + self.slider_spacing,
                            self.slider_bottom, '/lpCutoff', wall_index, 'exp')
        resSL = Slider(self.ctl_settings, self.screen, 0, 1,
                       lpCutoffSL.rect.right + self.slider_spacing,
                       self.slider_bottom, '/res', wall_index, 'log')
        thresholdSL = Slider(self.ctl_settings, self.screen, 0.1, 50,
                             resSL.rect.right + self.slider_spacing,
                             self.slider_bottom, '/threshold', wall_index,
                             'linear')
        packetLengthSL = Slider(self.ctl_settings, self.screen, 0, 1000,
                                thresholdSL.rect.right + self.slider_spacing,
                                self.slider_bottom, '/packetLength',
                                wall_index, 'linear')
        delayLengthSL = Slider(self.ctl_settings, self.screen, 0, 10000,
                               packetLengthSL.rect.right + self.slider_spacing,
                               self.slider_bottom, '/delayLength', wall_index,
                               'linear')

        # Add all sliders to this list
        self.sliders = [
            micGainSL, hpCutoffSL, lpCutoffSL, resSL, thresholdSL,
            packetLengthSL, delayLengthSL
        ]

        # prep wall label
        self.prep_wall_label()
Ejemplo n.º 19
0
def test_other_dir(tmpdir):
    root = str(tmpdir)
    cwd = os.getcwd()
    os.chdir(root)
    from slider import Slider, SliderError
    slider = Slider()

    target_dir = os.path.join(root, 'html')
    os.mkdir(target_dir)
    pages = slider.parse(os.path.join(cwd, 'cases', 'all.md'))
    slider.generate_html_files(target_dir)
    compare_dirs(target_dir, os.path.join(cwd, 'cases', 'html', 'all'), 'all')

    data = slider.process_yml(os.path.join(cwd, 'cases', 'multi.yml'))
    assert data == {}

    os.chdir(cwd)
Ejemplo n.º 20
0
def test_md_to_html_no_file_extension(tmpdir, name):
    slider = Slider()

    md_file = os.path.join('cases', 'input', '{}.md'.format(name))
    pages = slider.parse(md_file)
    with open(os.path.join('cases', 'output', 'dom',
                           '{}.json'.format(name))) as fh:
        assert pages == json.load(fh)

    target_dir = str(tmpdir)
    print(target_dir)

    html = OnePage(
        chapter=pages,
        includes=os.path.dirname(md_file),
    )
    html.generate_html_files(target_dir)
    compare_dirs(target_dir, os.path.join('cases', 'output', 'plain_html',
                                          name), name)
Ejemplo n.º 21
0
    def init_sliders(self):
        self.sliders.append(
            Slider(-5000, (-10000, 5000), 'g', (0, 5), "Gravity"))
        self.sliders.append(Slider(.1, (-1.0, 1.0), 'k', (0, 35), "Spring"))
        self.sliders.append(Slider(.6, (0, 1.0), 'd', (0, 65), "Dampening"))

        self.color_sliders.append(
            Slider(150, (0, 255), 'red', (0, 5), "red", (100, 10),
                   (255, 0, 0)))
        self.color_sliders.append(
            Slider(150, (0, 255), 'green', (0, 35), "green", (100, 10),
                   (0, 255, 0)))
        self.color_sliders.append(
            Slider(150, (0, 255), 'blue', (0, 65), "blue", (100, 10),
                   (0, 0, 255)))
Ejemplo n.º 22
0
def test_exceptions(tmpdir):
    slider = Slider()
    path = os.path.join('cases', 'no-chapter-title.md')
    with pytest.raises(Exception) as exinfo:
        slider.parse(path)
    assert exinfo.type == SliderError
    assert str(exinfo.value) == 'Chapter title is missing in {}'.format(path)


    path = os.path.join('cases', 'no-chapter-id.md')
    with pytest.raises(Exception) as exinfo:
        slider.parse(path)
    assert exinfo.type == SliderError
    assert str(exinfo.value) == 'Chapter id is missing in {}'.format(path)


    path = os.path.join('cases', 'chapters.md')
    with pytest.raises(Exception) as exinfo:
        slider.parse(path)
    assert exinfo.type == SliderError
    assert str(exinfo.value) == 'Second chapter found in the same file in {}'.format(path)
Ejemplo n.º 23
0
def test_other_dir(tmpdir):
    root = str(tmpdir)
    original = os.getcwd()
    with cwd(root):
        slider = Slider()

        target_dir = os.path.join(root, 'html')
        os.mkdir(target_dir)
        md_file = os.path.join(original, 'cases', 'input', 'all.md')
        pages = slider.parse(md_file)
        with open(os.path.join(original, 'cases/output/dom/all.json')) as fh:
            expected = json.load(fh)
        assert expected == pages

        html = OnePage(
            chapter=pages,
            includes=os.path.dirname(md_file),
            ext='html',
        )

        html.generate_html_files(target_dir)
        compare_dirs(target_dir,
                     os.path.join(original, 'cases', 'output', 'html', 'all'),
                     'all')
Ejemplo n.º 24
0
def main():
    mouseDown = False

    pygame.init()
    screen = makeWindow((600, 400))

    maxParticlesSlider = Slider(100, 1, 450, 10, 100, "maxParticles")
    gravityXSlider = Slider(0.5, -0.5, 450, 50, 100, "gravityX")
    gravityXSlider.t = 0.5
    gravityYSlider = Slider(0.5, -0.5, 450, 90, 100, "gravityY")
    gravityYSlider.t = 0.5
    frictionSlider = Slider(1, 0, 450, 130, 100, "friction")
    minSizeSlider = Slider(20, 5, 450, 170, 100, "minSize")
    thetaSlider = Slider(360, 0, 450, 210, 100, "theta")
    velocitySlider = Slider(10, 0.5, 450, 250, 100, "velocity")

    emitter = Emitter(1, 15, 20, 5, 0.15, Particle, [200, 200])

    walls = []
    walls.append(Wall([10, 390], [390, 390], True))
    walls.append(Wall([10, 10], [10, 390], True))
    walls.append(Wall([10, 10], [390, 10], False))
    walls.append(Wall([390, 390], [390, 10], True))
    walls.append(Wall([200, 390], [390, 200], True))

    running = True
    while running:
        screen.fill((0, 0, 0))
        emitter.update(round(maxParticlesSlider.getValue()), round(minSizeSlider.getValue()), round(thetaSlider.getValue()), velocitySlider.getValue())
        for particleI in emitter.particles:
            particleI.update(walls, (gravityXSlider.getValue(), gravityYSlider.getValue()), frictionSlider.getValue())
            pygame.draw.circle(screen, (255, 255, 255), (particleI.position.x, particleI.position.y), particleI.size, 1)
        
        for wall in walls:
            pygame.draw.line(screen, (255, 255, 255), (wall.start.x, wall.start.y), (wall.end.x, wall.end.y), 1)
        
        for wall in walls:
            pygame.draw.line(screen, (255, 0, 0), (wall.start.x, wall.start.y), (wall.start.x + wall.normal.x * 10, wall.start.y + wall.normal.y * 10), 1)

        maxParticlesSlider.drawSlider(screen)
        gravityXSlider.drawSlider(screen)
        gravityYSlider.drawSlider(screen)
        frictionSlider.drawSlider(screen)
        minSizeSlider.drawSlider(screen)
        thetaSlider.drawSlider(screen)
        velocitySlider.drawSlider(screen)

        if mouseDown:
            pos = pygame.mouse.get_pos()
            maxParticlesSlider.setT(pos[0], pos[1])
            gravityXSlider.setT(pos[0], pos[1])
            gravityYSlider.setT(pos[0], pos[1])
            frictionSlider.setT(pos[0], pos[1])
            minSizeSlider.setT(pos[0], pos[1])
            thetaSlider.setT(pos[0], pos[1])
            velocitySlider.setT(pos[0], pos[1])

        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouseDown = True
            if event.type == pygame.MOUSEBUTTONUP:
                mouseDown = False

        time.sleep(0.0166)
Ejemplo n.º 25
0
def main():
    proxSensor = proximitySensor()
    contScale = False
    minDist = 0
    maxIndex = 0
    if '-d' in argv:
        minDist = 5000
        maxDist = 30000
    else:
        minDist, maxDist = proxSensor.initialize()
    err = 50
    if '-e' in argv:
        err = int(raw_input("Please enter an error threshold"))
    print str(minDist) + ' ' + str(maxDist)
    raw_input('Press any key to continue')
    stepLength = maxDist - minDist
    scaleFactor = 220.0 / stepLength
    stepLength /= 8
    note = ' '

    last = -1
    first = None

    pitchSlider = Slider(err, minDist, True, False, 150, 0, "pitch")

    lastVolume = 1.0
    timing = False
    vstartTime = 0
    vstart = 0
    vcontrolenabled = True

    wav.out()
    stopped = False
    pitchBendEnable = True
    #main loop
    while True:
        ret, orgframe, cframe = proxSensor.setFrame(show)
        if not ret:
            continue

        #frames for displaying
        orgpframe = orgframe[100:400, 500:900]
        orgvframe = orgframe[0:100, 300:500]
        orgframe = orgframe[100:300, 100:300]

        #cropping frame for more accurate detection
        thresh, curr, numcnts = proxSensor.getValcropped(100, 300, 100, 300)
        vthresh, vcurr, vnumcnts = proxSensor.getValcropped(0, 100, 300, 500)
        pitchframe = cframe[100:400, 500:900]
        pnumcnts, pitchBend, _ = pitchSlider.getVal(pitchframe, orgpframe)
        cv2.imshow('vthresh', vthresh)

        #changes amplitude when the object in the detection zone is still
        estimate = int(lastVolume)
        if vcontrolenabled and vnumcnts < err:
            if timing:
                if abs(vstart - vcurr) > 500:
                    timing = False
                else:
                    if time() - vstartTime >= 2 and vcurr >= minDist / 2:
                        timing = False
                        lastVolume = 10 * (vcurr -
                                           (minDist / 2)) / (maxDist / 2)
                    estimate = int(10 * (vcurr - (minDist / 2)) /
                                   (maxDist / 2))
            else:
                timing = True
                vstartTime = time()
                vstart = vcurr
        else:
            timing = False
        s.setAmp(lastVolume)

        #Setting frequency based off of distance
        #normal mode sets frequency to one of the frequencies in the
        #dictionary. Continuous mode maps the frequency to the range
        #220Hz(a) to 440Hz(HighA)
        if abs(curr - last) > 10:
            f = curr - minDist
            if contScale:
                f = 220 + scaleFactor * f
                note = str(f) + 'Hz'
                pitchBend = 0
            else:
                f /= stepLength
                f = int(f)
                f %= 8
                if curr > maxDist:
                    f = 7
                if curr < minDist:
                    f = 0
                keys = notes.keys()
                keys.sort()
                temp = f
                note = keys[f]
                f = notes[note]

                #pitchbend
                if pitchBendEnable and pnumcnts < err and pitchBend != 0:
                    if pitchBend < 150:
                        upper = 0
                        if temp + 1 > 7:
                            upper = f + 100
                        else:
                            upper = keys[temp + 1]
                            upper = notes[upper]
                        upper = upper - f
                        pitchBend = upper - pitchBend * (upper / 150)
                    else:
                        lower = 0
                        if temp - 1 < 0:
                            lower = f - 100
                        else:
                            lower = keys[temp - 1]
                            lower = notes[lower]
                        lower = f - lower
                        pitchBend = -1 * (pitchBend - 150) * (lower / 150)
                    f += pitchBend
                else:
                    pitchBend = 0

            #invalid detection
            if numcnts > err or curr < minDist / 2:
                f = 0
                note = " "

            cls()
            print 'current note: ' + note
            print 'pitch bend: ' + str(pitchBend)
            print 'amp: ' + str(lastVolume)
            print 'changing amp: ' + str(timing) + ' time remaining: ' + str(
                5 - time() + vstartTime)
            if timing:
                print 'projected new amp: ' + str(estimate)

            #change frequencies incrementally
            f = 2 * Pi * f
            oldFreq = wav.freq
            if oldFreq != 0:
                while abs(oldFreq - f) > 0.05:
                    #oldFreq = (oldFreq+f)/2
                    if oldFreq < f:
                        oldFreq += 0.05
                    else:
                        oldFreq -= 0.05
                    wav.setFreq(oldFreq)
            wav.setFreq(f)
        last = curr

        #useful for debugging
        if show:
            cv2.imshow("t", thresh)

        cv2.imshow("Theremin", orgframe)
        k = cv2.waitKey(30)

        #keyboard controls
        if k == ord('q'):
            return
        elif k == ord('c'):
            contScale = not contScale
        elif k == ord('m'):
            if stopped:
                wav.out()
                stopped = False
            else:
                wav.stop()
                stopped = True
        elif k == ord('p'):
            pitchBendEnable = not pitchBendEnable
        elif k == ord('v'):
            vcontrolenabled = not vcontrolenabled
        elif k == ord(']') and not vcontrolenabled:
            lastVolume += 0.5
        elif k == ord('[') and not vcontrolenabled:
            lastVolume -= 0.5
        elif k == ord('\\'):
            lastVolume = int(lastVolume)
Ejemplo n.º 26
0
    def __init__(self,
                 interactor,
                 value,
                 min_val,
                 max_val,
                 label,
                 on_show_slider=None,
                 update=None,
                 end=None,
                 corner_radius=5,
                 width=None,
                 height=None,
                 left=0,
                 top=0,
                 image=None,
                 bgcolor=(.5, .5, .5),
                 fgcolor=(1, 1, 1),
                 font="Arial",
                 opacity=1,
                 size=14,
                 states=None,
                 halign=LEFT_ALIGN,
                 valign=CENTER_ALIGN,
                 point1=(0, .1),
                 point2=(1, .1)):

        self.slider = Slider(interactor,
                             update=update,
                             end=end,
                             title=label,
                             value=value,
                             min_val=min_val,
                             max_val=max_val,
                             point1=point1,
                             point2=point2)

        def _show_slider():
            if on_show_slider:
                on_show_slider()
            self.slider.show()

        super(SliderButton, self).__init__(interactor,
                                           label,
                                           on=_show_slider,
                                           off=self.slider.hide,
                                           corner_radius=corner_radius,
                                           width=width,
                                           height=height,
                                           left=left,
                                           top=top,
                                           image=image,
                                           bgcolor=bgcolor,
                                           fgcolor=fgcolor,
                                           font=font,
                                           opacity=opacity,
                                           size=size,
                                           states=states,
                                           on_prefix="Show",
                                           off_prefix="Hide",
                                           halign=halign,
                                           valign=valign)
Ejemplo n.º 27
0
    def __init__(self, ctl_settings, screen, label, top_y, height, fullsize):
        super().__init__(ctl_settings, screen, label, top_y, height, fullsize)

        self.timer = False

        self.padding = 50  # custom padding here

        self.button_x_spacing = 30

        # add slider to control playback speed: ctl_settings.bpm
        self.slider_bottom = self.rect.bottom - 10

        self.BPM = Slider(self.ctl_settings, self.screen, 0, 200,
                          self.rect.left + self.button_x_spacing,
                          self.slider_bottom, 'BPM', 'linear')
        self.BPM.automate(30)  # set initial value

        # Display buttons in sequencer - to show sequence
        row1_y = self.rect.top + self.padding
        pb1 = Button(ctl_settings, screen,
                     self.BPM.rect.right + self.button_x_spacing, row1_y, '1')
        pb2 = Button(ctl_settings, screen,
                     pb1.rect.right + self.button_x_spacing, row1_y, '2')
        pb3 = Button(ctl_settings, screen,
                     pb2.rect.right + self.button_x_spacing, row1_y, '3')
        pb4 = Button(ctl_settings, screen,
                     pb3.rect.right + self.button_x_spacing, row1_y, '4')
        pb5 = Button(ctl_settings, screen,
                     pb4.rect.right + self.button_x_spacing, row1_y, '5')
        pb6 = Button(ctl_settings, screen,
                     pb5.rect.right + self.button_x_spacing, row1_y, '6')
        pb7 = Button(ctl_settings, screen,
                     pb6.rect.right + self.button_x_spacing, row1_y, '7')
        pb8 = Button(ctl_settings, screen,
                     pb7.rect.right + self.button_x_spacing, row1_y, '8')

        self.buttons = [pb1, pb2, pb3, pb4, pb5, pb6, pb7,
                        pb8]  # add all buttons here

        # Control buttons in sequencer - to show sequence
        row2_y = pb1.rect.bottom + 13
        brick1 = Button(ctl_settings, screen,
                        self.BPM.rect.right + self.button_x_spacing, row2_y,
                        'brick')
        brick2 = Button(ctl_settings, screen,
                        brick1.rect.right + self.button_x_spacing, row2_y,
                        'brick')
        brick3 = Button(ctl_settings, screen,
                        brick2.rect.right + self.button_x_spacing, row2_y,
                        'brick')
        brick4 = Button(ctl_settings, screen,
                        brick3.rect.right + self.button_x_spacing, row2_y,
                        'brick')
        brick5 = Button(ctl_settings, screen,
                        brick4.rect.right + self.button_x_spacing, row2_y,
                        'brick')
        brick6 = Button(ctl_settings, screen,
                        brick5.rect.right + self.button_x_spacing, row2_y,
                        'brick')
        brick7 = Button(ctl_settings, screen,
                        brick6.rect.right + self.button_x_spacing, row2_y,
                        'brick')
        brick8 = Button(ctl_settings, screen,
                        brick7.rect.right + self.button_x_spacing, row2_y,
                        'brick')
        self.brick_buttons = [
            brick1, brick2, brick3, brick4, brick5, brick6, brick7, brick8
        ]
Ejemplo n.º 28
0
from vec2d import Vec2d
from coords import Coords
from circle import Circle
from random import uniform, randint, random
from slider import Slider

# Define some colors
BLACK    = (   0,   0,   0)
WHITE    = ( 255, 255, 255)
GREEN    = (   0, 255,   0)
RED      = ( 255,   0,   0)
BLUE     = (   0,   0, 255)
GRAY     = ( 127, 127, 127)

# The slider to enter the mass of new objects
massSlider = Slider(0.3, 0.8, 30, (30, 80), (300, 5))
centerMass = 0
centerVelocity = 0


def center(objects):
    mass = 0
    rmass = 0
    vmass = 0
    
    for i1, obj1 in enumerate(objects):
        r = obj1.pos
        rmass += r * obj1.mass
        mass += obj1.mass
        vmass += obj1.vel * obj1.mass
    
Ejemplo n.º 29
0
def test_multi():
    slider = Slider()

    data = slider.process_yml(os.path.join('cases', 'multi.yml'))
    assert data == {}
Ejemplo n.º 30
0
def test_cases(name):
    slider = Slider()
    pages = slider.parse(os.path.join('cases', '{}.md'.format(name)))
    with open(os.path.join('cases', 'dom', '{}.json'.format(name))) as fh:
        assert pages == json.load(fh)