def main(): """Help user build anagram phrase from their name.""" name = ''.join(ini_name.lower().split()) name = name.replace('-','') limit = len(name) phrase = '' running = True while running: temp_phrase = phrase.replace(' ', '') if len(temp_phrase) < limit: print("Length of anagram phrase = {}".format(len(temp_phrase))) find_anagrams(name, dict_file) print("Current anagram phrase =", end=" ") print(phrase, file=sys.stderr) choice, name = process_choice(name) phrase += choice + ' ' elif len(temp_phrase) == limit: print("\n*****Finished!!!*****\n") print("Anagram of name =", end=" ") print(phrase, file=sys.stderr) print() try_again = input('\n\nTry again? (Press Enter else "n" to quit)\n ') if try_again.lower() == "\n": running = False sys.Exit() else: main()
def loadFiles(e, p, pairs, res): with open(res.enc + "/" + e, "rb") as e_file: with open(res.plain + "/" + p, "rb") as p_file: while True: be = e_file.read(16) bp = p_file.read(16) if not be and not bp: break if not be: print "[-] Encrypted file [" + e + "] is smaller than plain text pair [" + p + "]. Aborting" sys.Exit(1) if not bp: print "[-] Plain file [" + p + "] is smaller than encrypted pair [" + e + "]. Aborting" sys.Exit(1) pairs[be.encode('hex')] = bp
def make_intr(in_name, from_name, to_name, adjustment=1.1, description="Default"): from_state=State.query.filter_by(name=from_name).all() to_state=State.query.filter_by(name=to_name).all() in_state=State.query.filter_by(name=in_name).all() if len(from_state) > 1 or len(to_state) > 1 or len(in_state) > 1 : print "Ambiguity in interaction" sys.Exit(0) from_state=State.query.filter_by(name=from_name).first() if from_state == None: print "Error - cannot find from state: " + from_name sys.exit(0) to_state=State.query.filter_by(name=to_name).first() if to_state == None: print "Error - cannot find to state: " + to_name sys.exit(0) in_state=State.query.filter_by(name=in_name).first() if in_state == None: print "Error - cannot find to state: " + in_name sys.exit(0) if description == "Default": description = "RR/OR of transfering from " + from_name + " to " + to_name + " if in: " + in_name affected_chain = from_state.chain save(Interaction( from_state_name=from_state.name, to_state_name=to_state.name, in_state_name=in_state.name, in_state=in_state, from_state=from_state, to_state=to_state, description=description, adjustment=adjustment, affected_chain=affected_chain))
def isSpecialWord(word): if (word == "upperCnt" or word == "symbolCnt" or word == "loneCnt" or word == "markupPrsnt" or word == "IsSpam"): print("Special Word was present") sys.Exit() return True else: return False
def __congratulions(self): """ End of the game.Congratulions one of the players i dont sure in this method because I dont win anytime :return: None """ import sys print('Yeah!!! The player {} is win!!!My congratulions!!!'.format(\ self.__players[self.__current_player].name)) sys.Exit()
def Execute(command, verbose=False): if verbose: commandtext = ' '.join(command) print commandtext sys.Exit(0) res = subprocess.check_output(command) if verbose: print res return res
def create_builder_job(self, service, image, ns, name=default_name): job = self.api.create_builder_job(name, image, ns, service) try: created = self.batchv1.create_namespaced_job(namespace=ns, body=job) except ApiException as e: print(e) sys.Exit(1) return created
def main(): os.system("clear") print("Welcome to the Adventure Game \n ") print "1. Start" print "2. Load Save" print "3. Exit" option = int(raw_input("-> ")) if option == 1: start() elif option == 2: pass elif option == 3: sys.Exit() else: main()
def startup(): print "Welcome to Luke\'s Ledger" print "What would you like to do?" print "" print "1. Add Expense" print "2. Remove Expense" print "3. Print Previous Month Summary" print "4. Print Current Month Summary" print "5. Print Expenses" print "6. Change Monthly Income" print "7. Add End of Month Statement" print "8. Exit" print "" menuDecision = raw_input() print "" if menuDecision == "1": addExpense() elif menuDecision == "2": removeExpense() elif menuDecision == "3": pass #TODO add this elif menuDecision == "4": printShortSummary() elif menuDecision == "5": printExpenses() elif menuDecision == "6": setIncome() elif menuDecision == "7": createMonthlySummary() elif menuDecision == "8": sys.Exit(0) startup()
def VectorMagnitude(vector): return math.sqrt(vector[0]**2 + vector[1]**2 + vector[2]**2) #def PrintRpy(roll, ) print("--------------Misson control--------------\n") #create connection conn = krpc.connect(name='Sub-orbital flight') if (conn is not None): print("KSP Connection Succesfull") else: sys.Exit(0) #get active vessel vessel = conn.space_center.active_vessel #trun off auto pilot #vessel.auto_pilot.disengage(); vessel.auto_pilot.engage() #try to activate S.A.S. try: #vessel.auto_pilot.wait(); vessel.control.sas = True time.sleep(2) vessel.control.sas_mode = conn.space_center.SASMode.prograde except:
def quit(self): sys.Exit()
def __init__(self, groups, board, inject_xml_file_name): all_json = dict() all_json['version'] = 1 all_json['uid'] = 1 #COMPONENT_INFORMATION.comp_metadata_type all_json['scope'] = "Firmware" all_params = [] all_json['parameters'] = all_params #xml_parameters = ET.Element("parameters") #xml_version = ET.SubElement(xml_parameters, "version") #xml_version.text = "3" #xml_version = ET.SubElement(xml_parameters, "parameter_version_major") #xml_version.text = "1" #xml_version = ET.SubElement(xml_parameters, "parameter_version_minor") #xml_version.text = "15" schema_map = { "short_desc": "shortDesc", "long_desc": "longDesc", "unit": "units", "decimal": "decimalPlaces", "min": "min", "max": "max", "increment": "increment", "reboot_required": "rebootRequired" } allowed_types = { "Uint8", "Int8", "Uint16", "Int16", "Uint32", "Int32", "Float" } last_param_name = "" board_specific_param_set = False for group in groups: group_name = group.GetName() for param in group.GetParams(): if (last_param_name == param.GetName() and not board_specific_param_set ) or last_param_name != param.GetName(): curr_param = dict() curr_param['name'] = param.GetName() curr_param['default'] = param.GetDefault() curr_param['type'] = param.GetType().capitalize() if not curr_param['type'] in allowed_types: print( "Error: %s type not supported: curr_param['type']" % (curr_param['name'], curr_param['type'])) sys.Exit(1) curr_param['group'] = group_name if (param.GetCategory()): curr_param['category'] = param.GetCategory() if (param.GetVolatile() == "true"): curr_param['volatile'] = param.GetVolatile() last_param_name = param.GetName() for code in param.GetFieldCodes(): value = param.GetFieldValue(code) if code == "board": if value == board: board_specific_param_set = True # JSON schema has no field for board_specific schema. Ignore. else: #xml_group.remove(xml_param) continue else: #map PX4 param field names to schema names if code in schema_map: curr_param[schema_map[code]] = value else: print('ERROR: Field not in json schema: %s' % code) sys.exit(1) if last_param_name != param.GetName(): board_specific_param_set = False enum_codes = param.GetEnumCodes( ) or '' # Gets numerical values for parameter. if enum_codes: enum_codes = sorted(enum_codes, key=float) codes_list = list() for item in enum_codes: code_dict = dict() code_dict['value'] = item code_dict['description'] = param.GetEnumValue(item) codes_list.append(code_dict) curr_param['values'] = codes_list if len(param.GetBitmaskList()) > 0: bitmasks_list = list() for index in param.GetBitmaskList(): bitmask_dict = dict() bitmask_dict['index'] = index bitmask_dict['description'] = param.GetBitmaskBit( index) bitmasks_list.append(bitmask_dict) curr_param['bitmask'] = bitmasks_list all_params.append(curr_param) #Json string output. self.output = json.dumps(all_json, indent=2)
logo() print "These Are Some Advanced Options From Nmap..." time.sleep(1) os.system("nmap") print "You Can use The By Typing 'Nmap <Option>'" time.sleep(2) sys.exit() if op == '99': cls() logo() print "Sure! Quiting.... Hope U Liked" sys.exit() if op == '4' or op == '04': cls() os.system("figlet -f slant About") print print "This Tools Is Made For The Newbie and Also Expert Hackers That Do Not Know How to use Nmap The Hacking Tools Because The Nmap has a Litle Difficul Statements To Exexute Them By This Tools You Do Not Have To Write Any Statements You Can Exexute Nmap and Scan Websites By Just Writing The Name Of The Website/Ip Advanced Options are also there For Some Experts " print "" print "Author -> Sarthak" print "Posted on -> Github" print "Authors Age -> 11 Years" print "Intrested in -> Cyber Security,Ethical Hacking,Tech" print "" else: print "\n[!] ERROR : Wrong Input" time.sleep(1) sys.Exit()
argp = argparse.ArgumentParser() argp.add_argument("bin", type=str, help="Input binary to load") argp.add_argument("outfile", type=str, help="Symbolized ASM output") argp.add_argument("--ignorepie", dest="ignorepie", action='store_true', help="Ignore position-independent-executable check (use with caution)") argp.set_defaults(ignorepie=False) args = argp.parse_args() loader = Loader(args.bin) if loader.is_pie() == False and args.ignorepie == False: print("RetroWrite requires a position-independent executable.") print("It looks like %s is not position independent" % args.bin) sys.Exit(1) flist = loader.flist_from_symtab() loader.load_functions(flist) slist = loader.slist_from_symtab() loader.load_data_sections(slist, lambda x: x in Rewriter.DATASECTIONS) reloc_list = loader.reloc_list_from_symtab() loader.load_relocations(reloc_list) global_list = loader.global_data_list_from_symtab() loader.load_globals_from_glist(global_list) loader.container.attach_loader(loader)
def combine(name=None, dir=None, mode=None): proc = "combine" args = srclib.arguments(name, dir, mode, proc) # get the arguments if not args: return 1 path = args[0] datain = args[1] dataout = args[2] setup = args[3] var = None # variable list m = re.search(r"(^|;)\s*var[\w]*\s+([^;]+);", setup, flags=re.IGNORECASE) # supplied? if m: var = m.group(2).strip() var = var.strip() if not re.match(r"^[\w -]+$", var): # check it sys.Exit("Invalid variable list.") # invalid filenames = datain.strip() # build the file names list filelist = [] while filenames != "": # loop through file names m = re.match(r'^"([^"]+)"(\s+.*)?$', filenames) # double quotes if not m: m = re.match(r"^'([^']+)'(\s+.*)?$", filenames) # single quotes if not m: m = re.match(r"^([^\s]+)(\s+.*)?$", filenames) # no quotes if m.group(2): filenames = m.group(2).strip() # trim the remaining names else: filenames = "" file = m.group(1).strip() # extract the file name m = re.match(r"^[~\.\\/:\w -]+$", file) # check it if not m: sys.Exit("Invalid datain.") # invalid if not re.match(r"\.sav$", file, flags=re.IGNORECASE): # add .sav file += ".sav" filelist.append(file) # append it to the list #dataout if not re.match(r"\.sav$", dataout, flags=re.IGNORECASE): # add .sav dataout += ".sav" beg = 0 # merge the files count = 0 for file in filelist: # loop through the input files if count > 0: # not the first file cmd = "save outfile='{0}'.\n".format( dataout) # save the intermediate file spss.Submit(cmd) cmd = "get file='{0}'.\n".format(file) # get the input file spss.Submit(cmd) cmd = "compute OBS_ = $casenum.\n" # compute the observation number cmd += "compute OBS_ = OBS_ + {0}.\n".format(beg) cmd += "execute.\n" spss.Submit(cmd) beg += spss.GetCaseCount() # increment the case count if count > 0: # not the first file cmd = "match files file=* /file='{0}' /by OBS_.\n".format( dataout) # match the input and intermediate files spss.Submit(cmd) count += 1 if var: # variable list cmd = "save outfile='{0}' /keep={1}.\n".format( dataout, var) # subset variables and save else: cmd = "save outfile='{0}'.\n".format(dataout) # save the output file spss.Submit(cmd)
def hack( target_pid, dll_path, eject=False, createremotethread=True, dll_function=None, dll_function_args=None, ): # print config dll_name = os.path.basename(dll_path) printDebug("+++CONFIGURATION+++") printDebug("\tTARGET PID : %s" % target_pid) printDebug("\tDLL NAME : %s" % dll_name) printDebug("\tDLL PATH : %s" % dll_path) if eject: printDebug("\tACTION : EJECT") else: printDebug("\tACTION : INJECT") if createremotethread: printDebug("\tMETHOD : CreateRemoteThread") else: printDebug("\tMETHOD : HIJACK PRIMARY THREAD") if dll_function: printDebug("\tDLL FUNCTION : %s" % dll_function) if dll_function_args: printDebug("\tDLL FUNCTION ARGS: %s" % ' '.join(dll_function_args)) # obtain handle to target process printDebug("Obtaining handle to target process ..") target_process_handle = windll.kernel32.OpenProcess( PROCESS_ALL_ACCESS, 0, target_pid, ) if not target_process_handle: # error-check printDebug( "Error: windll.kernel32.OpenProcess: couldn't obtain handle to target process (GetLastError()\ = 0x%08X)." % windll.kernel32.GetLastError()) sys.exit(1) printDebug("OK.") # make space for payload printDebug("Allocating %d-byte code-cave in target process .." % CODECAVE_SIZE) codecave_addr = windll.kernel32.VirtualAllocEx( target_process_handle, 0, CODECAVE_SIZE, MEM_COMMIT, PAGE_EXECUTE_READWRITE, ) if not codecave_addr: # error-check printDebug( "Error: windll.kernel32.VirtualAllocEx: couldn't allocate code-cave in target process (GetLastError()\ = 0x%08X)." % windll.kernel32.GetLastError()) sys.exit(1) printDebug("OK (code-cave starts at 0x%08X)." % codecave_addr) # if not createremotethread option, prepare to hijack target process primary thread if not createremotethread: # we will hijack the primary thread of the target process and let it trigger our payload for us printDebug("Obtaing remote process primary thread ID ..") primary_tid = GetPrimaryThreadId(target_pid) if not primary_tid: printDebug( "Error: GetPrimaryThreadId: couldn't get target process primary thread ID \ (windll.kernel32.GetLastError() = 0x%08X)." % windll.kernel32.GetLastError()) sys.Exit(1) printDebug("OK (target process primary thread ID = %d)." % primary_tid) printDebug("Obtaining handle to target process primary thread ..") primary_thread_handle = windll.kernel32.OpenThread(THREAD_GET_CONTEXT | THREAD_SUSPEND_RESUME | \ THREAD_SET_CONTEXT, 0, primary_tid, ) windll.kernel32.SuspendThread(primary_thread_handle) printDebug("Obtaining target process primary thread context ..") primary_thread_ctx = CONTEXT(0) primary_thread_ctx.ContextFlags = CONTEXT_CONTROL windll.kernel32.GetThreadContext( primary_thread_handle, byref(primary_thread_ctx), ) primary_thread_saved_EIP = primary_thread_ctx.Eip # so we may de-hijack the thread in case of trouble printDebug("OK (target process primary thread EIP = 0x%0X)" % primary_thread_ctx.Eip) if not primary_thread_handle: printDebug( "Error: windll.kernel32.OpenThread: couldn't obtain handle to target process primary thread \ (windll.kernel32.GetLastError() = 0x%08X)." % windll.kernel32.GetLastError()) sys.exit(1) printDebug("OK.") printDebug("Building payload ..") # instantiate payload payload = Payload(start_offset=codecave_addr) # push offset strings err_caption_addr = payload.addConstStr("%s: Error:" % os.path.basename(sys.argv[0])) ejection_failure_err_txt_addr = payload.addConstStr("Couldn't eject %s" % dll_name) injection_failure_err_txt_addr = payload.addConstStr("Couldn't inject %s" % dll_path) if dll_function: dll_function_addr = payload.addConstStr(dll_function) import_dll_function_failure_err_txt_addr = payload.addConstStr("Couldn't import %s API from %s" \ %(dll_function,dll_name)) dll_addr = payload.addConstStr(dll_path) # calculate payload entry-point EP = payload.getCurrentOffset() if createremotethread: exitthread_EP = codecave_addr + CODECAVE_SIZE - EXITTHREADPAYLOAD_LEN prolog = exitthread_EP exitthread_payload = ExitThreadPayload( start_offset=exitthread_EP, pseudo="exit thread", ) freelibraryandexitthread_EP = exitthread_EP - FREELIBRARYANDEXITTHREADPAYLOAD_LEN - \ UNCONDITIONALJMPPAYLOAD_LEN freelibraryandexitthread_payload = FreeLibraryAndExitThreadPayload(dll_addr, start_offset=freelibraryandexitthread_EP, pseudo="unload %s and exit thread" \ %dll_name, ) end_of_seh = freelibraryandexitthread_EP else: prolog = codecave_addr + CODECAVE_SIZE - 1 - 1 - 1 freelibrary_EP = prolog - FREELIBRARYPAYLOAD_LEN - UNCONDITIONALJMPPAYLOAD_LEN freelibrary_payload = FreeLibraryPayload( dll_addr, start_offset=freelibrary_EP, pseudo="unload %s" % dll_name, ) end_of_seh = freelibrary_EP # build sub-payloads (error-notifiers/seh blocks, loader, unloader, etc.) unload_dll_EP = end_of_seh injection_failure_EP = end_of_seh - MESSAGEBOXPAYLOAD_LEN - UNCONDITIONALJMPPAYLOAD_LEN injection_failure_payload = MessageBoxPayload( injection_failure_err_txt_addr, err_caption_addr, kind=MB_ICONERROR, start_offset=injection_failure_EP, pseudo="%s injection failure notification" % dll_name, ) ejection_failure_EP = injection_failure_EP - MESSAGEBOXPAYLOAD_LEN - UNCONDITIONALJMPPAYLOAD_LEN ejection_failure_payload = MessageBoxPayload( ejection_failure_err_txt_addr, err_caption_addr, kind=MB_ICONERROR, start_offset=ejection_failure_EP, pseudo="%s ejection failure notification" % dll_name, ) start_of_seh = ejection_failure_EP # SEH = Structured-Exception-Handling if dll_function: import_dll_function_failure_EP = start_of_seh - MESSAGEBOXPAYLOAD_LEN - UNCONDITIONALJMPPAYLOAD_LEN import_dll_function_failure_payload = MessageBoxPayload(import_dll_function_failure_err_txt_addr, err_caption_addr, kind=MB_ICONERROR, start_offset=import_dll_function_failure_EP, pseudo="%s API import failure notification" \ %dll_function, ) start_of_seh = import_dll_function_failure_EP # build payload tail (error-notifiers, etc., live here) payload_tail = Payload(start_offset=start_of_seh) if dll_function: payload_tail.addPayload(import_dll_function_failure_payload) payload_tail.jmp(prolog) payload_tail.addPayload(ejection_failure_payload) payload_tail.jmp(prolog) payload_tail.addPayload(injection_failure_payload) payload_tail.jmp(prolog) if createremotethread: payload_tail.addPayload(freelibraryandexitthread_payload) payload_tail.jmp(prolog) payload_tail.addPayload(exitthread_payload) else: payload_tail.addPayload(freelibrary_payload) payload_tail.jmp(prolog) payload_tail.addBlockEntryTag("carrier thread epilog") payload_tail.popFd() # restore flags payload_tail.popAd() # restore all general-purpose registers payload_tail.retn() payload_tail.addBlockExitTag("carrier thread epilog") if not createremotethread: payload.addBlockEntryTag("carrier thread prolog") payload.push(primary_thread_ctx.Eip) # save EIP payload.pushAd() # save all general-purpose registers payload.pushFd() # save flags (EFLAGS) payload.addBlockExitTag("carrier thread prolog") get_dll_handle_payload = GetModuleHandlePayload( dll_addr, start_offset=payload.getCurrentOffset(), pseudo="get %s handle" % dll_name, ) payload.addPayload(get_dll_handle_payload) payload.cmpEax(0x0) if eject: payload.jz(ejection_failure_EP) payload.saveEax(dll_addr) payload.jmp(unload_dll_EP) else: payload.jnz(payload.getCurrentOffset() + CONDITIONALJMPPAYLOAD_LEN + LOADLIBRARYPAYLOAD_LEN) load_dll_payload = LoadLibraryPayload( dll_addr, start_offset=payload.getCurrentOffset(), pseudo="load %s" % dll_name, ) payload.addPayload(load_dll_payload) payload.cmpEax(0x0) payload.jz(injection_failure_EP) payload.saveEax(dll_addr) if dll_function: import_dll_function_payload = GetProcAddressPayload( dll_addr, dll_function_addr, start_offset=payload.getCurrentOffset(), pseudo="import %s API from %s" % (dll_function, dll_name), ) payload.addPayload(import_dll_function_payload) payload.cmpEax(0x0) payload.jz(import_dll_function_failure_EP) payload.saveEax(dll_function_addr) payload.addBlockExitTag("invoke %s(..)" % dll_function) if dll_function_args: l = len(dll_function_args) for j in xrange(l): payload.push(int(dll_function_args[l - j - 1])) payload.callByReference(dll_function_addr) payload.addBlockExitTag("invoke %s(..)" % dll_function) payload.jmp(prolog) payload.nopSled(start_of_seh - payload.getCurrentOffset()) payload.addPayload(payload_tail) payload.display() printDebug("OK (payload EP = 0x%08X)." % EP) # copy payload to remote code-cave dug earlier printDebug("Writing payload to code-cave in remote process ..") nb_bytes_written = DWORD(0) copy_OK = windll.kernel32.WriteProcessMemory( target_process_handle, codecave_addr, payload.getEgg(), payload.getSize(), byref(nb_bytes_written), ) copy_OK = copy_OK and (nb_bytes_written.value == payload.getSize()) if not copy_OK: # error-check printDebug( "Error: windll.kernel32.WirteProcessMeMemory: couldn't copy payload to code-cave in remote process \ (windll.kernel32.GetLastError() = 0x%08X)." % windll.kernel32.GetLastError()) sys.exit(1) printDebug("OK.") # deploy carrier thread if createremotethread: printDebug( "Creating remote payload carrier thread in target process ..") carrier_tid = DWORD(0) carrier_thread_handle = windll.kernel32.CreateRemoteThread( target_process_handle, 0, 0, EP, 0, 0, byref(carrier_tid), ) if not carrier_thread_handle: # error-check printDebug( "Error: windll.kernel32.CreateRemoteThread: couldn't create remote thread \ (windll.kernel32.GetLastError() = 0x%08X)." % windll.kernel32.GetLastError()) sys.exit(1) printDebug("OK (carrier thread ID = %d)." % carrier_tid.value) windll.kernel32.WaitForSingleObject(carrier_thread_handle, INFINITE) else: printDebug( "Hijacking target process primary thread to execute payload ..") primary_thread_ctx.Eip = EP windll.kernel32.SetThreadContext( primary_thread_handle, byref(primary_thread_ctx), ) windll.kernel32.ResumeThread(primary_thread_handle) windll.kernel32.WaitForSingleObject(primary_thread_handle, INFINITE) printDebug("OK.") # free code-cave printDebug("Freeing code-cave in target process ..") codecave_addr = windll.kernel32.VirtualFreeEx(target_process_handle, codecave_addr, CODECAVE_SIZE, MEM_RELEASE) printDebug("OK.")
def print_allowed_methods_and_exit(allowed_methods): print("Allowed methods: {}.".format(", ".join(allowed_methods))) sys.Exit(1)
def __init__(self, groups, board, inject_xml_file_name): all_json = dict() all_json['version'] = 1 all_json['scope'] = "Firmware" all_params = [] all_json['parameters'] = all_params schema_map = { "short_desc": "shortDesc", "long_desc": "longDesc", "unit": "units", } schema_map_typed = { "min": "min", "max": "max", "increment": "increment", } schema_map_fix_type = { "reboot_required": ("rebootRequired", bool), "decimal": ("decimalPlaces", int), } allowed_types = { "Uint8", "Int8", "Uint16", "Int16", "Uint32", "Int32", "Float" } last_param_name = "" board_specific_param_set = False for group in groups: group_name = group.GetName() def get_typed_value(value: str, type_name: str): if type_name == 'Float': return float(value) if type_name == 'Int32': return int(value) return value for param in group.GetParams(): if (last_param_name == param.GetName() and not board_specific_param_set ) or last_param_name != param.GetName(): curr_param = dict() curr_param['name'] = param.GetName() type_name = param.GetType().capitalize() curr_param['type'] = type_name if not type_name in allowed_types: print( "Error: %s type not supported: curr_param['type']" % (curr_param['name'], curr_param['type'])) sys.Exit(1) curr_param['default'] = get_typed_value( param.GetDefault(), type_name) curr_param['group'] = group_name if param.GetCategory(): curr_param['category'] = param.GetCategory() if param.GetVolatile(): curr_param['volatile'] = True last_param_name = param.GetName() for code in param.GetFieldCodes(): value = param.GetFieldValue(code) if code == "board": if value == board: board_specific_param_set = True # JSON schema has no field for board_specific schema. Ignore. else: #xml_group.remove(xml_param) continue else: #map PX4 param field names to schema names if code in schema_map: curr_param[schema_map[code]] = value elif code in schema_map_typed: curr_param[ schema_map_typed[code]] = get_typed_value( value, type_name) elif code in schema_map_fix_type: curr_param[schema_map_fix_type[code][ 0]] = schema_map_fix_type[code][1](value) else: print('ERROR: Field not in json schema: %s' % code) sys.exit(1) if last_param_name != param.GetName(): board_specific_param_set = False enum_codes = param.GetEnumCodes( ) or '' # Gets numerical values for parameter. if enum_codes: enum_codes = sorted(enum_codes, key=float) codes_list = list() for item in enum_codes: code_dict = dict() code_dict['value'] = get_typed_value(item, type_name) code_dict['description'] = param.GetEnumValue(item) codes_list.append(code_dict) curr_param['values'] = codes_list if len(param.GetBitmaskList()) > 0: bitmasks_list = list() for index in param.GetBitmaskList(): bitmask_dict = dict() bitmask_dict['index'] = int(index) bitmask_dict['description'] = param.GetBitmaskBit( index) bitmasks_list.append(bitmask_dict) curr_param['bitmask'] = bitmasks_list all_params.append(curr_param) #Json string output. self.output = json.dumps(all_json, indent=2)
def parsePuzzle(self): print("Parsing") #click on window to ensure puzzle is in focus pyautogui.click(10,10) #Using a try catch to close the program if there is no puzzle try: #identify the puzzle via image recognition of the empty cells. cellLoc = list(pyautogui.locateAllOnScreen('cell.png', confidence = 0.95)) #store the coord of first cell. this is cell (0,0). self.firstCell = pyautogui.center(cellLoc[0]) pyautogui.moveTo(self.firstCell) self.cellSize = abs(self.firstCell[0] - pyautogui.center(cellLoc[1])[0]) except IndexError: sys.exit("Error - no picross puzzle detected. Ensure that the picross puzzle is visible on the current screen.") except: sys.Exit("Unknown Error occurred") #locate the toggle self.togLoc = pyautogui.locateCenterOnScreen('toggle.png') self.togFill = True #Maximum error is one either way if math.isqrt(len(cellLoc)) in range(4, 6): self.size = 5 elif math.isqrt(len(cellLoc)) in range(9,11): self.size = 10 else: print("err") maxClue = int(math.ceil(self.size/2)) self.clues = np.empty([self.size, 2, maxClue], int) for r in range(self.size): #rows first for clue in range(maxClue, 0 , -1): #move to cell just for user feedback pyautogui.moveTo(((self.firstCell[0] - (clue * self.cellSize)), self.firstCell[1] + (r * self.cellSize))) #calculate the region to search in reg = (pyautogui.position()[0] - int(self.cellSize / 2), pyautogui.position()[1] - int(self.cellSize / 2), self.cellSize, self.cellSize) #check for each of the clues for i in range(self.size + 1): if pyautogui.locateOnScreen((str(i) + ".png"),region = reg, confidence = 0.87) != None: self.clues[r,0,abs(clue-maxClue)] = i break #same again for columns pyautogui.moveTo(((self.firstCell[0] + (r * self.cellSize), self.firstCell[1] - (clue * self.cellSize)))) reg = (pyautogui.position()[0] - int(self.cellSize / 2), pyautogui.position()[1] - int(self.cellSize / 2), self.cellSize, self.cellSize) #check for each of the clues for i in range(self.size + 1): if pyautogui.locateOnScreen((str(i) + ".png"),region = reg, confidence = 0.85) != None: self.clues[r,1,abs(clue-maxClue)] = i break #create the mats #A square mat of the grid #four possible values: empty, marked, incorrect, correct self.grid = np.full((self.size, self.size), "empty") #workingClues holds clues that are still relevant, e.g, clues that have not been fulfilled, #avoids solver filling cells that have allready been filled by a previous rule, and to go back and check what those clues were self.workingClues = self.clues print(self.clues) print("Parsing complete") print(self.grid.shape)