def _getRegistryHelper(registry, path): filename = os.path.basename(path) usbpath = UsbUtil.toUsbPath(filename) if usbpath == None: return vendorFile = os.path.join(path, "idVendor") deviceFile = os.path.join(path, "idProduct") usbidentifier = None if os.path.isfile(vendorFile) and os.path.isfile(deviceFile): usbidentifier = UsbIdentifier(util.readFile(vendorFile), util.readFile(deviceFile)) node = UsbNode(usbpath, usbidentifier) registry.addNode(node)
def load_data(file_path): lines = readFile(file_path).strip().split("\n") results = [ tuple([float(n) for n in line.strip().split()]) for line in lines ] results = zip(*results) return map(list, results)
def do_open (self, fileName, prof): # assert not modified try: encodedText = util.readFile(fileName) except Exception, e: self.msg_set( tr('#File read error') + ': ' + exMsg(e) )
def checkpath(path, structure): expectedFiles = structure.get('files') expectedAllFile = structure.get('allFile') print('checking', path) if expectedAllFile != None or expectedFiles != None: files = set(os.listdir(path)) if expectedAllFile != None: for file in files: checkpath(os.path.join(path, file), expectedAllFile) elif expectedFiles != None: expectedFileSet = set(expectedFiles.keys()) try: filenameMatches = matchFilenames(files, expectedFileSet) except: err_quit('Ennek a könytárnak pontosan ezen fájlokat kell tartalmaznia: ' + str(expectedFileSet)) for expectedFile in expectedFileSet: checkpath(os.path.join(path, filenameMatches[expectedFile]), expectedFiles[expectedFile]) else: if os.path.getsize(path) > maxFileSize: err_quit('Ez a fájl túl sok helyet foglal! A maximális fájl méret 1MB!') _, ext = os.path.splitext(path) assertByExt = assertsByExt.get(ext) if assertByExt != None: assertByExt(readFile(path), structure)
def new(public=None, description=None, content=None, filename=None): api.getCredentials() log.debug( "Command: New: public: '{0}' description: '{1}' filename: '{2}' content: '{3}'." .format(str(public), str(description), str(filename), str(content))) if public == None: if _supress: public = defaults.public else: public = util.parseBool( util.readConsole(prompt='Public Gist? (y/n):', bool=True)) if description == None: if _supress: description = defaults.description else: description = util.readConsole(prompt='Description:', required=False) if content == None and filename != None: if os.path.isfile(filename): content = util.readFile(filename) else: print("Sorry, filename '{0}' is actually a Directory.".format( filename)) sys.exit(0) if content == None: if _supress: content = defaults.content else: content = util.readConsole() if filename == None: filename = defaults.file log.debug("Creating Gist using content: \n" + content) url = '/gists' data = { 'public': str(public).lower(), 'description': description, 'files': { os.path.basename(filename): { 'content': content } } } log.debug('Data: ' + str(data)) gist = api.post(url, data=data) pub_str = 'Public' if gist['public'] else 'Private' print("{0} Gist created:Id '{1}' and Url: {2}".format( pub_str, gist['id'], gist['html_url']))
def main(filename): input = util.readFile(filename) print(input) sfn = SnailfishNumber.create(input[0]) for n in range(1, len(input)): sfn = sfn.add(SnailfishNumber.create(input[n])) sfn.fullReduce() return f"{sfn}"
def loadKeys(self): ''' Load the preferences keys ''' scriptPath = os.path.dirname(os.path.abspath(__file__)) + '\\' # absKeysFilePath = os.path.normpath(scriptPath + KEYSFILEPATH) absKeysFilePath = self.appctxt.get_resource('preferences.keys') keysFileContent = readFile(absKeysFilePath) for key in keysFileContent['lines']: self.keys.append(key.replace('\n', ''))
def main(): sourceFilename = sys.argv[1] try: backendName = sys.argv[2] except: print 'Error: no backend specified.' print 'You must tell Parrot which backend to use.' usage() return try: source = util.readFile(sourceFilename) except: print 'Error: cannot read file "%s"' % sourceFilename return if backendName not in backendList: print 'Error: Parrot doesn\'t have a "%s" backend.' \ % backendName print "Installed backends are:", for be in backendList: print be, print "\nParrot is aborting now." return #>>>>> create the backendGlobal variable, dependent on backend TheBackend = __import__(backendName + "Backend") backendGlobal = eval('TheBackend.' + backendName + '_GLOBAL()') try: outputFilename = sys.argv[3] except: # couldn't read argv[3], so form the output filename # from the backend outputFilename = backendGlobal.calcOutputFilename(sourceFilename) if debug: print 'outputFilename =', outputFilename #>>>>> read input: if debug: print '----- main: lexical analysis: -----' scanner = pparser.ParrotScanner() res = scanner.tokenize(source) if debug: print '----- main: parsing: -----' # we tell the Parser what (source) is, to help it print # error text if necessary parser = pparser.ParrotParser(source) try: parser.parse(res) except Exception, details: # an error occurred while parsing print "Error occurred while parsing, will not create output." return
def append(id, description=None, content=None, filename=None): api.getCredentials() log.debug( "Command: Append: id: '{0}' description: '{1}' filename: '{2}' content: '{3}'." .format(id, str(description), str(filename), str(content))) if id[0] in _cmds['#']: id = _get_id_for_index(id) if description == None: if _supress: description = defaults.description else: description = util.readConsole(prompt='Description:', required=False) if content == None and filename != None: if os.path.isfile(filename): content = util.readFile(filename) else: print("Sorry, filename '{0}' is actually a Directory.".format( filename)) sys.exit(0) if content == None: if _supress: content = defaults.content else: content = util.readConsole(required=False) if filename == None: filename = defaults.file log.debug("Appending Gist " + id + " with content: \n" + content) oldgist = _get_gist(id) if description and description != '?': oldgist['description'] = description if content and content != '?': for (file, data) in list(oldgist['files'].items()): oldgist['files'][file][ 'content'] = data['content'] + '\n' + content log.debug('Data: ' + str(oldgist)) url = '/gists/' + id gist = api.patch(url, data=oldgist) pub_str = 'Public' if gist['public'] else 'Private' print("{0} Gist appended: Id '{1}' and Url: {2}".format( pub_str, gist['id'], gist['html_url']))
def decrypt(translation, f): in_file = f words = util.readFile(in_file, True, 1)[1:] test_n = 1 with open(in_file + "_out", "w") as f: for w in words: out = "" for c in w: out += translation[c] util.debug("input:%s " % w) out = "Case #%s: %s" % (test_n, out) f.write(out + "\n") test_n += 1 util.debug("out:%s " % out)
def largestFromTwo(filename): input = util.readFile(filename) max = 0 for i in range(0, len(input)): for j in range(0, len(input)): if i != j: sfn1 = SnailfishNumber.create(input[i]) sfn2 = SnailfishNumber.create(input[j]) sum = sfn1.add(sfn2) sum.fullReduce() magnitude = sum.magnitude() if magnitude > max: max = magnitude return max
def update(id, description=None, content=None, filename=None): api.getCredentials() log.debug( "Command: Update: id: '{0}' description: '{1}' filename: '{2}' content: '{3}'." .format(id, str(description), str(filename), str(content))) if id[0] in _cmds['#']: id = _get_id_for_index(id) if description == None: if _supress: description = defaults.description else: description = util.readConsole(prompt='Description:', required=False) if content == None and filename != None: if os.path.isfile(filename): content = util.readFile(filename) else: print "Sorry, filename '{0}' is actually a Directory.".format( filename) sys.exit(0) if content == None: if _supress: content = defaults.content else: content = util.readConsole(required=False) if filename == None: filename = defaults.file log.debug("Updating Gist " + id + " with content: \n" + content) url = '/gists/' + id data = {} if description and description != '?': data['description'] = description if content and content != '?': data['files'] = {os.path.basename(filename): {'content': content}} log.debug('Data: ' + str(data)) gist = api.patch(url, data=data) pub_str = 'Public' if gist['public'] else 'Private' print "{0} Gist updated: Id '{1}' and Url: {2}".format( pub_str, gist['id'], gist['html_url'])
def append (id, description=None,content=None,filename=None): api.getCredentials() log.debug ("Command: Append: id: '{0}' description: '{1}' filename: '{2}' content: '{3}'.".format(id, str(description), str(filename), str(content))) if id[0] in _cmds['#']: id = _get_id_for_index(id) if description == None: if _supress: description = defaults.description else: description = util.readConsole(prompt='Description:', required=False) if content == None and filename != None: if os.path.isfile( filename ): content = util.readFile(filename) else: print "Sorry, filename '{0}' is actually a Directory.".format(filename) sys.exit(0) if content == None: if _supress: content = defaults.content else: content = util.readConsole(required=False) if filename == None: filename = defaults.file log.debug ("Appending Gist " + id + " with content: \n" + content) oldgist = _get_gist(id) if description and description != '?': oldgist['description'] = description if content and content != '?': for (file, data) in oldgist['files'].items(): oldgist['files'][file]['content'] = data['content'] + '\n' + content log.debug ('Data: ' + str(oldgist)) url = '/gists/' + id gist = api.patch(url, data=oldgist) pub_str = 'Public' if gist['public'] else 'Private' print "{0} Gist appended: Id '{1}' and Url: {2}".format(pub_str, gist['id'], gist['html_url'])
def new (public=None,description=None,content=None,filename=None): api.getCredentials() log.debug ("Command: New: public: '{0}' description: '{1}' filename: '{2}' content: '{3}'.".format(str(public), str(description), str(filename), str(content))) if public == None: if _supress: public = defaults.public else: public = util.parseBool( util.readConsole(prompt='Public Gist? (y/n):', bool=True) ) if description == None: if _supress: description = defaults.description else: description = util.readConsole(prompt='Description:', required=False) if content == None and filename != None: if os.path.isfile( filename ): content = util.readFile(filename) else: print "Sorry, filename '{0}' is actually a Directory.".format(filename) sys.exit(0) if content == None: if _supress: content = defaults.content else: content = util.readConsole() if filename == None: filename = defaults.file log.debug ("Creating Gist using content: \n" + content) url = '/gists' data = {'public': str(public).lower(), 'description': description, 'files': { os.path.basename(filename): { 'content': content } } } log.debug ('Data: ' + str(data)) gist = api.post(url, data=data) pub_str = 'Public' if gist['public'] else 'Private' print "{0} Gist created:Id '{1}' and Url: {2}".format(pub_str, gist['id'], gist['html_url'])
def cipher_threefish_file(filename,mode): #set iv if ( nw == 4 ) : iv = cts.INITIAL_VECTEUR_4 elif (nw == 8 ) : iv = cts.INITIAL_VECTEUR_8 elif (nw == 16 ) : iv = cts.INITIAL_VECTEUR_16 #generation of initials list of keys, nb_keys in a round = nb of messages in a bloc = blocksize / messagesize keys = key_generation(nb_key) c_blocs = util.readFile(filename, blocksize) c_blocs = cipher_threefish_blocs(mode,c_blocs, keys, blocksize, nr, tweaks) #util.writeFile(filename, c_blocs) str1="" for i in range(len(c_blocs)): for j in range(nw): str1+=str(bin(c_blocs[i][j])) fo = open(filename,"w+") fo.write(str1) fo.close()
async def on_message(message): channel = client.get_channel(int(os.getenv('CHANNEL_ID'))) if message.author == client.user: return mess = message.content.split(' ') mess = mess[0].strip() if message.channel == channel: lastMsg = util.readFile() if not mess.isnumeric(): await message.delete() prompt = f"Message sent by {message.author.mention} was deleted because it violated game rules.\nLast valid count: {lastMsg}" await channel.send(prompt) else: res = int(mess) - lastMsg if res != 1: await message.delete() prompt = f"Message sent by {message.author.mention} was deleted because it violated game rules.\nLast valid count: {lastMsg}" await channel.send(prompt) else: util.writeFile(str(lastMsg + 1))
def main(): path = input("Please Enter the directory Path of your Input Data File: ") prefix = input("Please Enter the Prefix of your Input Data File: ") size = int(input("Please Enter the max Size of Output File in BYTES: ")) filepathlist = util.getAllFiles(prefix, path) if len(filepathlist) == 0: mergedjson = {} raise Exception( "The Path entered is either incorrect or the prefix is incorrect or File Not found" ) elif len(filepathlist) == 1: mergedjson = util.readFile(filepathlist[0]) elif len(filepathlist) == 2: mergedjson = json_merge_recursive(util.readFile(filepathlist[0]), util.readFile(filepathlist[1])) else: mergedjson = json_merge_recursive(util.readFile(filepathlist[0]), util.readFile(filepathlist[1])) for i in range(2, len(filepathlist)): mergedjson = json_merge_recursive(util.readFile(filepathlist[i]), mergedjson) jsonstring = json.dumps(mergedjson, indent=2) util.fileWrite(path, "merge.json", jsonstring) statinfo = os.stat(os.path.join(path, "merge.json")) print("merge.json is your output file") if statinfo.st_size > size: print( "The prefered size is slightly more. Can I please minimize the json removing all indentations" ) print("Y/N") choice = input() if choice == "Y": jsonstring = json.dumps(mergedjson) util.fileWrite(path, "merge.json", jsonstring) statinfo = os.stat(os.path.join(path, "merge.json")) if statinfo.st_size > size: print("Sorry the file size mentioned is low") print("Please try again with more size. Output File Removed") os.remove(os.path.join(path, "merge.json"))
# thomas grice tag130230 import util import sys import NBL args = sys.argv #arg[1] is training data #arg[2] is test data attributes, trainingData = util.readFile(args[1]) # train the NBL naivebayeslearner = NBL.NBL(trainingData, attributes) naivebayeslearner.printProbabilities() # test on training data naivebayeslearner.classifyData(trainingData, "training set") testAttributes, testData = util.readFile(args[2]) naivebayeslearner.classifyData(testData, "test set")
import graph as g import util as util import catagorize as cat import time, csv import minimumGas as mg start = time.time() data = util.readFile( 'cmStatus_src\\result\\contractMethodTxStatusRange_Filter.csv') #data = util.filterOogRate(data,30) print("Data Loaded") dst = 'cmPic2' util.createDirectory(dst) dst += '\\Step' util.createDirectory(dst) util.createDirectory(dst + '\\byMethod') util.createDirectory(dst + '\\byType') csv_write = open('cmPic2\\minimumGas.csv', 'w+', newline='') csv_writer = csv.writer(csv_write, delimiter=',') #csv_writer.writerow(['No', 'Contract', 'Method', 'Type', 'Minimum Gas', 'Recommend Gas']) index = 0 for cm in data: _ = g.plotAll(cm, data[cm], index, dst + '\\') result = mg.calMinimumGas(cm, data[cm]) #csv_writer.writerow([index, cm[0], cm[1], result[1], result[0], ]) index += 1 if (index % 20 == 0):
def run(request, params): if params is None: params = {} url_path = urllib.parse.urlparse(request.path) qs_params = urllib.parse.parse_qs(url_path.query) load_plugins = [] for _plugin_name, _plugin in plugin.plugins.items(): serializable = {} serializable["name"] = _plugin_name serializable["is_loaded"] = _plugin.is_loaded serializable["location"] = _plugin.location serializable["config"] = {} serializable["DESCRIPTION"] = _plugin.config.DESCRIPTION serializable["AUTHOR"] = _plugin.config.AUTHOR serializable["HOMEPAGE"] = _plugin.config.HOMEPAGE serializable["VERSION"] = _plugin.config.VERSION load_plugins.append(serializable) js_init = """ GDBFrontend = {}; GDBFrontend.version = '""" + util.versionString(statics.VERSION) + """'; GDBFrontend.config = {}; GDBFrontend.config.host_address = '""" + str(config.HOST_ADDRESS) + """'; GDBFrontend.config.bind_address = '""" + str(config.BIND_ADDRESS) + """'; GDBFrontend.config.http_port = """ + str(config.HTTP_PORT) + """; GDBFrontend.config.gotty_port = """ + str(config.GOTTY_PORT) + """; GDBFrontend.config.server_port = """ + str(config.SERVER_PORT) + """; GDBFrontend.config.app_path = '""" + str(config.app_path) + """'; GDBFrontend.config.plugins_dir = '""" + str(config.PLUGINS_DIR) + """'; GDBFrontend.config.gdb_path = '""" + str(config.gdb_path) + """'; GDBFrontend.config.is_readonly = """ + json.dumps( config.IS_READONLY) + """; GDBFrontend.load_plugins = JSON.parse('""" + json.dumps( load_plugins) + """'); """ plugin_htmls = "" for _plugin_name, _plugin in plugin.plugins.items(): _html_path = _plugin.webFSPath( os.path.join("html", _plugin_name + ".html")) if os.path.exists(_html_path): fd = open(_html_path, 'r') _plugin_html = fd.read() fd.close() plugin_htmls += "\n" + _plugin_html if "layout" not in params.keys(): gui_mode = statics.GUI_MODE_WEB gui_scripts = "" elif params["layout"] == "terminal": gui_mode = statics.GUI_MODE_WEB_TMUX gui_scripts = "" elif params["layout"] == "gui": gui_mode = statics.GUI_MODE_GUI gui_scripts = "<script src='qrc:///qtwebchannel/qwebchannel.js'></script>" else: request.send_response(404) request.send_header("Content-Type", "text/html; charset=utf-8") request.end_headers() request.wfile.write( ("Invalid mode. (" + params["layout"] + ")").encode()) return html_messageBox = util.readFile( util.webFSPath("/components/MessageBox/html/MessageBox.html")) html_aboutDialog = util.readFile( util.webFSPath("/components/AboutDialog/html/AboutDialog.html")) html_checkbox = util.readFile( util.webFSPath("/components/Checkbox/html/Checkbox.html")) html_fileBrowser = util.readFile( util.webFSPath("/components/FileBrowser/html/FileBrowser.html")) html_sourceTree = util.readFile( util.webFSPath("/components/SourceTree/html/SourceTree.html")) html_fileTabs = util.readFile( util.webFSPath("/components/FileTabs/html/FileTabs.html")) html_threadsEditor = util.readFile( util.webFSPath("/components/ThreadsEditor/html/ThreadsEditor.html")) html_breakpointsEditor = util.readFile( util.webFSPath( "/components/BreakpointsEditor/html/BreakpointsEditor.html")) html_stackTrace = util.readFile( util.webFSPath("/components/StackTrace/html/StackTrace.html")) html_variablesExplorer = util.readFile( util.webFSPath( "/components/VariablesExplorer/html/VariablesExplorer.html")) html_watches = util.readFile( util.webFSPath("/components/Watches/html/Watches.html")) html_fuzzyFinder = util.readFile( util.webFSPath("/components/FuzzyFinder/html/FuzzyFinder.html")) html_disassembly = util.readFile( util.webFSPath("/components/Disassembly/html/Disassembly.html")) html_evaluateExpression = util.readFile( util.webFSPath( "/components/EvaluateExpression/html/EvaluateExpression.html")) html_messageBox = html_messageBox.format(**vars()) html_aboutDialog = html_aboutDialog.format(**vars()) html_checkbox = html_checkbox.format(**vars()) html_fileBrowser = html_fileBrowser.format(**vars()) html_sourceTree = html_sourceTree.format(**vars()) html_fileTabs = html_fileTabs.format(**vars()) html_threadsEditor = html_threadsEditor.format(**vars()) html_breakpointsEditor = html_breakpointsEditor.format(**vars()) html_stackTrace = html_stackTrace.format(**vars()) html_variablesExplorer = html_variablesExplorer.format(**vars()) html_watches = html_watches.format(**vars()) html_fuzzyFinder = html_fuzzyFinder.format(**vars()) html_disassembly = html_disassembly.format(**vars()) html_evaluateExpression = html_evaluateExpression.format(**vars()) html = util.readFile( util.webFSPath("/templates/modules/main/main.html")).format(**vars()) request.send_response(200) request.send_header("Content-Type", "text/html; charset=utf-8") request.end_headers() request.wfile.write(html.encode())
def test_read_file(self): a = readFile("test_util.py") print(a) self.assertTrue(a.startswith("from unittest"))