def handle_connection(self, conn): started = time.time() _in = conn.makefile("r") _out = conn.makefile("w") env = self.read_env(_in) # Replace stdin/stdout so we can be lazy sys.__stdin__ = sys.stdin = _in sys.__stdout__ = sys.stdout = _out # Work out wtf our PATH_INFO and SCRIPT_NAME should be if not env.has_key("PATH_INFO"): env["PATH_INFO"] = env["SCRIPT_NAME"][len(self.prefix) :] env["SCRIPT_FILENAME"] = sys.argv[0] env["SCRIPT_NAME"] = self.prefix # Show the page index.main(env=env, started=started, scgi=1) # Clean up try: _in.close() _out.close() conn.close() except IOError: pass
def _handle_events(self): """Käsittelee tapahtumat pelissä eli mikäli ruudukkoon halutaan sijoittaa luku tai halutaan lopettaa peli. """ import index _running = True while True: if _running: self._update_clock() for event in pygame.event.get(): pygame.display.update() if event.type == pygame.MOUSEBUTTONUP and event.button == 1: _pos = pygame.mouse.get_pos() if 530 <= _pos[0] <= 685 and 100 <= _pos[1] <= 160: index.main() pygame.quit() sys.exit(0) elif 30 <= _pos[0] <= 490 and 30 <= _pos[1] <= 490: self._insert((_pos[0] // 50, _pos[1] // 50)) elif 530 <= _pos[0] <= 630 and 470 <= _pos[1] <= 510: if self._grid.is_correct() == True: self._draw_solved() _running = False if event.type == pygame.QUIT: pygame.quit() sys.exit(0)
def main(): parser = parser_generator() args = parser.parse_args() if args.scaler_path: scaler = joblib.load(args.scaler_path) if args.operation == "train": deep_d.train_model(num_epochs=args.num_epochs, path=args.model_path, gamma_scheduler=args.gamma_scheduler, batch_size=args.batch_size, use_qs=args.use_q, lr=args.lr, num_spacings=args.num_spacings, scaler_path=args.scaler_path) elif args.operation == "evaluate": #evaluate.evaluate(args.model_path, use_qs=args.use_q, a=args.a, b=args.b, gamma=args.gamma, scaler=scaler) #TODO: this doesn't work. evaluate.evaluate( **{k: v for k, v in vars(args).items() if v is not None}) elif args.operation == "index": index.main(model_path=args.model_path, scaler=scaler)
def run(self): self.frame.insert('end', '\n开始爬取\n') sys.stdout = redirect(self.frame) index.main(self.settings, self.tags, self.discard_tags) self.frame.insert('end', '\n爬取结束\n') self.frame.see('end') sys.stdout = sys.__stdout__ self.reset_button.config(state='normal')
def logar(): nome = str(user.get()) psw = str(senha.get()) if nome != 'Admin' or psw != '123456': msg2['text'] = "USUÁRIO OU SENHA INCORRETO..." msg['text'] = "" else: root.destroy() main()
def main(): for test in os.listdir("tests"): path = f"tests/{test}" if os.path.isdir(path) and test != "." and test != "..": dotenv.load_dotenv(dotenv_path=pathlib.Path(f"{path}/.env")) test_filename = "{}/{}".format(path, os.environ["PLUGIN_FILENAME"]) os.environ["PLUGIN_FILENAME"] = test_filename comparison_filename = glob.glob(f"{path}/*solution*")[0] index.main() if not filecmp.cmp(test_filename, comparison_filename): sys.exit(1)
def get(self): self.response.headers['Content-Type'] = 'text/html' uid = self.request.get("uid") if uid: show_solved = self.request.get("show_solved") self.response.out.write(index.main(uid, show_solved)) else: self.response.out.write(index.form())
def test_main(dir): path = 'solutions/' + dir index.main(path + '/schrodinger.inp') test_pot = np.genfromtxt('output/potential.dat') test_eigen = np.genfromtxt('output/eigenvalues.dat') test_wave = np.genfromtxt('output/wavefuncs.dat') test_expv = np.genfromtxt('output/expvalues.dat') solution_pot = np.genfromtxt(path + '/potential.dat') solution_eigen = np.genfromtxt(path + '/eigenvalues.dat') solution_wave = np.genfromtxt(path + '/wavefuncs.dat') solution_expv = np.genfromtxt(path + '/expvalues.dat') assert abs(np.all(test_pot - solution_pot)) < 0.1 assert abs(np.all(test_eigen - solution_eigen)) < 0.1 assert abs(np.all(test_wave - solution_wave)) < 0.5 assert abs(np.all(test_expv - solution_expv)) < 0.03
def application(environ, start_response): try: import index return index.main(environ, start_response) except: import traceback start_response('500 Internal Server Error', [('Content-type', 'text/plain')]) return [traceback.format_exc().encode()]
def test_main(inp_dir): """test function for solver output""" path = 'solutions/' + inp_dir index.main(path + '/schrodinger.inp') test_pot = np.genfromtxt('output/potential.dat') test_eigen = np.genfromtxt('output/eigenvalues.dat') test_wave = np.genfromtxt('output/wavefuncs.dat') test_expv = np.genfromtxt('output/expvalues.dat') solution_pot = np.genfromtxt(path + '/potential.dat') solution_eigen = np.genfromtxt(path + '/eigenvalues.dat') solution_wave = np.genfromtxt(path + '/wavefuncs.dat') solution_expv = np.genfromtxt(path + '/expvalues.dat') assert np.allclose(test_pot, solution_pot, 0.1) assert np.allclose(test_eigen, solution_eigen, 0.1) assert np.allclose(test_wave, solution_wave, 0.5) assert np.allclose(test_expv, solution_expv, 0.03)
def click_select_proect(self): laravel = self.laravel.isChecked() modx = self.modx.isChecked() if (laravel): type_project = 'laravel' if (modx): type_project = 'modx' laravel_app = QtWidgets.QApplication( sys.argv) # Новый экземпляр QApplication win = index.main() # Создаём объект класса StartWindow win.show() # Показываем окно sys.exit(laravel_app.exec())
def clicked(): """ Send request to the index function to perform the needy and performs error handling Parameters ---------- None Returns ------- None """ res = "Processing " + txt.get() + "..." outputval = index.main(str(txt.get())) # lbl.configure(text= res) # lbl.configure(text="Your output file is ready!") if outputval == 0: messagebox.showinfo( 'Processing Done!', 'Output file has been generated! Thank you for using the application!' ) print("Output ready!") elif outputval == 1: messagebox.showinfo( "Format unsupported!", 'Unfortunately, we only accept mp4 files as of now!') elif outputval == 2: messagebox.showinfo( "File too big!", 'Please use a smaller file! Anything below 8 minutes should be fine!' ) else: messagebox.showinfo( "Unknown Error!", 'Unknown error has occured. We will investigate it!')
import search import index from sys import argv import os if __name__ == "__main__": if len(argv) < 2: raise ValueError('Expected at least one command line argument.') if argv[1] == 'index': # построение индекса if len(argv) > 2: index.main(['index.py', argv[2]]) else: index.main(['index.py']) elif argv[1] == 'search': # булев поиск search.main() elif argv[1] == 'clean': # очистка временныъ данных path = 'temp_dumps/' if len(argv) < 3 else argv[2] if path[-1] != '/': path += '/' flag = False for file in ('reversed_index.gz', 'word_to_id.gz', 'id_to_url.gz', 'url_to_id.gz'): if os.path.exists(f'{path}{file}'): os.system(f'rm {path}{file}') flag = True if not flag: raise ValueError('The directory does not contain temporary files.') else: raise ValueError('Unexpected command line argument.')
def test_main_returns_true(): assert main() == True
def face_recognize(): index.main()
def testSentInfo(self): #mock_recog = Mock() #index.sendLicPlate((mock_recog)) #print(index.mock_calls) self.assertEqual(index.main(),'U8NTBAD') # test the image recognition
# # with open(w_csv, 'a')as f: # writer = csv.writer(f, lineterminator='\n') # writer.writerows(list_pea) ################################################################################ add_trues_list = trues_list + add_trues_list add_trues_list = list(set(add_trues_list)) pd.to_pickle(add_trues_list, pkl_path) ################################################################################ #ファイル書き出し ret_text = ret_text.replace("<br>", "\n").replace('<span class="mstake">', "").replace( "</span>", "").replace("<", "<").replace(">", ">") with open(f_path, 'w') as f: f.write(ret_text) ################################################################################ #次のファイル読込 tit, txt = index.main() if txt is None: response = {"txtx": "すべてのファイルが終了しました。", "title": "end"} else: response = {"txtx": txt, "title": tit} print( 'Content-type: text/html\nAccess-Control-Allow-Origin: *;charset=UTF-8\n') print(json.JSONEncoder().encode(response))
def get(self): self.write(unicode(index.main(self)))
def run(self): self.frame.insert('end', '\n开始爬取\n') index.main(self.settings, self.tags, self.discard_tags, self.frame, False) self.frame.insert('end', '爬取结束') self.reset_button.config(state='normal')
def main(argv): # { q = Queue() storedPages = [] if len(argv) > 0: if isinstance(argv, list): for a in argv: q.push(a) else: q.push(argv) else: q.push("https://en.wikipedia.org/wiki/String_theory") # q.push("http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array") while len(storedPages) < 100 and not q.isEmpty(): # { url = q.pop() if url in storedPages: continue urlLen = len(url) protocol = '' if ':' in url: protocol = url.split(':', 1)[0] else: continue if not protocol or 'http' not in protocol: continue try: page = RIW.main(url)[0] # get an parse the page with own module "./RIW.py" except: e = sys.exc_info() type = e[0] msg = e[1] print(type) print(msg) continue urlContent = page["content"].decode() urlText = page["text"].decode() urlLinks = page["a"] for link in urlLinks: if link not in storedPages and link not in q: q.push(link) if url[urlLen - 5:urlLen] != '.html': url += '.html' path_file = url.split('//', 2) path_file = path_file[1] if len(path_file) == 2 else path_file[0] indexOfFilenameStart = len(path_file) - 1 - path_file[::-1].index( '/') + 1 # last index of '/' + 1 is the start of the filename path_folder = pathToStore + '/' + protocol + '/' + path_file[:indexOfFilenameStart - 1] filename = path_file[indexOfFilenameStart:] for f in forbidden: if f in filename: continue if not os.path.exists(path_folder): os.makedirs(path_folder) path_file = path_folder + '/' + filename file_page = open(path_file, mode='w', encoding='utf-8') file_page.write(urlContent) file_page.close() file_page = open(path_file[:len(path_file)-4]+'txt', mode='w', encoding='utf-8') file_page.write(urlText) file_page.close() if os.path.exists(path_file) and os.path.exists(path_file[:len(path_file)-4]+'txt'): storedPages.append(url[:urlLen]) print(len(storedPages)) # } while not empty or 100 # call index.py to index stored pages "./storage" index.main(pathToStore) # index.py for downloaded content to be searchable
def do_request(self): global globalargs host = self.headers.get('host').split(':') hostport = host[1] if len(host) > 1 else '80' host = host[0] hostkeys = host.split('.') while len(hostkeys) > 0: if os.path.exists('.'.join(hostkeys) + '/index.py'): break hostkeys = hostkeys[1:] hostpath = '.'.join(hostkeys) if forbiddenre.match(self.path) is not None: #forbidden something msg = '\r\nYou can\'t go here.' self.send_response(403) self.send_header('Content-length', str(len(msg))) self.wfile.write(msg) return if datare.match(self.path) is not None: try: reqmed = open(os.path.join(hostpath, self.path[1:])).read() self.send_response(200) self.send_header('Content-length', str(len(reqmed))) import mimetypes type = mimetypes.guess_type(self.path)[0] if type is None: type = 'application/octet-stream' self.send_header('Content-type', type) self.send_header('Connection', 'Close') #TODO: why the hell am I hanging on keep-alive connections? self.end_headers() self.wfile.write(reqmed) return except IOError as ex: if ex.errno == 21 and noindexesre.match(self.path) is None: self.basic_response(200, 'Directory indexes! Not actually a thing yet.') else: self.basic_response(404, '404 Not Found\r\n\r\nThe file you requested does not exist.') return import webframe try: if globalargs['debug']: reload(webframe) webframe.setupSwitch((self, host, hostport)) if hostpath != '': if '.' not in sys.path: sys.path.append('.') os.chdir(hostpath) import index if globalargs['debug']: reload(index) index.main() except Exception as e: resp = 'Internal server error!' import traceback tb = '\n'.join(traceback.format_exception(*sys.exc_info())) print tb if globalargs['printerrors']: resp += ' Here\'s the deal:\n\n' + tb if len(webframe.documentErrors) != 0: resp += '\n\nIn addition, webframe accumulated the following errors:\r\n\t\n' resp += '\n'.join(webframe.documentErrors) self.basic_response(500, resp) return
import index import datetime def validate(date_text): try: datetime.datetime.strptime(date_text, '%d-%m-%Y') except ValueError: raise ValueError("Incorrect data format, should be YYYY-MM-DD") data = index.main() DATE = 0 RESERVOIRS = { '1': { 'name': 'POONDI', 'maxWaterLevel': 3000.00 }, '2': { 'name': 'CHOLAVARAM', 'maxWaterLevel': 800.00 }, '3': { 'name': 'REDHILLS', 'maxWaterLevel': 3200.00 }, '4': { 'name': 'CHEMBARAMBAKKAM', 'maxWaterLevel': 3200.00
def chart(): baz = main() labels = [0, 2, 4, 6, 8, 10] values = baz return render_template('chart.html', values=values, labels=labels)
# define the default module # @2016/05/17 import index index.main()
#!/usr/bin/python3 """Start application""" import os import sys import index if __name__ == "__main__": os.system('clear') # Resizing terminal width and height sys.stdout.write("\x1b[8;{rows};{cols}t".format(rows=30, cols=100)) index.main()