def recordResults(self): fileAlreadyMade = True file = self.parent.parent.location + '/UserData/' + self.user.username + '/History' if not fileExists(file): os.mkdir(file) file += '/' + str(date.today()) + self.day.lessonName + '.csv' if fileExists(file): writeToCSVFile(file, [{ 'Lesson': self.lesson.filename, 'Accuracy': self.accuracy, 'WPM': self.realWPM, 'IdleTime': self.fileIdleTime }]) else: writeNewCSVFile(file, ['Lesson', 'Accuracy', 'WPM', 'IdleTime'], [{ 'Lesson': self.lesson.filename, 'Accuracy': self.accuracy, 'WPM': self.realWPM, 'IdleTime': self.fileIdleTime }]) self.parent.parent.resultsObject.addResults( lessonName=self.lesson.filename, accuracy=self.accuracy, wpm=self.realWPM, idleTimeInLesson=self.fileIdleTime) self.parent.parent.resultsObject.totalIdleTime += self.fileIdleTime
def build_file_generator(): logger.info("build_file_generator") dockerBuildUtils.make_ndk_build(THIS_DIR) if not fileExists(FG_BIN): raise Exception("Fail to make FileGen") if not fileExists(SINGLE_FG_BIN): raise Exception("Fail to make SingleFileGen")
def make_clean(): logger.info("make_clean") makeUtils.make(THIS_DIR, "clean") if fileExists(FG_BIN): raise Exception("Fail to make clean FileGen") if fileExists(SINGLE_FG_BIN): raise Exception("Fail to make clean SingleFileGen")
def combine(self, song1, song2, song3): if fileExists(song1+'.mp3') and fileExists(song2+'.mp3'): song1 = AudioSegment.from_mp3(song1+'.mp3') song2 = AudioSegment.from_mp3(song2+'.mp3') song = song1 + song2 song.export(song3+'.mp3', format='mp3') print('预合成完成 ...',end = '\r')
def company_write(): try: if fileExists(COMPANY_DATA_FOLDER) and len( listdir(COMPANY_DATA_FOLDER)) == 0: rmdir(COMPANY_DATA_FOLDER) if not fileExists(COMPANY_DATA_FOLDER): prompt_1 = input( "Company data not found! Enroll your company? (Y/N): ").upper( ) if prompt_1 == "Y": mkdir(COMPANY_DATA_FOLDER) company_name = input("Enter Company Name: ") position_num = int( input("Enter number of available positions: ")) if position_num < 1: raise ValueError company_position = "" i = 0 while i < position_num: if len(company_position) == 0: company_position = input("Enter position: ") try: est_salary = int(input("Monthly salary: ")) if est_salary < 1: raise ValueError except ValueError: continue filename = company_file_location(company_position) file = open(filename, "w+") file.write( "Company Position: {}\n".format(company_position)) file.write("Salary: {}\n".format(est_salary)) file.close() i += 1 company_position = "" print_lines() elif prompt_1 == "N": sys.exit() else: raise ValueError except KeyError and ValueError: print("Invalid input! Please try again.") if fileExists(COMPANY_DATA_FOLDER): shutil.rmtree(COMPANY_DATA_FOLDER) print_lines() company_write() except OSError as osexc: if osexc.errno != errno.EEXIST: return print_lines() company_write()
def combineToMp3(self, fp=None, fpz=None): if (fp is not None): self.fp = fp if (fpz is not None): self.fpz = fpz print(self.fp, self.fpz) rw = csr.sub('_', self.word) self.fpzy = os.path.join(self.outdir, '%s_ChEn.mp3' % rw) if fileExists(self.fp) and fileExists(self.fpz): song1 = AudioSegment.from_mp3(self.fp) song2 = AudioSegment.from_mp3(self.fpz) song = song1 + song2 song.export(self.fpzy, format='mp3') print('预合成完成 ...%s' % self.fpzy, end='\r') return
def company_update(): print_lines() print("Available Company data: ") print_dir_contents(COMPANY_DATA_FOLDER) post_input = fix_text_format(input("To edit data, enter position name: ")) filename = company_file_location(post_input) if not fileExists(filename): print_message("Data not found!") main_menu() pfile = open(filename, "r+") contents = pfile.readlines() fields = extract_data(contents) if len(fields) == 0: pfile.close() print_message("Company data is empty!") main_menu() pfile.seek(0) pfile.truncate() print("Press enter to skip updating the specific field.") for key, value in fields.items(): new_value = input("{} ({}): ".format(key, value)) if len(new_value) > 0: fields[key] = new_value pfile.write("{}: {}\n".format(key, fields[key])) pfile.close() print_lines() print_message("Company data updated successfully!") main_menu()
def get_ndk_path(): env_dict = os.environ for key in env_dict: for path in env_dict[key].split(":"): if fileExists(pathJoin(path, "ndk-build")): return path raise Exception("Unable to find ndk path")
def initialise(): makedirs(homepath('~/.ArcheoSiteNamer'), exist_ok=True) if fileExists(_SETTINGS_FILE_PATH): try: _CONFIG.read(_SETTINGS_FILE_PATH) try: _CONFIG["SETTINGS"].getint("desc_length") return _CONFIG["SETTINGS"] except Exception: raise CorruptSettingsError("Corrupt Settings Values") except CorruptSettingsError as e: print(e) print("Settings file is corrupt." " Edit the file directly or reset to default.") print(_SETTINGS_FILE_PATH) with open(_SETTINGS_FILE_PATH, "r") as file: print(file.read()) if input("Reset ALL Settings to default? " "Y to reset, any key to exit: ").upper() == "Y": reset_to_defaults() return initialise() else: print("Exiting...") exit() else: reset_to_defaults() return initialise()
def combineToMP3(self, fileName): if not fileExists(fileName + '.mp3'): self.combine('en', 'zh', fileName) else: self.combine('en', 'zh', 'word') self.combine(fileName, 'word', fileName) print('合成完毕 ...', end='\r')
def build_release(cwd): # _exec_cmd(android update sdk --all --no-ui --filter # extra-android-m2repository", cwd) out, err = exec_task("assembleRelease", cwd) release_apk = pathJoin(cwd, RELEASE_APK_RELATIVE) if not fileExists(release_apk): raise Exception("Fail to build apk:" + str((out, err))) return release_apk
def prepare_file_pattern(): logger.info("prepare_file_pattern") if not fileExists(RANDOM_FILE): with open(RANDOM_FILE, 'w') as rand_file: for i in range(1, 1): f.write(os.urandom(1048576)) adb.push_as_root(RANDOM_FILE, RANDOM_FILE_PHONE) if not android_fileUtils.is_existed(RANDOM_FILE_PHONE): raise Exception("Fail to adb push random file.")
def combine(self, song1, song2, song3): if fileExists(song1 + '.mp3') and fileExists(song2 + '.mp3'): song1 = AudioSegment.from_mp3(song1 + '.mp3') song2 = AudioSegment.from_mp3(song2 + '.mp3') # db1 = song1.dBFS # db2 = song2.dBFS # dbplus = db1 - db2 # if dbplus < 0: # song1 += abs(dbplus) # elif dbplus > 0: # song1 += abs(dbplus) song = song1 + song2 song.export(song3 + '.mp3', format='mp3') print('预合成完成 ...', end='\r')
def add_svg_file(self, svgfile, objname): """ Add a svg file to the composition """ if fileExists(svgfile): root = st.fromfile(svgfile).getroot() self.__SVGS[objname] = root return self.__SVGS[objname] else: print('File {fl} not found.'.format(fl=svgfile)) return None
def employee_read(): print_lines() id_input = input("To read data, enter employee's I.D. Number: ") filename = employee_file_location(id_input) if not fileExists(filename): print_message("Employee data not found!") main_menu() # Calls function 'salary_read' and uses I.D. as parameter salary_read(id_input) print_lines() main_menu()
def main_menu(): company_write() # MAIN MENU print_message("Welcome to Bonapay Payroll Management System") print("Select an action: \n" + "(1) Review company data \n" + "(2) Update company data \n" + "(3) Enroll employee \n" + "(4) Read employee data \n" + "(5) Update employee data\n" + "(6) Delete employee data\n" + "(7) Reset program\n" + "(8) Exit") cmd = int(input(">> ")) print("") if cmd == 1: confirm_prompt("You are about to review your company's data.", company_read) elif cmd == 2: confirm_prompt("You are about to update your company's data.", company_update) elif cmd == 3: confirm_prompt("You are about to enroll your employee's data", employee_write) # READ DATA: elif cmd == 4: print("Available Company data: ") print_dir_contents(EMPLOYEES_DATA_FOLDER) confirm_prompt( "NOTE: To read an employee's data, make sure to enroll an employee first.", employee_read) elif cmd == 5: confirm_prompt("You are about to update your employee's data.", employee_update) # DELETE EMPLOYEE DATA elif cmd == 6: confirm_prompt("You are about to delete your employee's data.", employee_delete) # PROGRAM RESET: elif cmd == 7: print("This will delete all of the enrolled data. Proceed? (Y/N)") cmd_1 = input(">> ").upper() if cmd_1 == "Y": if fileExists(EMPLOYEES_DATA_FOLDER): shutil.rmtree(EMPLOYEES_DATA_FOLDER) print_message("Employee data deleted succesfully!") shutil.rmtree(COMPANY_DATA_FOLDER) print_message("Company data deleted succesfully!") else: error_message() main_menu() # EXIT elif cmd == 8: sys.exit() else: print_message("Invalid input! Try again.") main_menu()
def company_read(): print_lines() post_input = fix_text_format(input("To read data, enter position name: ")) filename = company_file_location(post_input) if not fileExists(filename): print_message("Data not found!") main_menu() file = open(filename, "r") contents = file.readlines() if len(contents) > 0: print("".join(contents)) file.close() main_menu()
def employee_write(): if not fileExists(EMPLOYEES_DATA_FOLDER): mkdir(EMPLOYEES_DATA_FOLDER) employee_fName = input("First Name: ") employee_lName = input("Last Name: ") employee_idNum = input("Employee I.D.: ") filename = employee_file_location(employee_idNum) # FILE EXISTENCE CHECK: if fileExists(filename): print_message("Employee already exists!") main_menu() print_dir_contents(COMPANY_DATA_FOLDER) employee_position = input("Enter Position: ") employee_absences = int(input("Number of Absences: ")) employee_overtimeHrs = int(input("Number of Overtime Hours: ")) employee_late = int(input("Number of Times Late (in mins.): ")) position_filename = company_file_location(employee_position) position_file = open(position_filename, "r+") contents = position_file.readlines() fields = extract_data(contents) employee_salary = fields["Salary"] # DATA WRITING: file = open(filename, "w+") file.write("Employee Name: {}\n".format(employee_fName + " " + employee_lName)) file.write("Employee I.D.: {}\n".format(employee_idNum)) file.write("Employee's Position: {}\n".format(employee_position)) file.write("Num. of Absences: {}\n".format(employee_absences)) file.write("Num. of Overtime Hours: {}\n".format(employee_overtimeHrs)) file.write("Num. of Times Late (in mins.): {}\n".format(employee_late)) file.write("EST. SALARY: {}\n".format(employee_salary)) file.close() print_lines() print_message("Employee data saved successfully!") main_menu()
def employee_update(): print_lines() print("Available employee data: ") print_dir_contents(EMPLOYEES_DATA_FOLDER) id_input = input("To update data, enter employee's I.D. Number: ") filename = employee_file_location(id_input) if not fileExists(filename): print_message("Employee data not found!") main_menu() employee_file = open(filename, "r+") contents = employee_file.readlines() fields = extract_data(contents) if len(contents) == 0 or len(fields) == 0: employee_file.close() print_message("Employee data is empty!") main_menu() employee_file.seek(0) employee_file.truncate() print("Press enter to skip updating the specific field.") for key, value in fields.items(): if key == "Employee I.D.": continue elif key == "Employee's Position": print_dir_contents(COMPANY_DATA_FOLDER) elif key == "EST. SALARY": position_filename = company_file_location( fields["Employee's Position"]) position_file = open(position_filename, "r+") pfields = extract_data(position_file.readlines()) employee_file.write("{}: {}\n".format(key, pfields["Salary"])) continue new_value = input("{} ({}): ".format(key, value)) if len(new_value) > 0: fields[key] = new_value employee_file.write("{}: {}\n".format(key, fields[key])) employee_file.close() print_lines() print_message("Employee data updated successfully!") main_menu()
def build_socket_utils(): logger.info("build_socket_utils") dockerBuildUtils.make_ndk_build(THIS_DIR) if not fileExists(BIN_LOCAL_PATH): raise Exception("Fail to make.")
def build_hcfs_adapter(): logger.info("build_hcfs_adapter") dockerBuildUtils.make_ndk_build(THIS_DIR) if not fileExists(ADAPTER_BIN_LOCAL): raise Exception("Fail to make adapter.")
def get_hcfs_lib_from_phone(): logger.info("get_hcfs_lib_from_phone") adb.pull_as_root(HCFS_LIB_PHONE_PATH, HCFS_LIB) if not fileExists(HCFS_LIB): raise Exception("Fail to adb pull API so file.")
def clean_env(): logger.info("clean_env") if fileExists(HCFS_LIB): os.remove(HCFS_LIB)
def make_clean(): logger.info("make_clean") makeUtils.make(THIS_DIR, "clean") if fileExists(ADAPTER_BIN_LOCAL): raise Exception("Fail to make clean adapter")
def provePrimal(proofOption, output, outputCode, outputReport): tree = etree.parse(output + "report.xml") with Job("Proof"): timeout, nbPar, retry, model = proofOption conf = outputReport + "/report.conf" result_path = output + "proof.json" if fileExists(result_path): with open(result_path, 'r') as f: results = json.load(f) else: results = {} with open(conf, 'w') as f: f.write(REPORT) codes = sorted([p for p in listdir(outputCode) if p.endswith(".c")]) provennow = 0 proven = 0 ignored = 0 for i in range( min(DEBUG_NBR_GOAL, len(codes) ) if DEBUG_NBR_GOAL else len(codes)): fname = codes[i][:-2] name = fname.partition('_')[2] ignore = tree.xpath( "/report/hierarchy/*[@name = '{}']/@ignore".format(name)) if name in ['main', ''] or (ignore[0] == '1' if ignore else False): simpleJob(status(i + 1, len(codes)), "{:45}".format(fname[:45])) simpleJob(" " + color("Ignored", YELLOW)) ignored += 1 continue already = False if name in results and ((not retry) or results[name]['proven']): already = True simpleJob(status(i + 1, len(codes)), "{:45}".format(fname[:45])) else: source = join(outputCode, codes[i]) dest = join(outputReport, fname) with SimpleTimedJob(status(i + 1, len(codes)), "{:45}".format(fname[:45])) as j: data = run( "frama-c", "-wp", source, "-wp-model", model, "-wp-report", conf, "-wp-report-basename", dest, "-wp-prover", "alt-ergo", #"-wp-alt-ergo-opt=-nb-triggers", #"-wp-alt-ergo-opt=4", "-wp-par", str(nbPar), "-wp-timeout", str(timeout), "-wp-rte") #print(data) with open(dest + ".report", 'r') as f: lines = f.read().split("\n") assert (len(lines) == 2) assert ('/' in lines[0]) (nbr, tot) = lines[0].split('/') results[name] = {} results[name]['type'] = fname.partition('_')[0] results[name]['nbr'] = 0 if nbr == '-' else int(nbr) results[name]['tot'] = 0 if tot == '-' else int(tot) results[name]['proven'] = (nbr == tot) and (nbr != '-') results[name]['time'] = j.dt simpleJob(" {0:55} {1:4}/{2:4}".format( redgreen("Already proven" if already else "Proven", "Already failed" if already else "Failed", results[name]['proven']), results[name]['nbr'], results[name]['tot'])) if results[name]['proven']: if not already: provennow += 1 proven += 1 rem = len(codes) - proven - ignored simpleJob( "{0:3} more proven, total: {1:3}+{2:3}/{3:3} ({4:3} remaining)". format(redgreen(provennow), color(proven, RED), color(ignored, YELLOW), len(codes), redgreen(rem, cond=rem == 0))) with open(result_path, 'w') as f: json.dump(results, f, indent=4)
def is_ndk_has_gcc(ndk_path, arch, os, gcc): gcc = pathJoin(ndk_path, "toolchains", arch, "prebuilt", os, "bin", gcc) return fileExists(gcc)
import json import csv from os.path import isfile as fileExists parser = argparse.ArgumentParser() parser.add_argument("srcFiles", nargs='*', help="The JSON files to add to the spreadsheet") args = parser.parse_args() sourceData = args.srcFiles allData = [] for j in sourceData: if fileExists(j): data = json.load(open(j, 'r')) allData += data else: print("\"{}\" is not a valid file".format(j)) freshFile = not fileExists("output.csv") with open("output.csv", 'w', newline='') as f: #While it is possible to grab the fields from the dictionary's keys #that would not guarantee the order will be consistent and does not #account for missing fields fields = [ "teamNumber", "teamRating", "canClimb", "gearLoaded", "gearFloor", "shootsLow", "shootsHigh", "autoStation1", "autoStation2", "autoStation3", "autoDepositGear", "shootsAuto", "comments"
def make_clean(): logger.info("make_clean") makeUtils.make(UTILS_DIR, "clean") if fileExists(UTILS_LOCAL): raise Exception("Fail to make clean alias utils binary")
def build_alias_utils(): logger.info("build_alias_util") dockerBuildUtils.make_ndk_build(UTILS_DIR) if not fileExists(UTILS_LOCAL): raise Exception("Fail to make alias utils binary.")
def make_clean(): logger.info("make_clean") makeUtils.make(THIS_DIR, "clean") if fileExists(BIN_LOCAL_PATH): raise Exception("Fail to make clean")