Best Python code snippet using tempest_python
CoCo Badig Build.py
Source:CoCo Badig Build.py
...20tokenize = True # Tokenize the ASCII code21tokenize_stop = True # Stop the execution on tokenize errors (keeps the ASCII version)22verbose_level = 3 # Show processing status: 0-silent 1-+erros 2-+warnings 3-+steps 4-+details23show_output = True # Show the XRoar stdout output24def show_log(line, text, level, **kwargs):25 bullets = ['', '*** ', ' * ', '--- ', ' - ', ' ']26 if line != '':27 line_num, line_alt, line_file = line28 else:29 line_num, line_file = '', ''30 show_file = [True, False]31 try:32 bullet = kwargs['bullet']33 except KeyError:34 bullet = level35 try:36 show_file = kwargs['show_file']37 except KeyError:38 show_file = False39 display_file_name = ''40 if show_file and line_file != '':41 display_file_name = included_dict[line_file] + ': '42 line_num = '(' + str(line_num) + '): ' if line_num != '' else ''43 if verbose_level >= level:44 print(bullets[bullet] + display_file_name + line_num + text)45 if bullet == 1 and not show_file:46 print(' Execution_stoped')47 print()48 raise SystemExit(0)49show_log('', 'CoCo Badig Build', 3, bullet=0)50parser = argparse.ArgumentParser(description='Convert CoCo Basic Dignified source and run on XRoar')51parser.add_argument("file_path", help='The path to the opened file to convert')52parser.add_argument("file_name", help='The opened file to convert')53parser.add_argument("-classic", action='store_true', help='The flavor of Basic to process')54parser.add_argument("-convert", action='store_true', help='Do not run the code after conversion')55parser.add_argument("-tokenize", default=tokenize, action='store_true', help='Tokenize the ASCII code')56parser.add_argument("-list", action='store_true', help='Save a .mlt list file')57args = parser.parse_args()58export_path = args.file_path + '/'59export_file = os.path.splitext(args.file_name)[0] + '.asc'60classic_basic = args.classic61convert_only = args.convert62tokenize = args.tokenize63file_load = args.file_name64local_path = os.path.split(os.path.abspath(__file__))[0] + '/'65if os.path.isfile(local_path + 'CoCo Badig Build.ini'):66 config = configparser.ConfigParser()67 config.sections()68 try:69 config.read(local_path + 'CoCo Badig Build.ini')70 cocobadig_filepath = config.get('DEFAULT', 'cocobadig_filepath') if config.get('DEFAULT', 'cocobadig_filepath') else cocobadig_filepath71 decb_filepath = config.get('DEFAULT', 'decb_filepath') if config.get('DEFAULT', 'decb_filepath') else decb_filepath72 xroar_filepath = config.get('DEFAULT', 'xroar_filepath') if config.get('DEFAULT', 'xroar_filepath') else xroar_filepath73 xrconfig_name = config.get('DEFAULT', 'xrconfig_name') if config.get('DEFAULT', 'xrconfig_name') else xrconfig_name74 tokenize = config.getboolean('DEFAULT', 'tokenize') if config.get('DEFAULT', 'tokenize') else tokenize75 tokenize_stop = config.getboolean('DEFAULT', 'tokenize_stop') if config.get('DEFAULT', 'tokenize_stop') else tokenize_stop76 verbose_level = config.getint('DEFAULT', 'verbose_level') if config.get('DEFAULT', 'verbose_level') else verbose_level77 except (ValueError, configparser.NoOptionError) as e:78 show_log('', '', 1, bullet=0)79 show_log('', 'CoCo Badig Build.ini: ' + str(e), 1)80valid_args = ['-ls', '-lp', '-lz', '-rh', '-cs', '-gs', '-uo', '-bl', '-lg', '-sl', '-ll', '-nr', '-cr',81 '-ki', '-nc', '-tg', '-of', '-vs', '-vb', '-frb', '-ini']82arg_num = len(valid_args)83arg = ['-frb'] * arg_num84arg[arg_num - 2] = '-vb=' + str(verbose_level)85disk_ext_slot = 'ext'86using_xrconfig = 'default config'87output = ''88decb_output = ''89arguments_line = ''90line_chama = ''91line_list = {}92included_dict = {}93if cocobadig_filepath == '':94 cocobadig_filepath = local_path + 'CoCoBadig.py'95if decb_filepath == '':96 decb_filepath = local_path + 'decb'97if xroar_filepath == '':98 xroar_filepath = local_path + 'XRoar.app'99cocotocas_filepath = local_path + 'CoCoToCas.py'100show_log('', ''.join(['Building ', args.file_path, '/', args.file_name]), 3, bullet=0)101show_log('', '', 3, bullet=0)102show_log('', ''.join([('Classic Basic' if classic_basic else 'Basic Dignified')]), 3)103if classic_basic:104 label_log = 'Tokenize only' if tokenize and convert_only else \105 'Tokenize and run' if tokenize and not convert_only else 'Run'106if not classic_basic:107 label_log = 'Convert only' if convert_only else 'Default'108show_log('', label_log, 3, bullet=5)109if not os.path.isfile(cocobadig_filepath) and not classic_basic:110 show_log('', ''.join(['CoCo_Basic_Dignified.py_not_found: ', cocobadig_filepath]), 1) # Exit111# if not os.path.isfile(decb_filepath) and tokenize:112# show_log('', ''.join(['decb_not_found: ', decb_filepath]), 1) # Exit113if not os.path.isdir(xroar_filepath) and not convert_only:114 show_log('', ''.join(['XRoar_not_found: ', xroar_filepath]), 1) # Exit115show_log('', '', 3, bullet=5)116if not classic_basic:117 with open(args.file_path + '/' + args.file_name, encoding='latin1') as f:118 for n, line in enumerate(f):119 if line.startswith('##BB:export_path='):120 export_path = line.replace('##BB:export_path=', '').strip()121 if export_path[-1:] != '/':122 export_path += '/'123 if line.startswith('##BB:export_file='):124 export_file = line.replace('##BB:export_file=', '').strip()125 if line.startswith('##BB:convert_only='):126 convert_only = True if line.replace('##BB:convert_only=', '').lower().strip() == 'true' else False127 if line.startswith('##BB:override_config='):128 xrconfig_name = line.replace('##BB:override_config=', '').strip()129 if line.startswith('##BB:arguments='):130 arguments_line = n + 1131 arguments = line.replace('##BB:arguments=', '').strip()132 arguments = arguments.split(',')133 for num, item in enumerate(arguments):134 if num > arg_num - 5: # args [arg_num-4], [arg_num-3], [arg_num-2] and [arg_num-1] are reserved to -tt, -vb, -exe and -frb135 break136 item2 = item137 item2 = item2.strip()138 item2 = item2.replace(' ', '=')139 if item2.split('=')[0] not in valid_args:140 show_log('', ' '.join(['invalid_argument:', item2]), 1)141 if item2.split('=')[0] == '-vb':142 try:143 verbose_level = int(item2.split('=')[1])144 except IndexError:145 show_log('', ' '.join(['invalid_argument_value:', '-vb']), 1)146 arg[arg_num - 2] = item2147 item2 = '-frb'148 if item2.split('=')[0] == '-tt':149 try:150 tokenize_tool = item2.split('=')[1].upper()151 except IndexError:152 show_log('', ' '.join(['invalid_argument_value:', '-tt']), 1)153 arg[arg_num - 3] = item2154 item2 = '-frb'155 arg[num] = item2156 args_token = list(set(arg))157 show_log('', 'CoCo Basic Dignified', 3, bullet=0)158 show_log('', ''.join(['Converting ', args.file_path, '/', args.file_name]), 3, bullet=0)159 show_log('', ''.join(['To ', export_path, export_file]), 3, bullet=0)160 show_log('', ''.join(['With args ', ' '.join(args_token)]), 3, bullet=0)161 try:162 chama = ['python3', '-u', cocobadig_filepath, args.file_path + '/' + args.file_name, export_path + export_file]163 chama.extend(arg)164 output = subprocess.check_output(chama, encoding='utf-8')165 for line in output:166 line_chama += line167 if line == '\n':168 if 'linelst-' in line_chama:169 line_get = line_chama.replace('linelst-', '').split(',')170 line_list[line_get[0]] = [line_get[1].rstrip(), line_get[2].rstrip()]171 elif 'export_file-' in line_chama:172 export_file = line_chama.replace('export_file-', '').strip()173 elif 'includedict-' in line_chama:174 included_get = line_chama.replace('includedict-', '').strip()175 included_get = included_get.split(',')176 included_dict[included_get[0]] = included_get[1]177 elif 'Tokenizing_aborted' in line_chama:178 show_log('', line_chama.rstrip(), 1, bullet=0)179 tokenize = False180 else:181 show_log('', line_chama.rstrip(), verbose_level, bullet=0)182 line_chama = ''183 export_file = os.path.splitext(export_file)[0] + '.asc'184 except subprocess.CalledProcessError:185 show_log('', ''.join([args.file_name, ': (', str(arguments_line), '): argument_error']), 1) # Exit186if xrconfig_name != '' and not os.path.isfile(xrconfig_name) and not convert_only:187 show_log('', ''.join(['XRoar_alternate_config_not_found: ', xrconfig_name]), 1) # Exit188if xrconfig_name != '':189 using_xrconfig = xrconfig_name190 xrconfig_name = ['-c', xrconfig_name]191list_arg = ['-t'] * 1192out_line = ''193args_token = list(set(list_arg))194pre_args = '' if ''.join(args_token) else 'no '195show_log('', "ToolShed's decb tokenizer", 3, bullet=0)196show_log('', ''.join(['Converting ', export_path, export_file]), 3, bullet=0)197show_log('', ''.join(['To ', export_path, os.path.splitext(export_file)[0] + '.bas']), 3, bullet=0)198show_log('', ''.join(['With ', pre_args + 'args ', ' '.join(args_token)]), 3, bullet=0)199if os.path.isfile(decb_filepath):200 decb_cmd = [decb_filepath, 'copy', export_path + export_file,201 export_path + os.path.splitext(export_file)[0] + '.bas', list_arg[0]]202 decb_output = subprocess.check_output(decb_cmd, encoding='utf-8')203 for line in decb_output:204 out_line += line205 if line == '\n':206 show_log('', out_line.rstrip(), verbose_level, bullet=0)207 out_line = ''208 print ()209 export_file = os.path.splitext(export_file)[0] + '.bas'210else:211 show_log('', ''.join(['decb_not_found: ', decb_filepath]), 2)212 print()213if convert_only:214 raise SystemExit(0)215list_arg = [''] * 1216out_line = ''217args_token = list(set(list_arg))218pre_args = '' if ''.join(args_token) else 'no '219show_log('', "CoCo to CAS", 3, bullet=0)220show_log('', ''.join(['Converting ', export_path, export_file]), 3, bullet=0)221show_log('', ''.join(['To ', export_path, os.path.splitext(export_file)[0] + '.cas']), 3, bullet=0)222show_log('', ''.join(['With ', pre_args + 'args ', ' '.join(args_token)]), 3, bullet=0)223if os.path.isfile(cocotocas_filepath):224 try:225 cocotocas_cmd = ['python3', '-u', cocotocas_filepath, export_path + export_file, list_arg[0]]226 cocotocas_output = subprocess.check_output(cocotocas_cmd, encoding='utf-8')227 for line in cocotocas_output:228 out_line += line229 if line == '\n':230 show_log('', out_line.rstrip(), verbose_level, bullet=0)231 out_line = ''232 print ()233 export_file = os.path.splitext(export_file)[0] + '.cas'234 except subprocess.CalledProcessError:235 show_log('', ' '.join(['argument_error:', ''.join(args_token)]), 1) # Exit236else:237 show_log('', ''.join(['CoCoToCas.py_not_found']), 2)238if not tokenize:239 osremove(export_path + export_file)240def output(show_output, output_text):241 fail_words = ['cannot open', 'failed to open', 'Invalid CRC']242 if show_output and output_text.strip() != '':243 if any(word in output_text for word in fail_words):244 output_text = output_text.replace('WARNING: ', '')245 proc.kill()246 show_log('', output_text.rstrip(), 1) # Exit247 elif 'WARNING:' in output_text:248 output_text = output_text.replace('WARNING: ', '')249 show_log('', output_text.rstrip(), 2)250 elif output_text[:1] != '\t':251 show_log('', output_text.rstrip(), 3)252 else:253 show_log('', output_text.strip(), 4)254show_log('', 'XRoar', 3, bullet=0)255show_log('', ''.join(['Opeening ', export_path, export_file]), 3, bullet=0)256show_log('', ''.join(['With ', using_xrconfig]), 3, bullet=0)257show_log('', '', 3, bullet=0)258cmd = [xroar_filepath + '/Contents/MacOS/xroar']259if xrconfig_name != '':260 cmd.extend(xrconfig_name)261cmd.extend(['-run', export_path + export_file])262cmd.extend(['-v', '2', '-debug-file', '0x0004'])263proc = subprocess.Popen(cmd, bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding='utf-8')264for line in iter(proc.stdout.readline, b''):265 output(show_log, line)266 poll = proc.poll()267 if poll is not None:268 print ()269 break270osremove(export_path + export_file)...
UnitHandler.py
Source:UnitHandler.py
...14 """15 """16 if self.special_unit:17 if self.special_unit.hp <= 1:18 Logs.show_log(f"restart special unit")19 self.special_unit = None20 else:21 Logs.show_log(22 f" we have special unit now {self.special_unit.unit_id}")23 paths_for_my_units = self.choose_path(world)24 Logs.show_log(25 f"choosen paths: {[path.id for path in paths_for_my_units]}")26 self.paths_for_my_units = paths_for_my_units27 self.put_units(world, paths_for_my_units)28 def choose_path(self, world: World):29 """30 choose path and put it in self.paths_for_my_nits31 """32 if self.in_danger(world):33 Logs.show_log(f"goes in defense mode.")34 paths_for_my_units = self.defense_mode(world)35 # elif self.iam_helper(world):36 # Logs.show_log(f"goes in helper mode.")37 # paths_for_my_units = self.helper_mode(world)38 else:39 Logs.show_log(f"goes in attack mode.")40 paths_for_my_units = self.attack_mode(world)41 return paths_for_my_units42 def in_delta_mode(self, world: World):43 Logs.show_log(f"check for delta")44 Logs.show_log(45 f"range upgrades number {world.get_range_upgrade_number()}")46 Logs.show_log(47 f"damage upgrades number {world.get_damage_upgrade_number()}")48 option2 = world.get_range_upgrade_number(49 ) >= 1 and world.get_damage_upgrade_number() >= 450 option3 = world.get_range_upgrade_number() >= 351 return option2 or option352 def iam_helper(self, world: World):53 units = world.get_me().units54 if any(unit.target_if_king for unit in units):55 return None56 units = world.get_friend().units57 return any(u.target_if_king for u in units)58 def helper_mode(self, world: World):59 friend_units = world.get_friend().units60 path_for_my_units = self.attack_mode(world)61 my_paths = world.get_me().paths_from_player62 if friend_units:63 path = None64 for unit in friend_units:65 if unit.target_if_king:66 for p in my_paths:67 if unit.target_if_king.center in p.cells:68 path = p69 break70 if path:71 break72 path_for_my_units.append(path)73 return path_for_my_units74 def choose_units(self, world: World):75 """76 """77 myself = world.get_me()78 hand = sorted(myself.hand, key=lambda u: 1/u.ap)79 return hand, myself80 def two_by_two_mode(self, world: World):81 if world.get_current_turn() % 2 == 0:82 i = 083 myself = world.get_me()84 hand = myself.hand85 hand.sort(key=lambda u: u.ap)86 for unit in hand:87 if i == 2:88 return89 if unit.ap <= myself.ap:90 myself.ap -= unit.ap91 Logs.show_log(92 f"unit: {unit.type_id} in path: {self.paths_for_my_units[0].id}")93 world.put_unit(94 base_unit=unit, path=self.paths_for_my_units[0])95 i += 196 def units_aggregation(self, world: World):97 max_number = 098 my_units = world.get_me().units99 path = self.paths_for_my_units[0]100 for i in range(1, len(path.cells)-1):101 unit_number = 0102 units = world.get_cell_units(path.cells[i-1])103 for unit in units:104 if unit in my_units:105 unit_number += 1106 units = world.get_cell_units(path.cells[i])107 for unit in units:108 if unit in my_units:109 unit_number += 1110 units = world.get_cell_units(path.cells[i+1])111 for unit in units:112 if unit in my_units:113 unit_number += 1114 if unit_number > max_number:115 max_number = unit_number116 Logs.show_log(f"aggregation unit: {max_number}")117 return max_number118 def unit_total(self, world: World):119 unit_number = 0120 my_units = world.get_me().units121 path = self.paths_for_my_units[0]122 for cell in path.cells:123 cell_units = world.get_cell_units(cell)124 for unit in cell_units:125 if unit in my_units:126 unit_number += 1127 Logs.show_log(f"total unit: {unit_number}")128 return unit_number129 def we_do_attack(self, world: World):130 my_units = world.get_me().units131 return any(unit.target_if_king for unit in my_units)132 def check_stand_by(self, world: World):133 Logs.show_log(f"checking for standby")134 myself = world.get_me()135 max_ap = world.get_game_constants().max_ap136 if self.in_danger(world):137 Logs.show_log(f"standby off cause of danger")138 self.standby = False139 return140 if self.we_do_attack(world):141 Logs.show_log(f"standby off cause of attack")142 self.standby = False143 return144 if myself.ap == max_ap:145 self.standby = False146 def put_units(self, world: World, paths_for_my_units: List[Path]):147 """148 """149 hand, myself = self.choose_units(world)150 self.check_stand_by(world)151 if self.standby:152 return153 if world.get_current_turn() < 10:154 self.two_by_two_mode(world)155 return156 # multi path157 if len(paths_for_my_units) > 1:158 Logs.show_log(f"try to put in multi path")159 hand.sort(key=lambda u: u.ap)160 its_odd_turn = world.get_current_turn() % 2161 if its_odd_turn:162 for i, path in enumerate(paths_for_my_units):163 if i % 2:164 for unit in hand:165 if unit.ap <= myself.ap:166 myself.ap -= unit.ap167 Logs.show_log(168 f"unit: {unit.type_id} in path: {path.id}")169 world.put_unit(170 base_unit=unit, path=path)171 break # put one unit172 else: # even path173 continue174 else: # even turn175 for i, path in enumerate(paths_for_my_units):176 if not i % 2:177 for unit in hand:178 if unit.ap <= myself.ap:179 myself.ap -= unit.ap180 Logs.show_log(181 f"unit: {unit.type_id} in path: {path.id}")182 world.put_unit(183 base_unit=unit, path=path)184 break # put one unit185 else: # one path186 # special case187 if self.put_special:188 if world.get_me().units:189 last_unit = world.get_me().units[-1]190 self.special_unit = last_unit191 self.put_special = False192 Logs.show_log(193 f" we have special unit now {self.special_unit.unit_id}")194 if self.in_delta_mode(world) and not self.special_unit:195 Logs.show_log(f"in delta mode")196 for u in hand:197 if u.type_id == 0:198 Logs.show_log(f" found a unit")199 if u.ap <= myself.ap:200 paths = self.attack_mode(world)201 Logs.show_log(202 f"units before put: {[unit.base_unit.type_id for unit in world.get_me().units]}")203 world.put_unit(base_unit=u, path=paths[0])204 self.put_special = True205 return206 else:207 Logs.show_log(f"not enough ap {myself.ap}")208 return209 if not self.put_special:210 Logs.show_log(211 f" not found a unit {[u.type_id for u in hand]}")212 # end of special case213 # reversed best are in the end214 if myself.ap < 6:215 self.standby = True216 return217 for unit in reversed(hand):218 if unit.ap <= myself.ap:219 myself.ap -= unit.ap220 Logs.show_log(221 f"unit: {unit.type_id} in path: {paths_for_my_units[0].id}")222 world.put_unit(base_unit=unit, path=paths_for_my_units[0])223 return # one unit per turn224 self.standby = True225 Logs.show_log(f"put no unit.")226 def enemy_aggregation(self, world: World, path: Path, i, enemy_units: List[Unit]):227 unit_number = 0228 units = world.get_cell_units(path.cells[i-1])229 for unit in units:230 if unit in enemy_units:231 unit_number += 1232 units = world.get_cell_units(path.cells[i])233 for unit in units:234 if unit in enemy_units:235 unit_number += 1236 units = world.get_cell_units(path.cells[i+1])237 for unit in units:238 if unit in enemy_units:239 unit_number += 1240 return unit_number241 def in_danger(self, world: World) -> Path:242 """243 """244 paths = world.get_me().paths_from_player245 king_range = world.get_me().king.range246 units = world.get_first_enemy().units + world.get_second_enemy().units247 for path in paths:248 if self.enemy_aggregation(world, path, king_range-2, units) >= 2:249 Logs.show_log(f"danger: enemy aggregation")250 return path251 for unit in units:252 if unit.target_if_king == world.get_me().king:253 for path in paths:254 if unit.cell in path.cells:255 Logs.show_log(f"danger: king under attack")256 return path257 return None258 def defense_mode(self, world: World):259 """260 """261 target_path = self.in_danger(world)262 return [target_path]263 def attack_mode(self, world: World):264 """265 """266 # my paths267 my_king = world.get_me().king.center268 paths_from_me = world.get_paths_crossing_cell(cell=my_king)269 paths_to_first_enemy = []270 paths_to_second_enemy = []271 # first enemy paths272 if world.get_first_enemy().is_alive():273 first_enemy_king = world.get_first_enemy().king.center274 paths_to_first_enemy = world.get_paths_crossing_cell(275 cell=first_enemy_king)276 # second enemy paths277 if world.get_second_enemy().is_alive():278 second_enemy_king = world.get_second_enemy().king.center279 paths_to_second_enemy = world.get_paths_crossing_cell(280 cell=second_enemy_king)281 path_to_enemy = [282 path for path in paths_from_me if path in paths_to_first_enemy]283 path_to_enemy.extend(284 [path for path in paths_from_me if path in paths_to_second_enemy])285 min_path = min(path_to_enemy, key=lambda p: len(p.cells))286 path_for_my_units = [287 p for p in path_to_enemy if len(p.cells) == len(min_path.cells)288 ]289 if not path_for_my_units:290 Logs.show_log(f"error in finding path in attack mode")...
extract_blc_from_wordnet.py
Source:extract_blc_from_wordnet.py
1#!/usr/bin/env python2from collections import defaultdict3import argparse4def extract_synset(wn_line):5 p = wn_line.find(' ')6 return wn_line[:p]7def extract_num_relations_and_hyperonyms(wn_line, type_relations):8 p = wn_line.find('|')9 info = wn_line[:p]10 fields = info.split(' ')11 num_words = int(fields[3],16) #It is hexadecimal12 position_pointer_count = 4 + 2*num_words13 num_relations = int(fields[position_pointer_count])14 15 this_position = position_pointer_count + 116 hypo_relations = 017 hyperonyms = []18 for r in xrange(num_relations):19 this_relation = fields[this_position]20 if this_relation == '~':21 hypo_relations += 122 elif this_relation in ['@','@i']:23 hyperonyms.append(fields[this_position+1])24 this_position += 425 26 27 if type_relations == 'all':28 pass29 elif type_relations == 'hypo':30 num_relations = hypo_relations31 32 return num_relations, hyperonyms33def get_max_hyperonym(list_hyperonyms, type_relations, wn_line_for_synset):34 best_hy = None35 best_num_rel = -136 for hy in list_hyperonyms:37 wn_line = wn_line_for_synset[hy]38 num_relations, _ = extract_num_relations_and_hyperonyms(wn_line, type_relations)39 if num_relations > best_num_rel:40 best_num_rel = num_relations41 best_hy = hy42 return best_hy, best_num_rel43def extract_hyperonyms(best_hyperonym,wn_list_for_synset):44 wn_line = wn_list_for_synset[best_hyperonym]45 _, list_hyperonyms = extract_num_relations_and_hyperonyms(wn_line, 'all')46 return list_hyperonyms47def extract_blc(this_synset, wn_line_for_synset, type_relations, start_at_synset, show_log=False):48 this_blc = 'fake_blc'49 wn_line = wn_line_for_synset[this_synset]50 #print wn_line51 52 num_relations_for_synset, list_hyperonyms = extract_num_relations_and_hyperonyms(wn_line, type_relations)53 if show_log:54 print 'BLC for synset', this_synset, 'with %d relations' % num_relations_for_synset55 56 already_visited = set()57 if len(list_hyperonyms) == 0:58 this_blc = this_synset59 else:60 if show_log:61 print 'First level of hyperonyms:', list_hyperonyms62 best_hyperonym, best_num_relations_for_hyperonym = get_max_hyperonym(list_hyperonyms, type_relations, wn_line_for_synset)63 already_visited.add(best_hyperonym)64 if show_log:65 print 'Best syn and num relations:', best_hyperonym, best_num_relations_for_hyperonym66 67 if start_at_synset:68 previous = this_synset69 else:70 previous = None71 72 if show_log:73 print ' Starting iteration'74 75 while best_num_relations_for_hyperonym > num_relations_for_synset or (not start_at_synset and previous is None):76 if show_log:77 print ' Step'78 hyperonyms = extract_hyperonyms(best_hyperonym,wn_line_for_synset)79 if show_log:80 print ' Hyperonyms obtained for %s --> %s' % (best_hyperonym,str(hyperonyms))81 if len(hyperonyms) != 0:82 num_relations_for_synset = best_num_relations_for_hyperonym83 previous = best_hyperonym84 best_hyperonym, best_num_relations_for_hyperonym = get_max_hyperonym(hyperonyms, type_relations, wn_line_for_synset)85 if show_log:86 print ' Best hyperonym and nu relations:',best_hyperonym, best_num_relations_for_hyperonym87 if best_hyperonym in already_visited:88 #Cycle89 if show_log:90 print ' There is a cycle'91 break92 already_visited.add(best_hyperonym)93 else:94 if show_log:95 print ' There are no hyperonyms, so STOP'96 previous = best_hyperonym97 break98 99 this_blc = previous100 101 if show_log:102 print 'Synset: %s BLC %s' % (this_synset, this_blc)103 print104 return this_blc105def reassign_blc(this_blc, min_frequency,subsumed_by_blc,wn_line_for_synset,type_relations, show_log=False):106 subsumed = subsumed_by_blc[this_blc]107 if show_log:108 print 'Calculating new BLC for %s which subsumes %d synsets' % (this_blc, subsumed)109 already_visited = set()110 best_hyperonym = this_blc111 greatest_synset = None112 greatest_subsumed = -1113 while subsumed < min_frequency:114 this_wn_line = wn_line_for_synset[best_hyperonym]115 hyperonyms = extract_hyperonyms(best_hyperonym,wn_line_for_synset)116 if show_log:117 print ' Hyperonyms:', hyperonyms118 if len(hyperonyms) != 0:119 best_hyperonym, best_num_relations_for_hyperonym = get_max_hyperonym(hyperonyms, type_relations, wn_line_for_synset)120 if show_log:121 print ' Best hyperonym %s' % best_hyperonym122 if best_hyperonym in already_visited:123 if show_log:124 print ' Already visited, we stop'125 break126 else:127 subsumed = subsumed_by_blc.get(best_hyperonym,0)128 if subsumed >= greatest_subsumed:129 greatest_subsumed = subsumed130 greatest_synset = best_hyperonym131 if show_log:132 print ' This one subsumes: %d' % subsumed133 already_visited.add(best_hyperonym) 134 else:135 if show_log:136 print ' No hyperonyms, so we stop'137 if greatest_subsumed >= 0: 138 # we return the one with greatest number subsumed in the chain139 best_hyperonym = greatest_synset140 else:141 #We dont find any other BLC in the chain that subsumes the min142 # so we stay with the same as it was assigned143 best_hyperonym = this_blc144 break145 return best_hyperonym146 147 148def load_friendly_blc(path_to_sense_index):149 friendly_blc_for_synset_pos = {}150 fd = open(path_to_sense_index,'r')151 for line in fd:152 lexkey, synset, sense, freq = line.strip().split()153 p = lexkey.find('%')154 lemma = lexkey[:p]155 int_pos = lexkey[p+1]156 157 pos = None158 if int_pos == '1':159 pos = 'n'160 elif int_pos == '2':161 pos = 'v'162 163 if pos is not None:164 fr_blc = '%s.%s#%s' % (lemma,pos,sense)165 if (synset,pos) not in friendly_blc_for_synset_pos:166 friendly_blc_for_synset_pos[(synset,pos)] = (fr_blc,freq)167 else:168 _ , prev_freq = friendly_blc_for_synset_pos[(synset,pos)]169 if freq > prev_freq:170 friendly_blc_for_synset_pos[(synset,pos)] = (fr_blc,freq)171 fd.close()172 return friendly_blc_for_synset_pos173 174 175 176 177if __name__ == '__main__':178 argument_parser = argparse.ArgumentParser(description='Extract BLC concepts from WordNet')179 argument_parser.add_argument('-i', type=argparse.FileType('r'), dest='fd_wn_data_file', help='Wordnet data file', required=True)180 argument_parser.add_argument('-o', type=argparse.FileType('w'), dest='fd_output', help='Output file', required=True)181 argument_parser.add_argument('-t', dest='type_relations', choices=['all','hypo'], help='Type of relations to consider', required=True)182 argument_parser.add_argument('-m', dest='min_frequency', type=int, help='Minimum number of synsets subsumed per BLC', required=True)183 argument_parser.add_argument('-log', dest='log', action='store_true', help='Show log')184 argument_parser.add_argument('-pos', dest='pos', choices=['n','v'], help='POS tag', required=True)185 argument_parser.add_argument('-start-at-synset', dest='start_at_synset', action='store_true', help='Start the iteration process at the synset itself')186 args = argument_parser.parse_args()187 188 wn_line_for_synset = {}189 for wn_line in args.fd_wn_data_file:190 if wn_line[0] != ' ':191 wn_line = wn_line.strip()192 synset = extract_synset(wn_line)193 wn_line_for_synset[synset] = wn_line194 195 blc_for_synset = {}196 subsumed_by_blc = defaultdict(int)197 198 199 #First selection of a BLC candidate for every synset200 for this_synset in wn_line_for_synset.keys():201 this_blc = extract_blc(this_synset, wn_line_for_synset, args.type_relations, args.start_at_synset, args.log)202 #print this_synset, '-->', this_blc203 blc_for_synset[this_synset] = this_blc204 subsumed_by_blc[this_blc] += 1205 #Filtering to make sure every BLC at least subsumes enough number206 reassigned = {}207 final_blc_for_synset = {}208 for this_synset, this_blc in blc_for_synset.items():209 subsumed = subsumed_by_blc[this_blc]210 if subsumed < args.min_frequency:211 new_blc = None212 if this_blc in reassigned:213 new_blc = reassigned[this_blc]214 else:215 new_blc = reassign_blc(this_blc,args.min_frequency,subsumed_by_blc,wn_line_for_synset, args.type_relations, args.log)216 reassigned[this_blc] = new_blc217 if args.log:218 print 'Reassing blc to %s because %s only subsumes %d symsets' % (this_synset, this_blc, subsumed)219 print '\tReassigned to: %s which subsumes %d synsets' % (new_blc, subsumed_by_blc[new_blc])220 final_blc_for_synset[this_synset] = new_blc221 else:222 final_blc_for_synset[this_synset] = this_blc223 224 path_to_data = args.fd_wn_data_file.name225 p = path_to_data.rfind('/')226 path_to_sense_index = path_to_data[:p+1]+'index.sense'227 friendly_blc_for_synset_pos = load_friendly_blc(path_to_sense_index)228 229 args.fd_output.write('### START PARAMETERS\n')230 for p, v in args._get_kwargs():231 if isinstance(v,file):232 v = v.name233 args.fd_output.write('### %s => %s\n' % (p,v))234 args.fd_output.write('### END PARAMETERS\n')235 236 for this_synset, this_blc in final_blc_for_synset.items():237 friendly, frequency = friendly_blc_for_synset_pos[(this_blc,args.pos)]238 args.fd_output.write('%s %s %s %d\n' % (this_synset, this_blc, friendly, subsumed_by_blc[this_blc]))239 240 241 242 args.fd_output.close()243 print 'Output in %s' % args.fd_output.name244 ...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!