def generate_block(size, num_blocks, seed=0, psco=False, use_storage=True, set_to_zero=False, p_name=''): """ Generate a square block of given size. :param size: <Integer> Block size :param num_blocks: <Integer> Number of blocks :param seed: <Integer> Random seed :param psco: <Boolean> If psco :param use_storage: <Boolean> Use storage :param set_to_zero:<Boolean> Set block to zeros :return: Block (with storage) or np.matrix (otherwise) """ import numpy as np np.random.seed(seed) b = np.matrix(np.random.random((size, size)) if not set_to_zero else np.zeros((size, size))) # Normalize matrix to ensure more numerical precision if not set_to_zero: b /= np.sum(b) * float(num_blocks) if psco: if use_storage: from classes.block import Block else: from classes.fake_block import Block ret = Block() ret.block = b # Hecuba assignment if use_storage: ret.make_persistent(p_name) else: ret = b return ret
def mineRemainingTransactions(self): """Adds all the transaction present in the transaction queue of a blockchain to this block """ block = Block(self.remainingTransactions) block.mineBlock(self.difficulty) self.chain.append(block) print("New block added : {}".format(block.hash))
def handle(_, block: Block, options: list[str]): """Hides or shows blocks based on their tags. Every option with the exception of the last is treated as a tag category. The last option is the tag inside that category.""" if options == []: raise GeneratorError(_EMPTY_TAG_ERROR.format("handler")) command_category = options[:-1] command_tag = options[-1] tag_index = len(options) - 1 for rule in block.get_rules(_NAME): split_description = rule.description.split() if split_description == []: raise GeneratorError(_EMPTY_TAG_ERROR.format("rule"), rule.line_number) if len(split_description) <= tag_index: continue rule_category = split_description[:tag_index] rule_tag = split_description[tag_index] if command_category == rule_category: if command_tag == rule_tag: block.show() else: block.hide() return [block]
def handle(_, block: Block, options: list[str]): """Handles creation of strictness subfilters. Only one option is accepted and it should include the strictness value to use.""" if len(options) != 1: raise GeneratorError( _STRICTNESS_ARG_COUNT_ERROR.format("handler", len(options))) if not options[0].strip().isdigit(): raise GeneratorError( _STRICTNESS_ARG_TYPE_ERROR.format("handler", options[0])) command_strictness = int(options[0]) for rule in block.get_rules(_NAME): if not rule.description.strip().isdigit(): raise GeneratorError( _STRICTNESS_ARG_TYPE_ERROR.format("rule", rule.description), rule.line_number) rule_strictness = int(rule.description) if rule_strictness >= command_strictness: block.show() else: block.hide() return [block]
def persist_result(b, p_name=''): """ Persist results of block b. :param b: Block to persist :return: None """ from classes.block import Block bl = Block() bl.block = b # Hecuba assignment print "YYY " + p_name bl.make_persistent(p_name)
def __init__(self): super(VCGame, self).__init__(255, 255, 255, 255, 800, 600) # 初始化参数 # frames_per_buffer self.numSamples = 1000 # 声控条 self.vbar = Sprite('black.png') self.vbar.position = 20, 450 self.vbar.scale_y = 0.1 self.vbar.image_anchor = 0, 0 self.add(self.vbar) # 皮卡丘类 self.pikachu = Pikachu() self.add(self.pikachu) # cocosnode精灵类 self.floor = cocos.cocosnode.CocosNode() self.add(self.floor) position = 0, 100 for i in range(120): b = Block(position) self.floor.add(b) position = b.x + b.width, b.height # 声音输入 audio = PyAudio() SampleRate = int( audio.get_device_info_by_index(0)['defaultSampleRate']) self.stream = audio.open(format=paInt16, channels=1, rate=SampleRate, input=True, frames_per_buffer=self.numSamples) self.schedule(self.update)
def _get_initial_params(filepath: str, block: Block): name_rules = block.get_rules(_BLOCK_NAME) if len(name_rules) > 0: blockname = name_rules[-1].description.strip() return [_Params(filepath, blockname)] else: return [_Params(filepath)]
def createGenisisBlock(self): """Create the first block (genisis) for the blockchain block Returns: Block: Returns the genisis block """ return Block([Transaction()], "0000")
def handle(_, block: Block, options: list): """Handles creation of economy adjusted filters. Hardcore standard is not supported because poe.ninja doesn't support it. Options: - if 'hc' is passed then the hardcore temp league is queried, if not softcore - if 'std' is passed then standard is queried, if not temp league""" for rule in block.get_rules(_NAME): params = _parse_rule_params(rule) league = _get_league(options) base_types = _get_base_types(league, params["type"], params["lower"], params["upper"]) base_types_string = _get_base_types_string(base_types) block.swap(_BASE_TYPE_IDENTIFIER, base_types_string) if len(base_types) == 0: block.comment() return [block]
def main(): parser = GooeyParser(description='Create_concrete_experiment') parser.add_argument('Experiment_file_name', widget='FileChooser', help='Choose experiment file with general info') parser.add_argument('Participant_ID', type=str) parser.add_argument('Participant_Age', default=0, type=int) parser.add_argument('Participant_Sex', default='M', choices=['M', 'F']) parser.add_argument('Random', default='True', choices=['True', 'False'], help="Present trials in random order") parser.add_argument('EEG_connected', default='0', choices=['1', '0'], help='Choice') parser.add_argument('NIRS_connected', default='0', choices=['1', '0'], help='Choice') args = parser.parse_args() number_of_blocks, data = load_info(args.Experiment_file_name) experiment = Experiment([], args.Participant_ID, args.Participant_Sex, args.Participant_Age, int(args.EEG_connected), int(args.NIRS_connected)) for idx in range(number_of_blocks): block = Block([]) experiment.list_of_blocks.append(block) for idx in range(len(data)): trial_info = data[idx] block_number = trial_info['BLOCK_NUMBER'] if trial_info['SAMPLE_TYPE'] == 'instruction': if trial_info['INSTRUCTION'][-3:] == 'txt': instruction_type = 'text' elif trial_info['INSTRUCTION'][-3:] == 'bmp' or trial_info[ 'INSTRUCTION'][-3:] == 'jpg': instruction_type = 'image' else: raise AssertionError("wrong instruction file type") trial = Instruction(trial_info['INSTRUCTION'], instruction_type, trial_info['STIMTIME']) else: trial = Trial(trial_info['SAMPLE_TYPE'], trial_info['N'], trial_info['NR'], trial_info['STIMTIME'], trial_info['RESPTIME'], trial_info['FEEDB'], trial_info['FEEDB_TIME'], trial_info['WAIT'], trial_info['EXP'], trial_info['BIN'], trial_info['TRAIL_TYPE']) trial.create_sample() experiment.list_of_blocks[block_number - 1].list_of_trials.append(trial) if args.Random: experiment.randomize() experiment.save()
def move(self, direction): # Grid updates itself and snake together. self.body.append(Block(self.grid_location, self.body_image)) # self.parent.update_grid() if self.move_rule == MoveRules.WRAP_AROUND: self.grid_x = (self.grid_x + direction[0]) % grid_dimensions[0] self.grid_y = (self.grid_y + direction[1]) % grid_dimensions[1] else: # separated so you can crash self.grid_x += direction[0] self.grid_y += direction[1]
def add_blocks(self, block_cursor): for element in block_cursor: model = element.pop("block_model", None) x = element.pop(self.data_map["x"], None) y = element.pop(self.data_map["y"], None) z = element.pop(self.data_map["z"], None) weight = element.pop(self.data_map["weight"], None) grades_values = self.get_grade_values(element) new_block = Block(model, x, y, z, weight, grades_values, element) self.blocks.append(new_block)
def create_block(old_coordinates, new_dimensions): new_x = old_coordinates[0] // new_dimensions[0] new_y = old_coordinates[1] // new_dimensions[1] new_z = old_coordinates[2] // new_dimensions[2] new_weight, new_grade_values = self.collect_blocks_information( old_coordinates, new_dimensions) new_blocks.append( Block(self.name, new_x, new_y, new_z, new_weight, new_grade_values, data=None))
def __init__(self): #初始化窗体(R ,G ,B ,Light ,Width, Height) super(eight_note_game, self).__init__(255, 255, 255, 255, 800, 600) # 初始化参数 # frames_per_buffer self.numSamples = 1000 self.trip = 0 #音量条 self.vbar = Sprite("resources/black.png") self.vbar.position = 50, 450 self.vbar.scale_y = 0.1 self.vbar.image_anchor = 0, 0 self.add(self.vbar) # 音量示数 self.label = cocos.text.Label( '音量:', font_name='Times New Roman', #字体样式 font_size=10, #字体大小 color=(0, 0, 0, 255), #字体颜色 anchor_x='center', anchor_y='center' #字体位置 ) self.label.position = 30, 455 self.add(self.label) #输入声音 audio = PyAudio() SampleRate = int(audio.get_default_input_device_info() ['defaultSampleRate']) #读取默认的速率 self.stream = audio.open(format=paInt16, channels=1, input=True, rate=SampleRate, frames_per_buffer=self.numSamples) #创建八分音符酱 self.eight_note = eight_note() self.add(self.eight_note) #创建地板 self.floor = cocos.cocosnode.CocosNode() self.add(self.floor) position = 0, 100 for i in range(200): b = Block(position) self.floor.add(b) position = b.x + b.width, b.height #游戏主循环 self.schedule(self.loop)
def createDirectory(self, name): inode = self.Device.createInode(0, 0) availableBlock = self.Device.getAvailableSpaceInDataBitmap() self.Device.setOcuppiedDataBitmap(availableBlock) block = Block(availableBlock, self.currentDirectory, availableBlock) inode.addBlock(availableBlock) self.Device.saveInodeInDisk(inode) nameSize = len(bytearray(name, "utf8")) if self.currentDirectory is None: self.currentDirectory = block self.currentBlock = availableBlock else: lastDirectory = self.currentDirectory.getLastDirectoryEntries() if lastDirectory: rec_len = lastDirectory.getRecLen() self.currentDirectory.addDirectoryEntry( inode.getId(), rec_len + 64 + nameSize, nameSize, name, inode) else: self.currentDirectory.addDirectoryEntry( inode.getId(), 0, nameSize, name, inode) self.Device.writeObject(block, availableBlock) self.Device.writeObject(self.currentDirectory, self.currentBlock)
def handle(filter: Filter, block: Block, _): """Handles appends of lines to blocks. Options are ignored.""" params = _get_initial_params(filter.filepath, block) lines = _get_lines_from_block(block, params, True) raw_lines = [line.text for line in lines] return Block.extract(raw_lines, block.line_number)
def _get_blockname(block: Block): name_rules = block.get_rules(_BLOCK_NAME) return name_rules[-1].description.strip() if len(name_rules) > 0 else None
from classes.blockchain import Blockchain from classes.block import Block election = Blockchain() election.addBlock(Block(1, "02/02/2020", {"candidate": 1})) election.addBlock(Block(2, "20/02/2020", {"candidate": 2})) print(election.isChainValid())
def startGame(): all_sprites_list = pygame.sprite.RenderPlain() block_list = pygame.sprite.RenderPlain() monsta_list = pygame.sprite.RenderPlain() pacman_collide = pygame.sprite.RenderPlain() wall_list = setupRoomOne(all_sprites_list) gate = setupGate(all_sprites_list) pinky_turn = 0 pinky_steps = 0 blinky_turn = 0 blinky_steps = 0 inky_turn = 0 inky_steps = 0 clyde_turn = 0 clyde_steps = 0 Pacman = Player(w, pacman_height, "images/pacman.png") all_sprites_list.add(Pacman) pacman_collide.add(Pacman) Blinky = Ghost(w, blinky_height, "images/Blinky.png") monsta_list.add(Blinky) all_sprites_list.add(Blinky) Pinky = Ghost(w, monster_height, "images/Pinky.png") monsta_list.add(Pinky) all_sprites_list.add(Pinky) Inky = Ghost(inky_width, monster_height, "images/Inky.png") monsta_list.add(Inky) all_sprites_list.add(Inky) Clyde = Ghost(clyde_width, monster_height, "images/Clyde.png") monsta_list.add(Clyde) all_sprites_list.add(Clyde) # Draw the grid for row in range(19): for column in range(19): if (row == 7 or row == 8) and (column == 8 or column == 9 or column == 10): continue else: block = Block(yellow, 4, 4) # Set a random location for the block block.rect.x = (30 * column + 6) + 26 block.rect.y = (30 * row + 6) + 26 b_collide = pygame.sprite.spritecollide( block, wall_list, False) p_collide = pygame.sprite.spritecollide( block, pacman_collide, False) if b_collide: continue elif p_collide: continue else: # Add the block to the list of objects block_list.add(block) all_sprites_list.add(block) bll = len(block_list) score = 0 done = False i = 0 while done == False: # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT or event.key == ord('a'): Pacman.changespeed(-30, 0) if event.key == pygame.K_RIGHT or event.key == ord('d'): Pacman.changespeed(30, 0) if event.key == pygame.K_UP or event.key == ord('w'): Pacman.changespeed(0, -30) if event.key == pygame.K_DOWN or event.key == ord('s'): Pacman.changespeed(0, 30) if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == ord('a'): Pacman.changespeed(30, 0) if event.key == pygame.K_RIGHT or event.key == ord('d'): Pacman.changespeed(-30, 0) if event.key == pygame.K_UP or event.key == ord('w'): Pacman.changespeed(0, 30) if event.key == pygame.K_DOWN or event.key == ord('s'): Pacman.changespeed(0, -30) # ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT Pacman.update(wall_list, gate) returned = Pinky.changespeed(Pinky_directions, False, pinky_turn, pinky_steps, pinky_movements_list) pinky_turn = returned[0] pinky_steps = returned[1] Pinky.changespeed(Pinky_directions, False, pinky_turn, pinky_steps, pinky_movements_list) Pinky.update(wall_list, False) returned = Blinky.changespeed(Blinky_directions, False, blinky_turn, blinky_steps, blinky_movements_list) blinky_turn = returned[0] blinky_steps = returned[1] Blinky.changespeed(Blinky_directions, False, blinky_turn, blinky_steps, blinky_movements_list) Blinky.update(wall_list, False) returned = Inky.changespeed(Inky_directions, False, inky_turn, inky_steps, inky_movements_list) inky_turn = returned[0] inky_steps = returned[1] Inky.changespeed(Inky_directions, False, inky_turn, inky_steps, inky_movements_list) Inky.update(wall_list, False) returned = Clyde.changespeed(Clyde_directions, "clyde", clyde_turn, clyde_steps, clyde_movements_list) clyde_turn = returned[0] clyde_steps = returned[1] Clyde.changespeed(Clyde_directions, "clyde", clyde_turn, clyde_steps, clyde_movements_list) Clyde.update(wall_list, False) # See if the Pacman block has collided with anything. blocks_hit_list = pygame.sprite.spritecollide(Pacman, block_list, True) # Check the list of collisions. if len(blocks_hit_list) > 0: score += len(blocks_hit_list) # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT screen.fill(black) wall_list.draw(screen) gate.draw(screen) all_sprites_list.draw(screen) monsta_list.draw(screen) text = font.render("Score: " + str(score) + "/" + str(bll), True, red) screen.blit(text, [10, 10]) if score == bll: doNext("Congratulations, you won!", 145, all_sprites_list, block_list, monsta_list, pacman_collide, wall_list, gate) monsta_hit_list = pygame.sprite.spritecollide(Pacman, monsta_list, False) if monsta_hit_list: doNext("Game Over", 235, all_sprites_list, block_list, monsta_list, pacman_collide, wall_list, gate) pygame.display.flip() clock.tick(10)
def concrete_experiment(participant_id, participant_sex, participant_age, file_name, random=1, eeg=0, fnirs=0): experiment_file_name = file_name + ".xlsx" number_of_blocks, data = load_info(experiment_file_name) experiment = Experiment(id=participant_id, sex=participant_sex, age=participant_age, eeg=eeg, fnirs=fnirs) for idx in range(number_of_blocks): block = Block([]) experiment.list_of_blocks.append(block) for idx in range(len(data)): trial_info = data[idx] block_number = trial_info['block_number'] if trial_info['trial_type'] == 'instruction': if trial_info['tip'][-3:] == 'txt': instruction_type = 'text' elif trial_info['tip'][-3:] == 'bmp' or trial_info['tip'][ -3:] == 'jpg': instruction_type = 'image' else: raise AssertionError("wrong instruction file type") experiment.list_of_blocks[block_number - 1].instruction = trial_info['tip'] experiment.list_of_blocks[ block_number - 1].instruction_time = trial_info['tip_time'] experiment.list_of_blocks[block_number - 1].instruction_type = instruction_type else: matrix = Matrix(elements=trial_info['elements'], ftime=trial_info['ftime'], mtime=trial_info['mtime'], stime=trial_info['stime'], maxtime=trial_info['maxtime'], var=trial_info['var'], shint=trial_info['shint'], ehint=trial_info['ehint'], feedb=trial_info['feedb'], wait=trial_info['wait'], exp=trial_info['trial_type'], change=trial_info['change'], unique=trial_info['unique'], figure=trial_info['figure'], colors=trial_info['colors'], all=trial_info['all']) matrix.convert_matrix() experiment.list_of_blocks[block_number - 1].list_of_matrix.append(matrix) if random: experiment.randomize() experiment.save()
from classes.chain import Chain from classes.block import Block from classes.data import Data from datetime import datetime chain = Chain() data = Data("senderKey", "receiverKey", 123456, datetime) block = Block(1, None, data) chain.addNewBlock(block) print(chain.isChainValid())
def __init__(self, width, height, paddle_size, paddle_color, go_back_view, block_size=64): super().__init__() self.block_size = block_size self.up_and_down = arcade.SpriteList() self.right_wall = arcade.SpriteList() self.left_wall = arcade.SpriteList() offset_w = block_size / 2 offset_h = block_size / 2 # up and down walls for i in range(0, width, block_size): self.up_and_down.append(Block(offset_w + i, height - offset_w)) self.up_and_down.append(Block(offset_w + i, offset_w)) # right wall for i in range(0, height, block_size): self.right_wall.append(Block(width - offset_h, i + offset_h)) # left wall for i in range(0, height, block_size): self.left_wall.append(Block(offset_w, i + offset_h)) self.width = width self.height = height self.go_back_view = go_back_view self.paddle_size = paddle_size self.paddle_color = paddle_color self.player_1_score = 0 self.player_2_score = 0 self.counter_ball_is_speeding = 1 self.ball_speed = 3 self.max_ball_speed = 6 # text box self.score_text_box_w = 350 self.score_text_box_h = 70 self.score_text_box_x = (self.width / 2) self.score_text_box_y = self.height - 20 self.left_player = Paddle( init.paddle_left_image, init.paddle_left_center_x, init.paddle_left_direction_movement_x, init.paddle_left_key_up, init.paddle_left_key_down, init.paddle_left_key_speed, init.paddle_left_key_push) self.right_player = Paddle( init.paddle_right_image, init.paddle_right_center_x, init.paddle_right_direction_movement_x, init.paddle_right_key_up, init.paddle_right_key_down, init.paddle_right_key_speed, init.paddle_right_key_push) self.paddles = arcade.SpriteList() self.paddles.append(self.left_player) self.paddles.append(self.right_player) self.ball = Ball() self.meteor_1 = meteor.Meteor(center_x=width / 2, center_y=height / 2 + 128) self.meteor_2 = meteor.Meteor(center_x=width / 2, center_y=height / 2 - 128) self.meteors = arcade.SpriteList() self.meteors.append(self.meteor_1) self.meteors.append(self.meteor_2) self.paddles = arcade.SpriteList() self.paddles.append(self.left_player) self.paddles.append(self.right_player)