def create_root_volume(self, defaults): """ Create a root volume for the vFiler if one hasn't been manually defined """ log.debug("No manually defined root volume. Creating one...") ns = self.populate_namespace() try: volname = defaults.get('vfiler', 'root_volume_name') % ns except (NoSectionError, NoOptionError): volname = '%s_root' % self.name pass # FIXME: This can probably be improved somehow usable = float(defaults.get('vfiler', 'root_volume_usable')) aggr = self.get_root_aggregate() log.debug("got root aggr") xmldata = """<volume type="root" name="%s" usable="%s" raw="%s" /> """ % (volname, usable, usable) node = etree.fromstring(xmldata) vol = Volume() vol.configure_from_node(node, defaults, aggr) vol.snapreserve = int(defaults.get('vfiler', 'root_volume_snapreserve')) vol.space_guarantee = 'volume' if defaults.getboolean('vfiler', 'backup_root_volume'): log.warn("Request to back up vfiler root volume") log.debug("Root volume: %s", vol) # Add the volume as a child of the root aggregate aggr.add_child(vol) pass
def generate(self): self.states = [] # Generate all quantities for each state. states_q = itertools.product(Inflow.get_quantities(), Volume.get_quantities(), Outflow.get_quantities()) # Create objects for each state. for state_q in states_q: self.states.append( State(Inflow(state_q[0], None), Volume(state_q[1], None), Outflow(state_q[2], None))) print "[trace] - Generate states - remove constraints" self.remove_inconsistencies() print "[trace] - Generate states - Calculate derivitives" self.calc_derives() print "[trace] - Generate states - Unpack the inflow derivitives" self.unpack_inflow() print "[trace] - Generate states - Set state ids" # At this point all valid states are created and should receive an id for i, state in enumerate(self.states): state.set_id(i) print "[trace] - Create paths - Start" self.create_paths() print "[trace] - Create paths - End" return self.states, self.paths
def __init__(self, oled, hyp): logger.info("Initializing hardware") import RPi.GPIO as GPIO import smbus self.bus = smbus.SMBus(1) # Rev 2 Pi self.outPa = 18 #Relais für PA2200 self.outTv = 16 #Relais für TV und Sony-Verstärker self.outPhono = 33 #Relais für Phono-Preamp Power self.Out_pwr_rel = 29 #Relais für Ampi-Ringkerntrafo self.inMcpInt = 37 self.inVolDir = 36 self.inVolClk = 7 self.inVolMute = 15 self.validSources = [ 'Aus', 'CD', 'Schneitzlberger', 'Portable', 'Hilfssherriff', 'Bladdnspiela', 'Himbeer314' ] self.source = "Aus" self.ampPwr = False self.tvPwr = False self.oled = oled #OLED-Objekt erzeugen self.hyp = hyp #Hyperion-Objekt erzeugen self.kodi = Kodi("http://localhost/jsonrpc") self.initGpios() #GPIOs initialisieren self.volume = Volume(self.oled, self.bus) #Volumen-Objekt erzeugen self.sources = Sources(self.oled, self.bus) #Quellen-Objekt erzeugen
def consistencygroup_list(args): obj = ConsistencyGroup(args.ip, args.port) try: uris = obj.list(args.project, args.tenant) output = [] rawoutput = [] for uri in uris: cg = obj.show(uri, args.project, args.tenant) if (cg): rawoutput.append(cg) from volume import Volume from storagesystem import StorageSystem cg["system_consistency_groups"] = " " if ("volumes" in cg): volumeuris = common.get_node_value(cg, "volumes") volobj = Volume(args.ip, args.port) volumenames = [] for volume in volumeuris: vol = volobj.show_by_uri(volume['id']) if (vol): volumenames.append(vol['name']) cg['volumes'] = volumenames volumenames = [] output.append(cg) if (not args.verbose): if (len(output)): TableGenerator(output, ['name', 'volumes']).printTable() else: if (len(rawoutput)): return common.format_json_object(rawoutput) except SOSError as e: raise SOSError(SOSError.SOS_FAILURE_ERR, "Consistency Group List failed:\n" + e.err_text)
def demand_volume(self): """Generates lines for demand volume constraints""" for sn in range(1, self.n_source_nodes+1): for dn in range(1, self.n_destination_nodes+1): volume = Volume(self.n_transit_nodes) volume.create_constraint(sn, dn) self.add_line(volume)
def run(self, *args, **kwargs): while True: df = LoadNet().get_QVIX() self.update_qvix.emit(df) df_north = LoadNet().get_north() self.update_north.emit(df_north) df_vol, cha = Volume().update() data, last = LoadNet().get_50_163() ser = (data['current'] - last) / last self.update_vol.emit(df_vol, ser) if not self.data_model.df_op.empty: df_month = self.data_model.iv_month_50300() self.update_month.emit(df_month) df_iv50, df_iv300 = self.data_model.get_iv() self.update_iv.emit(df_iv50, df_iv300) hp = HoldPositions() greek = hp.update(self.data_model.df_op) self.update_greek.emit(greek) time.sleep(3)
def __init__(self, master): # create GUI self.gpio = pigpio.pi() self.master = master self.master.title('JoyStick Test') label = tk.Label(root, text='Joystick') label.pack() self.gui = GuiRarm(master=root) self.gui.createCordinateLabelServo() self.gui.createButton(btn_name='Finish', callback=self.cleanup) #self.gui.createCircleJs2(200,200,220,220,'blue') #JoyStick instanse self.jsR = JoyStick(-1, 4, 27) self.val_horz = 0 #self.jsL = JoyStick(7,4,22) self.jsL = JoyStick(2, -1, 22) self.val_vert = 0 #Volume instance self.vol = Volume(6) self.val_vol = 0 self.vol_sum = 0 self.sampleCount = 0 #ServMotor #self.servo= ServMotor(18,180,0) self.servo = I2cServo() #PWM Freq: 60Hz self.servo.setPWMFreq(60) # Led instance self.Led = Led(4) self.Led.setLedOn() # PowrSw self.PowSw = Sw(17, pud='pudup') self.PowSwCont = 0
def should_have_printed_usage_instructions(monkeypatch) -> None: print_coloured_calls = [] mock_parse_argv(MODULE_NAME, 'Volume', monkeypatch) monkeypatch.setattr(f"{MODULE_NAME}.print_coloured", lambda *a, **k: print_coloured_calls.append('')) Volume().usage() assert len(print_coloured_calls) == 2
def update(self, name, project, tenant, add_volumes, remove_volumes, sync, synctimeout=0): ''' This function is used to add or remove volumes from consistency group It will update the consistency group with given volumes. parameters: name : Name of the consistency group. project: Name of the project path. tenant: Container tenant name. add_volumes : volumes to be added to the consistency group remove_volumes: volumes to be removed from CG. return returns with status of creation. ''' if (tenant is None): tenant = "" fullproj = tenant + "/" + project projobj = Project(self.__ipAddr, self.__port) projuri = projobj.project_query(fullproj) parms = [] add_voluris = [] remove_voluris = [] #volumes = None from volume import Volume volobj = Volume(self.__ipAddr, self.__port) if (add_volumes): for volname in add_volumes: fullvolname = tenant + "/" + project + "/" + volname add_voluris.append(volobj.volume_query(fullvolname)) volumes = {'volume': add_voluris} parms = {'add_volumes': volumes} if (remove_volumes): for volname in remove_volumes: fullvolname = tenant + "/" + project + "/" + volname remove_voluris.append(volobj.volume_query(fullvolname)) volumes = {'volume': remove_voluris} parms = {'remove_volumes': volumes} body = json.dumps(parms) uri = self.consistencygroup_query(name, project, tenant) (s, h) = common.service_json_request( self.__ipAddr, self.__port, "PUT", self.URI_CONSISTENCY_GROUPS_INSTANCE.format(uri), body, None, None) o = common.json_decode(s) if (sync): return self.check_for_sync(o, sync, synctimeout) else: return o
def generate(self): self.states = [] print "\n[trace] - Generate states - Generate quantity combinations:" # Generate all quantities for each state. states_q = itertools.product(Inflow.get_quantities(), Volume.get_quantities(), Outflow.get_quantities(), Height.get_quantities(), Pressure.get_quantities()) # Create objects for each state. for state_q in states_q: self.states.append( BonusState(Inflow(state_q[0], None), Volume(state_q[1], None), Outflow(state_q[2], None), Height(state_q[3], None), Pressure(state_q[4], None))) pprint.pprint(self.states) print "[trace] - Generate states - " +\ str(len(self.states)) + " current states" print "\n[trace] - Generate states - remove constraints:" self.remove_inconsistencies() pprint.pprint(self.states) print "[trace] - Generate states - " +\ str(len(self.states)) + " current states" print "\n[trace] - Generate states - Calculate derivitives:" self.calc_derives() pprint.pprint(self.states) print "[trace] - Generate states - " +\ str(len(self.states)) + " current states" print "\n[trace] - Generate states - Unpack the inflow derivitives" self.unpack_inflow() print "\n[trace] - Generate states - Set state ids" # At this point all valid states are created and should receive an id for i, state in enumerate(self.states): state.set_id(i) pprint.pprint(self.states) print "[trace] - Generate states - " +\ str(len(self.states)) + " current states" print "\n[trace] - Create paths - Start" self.create_paths() pprint.pprint(self.paths) print "[trace] - Generate states - " +\ str(len(self.paths)) + " current paths" print "[trace] - Create paths - End\n" return self.states, self.paths
def execute(self) -> str: log('Good night!') automations = [ Volume(['0.0']), Bluetooth(['off']), Wifi(['off']), Sleep(), ] for automation in automations: automation.execute() return ''
def should_not_have_parsed_argv_with_wrong_or_no_option( monkeypatch, argv: List[str]) -> None: def mock_raise_error(*args: tuple, **kwargs: dict) -> None: assert kwargs['usage'] is not None raise SystemExit(0) # Controlled early exit monkeypatch.setattr(f"{MODULE_NAME}.raise_error", mock_raise_error) with pytest.raises(SystemExit) as e: Volume(argv) assert e.type == SystemExit assert e.value.code == 0
def convert_unit(self, value, input_unit, output_unit): if self.measurement is 'length': return Length(value, input_unit, output_unit).convert() if self.measurement is 'temperature': return Temperature(value, input_unit, output_unit).convert() if self.measurement is 'area': return Area(value, input_unit, output_unit).convert() if self.measurement is 'volume': return Volume(value, input_unit, output_unit).convert() if self.measurement is 'weight': return Weight(value, input_unit, output_unit).convert() return "Not a valid measurement is entered! Select from : length, temperature, volume, area, weight"
def cross_limit_order(self, bar): buy_cross_price = bar.low_price() # 若买入方向限价单价格高于该价格,则会成交 sell_cross_price = bar.high_price() # 若卖出方向限价单价格低于该价格,则会成交 buy_best_cross_price = bar.open_price() # 在当前时间点前发出的买入委托可能的最优成交价 sell_best_cross_price = bar.open_price() # 在当前时间点前发出的卖出委托可能的最优成交价 #遍历所有的限价单 for order_id, order in self.__working_limit_order.items(): if order.status() == OrderStatus.not_traded: # 委托成功推送到策略 order.set_status(OrderStatus.entrust_traded) self.__strategy.on_order(order) #判断是否会成交 buy_cross = (order.direction() == Direction.buy_direction and order.limit_price() >= buy_cross_price and buy_cross_price > 0) sell_cross = (order.direction() == Direction.sell_direction and order.limit_price() <= sell_cross_price and sell_cross_price > 0) if buy_cross or sell_cross: order.set_status(OrderStatus.all_traded) # 委托推送策略 self.__strategy.on_order(order) vol = Volume() vol.create_trader_id() vol.set_symbol(order.symbol()) vol.set_order_id(order.order_id()) vol.set_direction(order.direction()) vol.set_comb_offset_flag(order.comb_offset_flag()) if buy_cross: vol.set_limit_price( min(order.limit_price(), buy_best_cross_price)) vol.set_amount(order.amount()) vol.set_min_volume(order.min_volume()) else: vol.set_limit_price( max(order.limit_price(), sell_best_cross_price)) vol.set_amount(order.amount()) vol.set_min_volume(order.min_volume()) vol.set_create_time(bar.current_time()) vol.set_margin_ratio(order.margin_ratio()) vol.set_fee(order.fee_ratio()) self.__volume_order[vol.trader_id()] = vol # 成交推送策略 self.__strategy.on_volume(vol, order) if order_id in self.__working_limit_order: del self.__working_limit_order[order_id]
def get_attached_volumes(self, instanceId, latest=False): instance = self.id2inst.get(instanceId, None) if instance == None: raise Exception if latest: self.id2vols.clear() volumes = self.handle.volumes.get_server_volumes(instanceId) vols = [] for volume in volumes: vols.append(Volume(instance, volume)) self.id2vols[instanceId] = vols return self.id2vols[instanceId]
def __init__(self, volume, template, gpu): self.gpu = gpu volume_gpu = gu.to_gpu(volume) self.fwd_plan = Plan(volume.shape, volume.dtype, np.complex64) self.volume_fft = gu.zeros_like(volume_gpu, dtype=np.complex64) fft(volume_gpu, self.volume_fft, self.fwd_plan) self.template_fft = gu.zeros_like(volume_gpu, dtype=np.complex64) self.ccc_map = gu.zeros_like(volume_gpu, dtype=np.float32) self.norm_volume = gu.prod(volume_gpu.shape) #self.scores = gu.zeros_like(volume_gpu, dtype=np.float32) #self.angles = gu.zeros_like(volume_gpu, dtype=np.float32) self.padded_volume = gu.zeros_like(volume_gpu, dtype=np.float32) del volume_gpu self.inv_plan = Plan(volume.shape, np.complex64, volume.dtype) self.template = Volume(template)
def _build_algorithms(self): """ + Description: build algorithms based on data modules. + Input: - + Output: - """ self.algorithms = {} for algo_id, algo_values in self.algorithms_elements.items(): if algo_values[definitions.algorithm] == definitions.crossing_sma: self.algorithms[algo_id] = CrossingSMA(algo_id, algo_values, self.data_modules, self.assets, self.oracle) elif algo_values[definitions.algorithm] == definitions.volume: self.algorithms[algo_id] = Volume(algo_id, algo_values, self.data_modules, self.assets, self.oracle) elif algo_values[ definitions.algorithm] == definitions.twitter_analysis: self.algorithms[algo_id] = TwitterAnalysis( algo_id, algo_values, self.data_modules, self.assets, self.oracle) elif algo_values[ definitions.algorithm] == definitions.virtual_transfer: self.algorithms[algo_id] = VirtualTransfer( algo_id, algo_values, self.data_modules, self.assets, self.oracle, self.world) elif algo_values[definitions.algorithm] == definitions.statarb: self.algorithms[algo_id] = StatArb(algo_id, algo_values, self.data_modules, self.assets, self.oracle, self.world) else: raise ValueError("Bad algorithm: '" + algo_id + "'.") print("\nAlgorithms:") pprint(self.algorithms)
def should_have_executed(monkeypatch) -> None: def mock_build_apple_script(*args: tuple, **kwargs: dict) -> str: assert args[1] == volume_level return apple_script def mock_execute_cmd(*args: tuple, **kwargs: dict) -> str: assert args[0] == ['osascript', '-e', apple_script] return f" {expected_result} " apple_script = next_alphanumeric(16) mock_parse_argv(MODULE_NAME, 'Volume', monkeypatch) mute_logs(MODULE_NAME, monkeypatch) monkeypatch.setattr(f"{MODULE_NAME}.Volume.build_apple_script", mock_build_apple_script) monkeypatch.setattr(f"{MODULE_NAME}.execute_cmd", mock_execute_cmd) volume_level = random.random() expected_result = next_alphanumeric(10) automation = Volume() automation.volume = volume_level automation.execute()
def volume_convert(): volume = Volume() while True: title() option = str(input(''' [1] centimetro cúbico a Litro [2] Litros a centimetro cúbico [3] Milimetros cúbicos a Litros [s]alir ''')).lower() if option == '1': volume.cmAL() elif option == '2': volume.LAcm() elif option == '3': volume.mcAL() elif option == 's': break else: print('Ingreso un dato invalido')
def __init__(self, name, conf, os_auth_info): BaseClient.__init__(self, name, conf, os_auth_info) self.handle = client.Client( os_auth_info["username"], os_auth_info["password"], os_auth_info["tenant_name"], os_auth_info["auth_url"], insecure=True, service_type="compute") # Maybe the client doesn't prefer ssh route self.ssh_info = conf.get("ssh", None) servers = [] try: servers.extend(self.handle.servers.list()) except NotFound: logging.warn("No servers present for client %s" % name) self.pattern = re.compile("^" + os_auth_info["username"] + "-[0-9]{3}") for inst in servers: if not self.pattern.match(inst.name): continue instance = Instance(inst, self.ssh_info) instanceId = instance.get_id() self.id2inst[instanceId] = instance vols = [] try: vols.extend(self.handle.volumes.get_server_volumes(instanceId)) except NotFound: logging.warn("No volume attached for instance %s(%s)" % (instance.get_name(), instance.get_id())) volumes = self.id2vols[instanceId] = [] for vol in vols: volumes.append(Volume(instance, vol))
def split_on_volume(): ''' split text into volume objects ''' with open( 'files/pdfminer/output/ferguson_grand_jury_testimony.txt') as file: volumes = [] recording = False text = file.readlines() for line in text: line_details = get_line_details(line) # split on volumes, where VOLUME [IVX]+ is the only text match = re.match("(VOLUME [IVX]+)", line_details["text"]) if match: volume = Volume() volume.debateSection(match.group(1)) volumes.append(volume) recording = True # get the rest of the text too if recording: volume.full_text.append(line_details) return volumes
def init_vipr_cli_components(self): import common as vipr_utils vipr_utils.COOKIE = None from exportgroup import ExportGroup from host import Host from hostinitiators import HostInitiator from snapshot import Snapshot from virtualarray import VirtualArray from volume import Volume # instantiate a few vipr cli objects for later use self.volume_obj = Volume(self.configuration.vipr_hostname, self.configuration.vipr_port) self.exportgroup_obj = ExportGroup(self.configuration.vipr_hostname, self.configuration.vipr_port) self.host_obj = Host(self.configuration.vipr_hostname, self.configuration.vipr_port) self.hostinitiator_obj = HostInitiator( self.configuration.vipr_hostname, self.configuration.vipr_port) self.varray_obj = VirtualArray(self.configuration.vipr_hostname, self.configuration.vipr_port) self.snapshot_obj = Snapshot(self.configuration.vipr_hostname, self.configuration.vipr_port)
def __init__(self): self.UPDATE_TIME =10000 self.model = DataModel() self.v = Volume() self.hold_positions = HoldPositions() self.colors = ['r','orange','darkgreen','k'] #plt.ion() self.fig = plt.figure(facecolor='darkgray',figsize=(19,10)) plt.tight_layout(pad=1, w_pad=1.0, h_pad=1.0) self.ax_iv50 = self.fig.add_subplot(231) self.ax_iv300 = self.fig.add_subplot(232) self.ax_iv_month = self.fig.add_subplot(233) self.ax_volume =self.fig.add_subplot(236) self.ax_greek =self.fig.add_subplot(235) self.ax_QVIX =self.fig.add_subplot(234) # t= threading.Thread(target=self.loop) # t.start() timer = self.fig.canvas.new_timer(interval=self.UPDATE_TIME) timer.add_callback(self.loop) timer.start() plt.show()
class Scraper: volume = Volume() CURRENT_VOLUME = volume.get_volume() WEB_LINKS = {"flashscore": "https://www.soccer24.com/"} def scrape(self): # CONNECT THE DATABASE connector = sqlite3.connect('games-db') cursor = connector.cursor() cursor.execute('DROP TABLE IF EXISTS allGames') cursor.execute( 'CREATE TABLE allGames(time TEXT, home_team TEXT, away_team TEXT, ' 'result TEXT, home_odd REAL, draw_odd REAL, away_odd REAL)') # OPEN THE WEBSITE AND GET THE DATA options = ChromeOptions() options.headless = True driver = Chrome(options=options, executable_path='C://Windows/chromedriver.exe') driver.get(self.WEB_LINKS["flashscore"]) sleep(1) html = driver.execute_script( "return document.documentElement.outerHTML;") driver.find_element_by_xpath( '/html/body/div[4]/div[1]/div/div[1]/div[2]/div[4]/div[2]/div[1]/div[2]/div[3]/div' ).click() sleep(1) html_tomorrow = driver.execute_script( "return document.documentElement.outerHTML;") # CLOSE THE BROWSER driver.close() # WORK WITH THE DATA AND GET THE GAMES soup = bs4.BeautifulSoup(html, 'html.parser') soup2 = bs4.BeautifulSoup(html_tomorrow, 'html.parser') matches = soup.find_all(class_=re.compile("event__match")) matches_tomorrow = soup2.find_all(class_=re.compile("event__match")) all_games = [ list(game) for game in matches if 'event__match--scheduled' in str(game) ] all_games_tomorrow = [ list(game) for game in matches_tomorrow if 'event__match--scheduled' in str(game) ] all_games += all_games_tomorrow print(len(all_games)) # INSERT THE GAMES INTO THE DATABASE for game in all_games: game = game[1:] items = { "time": "", "home": "", "away": "", "home_odd": "", "draw_odd": "", "away_odd": "" } for element in game: # GET THE START HOUR if "event__time" in str(element): pattern = r'(\d+[:]\d{2})' time = re.search(pattern, str(element)) items["time"] = time.group() # GET THE HOME TEAM elif "participant--home" in str(element): pattern = r'\"\>([A-z0-9]+.+)\<\/' home_team = re.search(pattern, str(element)) items["home"] = home_team.group(1) # GET THE AWAY TEAM elif "participant--away" in str(element): pattern = r'\"\>([A-z0-9]+.+)\<\/' away_team = re.search(pattern, str(element)) items["away"] = away_team.group(1) # GET THE HOME ODD elif "o_1" in str(element): pattern = r'\"\>(\d{1,2}\.\d{2})\<\/[s]' try: home_odd = re.search(pattern, str(element)) items["home_odd"] = home_odd.group(1) except AttributeError: items["home_odd"] = "1.00" # GET THE DRAW ODD elif "o_0" in str(element): pattern = r'\"\>(\d{1,2}\.\d{2})\<\/[s]' try: draw_odd = re.search(pattern, str(element)) items["draw_odd"] = draw_odd.group(1) except AttributeError: items["draw_odd"] = "1.00" # GET THE AWAY ODD elif "o_2" in str(element): pattern = r'\"\>(\d{1,2}\.\d{2})\<\/[s]' try: away_odd = re.search(pattern, str(element)) items["away_odd"] = away_odd.group(1) except AttributeError: items["away_odd"] = "1.00" # INSERT THE GAMES INTO THE DATABASE cursor.execute( 'INSERT INTO allGames(time, home_team, away_team, home_odd, draw_odd, away_odd) ' 'VALUES (?, ?, ?, ?, ?, ?)', (items["time"], items["home"], items["away"], items["home_odd"], items["draw_odd"], items["away_odd"])) connector.commit() connector.close()
def __init__(self): # variables ----------------------------------------------- # load background self.backg = Background(BKG_FOLDER + "stars.png") # set initial score self.score = 0 # load sound and music volume from file # if there's a problem with the file, simply create a new one with default values try: volume = pickle.load(open("volume.p", "rb")) except: volume = {"sound": 100, "music": 30} pickle.dump(volume, open("volume.p", "wb")) # sounds self.laserSnd = pygame.mixer.Sound(SND_FOLDER + "laser.wav") self.explodeSnd = pygame.mixer.Sound(SND_FOLDER + "explosion.wav") self.powerUpSnd = pygame.mixer.Sound(SND_FOLDER + "powerUp.wav") # put everything into a list so it's easier to change the volume # the list elements are the same objects as the initial ones # as python copies by reference and not by value (I would have # preferred to use pointers, to avoid ambiguity, but oh well...) self.sounds = [self.laserSnd, self.explodeSnd, self.powerUpSnd] # set volume for all sound objects for snd in self.sounds: snd.set_volume(volume["sound"] / 100.) # set new volume # music self.music = pygame.mixer.music.load(MUS_FOLDER + "reachingForTheSun.mp3") pygame.mixer.music.play(-1) # loop pygame.mixer.music.set_volume(volume["music"] / 100.) # creating user ship self.userShip1 = ShipY001() self.userShip2 = ShipY002() self.userShip3 = ShipY003() self.userShip1.speed = 10 self.userShip2.speed = 10 self.userShip3.speed = 10 # group of all sprites self.userSprites1 = pygame.sprite.Group() self.userSprites2 = pygame.sprite.Group() self.userSprites3 = pygame.sprite.Group() self.laserSprites = pygame.sprite.Group() self.aiSprites = pygame.sprite.Group() self.powerUpSprites = pygame.sprite.Group() # add to groups self.userSprites1.add(self.userShip1) self.userSprites2.add(self.userShip2) self.userSprites3.add(self.userShip3) # Creating main menu self.menu = Menu(["Quit", "Credits", "Volume", "Play"], self.backg) # Creating game_mode self.mode = Menu(["HELL", "HARD", "NORMAL"], self.backg) self.modeBack = 0 # Creating pause menu (could be generated later, but shouldn't impact performance) self.pause = Menu(["Quit", "Volume", "Restart", "Continue"], self.backg) # Creating volume menu (could be generated later, but shouldn't impact performance) self.volume = Volume(self.backg, volume) self.volumeBack = 0 # some stupid flag to tell us whether we came from the main menu # of from the pause menu # Creating credits self.credits = Credits([ "Sound: Obtained from Freesound", "Music: 'Reaching for the Sun' by Deshiel and Bacon92", "Graphics: Filipa Silva", "Code: Alexandre Lopes" ], self.backg) # gameState # Available states: menu, credits ,game, gameOver self.gameState = "menu"
from volume import Volume from firefoxscroll import FirefoxScroll from alttab import AltTab def getPos(arduino): read = arduino.readline() if '@' in read and '%' in read: start = read.index('@') + 1 end = read.index('%', start) return int(read[start:end]) return -1 def moveTo(arduino, pos): arduino.write(str(pos)) plugins = [Plugin(), Volume(), FirefoxScroll(), AltTab()] #setup arduino communication arduino = Serial('/dev/ttyUSB0', 9600) #start program plgn = None pos = 50 running = True program = '' keys = [] #threads class UpdateThread(Thread): def run(self): global pos
def should_have_parsed_argv(argv: List[str], expected_volume_level: float) -> None: volume = Volume(argv) assert volume.argv == argv assert volume.volume == expected_volume_level
def make_volume_object(string): object = Volume(string) object_list.append(object) return object
import scipy.io.wavfile as wavf import numpy as np import math import wave import json import urllib2 import random import subprocess TESTING = True from datetime import timedelta from functools import update_wrapper from volume import Volume v = Volume() app = Flask(__name__) app.config['SECRET_KEY'] = 'qwerqwerqwerqwerqwer' app.config['CORS_HEADERS'] = 'Content-Type' cors = CORS(app, resources={r"/api": {"origins": "http://localhost:port"}}) def crossdomain(origin=None, methods=None, headers=None, max_age=21600, attach_to_all=True, automatic_options=True): if methods is not None: methods = ', '.join(sorted(x.upper() for x in methods)) if headers is not None and not isinstance(headers, basestring): headers = ', '.join(x.upper() for x in headers)
def should_have_built_apple_script(monkeypatch) -> None: volume = random.random() mock_parse_argv(MODULE_NAME, 'Volume', monkeypatch) expected_result = f"set Volume {str(volume)}" assert Volume().build_apple_script(volume) == expected_result