def run(args): """ For a list of arguments tha the main is called, run function calls specific methods or returns error messages if sth is wrong. :param args: List of sys arguments retrieved from the command line. :return: the results of run execution. Either messages of results of function execution. """ if len(args) > 1: if args[1] == 'generate': return multi_gen(int(args[2])) if len(args) > 2 else multi_gen() elif args[1] == 'generate_leg': return multi_legacy_gen(int(args[2])) if len(args) > 2 else multi_legacy_gen() elif args[1] == 'resolve': os.system('clear') values = multi_gen(int(args[2])) if len(args) > 2 else multi_gen() return printer(values) elif args[1] == 'resolve_leg': os.system('clear') values = multi_legacy_gen(int(args[2])) if len(args) > 2 else multi_legacy_gen() return printer(values) elif args[1] == 'offline' and args[2] == 'resolve': os.system('clear') values = multi_gen(int(args[3])) if len(args) > 3 else multi_gen() return printer(values, True) elif args[1] == 'offline' and args[2] == 'resolve_leg': os.system('clear') values = multi_legacy_gen(int(args[3])) if len(args) > 3 else multi_legacy_gen() return printer(values, True) else: return (Style.BRIGHT + Fore.RED + 'Not Supported Command' + Fore.WHITE + Style.NORMAL) else: return (Style.BRIGHT + Fore.RED + 'Not enough arguments' + Fore.WHITE + Style.NORMAL)
def run(self): print 'USRP #',self.ip,'DP Thread Launched' printer.header(self.csvfile) for mc in range (int((run_time /self.rx.rawfile.T_big))): if not keepRunning: break self.counter += 1 self.rx.dp_track(1) printer.printer(\ self.counter,\ weekno,\ self.rx.rxTime_a,\ self.rx.ekf.X_ECEF,\ self.csvfile\ ) self.X_list += [self.rx.ekf.X_ECEF.copy()] self.rxTime_list += [self.rx.rxTime_a] if self.counter % 100 == 0: np.save(postpath+'usrp%d_X'%self.ip,np.array(self.X_list)) np.save(postpath+'usrp%d_t'%self.ip,np.array(self.rxTime_list)) self.rx.save_measurement_logs(dirname = postpath,subdir= 'end-of-dp_usrp%d'%self.ip) print 'DP File saved, continue running.' print 'DP Concluded.' elapse = time.time() - start print elapse,'seconds elapsed for %ds data proc.'%np.ceil(self.rx.rawfile.T_big * mc) np.save(postpath+'usrp%d_X'%self.ip,np.array(self.X_list)) np.save(postpath+'usrp%d_t'%self.ip,np.array(self.rxTime_list)) #self.rx.save_measurement self.rx.save_measurement_logs(dirname = postpath,subdir= 'end-of-dp_usrp%d'%self.ip) self.csvfile.close() self.running = False
def send2printer(self): self.action_done = True for _ in range(self.nbPrint): printer(self.lastPhoto) self.printer_fan_thread = Thread(target=self.printer_fan_controler) self.printer_fan_thread.start() self.set_compt_print(self.nbPrint) self.show_cam()
def __init__(self,_x,_y,_block,_trap,_goal,_cost,_gamma,_prob_succ): self.x=_x self.y=_y self.block=_block self.trap =_trap self.goal =_goal self.cost =_cost self.arr = [[0 for x in range(_x)]for y in range(_y)] self.rewardArr = [[0 for x in range(_x)]for y in range(_y)] self.ArrowArr = [[0 for x in range(_x)]for y in range(_y)] self.gamma = _gamma self.prob_succ = _prob_succ self.prob_fail = (1-self.prob_succ)/2 self.printer = printer() self.iter=0 for b in self.block: self.arr[b[1]][b[0]]='X' self.ArrowArr[b[1]][b[0]]='X' self.rewardArr[b[1]][b[0]]='X' for t in self.trap: self.arr[t[1]][t[0]]=float(t[2]) self.ArrowArr[t[1]][t[0]]=float(t[2]) self.rewardArr[t[1]][t[0]]=float(t[2]) for g in self.goal: self.arr[g[1]][g[0]]=float(g[2]) self.ArrowArr[g[1]][g[0]]=float(g[2]) self.rewardArr[g[1]][g[0]]=float(g[2]) print("Created ",self.x,"x",self.y,"Gridworld") print("With",len(self.trap),"Traps and",len(self.goal),"Goals")
def __init__(self): self.printer = printer.printer(self.printer_onlineCallback, self.printer_offlineCallback, self.printer_positionCallback, self.printer_temperatureCallback, self.printer_receiveCallback, self.printer_sendCallback) self.printProcess = printer.printprocess( self.printer, self.printProcess_showImageCallback, self.printProcess_hideImageCallback, self.printProcess_startedPrintingCallback, self.printProcess_finishedPrintingCallback) self.isOnline = False self.isPrinting = False self.reader = csv.reader(sys.stdin, csv.get_dialect('StdioPrinterDriverCustom')) self.writer = csv.writer(sys.stdout, csv.get_dialect('StdioPrinterDriverCustom')) self.verbMap = { 'move': self.move, 'moveTo': self.moveTo, 'home': self.home, 'lift': self.lift, 'askTemp': self.askTemp, 'send': self.send, 'queryOnline': self.queryOnline, 'queryPrinting': self.queryPrinting, 'stopPrinting': self.stopPrinting, 'terminate': self.terminate }
def _print(self, picture): #Take in the payload with the name print("Print command: ({})".format(picture), file=sys.stderr) print("printing " + picture.lower().replace(" ", "") + ".png") # conjoin words and make lowercase to match filename if picture.lower().replace(" ", "") == "custom": # if the print id is "custom" - take a picture using the webcam. Use imagemagick to do canny edge detection and various edits to optimize the picture for printing print("taking picture") os.system( "fswebcam --no-banner -r 640x480 --jpeg 85 -D 1 web-cam-shot.jpg ; convert web-cam-shot.jpg -colorspace gray -canny 0x1+10%+10% -negate -rotate -90 -posterize 3 -resize 120 -threshold 80% -monochrome custom.png" ) # call printer() from printer.py print("starting print") printer.printer(picture.lower().replace(" ", "") + ".png")
def start_game(): for i in range(GAME_NUM): manager.registerAI("printer", printer(gateway)) print("Start game", i) game = manager.createGame("ZEN", "LUD", "printer", "RandomAI") manager.runGame(game) print("After game", i) sys.stdout.flush()
def main(): irc = twitchchat("drluke4", "oauth:vb6vffy4rqtvon9izfi928g3yoytd1", "#drluke4") uguu = bot(irc) pri = printer(uguu) irc.addcommand(uguu.drawmatrixcallback, "draw") irc.addcommand(uguu.helpcallback, "help") irc.addcommand(uguu.drawhexcallback, "hex") while(1): irc.parse(bytes.decode(irc.recv())) if(not irc.valid): irc = twitchchat("drluke4", "oauth:vb6vffy4rqtvon9izfi928g3yoytd1", "#drluke4") pri.work()
def main(): irc = twitchchat("drluke4", "oauth:vb6vffy4rqtvon9izfi928g3yoytd1", "#drluke4") uguu = bot(irc) pri = printer(uguu) irc.addcommand(uguu.drawmatrixcallback, "draw") irc.addcommand(uguu.helpcallback, "help") irc.addcommand(uguu.drawhexcallback, "hex") while (1): irc.parse(bytes.decode(irc.recv())) if (not irc.valid): irc = twitchchat("drluke4", "oauth:vb6vffy4rqtvon9izfi928g3yoytd1", "#drluke4") pri.work()
def __init__(self): self.printer = printer.printer(self.printer_onlineCallback, self.printer_offlineCallback, self.printer_positionCallback, self.printer_temperatureCallback, self.printer_receiveCallback, self.printer_sendCallback) self.isOnline = False self.isPrinting = False self.reader = csv.reader(sys.stdin, csv.get_dialect('StdioPrinterDriverCustom')) self.writer = csv.writer(sys.stdout, csv.get_dialect('StdioPrinterDriverCustom')) self.verbMap = { 'moveRel': self.moveRel, 'moveAbs': self.moveAbs, 'home': self.home, 'send': self.send, 'terminate': self.terminate }
x = 0 while x != len(added): z = z + 1 print(added[x]) name = added[x] if "pi" in name or "mono" in name: # os.system('convert /var/www/html/uploads/'+added[x]+' -rotate 90 -negate -flop -monochrome print.png') os.system( 'convert /var/www/html/uploads/' + added[x] + ' -rotate 90 -negate -resize 132 -monochrome print.png') save = added[x] added[x] = 'print.png' added[x] = added[x].replace(" ", "\ ") if "photo" in name: print("Processing...") os.system('convert "/var/www/html/uploads/' + added[x] + '" -negate -resize 132 -monochrome print.png') # os.system('convert "/var/www/html/uploads/'+added[x]+'" -negate -flop -monochrome print.png') save = added[x] added[x] = 'print.png' added[x] = added[x].replace(" ", "\ ") if "color" in name: os.system('cp "/var/www/html/uploads/' + added[x] + '" print.png') save = added[x] added[x] = 'print.png' added[x] = added[x].replace(" ", "\ ") x = x + 1 printer.printer("print.png") before = after
from intro import intro from input_parser import input_parser from compressor import compressor from printer import printer from robo_browser import robo_browser from misc_data import ListAlbum # This is what runs the program. It calls multiple methods from different files to do so. user_object = intro() album_list = ListAlbum() input_parser(user_object, album_list) album_object = compressor(album_list) printer(album_object) robo_browser(album_object, user_object)
from printer import printer if __name__ == '__main__': printer().printSomething()
def newInvoiceMaker(): print( "Welcome to your InvoiceMaker 0.1\nLet's start creating an Invoice!!!") s = start() name, ssn, client, venue, address, phone, email, invoiceName = infoMaker() info = { 'info': [name, ssn, client, venue, address, phone, email], 'fields': [ 'Name: ', 'SSN: ', 'Client:', 'Venue: ', 'Address: ', 'Phone: ', 'E-mail: ' ] } while s == True: newLine = "Y" lines = [] dateList = [] positionList = [] timeInList = [] timeOutList = [] walkAwayList = [] rateList = [] hoursList = [] otList = [] totalList = [] grandTotal = 0 while newLine == "Y": date = dateValidator( input( "For what date do you want to create this Invoice? (mm/dd/yy) : " )) position = input("What's your position for this day? : ") timeIn = input("At what time did you got in? (AM/PM) : ").upper() timeOut = input("At what time did you got out? (AM/PM) : ").upper() walkAway = input( "Did you have an hour of Walkaway? (Y/N) : ").upper() rate = input( "What's your rate for this position? (Only numbers) : ") body = printer(date, position, timeIn, timeOut, walkAway, rate) lines.append(body[0]) grandTotal += body[2] dateK = dateValidator(date) dateList.append(dateK) positionList.append(position) timeInList.append(time_fixer(timeIn)[0]) timeOutList.append(time_fixer(timeOut)[0]) #Gets the time fixed and gets the number for total time logic inh = time_fixer(timeIn) outh = time_fixer(timeOut) #Calculate the total amount of hours hours = outh[1] - inh[1] ot = 0 timeH = hourChecker(hours, walkAway) hours = timeH[0] ot = timeH[1] hoursList.append(str(hours)) walkAwayList.append(walkAway) otList.append(str(ot)) rateList.append(f'${rate}') total = (hours * int(rate)) + (ot * (int(rate) * 1.5)) totalList.append(str(total)) newLine = body[1] else: gT = len(rateList) + 11 grandT = {'field': ['Grand Total: '], 'total': [str(grandTotal)]} path = f'{invoiceName}.xlsx' xldata = { 'Date': dateList, 'Position': positionList, 'Time In:': timeInList, 'Time Out:': timeOutList, 'Walkaway:': walkAwayList, 'Hours:': hoursList, 'OT:': otList, 'Rate:': rateList, 'Total:': totalList } df2 = pd.DataFrame(info) df2.set_index('fields', drop=True, inplace=True) df = pd.DataFrame(xldata) df3 = pd.DataFrame(grandT) df3.set_index('field', drop=True, inplace=True) writer = ExcelWriter(path, engine='xlsxwriter', mode='w') df2.to_excel(writer, header=None) df3.to_excel(writer, startcol=7, startrow=gT, header=None) df.to_excel(writer, index=False, startrow=10) writer.save() print("Thanks for using InvoiceMaker v0.1") break
merger = mgr.merger(args.process, yamldir, args.version) merger.merge(args.force) elif args.clean: print 'clean the dictionnary and eos' import cleaner as clf clean = clf.cleaner(indir, yamldir, args.process, args.version) clean.clean() elif args.cleanold: print 'clean the dictionnary from old jobs that have not been checked' import cleaner as clf clean = clf.cleaner(indir, yamldir, args.process, args.version) clean.cleanoldjobs() elif args.web: import printer as prt webfile = webfile.replace('VERSION', args.version) printdic = prt.printer(yamldir, indir, webfile, args.version) printdic.run() elif args.remove: if args.process == '': print 'need to specify a process, exit' sys.exit(3) print 'remove process %s from eos and database' % args.process import remove as rmp remove = rmp.remove(args.process, indir, yamldir, args.version) remove.remove()
[If(And(bl_corner[j][0] <= i, i < bl_corner[j][0] + dim_pieces[j][0]), dim_pieces[j][1],0) for j in range(pieces)]) <= h) for i in range(h): for j in range(pieces): implied.append(Sum( [If(And( bl_corner[j][1] <= i, i < bl_corner[j][1] + dim_pieces[j][1]), dim_pieces[j][0],0) for j in range(pieces)]) <= w) solver = Solver() solver.add(constraints) if solver.check() == sat: m = solver.model() printer(m, true_dim, bl_corner, h, w, pieces, solver, # If you want to save the solution uncomment this parameter and specify the path in output #file = join(output_dir,filename).replace(".txt", "-out.txt"), rotation = True, solution = True, statistics = False console_output = True ) else: print("Not satisfiable")
def run(self): print 'USRP #', self.ip, 'DP Thread Launched' xFileFile = open(postpath + 'usrp%d_XFile.csv' % self.ip, 'w') xwriter = csv.writer(xFileFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) rcFileFile = open(postpath + 'usrp%d_rc.csv' % self.ip, 'w') rcwriter = csv.writer(rcFileFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) riFileFile = open(postpath + 'usrp%d_ri.csv' % self.ip, 'w') riwriter = csv.writer(riFileFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) fcFileFile = open(postpath + 'usrp%d_fc.csv' % self.ip, 'w') fcwriter = csv.writer(fcFileFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) fiFileFile = open(postpath + 'usrp%d_fi.csv' % self.ip, 'w') fiwriter = csv.writer(fiFileFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) cpFileFile = open(postpath + 'usrp%d_cp.csv' % self.ip, 'w') cpwriter = csv.writer(cpFileFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) printer.header(self.csvfile) for mc in range(int((run_time / self.rx.rawfile.T_big))): if not keepRunning: break self.counter += 1 self.rx.dp_track(1) printer.printer(\ self.counter,\ weekno,\ self.rx.rxTime_a,\ self.rx.ekf.X_ECEF,\ self.csvfile\ ) self.X_list += [self.rx.ekf.X_ECEF.copy()] #temp_rc = [] #temp_ri = [] #temp_fc = [] #temp_fi = [] #temp_cp = [] #for prn in self.rx.channels: # temp_rc.append(self.rx.channels[prn].rc[self.rx._mcount]) # temp_ri.append(self.rx.channels[prn].ri[self.rx._mcount]) # temp_fc.append(self.rx.channels[prn].fc[self.rx._mcount]) # temp_fi.append(self.rx.channels[prn].fi[self.rx._mcount]) # temp_cp.append(self.rx.channels[prn].cp[self.rx._mcount]) #self.rc_list += [temp_rc.copy()] #self.ri_list += [temp_ri.copy()] #self.fc_list += [temp_fc.copy()] #self.fi_list += [temp_fi.copy()] #self.cp_list += [temp_cp.copy()] #self.rxTime_list += [self.rx.rxTime_a] xwriter.writerow(np.squeeze(self.rx.ekf.X_ECEF).tolist()[0]) #rcwriter.writerow(temp_rc) #riwriter.writerow(temp_ri) #fcwriter.writerow(temp_fc) #fiwriter.writerow(temp_fi) #cpwriter.writerow(temp_cp) if self.counter % 100 == 0: np.save(postpath + 'usrp%d_X' % self.ip, np.array(self.X_list)) np.save(postpath + 'usrp%d_t' % self.ip, np.array(self.rxTime_list)) self.rx.save_measurement_logs(dirname=postpath, subdir='end-of-dp_usrp%d' % self.ip) print 'DP File saved, continue running.' print 'DP Concluded.' elapse = time.time() - start print elapse, 'seconds elapsed for %ds data proc.' % np.ceil( self.rx.rawfile.T_big * mc) np.save(postpath + 'usrp%d_X' % self.ip, np.array(self.X_list)) np.save(postpath + 'usrp%d_t' % self.ip, np.array(self.rxTime_list)) #self.rx.save_measurement self.rx.save_measurement_logs(dirname=postpath, subdir='end-of-dp_usrp%d' % self.ip) self.csvfile.close() xFileFile.close() rcFileFile.close() riFileFile.close() fcFileFile.close() fiFileFile.close() cpFileFile.close() self.running = False
import printer printer.printer('hello')
from printer import printer printer("hi")
# -*- encoding: utf-8 -*- """ Включение имени из модуля в область видимости """ from printer import printer # copy out one variable printer("Hello world!") # no need to qualify name
# -*- encoding: utf-8 -*- """ Включение имени из модуля в область видимости """ from printer import printer # copy out one variable printer('Hello world!') # no need to qualify name
).lower() if inp != 'y': filename = input( "Enter the path to a wordlist file. \nKeep empty for the default SOWPODS(format: new words on each new line, no capitals): " ) if filename == '': currentgame = GameEngine(playernames, 'new') else: currentgame = GameEngine(playernames, 'new', filename=filename) else: currentgame = GameEngine(playernames, 'new', False) reply = 'C' while reply == 'C': cont = False # A bool allowing to decide for continuing based on the validity of the enetered move while not cont: printer(currentgame.board) for i in currentgame.players: print(i.name, ': Your score is ', i.score) print(playernames[currentgame.turn], ', it is your turn. Here are the letters in you rack.') print(currentgame.players[currentgame.turn].rack) inp = input( 'Do you want to exchange tiles - y/n? (Only possible if the tiles in the pouch are more than 7): ' ).lower() if inp == 'y': tiles_to_exchange = input( 'Enter the tiles you want to exchange (enter a space to exchange a blank tile) - \nexample (ABC to exchange A, B and C): ' ) tiles_to_exchange = list(tiles_to_exchange) status = currentgame.exchange(tiles_to_exchange) if status[0]:
def __init__(self, Config): logging.basicConfig( filename='pb.log', level=logging.INFO, format= '%(asctime)s %(levelname)-7s %(module)-8s/%(funcName)-8s: %(message)s' ) #root = logging.getLogger () #root.setLevel (logging.DEBUG) #fh = logging.FileHandler ('pb.log') #fh.setFormatter (pbFormatter ('%(asctime)s %(levelname)-7s %(module)-8s/%(funcName)-8s: %(message)s')) #root.addHandler (fh) # Init pygame pygame.init() pygame.display.set_caption("Photobooth") #pygame.mouse.set_visible (False) # Set display mode self.screen = pygame.display.set_mode(self.screen_size, pygame.FULLSCREEN) logging.info('Screen size: ' + str(self.screen_size)) # This is a font we use to draw text on the screen (size 36) self.font = pygame.font.Font(None, 68) # Used to manage how fast the screen updates self.clock = pygame.time.Clock() # Print and gallery button self.button_print = pygbutton.PygButton( self.button_print_rect, 'Drucken', bgcolor=RED) self.button_gallery = pygbutton.PygButton( self.button_gallery_rect, 'Galerie', bgcolor=GREEN) # Project name self.name = Config['Name'] if 'Name' in Config else 'Test' logging.info('Name: ' + self.name) # Setup FlashAir card self.fa_address = Config[ 'FlashAirAddress'] if 'FlashAirAddress' in Config else '1.2.3.4' self.fa = card.connection(self.fa_address, 80, 10) logging.info('FlashAir address: ' + self.fa_address) self.connected = False # Last file self.current_file = None # Image folder self.image_folder = os.path.join('images', self.name) if not os.path.exists(self.image_folder): os.makedirs(self.image_folder) if os.access(self.image_folder, os.W_OK): logging.info('Image folder: ' + self.image_folder) else: logging.error('No access to image folder: ' + self.image_folder) # Printer if 'PrinterName' in Config: logging.info('Printer: ' + Config['PrinterName']) self.printer = printer.printer(Config['PrinterName']) # Print history self.phistory = printer.print_history( os.path.join(self.image_folder, 'print_history.txt')) # Upload if 'UploadHost' in Config: UploadSize = [int(Config['UploadSize'])] * 2 self.upload = pbupload.pfweb(self.name, Config['UploadHost'], Config['UploadUser'], Config['UploadPath'], UploadSize) # Add missing files self.upload.addFolder(self.image_folder) else: self.upload = None # QRCode path self.QRPath = Config['QRPath'] if 'QRPath' in Config else None # WhatsApp support self.WhatsAppNumber = Config[ 'WhatsAppNumber'] if 'WhatsAppNumber' in Config else None # Underexposure detection self.UEThreshold = int( Config['UEThreshold']) if 'UEThreshold' in Config else 0 # Telegram bot if 'TGBotToken' in Config: AdminId = int( Config['TGAdminId']) if 'TGAdminId' in Config else None self.TGBot = pbtelepot.pbBot(Config['TGBotToken'], AdminId) self.TGBot.sendMessage('Photobooth started') else: self.TGBot = None # Gallery self.gallery = gallery.gallery(self.screen_size, 4, 3) # State self.state = state.pb_none # Status & Counters self.status_message = '' self.count_images = len(self.GetFileList()) logging.info('Init image count: ' + str(self.count_images)) if self.phistory: # Add number of prints self.count_prints = self.phistory.Count() logging.info('Init print count: ' + str(self.count_prints)) # Current image self.current_image = None
import math import random from lloydCluster import lloydClusters import matplotlib.pyplot as plot from printer import printer file = open("Dataset.txt") points = [] lines = file.readlines() for line in lines: points.append(tuple(map(int, line.split()))) x, y = 0, 0 k = 8 clusters = lloydClusters(points, k) printer(clusters)
else: id_video, _ = endpoint["requests"][randint(0, 1)] for id_cache, _ in endpoint["caches"]: if caches[id_cache] > videos[id_video]: solution[id_cache].add(id_video) caches[id_cache] -= videos[id_video] endpoints_ordered[i]["requests"] = endpoints_ordered[i][ "requests"][1:] shall_we_go_on = True break for i in range(len(solution)): solution[i] = list(solution[i]) return solution, endpoints if __name__ == "__main__": filenames = [ "kittens.in", "me_at_the_zoo.in", "trending_today.in", "videos_worth_spreading.in" ] maxscores = {f: -1 for f in filenames} for i in range(20): for filename in filenames: solution, endpoints = better_better_solution(filename) nowscore = score(endpoints, solution) if nowscore > maxscores[filename]: maxscores[filename] = nowscore printer(solution, filename)
def _sort_headers(headers): """Ensure the column order is always the same.""" headers = set(headers) default_order = ["id", "name", "email"] sorted_headers = [] for i in default_order: if i not in headers: continue headers.remove(i) sorted_headers.append(i) sorted_headers += sorted(headers) return sorted_headers data = [ { "id": "6018975a-dde7-4666-9436-b171c5a11dde", "name": "Jonh Doe", "email": "*****@*****.**", }, { "id": "f05b3da7-701b-40bd-87e8-780693a07b13", "name": "Bob Dylan", "email": "*****@*****.**", }, ] headers = data[0].keys() headers = _sort_headers(headers) lines = format_lines_adjusted_to_console(data, headers) printer(lines)
def __repr__(self): return printer(self)
def main(): from printer import printer import argparse import time import os import sysBuilding startTime = time.time() script_dir = os.path.dirname(__file__) logo = open(script_dir + '/asciilogo.txt', 'r') print(logo.read()[-285:]) print("\nIt's beeing developed by the MSSM/LabMMol laboratory at IQ/UFRJ.") print("More about us in our webpage: https://labmmol.iq.ufrj.br/mssm/ \n") print( "You need to have the topology and the coordinates files as well as the gromacs and plummed installed\n" ) print("in way to use this software.\n") print("Use -h to access the help menu.\n") parser = argparse.ArgumentParser(description="There is no description") # parser.add_argument('--coreSize', help="Number of atoms in the core block of the dendrimer") # parser.add_argument('--interSize', help="Number of atoms in the intermediary block of the dendrimer") # parser.add_argument('--terSize', help="Number of atoms in the terminal block of the dendrimer") parser.add_argument('--host', help="Name of the host molecule", default="Dendrimer") parser.add_argument('--ligand', help="Name of the molecule to be docked", default="Ligand") parser.add_argument('--nligand', help="Number of ligand molecules to be docked", default="10") parser.add_argument('--atomInDend', help="Number of atoms in your model of dendrimer", default=None) parser.add_argument('--atomInLigand', help="Number of atoms in your model of ligand", default=None) parser.add_argument('--ligandCoord', help="Path to the ligand coordinates file", default="ligand.gro") parser.add_argument('--dendCoord', help="Path to the dendrimer coordinates file", default="dend.gro") # parser.add_argument('--dendGeneration', help="Dendrimer generation", default="3") parser.add_argument('--ligandTop', help="Path to the ligand topology file", default="ligand.itp") parser.add_argument('--dendTop', help="Path to the dendrimer topology file", default="dend.itp") parser.add_argument('--FFPath', help="Path to the forcefield directory", default=None) parser.add_argument('--gmxPath', help="Path to the Gromacs binary file", default='/usr/local/gromacs') parser.add_argument('--mdpPath', help="Path to the mdp files directory", default='./mdp') parser.add_argument('--nameOut', help="Output name of the system", default='System') parser.add_argument('--topolOut', help="Output name of the topology file", default='topol.top') parser.add_argument('--dockOut', help="Output name of the docking file", default='plumed_dock.dat') parser.add_argument('--runOut', help="Output name of the run file", default='run.sh') parser.add_argument( '--force', help= "Force constant of the harmonic potential (or the slope in linear potential) in steered dynamics", default="500.0") parser.add_argument( '--method', help= "Docking method: harmonic, linear, shell, harmonicWall or linearWall", default="harmonic") parser.add_argument( '--at', help= "The point of the colective variable in which the potential is zero", default="0.0") parser.add_argument('--workflow', help="Path to the workflow file", default="workflow.inp") parser.add_argument('--nn', help="Path to the workflow file", default="0") parser.add_argument('--np', help="Path to the workflow file", default="0") args = vars(parser.parse_args()) #Getting the atomInDend if args['dendCoord'][-4:] == '.gro': f = open(args['dendCoord']) f.readline() args['atomInDend'] = f.readline().strip() f.close() noneInArgs = False for k in args: if args[k] is None: print("The {0:^15s} should be defined.".format(k)) noneInArgs = True if noneInArgs == True: error("There were some undefined variables.") if not args['method'] in [ 'harmonic', 'linear', 'shell', 'harmonicWall', 'linearWall' ]: error("This is not a valid method.") print("The used list of parameters to dendriDocker are:\n") for i in args: print("{0:15s}: {1}".format(i, args[i])) print("\n") # create workflow based on an external file # workflow=sysBuilding.gromacsBuilding.read_input(args['workflow']) # create workflow using dendridocker parameters workflow = create_workflow(args) sysBuilding.writeMDP.write_mdp(workflow, args['mdpPath']) sysBuilding.writeRun.write_run(run_file=args['runOut'], workdir=".", program=args["gmxPath"], init_struct=args["dendCoord"], topo=args["topolOut"], mdpPath=args["mdpPath"], workflow=workflow) sysBuilding.writeRun.write_submission(file_name="runjob", job_name="TEST1", run_file="./runmd.sh") prt = printer() prt.printPlumedDock(args) prt.printTop(args) # prt.printSetup(args) os.system('chmod u+x {0}'.format(args['runOut'])) os.system('./{0}'.format(args['runOut'])) os.system('rm -rf \#*') print("The run took: {0:.2g} minutes.\n".format( (time.time() - startTime) / 60.0))
# -*- encoding: utf-8 -*- """ Импортирование модуля """ import printer # get module as a whole printer.printer("Hello world!") # qualify to get names
#이파일은 최초 테스트용 입니다. from printer import printer from calc import calc print("hello, welcome to python world.") ''' #반복문을 위한 구구단 연습 name = "jay2" if (name == "jay") : print("welcome jay!!") else : print("wow") temp1 = 1 while(temp1 < 10) : temp2 = 1 while(temp2 <10 ) : print(temp1,"+",temp2,"=",temp1*temp2) temp2 +=1 temp1 += 1 ''' #클래스 생성 및 메소드 호출, 생성자 확인. printer().do(calc().do(3,4)); print ("Good bye!")
def test.printer(self): pass
def test_printer2(self): result = printer.printer([1, 1, 9, 1, 1, 1], 0) self.assertEqual(result, 5)
# -*- encoding: utf-8 -*- """ Импортирование модуля """ import printer # get module as a whole printer.printer('Hello world!') # qualify to get names
def __START(self): os.environ['TZ'] = 'Europe/Copenhagen' self.__process_started = datetime.datetime.now() print self.__process_started if(isinstance(sys.stdout, file)): sys.stdout = printer(self.__webserver_L) try: self.matlab = MATLAB.MATLAB() except Exception as exc: self.__success = "Problem initializing MATLAB: %s" % exc self.__set_state(STATES.FATAL_ERROR) print 'Problem initializing MATLAB' try: self.__freesurfer = FS.FreeSurfer() except Exception as exc: self.__success = "Problem initializing FreeSurfer: %s" % exc self.__set_state(STATES.FATAL_ERROR) print 'Problem initializing FreeSurfer.' try: dicom.read_file(self.__dicoms) except Exception as exc: self.__success = "Problem reading DICOM files: %s" % exc self.__set_state(STATES.FATAL_ERROR) print 'Invalid data or datapath.' return print "Checking integrity of metadata." try: self.data = get_data.DataForDocument( self.__dicoms, self.__freesurfer, self.__db_L) self.data.check_integrity_pt_data() except Exception as exc: self.__success = "Problem processing patient data and database: %s" % exc self.__set_state(STATES.FATAL_ERROR) print "Problem initializing patient data and database: %s" % exc try: if(not self.data.data["patientid"] or not self.data.data["accession"] or not self.data.data["series_description"]): raise ValueError( "Patient ID, accession number or series description empty.") self.__patient = Patient(self.data.data['patientid'], self.data.data["accession"], self.data.data["series_description"]) self.__patient.set_internal_ptid_uniq(self.__patient.ID, self.__patient.AccessionNumber, self.__patient.SeriesDescription) except Exception as exc: print "Problem processing patient information: %s" % exc self.__success = "Problem when extracting patient information: %s" % exc self.__set_state(STATES.QUITTING) return if(self.__pid_ptid_mapping.has_key((self.__patient.ID, self.__patient.AccessionNumber, self.__patient.SeriesDescription))): self.__set_state(STATES.QUITTING) self.__success = "Processing already in progress" print "Processing already in progress" try: self.__webserver_L.acquire() except Exception as exc: print "Problem acquiring lock: %s" % exc else: try: if(not self.__pid_ptid_mapping.has_key((self.__patient.ID, self.__patient.AccessionNumber, self.__patient.SeriesDescription))): self.__pid_ptid_mapping[self.__patient.ID, self.__patient.AccessionNumber, self.__patient.SeriesDescription] = [ os.getpid(), self.__process_started] except Exception as exc: print "Problem reading and writing to PID-Patient ID mapping: %s" % exc finally: self.__webserver_L.release() try: read_write_files.mod_file(self.__webserver_L, [self.__patient.ID, self.__patient.AccessionNumber, self.__patient.SeriesDescription, self.data.data['scan_date'], self.__process_started, self.__priority], lambda x, y: x + [y], os.path.join(path_constants.jobs, "running")) except Exception as exc: print "Problem modifying file containing runnning processes: %s" % exc try: if(not series_description_indicates_right_format(self.data.data["series_description"], self.__webserver_L)): self.__success = "Error: Series description indicates: Wrong format." self.__state = STATES.QUITTING except Exception as exc: print "Problem reading series description: %s" % exc if(self.__state == STATES.START): self.__set_state(STATES.GET_STATUS)
def send2printer(self): for i in range(self.nbPrint): printer(self.lastPhoto) self.setComptPrint(self.nbPrint) self.ShowCam()
def test_printer1(self): result = printer.printer([2, 1, 3, 2], 2) self.assertEqual(result, 1)
#from instructions import instructions from printer import printer with open("input.txt") as f: content = f.readlines() content = [x.strip() for x in content] my_printer = printer(content) my_printer.run_program()