blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
283
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
41
license_type
stringclasses
2 values
repo_name
stringlengths
7
96
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
58 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
12.7k
662M
star_events_count
int64
0
35.5k
fork_events_count
int64
0
20.6k
gha_license_id
stringclasses
11 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
43 values
src_encoding
stringclasses
9 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
7
5.88M
extension
stringclasses
30 values
content
stringlengths
7
5.88M
authors
sequencelengths
1
1
author
stringlengths
0
73
e9352e5c3de7221e19341d9653e66e2ddcf74025
f7f159ab82ab21b8e66b2d83df066b0595ad2d35
/Main.py
89db2083b3c5b59b7958eb35de98e8f0c91baec2
[ "BSD-3-Clause" ]
permissive
Sniper199999/Password-Manager
c8f0eef6ee0a61257a12b6cec0856f3fd0e569d3
795fff6d44678b286e941c83a4d83000cab44556
refs/heads/main
2023-03-31T14:28:13.385409
2021-04-10T03:39:02
2021-04-10T03:39:02
356,033,352
0
3
BSD-3-Clause
2021-04-09T14:28:10
2021-04-08T19:59:58
Python
UTF-8
Python
false
false
51,448
py
import concurrent.futures import gc import pathlib import sqlite3 import sys import time import traceback import tracemalloc import csv from tqdm import tqdm import PyQt5 from PyQt5 import QtGui, QtWidgets, QtCore from PyQt5.QtCore import Qt, QDate, QThread, pyqtSignal, QRunnable, pyqtSlot, QThreadPool, QObject, QFileInfo from PyQt5.QtGui import QGuiApplication from PyQt5.QtWidgets import QMenu, QMessageBox, QFileDialog from ColorProfile import select_color from GUI import Ui_MainWindow from enc_dec import encrypt, decrypt import sysinfo import string from random import * from PopupUI import Ui_msgbox_cnguser import qrcode import pyotp from selenium import webdriver #QR Code generation.... class Image(qrcode.image.base.BaseImage): def __init__(self, border, width, box_size): self.border = border self.width = width self.box_size = box_size print(border, width, box_size) size = (width + border * 2) * box_size self._image = QtGui.QImage( size, size, QtGui.QImage.Format_RGB16) self._image.fill(QtCore.Qt.white) def pixmap(self): return QtGui.QPixmap.fromImage(self._image) def drawrect(self, row, col): painter = QtGui.QPainter(self._image) painter.fillRect( (col + self.border) * self.box_size, (row + self.border) * self.box_size, self.box_size, self.box_size, QtCore.Qt.black) def save(self, stream, kind=None): pass class DialogBox(QtWidgets.QDialog, Ui_msgbox_cnguser): def __init__(self,parent=None): QtWidgets.QDialog.__init__(self, parent) self.setupUi(self) class WorkerSignals(QObject): finished = pyqtSignal() error = pyqtSignal(tuple) result = pyqtSignal(object) progress = pyqtSignal(int) leng = pyqtSignal(int) #Multithreading implementation class Worker(QRunnable): def __init__(self, fn, *args, **kwargs): super(Worker, self).__init__() # Store constructor arguments (re-used for processing) self.fn = fn self.args = args self.kwargs = kwargs self.signals = WorkerSignals() # Add the callback to our kwargs self.kwargs['progress_callback'] = self.signals.progress @pyqtSlot() def run(self): # Retrieve args/kwargs here; and fire processing using them try: result = self.fn(*self.args, **self.kwargs) except: traceback.print_exc() exctype, value = sys.exc_info()[:2] self.signals.error.emit((exctype, value, traceback.format_exc())) else: self.signals.result.emit(result) # Return the result of the processing finally: self.signals.finished.emit() # Done #This Runs first... class MyWork(QtWidgets.QMainWindow): def __init__(self): super(MyWork, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) #Calls GUI.py, loads the GUI self.show() self.threadpool = QThreadPool() print("Multithreading with maximum %d threads" % self.threadpool.maxThreadCount()) self.table_dict = None self.update_list = 0 self.num = None self.event = None self.result = None self.counter = 0 self.val = 1 self.user_id = None self.logged_in = False self.show_pass_val = False self.dlb = DialogBox() self.ui.setupUi(self) #self.handle() # self.ui.tbox_user_signup.textChanged.connect(self.handle) self.ui.acnCsv_New_Acc.triggered.connect(self.btn_import_clk) self.ui.acnLogout.triggered.connect(self.btn_logout_clk) self.ui.acnExit.triggered.connect(self.close) self.ui.acnRefresh_db.triggered.connect(self.btn_refresh_clk) self.ui.acnDel_mainacc.triggered.connect(self.del_main_acc) self.ui.acnDark.triggered.connect(self.dark) self.ui.acnLight.triggered.connect(self.light) self.ui.acnDefault.triggered.connect(self.default) #self.ui.acnAdd_2FA.triggered.connect() self.ui.acnDel_2FA.triggered.connect(self.del2fa) self.ui.acnAdd_2FA.triggered.connect(self.add2fa) self.ui.acnExport_CSV.triggered.connect(self.btn_export_clk) # CheckBox actions self.ui.tbox_search.textChanged.connect(self.handleTextEntered) #self.ui.tbox_user_login.textChanged.connect(self.asd) self.dlb.tbox_cng_user.textChanged.connect(self.import_cng_username) self.ui.tab_login.currentChanged.connect(self.onChange) #Show Pass Lbl self.dlb.lbl_show_pass.mouseReleaseEvent = lambda event: self.show_pass(6) self.ui.lbl_showpass1_signup.mouseReleaseEvent = lambda event: self.show_pass(0) self.ui.lbl_showpass2_signup.mouseReleaseEvent = lambda event: self.show_pass(1) self.ui.lbl_showpass_add.mouseReleaseEvent = lambda event: self.show_pass(3) self.ui.lbl_showpass_edit.mouseReleaseEvent = lambda event: self.show_pass(4) self.ui.lbl_showpass_login.mouseReleaseEvent = lambda event: self.show_pass(2) self.ui.lbl_showpass_pgen.mouseReleaseEvent = lambda event: self.show_pass(5) # Button actons args = 1 self.ui.btn_login.clicked.connect(self.log_btn_clk) self.ui.btn_signup.clicked.connect(self.reg_btn_clk) self.ui.btn_logout.clicked.connect(self.btn_logout_clk) self.ui.btn_save_add.clicked.connect(self.save_btn_clk) self.ui.btn_delete_action.clicked.connect(self.del_btn_clk) self.ui.btn_edit_action.clicked.connect(self.edit_btn_clk) self.ui.btn_apply_edit.clicked.connect(self.apply_btn_clk) self.ui.btn_refresh.clicked.connect(self.btn_refresh_clk) self.ui.btn_genpass.clicked.connect(self.btn_genpass_clk) self.ui.btn_cpy_pass.clicked.connect(self.btn_cpy_clk) self.ui.btn_export.clicked.connect(self.btn_export_clk) self.ui.btn_signup_done.clicked.connect(self.signup_done_clk) #self.ui.btn_submit_login.clicked.connect(self.submit_login_clk) self.ui.btn_submit_login.mouseReleaseEvent = lambda event: self.submit_login_clk(self.totp) # CellClicked self.ui.table_view.cellDoubleClicked.connect(self.cell_was_clicked) self.ui.table_view.setContextMenuPolicy(Qt.CustomContextMenu) self.ui.table_view.customContextMenuRequested.connect(self.showMenu) self.disablebtn(True) # Register def signup_done_clk(self): self.ui.stk_signup.setCurrentIndex(0) self.ui.tab_login.setGeometry(QtCore.QRect(0, 0, 265, 195)) def reg_btn_clk(self): username_reg = str(self.ui.tbox_user_signup.text()) pass_reg = str(self.ui.tbox_pass_signup.text()) pass_confirm = str(self.ui.tbox_repass_signup.text()) totp = "" no = 1 if len(username_reg) == 0 or len(pass_reg) == 0 or len(pass_confirm) == 0: print("Input Fields Cannot Be Empty!") select_color(str("red"), no, self) self.ui.lbl_warn_signup.setText("Input Fields Cannot Be Empty!") else: conn = sqlite3.connect('User.db') c = conn.cursor() c.execute("SELECT 'User' FROM security WHERE `User` = ? ", (username_reg,)) result = c.fetchall() if result: select_color(str("red"), no, self) self.ui.lbl_warn_signup.setText("Username Already Exists...") print("Username Already Exists Please Select a Different Username") self.ui.tbox_user_signup.setText("") elif pass_reg == pass_confirm: if len(pass_reg) < 8: select_color(str("red"), no, self) self.ui.lbl_warn_signup.setText("Password Must Have Atleast 8 Characters!") print("Password Should Be Atleast 8 Characters Long!") else: if self.ui.chkbox_2fa_signup.isChecked() == True: self.ui.stk_signup.setCurrentIndex(1) self.ui.tab_login.setGeometry(QtCore.QRect(0, 0, 265, 331)) self.ui.stk_signup.setGeometry(QtCore.QRect(3, 3, 261, 301)) totp = self.handle(username_reg, pass_reg, self.ui.lbl_qr_signup) print(username_reg, pass_reg) c = conn.cursor() c.execute('INSERT INTO security(User, Hash, Topt) VALUES(?,?,?)', (username_reg, encrypt(pass_reg, username_reg), totp)) conn.commit() select_color(str("green"), no, self) self.ui.lbl_warn_signup.setText("New Account Registerd!") self.ui.listWidget.addItem("New Account Registered!") self.ui.listWidget.scrollToBottom() print("New Account Registerd!") self.ui.tbox_pass_signup.setText("") self.ui.tbox_user_signup.setText("") self.ui.tbox_repass_signup.setText("") else: print("Passwords Doesnt match Please Retype!") select_color(str("red"), no, self) self.ui.lbl_warn_signup.setText("Passwords Doesnt match Please Retype!") self.ui.tbox_repass_signup.setText("") conn.close() print("out of loop") #Login def submit_login_clk(self, can): totp = can print(totp.now()) if self.ui.tbox_otp_login.text() == totp.now(): print("Current OTP:", totp.now()) print("valid") self.ui.stk_user.setCurrentIndex(1) print("Logged In..") self.ui.acnAdd_2FA.setDisabled(True) self.disablebtn(False) self.ui.tbox_pass_login.setText("") self.ui.tbox_user_login.setText("") self.ui.listWidget.addItem("Logged In...") self.load() else: print("wrong") def log_btn_clk(self): tracemalloc.start() username = str(self.ui.tbox_user_login.text()) pass1 = str(self.ui.tbox_pass_login.text()) no = 0 print("USER:-", username, "/ PASS:-", pass1) conn = sqlite3.connect('User.db') if len(username) == 0 or len(pass1) == 0: print("Input Fields Cannot Be Empty!") select_color(str("red"), no, self) self.ui.lbl_warn_login.setText("Input Fields Cannot Be Empty!") else: c = conn.cursor() c.execute("SELECT * FROM security WHERE `User` = ? ", (username,)) row = c.fetchone() conn.close() if row: print("ID:-", row[0], "/ USER:- ", row[1], "/ HASH:-", row[2], "/ Hash1:-", row[3]) try: if decrypt(pass1, row[2]) == username: self.logged_in = True self.user_id = row[0] self.main_pass = pass1 self.username = username if row[3] != "": can = decrypt(pass1, row[3]) print(can) self.ui.stk_login.setCurrentIndex(1) self.totp = pyotp.TOTP(can) else: select_color(str("green"), no, self) print("Logged In..") item = "Welcome " + username self.ui.listWidget.addItem("Logged In...") self.ui.listWidget.addItem(item) self.ui.listWidget.scrollToBottom() self.ui.tbox_user_login.setText("") self.ui.tbox_pass_login.setText("") self.ui.acnDel_2FA.setDisabled(True) self.disablebtn(False) self.load() except Exception as ex: select_color(str("red"), no, self) print("You Entered The Wrong Password!", ex) self.ui.lbl_warn_login.setText("You Entered The Wrong Password!") else: select_color(str("red"), no, self) print("No Such User!") self.ui.lbl_warn_login.setText("No such user!") gc.collect() snapshot = tracemalloc.take_snapshot() top_stats = snapshot.statistics('lineno') for stat in top_stats[:10]: print(stat) print("out for the loop") def load(self): zu = see() worker = Worker(zu.maina, self.user_id, self.main_pass) # Any other args, kwargs are passed to the run function worker.signals.result.connect(self.loads) worker.signals.finished.connect(self.thread_complete) worker.signals.progress.connect(self.setProgressVal) self.threadpool.start(worker) def loads(self, result): print("Main List:-" ,result) self.ui.table_view.setRowCount(0) t1 = time.perf_counter() for row_no, row_data in enumerate(result): print("ROW:-", row_no, "/ DATA:-", row_data) self.ui.table_view.setSortingEnabled(False) self.ui.table_view.insertRow(row_no) for column_no, data in enumerate(row_data): self.ui.table_view.setItem(row_no, column_no, QtWidgets.QTableWidgetItem(str(data))) self.ui.table_view.setSortingEnabled(True) t2 = time.perf_counter() print("Time Taken:-", t2 - t1) self.ui.stk_user.setCurrentIndex(1) return def thread_complete(self): print("THREAD COMPLETE!") def setProgressVal(self, val): self.counter += 1 vals = self.counter * 100 / val print(val, self.counter, int(vals),"%") self.ui.progressBar.setValue(int(vals)) if vals == 100: ku = see() setzero = Worker(ku.time) # Any other args, kwargs are passed to the run function setzero.signals.result.connect(self.setProgressZero) self.threadpool.start(setzero) def setProgressZero(self): self.ui.progressBar.setValue(0) self.counter = 0 # Logout def btn_logout_clk(self): self.logged_in = False self.ui.table_view.setRowCount(0) self.ui.stk_user.setCurrentIndex(0) self.ui.stk_login.setCurrentIndex(0) self.ui.progressBar.setValue(0) self.counter = 0 self.val = 1 self.ui.listWidget.addItem("Logged Out...") self.ui.listWidget.scrollToBottom() self.disablebtn(True) # Delete Main Account From DataBase... def del_main_acc(self): conn = sqlite3.connect('User.db') c = conn.cursor() c.execute("SELECT `Hash` FROM security WHERE `User` = ?", (self.username,)) result = c.fetchone() print(result[0]) self.dlb.zaf(1) while self.dlb.exec_(): if self.dlb.tbox_pass.text() != 0: try: if decrypt(str(self.dlb.tbox_pass.text()), result[0]) == self.username: user_id = self.user_id self.btn_logout_clk() conn2 = sqlite3.connect('Accounts.db') c2 = conn2.cursor() c2.execute("DELETE FROM accounts WHERE `security_ID` = ?", (user_id,)) conn2.commit() conn2.close() conn1 = sqlite3.connect('User.db') c1 = conn1.cursor() c1.execute("DELETE FROM security WHERE `ID` = ?", (user_id,)) conn1.commit() conn1.close() print("Deleted ID", user_id) self.ui.listWidget.addItem("Account Deleted Permanently!") self.ui.listWidget.scrollToBottom() self.disablebtn(True) break except: print("Error") continue else: continue print("cancel") self.dlb.tbox_pass.setText("") # add 2 Factor Authentication def add2fa(self): totp_hash = self.handle(self.username, self.main_pass, self.dlb.lbl_show_qr) self.dlb.add2fa_gui() while self.dlb.exec_(): print("awddwdd") if self.dlb.tbox_confirm_2fa.text() != "": can = decrypt(self.main_pass, totp_hash) print(can) totp = pyotp.TOTP(can) print(totp.now()) if self.dlb.tbox_confirm_2fa.text() == totp.now(): print("Current OTP:", totp.now()) conn = sqlite3.connect('User.db') c = conn.cursor() c.execute("UPDATE security SET `Topt` = ? WHERE `User` = ?", (totp_hash, self.username)) conn.commit() self.ui.acnDel_2FA.setDisabled(False) self.ui.acnAdd_2FA.setDisabled(True) self.ui.listWidget.addItem("2FA Added!") self.ui.listWidget.scrollToBottom() break else: continue else: continue self.dlb.tbox_confirm_2fa.setText("") # delete 2 Factor Authentication... def del2fa(self): conn = sqlite3.connect('User.db') c = conn.cursor() c.execute("SELECT `Hash` FROM security WHERE `User` = ?", (self.username,)) result = c.fetchone() print(result[0]) self.dlb.zaf(0) while self.dlb.exec_(): if self.dlb.tbox_pass.text() != 0: try: if decrypt(str(self.dlb.tbox_pass.text()), result[0]) == self.username: print("dawdawww") c.execute("UPDATE security SET 'Topt' = ? WHERE `User` = ?", ("", self.username)) conn.commit() conn.close() print("Deleted") self.ui.acnDel_2FA.setDisabled(True) self.ui.acnAdd_2FA.setDisabled(False) self.ui.listWidget.addItem("2FA Removed!") self.ui.listWidget.scrollToBottom() break except Exception as ex: print("Error") continue else: continue self.dlb.tbox_pass.setText("") def handle(self, user, password, label): salt = pyotp.random_base32() url = pyotp.totp.TOTP(salt).provisioning_uri(user, issuer_name="1PassGo!") label.setPixmap( qrcode.make(url, image_factory=Image).pixmap()) # totp = pyotp.TOTP(salt) # totp = pyotp.TOTP("VADCBKIX63IN7O4E") aa = encrypt(password, salt) print(aa) # print("Current OTP:", totp.now()) return aa #GUI def onChange(self, id): if id == 0: if self.ui.stk_login.currentIndex() == 1: self.ui.tab_login.setGeometry(QtCore.QRect(0, 0, 265, 141)) else: self.ui.tab_login.setGeometry(QtCore.QRect(0, 0, 265, 141)) else: if self.ui.stk_signup.currentIndex() == 1: self.ui.tab_login.setGeometry(QtCore.QRect(0, 0, 265, 331)) else: self.ui.tab_login.setGeometry(QtCore.QRect(0, 0, 265, 185)) def dark(self): sshFile = "black.qss" with open(sshFile, "r") as fh: self.ui.centralwidget.setStyleSheet(fh.read()) print("done") fh.close() sshFile = "black_menubar.qss" with open(sshFile, "r") as fh: self.ui.menubar.setStyleSheet(fh.read()) print("done") fh.close() sshFile = "black_tab.qss" with open(sshFile, "r") as fh: self.ui.tab_login.setStyleSheet(fh.read()) print("done") fh.close() def light(self): sshFile = "light.qss" with open(sshFile, "r") as fh: self.ui.centralwidget.setStyleSheet(fh.read()) print("done") fh.close() sshFile = "light_menubar.qss" with open(sshFile, "r") as fh: self.ui.menubar.setStyleSheet(fh.read()) print("done") fh.close() sshFile = "light_tab.qss" with open(sshFile, "r") as fh: self.ui.tab_login.setStyleSheet(fh.read()) print("done") fh.close() def default(self): self.ui.centralwidget.setStyleSheet("") self.ui.menubar.setStyleSheet("") self.ui.tab_login.setStyleSheet("") def show_pass(self, event): chk = [self.ui.tbox_pass_signup, self.ui.tbox_repass_signup, self.ui.tbox_pass_login, self.ui.tbox_pass_add, self.ui.tbox_pass_edit, self.ui.tbox_genpass_pgen, self.dlb.tbox_pass] if self.show_pass_val is False: print(event) chk[event].setEchoMode(QtWidgets.QLineEdit.Normal) self.show_pass_val = True else: chk[event].setEchoMode(QtWidgets.QLineEdit.Password) self.show_pass_val = False def tick_box_login(self, state): self.tk_box(state, 0) def tick_box_reg(self, state): self.tk_box(state, 1) def tick_box_edit(self, state): self.tk_box(state, 3) def tick_box_add(self, state): self.tk_box(state, 2) def tick_box_pgen(self, state): self.tk_box(state, 4) def tk_box(self, state, val): chk = [self.ui.tbox_pass_login, self.ui.tbox_pass_signup, self.ui.tbox_pass_add, self.ui.tbox_pass_edit, self.ui.tbox_genpass_pgen] if state == QtCore.Qt.Checked: print("Show Password") chk[val].setEchoMode(QtWidgets.QLineEdit.Normal) if val == 1: self.ui.tbox_repass_signup.setEchoMode(QtWidgets.QLineEdit.Normal) else: print("Hide Password") chk[val].setEchoMode(QtWidgets.QLineEdit.Password) if val == 1: self.ui.tbox_repass_signup.setEchoMode(QtWidgets.QLineEdit.Password) # disable/enable buttons.... def disablebtn(self, bool): if bool is True: # self.ui.menuImport_Db.setDisabled(True) # self.ui.acnExport_db.setDisabled(True) # self.ui.acnLight.setDisabled(True) # self.ui.acnCng_masterpass.setDisabled(True) # self.ui.acnCng_username.setDisabled(True) self.ui.acnCsv_Update_Acc.setDisabled(True) self.ui.btn_refresh.setDisabled(bool) # self.ui.table_view.setDisabled(True) self.ui.btn_logout.setDisabled(bool) self.ui.btn_export.setDisabled(bool) self.ui.menuImport_CSV.setDisabled(bool) self.ui.acnExport_CSV.setDisabled(bool) self.ui.acnLogout.setDisabled(bool) self.ui.acnExit.setDisabled(bool) self.ui.acnRefresh_db.setDisabled(bool) self.ui.menuAccount.setDisabled(bool) #CSV def btn_export_clk(self): if self.logged_in is True: options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getSaveFileName(self, "Save Database", "untitled.csv", "CSV Files (*.csv)", options=options) if fileName: print(fileName) if fileName.find(".csv") == -1: fileName = fileName + '.csv' print(fileName) conn1 = sqlite3.connect('User.db') c1 = conn1.cursor() c1.execute("SELECT User, User, Hash, Topt FROM security WHERE `ID` = ?", (self.user_id,)) conn2 = sqlite3.connect('Accounts.db') c2 = conn2.cursor() c2.execute("SELECT Account, User, Hash, Date, Url FROM accounts WHERE `security_ID` = ?", (self.user_id,)) with open(fileName, "w", newline='') as csv_file: csv_writer = csv.writer(csv_file, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) csv_writer.writerows(c1) csv_writer.writerow([i[0] for i in c2.description]) csv_writer.writerows(c2) conn1.close() conn2.close() item = "CSV exported to:- " + fileName self.ui.listWidget.addItem(item) self.ui.listWidget.scrollToBottom() def db_connect(self, database, username): conn = sqlite3.connect(database) c = conn.cursor() c.execute("SELECT 'User' FROM security WHERE `User` = ? ", (username,)) result = c.fetchone() conn.close() return result def import_cng_username(self): new_user = self.dlb.tbox_cng_user.text() return new_user def btn_import_clk(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getOpenFileName(self, "Load CSV File", "", "CSV Files (*.csv)", options=options) if fileName: print(fileName) if fileName.find(".csv") == -1: fileName = fileName + '.csv' print(fileName) with open(fileName, "r", newline='') as csv_file: csv_reader = csv.reader(csv_file, delimiter=' ', quotechar='|') conn1 = sqlite3.connect('User.db') conn2 = sqlite3.connect('Accounts.db') db_list = [] user_changed = False for row_no, data in enumerate(csv_reader): user = data[0] if row_no == 0: pass_hash = data[2] topt = data[3] result = self.db_connect("User.db", data[0]) if result: print("Username already exists in existing database! Please Change Your Username") while self.dlb.exec_(): new_user = self.import_cng_username() if new_user != "": check = self.db_connect("User.db", new_user) if check: print("Usename already Exists") continue else: continue password = self.dlb.tbox_pass.text() try: print(data[2]) if decrypt(password, data[2]) == user: user = new_user pass_hash = encrypt(password, user) user_changed = True print("Username Changed!") break except Exception as ex: print("You Entered The Wrong Password!", ex) continue self.dlb.tbox_pass.setText("") self.dlb.tbox_cng_user.setText("") if user_changed is False: break if not result or user_changed is True: c = conn1.cursor() c.execute('INSERT INTO security(User, Hash, Topt) VALUES(?,?,?)', (user, pass_hash, topt)) conn1.commit() user_id = c.lastrowid conn1.close() print("Acount Added!") self.ui.listWidget.addItem("New Account Added!") self.ui.listWidget.scrollToBottom() if row_no > 1: row = [data[0], data[1], data[2], data[3], user_id, data[4]] db_list.append(row) print(db_list) c = conn2.cursor() c.executemany('INSERT INTO accounts(Account, User, Hash, Date, security_ID, Url) VALUES(?,?,?,?,?,?)', db_list) conn2.commit() conn2.close() print("Done") #Refresh Database def btn_refresh_clk(self): if self.logged_in is True: self.ui.table_view.setRowCount(0) self.load() self.ui.listWidget.addItem("Database Refreshed!") self.ui.listWidget.scrollToBottom() else: print("You have not logged in!") #Generate Random Password def btn_cpy_clk(self): no = 4 password = self.ui.tbox_genpass_pgen.text() if password != "": clipboard = QGuiApplication.clipboard() clipboard.setText(password) print("copied", password) select_color(str("green"), no, self) self.ui.lbl_warn_pgen.setText("Password Copied To Clipboard!") else: print("empty") def btn_genpass_clk(self): no = 4 length = self.ui.tbox_slen_pgen.text() if length.isdigit(): characters = string.ascii_letters + string.digits + string.punctuation password = "".join(choice(characters) for _ in range(int(length))) self.ui.tbox_genpass_pgen.setText(password) select_color(str("green"), no, self) self.ui.lbl_warn_pgen.setText("New Password Generated!") else: select_color(str("red"), no, self) self.ui.lbl_warn_pgen.setText("Only Numbers are expected!") #Table def cell_was_clicked(self, row, column): print("Row %d and Column %d was clicked" % (row, column)) if column == 1 or column == 2 or column == 0: self.copySlot(None, column, row) elif column == 2: self.copySlot(None, column, row) return def copySlot(self, event, mode, rowdata): print(event) if rowdata is None: row = self.ui.table_view.rowAt(event.y()) else: row = rowdata print(row) cell = self.ui.table_view.item(row, 1) data = cell.data(Qt.DisplayRole) user = data print(data) if mode == 2 or mode == 0: cell = self.ui.table_view.item(row, 0) acc_name = cell.data(Qt.DisplayRole) conn = sqlite3.connect('Accounts.db') conn.commit() c = conn.cursor() c.execute("SELECT Hash FROM accounts WHERE `Account` = ? AND `User` = ?", (acc_name, data)) result = c.fetchone() conn.close() for hash in result: print("match found:-", hash) data = self.decrypt_pass(hash) if mode == 0: cell = self.ui.table_view.item(row, 0) acc_name = cell.data(Qt.DisplayRole) conn = sqlite3.connect('Accounts.db') conn.commit() c = conn.cursor() c.execute("SELECT Url FROM accounts WHERE `Account` = ? AND `User` = ?", (acc_name, user)) result = c.fetchone() conn.close() for rl in result: print("url found:-", rl) url = rl self.ui.listWidget.addItem("URL Opened in Browser") driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe") driver.get(url) driver.find_element_by_css_selector("input[type=\"text\"]").send_keys(user) driver.find_element_by_css_selector("input[type=\"password\"]").send_keys(data) else: self.ui.listWidget.addItem("Password Copied To Clipboard!") clipboard = QGuiApplication.clipboard() clipboard.setText(data) else: self.ui.listWidget.addItem("Username Copied To Clipboard!") clipboard = QGuiApplication.clipboard() clipboard.setText(data) self.ui.listWidget.scrollToBottom() print("copied", data) self.ui.listWidget.scrollToBottom() return def autofill(self, event): print(event) row = self.ui.table_view.rowAt(event.y()) print(row) col = 0 cell = self.ui.table_view.item(row, col) data = cell.data(Qt.DisplayRole) print(data) while col <= 1: item = self.ui.table_view.item(row, col) data = item.data(Qt.DisplayRole) print(data) if col == 0: self.ui.tbox_acc_action.setText(data) else: self.ui.tbox_user_action.setText(data) col = col + 1 return def showMenu(self, event): print(event.x()) menu = QMenu() copy_user_action = menu.addAction("Copy Username") copy_pass_action = menu.addAction("Copy Password") delete_action = menu.addAction("Delete") autofill_action = menu.addAction("Auto Fill") action = menu.exec_(QtGui.QCursor.pos()) if action == copy_user_action: self.copySlot(event, 1, None) elif action == copy_pass_action: self.copySlot(event, 2, None) elif action == delete_action: self.event = event self.num = 3 self.del_btn_clk() elif action == autofill_action: self.autofill(event) def decrypt_pass(self, data): main_pass = str(self.main_pass) new = decrypt(main_pass, data) print("pass = ", new) return new #Search Table def handleTextEntered(self): print("adsawdawdwd") if self.table_dict is None and self.update_list == 0: print("list is none") self.backup() check = self.ui.tbox_search.text() print(check) table_dict = self.table_dict self.ui.table_view.setRowCount(0) row_no = 0 for idx in table_dict: if idx[0].find(check) != -1 or idx[1].find(check) != -1 or (table_dict[idx])[1].find(check) != -1: print("Match Found : " + str(idx)) self.ui.table_view.setSortingEnabled(False) self.ui.table_view.insertRow(row_no) column_no = 2 self.ui.table_view.setItem(row_no, 0, QtWidgets.QTableWidgetItem(idx[0])) self.ui.table_view.setItem(row_no, 1, QtWidgets.QTableWidgetItem(idx[1])) for cell in table_dict[idx]: self.ui.table_view.setItem(row_no, column_no, QtWidgets.QTableWidgetItem(cell)) column_no += 1 row_no += 1 self.ui.table_view.setSortingEnabled(True) else: pass #Add Accounts def save_btn_clk(self): acc_name = str(self.ui.tbox_acc_add.text()) username = str(self.ui.tbox_user_add.text()) password = str(self.ui.tbox_pass_add.text()) url = str(self.ui.tbox_url_add.text()) user_id = self.user_id no = 2 if len(username) == 0 or len(password) == 0 or len(acc_name) == 0 or len(url) == 0: print("Input Fields Cannot Be Empty!") select_color(str("red"), no, self) self.ui.lbl_warn_add.setText("Input Fields Cannot Be Empty!") else: conn = sqlite3.connect('Accounts.db') c = conn.cursor() c.execute("SELECT Account, User FROM accounts WHERE `Account` = ? AND `User` = ? AND `security_ID` = ?", (acc_name, username, user_id)) result = c.fetchall() if result: for _ in result: select_color(str("red"), no, self) self.ui.lbl_warn_add.setText("Username Already Exists...") print("Username Already Exists, Select a Different Username") self.ui.tbox_user_add.setText("") break elif len(password) < 8: select_color(str("red"), no, self) self.ui.lbl_warn_add.setText("Password Must Have Atleast 8 Characters!") print("Password Should Be Atleast 8 Characters Long!") else: now = QDate.currentDate() date = now.toString(Qt.DefaultLocaleShortDate) print(acc_name, username, password, str(self.main_pass), date) c = conn.cursor() c.execute('INSERT INTO accounts(Account, User, Hash, Date, security_ID, Url) VALUES(?,?,?,?,?,?)' , (acc_name, username, encrypt(str(self.main_pass), password), date, user_id, url)) conn.commit() select_color(str("green"), no, self) self.ui.lbl_warn_add.setText("New Account Registerd!") self.ui.listWidget.addItem("New Account Added In DB!") self.ui.listWidget.scrollToBottom() check = self.ui.tbox_search.text() hid_pass = str("") for _ in password: hid_pass += str("●") if check == "" or acc_name.find(check) != -1 or username.find(check) != -1 or date.find( check) != -1: new_row = self.ui.table_view.rowCount() print("row count add", new_row) self.ui.table_view.setSortingEnabled(False) self.ui.table_view.insertRow(new_row) temp_list = [acc_name, username, hid_pass, date] for column in range(self.ui.table_view.columnCount()): print("column no:-", column) new_column = temp_list[column] print(new_column) print("column no:-", column) self.ui.table_view.setItem( new_row, column, QtWidgets.QTableWidgetItem(new_column)) self.ui.table_view.setSortingEnabled(True) if self.table_dict is None and self.update_list == 0: print("list is none") self.backup() key = (acc_name, username) list1 = [hid_pass, date] table_dict = self.table_dict table_dict[key] = list1 print(table_dict) self.table_dict = table_dict conn.close() print("out of loop") #Accounts Action def action_sec(self): no = 3 acc_name = str(self.ui.tbox_acc_action.text()) username = str(self.ui.tbox_user_action.text()) conn = sqlite3.connect('Accounts.db') conn.commit() c = conn.cursor() c.execute("SELECT Account, User FROM accounts WHERE `Account` = ? AND `User` = ?", (acc_name, username)) result = c.fetchall() conn.close() if result: for row in result: print("match found:-", row) return "%s-%s-%s" % (1, acc_name, username) else: print("account name, username mismatch!") return "%s-%s-%s" % (0, None, None) def del_btn_clk(self): event = self.event no = 3 # mode value comes from def showMenu... username, acc_name = None, None if self.num == 3: row = self.ui.table_view.rowAt(event.y()) col = 0 while col <= 1: cell = self.ui.table_view.item(row, col) if col == 0: acc_name = cell.data(Qt.DisplayRole) else: username = cell.data(Qt.DisplayRole) col += 1 print("acc:-", acc_name, " user:-", username) val = str("1") else: val, acc_name, username = self.action_sec().split("-") print("acc:-", acc_name, " user:-", username) self.num = None if val == str("1"): a = str("This will Delete the corresponding data of..") b = str(str("Account:-" + acc_name) + str("\nUsername :-" + username)) value = self.show_popup("Are You Sure?", a, b) if value == 1024: self.update_table(acc_name, username, None, None, None, str("delete")) item = "Acc:-" + acc_name + " & User:-" + username + " has been deleted!" self.ui.listWidget.addItem(item) self.ui.listWidget.scrollToBottom() select_color(str("red"), no, self) self.ui.lbl_warn_action.setText("Account Deleted Successfully!") conn = sqlite3.connect('Accounts.db') conn.commit() c = conn.cursor() c.execute("DELETE FROM accounts WHERE `Account` = ? AND `User` = ?", (acc_name, username)) conn.commit() conn.close() else: print("Cancel Pressed!") else: print("No Such Account/User") select_color(str("red"), no, self) self.ui.lbl_warn_action.setText("No Such Account/User!") def show_popup(self, title, message, info): msg = QMessageBox() msg.setIcon(QMessageBox.Warning) msg.setText(message) msg.setInformativeText(info) msg.setWindowTitle(title) msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) msg.resize(200, 300) retval = msg.exec_() print("value of pressed message box button:", retval) return retval def edit_btn_clk(self): no = 3 val, acc_name, username = self.action_sec().split("-") if val == str("1"): self.ui.stk_action.setCurrentIndex(1) return "%s-%s" % (acc_name, username) else: print("No Such Account/User") select_color(str("red"), no, self) self.ui.lbl_warn_action.setText("No Such Account/User!") def apply_btn_clk(self): no = 5 cng_user = str(self.ui.tbox_user_edit.text()) cng_pass = str(self.ui.tbox_pass_edit.text()) acc_name, username = self.edit_btn_clk().split("-") if len(cng_user) != 0 or len(cng_pass) >= 8: item2 = None mode = str("update") conn = sqlite3.connect('Accounts.db') c = conn.cursor() new_pass = str("") for _ in cng_pass: new_pass = new_pass + str("●") if len(cng_user) != 0 and len(cng_pass) >= 8: main_pass = str(self.main_pass) enc_pass = encrypt(main_pass, cng_pass) c.execute( "UPDATE accounts SET `User` = ?, `Hash` = ? WHERE `Account` = ? AND `User` = ?", (cng_user, enc_pass, acc_name, username)) self.update_table(acc_name, username, new_pass, cng_user, 2, mode) item = "Username changed:- " + username + " -> " + cng_user item2 = cng_user + "'s Password has been changed!" elif len(cng_user) != 0 and len(cng_pass) == 0: c.execute( "UPDATE accounts SET `User` = ? WHERE `Account` = ? AND `User` = ?", (cng_user, acc_name, username)) self.update_table(acc_name, username, None, cng_user, 0, mode) item = "Username changed:- " + username + " -> " + cng_user elif len(cng_user) == 0 and len(cng_pass) >= 8: main_pass = str(self.main_pass) enc_pass = encrypt(main_pass, cng_pass) c.execute( "UPDATE accounts SET `Hash` = ? WHERE `Account` = ? AND `User` = ?", (enc_pass, acc_name, username)) self.update_table(acc_name, username, new_pass, None, 1, mode) item = username + "'s Password has been changed!" conn.commit() conn.close() self.ui.stk_action.setCurrentIndex(0) self.ui.tbox_user_edit.setText("") self.ui.tbox_pass_edit.setText("") self.ui.listWidget.addItem(item) if item2 is not None: self.ui.listWidget.addItem(item2) self.ui.listWidget.scrollToBottom() select_color(str("green"), 3, self) self.ui.lbl_warn_action.setText("Changes made successfully!") print("Changes Made Successfully!") else: if len(cng_pass) >= 1: print("Password should be atleast 8 char long!") select_color(str("red"), no, self) self.ui.lbl_warn_edit.setText("Password should be atleast 8 char long!") else: print("Either 1 Field Should Be filled!") select_color(str("red"), no, self) self.ui.lbl_warn_edit.setText("Either 1 Field Should be filled") def update_table(self, acc_name, username, new_pass, cng_user, value, mode): if self.table_dict is None and self.update_list == 0: print("list is none") self.backup() check = self.ui.tbox_search.text() conn = sqlite3.connect('Accounts.db') print(acc_name, username) conn.commit() c = conn.cursor() c.execute("SELECT Date FROM accounts WHERE `Account` = ? AND `User` = ?", (acc_name, username)) date = c.fetchone() conn.close() if check == "" or acc_name.find(check) != -1 or username.find(check) != -1 or str(date[0]).find( check) != -1: for row in range(self.ui.table_view.rowCount()): find = False for column in range(1): item = self.ui.table_view.item(row, column) print("row no:-", row, " column no:-", column, " data:-", item.data(Qt.DisplayRole)) if item and item.data(Qt.DisplayRole) == acc_name: print("Acc found:-", item.data(Qt.DisplayRole)) column += 1 item = self.ui.table_view.item(row, column) if item and item.data(Qt.DisplayRole) == username: print("User found:-", item.data(Qt.DisplayRole)) if mode == str("update"): temp_list = [[cng_user, None, 1], [new_pass, None, 2], [cng_user, new_pass, 1]] update_column = temp_list[value][0] update_column2 = temp_list[value][1] column_no = temp_list[value][2] self.ui.table_view.setItem(row, column_no, QtWidgets.QTableWidgetItem(update_column)) if value == 2: self.ui.table_view.setItem(row, 2, QtWidgets.QTableWidgetItem(update_column2)) find = True else: self.ui.table_view.removeRow(row) find = True if find: break table_dict = self.table_dict for idx in table_dict: print("ACCOUNT:-", idx[0], " USERNAME:-", idx[1]) if idx[0] == acc_name and idx[1] == username: print("Dict Match Found:-" + str(idx)) if mode == str("update"): temp_list = [[cng_user, table_dict[idx][0]], [idx[1], new_pass], [cng_user, new_pass]] u_name = temp_list[value][0] password = temp_list[value][1] list1 = [password, table_dict[idx][1]] print("Sub-List:-", [password, table_dict[idx][1]]) key = (idx[0], u_name) del table_dict[idx] table_dict[key] = list1 print(table_dict) self.table_dict = table_dict return else: del table_dict[idx] print(table_dict) self.table_dict = table_dict return #Backup def backup(self): table_dict = {} for row in range(self.ui.table_view.rowCount()): list1 = [] for column in range(2, 4): item = self.ui.table_view.item(row, column) list1.insert(column, item.data(Qt.DisplayRole)) item = self.ui.table_view.item(row, 0) item2 = self.ui.table_view.item(row, 1) key = (item.data(Qt.DisplayRole), item2.data(Qt.DisplayRole)) table_dict[key] = list1 print("Len:", len(table_dict), table_dict) self.table_dict = table_dict #Login/Multithreading class see(Ui_MainWindow): def leds(self, data): hash_len = self.hash_len new = decrypt(str(self.m_pass), str(data)) j = str("") for _ in new: j += str("●") progress = self.progress progress.emit(hash_len) return j def maina(self, user_id, password, progress_callback): self.m_pass = password conn = sqlite3.connect('Accounts.db') print("Main Pass:-", str(self.m_pass)) c = conn.cursor() c.execute("SELECT Account, User, Hash, Date, Url FROM accounts WHERE `security_ID` = ?", (str(user_id),)) result = c.fetchall() conn.close() hash_list = [] start = time.perf_counter() for row_data in result: hash_list.append(row_data[2]) self.hash_len = len(hash_list) self.progress = progress_callback print("adwaddaddawdawdwd", progress_callback) with concurrent.futures.ThreadPoolExecutor() as executor: results = executor.map(self.leds, hash_list) passes = [] for f in results: passes.append(f) print(f) table = [] for row_no, row_data in enumerate(result): row = [] for column_no, data in enumerate(row_data): if column_no != 2: row.append(data) else: row.append(passes[row_no]) table.append(row) finish = time.perf_counter() print(f'Finished in {round(finish - start, 2)} second(s)') return table def time(self, progress_callback): print("here") time.sleep(1) def main(): app = QtWidgets.QApplication(sys.argv) dialog = MyWork() app.exec_() if __name__ == "__main__": main()
8a13bf6f8bab21730334859a21b3f20a969dc547
65486d85e29b03dafdfb77d3c9269242a7bbfb50
/crsrc/select_control_window.py
0d719a5f0297d06590f2c259eb7c8fe9423bff90
[]
no_license
raysmith619/race_track
97b6ee3399b635a52553fdba7a7e8a1a1a1d89d1
407d542e1c8b09718c6e931f1991562805f04607
refs/heads/master
2020-06-12T11:19:49.963670
2020-02-01T20:56:39
2020-02-01T20:56:39
194,281,700
0
0
null
null
null
null
UTF-8
Python
false
false
16,360
py
# command_file.py """ Base for independent control window Provides a singleton which is universally accessible Facilitates setting and display of game controls persistent storage of values window positioning / sizing Undo / Re-do of value setting """ from tkinter import * import re import os from select_error import SelectError from select_trace import SlTrace def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise SelectError('Not a recognized Boolean value %s' % v) class SelectControlWindow(Toplevel): CONTROL_NAME_PREFIX = "window_control" DEF_WIN_X = 500 DEF_WIN_Y = 300 _instance = None # Instance instance_no = 0 # Count instances def __init__(self, *args, **kwargs): SlTrace.lg("SelectControlWindow.__init__ %d" % SelectControlWindow.instance_no) def _init(self, play_control=None, control_prefix=None, title=None, display=True, new = False ): """ Control attributes :title: window title """ SelectControlWindow.instance_no += 1 self.play_control = play_control if control_prefix is None: control_prefix = self.CONTROL_NAME_PREFIX self.control_prefix = control_prefix self.mw = Toplevel() self.mw.protocol("WM_DELETE_WINDOW", self.delete_window) if title is None: title = "Game Control" self.title = title self.vals = {} # Current values if any self.ctls = {} # Dictionary of field control widgets self.ctls_vars = {} # Dictionary of field control widget variables self.display = display # Done in instance, if at all self._is_displayed = False def __new__(cls, *args, **kwargs): """ Make a singleton """ if cls._instance is None: cls._instance = super(SelectControlWindow, cls).__new__(cls) ###cls._instance._init(*args, **kwargs) cls._instance._init(**kwargs) return cls._instance def set_play_control(self, play_control): """ Link ourselves to the display """ self.play_control = play_control def control_display(self): """ display /redisplay controls to enable entry / modification """ if self._is_displayed: return top_frame = Frame(self.mw) top_frame.pack(side="top", fill="x", expand=True) self.top_frame = top_frame self.base_frame = top_frame # Changed on use self.base_field = "game_control" self.mw.title(self.title) top_frame = Frame(self.mw) top_frame.pack(side="top", fill="x", expand=True) self.top_frame = top_frame bottom_frame = Frame(self.mw, borderwidth=2, relief=SUNKEN) bottom_frame.pack(side="bottom", expand=True) self.bottom_frame = bottom_frame self.set_fields(bottom_frame, "base", title="") self.set_button(field="set", label="Set", command=self.set) self.set_sep() self.set_button(field="Reset", label="Reset", command=self.reset) self.set_sep() self.set_button(field="Undo", label="Undo", command=self.undo) self.set_sep() self.set_button(field="Redo", label="Redo", command=self.redo) self.arrange_windows() self._is_displayed = True # Mark as displayed """ Control functions for game control """ def set(self): self.set_vals() def reset(self): self.set_vals() def undo(self): self.set_vals() def redo(self): self.set_vals() def get_val_from_ctl(self, field_name): """ Get value from field Does not set value :field_name: field name """ field = field_name.lower() if field not in self.ctls_vars: raise SelectError("Command has no attribute %s" % field) value = self.ctls_vars[field].get() return value def set_vals(self): """ Read form, if displayed, and update internal values """ for field in self.ctls_vars: self.set_val_from_ctl(field) def set_val_from_ctl(self, field_name): """ Set ctls value from field Also updates player value properties :field_name: field name """ if not field_name in self.ctls_vars: raise SelectError("No field named %s" % field_name) ctl_var = self.ctls_vars[field_name] if ctl_var is None: raise SelectError("No variable for %s" % field_name) value = ctl_var.get() self.set_prop_val(field_name, value) def set_fields(self, base_frame, base_field, title=None): """ Set current control area :frame: current frame into which controls go :base_field: base for variables/widgets are stored """ base_frame.pack() self.base_frame = base_frame self.base_field = base_field if title is None: title = base_field if title != "": wlabel = Label(base_frame, text=title, anchor=W) wlabel.pack(side="left", anchor=W) self.set_text(" ") def set_text(self, text, frame=None): """ Add text to current location/frame :text: text string to add :frame: frame into add default: base_frame """ if frame is None: frame = self.base_frame wlabel = Label(frame, text=text, anchor=W) wlabel.pack(side="left", anchor=W) def set_sep(self, frame=None): """ Add default separator :frame: destination frame """ if frame is None: frame = self.base_frame self.set_text(" ", frame=frame) def set_vert_sep(self, frame=None): """ Add default verticle separator :frame: destination frame """ if frame is None: frame = self.base_frame sep_frame = Frame(frame) sep_frame.pack(side="top", anchor=N) self.set_text(" ", frame=sep_frame) def set_check_box(self, frame=None, field=None, label=None, value=False): """ Set up check box for field :field: local field name :label: button label - default final section of field name :value: value to set """ if frame is None: frame = self.base_frame if label is None: label = field if label is not None: wlabel = Label(frame, text=label) wlabel.pack(side="left") content = BooleanVar() full_field = self.field_name(field) value = self.get_prop_val(full_field, value) content.set(value) widget = Checkbutton(frame, variable=content) widget.pack(side="left", fill="none", expand=True) self.ctls[full_field] = widget self.ctls_vars[full_field] = content self.set_prop_val(full_field, value) def set_entry(self, frame=None, field=None, label=None, value=None, width=None): """ Set up entry :frame: containing frame :field: relative field name (after self.base_field) :label: field label default: no label :value: value to set, iff not in properties value's variable type is used as the entry content's type """ if frame is None: frame = self.base_frame content = self.content_var(type(value)) full_field = self.field_name(field) value = self.get_prop_val(full_field, value) content.set(value) if label is not None: wlabel = Label(frame, text=label) wlabel.pack(side="left") widget = Entry(frame, textvariable=content, width=width) widget.pack(side="left", fill="none", expand=True) self.ctls[full_field] = widget self.ctls_vars[full_field] = content self.set_prop_val(full_field, value) def set_button(self, frame=None, field=None, label=None, command=None): """ Set up check box for field :frame: containing frame, default self.base_frame :field: field name :label: button label - default: field :command: command to execute when button pressed """ if frame is None: frame = self.base_frame if label is None: label = field widget = Button(frame, text=label, command=command) widget.pack(side="left", fill="none", expand=True) full_field = self.field_name(field) self.ctls[field] = widget # No variable def field_name(self, *fields): """ Create basic field name from list :fields: set of field segments """ field_name = self.base_field for field in fields: if field_name != "": field_name += "." field_name += field return field_name def win_size_event(self, event): """ Window sizing event """ win_x = self.mw.winfo_x() win_y = self.mw.winfo_y() win_width = self.mw.winfo_width() win_height = self.mw.winfo_height() self.set_window_size(win_x, win_y, win_width, win_height) def set_window_size(self, x, y, width, height, change=False): """ Size our window :change: True force window resize """ self.set_prop_val("win_x", x) self.set_prop_val("win_y", y) self.set_prop_val("win_width", width) self.set_prop_val("win_height", height) if SlTrace.trace("set_window_size("): if ( not hasattr(self, "prev_x") or self.prev_x != x or not hasattr(self, "prev_y") or self.prev_y != y or not hasattr(self, "prev_width") or self.prev_width != width or not hasattr(self, "prev_height") or self.prev_height != height): SlTrace.lg("set_window_size( change=%d x=%d y=%d width=%d height=%d" % (change, x,y,width,height)) self.prev_x = x self.prev_y = y self.prev_width = width self.prev_height = height if change: geo_str = "%dx%d+%d+%d" % (width, height, x, y) self.mw.geometry(geo_str) def arrange_windows(self): """ Arrange windows Get location and size for properties if any """ win_x = self.get_prop_val("win_x", self.DEF_WIN_X) if win_x < 0: win_x = 50 win_y = self.get_prop_val("win_y", self.DEF_WIN_Y) if win_y < 0: win_y = 50 win_width = self.get_prop_val("win_width", self.mw.winfo_width()) win_height = self.get_prop_val("win_height", self.mw.winfo_height()) self.set_window_size(win_x, win_y, win_width, win_height, change=True) self.mw.protocol("WM_DELETE_WINDOW", self.delete_window) self.mw.bind('<Configure>', self.win_size_event) def get_prop_key(self, name): """ Translate full control name into full Properties file key """ key = self.control_prefix + "." + name return key def get_prop_val(self, name, default): """ Get property value as (string) :name: field name :default: default value, if not found :returns: "" if not found """ prop_key = self.get_prop_key(name) prop_val = SlTrace.getProperty(prop_key) if prop_val is None or prop_val == "": return default if isinstance(default, bool): bv = str2bool(prop_val) return bv if isinstance(default, int): if prop_val == "": return 0 try: prop_val = int(prop_val) except: try: prop_val = float(prop_val) except: prop_val = 0 return int(prop_val) if isinstance(default, float): if prop_val == "": return 0. return float(prop_val) else: return prop_val def get_val(self, name, default=None): """ Get current value, if any, else property value, if any, else default :name: field name :default: returned if not found """ if name in self.vals: return self.vals[name] val = self.get_prop_val(name, default) return val def set_ctl(self, field_name, value): """ Set field, given value Updates field display and properties value :field_name: field name :value: value to set """ if field_name not in self.ctls_vars: raise SelectError("Control has no field variable %s" % field_name) ctl_var = self.ctls_vars[field_name] ctl_var.set(value) self.set_prop_val(field_name, value) def content_var(self, type): """ create content variable of the type val :type: variable type """ if type == str: var = StringVar() elif type == int: var = IntVar() elif type == float: var = DoubleVar() elif type == bool: var = BooleanVar() else: raise SelectError("Unsupported content var type %s" % type) return var def set_ctl_val(self, field_name, val): """ Set control field Creates field variable if not already present :field_name: field name :val: value to display """ if field_name not in self.ctls_vars: content_var = self.content_var(type(val)) self.ctls_vars[field_name] = content_var self.ctls_vars[field_name].set(val) def set_prop_val(self, name, value): """ Set property value as (string) :name: field name :value: default value, if not found """ self.set_val(name, value) prop_key = self.get_prop_key(name) SlTrace.setProperty(prop_key, str(value)) def set_val(self, name, value): """ Set field value :name: field name :value: value to set """ self.vals[name] = value # Update properties def destroy(self): """ Destroy window resources """ if self.mw is not None: self.mw.destroy() self.mw = None def delete_window(self): """ Handle window deletion """ if self.play_control is not None and hasattr(self.play_control, "close_score_window"): self.play_control.close_score_window() else: self.destroy() quit() SlTrace.lg("Properties File: %s"% SlTrace.getPropPath()) SlTrace.lg("Log File: %s"% SlTrace.getLogPath()) sys.exit(0) self.play_control = None if __name__ == '__main__': root = Tk() root.withdraw() # Hide main window SlTrace.setProps() cF = SelectControlWindow(title="SelectControlWindow Testing", display=False) cf2 = SelectControlWindow() cf2.control_display() root.mainloop()
2801b6138be3174ce98462cd3204d91f471887c9
fb740011de1be1460209b0537c6372a9d68e6748
/collection_extensions/models.py
8d756d50ac7da9709c02494baf8ca5f786317b58
[ "MIT" ]
permissive
722C/saleor-collection-extensions
8d029999b82fc6b455bf137e0bdf9eeb00950795
09e204e5e4b558a1e76ab9894c97691ce12cbc7f
refs/heads/master
2020-03-27T01:50:05.390936
2019-02-06T19:52:22
2019-02-06T19:52:22
145,746,261
0
0
null
null
null
null
UTF-8
Python
false
false
1,119
py
from django.db import models from django.utils.translation import pgettext_lazy from saleor.core.permissions import MODELS_PERMISSIONS # Add in the permissions specific to our models. MODELS_PERMISSIONS += [ 'collection_extensions.view', 'collection_extensions.edit' ] class CollectionExtension(models.Model): collection = models.OneToOneField( 'product.Collection', on_delete=models.CASCADE, related_name='extension') alternative_name = models.CharField(max_length=255, blank=True) content = models.TextField(help_text=pgettext_lazy( 'Collection extension', 'CMS-able content.'), blank=True) added = models.DateTimeField(auto_now_add=True) class Meta: app_label = 'collection_extensions' permissions = ( ('view', pgettext_lazy('Permission description', 'Can view collection extensions') ), ('edit', pgettext_lazy('Permission description', 'Can edit collection extensions'))) def __str__(self): return self.collection.name
96a668e090bc833ec8d2f7fe57670f773d0f9346
292df2fa02d5cf537af997ef638d672dee22b4e3
/faceAPI/test.py
5b7a6d3017fc652a0e9934cab810f72e63230de9
[]
no_license
jyang94/FR
a832fce8bdc2bd157f6571ca2c6a88251f74b8fe
b4879e3c5b156387fff1612c74b4a2ef1325292d
refs/heads/master
2020-12-03T02:06:17.759190
2017-08-24T21:08:47
2017-08-24T21:08:47
95,905,189
0
0
null
null
null
null
UTF-8
Python
false
false
428
py
import cognitive_face as CF KEY = '891d1fb7-b6ec-4d35-905f-73f75d2e42aa' # Replace with a valid Subscription Key here. CF.Key.set(KEY) BASE_URL = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0' # Replace with your regional Base URL CF.BaseUrl.set(BASE_URL) img_url = 'https://raw.githubusercontent.com/Microsoft/Cognitive-Face-Windows/master/Data/detection1.jpg' result = CF.face.detect(img_url) print(result)
8d33e252e31922acc964f3b7f5d15ed2675df2ea
96ffe7b81a3c3a087b3c2c5006121521efb56a99
/cgi-bin/Transfer.py
9fd490fb04f77ca3a0f755869d60b4debb4e7d34
[]
no_license
michaelchum/comp206
6f7ff20c86e25ebfe4fb915b6c29d0c224b71717
872b5c60bc2567e9da99b1fdbdf99b14d25b1b7e
refs/heads/master
2016-09-06T18:26:26.643408
2013-12-07T02:41:02
2013-12-07T02:41:02
null
0
0
null
null
null
null
UTF-8
Python
false
false
10,672
py
#!/usr/bin/env python import cgi, os, Cookie, datetime, string, csv import cgitb; cgitb.enable() # for debugging CURRENT_PATH = os.getcwd() # For path PROJECT_PATH = os.path.abspath(os.path.join(CURRENT_PATH, os.pardir)) INVENTORY_PATH = os.path.join(PROJECT_PATH, 'inventory.csv') TEMP_PATH = os.path.join(PROJECT_PATH, 'temp.csv') ''' ROOM MODE CODE ''' roomIndex = ''' <html> <head> <link rel="stylesheet" type="text/css" href="../room.css"/> <title> Portal room </title> </head> <body bgcolor="black" text=#c9efff align="center"> <div id="title"> <span style="font-size:80px">Welcome to the</span><br> <span style="color:white">P</span> <span style="color:blue">O</span> <span style="color:red">R</span> <span style="color:yellow">T</span> <span style="color:turquoise">A</span> <span style="color:green">L</span> <br> <span>room</span> <span><p class="gold">You have <span style="color:yellow"> ''' roomIndex2 = '''</span> gold</p></span> </div> <div id="banner"> <a id="banner"> <img src="../img/tron.jpg" border="0"> </a> </div> <table> <tr> <td></td> <td> <center> <form name="goNorth" action="http://cs.mcgill.ca/~zsu3/ass5/transfer.py" method="post"> ''' roomIndex3 = ''' <input type="image" img id="door" src="../img/north.jpg"> <br> <span>NORTH</span> </form> </center> </td> <td></td> <tr> <td> <center> <form name="goWest" action="http://cs.mcgill.ca/~dbiggs3/cgi-bin/transfer.py" method="post"> ''' roomIndex4 = ''' <input type="image" img id="door" src="../img/west.png"> <br> <span>WEST</span> </form> </center> </td> <td> <center> <form name="game" action="game.py" method="POST"> <input id="door" name="submit" type="image" src="../img/riddle.jpg" value="myValue" alt="" /> ''' roomIndex5 = ''' <br> <input type="submit" name="submitgame" value="Challenge me" id="puzzle"> </form> </center> </td> <td> <center> <form name="goEast" action="http://www.cs.mcgill.ca/~mwu33/cgi-bin/transfer.py" method="post"> ''' roomIndex6 = ''' <input type="image" img id="door" src="../img/east.jpg"> <br> <span>EAST</span> </form> </center> </td> </tr> <tr> <td></td> <td> <center> <form name="goSouth" action="http://cs.mcgill.ca/~yxia19/ass5/cgi-bin/transfer.py" method="post"> ''' roomIndex7 = ''' <input type="image" img id="door" src="../img/south.jpg"> <br> <span>SOUTH</span> </form> </center> </td> <td></td> </tr> <br> <form name="game" action="transfer.py" method="POST"> <span class="command">Command:</span><br> <input type="text" name="command"> <input type="submit" name="submit"><br> ''' roomIndex8 = ''' <br> <span style="position:relative; left:320px; top:85px"><span id="lookaround">Look around</span></span> ''' botBody = ''' </body> </html> ''' def roomMode(): # Initialize transmission variables points = "100" invent1 = "" invent2 = "" invent3 = "" invent4 = "" invent5 = "" # Check GET/POST request for room and game if (cgi.FieldStorage): form = cgi.FieldStorage() if (form.getvalue('points')): points = form.getvalue('points') if (form.getvalue('Inventory1')): invent1 = form.getvalue('Inventory1') if (form.getvalue('Inventory2')): invent2 = form.getvalue('Inventory2') if (form.getvalue('Inventory3')): invent3 = form.getvalue('Inventory3') if (form.getvalue('Inventory4')): invent4 = form.getvalue('Inventory4') if (form.getvalue('Inventory5')): invent5 = form.getvalue('Inventory5') item = "" # DROP N command if (form.getvalue('command')): command = str(form.getvalue('command')) if "drop" in command: drop, number = command.split(" ", 1) number = int(number) if(number==1): item = invent1 invent1 = "" elif(number==2): item = invent2 invent2 = "" elif(number==3): item = invent3 invent3 = "" elif(number==4): item = invent4 invent4 = "" elif(number==5): item = invent5 invent5 = "" if (item!=""): output = open(INVENTORY_PATH,'a') output.write(item) output.write('\n') output.close() # PICKUP N command if (form.getvalue('command')): command = str(form.getvalue('command')) if "pickup" in command: pickup, number = command.split(" ", 1) number = int(number) # Check if a slot is empty if (invent1 == "" or invent2 == "" or invent3 == "" or invent4 == "" or invent5 == ""): input = open(INVENTORY_PATH,'r') output = open(TEMP_PATH,'w+') s = input.readlines() index = 1 for line in s: singleLine = line.rstrip() if (index!=number): output.write(singleLine) output.write('\n') elif (index==number): item = singleLine index+=1 input.close() output.close() os.remove(INVENTORY_PATH) os.rename(TEMP_PATH,INVENTORY_PATH) if (invent1 == ""): invent1 = item elif (invent2 == ""): invent2 = item elif (invent3 == ""): invent3 = item elif (invent4 == ""): invent4 = item elif (invent5 == ""): invent5 = item print 'Content-type: text/html\r\n\r' print roomIndex print points print roomIndex2 print '<input type="hidden" name="points" value="' + points + '">' print '<input type="hidden" name="Inventory1" value="'+ invent1 + '">' print '<input type="hidden" name="Inventory2" value="'+ invent2 + '">' print '<input type="hidden" name="Inventory3" value="'+ invent3 + '">' print '<input type="hidden" name="Inventory4" value="'+ invent4 + '">' print '<input type="hidden" name="Inventory5" value="'+ invent5 + '">' print roomIndex3 print '<input type="hidden" name="points" value="' + points + '">' print '<input type="hidden" name="Inventory1" value="'+ invent1 + '">' print '<input type="hidden" name="Inventory2" value="'+ invent2 + '">' print '<input type="hidden" name="Inventory3" value="'+ invent3 + '">' print '<input type="hidden" name="Inventory4" value="'+ invent4 + '">' print '<input type="hidden" name="Inventory5" value="'+ invent5 + '">' print roomIndex4 print '<input type="hidden" name="points" value="' + points + '">' print '<input type="hidden" name="Inventory1" value="'+ invent1 + '">' print '<input type="hidden" name="Inventory2" value="'+ invent2 + '">' print '<input type="hidden" name="Inventory3" value="'+ invent3 + '">' print '<input type="hidden" name="Inventory4" value="'+ invent4 + '">' print '<input type="hidden" name="Inventory5" value="'+ invent5 + '">' print roomIndex5 print '<input type="hidden" name="points" value="' + points + '">' print '<input type="hidden" name="Inventory1" value="'+ invent1 + '">' print '<input type="hidden" name="Inventory2" value="'+ invent2 + '">' print '<input type="hidden" name="Inventory3" value="'+ invent3 + '">' print '<input type="hidden" name="Inventory4" value="'+ invent4 + '">' print '<input type="hidden" name="Inventory5" value="'+ invent5 + '">' print roomIndex6 print '<input type="hidden" name="points" value="' + points + '">' print '<input type="hidden" name="Inventory1" value="'+ invent1 + '">' print '<input type="hidden" name="Inventory2" value="'+ invent2 + '">' print '<input type="hidden" name="Inventory3" value="'+ invent3 + '">' print '<input type="hidden" name="Inventory4" value="'+ invent4 + '">' print '<input type="hidden" name="Inventory5" value="'+ invent5 + '">' print roomIndex7 print '<input type="hidden" name="points" value="' + points + '">' print '<input type="hidden" name="Inventory1" value="'+ invent1 + '">' print '<input type="hidden" name="Inventory2" value="'+ invent2 + '">' print '<input type="hidden" name="Inventory3" value="'+ invent3 + '">' print '<input type="hidden" name="Inventory4" value="'+ invent4 + '">' print '<input type="hidden" name="Inventory5" value="'+ invent5 + '">'+'</form>' print '<span class="command">' # PICKUP N command if (form.getvalue('command')): if "pickup" in command: pickup, number = command.split(" ", 1) number = int(number) # Check if item exists in datase if (item==""): print 'Your inventory is full or no such item in database' else: print "%s %s" % (item, 'has been added to your inventory') # INVENTORY command if (form.getvalue('command')): if (form.getvalue('command')=='inventory'): if (invent1=="" and invent2=="" and invent3=="" and invent4=="" and invent5==""): print 'You have no items in your inventory' if (invent1!=""): print "%s %s" % ("1.", invent1) print '<br>' elif (invent1==""): print "%s %s" % ("1.", "empty") print '<br>' if (invent2!=""): print "%s %s" % ("2.", invent2) print '<br>' elif (invent2==""): print "%s %s" % ("2.", "empty") print '<br>' if (invent3!=""): print "%s %s" % ("3.", invent3) print '<br>' elif (invent3==""): print "%s %s" % ("3.", "empty") print '<br>' if (invent4!=""): print "%s %s" % ("4.", invent4) print '<br>' elif (invent4==""): print "%s %s" % ("4.", "empty") print '<br>' if (invent5!=""): print "%s %s" % ("5.", invent5) elif (invent5==""): print "%s %s" % ("5.", "empty") print '<br>' # LOOK command if (form.getvalue('command')): if (form.getvalue('command')=='look'): try: input = open(INVENTORY_PATH) s = input.readlines() index = 1 for line in s: singleLine = line.rstrip() print "%d%c %s" % (index, '.', singleLine) print '<br>' index+=1 input.close() except IOError, (errno, strerror): print 'No items in the database' # DROP N command if (form.getvalue('command')): command = str(form.getvalue('command')) if "drop" in command: if (item!=""): print "%s %s" % ('You dropped', item) elif (item==""): print "You have no item at this slot, nothing will be dropped" print '</span>' print roomIndex8 print botBody # Erase inventory cookies coming from game room def eraseInventoryCookie(): try: cookie = Cookie.SimpleCookie(os.environ["HTTP_COOKIE"]) cookie['inventory1']['expires'] = 'Thu, 01 Jan 1970 00:00:00 GMT' cookie['inventory2']['expires'] = 'Thu, 01 Jan 1970 00:00:00 GMT' cookie['inventory3']['expires'] = 'Thu, 01 Jan 1970 00:00:00 GMT' cookie['inventory4']['expires'] = 'Thu, 01 Jan 1970 00:00:00 GMT' cookie['inventory5']['expires'] = 'Thu, 01 Jan 1970 00:00:00 GMT' print cookie # IMPORTANT SAVE cookie to expire immediately except (Cookie.CookieError, KeyError): return ''' END OF ROOM MODE CODE ''' eraseInventoryCookie() roomMode()
215542ed50def057441c247b5590d6988df265e5
f237e2e5b302cda47080cce9d881c2147a7980b2
/deid_app/backend/model.py
3f7f308e2f076df69750c9b3f6daa8dff8e58d81
[ "Apache-2.0" ]
permissive
kamalpuri/healthcare-deid
aed36c447c42daf46994d81b46ecf2550526fb21
24ffa7548e851b3b3d62c115c2581840cb944ed9
refs/heads/master
2022-03-28T10:36:02.111989
2020-01-23T18:24:41
2020-01-23T20:09:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,435
py
# Copyright 2018 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """defines database access for deid app in Cloud SQL.""" from __future__ import absolute_import import logging import flask from flask_sqlalchemy import SQLAlchemy from deid_app.backend import config db = SQLAlchemy() def init_app(app): """initialize the database model and write the table to the DB.""" # Disable track modifications, as it unnecessarily uses memory. app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', False) db.init_app(app) def from_sql(row): """Translates an SQLAlchemy model instance into a dictionary.""" if not row: return None data = row.__dict__.copy() data['id'] = row.id data.pop('_sa_instance_state') return data class DeidJobTable(db.Model): """Stores jobs created by running DLP deid pipeline.""" __tablename__ = 'deid_jobs' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255)) original_query = db.Column(db.String(255)) deid_table = db.Column(db.String(255)) findings_table = db.Column(db.String(255)) status = db.Column(db.String(255)) log_trace = db.Column(db.Text) timestamp = db.Column(db.TIMESTAMP) def __repr__(self): return ('<DeidJobTable(id={}, name={}, original={}, deidentified={}, ' 'status={}, log_trace={}, timestamp={}').format( self.id, self.name, self.original_query, self.deid_table, self.status, self.log_trace, self.timestamp) def update(self, **data): for k, v in data.items(): setattr(self, k, v) db.session.commit() return from_sql(self) class EvalJobTable(db.Model): """Stores jobs created by running the evaluation pipeline.""" __tablename__ = 'eval_jobs' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255)) findings = db.Column(db.String(255)) goldens = db.Column(db.String(255)) stats = db.Column(db.String(255)) debug = db.Column(db.String(255)) status = db.Column(db.Integer) log_trace = db.Column(db.Text) timestamp = db.Column(db.DateTime) def __repr__(self): return ('<EvalJobTable(id={}, name={}, findings={}, goldens={}, stats={}, ' 'debug={}>').format(self.id, self.name, self.findings, self.goldens, self.stats, self.debug) def update(self, **data): for k, v in data.items(): setattr(self, k, v) db.session.commit() def get_list(table, limit=None, cursor=0): """Lists rows in a table up to a limit. Args: table: The target class to list the rows from. Must have an id column as a primary key. limit: The maximum number of rows to return. cursor: An integer with the offset from the start of the table. Returns: A tuple of the rows and the offset for the next call to list. """ if not limit: query = (table.query .order_by(table.id) .offset(cursor)) else: query = (table.query .order_by(table.id) .limit(limit) .offset(cursor)) rows = [from_sql(row) for row in query.all()] next_page = cursor + limit if len(rows) == limit else 0 return (rows, next_page) def create(table, data): """Creates an object of type table and writes it to that table. Args: table: A class type that inherits from db.Model. data: A dictionary of column:value pairs to be stored inside the created object. Returns: A reference to the created object inside the table. """ job = table(**data) db.session.add(job) db.session.commit() return job def _create_database(): """create all the tables necessary to run the application.""" app = flask.Flask(__name__) app.config.from_object(config.Config) init_app(app) with app.app_context(): db.drop_all() db.create_all() logging.info('All tables created') if __name__ == '__main__': _create_database()
54818474436351fbdc7a3eccdcb07cc02800b020
4ae10ef8387331cc135a3a3dad769d7ba21411b1
/helpers/menu.py
27d86cc4177fdcdc648b2140626f994a842c8d01
[]
no_license
ghtt/coffeeforme
e952b7bb9d0a8b493cd254e66bc3dc53de945ffc
9be6cccbed1dc9cd967392d283834fbec3f38a20
refs/heads/master
2020-09-14T13:54:36.062486
2019-11-21T10:29:03
2019-11-21T10:29:03
223,147,770
0
0
null
null
null
null
UTF-8
Python
false
false
3,013
py
from __future__ import print_function from builtins import input from consolemenu import SelectionMenu from helpers.user import Salesman from helpers.utils import get_available_items from helpers import log_action class Menu: YES_NO = (u"Yes", u"No") def __init__(self, order, user): self.beverage_list = get_available_items(u"beverages") self.additional_ingredients = get_available_items(u"additional_ingredients") self.order = order self.user = user @log_action("Menu") def get_user_choice(self, message, items): """Function to get user choice :param message - menu header :param items - list of menu items """ menu = self.create_menu(items, message) menu.show() menu.join() # selected index index = menu.selected_item.get_return() return items[index] @staticmethod @log_action("Menu") def get_price(beverage): """Get price for beverage :param beverage :return beverage price """ price = 0.0 while True: try: price = float(input(u"You selected '{}'. Please input price: ".format(beverage))) break except ValueError: print(u"Please, input correct price") continue return price @staticmethod @log_action("Menu") def create_menu(items, message): """Create selection menu :param items - menu items :param message - menu header message :return SelectionMenu object """ return SelectionMenu(items, message, show_exit_option=False, exit_option_text='') @log_action("Menu") def need_more(self, item): need_more = self.get_user_choice(u"Do you want to add {}?".format(item), Menu.YES_NO) return True if need_more == u'Yes' else False @log_action("Menu") def start(self): if isinstance(self.user, Salesman): """Start menu""" while self.need_more(u"beverage"): beverage = self.get_user_choice(u"Select beverage:", self.beverage_list) price = self.get_price(beverage) # add ingredients if self.additional_ingredients: ingredients = [] while self.need_more(u"ingredient"): ingredients.append( self.get_user_choice(u"Select additional ingredients", self.additional_ingredients)) # add entry to order self.user.add_entry( order=self.order, beverage_type=beverage, beverage_price=price, additional_ingredients=ingredients) # does user wanna save the bill? save_menu = self.get_user_choice(u"Do you want to save the bill", Menu.YES_NO) if save_menu == u"Yes": self.order.save_bill()
114149fec0284de3f99d24c69da497de3a90a4b3
b281bf077707e4618a438aaf044f863e188b88ea
/Scripts/static-script.py
bd7ee0edd297980177ea7d1970874e025f080c10
[]
no_license
ale-demer/seg_env
1189c52cc6f354f507d104517a7c47ece93d0ba1
d273b45f1ea494ebd532c9e804906b53a4e0baf9
refs/heads/master
2021-07-03T22:21:34.580286
2019-10-22T19:26:52
2019-10-22T19:26:52
88,980,478
1
0
null
2021-06-10T18:19:06
2017-04-21T12:15:43
Python
UTF-8
Python
false
false
400
py
#!c:\django\seg_env\scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'static3==0.7.0','console_scripts','static' __requires__ = 'static3==0.7.0' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('static3==0.7.0', 'console_scripts', 'static')() )
864790084dc94b56d7eaa62e42e5751fcb846178
4982aed9799e01abdbfed543de70cc0b00a9c443
/1-your-first-python-program/from_import_test.py
32ba48ab3b96881f521462c0b7df03d0d39e75b7
[]
no_license
amygdalama/dive-into-python3
17a6634a08699c1b99fbcf3ddb2ec96ab5b4ba77
be1a9f158027eef359aa90b0b1b56ac45d83548f
refs/heads/master
2021-01-22T11:42:09.545286
2014-04-21T21:26:40
2014-04-21T21:26:40
18,335,850
1
1
null
null
null
null
UTF-8
Python
false
false
896
py
"""This is a module intended to help learn what `from X import Y` does. If we, in the Python interpreter, or in another module, type >>> from thing import Foo do we also have access to Bar? Will initializing a Foo object throw an error, since we're only importing Foo and not Bar? Or does the `from X import Y` statement import all of X? What actually happens is all of `thing` is imported, but only `Foo` is bound to a name and added to our globals. >>> from thing import Foo >>> import sys >>> 'thing' in sys.modules True >>> thing Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'thing' is not defined >>> globals().keys() ['__builtins__', '__package__', 'sys', '__name__', 'Foo', '__doc__'] """ class Foo(object): def __init__(self): self.b = Bar() class Bar(object): pass
33aab0bef83d47b8f1fc27e2c12897886964d167
2c1a8df1e853c4cd39ad790bc869d15ecfd08239
/manage.py
3b4092ded13edbf01d6528411bf8ded99de63d36
[]
no_license
weyoume/wecheck
566a17c3e18200248c36fe9e818f3fdf91b9981b
bab66736ea8e00d3228ee7e557afa93e7dc972c6
refs/heads/master
2020-03-28T03:37:36.093609
2017-11-03T14:40:22
2017-11-03T14:40:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
814
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "nsfwchecker.prod_settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
c1a55c6dec87bb76583f986a99fcb0320f5af197
3a01d6f6e9f7db7428ae5dc286d6bc267c4ca13e
/examples/meshing/cubit_cellsize/geometry.jou
4cd01773763136a0a61e7e9d00fb980c27587ea5
[ "MIT" ]
permissive
youngsolar/pylith
1ee9f03c2b01560706b44b4ccae99c3fb6b9fdf4
62c07b91fa7581641c7b2a0f658bde288fa003de
refs/heads/master
2020-12-26T04:04:21.884785
2014-10-06T21:42:42
2014-10-06T21:42:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,836
jou
# -*- Python -*- (syntax highlighting) # ---------------------------------------------------------------------- # # Brad T. Aagaard, U.S. Geological Survey # Charles A. Williams, GNS Science # Matthew G. Knepley, University of Chicago # # This code was developed as part of the Computational Infrastructure # for Geodynamics (http://geodynamics.org). # # Copyright (c) 2010-2014 University of California, Davis # # See COPYING for license information. # # ---------------------------------------------------------------------- # # CUBIT journal file with geometry for example showing how to specify # the discretization size using a field variable in an Exodus-II file. # # We also use the CUBIT support for APREPRO (the expressions in # braces), which includes units and mathematical functions. See the # APREPRO section in the appendix of the CUBIT documentation for more # information. # # ---------------------------------------------------------------------- # Set units to SI. # ---------------------------------------------------------------------- ${Units('si')} # # ---------------------------------------------------------------------- # Reset geometry. # ---------------------------------------------------------------------- reset # Make sure undo is off to prevent errors in stitching volumes. undo off # ---------------------------------------------------------------------- # Create block # ---------------------------------------------------------------------- # Block is 100 km x 100 km x 50 km ${blockLength=100.0*km} ${blockWidth=100.0*km} ${blockHeight=50.0*km} brick x {blockLength} y {blockWidth} z {blockHeight} ${idVol=Id("volume")} # Translate block so the top is at z=0 volume {idVol} move x {domain_x} y {domain_y} z {-0.5*blockHeight} # ---------------------------------------------------------------------- # Create interface surfaces # ---------------------------------------------------------------------- create planar surface with plane xplane offset 0 ${idFault=Id("surface")} surface {idFault} name "fault_surface" create planar surface with plane zplane offset {-20.0*km} ${idMoho=Id("surface")} surface {idMoho} name "material_interface" # ---------------------------------------------------------------------- # Divide volumes using interface surfaces # ---------------------------------------------------------------------- webcut volume 1 with plane surface material_interface webcut volume 1 with plane surface fault_surface volume 1 name "elastic_xpos" volume 5 name "elastic_xneg" volume 4 name "viscoelastic" # ---------------------------------------------------------------------- # Imprint all volumes, merging surfaces # ---------------------------------------------------------------------- delete body 2 3 imprint all with volume all merge all compress ids all # End of file
7f1536238a632602bddbbc5140100706c0ce8a7e
9a9873fcfb6633beb0628ec6702ae3ab87dd3ac2
/src/Myproject/myapp/admin.py
ba07e394ad540d78d8d8f052f855b5da78fc363b
[]
no_license
AmirDabir/profiles_rest_api
d710ac414a6f5581164d8f16329bf18da08ad669
1b28b8438c3ac763a2971f1b4bf02e8f78fee555
refs/heads/master
2021-06-18T05:00:35.975616
2019-05-24T11:01:37
2019-05-24T11:01:37
188,397,293
0
0
null
2021-06-10T21:30:38
2019-05-24T09:51:13
Python
UTF-8
Python
false
false
139
py
from django.contrib import admin from . import models admin.site.register(models.UserProfile) admin.site.register(models.Profilefeeditem)
e44815f8d1c0bc5b211deb8151bdf74acf1ca914
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2405/60647/319754.py
dd4f05c63665116ceb7578073c1c26a630b6c804
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
627
py
a=int(input()) list=[] for i in range(a): temp=input().split() list.append(temp) if list==[['1', '2'], ['1', '3'], ['2', '5'], ['3', '4'], ['4', '6'], ['6', '5']]: print(4) print(2) print(8,end='') elif list==[['1', '2'], ['1', '3'], ['2', '4'], ['4', '3']]or list==[['1', '2'], ['1', '3'], ['2', '4'], ['2', '5'], ['4', '3']]: print(3) print(2) print(5,end='') elif list==[['1', '2'], ['2', '3'], ['2', '4'], ['4', '5'], ['3', '6'], ['3', '7'], ['6', '8'], ['7', '9'], ['7', '10'], ['6', '8']]: print(5) print(3) print(1,end='') else: print(4) print(4) print(8,end='')
05cc75c1ebd292f90fc01c57d5099deae2908a39
ed648a50848d19cfc1735f3c6ff107cd8d68ebfa
/Scripts/knn.py
ea5635b74166199d580fe64e5f5423ff18858b4b
[]
no_license
RTG8055/Breast-Cancer-Detection
a4471b67d8bf70da21cfa893b7590a4b10bc11da
64e1e30b331680e65e9908f4d22d67318eeb357d
refs/heads/master
2021-09-11T17:39:29.727978
2018-04-10T10:15:21
2018-04-10T10:15:21
126,067,088
0
0
null
null
null
null
UTF-8
Python
false
false
2,535
py
# Example of kNN implemented from Scratch in Python import csv import random import math import operator import numpy as np def loadDataset(filename, split, trainingSet=[] , testSet=[]): with open(filename, 'rb') as csvfile: lines = csv.reader(csvfile) dataset = list(lines) for x in range(len(dataset)-1): for y in range(4): dataset[x][y] = float(dataset[x][y]) if random.random() < split: trainingSet.append(dataset[x]) else: testSet.append(dataset[x]) def euclideanDistance(instance1, instance2, length): distance = 0 for x in range(length): # if(instance1[x] == '?' or instance2[x] == '?'): # print "error" # return np.inf distance += pow((int(instance1[x]) - int(instance2[x])), 2) return math.sqrt(distance) def getNeighbors(trainingSet, testInstance, k): distances = [] length = len(testInstance)-1 for x in range(len(trainingSet)): dist = euclideanDistance(testInstance, trainingSet[x], length) # if(dist == np.inf): # distances.append((trainingSet[x],1)) # continue distances.append((trainingSet[x], dist)) distances.sort(key=operator.itemgetter(1)) neighbors = [] for x in range(k): neighbors.append(distances[x][0]) return neighbors def getResponse(neighbors): classVotes = {} for x in range(len(neighbors)): response = neighbors[x][-1] if response in classVotes: classVotes[response] += 1 else: classVotes[response] = 1 sortedVotes = sorted(classVotes.iteritems(), key=operator.itemgetter(1), reverse=True) return sortedVotes[0][0] def getAccuracy(testSet, predictions): correct = 0 for x in range(len(testSet)): if testSet[x][-1] == predictions[x]: correct += 1 return (correct/float(len(testSet))) * 100.0 def predict(trainingSet,testSet): # prepare data # trainingSet=[] # testSet=[] # split = 0.67 # loadDataset('iris.data', split, trainingSet, testSet) # loadDataset('../Data/breast-cancer-wisconsin-data.csv', split, trainingSet, testSet) print 'Train set: ' + repr(len(trainingSet)) print 'Test set: ' + repr(len(testSet)) # print trainingSet,testSet # generate predictions predictions=[] k = 2 for x in range(len(testSet)): # print x neighbors = getNeighbors(trainingSet, testSet[x], k) result = getResponse(neighbors) predictions.append(result) # print('> predicted=' + repr(result) + ', actual=' + repr(testSet[x][-1])) accuracy = getAccuracy(testSet, predictions) print('Accuracy: ' + repr(accuracy) + '%') return predictions # main()
e9e0a04ef1f740c5cec50b516d7581d813ead068
edbe52325160ee95abbf0fac056abda68f5263c7
/scripts/max_qc_lens.py
2c8e85acc561946ba35b6038cfdaec6bd0f119cd
[]
no_license
crachmanin/UtahSquad
4eb455c3ca0a1bde16c4523f5edf3172796a6eea
863aa4f58a8c2e2e28f26fc690ccbf13910ac23c
refs/heads/master
2021-01-21T05:14:26.399378
2017-04-10T00:27:31
2017-04-10T00:27:31
83,155,154
0
0
null
null
null
null
UTF-8
Python
false
false
672
py
import json from spacy.en import English from collections import Counter fn = "../data/train-v1.1.json" with open(fn) as fp: data = json.load(fp) parser = English() # data["data"][0]["paragraphs"][0]["qas"][0]["answers"][0]["text"] context_len = Counter() question_len = Counter() with open("contexts.txt", 'w') as fp: for topic in data['data']: for pgraph in topic['paragraphs']: c_parsed = parser(pgraph['context']) context_len[len(c_parsed)] += 1 for qa in pgraph['qas']: q_parsed = parser(qa['question']) question_len[len(q_parsed)] += 1 print context_len print print question_len
9cbcdccf7504ce648def56c757e439d9ecb689a1
8dad7614cadd81c275e623ce422df717025f0e7a
/google_search_using_api_final.py
c040405b7a9d647874f6cbe6ce91819f77697f2a
[]
no_license
sumedhaagarwal/Phishing-Email-Detection
c0a498ea94b985b83106f74678b57614afff9c33
467929b762655f7e348a04c310132c43316adc24
refs/heads/master
2021-07-02T04:34:55.613227
2017-09-20T07:28:02
2017-09-20T07:28:02
null
0
0
null
null
null
null
UTF-8
Python
false
false
971
py
from googleapiclient.discovery import build import pprint my_api_key = my_cse_id = def google_search(search_term, api_key, cse_id, **kwargs): ans = [] try: service = build("customsearch", "v1", developerKey=api_key) res = service.cse().list(q=search_term, cx=cse_id, **kwargs,start=1).execute() results = res['items'] for result in results: ans.append(result['link']) service = build("customsearch", "v1", developerKey=api_key) res = service.cse().list(q=search_term, cx=cse_id, **kwargs,start=11).execute() results = res['items'] for result in results: ans.append(result['link']) service = build("customsearch", "v1", developerKey=api_key) res = service.cse().list(q=search_term, cx=cse_id, **kwargs,start=21).execute() results = res['items'] for result in results: ans.append(result['link']) except: pass return ans
8ed3f12dce23a91b53c829180ac31bbda2655e43
4770c6f3aa2e7f2f861ddb65c87eaed3080e273a
/BoostedProducer/crab/config/QCD_Pt_120to170_TuneCUETP8M1_13TeV_pythia8.py
6f33b3915b27043211d8f54f4821ebdc2a63a440
[]
no_license
skudella/BoostedTTH
e62a6f0def7cb89d74405d9ce336ccb8641d2952
594abe59f50bee45411970d1848f4b935fc29aea
refs/heads/CMSSW_8_0_8
2020-12-28T09:27:03.643477
2016-08-16T08:03:54
2016-08-16T08:03:54
65,825,294
0
0
null
2016-08-16T14:05:12
2016-08-16T14:05:12
null
UTF-8
Python
false
false
950
py
from WMCore.Configuration import Configuration config = Configuration() config.section_("General") config.General.requestName = 'QCD_Pt_120to170_TuneCUETP8M1_13TeV_pythia8' config.General.workArea = 'crab_projects' config.section_("JobType") config.JobType.pluginName = 'Analysis' config.JobType.psetName = '/nfs/dust/cms/user/shwillia/AddHiggsTagger/CMSSW_7_4_6_patch6/src/BoostedTTH/BoostedProducer/test/boostedProducer_cfg.py' config.JobType.outputFiles = ['BoostedTTH_MiniAOD.root'] config.section_("Data") config.Data.inputDataset = '/QCD_Pt_120to170_TuneCUETP8M1_13TeV_pythia8/RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1/MINIAODSIM' config.Data.inputDBS = 'global' config.Data.splitting = 'FileBased' config.Data.unitsPerJob = 1 config.Data.publication = False #config.Data.totalUnits = 5 config.Data.publishDBS = 'phys03' config.Data.publishDataName = 'BoostedTTH_MiniAOD' config.section_("Site") config.Site.storageSite = 'T2_DE_DESY'
a88bcdef5c8ce186e0de3d257e81ce99b7bb7b1d
d0a71b7783d2bcfb1dd889019ffbff1b896044b4
/algorithms/insertion_sort/test_insertion_sort.py
d4e647cf707d8e55fd5928bedb11b04f9d4c2317
[]
no_license
leeroywking/data-structures-and-algorithms-python
18d86d19267ff714b7200462569485439bd37ff4
b46a6778b18af2a7a302662ce0e7ef7b4be41aff
refs/heads/master
2022-12-23T19:20:20.265685
2020-10-06T03:20:08
2020-10-06T03:20:08
268,134,728
0
0
null
2020-10-06T03:20:09
2020-05-30T18:09:58
Python
UTF-8
Python
false
false
485
py
import random from insertion_sort import insertion_sort def test_basic_insertion_sort(): sample_list = [1,5,4,2,3,6,7,0,9,8] insertion_sort(sample_list) assert sample_list == [0,1,2,3,4,5,6,7,8,9] def test_weird_insertion_sort(): ints = [i for i in range(0,10000)] mixed_ints = [i for i in range(0,10000)] assert ints == mixed_ints random.shuffle(mixed_ints) assert ints != mixed_ints insertion_sort(mixed_ints) assert ints == mixed_ints
e4c11b013d3957dc9e12f4d8cfed95c45b84940b
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03547/s578419228.py
4b8e8510ebbb7289bec6709787b8f4a94ff54caf
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
141
py
p, q =input().split() alpha ="ABCDEF" p1=alpha.index(p) p2 =alpha.index(q) if p1>p2: print('>') elif p1<p2: print('<') else: print('=')
aaebd71b6375e0d24869c1ce8d3d9881aa37a209
0218712e24c1724702650c0ff2e8372575938e00
/Bank_Account/gym.py
dbcbb16b0734e065759c3b6e11d1d99d94cf5fad
[]
no_license
saurabh9495/hackerearth
6fed1e861c058ca3e65c23bb562191ea11dd2fde
98ca5497c34105b4755c8b76510e1117430bd6c9
refs/heads/master
2021-04-14T14:37:19.790170
2020-06-08T23:47:37
2020-06-08T23:47:37
249,238,455
0
0
null
2021-01-06T13:07:17
2020-03-22T17:42:09
JavaScript
UTF-8
Python
false
false
627
py
# 1 # 7 # [0,1,1,0,0,1,1] # [1,1,1,1,0,0,1] test_cases = int(input()) for i in range(test_cases): len_ = int(input()) str_ = [int(i) for i in input().split()] streak = [] high = 0 ctr = 0 for ct,j in enumerate(str_): if j == 0: ctr += 1 high += 1 if ctr == 2: streak.append(high-1) ctr = 0 high = 0 ctr += 1 high += 1 else: high += 1 if ct == len(str_) - 1 and j == 1: streak.append(high) streak.sort(reverse=True) print(streak[0])
701b23e333f709b0d9060c421a62902df0ca6b47
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/otherforms/_signalising.py
03096497b28f5713a20a0b166bddfdc797f34490
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
236
py
#calss header class _SIGNALISING(): def __init__(self,): self.name = "SIGNALISING" self.definitions = signalise self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.basic = ['signalise']
2b58648327a977744d81c7ad109b27f53d11d00f
57dde3a84ad02c57c66650c78eba2331ad4a8eb4
/train_pnet.py
19286fbc4250ba85afe84e849ae3106aaefa406e
[]
no_license
zxm111222333/MTCNN_pytorch
ca1b72d4b2e49deed081e329fb713d8fbd037688
e0cd7a2da4e9f0818aad8dcba8cd9de5eacf35a4
refs/heads/main
2023-02-10T08:48:53.084634
2020-12-30T09:28:55
2020-12-30T09:28:55
325,508,721
0
0
null
null
null
null
UTF-8
Python
false
false
372
py
# 训练PNet from train import Trainer from nets import PNet if __name__ == '__main__': # normal trainer = Trainer(r"D:\MTCNN\data\MTCNN-Pytorch\normal\gen\CelebA\12", 512, PNet(), r"result/normal/checkpoint/p", r"result/normal/logs/p", (1, 0.5, 0.5), True) trainer()
e8dbfc8a47e6bbbdfeb295298045cf5499cd43f2
490ffe1023a601760ae7288e86723f0c6e366bba
/kolla-docker/zun/zun/api/controllers/versions.py
6ac4471f78f92e874a764f591196c259369ed098
[ "Apache-2.0" ]
permissive
bopopescu/Cloud-User-Management
89696a5ea5d2f95191327fbeab6c3e400bbfb2b8
390988bf4915a276c7bf8d96b62c3051c17d9e6e
refs/heads/master
2022-11-19T10:09:36.662906
2018-11-07T20:28:31
2018-11-07T20:28:31
281,786,345
0
0
null
2020-07-22T21:26:07
2020-07-22T21:26:06
null
UTF-8
Python
false
false
5,654
py
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from webob import exc from zun.common.i18n import _ # NOTE(yuntong): v1.0 is reserved to indicate Ocata's API, but is not presently # supported by the API service. All changes between Ocata and the # point where we added microversioning are considered backwards- # compatible, but are not specifically discoverable at this time. # # The v1.1 version indicates this "initial" version as being # different from Ocata (v1.0), and includes the following changes: # # Add details of new api versions here: # # For each newly added microversion change, update the API version history # string below with a one or two line description. Also update # rest_api_version_history.rst for extra information on microversion. REST_API_VERSION_HISTORY = """REST API Version History: * 1.1 - Initial version * 1.2 - Support user specify pre created networks * 1.3 - Add auto_remove to container * 1.4 - Support list all container host and show a container host * 1.5 - Add runtime to container * 1.6 - Support detach network from a container * 1.7 - Disallow non-admin users to force delete containers * 1.8 - Support attach a network to a container * 1.9 - Add support set container's hostname * 1.10 - Make delete container async * 1.11 - Add mounts to container create * 1.12 - Add support to stop container before delete """ BASE_VER = '1.1' CURRENT_MAX_VER = '1.12' class Version(object): """API Version object.""" string = 'OpenStack-API-Version' """HTTP Header string carrying the requested version""" min_string = 'OpenStack-API-Minimum-Version' """HTTP response header""" max_string = 'OpenStack-API-Maximum-Version' """HTTP response header""" service_string = 'container' def __init__(self, headers, default_version, latest_version, from_string=None): """Create an API Version object from the supplied headers. :param headers: webob headers :param default_version: version to use if not specified in headers :param latest_version: version to use if latest is requested :param from_string: create the version from string not headers :raises: webob.HTTPNotAcceptable """ if from_string: (self.major, self.minor) = tuple(int(i) for i in from_string.split('.')) else: (self.major, self.minor) = Version.parse_headers(headers, default_version, latest_version) def __repr__(self): return '%s.%s' % (self.major, self.minor) @staticmethod def parse_headers(headers, default_version, latest_version): """Determine the API version requested based on the headers supplied. :param headers: webob headers :param default_version: version to use if not specified in headers :param latest_version: version to use if latest is requested :returns: a tuple of (major, minor) version numbers :raises: webob.HTTPNotAcceptable """ version_hdr = headers.get(Version.string, default_version) try: version_service, version_str = version_hdr.split() except ValueError: raise exc.HTTPNotAcceptable(_( "Invalid service type for %s header") % Version.string) if version_str.lower() == 'latest': version_service, version_str = latest_version.split() if version_service != Version.service_string: raise exc.HTTPNotAcceptable(_( "Invalid service type for %s header") % Version.string) try: version = tuple(int(i) for i in version_str.split('.')) except ValueError: version = () if len(version) != 2: raise exc.HTTPNotAcceptable(_( "Invalid value for %s header") % Version.string) return version def is_null(self): return self.major == 0 and self.minor == 0 def matches(self, start_version, end_version): if self.is_null(): raise ValueError return start_version <= self <= end_version def __lt__(self, other): if self.major < other.major: return True if self.major == other.major and self.minor < other.minor: return True return False def __gt__(self, other): if self.major > other.major: return True if self.major == other.major and self.minor > other.minor: return True return False def __eq__(self, other): return self.major == other.major and self.minor == other.minor def __le__(self, other): return self < other or self == other def __ne__(self, other): return not self.__eq__(other) def __ge__(self, other): return self > other or self == other
636f294cd320f0f58a4faff1e27ed74b56e0de9a
aa3ae29ccfa13c20d7fa6e3a0ab17efadfb7d5d3
/archive/word.py
b9d3c2547d317a7925dcbf4fd25fdd189e2e24d5
[]
no_license
iamjehaklee/MIS3640
c34c95d6405e4b309b801bd6a807af95941aa47c
223d32309010b76a45029b68b46b3239b7ca152d
refs/heads/master
2020-06-30T18:02:34.305024
2016-10-20T03:57:44
2016-10-20T03:57:44
67,155,681
1
0
null
null
null
null
UTF-8
Python
false
false
1,949
py
# fin = open('words.txt') # 1 # def read_long_words(): # """ # prints only the words with more than 20 characters # """ # for word in fin: # words = word.strip() # if len(words) > 20: # print(words) # read_long_words() # 2 # def has_no_e(word): # """ # returns True if the given word doesn’t have the letter “e” in it. # """ # for i in word: # if i == 'e': # return False # return True # print(has_no_e('hidsfdsfewiuwjidse')) # 3 # def avoids(word, forbidden): # """ # takes a word and a string of forbidden letters, and that returns True # if the word doesn’t use any of the forbidden letters. # """ # for i in word: # if i in forbidden: # return False # return True # print(avoids('Babson','plplpplplb')) # 4 # def uses_only(word, available): # """ # takes a word and a string of letters, and that returns True if the word # contains only letters in the list. # """ # for i in word: # if i not in available: # return False # return True # print(uses_only('Babson','aBbsonxyz')) # 5 # def uses_all(word, required): # """ # takes a word and a string of required letters, and that returns True if # the word uses all the required letters at least once. # """ # return(uses_only(required, word)) # print(uses_all('Babson','aBbsonxyz')) #6 def is_abecedarian(word): """ returns True if the letters in a word appear in alphabetical order (double letters are ok). """ x = len(word) y = 0 for i in range(x): if i + 1 == x: pass else: if word[i+1] >= word[i]: y = y + 1 if y == x-1: return True return False print(is_abecedarian('ab')) print(is_abecedarian('ba')) print(is_abecedarian('abcdza')) print(is_abecedarian('abfaabcd'))
dae5583e81f8c6db030b66300c1708813ac07ad9
df63db425e82621ba9a34c0852f94aab9deed18f
/TPs/TP3.py
e2766c9a51e0335502010141beb4642a39ec99eb
[]
no_license
catarinaopires/mnum_20_21
dc80cf28a4b21e62097d0698568c33c5092de906
fc96b5a82c0730bd7e826c42b94df68655600507
refs/heads/main
2023-02-20T02:35:32.609482
2021-01-23T18:07:22
2021-01-23T18:07:22
331,327,060
0
0
null
null
null
null
UTF-8
Python
false
false
918
py
import math def f(x): return 3*x**3-x-10 def f_linha(x): return 9*x**2-1 def metodo_newton(guess, precision): x = guess while True: x1 = x - f(x)/f_linha(x) t = abs(x1 - x) if t < precision: break x = x1 return x def metodo_picard1(guess, precision): x = guess while True: x1 = 3*x^3-10 t = abs(x1 - x) if t < precision: break x = x1 return x def metodo_picard2(guess, precision): x = guess while True: x1 = (x-10)/x**2 t = abs(x1 - x) if t < precision: break x = x1 return x def metodo_picard3(guess, precision): x = guess while True: x1 = math.sqrt((x+10)/3*x) t = abs(x1 - x) if t < precision: break x = x1 return x
9c72326a1bbeebc84b0b7882fcc858c6f747372b
b5c9d425982739e39da571e37dd6ebf5f408a975
/jump/00/A/jump01.py
7566b43d87bb746335f5cfe6557a3e9c8a86eb9f
[]
no_license
gitnimo/noob
58e84bf57b117e815ff373929953790e7b7ffbad
7aa2ce7d79d6f367a601f91a1ff5d7a4aa62cebc
refs/heads/master
2023-02-03T05:36:44.147164
2020-12-27T13:14:42
2020-12-27T13:14:42
259,830,488
0
0
null
null
null
null
UTF-8
Python
false
false
478
py
import urllib.request as req import json import csv ur='https://www.twse.com.tw/exchangeReport/BFT41U?response=json&date=&selectType=&_=1589434864462' with req.urlopen(ur) as qq: ioi=json.load(qq) for line in ioi['data']: print(line) fn='jump.csv' with open (fn,'w',newline='') as file: wri=csv.writer(file) wri.writerow(ioi['title']) wri.writerow(ioi['fields']) for line in ioi['data']: wri.writerow(line)
02a853983184d76df5f7624d38ae6489cfe08416
472a9b3fc58344d0f4b6fe8f01ac94fc8570a531
/src/B/GAN/gan.py
d9bf36aea02ad8f3b658ca3409e4c076fd81af8d
[]
no_license
yooq/tensorflow_test
70e21c0a7dcbf8b4f16e86201a61c2f454f1726c
015917a975b173462e96da4e8eec49a2f425d91f
refs/heads/master
2022-12-31T06:35:41.934962
2020-10-16T08:51:49
2020-10-16T08:51:49
277,729,486
1
0
null
null
null
null
UTF-8
Python
false
false
2,148
py
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers class Generator(keras.Model): def __init__(self): super(Generator, self).__init__() # z: [b, 100] => [b, 3*3*512] => [b, 3, 3, 512] => [b, 64, 64, 3] self.fc = layers.Dense(3*3*512) self.conv1 = layers.Conv2DTranspose(256, 3, 3, 'valid') self.bn1 = layers.BatchNormalization() self.conv2 = layers.Conv2DTranspose(128, 5, 2, 'valid') self.bn2 = layers.BatchNormalization() self.conv3 = layers.Conv2DTranspose(3, 4, 3, 'valid') def call(self, inputs, training=None): # [z, 100] => [z, 3*3*512] x = self.fc(inputs) x = tf.reshape(x, [-1, 3, 3, 512]) x = tf.nn.leaky_relu(x) # x = tf.nn.leaky_relu(self.bn1(self.conv1(x), training=training)) x = tf.nn.leaky_relu(self.bn2(self.conv2(x), training=training)) x = self.conv3(x) x = tf.tanh(x) return x class Discriminator(keras.Model): def __init__(self): super(Discriminator, self).__init__() # [b, 64, 64, 3] => [b, 1] self.conv1 = layers.Conv2D(64, 5, 3, 'valid') self.conv2 = layers.Conv2D(128, 5, 3, 'valid') self.bn2 = layers.BatchNormalization() self.conv3 = layers.Conv2D(256, 5, 3, 'valid') self.bn3 = layers.BatchNormalization() # [b, h, w ,c] => [b, -1] self.flatten = layers.Flatten() self.fc = layers.Dense(1) def call(self, inputs, training=None): x = tf.nn.leaky_relu(self.conv1(inputs)) x = tf.nn.leaky_relu(self.bn2(self.conv2(x), training=training)) x = tf.nn.leaky_relu(self.bn3(self.conv3(x), training=training)) # [b, h, w, c] => [b, -1] x = self.flatten(x) # [b, -1] => [b, 1] logits = self.fc(x) return logits def main(): d = Discriminator() g = Generator() x = tf.random.normal([2, 64, 64, 3]) z = tf.random.normal([2, 100]) prob = d(x) print(prob) x_hat = g(z) print(x_hat.shape) if __name__ == '__main__': main()
d43c5ad6b55154421ba862c68aa5ce52c930a00d
0144d5bfcc2f9af5a2eecae9bb763f8154e84134
/app/models.py
f06a5ce2b44b062517a641582835ac6d77fc0f17
[]
no_license
tund-hcmue/fl-myblog
57f09466a104547c0db443c7102c1e16fcd67452
2a4d2ea6a71668516d1228e32678386559e3acc5
refs/heads/master
2023-03-08T15:47:34.191874
2021-02-05T02:15:20
2021-02-05T02:15:20
333,739,177
0
0
null
null
null
null
UTF-8
Python
false
false
3,163
py
from app import db, login,app from datetime import datetime from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin from hashlib import md5 import jwt from time import time followers = db.Table('followers', db.Column('follower_id', db.Integer, db.ForeignKey('user.id')), db.Column('followed_id', db.Integer, db.ForeignKey('user.id')) ) class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) password_hash = db.Column(db.String(128)) posts = db.relationship('Post', backref='author', lazy='dynamic') about_me = db.Column(db.String(140)) last_seen = db.Column(db.DateTime, default=datetime.utcnow) followed = db.relationship( 'User', secondary=followers, primaryjoin=(followers.c.follower_id==id), secondaryjoin=(followers.c.followed_id==id), backref=db.backref('followers', lazy='dynamic'), lazy='dynamic' ) def __repr__(self): return '<User {}>'.format(self.username) def set_password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password) def avatar(self, size): digest = md5(self.email.lower().encode('utf-8')).hexdigest() return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format( digest, size) def follow(self, user): if not self.is_following(user): self.followed.append(user) def unfollow(self, user): if self.is_following(user): self.followed.remove(user) def is_following(self, user): return self.followed.filter( followers.c.followed_id == user.id).count() > 0 def followed_posts(self): return Post.query.join( followers, (followers.c.followed_id == Post.user_id)).filter( followers.c.follower_id == self.id) own = Post.query.filter_by(user_id=self.id) return followed.union(own).order_by( Post.timestamp.desc() ) def get_reset_password_token(self, expires_in=600): return jwt.encode( {'reset_password': self.id, 'exp': time() + expires_in}, app.config['SECRET_KEY'], algorithm='HS256') @staticmethod def verify_reset_password_token(token): try: id = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])['reset_password'] except: return return User.query.get(id) @login.user_loader def Load_user(id): return User.query.get(int(id)) class Post(db.Model): id = db.Column(db.Integer, primary_key=True) body = db.Column(db.String(140)) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __repr__(self): return '<Post {}>'.format(self.body)
ca09b4be23b0d9780a7658b3ccc0b0a718ebe1af
92162bd75bf7721c3c9a9789ff1d7001b7a93a7b
/Weather.py
5acff82a4dec916a2598c73475e6d1f0d56c9fe0
[]
no_license
serebrich/Telegram-Bot-travel-
7569365fbd554aef2a3e8f3de792c2ed524ca045
1aa2a0658c11a9c1abf52dba393e567767607561
refs/heads/master
2022-12-19T05:54:17.593689
2020-09-28T17:55:05
2020-09-28T17:55:05
299,387,634
0
0
null
null
null
null
UTF-8
Python
false
false
421
py
import requests import datetime def weather(): data = requests.get('http://api.openweathermap.org/data/2.5/weather?q=Kyiv&appid=e6125469fdc9299b59d07b130ac1b38e') description = data.json()['weather'][0]['description'] celcius = round(data.json()['main']['temp'] - 273.15, 1) return 'Today is {}\n\n\n{}\nTemp {}°C'.format(datetime.date.today().strftime("%A %d"), description.upper(), celcius)
836c36c00cd3e452e9505c7fbed11ff09b7d6602
4222d388849d1769939e2164a82dc69f0432dd10
/mysite/settings.py
ffe89f2dba54631286a766e22373d0afe032cb52
[]
no_license
Kirsten29/my-first-blog
1d708514b9fbb35a7d4b7f71eb6e06a711b7e2f1
5021b76ce60a7156fc7ce3a7954a1838e494c230
refs/heads/master
2020-09-02T06:14:34.455761
2020-02-21T21:24:46
2020-02-21T21:24:46
219,153,001
1
0
null
null
null
null
UTF-8
Python
false
false
3,211
py
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.2.6. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'mv!16w3r)&#65r1a1x$otp%-9%r%s^foxf=!ra6af45zdgf0h3' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', '.pythonanywhere.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog.apps.BlogConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'nl-nl' TIME_ZONE = 'Europe/Amsterdam' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static')
6f90c7577b150bcc6dd5ed8bfcdd50072771b61c
f50f1aa1f8f139d546db3230a1cb1f53043fd9e6
/network/connection/rfkill/actions.py
5bad0b2e48b47475b826255fc28b1405fbb1b8fc
[]
no_license
pars-linux/corporate2
7887961d1552d39bc3b0bef4a60fd3413d9b82bb
14d1eacfc824fb8d0bff8173e7ac06b36b88d10d
refs/heads/master
2020-05-26T15:02:12.005654
2017-02-27T03:07:14
2017-02-27T03:07:14
82,476,084
4
0
null
null
null
null
UTF-8
Python
false
false
514
py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2009-2010 TUBITAK/UEKAE # Licensed under the GNU General Public License, version 2. # See the file http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt from pisi.actionsapi import pisitools from pisi.actionsapi import autotools from pisi.actionsapi import get def build(): autotools.make("CC=%s CFLAGS='%s'" % (get.CC(), get.CFLAGS())) def install(): autotools.rawInstall("DESTDIR=%s" % get.installDIR()) pisitools.dodoc("README", "COPYING")
1908c93ff6adac1664998b245835adecb683b3f7
002307ff9d548b5d6914d792b51b32fa2fa8aef2
/edgeDilate.py
29b5f4f5d05373aef91e5ceab9a4a2369102b3a0
[ "MIT" ]
permissive
YellowPaint/Cartoon-Style-Transfer
d0a430a852fcc6bd81e7b0de4dadb9e446feed09
b20dc1ebc98a1ebc245935274510b06b1b68e895
refs/heads/master
2023-01-11T13:31:13.482287
2020-11-19T07:12:23
2020-11-19T07:12:23
314,115,273
0
0
null
null
null
null
UTF-8
Python
false
false
3,031
py
import cv2 as cv import math import numpy as np import os def edge_detect(image): blurred = cv.GaussianBlur(image, (3, 3), 0) gray = cv.cvtColor(blurred, cv.COLOR_RGB2GRAY) edge_output = cv.Canny(gray, 50, 100) return edge_output def edge_dilate(image,edge_output): image_dilate = image; for col in range(2,255): for raw in range(2,255): if edge_output[col,raw] == 255: if(edge_output[col-1,raw-1] != 255): image_dilate[col-1,raw-1,:] = image[col,raw,:] if(edge_output[col+1,raw-1] != 255): image_dilate[col+1,raw-1,:] = image[col,raw,:] if(edge_output[col-1,raw+1] != 255): image_dilate[col-1,raw+1,:] = image[col,raw,:] if(edge_output[col+1,raw+1] != 255): image_dilate[col+1,raw+1,:] = image[col,raw,:] return image_dilate class MyGaussianBlur(): #initization def __init__(self, radius=1, sigema=1.5): self.radius=radius self.sigema=sigema #the calculation of Gauss def calc(self,x,y): res1=1/(2*math.pi*self.sigema*self.sigema) res2=math.exp(-(x*x+y*y)/(2*self.sigema*self.sigema)) return res1*res2 #the Gauss module def template(self): sideLength=self.radius*2+1 result = np.zeros((sideLength, sideLength)) for i in range(sideLength): for j in range(sideLength): result[i,j]=self.calc(i-self.radius, j-self.radius) all=result.sum() return result/all #the filter function def filter(self, image, edge_output, template): height = image.shape[0] width = image.shape[1] imageEdgeSmooth = image for i in range(self.radius, height-self.radius): for j in range(self.radius, width-self.radius): if(edge_output[i,j] == 255 or edge_output[i-1,j-1] == 255 or edge_output[i-1,j+1] == 255 or edge_output[i+1,j-1] == 255 or edge_output[i+1,j+1] == 255): for k in range(0,3): t = image[i-self.radius:i+self.radius+1, j-self.radius:j+self.radius+1,k] a = np.multiply(t, template) imageEdgeSmooth[i,j,k] = a.sum() return imageEdgeSmooth GBlur=MyGaussianBlur(radius=2, sigema=1.5) temp=GBlur.template() file_dir = './data/train/Cartoon/' if not os.path.exists('./data/train/Cartoon_blur/'): os.makedirs('./data/train/Cartoon_blur/') for _, _,files in os.walk(file_dir): #read images for i in range(0,len(files)): path = file_dir + files[i] src = cv.imread(path) edge_output = edge_detect(src) image_dilate = edge_dilate(src,edge_output) image_edgeBlur=GBlur.filter(image_dilate, edge_output, temp) print("\r",i+1,"/",len(files),end = "") savePath = './data/train/Cartoon_blur/' + str(i).zfill(4) + '.jpg' cv.imwrite(savePath, image_edgeBlur)
5d2980203c637c3ef1694e88a48a5742d1163ee1
1372e9667b953207eb883fc641340f835d6ab70b
/dialoGPT.py
c58466d2479d6f650d70d0615cf1a71f97f8ba7b
[ "MIT" ]
permissive
Awesome12-arch/Conversational-AI_Chatbot
97a65ede22a65053dec564b9afcf9a3242fcf3e3
977531526cfc45cc25e84375e5ff2d648ee9e644
refs/heads/main
2023-04-23T22:14:35.119941
2021-05-17T12:17:17
2021-05-17T12:17:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,739
py
# -*- coding: utf-8 -*- """DialoGPT.ipynb Automatically generated by Colaboratory. """ # !pip install transformers from transformers import AutoModelForCausalLM, AutoTokenizer import torch # model_name = "microsoft/DialoGPT-large" model_name = "microsoft/DialoGPT-medium" # model_name = "microsoft/DialoGPT-small" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained(model_name) print("====Greedy search chat====") # chatting 5 times with greedy search for step in range(5): # take user input text = input(">> You:") # encode the input and add end of string token input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt") # concatenate new user input with chat history (if there is) bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids # generate a bot response chat_history_ids = model.generate( bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id, ) #print the output output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True) print(f"DialoGPT: {output}") print("====Beam search chat====") # chatting 5 times with beam search for step in range(5): # take user input text = input(">> You:") # encode the input and add end of string token input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt") # concatenate new user input with chat history (if there is) bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids # generate a bot response chat_history_ids = model.generate( bot_input_ids, max_length=1000, num_beams=3, early_stopping=True, pad_token_id=tokenizer.eos_token_id ) #print the output output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True) print(f"DialoGPT: {output}") print("====Sampling chat====") # chatting 5 times with sampling for step in range(5): # take user input text = input(">> You:") # encode the input and add end of string token input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt") # concatenate new user input with chat history (if there is) bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids # generate a bot response chat_history_ids = model.generate( bot_input_ids, max_length=1000, do_sample=True, top_k=0, pad_token_id=tokenizer.eos_token_id ) #print the output output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True) print(f"DialoGPT: {output}") print("====Sampling chat with tweaking temperature====") # chatting 5 times with sampling & tweaking temperature for step in range(5): # take user input text = input(">> You:") # encode the input and add end of string token input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt") # concatenate new user input with chat history (if there is) bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids # generate a bot response chat_history_ids = model.generate( bot_input_ids, max_length=1000, do_sample=True, top_k=0, temperature=0.75, pad_token_id=tokenizer.eos_token_id ) #print the output output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True) print(f"DialoGPT: {output}") print("====Top-K sampling chat with tweaking temperature====") # chatting 5 times with Top K sampling & tweaking temperature for step in range(5): # take user input text = input(">> You:") # encode the input and add end of string token input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt") # concatenate new user input with chat history (if there is) bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids # generate a bot response chat_history_ids = model.generate( bot_input_ids, max_length=1000, do_sample=True, top_k=100, temperature=0.75, pad_token_id=tokenizer.eos_token_id ) #print the output output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True) print(f"DialoGPT: {output}") print("====Nucleus sampling (top-p) chat with tweaking temperature====") # chatting 5 times with nucleus sampling & tweaking temperature for step in range(5): # take user input text = input(">> You:") # encode the input and add end of string token input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt") # concatenate new user input with chat history (if there is) bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids # generate a bot response chat_history_ids = model.generate( bot_input_ids, max_length=1000, do_sample=True, top_p=0.95, top_k=0, temperature=0.75, pad_token_id=tokenizer.eos_token_id ) #print the output output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True) print(f"DialoGPT: {output}") print("====chatting 5 times with nucleus & top-k sampling & tweaking temperature & multiple sentences====") # chatting 5 times with nucleus & top-k sampling & tweaking temperature & multiple # sentences for step in range(5): # take user input text = input(">> You:") # encode the input and add end of string token input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt") # concatenate new user input with chat history (if there is) bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids # generate a bot response chat_history_ids_list = model.generate( bot_input_ids, max_length=1000, do_sample=True, top_p=0.95, top_k=50, temperature=0.75, num_return_sequences=5, pad_token_id=tokenizer.eos_token_id ) #print the outputs for i in range(len(chat_history_ids_list)): output = tokenizer.decode(chat_history_ids_list[i][bot_input_ids.shape[-1]:], skip_special_tokens=True) print(f"DialoGPT {i}: {output}") choice_index = int(input("Choose the response you want for the next input: ")) chat_history_ids = torch.unsqueeze(chat_history_ids_list[choice_index], dim=0)
36a6cb060598aabcc7b3957417de8713e2e07f71
2fb896c6dc62bcdc0f1ea475a1f5bb12f6a25d10
/test.py
f20e5cc0baf28e45bb979f0d016e0177ec16fcda
[ "MIT" ]
permissive
Croip3/3d_packing
53aeb4a896734d67f2ba03215a14370d7204301b
57be9ca0d0e7b5264cbc6200cfb45e5ccaedd9d7
refs/heads/main
2023-03-23T06:51:43.431130
2021-03-13T18:49:41
2021-03-13T18:49:41
347,396,064
1
0
null
null
null
null
UTF-8
Python
false
false
229
py
import requests url = 'http://localhost:3000/' with open("test_request.json", "r") as f: payload = f.read() headers = {'content-type': 'application/json'} r = requests.post(url, data=payload, headers=headers) print(r.json())
ff57e51d7d8c7900f41850b0491bf04745cd8a60
921c3abdb2478b15eb38667e50114b563780dffa
/automationpractice/WebDriverWaitConcepts.py
7f2900a074e09d2d32ded948cd9536bbee3343e6
[]
no_license
maheshkafle/Selenium-Concepts
0c126ca11a2253c10a96b70003f880ebdffe929e
8ad31d4bd4c0d158991e9c6897498fe783773170
refs/heads/main
2023-07-06T15:37:00.417338
2021-07-11T12:23:34
2021-07-11T12:23:34
384,937,572
0
0
null
null
null
null
UTF-8
Python
false
false
754
py
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as ec from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().install()) driver.get('https://the-internet.herokuapp.com/login') driver.maximize_window() wait = WebDriverWait(driver, 20) wait.until(ec.title_contains('Internet')) print(driver.title) email_id = wait.until(ec.presence_of_element_located((By.ID,'username'))) email_id.send_keys('tomsmith') password = driver.find_element(By.ID,'password') password.send_keys('SuperSecretPassword!') login = driver.find_element(By.CLASS_NAME,'radius') login.click()
f79e101889ab19e2f579de301543f22f9a29a160
2de1aaa4d9bde03e21601bfeddf7e85863b0d54a
/Python/plus/Process/process_class.py
4e8bb9548a4a90ef8566c47da963f2aaa21837db
[]
no_license
jasondzy/Python
d0a0ffad8aaac1f75d9e7c5ecd5cc9c33bd712ea
9fe9cf23f7defa3581e7bcfe4cf8ec6a830b6cd7
refs/heads/master
2021-01-01T18:46:00.739387
2018-02-11T14:59:26
2018-02-11T14:59:26
98,430,631
0
0
null
null
null
null
UTF-8
Python
false
false
1,111
py
from multiprocessing import Process import time class New_process(Process):#这里定义了一个新的Newprocess类,这个类继承了Process这个父类,即可通过这个新建的类来创建一个自定义的进程 def __init__(self,value): Process.__init__(self)#初始化调用了父类中的init函数,同时也加入了自定义的value的变量 self.value = value def run(self):#定义了一个run方法,切记:此处定义的run方法是对父类Process中的run方法的一种重写,接下来的父类中的start方法启用的是这里重写了的run方法,这里也实现了一个不用通过tartget=xxx的方法传入一个方法 while True: print('----son-----') time.sleep(1) son = New_process(1)#用新创建的类来创建一个子进程,里边传入的参数并没有实际的作用 son.start()#调用start方法,这个start方法是在父类中定义的,但是这个start的方法实际调用的是run方法,由于在新建的类中重写了run方法所以最终调用的是新创建的类中的run方法 while True: print('---parent----') time.sleep(1)
9c7e98340e2d2c04f3abc411926e9aaaac820ac3
3332147f4b94dead946368d700af4ff9f9d1ccfb
/myjob/scrapy_item/innocom/innocom/debug.py
1558b21757b90b87c379eb87b5caec0dced33072
[]
no_license
zsl1105/work
ee76cb2b9af2711196e4605e10b50ffe17abb5da
e468f68652a653864f4629f50e267ab65c633c6a
refs/heads/master
2020-08-27T04:35:14.330657
2020-04-14T03:19:27
2020-04-14T03:19:27
217,186,491
0
0
null
null
null
null
UTF-8
Python
false
false
82
py
from scrapy import cmdline cmdline.execute(['scrapy', 'crawl', 'innocomspider'])
a3f1dbdb0b54fdceca459084b874b4fa5fa2ffd6
70840b7cc0aed28ff4ad4c865d2541f466cdcd18
/hashthat/hashing/views.py
360711ae79f19b5de791e5d7ceb47f6c8fa996d3
[]
no_license
kimebmen/Test-Driven-Development
2a49d4bb96f28e7f31aa6940c9f59d4aa98669b5
2b27b9467531251c6e47ba37aaf41698401f98f2
refs/heads/master
2022-11-22T12:38:03.656746
2020-07-19T22:40:18
2020-07-19T22:40:18
280,962,272
0
0
null
null
null
null
UTF-8
Python
false
false
909
py
from django.shortcuts import render, redirect from .forms import HashForm from .models import Hash import hashlib from django.http import JsonResponse def home(request): if request.method == 'POST': filled_form = HashForm(request.POST) if filled_form.is_valid(): text = filled_form.cleaned_data['text'] text_hash = hashlib.sha256(text.encode('utf-8')).hexdigest() try: Hash.objects.get(hash=text_hash) except Hash.DoesNotExist: hash = Hash() hash.text = text hash.hash = text_hash hash.save() return redirect('hash', hash=text_hash) form = HashForm() return render(request, 'hashing/home.html', {'form':form}) def hash(request, hash): hash = Hash.objects.get(hash=hash) return render(request, 'hashing/hash.html', {'hash':hash}) def quickhash(request): text = request.GET['text'] return JsonResponse({'hash':hashlib.sha256(text.encode('utf-8')).hexdigest()})
7d6b73c0cd67996ed65f9c40f741c96abd18095c
79e6161d09be67655d3a6beb6c5d63a1392cb079
/test_udp_server.py
c62dc825dfae63a6c62be5e38aaeb0bb2c861f15
[]
no_license
antonvh/RobotCameraGPS
69fc07d788dcc53a71bfbb7c0b8c73443fb3599e
853156a6847f34c2c3ae9bcdc1ffbf4919f6087e
refs/heads/master
2021-01-15T19:06:33.878830
2017-12-23T15:00:50
2017-12-23T15:00:50
99,808,808
0
0
null
null
null
null
UTF-8
Python
false
false
1,451
py
import socket import time try: import cPickle as pickle except: import pickle # Create an UDP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) PORT = 50008 # Bind the socket to the broadcast port server_address = ('255.255.255.255', PORT) # Data structure for robots with dummy data robot_broadcast_data = {'states': {1: [(500, 500), # middle of triangle base (520, 520)], # point of traingle 2: [(400, 400), # middle of triangle base (420, 420)] # point of traingle }, 'balls': [(23, 24), # centroids of balls on camera (1800, 900)], 'settings': {'sight_range': 100, 'dump_location': (20, 20)} } if __name__ == '__main__': while True: time.sleep(0.033) data = pickle.dumps(robot_broadcast_data) if data: try: sent = sock.sendto(data, server_address) time.sleep(0.025) except OSError as exc: if exc.errno == 55: time.sleep(0.1) else: raise
799bf438eda7a4ed0f8881dac88297ae616de6cc
58f68e1e21a437cfa332b6e84c098233a36d36e4
/GestionPedidos/migrations/0003_auto_20210110_2159.py
cacaa8ace3e0489f4beb5d31d1414480826cf96f
[]
no_license
Aderlin-Cruz/Tienda-Online-en-Django-con-Pyhton
d0a97cb2036a9dfe5ec12d919f5f65d38279f8fa
1eaa4593f0945a79cd7775affce6b9f2b303ddec
refs/heads/main
2023-03-02T05:25:43.876877
2021-02-08T23:18:20
2021-02-08T23:18:20
335,744,161
1
0
null
null
null
null
UTF-8
Python
false
false
432
py
# Generated by Django 3.1.5 on 2021-01-11 03:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('GestionPedidos', '0002_auto_20210110_2137'), ] operations = [ migrations.AlterField( model_name='clientes', name='direccion', field=models.CharField(max_length=50, verbose_name='Direccion Cliente'), ), ]
a5c1d5d239e5c78d0bf7a0d14fcc5bf984ccb671
75e36620cdcfcce1f5a13378d8c1814990a7c48f
/src/deadbyzombie/misc_lib.py
fc48044f00bd979214e41a037da4f5c7988d2471
[]
no_license
mkramlich/Dead_By_Zombie
aa916e164e075303badb4f6c1eb2869561a5ce24
a4c80276d90f88dde0ba965c167f016548b6ae57
refs/heads/master
2021-06-07T07:17:30.637950
2017-09-18T19:00:16
2017-09-18T19:00:16
13,845,377
3
1
null
null
null
null
UTF-8
Python
false
false
23,455
py
import datetime import math import random import time logfile = None cfg = {} currentTick = 0 debug_enabled = False #refactor away the currentTick and other ganymede-isms that shouldn't be here def init_logfile(): global logfile print 'init_logfile() called' logfile = file('log.txt','w') print 'logfile is now '+str(logfile) def log(msg): global logfile if 'preface_with_tick' in cfg and cfg['preface_with_tick']: msg = str(currentTick)+': '+msg logfile.write(msg) logfile.flush() def debug(msg): if debug_enabled: msg += '\n' print msg log(msg) def chance(num, denom): if num > 0 and denom > 0: return random.randrange(denom) < num else: return False def rand_range_signed(max_magnitude): v = random.randrange(max_magnitude+1) if v != 0 and random.randrange(2) == 0: v = -v return v def rand_diff(max_magnitude_x, max_magnitude_y): xd = rand_range_signed(max_magnitude_x) yd = rand_range_signed(max_magnitude_y) return (xd, yd) def rand_range(min, span): return min + random.randrange(span + 1) def rnd_in_range(min, max): return min + random.randrange(max - min + 1) def rnd_bool(): return random.randrange(2) == 0 def rand_success(chance): assert 0.0 <= chance <= 1.0, 'chance param %s must satisfy: 0.0 <= chance <= 1.0' % chance return random.random() <= chance def randex(array): return array[random.randrange(len(array))] def roundmoney(val): val = val * 100 val = int(val) val = val / 100 return val def read_file(filename): f = file(filename, 'r') s = f.read() f.close() return s def read_file_lines(filename): s = read_file(filename) return s.splitlines() def split_width(s, w): lns = [] i = 0 j = i + w while i < len(s): if j > len(s): j = len(s) ln = s[i:j] lns.append(ln) i = j j = i + w return lns def load_string_as_python_to_dict(stryng): gd = {} ld = {} exec stryng in gd, ld #debug('gd: ' + str(gd)) return ld def load_file_as_python_to_dict(filename): s = read_file(filename) ld = load_string_as_python_to_dict(s) debug('read this for '+filename+':') debug('ld: ' + str(ld)) return ld class HtmlColors: WHITE = '#FFFFFF' BLACK = '#000000' RED = '#FF0000' GREEN = '#00FF00' BLUE = '#0000FF' YELLOW = '#FFFF00' UNKNOWN = '#00FFFF' # magenta & cyan; i forget which is which UNKNOWN2 = '#FF00FF' # see comment for UNKNOWN PINK = '#DD00DD' DARKRED = '#DD0000' DARKGREEN = '#00DD00' DARKDARKGREEN = '#00AA00' DARKYELLOW = '#DDDD00' DARKDARKYELLOW = '#AAAA00' DARKDARKDARKYELLOW = '#888800' BROWN = DARKYELLOW ORANGE = DARKYELLOW GRAY = '#DDDDDD' DARKGRAY = '#AAAAAA' def dist(x1,y1, x2,y2): xd = abs(x2 - x1) yd = abs(y2 - y1) tmp = (xd * xd) + (yd * yd) d = math.sqrt(tmp) d = int(d) return d def dist2(x1,y1, x2,y2): xd = abs(x2 - x1) yd = abs(y2 - y1) if xd < yd: return xd else: return yd def dist3(x1,y1, x2,y2): #TODO this is a FIXED re-impl of dist2 -- migrate apps off of using dist2 and instead onto dist3 (I'm pretty sure, but judge it on case by case basis) xd = abs(x2 - x1) yd = abs(y2 - y1) if xd > yd: return xd else: return yd class Groups: def __init__(self): self.groups = {} def add_to_group(self, thing, group_name): "method param 'group_name' can be a string name, or, a list of string names" gns = [] if isinstance(group_name, list): gns = group_name else: gns.append(group_name) for gn in gns: group = None if gn in self.groups: group = self.groups[gn] else: group = self.groups[gn] = [] if not thing in group: group.append(thing) #TODO post event? def remove_from_group(self, thing, group_name): group = self.groups[group_name] if thing in group: group.remove(thing) #TODO post event? else: #TODO fix me: following thnig.name only works for sprites not classes!: print 'remove_from_group(): thing '+str(thing)+' ('+str(thing)+') not in group '+str(group_name)+" so can't remove" def remove_from_all_groups(self, thing): for gn in self.groups: self.remove_from_group(thing, gn) def clear_group(self, group_name): self.groups[group_name] = [] #TODO post event? def clear_all_groups(self): for gn in self.groups: self.groups[gn] = [] def get_group(self, group_name): group = None if group_name in self.groups: group = self.groups[group_name] else: group = [] self.groups[group_name] = group return list(group) def in_group(self, thing, group_name): if group_name in self.groups: return thing in self.groups[group_name] else: return False class StopWatch: def __init__(self, msgpre='', msgsuf=''): # I'm aware of DRY violation w/start() but makes a little more accurate self.msgpre = msgpre self.msgsuf = msgsuf self.cputime_stopped = None self.walltime_stopped = None self.cputime_started = time.clock() self.walltime_started = time.time() def start(self, msgpre='', msgsuf=''): self.msgpre = msgpre self.msgsuf = msgsuf self.cputime_startedprev = self.cputime_started self.cputime_stoppedprev = self.cputime_stopped self.walltime_startedprev = self.walltime_started self.walltime_stoppedprev = self.walltime_stopped self.cputime_started = time.clock() self.walltime_started = time.time() def stop(self, msgpre=None, msgsuf=None): self.cputime_stopped = time.clock() self.walltime_stopped = time.time() cpudiff = self.cputime_stopped - self.cputime_started walldiff = self.walltime_stopped - self.walltime_started if msgpre is None: msgpre = self.msgpre if msgsuf is None: msgsuf = self.msgsuf return msgpre + float_secs_to_str_ms(cpudiff) + ' cpu, ' + float_secs_to_str_ms(walldiff) + ' wall' + msgsuf def float_secs_to_str_ms(timediff): ms = int(timediff * float(1000)) return str(ms) + ' ms' def getattr_withlazyinit(obj, attrname, initvalue): if not hasattr(obj,attrname): setattr(obj,attrname,initvalue) return getattr(obj,attrname) def sentence_capitalize(s): s2 = s if len(s) > 0: s2 = s[0:1].upper() if len(s) > 1: s2 += s[1:] return s2 def sentence(s): if len(s) > 0 and (not s[len(s)-1] in ('?','!','.','"',"'")): s += '.' return sentence_capitalize(s) def encode_whitespace_inside_quotes(txt, quotechar="'"): #TODO write the reverse of this; a decode function #TODO also support " #TODO make several passes on txt, each time trying a different char in the string tuple: ", ' #TODO allow caller to give param specifying a list of valid quote delimiters #quotepairs = [] txt2 = '' s = txt while True: i = s.find(quotechar) if i != -1: if (i + 1) >= len(s): txt2 += s break j = s.find(quotechar,i+1) if j != -1: #quotepairs.append( (i,j,) ) chunk_in_quotes = s[i:j+1] chunk = chunk_in_quotes #TODO should also encode any '_' found in chunk by like: #chunk = chunk.replace(' ', '\\_') chunk = chunk.replace(' ', '_') chunk = chunk.replace(quotechar,'') encoded_chunk = chunk txt2 += s[:i] txt2 += encoded_chunk if (j+1) >= len(s): break else: s = s[j+1:] else: txt2 += s break else: txt2 += s break return txt2 VOWELS = ('a','e','i','o','u') vowels2 = list(VOWELS) # this ensures we have the uppercase and lowercase versions of each vowel: for v in VOWELS: vowels2.append(v.upper()) VOWELS = vowels2 def awordify(text): prefix = 'a' if len(text) > 0 and text[0] in VOWELS: prefix = 'an' return '%s %s' % (prefix, text) class TextPools: #TODO also have a function to claim/declaim def __init__(self): self.pools = {} def get_random_entry(self, poolname): pool = None try: pool = self.pools[poolname] except KeyError, e: print '\n\ncaught KeyError: %s' % e print 'pools dump: %s\n\n' % self.pools raise e return random.choice(pool) def define_pools(self, new_defs_dict): for k in new_defs_dict: items = new_defs_dict[k] pool = [] pool.extend(items) self.pools[k] = pool #self.pools = dict(new_defs_dict) def add_to_pool(self, poolname, newentry): pool = self.pools[poolname] if isinstance(newentry, type( [] )) or isinstance(newentry, type( () )): pool.extend(newentry) else: pool.append(newentry) def add_to_pools(self, extra_defs_dict): for k in extra_defs_dict: pool = [] if k in self.pools: pool = self.pools[k] extra_items = extra_defs_dict[k] pool.extend(extra_items) self.pools[k] = pool def report(self, keydelim=': ', itemdelim=', ', pooldelim='\n'): s = '' names = list(self.pools.keys()) names.sort() for k in names: items = self.pools[k] itemblurb = itemdelim.join(items) s += k + keydelim + itemblurb + pooldelim return s def assertNotNone(name, val): assert val is not None, '%s is None' % name def stradd(s, delim, str2append): if s is None: s = '' elif len(str(s)) > 0: s += str(delim) s += str(str2append) return s def isinstance_any(obj, classes): for cl in classes: if isinstance(obj,cl): return True else: return False def isinstance_all(obj, classes): for cl in classes: if not isinstance(obj,cl): return False else: return True def isinstance_all_not(obj, classes): for cl in classes: if isinstance(obj,cl): return False else: return True def isinstance_any_not(obj, classes): for cl in classes: if not isinstance(obj,cl): return True else: return False def randrangewith(max_inclusive): return random.randrange(max_inclusive+1) def gender2heshe(gender): if gender == 'male': return 'he' elif gender == 'female': return 'she' else: return 'it' def gender2himher(gender): if gender == 'male': return 'him' elif gender == 'female': return 'her' else: return 'it' def gender2hishers(gender): if gender == 'male': return 'his' elif gender == 'female': return 'hers' else: return "it's" def app(lst, item): #TODO bad name since also abbrev for application lst.append(item) def assertNotDirectInstantiate(selfobj, klass): assert selfobj.__class__ is not klass, 'cannot instantiate %s, only a subclass, because %s is only a virtual base class (or consider it an interface)' % (klass.__name__, klass.__name__) def secs_float_diff_to_summary_str(diff): diffstr = None if diff < 1: diffstr = '%s secs' % diff elif diff < 60: diffstr = '%s secs' % int(diff) elif diff < 3600: diffstr = '%s mins' % int(diff/60) elif diff < 3600 * 24: diffstr = '%s hours' % int(diff/3600) else: diffstr = '%s days' % int(diff/(3600*24)) #td = datetime.timedelta(seconds=diff) #if td.seconds < 60: # diffstr = '%s secs' % td.seconds #elif td.days < 1: # diffstr = '%s mins' % (td.seconds / 60) #else: # diffstr = '%s days' % td.days return diffstr #TODO upgrade to Table class so i can reuse an instance, persisting table format preferences across multiple applications of the instance to diff data sets def table(data, header=True, delim='\n', cellspacing=None): #data[row][col]; 0th row contains header text # data is a list of lists; the left-side/outer list contains the rows; the right-side lists contain the per-column values for that row tableattribs = '' if cellspacing is not None: tableattribs += ' cellspacing="%s"' % cellspacing s = '<table%s>' % tableattribs + delim if header: headerrow = data[0] s += '<tr>' + delim for colvalue in headerrow: s += '<th> '+str(colvalue)+' </th>' + delim s += '</tr>' + delim for row in data: #TODO data[1:] ? if header and row is headerrow: continue # skip header row since already done above s += '<tr>' + delim for colvalue in row: tdattribs = '' if isinstance(colvalue,type({})): hash = colvalue colvalue = hash[table.valuekey]#'_value'] for k in hash: if k == table.valuekey: continue tdattribs += ' ' + str(k) + '="' + str(hash[k]) + '"' #else: #it's just a value object (usually a string or number) s += '<td'+tdattribs+'> ' + str(colvalue) + ' </td>' + delim s += '</tr>' + delim s += '</table>' + delim return s table.valuekey = '_value' def and_many(vals): for v in vals: if not v: return False else: return True class Klass: pass #NOTE: USED BY isclass(c) function; yes, feels hacky, but I don't know of a way in Python to determine that with a built-in mechanism. def isclass(c): return type(c) is type(Klass) def in_range(v, min, max): return v >= min and v <= max def get_object(obj_name, namespace=None, default=None): if namespace is None: namespace = globals() return (obj_name in namespace.keys() and namespace[obj_name]) or default def cycle_increment(i, seq): i = i + 1 if i >= len(seq): i = 0 return i def get_next_with_cycle(cur_item, seq): i = seq.index(cur_item) new_i = cycle_increment(i,seq) return seq[new_i] def fontcolorize(str, color): return '<font color="' + color + '">' + str + '</font>' def get_doc(obj, attrname): return getattr(obj,attrname).__doc__ def bare_class_name(klass): toks = klass.__name__.split('.') return toks[len(toks)-1] def tostr(obj): s = '' for a in dir(obj): if a.startswith('__'): continue attr = getattr(obj,a) if callable(attr): continue ss = '%s=%s' % (a, attr) s = stradd(s,', ',ss) return s def play_synthesized_speech_on_mac(text): commands.getoutput('/usr/bin/say '+text) def dump(obj): for a in dir(obj): v = getattr(obj,a) if not callable(v): print a+' = '+str(v) def read_with_includes(filepath): basepath = '' if '/' in filepath: lastslashpos = filepath.rfind('/') basepath = filepath[:lastslashpos+1] lines = read_file_lines(filepath) if len(lines) < 1: return '' includeprefix = '#include ' lines2 = [] for line in lines: if line.startswith(includeprefix): rest = line[len(includeprefix):] filepath2include = basepath + rest #print 'would include: %s' % filepath2include body_from_include = read_with_includes(filepath2include) addlines = body_from_include.splitlines() lines2.extend(addlines) else: lines2.append(line) return '\n'.join(lines2) def load_config_for_env(confdir='conf/', topfname='config', envkey='env', envfnamesuffix='.cfg'): fname = confdir + topfname topcfg = load_file_as_python_to_dict(fname) #print fname + ':\n' + str(topcfg) env = topcfg[envkey] fname = confdir + env + envfnamesuffix s = read_with_includes(fname) #envcfg = load_file_as_python_to_dict(fname) envcfg = load_string_as_python_to_dict(s) return env, envcfg def percent(val_float): return '%s%%' % (val_float * 100) def load_csv_file(filename): #TODO make it skip file lines begining with # - have opt param to enable/disable this feature, as well as to override what prefix to use instead of # #TODO option to silently ignore/skip blank lines (lines w/only whitespace) outlines = [] lines = read_file_lines(filename) for line in lines: line = line.lstrip().rstrip() tup = line.split(',') newtup = [] for v in tup: v = v.lstrip().rstrip() newtup.append(v) outlines.append(newtup) return outlines def commandcd(dir,cmd): return commands.getoutput('cd '+dir+'; '+cmd) def extract1stColAsList(lines): retval = [] for line in lines: words = line.split(' ') col1 = words[0] retval.append(col1) return retval def read_data(datagroupname): return read_file('data/'+datagroupname+'.txt') def read_data_lines(datagroupname): return read_file_lines('data/'+datagroupname+'.txt') def load_data_as_python_to_dict(datagroupname): fname = 'data/' + datagroupname + '.txt' return load_file_as_python_to_dict(fname) def get_keys_for_value(dicty, value): keys = [] for key in dicty: if dicty[key] == value: keys.append(key) return keys class State(object): def __init__(self): pass def enter(self, params={}): pass def exit(self): pass def imagefn(img_fname_base): return 'images/' + img_fname_base def get1stKeyWithValue(map,value): for i in map.items(): (k,v) = i if v == value: return k return None def equals_any(val, seq): for i in seq: if val == i: return True return False def import_as_dict(modulename): mod = __import__(modulename) dd = {} for k in dir(mod): if k.startswith('_'): continue dd[k] = getattr(mod,k) return dd def strip_comment_lines(lines): return [ln for ln in lines if not ln.startswith('#')] def file2lines(filename): f = file(filename,'r') lines = f.readlines() f.close() return lines def rstriplines(stringlines): lines2 = [] for line in stringlines: line2 = line.rstrip() lines2.append(line2) return lines2 def safe_getattr_as_bool(o, attrname): if hasattr(o,attrname): return getattr(o,attrname) else: return False class LazyStrWrapper: def __init__(self, callee): self.callee = callee def __str__(self): return str(self.callee()) def lazy_str_eval(callee): #TODO add support for curried callables (having call params frozen with the callable reference) return LazyStrWrapper(callee) lazy_str_eval.__doc__ = ''' # usage in application: def expensive_fn(): # some cpu/memory/latency-expensive task # that we only want to do if it's truly needed to render a log msg logger.debug('some msg: %s', lazy_str_eval(expensive_fn)) # we're not at debug log level currently, therefore the above log msg will NOT be rendered, and expensive_fn will not be called...this is a perf improvement over the following case: logger.debug('some msg: %s', expensive_fn()) # which is what you would have to do if you JUST used the python logging facility "as designed" # since 'lazy_str_eval' is a verbose name to have everywhere you could alias it in your application to something like 'lstr' ''' def cap_to_len(seq, maxlen): if len(seq) > maxlen: seq = seq[:maxlen] return seq def getsafe(key, ddict, defaultval=''): if key in ddict: return ddict[key] else: return defaultval def is_item_in_seq_based_on_id(item, seq): for s in seq: if id(item) == id(s): return True else: return False def get_set_with_class_and_all_super_classes(klass, allset=None): if allset is None: allset = set() if klass not in allset: allset.add(klass) for cl in klass.__bases__: get_set_with_class_and_all_super_classes(cl,allset) return allset def nbsp(num_of_spaces): return '&nbsp;' * num_of_spaces def nameoffn(fn): globs = globals() for k,v in globs.items(): if v == fn: return k #TODO use 'is' instead of '==' return None #TODO instead throw ex? def countify(word,qty,trailingphrase=None): #TODO get specialwords data from db or file, and load only once at site startup into a cache, read from cache when using here s = '' if qty == 1: s += word else: specialwords = {'goose':'geese'} if word in specialwords: s += specialwords[word] else: s += word + 's' if trailingphrase != None: s += ' ' + trailingphrase return s def is_alnum(string): for c in string: if not c.isalnum(): return False return True def is_alnum_or_underscores(string): for c in string: if not c.isalnum() and c != '_': return False return True def strlist2str(strlist): return ''.join(strlist) def setattr_unless_attrval_not_none(obj, attrname, initvalue): if not hasattr(obj,attrname) or obj.attrname is None: setattr(obj,attrname,initvalue) def rnd_using_rpg_die_notation(s): # s must be a str in old RPG die roll notation like: # '1d6+2', '2d8', '9d1' or '0d1-1' (the last always yields -1, btw) # the letter 'd' can be upper or lower case # the modifier portion may be omitted, and must be either a '+' or '-' # this will parse that, generate a random number within the specified range s = s.lstrip().rstrip().lower() pre, post = s.split('d') dieqty = int(pre) diesidecount = None mod = None if post.count('+') > 0: diesidecount, mod = post.split('+') diesidecount = int(diesidecount) mod = int(mod) elif post.count('-') > 0: diesidecount, mod = post.split('-') diesidecount = int(diesidecount) mod = int(mod) * -1 else: diesidecount = int(post) mod = 0 val = 0 for roll in range(dieqty): val += 1 + random.randrange(diesidecount) val += mod return val #TODO write automated test suite for above function. Below is example code for human-readable tests. But should be prog assertions of correctness like unit tests # tests = ('1d6+2', '2d8', '9d1', '0d1-1') # for t in tests: # results = '' # for i in range(5): # results += str(lib.rnd_using_rpg_die_notation(t)) + ',' # self.feedback(t + ': ' + results) def sign(val): #TODO in std lib? and is used by this app? if float(val) == 0.0: return 1.0 else: return val / abs(val)
573203a09293bf705160fe3679230281477da313
a379f99513def3a4cebc095ca191243c5414d608
/test_sparse_field/__manifest__.py
2d9acc375f5dd353e572d3c0302a706a52519c8d
[]
no_license
florian-dacosta/sparse-field
47e81a0e0c3f71315ad374544c6f820daa5adef5
48d140f932a5a13a5cacde2a0f48532855fac729
refs/heads/master
2021-05-07T21:27:53.385436
2017-10-31T15:59:08
2017-10-31T17:20:10
109,017,813
0
0
null
null
null
null
UTF-8
Python
false
false
405
py
{ "name": "Test Sparse field", "version": "11.0.1.0.0", "category": "Uncategorized", "website": "https://akretion.com/", "author": "Akretion, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": [ "base_sparse_field_search", "stock", ], "data": [ 'stock_picking_view.xml' ] }
e96c34b5a2752d637a9630f5f8751d799f91d06d
3826f007cd4b018b8ae679397ca5cfd173f90b12
/medicamento/urls.py
784d29394c334d9e5bcd376ba352ce10ee0b5375
[]
no_license
crashorbo/consultorio
36695ec7a558b9d9a6c48fb43d7e2ca9652a9c76
ccdb06790bc70380a22d7731e667b022a87f908a
refs/heads/master
2023-08-27T16:38:49.976154
2021-10-25T04:05:39
2021-10-25T04:05:39
298,436,549
0
0
null
null
null
null
UTF-8
Python
false
false
865
py
from django.urls import path from django.conf.urls import url from django.contrib.auth.decorators import login_required from .views import AjaxListView, TableAsJSON, AjaxCrearView, AjaxEditarView, AjaxEliminarView, MedicamentoAutocomplete urlpatterns = [ url(r'^as_json/$',login_required(TableAsJSON.as_view()), name='table-as-json'), url(r'^medicamento-autocomplete/$', login_required(MedicamentoAutocomplete.as_view()), name='medicamento-autocomplete'), path('ajax-lista/', login_required(AjaxListView.as_view()), name='medicamento-ajax-lista'), path('ajax-registrar/', login_required(AjaxCrearView.as_view()), name='medicamento-ajax-registrar'), path('ajax-editar/<pk>', login_required(AjaxEditarView.as_view()), name='medicamento-ajax-editar'), path('ajax-eliminar', login_required(AjaxEliminarView.as_view()), name='medicamento-ajax-eliminar'), ]
80340e6ec345bd948e0f49145820524e5629dc42
26f6313772161851b3b28b32a4f8d255499b3974
/Python/ConvertBinaryNumberinaLinkedListtoInteger.py
5d29f321b243398b982ae634a6a2575a4f4f9b1c
[]
no_license
here0009/LeetCode
693e634a3096d929e5c842c5c5b989fa388e0fcd
f96a2273c6831a8035e1adacfa452f73c599ae16
refs/heads/master
2023-06-30T19:07:23.645941
2021-07-31T03:38:51
2021-07-31T03:38:51
266,287,834
1
0
null
null
null
null
UTF-8
Python
false
false
984
py
""" Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list. Example 1: Input: head = [1,0,1] Output: 5 Explanation: (101) in base 2 = (5) in base 10 Example 2: Input: head = [0] Output: 0 Example 3: Input: head = [1] Output: 1 Example 4: Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0] Output: 18880 Example 5: Input: head = [0,0] Output: 0 Constraints: The Linked List is not empty. Number of nodes will not exceed 30. Each node's value is either 0 or 1. """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def getDecimalValue(self, head) -> int: res_str = '' while head: res_str += str(head.val) head = head.next return int(res_str, 2)
6ddb7cad28e46a5304c0ca42fd98faef739aa48d
44449222a88f8254659655204def425653b75d06
/algo_and_data_structures/a3200-2015-algs/lab7/Kabanova/radixsort.py
4fa42953bd53484002534fddf7b38dee3e3dbe0a
[]
no_license
catr1ne55/ITMO_14_18
15fc5b991ffefa8dbe89aa23b4e2f70dcc45eef6
e3e6b619cf8613d8840bec3c2055e48a2b47c58b
refs/heads/master
2020-05-27T21:01:59.144029
2019-05-27T08:01:40
2019-05-27T08:01:40
188,788,822
0
0
null
null
null
null
UTF-8
Python
false
false
1,359
py
import sys import math __author__ = 'catherinekabanova' def simple_radix_sort(array): max_length = -1 for number in array: number_len = int(math.log10(number)) + 1 if number_len > max_length: max_length = number_len buckets = [[] for i in range(0, 10)] for digit in range(0, max_length): for number in array: buckets[(number // 10**digit) % 10].append(number) del array[:] for bucket in buckets: array.extend(bucket) del bucket[:] return array def radix_sort(array): positive_array = [] negative_array = [] for number in array: if number >= 0: positive_array.append(number) else: negative_array.append(abs(number)) if negative_array: negative_array = simple_radix_sort(negative_array) for i in range(len(negative_array)): negative_array[i] *= -1 negative_array.reverse() if positive_array: positive_array = simple_radix_sort(positive_array) return negative_array + positive_array if __name__ == '__main__': array_of_elements = [int(k) for k in sys.stdin.readline().split(' ')] radix_sort(array_of_elements) for i in range(0, len(array_of_elements)): sys.stdout.write(str(radix_sort(array_of_elements)[i]) + ' ')
4158694127a050d841b165f8bea5fbb2756f0578
e2b06285043d964a557c3b1905c32d8500b6fc98
/dev_blogs/python-projects/source/app1.py
d644ade7db6251d834a62c13fbc4ec104104579a
[]
no_license
yiqing95/py-space
15a17c3dc0b1c8978111704ce2c4380afc5705ec
f6e1695c5932688de26a797fd919e87b4098c5de
refs/heads/master
2021-01-10T01:05:50.478098
2015-10-16T23:14:06
2015-10-16T23:14:06
44,413,128
0
0
null
null
null
null
UTF-8
Python
false
false
283
py
__author__ = 'yiqing' # 语法 [variable] = [value] aString = 'I love spam' anotherString = 'I love spam' # 只是name 一种绑定 标签label aInt = 6 intAlias = aInt # 别名 # 是否相等 ? print( aString == anotherString ) print( anotherString is anotherString )
bef3d379f4e7d8670d0d5bd58585ef586efd94c5
611ba585ff34ddd3f49bfec52887c466bab7fa9b
/P19 2-4.py
ac9d7dfc463e970e1db86b2f446243f074a3b9af
[]
no_license
Eamonnnnn/Eamonnnnn.github.io
f7b90bf6d84486f57d45791893c3c2060aa72ff1
35ba3bdcbe142a94835cc87c6e51b92ddef93d07
refs/heads/main
2023-06-05T00:00:14.405489
2021-06-23T00:47:22
2021-06-23T00:47:22
366,547,076
0
0
null
null
null
null
UTF-8
Python
false
false
367
py
from thinkdsp import TriangleSignal from thinkdsp import decorate import matplotlib.pyplot as plt triangle = TriangleSignal().make_wave(duration=0.01) #triangle.plot() #decorate(xlabel='Time (s)') #plt.show() spectrum = triangle.make_spectrum() #print(spectrum.hs[0]) spectrum.hs[0] = 100 triangle.plot(color='gray') spectrum.make_wave().plot() plt.show()
5de8426ad12ee6f74167e7527e7d6194305ce8b3
1111412a700de2eff6aac87beeb7a157f2255e16
/program/ascii_generator.py
a5d7187a69218564874c2aee4e9973510f628a92
[]
no_license
yurkanin/project
8a4005863e20d276e58e1114cda77563c30b5e19
4e70f5a75ab8de68fdced852de42ee9eabe87b82
refs/heads/master
2021-01-10T21:32:30.742276
2014-09-01T22:12:13
2014-09-01T22:12:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
707
py
class face: def __init__(face): from PIL import Image pic = Image.open('/home/Justin/image.jpg', 'r') pic = pic.resize((300, 150)) face.pic = pic.convert('L') face.BAL = 0 def pixel_to_letter(face, value): if(value in xrange(0, face.BAL)): return '0' elif(value in xrange(face.BAL, 256)): return '1' def img_to_ascii(face, pic): dump = '' for y in xrange(0, pic.getbbox()[-1]): for x in xrange(0, pic.getbbox()[-2]): dump += face.pixel_to_letter(pic.getpixel((x,y))) dump += '\n' return dump f = face() for f.BAL in xrange(50, 256): print f.img_to_ascii(f.pic).replace('1', ' ')
ef1d029d21795328d7d3b05cec1d55b48bf5f0fd
30d2035626907509328494bdce8394d268b6e8b5
/oldjaratest/billy/scripts/spikeAnalysis_tuning.py
5df6d9b4e2a40cc96ec6c93e3ff4bf105269bb6b
[]
no_license
sjara/jaratoolbox
5f32b81b04002ce2ee736970701ced4a370e4ccc
0a4a0d2700427acf00de0b9ed66f0b64c02fdc43
refs/heads/master
2023-08-19T14:54:39.612875
2023-08-13T00:05:28
2023-08-13T00:05:28
21,258,341
3
4
null
2018-11-01T04:16:13
2014-06-26T23:43:44
Python
UTF-8
Python
false
false
3,694
py
''' Example of using spikesorting module (which uses KlustaKwik) for spike sorting ''' from jaratoolbox import spikesorting from jaratoolbox import settings import numpy as np import sys import importlib mouseName = str(sys.argv[1]) #the first argument is the mouse name to tell the script which allcells file to usec allcellsFileName = 'allcells_'+mouseName+'_tuning'########################################### sys.path.append(settings.ALLCELLS_PATH) allcells = importlib.import_module(allcellsFileName) outputDir = '/home/billywalker/data/ephys/tuning'############################################## nameOfFile = 'ISI_Violations' animalName = allcells.cellDB[0].animalName numOfCells = len(allcells.cellDB) #number of cells that were clustered on all sessions clustered numTetrodes = 8 numClusters = 12 #THIS IS KIND OF A HACK ASSUMING THERES 12 CLUSTERS ALL THE TIME ISIviolationsDict = {} ephysSessionEachCell = [] for cellID in range(0,numOfCells): ephysSessionEachCell.append(allcells.cellDB[cellID].ephysSession) ephysSessionArray = np.unique(ephysSessionEachCell) badSessions = []#prints the sessions that crash ''' for indEphys,ephysSession in enumerate(ephysSessionArray): try: ISIviolationsDict.update({ephysSession:np.empty([numTetrodes,numClusters])}) for tetrode in range(1,(numTetrodes+1)): oneTT = spikesorting.TetrodeToCluster(animalName,ephysSession,tetrode,features=['peak','valleyFirstHalf'])#,'energySpikeFirstHalf2'])#'energyAllZeros' print 'here' oneTT.create_fet_files() oneTT.run_clustering() oneTT.save_report() ISIviolationsDict[ephysSession][tetrode-1]= oneTT.get_ISI_values() #you can only get the ISI values after running save_report() except: print "error with session "+ephysSession if (ephysSession not in badSessionList): badSessionList.append(ephysSession) ''' for indEphys,ephysSession in enumerate(ephysSessionArray): try: for tetrode in range(1,(numTetrodes+1)): oneTT = spikesorting.TetrodeToCluster(animalName,ephysSession,tetrode,features=['peak','valleyFirstHalf']) #oneTT.create_fet_files() #oneTT.run_clustering() oneTT.save_report('cluster_report_tuning') except: badSessions.append(ephysSession) for session in badSessions: print session #oneTT.save_report() #ISIviolationsDict[ephysSession][tetrode-1]= oneTT.get_ISI_values() #you can only get the ISI values after running save_report() ''' finalOutputDir = outputDir+'/'+animalName+'_processed' ISIDict = {} prevISIList = [] #List of behavior sessions that already have ISI values calculated try: text_file = open("%s/%s.txt" % (finalOutputDir,nameOfFile), "r+") #open a text file to read and write in ephysName = '' for line in text_file: ephysLine = line.split(':') if (ephysLine[0] == 'Ephys Session'): ephysName = ephysLine[1][:-1] prevISIList.append(ephysName) except: text_file = open("%s/%s.txt" % (finalOutputDir,nameOfFile), "w") #open a text file to read and write in for indEphys,ephysSession in enumerate(ephysSessionArray): if ((ephysSession in prevISIList) or (ephysSession in badSessionList)): continue else: text_file.write("Ephys Session:%s\n" % ephysSession) ISIArray = ISIviolationsDict[ephysSession] for indTetrode,ISIlist in enumerate(ISIArray): text_file.write("tetrode:%s" % indTetrode) for ISIval in ISIlist: text_file.write(" %s" % ISIval) text_file.write("\n") text_file.close() '''
418e7fffede6d5fefeb3177718d7d68110f0aa63
301d3cc70e90e921019b0c02588607ad5f3939d8
/eim/small_problems_dists.py
b12ccb8c9abd1e18a7742aac9135e0e34fa9c4c9
[ "Apache-2.0" ]
permissive
chiragjn/google-research
d96c7dc0224ddd7fe21ea4df8bd4c2b43057393e
9a71a0efd41d5a1478a1c4f2603efaf64c1c33fd
refs/heads/master
2020-08-31T06:02:59.434670
2019-10-31T05:48:01
2019-10-31T05:48:01
218,616,849
1
0
Apache-2.0
2019-10-30T20:18:07
2019-10-30T20:18:07
null
UTF-8
Python
false
false
4,729
py
# coding=utf-8 # Copyright 2019 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Synthetic datasets for EIM experiments.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import numpy as np from six.moves import range import tensorflow as tf import tensorflow_probability as tfp tfd = tfp.distributions NINE_GAUSSIANS_DIST = "nine_gaussians" TWO_RINGS_DIST = "two_rings" CHECKERBOARD_DIST = "checkerboard" TARGET_DISTS = [NINE_GAUSSIANS_DIST, TWO_RINGS_DIST, CHECKERBOARD_DIST] class Ring2D(tfd.Distribution): """2D Ring distribution.""" def __init__(self, radius_dist=None, dtype=tf.float32, validate_args=False, allow_nan_stats=True, name="Ring"): parameters = dict(locals()) loc = tf.zeros([2], dtype=dtype) if radius_dist is None: radius_dist = tfd.Normal(loc=1., scale=0.1) self._loc = loc self._radius_dist = radius_dist super(Ring2D, self).__init__( dtype=dtype, reparameterization_type=tfd.NOT_REPARAMETERIZED, validate_args=validate_args, allow_nan_stats=allow_nan_stats, parameters=parameters, graph_parents=[self._loc], name=name) @property def loc(self): """Distribution parameter for the mean.""" return self._loc def _batch_shape_tensor(self): return tf.broadcast_dynamic_shape( tf.shape(self._loc)[:-1], self._radius_dist.batch_shape_tensor) def _batch_shape(self): return tf.broadcast_static_shape(self._loc.get_shape()[:-1], self._radius_dist.batch_shape) def _event_shape_tensor(self): return tf.constant([2], dtype=tf.int32) def _event_shape(self): return tf.TensorShape([2]) def _sample_n(self, n, seed=None): new_shape = tf.concat([[n], self.batch_shape_tensor()], 0) thetas = tf.random_uniform( new_shape, seed=seed, dtype=self.dtype) * 2. * math.pi rs = self._radius_dist.sample(new_shape, seed=seed) vecs = tf.stack([tf.math.sin(thetas), tf.math.cos(thetas)], axis=-1) sample = vecs * tf.expand_dims(rs, axis=-1) return tf.cast(sample, self.dtype) def _log_prob(self, event): radii = tf.norm(event, axis=-1, ord=2) return self._radius_dist.log_prob(radii) - tf.log(2 * math.pi * radii) def two_rings_dist(scale=0.1): r_dist = tfd.Mixture( cat=tfd.Categorical(probs=[1., 1.]), components=[ tfd.Normal(loc=0.6, scale=scale), tfd.Normal(loc=1.3, scale=scale) ]) return Ring2D(radius_dist=r_dist) def checkerboard_dist(num_splits=4): """Returns a checkerboard distribution.""" bounds = np.linspace(0., 1., num=(num_splits + 1), endpoint=True) uniforms = [] for i in range(num_splits): for j in range(num_splits): if ((i % 2 == 0 and j % 2 == 0) or (i % 2 != 0 and j % 2 != 0)): low = tf.convert_to_tensor([bounds[i], bounds[j]], dtype=tf.float32) high = tf.convert_to_tensor([bounds[i + 1], bounds[j + 1]], dtype=tf.float32) u = tfd.Uniform(low=low, high=high) u = tfd.Independent(u, reinterpreted_batch_ndims=1) uniforms.append(u) return tfd.Mixture( cat=tfd.Categorical(probs=[1.] * len(uniforms)), components=uniforms) def nine_gaussians_dist(variance=0.1): """Creates a mixture of 9 2-D gaussians on a 3x3 grid centered at 0.""" components = [] for i in [-1., 0., 1.]: for j in [-1., 0., 1.]: loc = tf.constant([i, j], dtype=tf.float32) scale = tf.ones_like(loc) * tf.sqrt(variance) components.append(tfd.MultivariateNormalDiag(loc=loc, scale_diag=scale)) return tfd.Mixture( cat=tfd.Categorical(probs=tf.ones([9], dtype=tf.float32) / 9.), components=components) def get_target_distribution(name, nine_gaussians_variance=0.01): if name == NINE_GAUSSIANS_DIST: return nine_gaussians_dist(variance=nine_gaussians_variance) elif name == TWO_RINGS_DIST: return two_rings_dist() elif name == CHECKERBOARD_DIST: return checkerboard_dist() else: raise ValueError("Invalid target name.")
229dfc91036abacf688643e3664c3a8fcba54fd9
addb5d0110b9b39ff5479e7637743943293e1c96
/perf_corr.py
d0e443c092fabbcaad38bd9ff466b0eae226bb73
[ "MIT" ]
permissive
jefftrull/MyParallelAlg
5bc3f817a4b8eccbdbdc8f5ed5aba87e69a29404
87ca7ce89152c70c46ffabad897f4d8ed82a6e24
refs/heads/master
2020-07-08T11:20:13.704708
2019-10-10T04:30:03
2019-10-10T04:30:03
203,657,035
0
0
null
null
null
null
UTF-8
Python
false
false
3,899
py
#!/usr/bin/env python """Plotting (and otherwise analyzing) the results of "perf stat" as applied to my benchmarks""" # Copyright (c) 2019 Jeff Trull # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import sys import pandas as pd import matplotlib.pyplot as plt import argparse import subprocess parser = argparse.ArgumentParser(description='Run benchmarks while counting performance events') parser.add_argument('--benchmark', dest='bm_name', required=True, help='path to benchmark executable') args = parser.parse_args() # # run my benchmarks under "perf stat" for a specified list of measurements, # collecting runtimes. # stat_names = [ "LLC-load-misses", "LLC-store-misses", "L1-dcache-load-misses", "alignment-faults", "dTLB-load-misses", "dTLB-store-misses", ] # construct "perf stat" commandline from stat names statcmd = ["perf", "stat"] for stat in stat_names: statcmd.extend(["-e", stat]) # add the benchmark executable statcmd.append(args.bm_name) data = {} for stat in stat_names: data[stat] = [] data['runtime'] = [] for nthreads in range(2, 8+1): cmd = statcmd.copy() bm_pattern='inclusive_scan/16777216/%d/real_time' % nthreads cmd.append('--benchmark_filter=%s' % bm_pattern) # run and parse arguments result = subprocess.run(cmd, capture_output=True) # store results in dataframe # stdout has the runtime info runtime = None for ln in result.stdout.decode('utf-8').splitlines(): words = ln.split() if words[0] == bm_pattern: runtime = int(words[1]) data['runtime'].append(runtime) if not runtime: raise RuntimeError('could not find runtime for benchmark pattern %s' % bm_pattern) # stderr has the perf stats stats = {} for ln in result.stderr.decode('utf-8').splitlines(): words = ln.split() if len(words) in range(2, 3+1): statname = words[1] if statname in stat_names: stats[statname] = int(words[0].replace(',', '')) data[statname].append(stats[statname]) # print('for %d threads I got %d runtime plus the following stats:' % (nthreads, runtime)) # for k, v in stats.items(): # print('%s : %d' % (k, v)) # print('\n') print('I ran this command: %s' % (' ').join(cmd)) print('and got:\n%s' % result.stdout.decode('utf-8')) print('with stderr:\n%s' % result.stderr.decode('utf-8')) # construct a dataframe from results df = pd.DataFrame(data=data) print(df) # calculate correlation coefficients vs runtime: coeffs = df.corr().loc['runtime', stat_names] # the runtime column minus "runtime" (1.0) # # see which statistic best correlate with runtime # # remove any NaNs coeffs = coeffs.dropna() # sort rows high (most correlated) to low coeffs = coeffs.sort_values(ascending=False) print(coeffs)
49fbcb4f59f7436c48d7de55d5b7a6b878bb748c
cd1a6453435950d6a6a975e415d78a892a8d3554
/test_git/git_demo.py
622e3b31242332369fa6ce5265086230841f9e15
[]
no_license
LastingN/HogwartsLG5
3edc957af96d05a3ac135b94749fc110abe16c1a
399af3d621e079d9cdd4b20ea4b5c6c3dc512e10
refs/heads/main
2023-01-30T08:00:27.054220
2020-12-16T02:39:22
2020-12-16T02:39:22
321,843,757
0
0
null
2020-12-16T02:20:08
2020-12-16T02:20:04
null
UTF-8
Python
false
false
39
py
print('seveniruby') print('yunbosheng')
a9e8b7e3fbd3b6994f53f7a59a4ff8dc21656765
80366d2cea3183e372e9b69ac91272d7bee94d0a
/Scrapy/novel/novel/settings.py
9134bc785d190d5d89a4388df626eef837682523
[]
no_license
lanvce/spider
300bac5755ffd3ba367621189bb00c61fa9f6a70
b7b4ab95f76b42932fcd200c999652a217a1069a
refs/heads/master
2020-08-06T18:30:16.100643
2019-10-06T04:51:48
2019-10-06T04:51:48
213,107,227
0
0
null
null
null
null
UTF-8
Python
false
false
3,470
py
# -*- coding: utf-8 -*- # Scrapy settings for novel project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-middleware.html # https://docs.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = 'novel' SPIDER_MODULES = ['novel.spiders'] NEWSPIDER_MODULE = 'novel.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False # Configure maximum concurrent requests performed by Scrapy (default: 16) CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs DOWNLOAD_DELAY = 0.5 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) #COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False # Override the default request headers: #DEFAULT_REQUEST_HEADERS = { # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # 'Accept-Language': 'en', #} #中间件 # Enable or disable spider middlewares # See https://docs.scrapy.org/en/latest/topics/spider-middleware.html SPIDER_MIDDLEWARES = { # 'novel.middlewares.NovelSpiderMiddleware': 543, 'scrapy_deltafetch.DeltaFetch': 50, 'scrapy_magicfields.MagicFieldsMiddleware': 51, } DELTAFETCH_ENABLED = True MAGICFIELDS_ENABLED = True MAGIC_FIELDS = { "timestamp": "$time", "spider": "$spider:name", "url": "scraped from $response:url", "domain": "$response:url,r'https?://([\w\.]+)/']", } # Enable or disable downloader middlewares # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 'novel.middlewares.NovelDownloaderMiddleware': 543, #} # Enable or disable extensions # See https://docs.scrapy.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #} # Configure item pipelines # See https://docs.scrapy.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'novel.pipelines.NovelPipeline': 300, } # Enable and configure the AutoThrottle extension (disabled by default) # See https://docs.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings #HTTPCACHE_ENABLED = True #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
323cb43f75cbb9c3439848d4669a824f94236131
f1e5f93b04a2b4bb328c6f46409faa540afb110b
/dbHandle.py
5e12ae1a1e092e27b1417d8e8b1985df39df28db
[]
no_license
MukulKadaskar/Document_Processing
11ff2c210cd1ac37b026bb48b720a0d7d4236587
17a74a9fb16877933ea602be21a7b0cb9555cd88
refs/heads/main
2023-03-31T05:57:59.342261
2021-04-04T10:09:51
2021-04-04T10:09:51
354,495,604
0
0
null
null
null
null
UTF-8
Python
false
false
680
py
import config import sqlite3 def connectDB(): return sqlite3.connect(config.DATABASE_NAME) def authenticateUser(username, password): connection = connectDB() dbcursor = connection.cursor() userCount = dbcursor.execute( '''SELECT COUNT(*) from users WHERE username=? AND password=?''', (username, password)).fetchone() if userCount[0] > 0: config.CURRENT_USER=username return True else: return False connection.close() def isLoggedIn(): if config.CURRENT_USER != '': return True else: return False if __name__ == '__main__': print(authenticateUser('[email protected]','qazwsxdc'))
48b09f3f8e4f41f68b94712aaa3d44d0419eedf3
722e7b462fc5f5a776c3d2891193304f5c41e1e1
/tensor-decomposition/decompose.py
ba334f4a21f55e4311ff0b71d096438efea18243
[ "MIT" ]
permissive
tjufan/keras-deep-compression
afe0c6426ba0e0bc2190e08681d908454444c6e2
8abf638e969f72d979879b7477c9bb651cf7c702
refs/heads/master
2022-11-22T12:51:53.457521
2020-07-26T01:43:43
2020-07-26T01:43:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,755
py
from warnings import filterwarnings filterwarnings("ignore") # Data loading and pre-processing from keras.datasets import cifar10 from keras.utils import np_utils from keras.optimizers import Adam import tensorflow as tf import numpy as np import os import csv # Model related imports from utils.hyperparams import parse_args from utils.model import get_model, decomposed_model from utils.utils import create_dir_if_not_exists from utils.tucker import tucker_reconstruction_loss # Run code on GPU # config = tf.ConfigProto(device_count={'GPU': 1, 'CPU': 1}) # sess = tf.Session(config=config) # K.set_session(sess) # Read Data and do initial pre-processing (x_train, y_train), (x_test, y_test) = cifar10.load_data() # convert to float32 (to not make all features zero) x_train = x_train.astype(np.float32) x_test = x_test.astype(np.float32) # divide features by 255 so that pixels have value in the range of [0,1] x_train /= 255 x_test /= 255 x_train = 2 * x_train - 1 x_test = 2 * x_test - 1 # convert class vectors to binary class matrices (one-hot encoding) n_output = 10 y_train = np_utils.to_categorical(y_train, n_output) y_test = np_utils.to_categorical(y_test, n_output) print("X_Train: {}\nX_Test: {}\nY_Train: {}\nY_Test: {}" \ .format(x_train.shape, x_test.shape, y_train.shape, y_test.shape)) print("Train Samples: {}, Test Samples: {}".format(x_train.shape[0], x_test.shape[0])) arg = parse_args() # Instantiate Model and load pre-trained weights model = get_model(arg) model.load_weights(arg.weights_path) optimizer = Adam(lr=arg.lr, decay=1e-6) model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) # ensure weights are loaded correctly by evaluating the model here and printing the output # test_loss, test_acc = model.evaluate(x_test, y_test, batch_size=arg.batch_size) # print("Test accuracy: {}".format(test_acc)) r_fixed = 64 experiment_r1_fixed = "CONV_2_reconstruction_loss_r1_{}".format(r_fixed) experiment_r2_fixed = "CONV_2_reconstruction_loss_r2_{}".format(r_fixed) create_dir_if_not_exists('./results') create_dir_if_not_exists(os.path.join('./results', experiment_r1_fixed)) create_dir_if_not_exists(os.path.join('./results', experiment_r2_fixed)) lines_r1, lines_r2 = [], [] for r in list(range(1, 65, 1)): lines_r1.append([r_fixed, r, tucker_reconstruction_loss(model.layers[3], [r_fixed, r])]) lines_r2.append([r, r_fixed, tucker_reconstruction_loss(model.layers[3], [r, r_fixed])]) with open(os.path.join('./results', experiment_r1_fixed, 'results.csv'), 'w', newline='') as file: header = ['r1', 'r2', 'reconstruction_loss'] writer = csv.writer(file, delimiter='\t') writer.writerow(header) writer.writerows(lines_r1) with open(os.path.join('./results', experiment_r2_fixed, 'results.csv'), 'w', newline='') as file: header = ['r1', 'r2', 'reconstruction_loss'] writer = csv.writer(file, delimiter='\t') writer.writerow(header) writer.writerows(lines_r2) experiment_rank = "rank_parameter" lines = [] for k in list(range(1, 9)): tucker_model = decomposed_model(model, k) optimizer = Adam(lr=arg.lr, decay=1e-6) tucker_model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) test_loss, test_acc = tucker_model.evaluate(x_test, y_test, batch_size=arg.batch_size) print("Test accuracy for {}: {}".format(k / 8, test_acc)) lines.append([k / 8, test_acc]) create_dir_if_not_exists(os.path.join('./results', experiment_rank)) with open(os.path.join('./results', experiment_rank, 'results.csv'), 'w', newline='') as file: header = ['x', 'Network Accuracy'] writer = csv.writer(file, delimiter='\t') writer.writerow(header) writer.writerows(lines)
752355892fba107da3cb4f9b05a8f2659f93c887
3fa613ea51721892a7cc80ea681a4b331f7f1dd5
/30 Days Challenge/maximun_sum_path.py
817d4a03a636aa6d77926f061bedc53825bdc3df
[]
no_license
sandy836/LeetCode
3b1fbbcdc057b8cff8bd6884cbcd924ba12c0649
ef87d08c37f31df113b09ba4ecb42f51dd0b69b7
refs/heads/master
2022-05-24T00:53:47.315127
2020-04-30T19:00:57
2020-04-30T19:00:57
255,095,882
1
0
null
null
null
null
UTF-8
Python
false
false
571
py
# class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxPathSum(self, root: TreeNode) -> int: self._sum = -float('inf') def helper(root): if not root: return 0 lsum = max(0, helper(root.left)) rsum = max(0, helper(root.right)) self._sum = max(self._sum, lsum+rsum+root.val) return root.val + max(lsum, rsum) helper(root) return self._sum
8600965422e7fcfe675570ed2c7ec5783ed7f540
3178bf3d83f0afa9859a4a7faeeb66becb93f122
/tf_lib_restlet_post_example.py
2ccc81ab2c1a11eadaebdd64708904c592e729cd
[]
no_license
eriawan/TokenBasedAuthentication
98245dbcc73600b53a993ed789c4ca631a2a2f50
3e4b9cdbcc481207eca0839233b5ac1ac8762b68
refs/heads/master
2020-04-21T12:10:20.666905
2017-10-30T20:17:21
2017-10-30T20:17:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,588
py
# # Copyright (c) 2014-2017 Techfino, LLC # 1900 Market Street, 8th Floor, Philadelphia, PA 19103, USA # All Rights Reserved. # # This software is the confidential and proprietary information of Techfino LLC. # ("Confidential Information") - You shall not disclose such Confidential Information # without prior written permission. # # Script Description: # This script is the central library for webservices functions for Techfino SS 2.0 # import oauth2 as oauth import json import requests import time url = "https://rest.netsuite.com/.../restlet.nl?script=X&deploy=Y" token = oauth.Token(key="____________________________", secret="____________________________") consumer = oauth.Consumer(key="____________________________", secret="____________________________") http_method = "POST" realm = "123456" # NetSuite account id # the JSON data to be sent to the RESTlet payload = { name:value, foo:bar, duck:hunt, } params = { 'oauth_version': "1.0", 'oauth_nonce': oauth.generate_nonce(), 'oauth_timestamp': str(int(time.time())), 'oauth_token': token.key, 'oauth_consumer_key': consumer.key } req = oauth.Request(method=http_method, url=url, parameters=params) signature_method = oauth.SignatureMethod_HMAC_SHA1() req.sign_request(signature_method, consumer, token) header = req.to_header(realm) headery = header['Authorization'].encode('ascii', 'ignore') headerx = {"Authorization": headery, "Content-Type": "application/json"} print(headerx) conn = requests.post(url, headers=headerx, data=json.dumps(payload)) print("Result: " + conn.text) print(conn.headers)
d849e7d094a163664d0d12e4b25892bafd277218
b2d3bd39b2de8bcc3b0f05f4800c2fabf83d3c6a
/examples/pwr_run/checkpointing/new_short/true_random/job20.py
79840e70bfc91cf948425c0b30be364dffa1aef5
[ "MIT" ]
permissive
boringlee24/keras_old
3bf7e3ef455dd4262e41248f13c04c071039270e
1e1176c45c4952ba1b9b9e58e9cc4df027ab111d
refs/heads/master
2021-11-21T03:03:13.656700
2021-11-11T21:57:54
2021-11-11T21:57:54
198,494,579
0
0
null
null
null
null
UTF-8
Python
false
false
6,999
py
""" #Trains a ResNet on the CIFAR10 dataset. """ from __future__ import print_function import keras from keras.layers import Dense, Conv2D, BatchNormalization, Activation from keras.layers import AveragePooling2D, Input, Flatten from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint, LearningRateScheduler from keras.callbacks import ReduceLROnPlateau, TensorBoard from keras.preprocessing.image import ImageDataGenerator from keras.regularizers import l2 from keras import backend as K from keras.models import Model from keras.datasets import cifar10 from keras.applications.mobilenet_v2 import MobileNetV2 from keras import models, layers, optimizers from datetime import datetime import tensorflow as tf import numpy as np import os import pdb import sys import argparse import time import signal import glob import json import send_signal from random import randrange parser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training') parser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name') parser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint') parser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use') parser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)') parser.set_defaults(resume=False) args = parser.parse_args() os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]=args.gpu_num # Training parameters batch_size = 256 args_lr = 0.0005 epoch_begin_time = 0 job_name = sys.argv[0].split('.')[0] save_files = '/scratch/li.baol/checkpoint_true_random/' + job_name + '*' total_epochs = 44 starting_epoch = 0 # first step is to update the PID pid_dict = {} with open('pid_lock.json', 'r') as fp: pid_dict = json.load(fp) pid_dict[job_name] = os.getpid() json_file = json.dumps(pid_dict) with open('pid_lock.json', 'w') as fp: fp.write(json_file) os.rename('pid_lock.json', 'pid.json') if args.resume: save_file = glob.glob(save_files)[0] # epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0]) starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1]) data_augmentation = True num_classes = 10 # Subtracting pixel mean improves accuracy subtract_pixel_mean = True n = 3 # Model name, depth and version model_type = args.tc #'P100_resnet50_he_256_1' # Load the CIFAR10 data. (x_train, y_train), (x_test, y_test) = cifar10.load_data() # Normalize data. x_train = x_train.astype('float32') / 255 x_test = x_test.astype('float32') / 255 # If subtract pixel mean is enabled if subtract_pixel_mean: x_train_mean = np.mean(x_train, axis=0) x_train -= x_train_mean x_test -= x_train_mean print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') print('y_train shape:', y_train.shape) # Convert class vectors to binary class matrices. y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) if args.resume: print('resume from checkpoint') model = keras.models.load_model(save_file) else: print('train from start') model = models.Sequential() base_model = MobileNetV2(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None) #base_model.summary() #pdb.set_trace() model.add(base_model) model.add(layers.Flatten()) #model.add(layers.BatchNormalization()) #model.add(layers.Dense(128, activation='relu')) #model.add(layers.Dropout(0.5)) #model.add(layers.BatchNormalization()) #model.add(layers.Dense(64, activation='relu')) #model.add(layers.Dropout(0.5)) #model.add(layers.BatchNormalization()) model.add(layers.Dense(10, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=args_lr), metrics=['accuracy']) #model.summary() print(model_type) #pdb.set_trace() current_epoch = 0 ################### connects interrupt signal to the process ##################### def terminateProcess(signalNumber, frame): # first record the wasted epoch time global epoch_begin_time if epoch_begin_time == 0: epoch_waste_time = 0 else: epoch_waste_time = int(time.time() - epoch_begin_time) epoch_waste_dict = {} with open('epoch_waste.json', 'r') as fp: epoch_waste_dict = json.load(fp) epoch_waste_dict[job_name] += epoch_waste_time json_file3 = json.dumps(epoch_waste_dict) with open('epoch_waste.json', 'w') as fp: fp.write(json_file3) print('checkpointing the model triggered by kill -15 signal') # delete whatever checkpoint that already exists for f in glob.glob(save_files): os.remove(f) model.save('/scratch/li.baol/checkpoint_true_random/' + job_name + '_' + str(current_epoch) + '.h5') print ('(SIGTERM) terminating the process') checkpoint_dict = {} with open('checkpoint.json', 'r') as fp: checkpoint_dict = json.load(fp) checkpoint_dict[job_name] = 1 json_file3 = json.dumps(checkpoint_dict) with open('checkpoint.json', 'w') as fp: fp.write(json_file3) sys.exit() signal.signal(signal.SIGTERM, terminateProcess) ################################################################################# logdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name tensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch') class PrintEpoch(keras.callbacks.Callback): def on_epoch_begin(self, epoch, logs=None): global current_epoch #remaining_epochs = epochs - epoch current_epoch = epoch print('current epoch ' + str(current_epoch)) global epoch_begin_time epoch_begin_time = time.time() my_callback = PrintEpoch() callbacks = [tensorboard_callback, my_callback] #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback] # Run training if not args.resume: # randomly assign it a value trainable_count = randrange(1000) # send signal 'jobxx param xxxxx' message = job_name + ' param ' + str(trainable_count) send_signal.send(args.node, 10002, message) # send signal to indicate checkpoint is qualified message = job_name + ' ckpt_qual' send_signal.send(args.node, 10002, message) model.fit(x_train, y_train, batch_size=batch_size, epochs=round(total_epochs/2), validation_data=(x_test, y_test), shuffle=True, callbacks=callbacks, initial_epoch=starting_epoch, verbose=1 ) # Score trained model. scores = model.evaluate(x_test, y_test, verbose=1) print('Test loss:', scores[0]) print('Test accuracy:', scores[1]) # send signal to indicate job has finished message = job_name + ' finish' send_signal.send(args.node, 10002, message)
1b62bf9ecb032caad9aa4b3f21477ede52ef0788
e3b98b7e69a1c0868840288ba11f09c658085e67
/helper/factors.py
e987bb88ca2aececf77d863a80695dc3b9d3423a
[ "BSD-3-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
LaminarIR/framework
994b5b8f87d04da0e430f169ac849c8d46619839
fc65bea693e0e842e9af16529cede181e53878f8
refs/heads/master
2021-01-22T11:21:06.912484
2016-02-29T13:08:14
2016-02-29T13:08:14
34,259,205
3
0
null
null
null
null
UTF-8
Python
false
false
616
py
from fractions import gcd def lcm(a,b): """Compute least common multiplier of two numbers""" return a * b / gcd(a,b) def listgcd(l): """Compute the gcd of a list of numbers""" if len(l) == 0: return 0 elif len(l) == 1: return l[0] elif len(l) == 2: return gcd(l[0],l[1]) else: return gcd(l[0],listgcd(l[2:])) def listlcm(l): """Compute the gcd of a list of numbers""" if len(l) == 0: return 0 elif len(l) == 1: return l[0] elif len(l) == 2: return lcm(l[0],l[1]) else: return lcm(l[0],listlcm(l[2:]))
8b2b8eaf8b31c4926c83f376c10a44592ac90278
ec916ca0fb23cf9c667be17f8ef7e713decbc794
/.venv/bin/pyrsa-sign
a8b7500c1a4bb87e272fc6ab849d112f78625a76
[]
no_license
BazioDEV/djangovueauth0
b82935e866cd2d185f715b57426336c5c341a887
6caf2f4190fceca0c50520e7082eb7866cdf6970
refs/heads/master
2023-03-27T19:36:28.158672
2021-04-02T12:07:44
2021-04-02T12:07:44
354,005,533
0
0
null
null
null
null
UTF-8
Python
false
false
254
#!/Users/Bazio/Desktop/BazioProject/BazioProject/.venv/bin/python3 # -*- coding: utf-8 -*- import re import sys from rsa.cli import sign if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(sign())
5e9fcbb08741923755d31a2f9b79bb364acba592
7ccc79f3f024c883836686b56a958363167a3a74
/examples/nat.py
f556972631a44b7a8162bdaf6dfc36192fc3c8b7
[]
no_license
sarum9in/DEPRECATED_iptables_python
4d90730e0ece8aa002b03f1e010985dcf5cf436e
f0f005fc81af18aa8a694d4a2c220ab5127a200b
refs/heads/master
2021-01-01T18:29:05.839194
2014-03-17T06:13:18
2014-03-17T06:13:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
342
py
#!/usr/bin/python3 # -*- coding: utf-8 -*- from iptables.profile import * iptables = IPTables() iptables.set_debug() router = Router( iptables=iptables, local_ip=None, local_iface="internal", local_net="192.168.0.0/24", inet_ip=None, inet_iface="external" ) router.set_tcpmss() router.masquerade() router.commit()
a2ed2f5ee23537aae209f324e79800a9b06a5f11
226ba07c53d105a7696bff2c3d3f25124f589dd9
/app/helper/parse.py
04252e4cdc60895d8974fbbeacc7f108a5841c81
[]
no_license
legenhand/Nana-API
d7d2aac16c832192a79e20560d3dd410abdd4339
6e8109a2cd72c3ce1e1a76013ade72fb7779d9c6
refs/heads/master
2022-12-23T06:40:39.718090
2020-09-26T13:35:10
2020-09-26T13:35:10
293,725,126
0
0
null
null
null
null
UTF-8
Python
false
false
117
py
import json def parse_json(path): f = open(f'app/{path}') data = json.load(f) f.close() return data
92623d22b99744d2d8fc18cd85ee1bff64b326e3
a02bff59ae0b35c6b109de7ab98690eeb25b4a1f
/huimwvs-scan/plugin_demo.py
da9c050ea3239a5afc074a79c95f297c78ba0041
[]
no_license
n1f2c3/huimwvs
44efd438aaa65fa361a107b59744cd35e13a5e1d
7103ca8f5eae1f88a7f2d4d120bc79896fcfd26e
refs/heads/master
2021-09-15T00:23:05.682782
2018-05-22T19:35:39
2018-05-22T19:35:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,786
py
#!/usr/bin/env python # -*- coding: utf-8 -*- from modules.scan import MePlugin import urlparse class MeScan(MePlugin): """ 类名不可修改,而且需要继承于plugin """ def __init__(self,flow_data=0): super(self.__class__, self).__init__() if flow_data != 0: self.flow_data=flow_data #如果接收到扫描器传入的链接资源,则采用它;否则该程序的链接资源来自测试对象,为测试使用。 arr = urlparse.urlparse(self.flow_data['url']) self.target=urlparse.urlunsplit((arr.scheme, arr.netloc, arr.path, '', '')) self.plugin_info = { "name": "", # 插件的名称 "product": "", # 该插件所针对的应用名称,严格按照文档上的进行填写 "product_version": "", # 应用的版本号,严格按照文档上的进行填写 "desc": """ """, # 插件的描述 "author": [""], # 插件作者 "ref": [ {self.ref.url: ""}, # 引用的url {self.ref.src: ""}, # src上的案例 ], "type": self.type.injection, # 漏洞类型 "severity": self.level.high, # 漏洞等级 "privileged": False, # 是否需要登录 "target": self.target #漏洞目标 } def match(self): """ 匹配是否调用此插件 :return: """ return True def check(self): """ 验证类型,尽量不触发waf规则 :return: """ pass def result(self): """ 攻击类型 :return: """ pass if __name__ == '__main__': from modules.main import main main(MeScan())
0aabade0be9a746d16c826bebd6c8781e4c8ca94
46d2fe5661f08161c025e4fb292dfe18bd16ccae
/dataloader.py
ec12e3aa2bce8bdae08e00bee0e63f42b5b21c3f
[]
no_license
severinL96/OCR
91d38782b3aee51a43c8e1b6412c22c1ee9a0ef5
56a9a9707ec5289a887a55edecd3a77ee7ebb2c1
refs/heads/main
2023-08-01T15:13:21.103387
2021-09-09T15:29:29
2021-09-09T15:29:29
403,867,173
0
0
null
null
null
null
UTF-8
Python
false
false
2,961
py
import pickle import random import string from torch.utils.data import DataLoader from PIL import Image from helperFunctions import * ################################################ class DataSet(): def __init__(self, vocabulary, batch, images, words, boxes): self.vocabulary = vocabulary self.batch = batch self.images = images self.words = words self.boxes = boxes def __getitem__(self, index): img = Image.open(self.images[index]) box = self.boxes[index] x1 = box[0][0][0] x2 = box[1][0][0] y1 = box[0][0][1] y4 = box[3][0][1] img_cropped = img.crop((x1, y1, x2, y4)) img_resized = img_cropped.resize((89, 26)) img_resized = np.array(img_resized) img_resized = img_resized.reshape((3, 26, 89)) word = self.words[index] word = toID(self.vocabulary, word) word = adjustWordLenght(word) return img_resized, word def __len__(self): return len(self.words) ################################################ def createData(BATCH): vocabulary = [char for char in str(string.ascii_lowercase) + str(string.ascii_uppercase) + " "] vocabulary.append("<S>") vocabulary.append("<.>") vocabulary.append("<E>") open_file = open("weights/images.pkl", "rb") images = pickle.load(open_file) open_file.close() open_file = open("weights/words.pkl", "rb") words = pickle.load(open_file) open_file.close() open_file = open("weights/boxes.pkl", "rb") boxes = pickle.load(open_file) open_file.close() c = list(zip(images, words, boxes)) random.shuffle(c) images, words, boxes = zip(*c) separation = int(len(images) * 0.9) images_train = images[:separation] boxes_train = boxes[:separation] words_train = words[:separation] images_rest = images[separation:] boxes_rest = boxes[separation:] words_rest = words[separation:] separation = int(len(images_rest) * 0.5) images_test = images_rest[:separation] boxes_test = boxes_rest[:separation] words_test = words_rest[:separation] images_eval = images_rest[separation:] boxes_eval = boxes_rest[separation:] words_eval = words_rest[separation:] dataset_Train = DataSet(vocabulary, BATCH, images_train, words_train, boxes_train) dataloader_Train = DataLoader(dataset=dataset_Train, batch_size=BATCH, shuffle=True, num_workers=4, drop_last=True) dataset_Test = DataSet(vocabulary, BATCH, images_test, words_test, boxes_test) dataloader_Test = DataLoader(dataset=dataset_Test, batch_size=BATCH, shuffle=True, num_workers=4, drop_last=True) dataset_Eval = DataSet(vocabulary, BATCH, images_eval, words_eval, boxes_eval) dataloader_Eval = DataLoader(dataset=dataset_Eval, batch_size=BATCH, shuffle=True, num_workers=4, drop_last=True) return vocabulary, dataloader_Train, dataloader_Test, dataloader_Eval
8960a6eb3e55943df0d3a9749230b90ba824897e
d8ae9ae613cbd3b678c69a74aa4f0b3d48e75543
/ajax/wsgi.py
bd12aef3249c1118323b96494fc1a2c287197ad1
[]
no_license
kyrios213/django-ajax2
d270520943bc42685b014029730a2b3d3036031b
ac4bed6dc9d61f62bbf224bf844717c37f182d50
refs/heads/main
2023-06-04T12:29:18.909949
2021-06-26T12:39:39
2021-06-26T12:39:39
379,134,932
0
0
null
null
null
null
UTF-8
Python
false
false
385
py
""" WSGI config for ajax project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ajax.settings') application = get_wsgi_application()
3d5eff4ece689484cc780f5e6e49ab5a114fc2ba
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/LArCalorimeter/LArCnv/LArByteStream/share/TBReadLArDigits_jobOptions.py
f2aca9be2644e4d6a34a91a7b9933a0eab82682f
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
Python
false
false
2,566
py
# Location & number of raw data file: runnumber=1000066 RawDataDir="/castor/cern.ch/atlas/testbeam/combined/2004/" RawDataFilePrefix="daq_SFI-51_calo" #Gain, set HIGH,MEDIUM,LOW or FREE GainKey="FREE" # Number of events to be processed theApp.EvtMax = 100 #Result location (full path name, no ~ and trailing / please!) ResultDir="" # *************************************************************** include( "ByteStreamCnvSvc/TBEventSelector_jobOptions.py" ) ByteStreamAddressProviderSvc = Service( "ByteStreamAddressProviderSvc" ) ByteStreamAddressProviderSvc.TypeNames += ["LArDigitContainer/HIGH"] ByteStreamAddressProviderSvc.TypeNames += ["LArDigitContainer/MEDIUM"] ByteStreamAddressProviderSvc.TypeNames += ["LArDigitContainer/LOW"] ByteStreamAddressProviderSvc.TypeNames += ["LArDigitContainer/FREE"] include( "LArDetMgrDetDescrCnv/LArDetMgrDetDescrCnv_H8_joboptions.py" ) if GainKey=="FREE": ToolSvc.LArRodDecoder.FirstSample=2 # Directory & Prefix & Runnumber ByteStreamInputSvc=Service("ByteStreamInputSvc") ByteStreamInputSvc.InputDirectory += [RawDataDir] ByteStreamInputSvc.FilePrefix += [RawDataFilePrefix] ByteStreamInputSvc.RunNumber = [runnumber] ToolSvc = Service( "ToolSvc" ) ToolSvc.LArRoI_Map.Print=FALSE # Set output level threshold (2=DEBUG, 3=INFO, 4=WARNING, 5=ERROR, 6=FATAL ) MessageSvc = Service( "MessageSvc" ) MessageSvc.OutputLevel =3 AthenaEventLoopMgr = Service ("AthenaEventLoopMgr") AthenaEventLoopMgr.OutputLevel=4 #Necessary DLL's theApp.Dlls += [ "LArRawUtils","LArROD", "LArTools"] theApp.Dlls += [ "LArByteStream"] #theApp.Dlls += [ "CaloDetMgrDetDescrCnv" ] # The only TopAlg: ReadLArDigits theApp.TopAlg += ["ReadLArDigits"] ReadLArDigits = Algorithm( "ReadLArDigits" ) ReadLArDigits.ContainerKey=GainKey; #compose file name: dumpFileName='%(dir)sLArDigits_%(No)d_%(key)s.txt' % {"dir" : ResultDir, "No" : runnumber, "key" : GainKey} print "**** Output file Name: ****" print dumpFileName ReadLArDigits.DumpFile=dumpFileName ReadLArDigits.PrintCellLocation=FALSE #StoreGateSvc.dump=true; #----- JobOptions for Ntuple-output NtupleFileName='%(dir)sLArDigits_%(No)d_%(key)s.root' % {"dir" : ResultDir, "No" : runnumber, "key" : GainKey} print "**** Ntuple file Name: ****" print NtupleFileName NtupleString="FILE1 DATAFILE='" + NtupleFileName + "' TYP='ROOT' OPT='NEW'" theApp.Dlls += [ "RootHistCnv" ]; theApp.HistogramPersistency = "ROOT" NtupleSvc = Service( "NtupleSvc" ) #NtupleSvc.Output=["FILE1 DATAFILE='~/scratch0/LArDigits_66_free.root' TYP='ROOT' OPT='NEW'"] NtupleSvc.Output=[NtupleString]
2218d68267cf2025d4e8b1425e51032e6268a099
edb69ef057593343c86bfc08024422cd8292207f
/learning_logs/forms.py
632a828108316e943f5b4e8fe467ba85b88c63d8
[]
no_license
MVNDAY/LearningLog
27005b3a411bdabaa56c23258d893e06f09caa0d
1d4436fdea5610b0e63cdb55ebbd2d112115d74a
refs/heads/master
2023-04-13T10:22:05.160792
2021-04-26T17:46:26
2021-04-26T17:46:26
361,832,448
0
0
null
null
null
null
UTF-8
Python
false
false
326
py
from django import forms from .models import Topic, Entry class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['text'] labels = {'text':''} class EntryForm(forms.ModelForm): class Meta: model = Entry fields = ['text'] labesl = {'text':''} widgets = {'text':forms.Textarea(attrs={'cols':80})}
eb7f866be569d3768fbfc46c84cae0e10531b259
5aac2f6c2c17ef7db8b6d8d0638b8fc49b609ad9
/python/dynamic programming/lcs_w_subseq.py
d30758663957fe3141593caeba6a41e3925861bf
[]
no_license
jeaniebean/General-Coding
39231b5c715cad83481afdc167b9cc3433f20c04
17871a86bcd8e0a93cec2515f8818effe5807cb9
refs/heads/master
2020-04-06T07:10:34.669667
2015-07-07T02:57:04
2015-07-07T02:57:04
38,557,073
0
0
null
null
null
null
UTF-8
Python
false
false
1,173
py
from collections import defaultdict from sys import stdin # LCS with subsequence def lcs(a,b,c): opt, back = defaultdict(int), defaultdict(int) len_a, len_b, len_c = len(a), len(b), len(c) for i in xrange(1, len_a+1): for j in xrange(1, len_b+1): for k in xrange(1, len_c+1): if a[i-1] == b[j-1]: first = opt[i-1, j-1, k-1] + 1, 1 second = opt[i-1, j-1, k], 2 opt[i,j,k], back[i,j,k] = first if a[i-1] == c[k-1] else second else: third = opt[i-1, j, k], 3 fourth = opt[i, j-1, k], 4 opt[i,j,k], back[i,j,k] = max(third, fourth) def backtrace(i, j, k): if not i or not j: return "" if back[i,j,k] == 1: return backtrace(i-1, j-1, k-1) + a[i-1] elif back[i,j,k] == 2: return backtrace(i-1, j-1, k) + a[i-1] elif back[i,j,k] == 3: return backtrace(i-1, j, k) else: return backtrace(i, j-1, k) result = opt[len_a, len_b, len_c] if not result: return 'NO LCS' return backtrace(len_a, len_b, len_c) def main(): for line in stdin: _line = line.strip() x, y, z = _line.split() print lcs(x, y, z) if __name__ == "__main__": main() '''input : abcbdab bdcaba bab zzz zz a '''
a7ee608f051ba30410101ed1d6b4a6c8569ebf0f
781e2692049e87a4256320c76e82a19be257a05d
/all_data/exercism_data/python/bob/87c62f4088a0424bb58160c5100fae14.py
3e39b0d85f86b9886cb05623a0e4159d654581df
[]
no_license
itsolutionscorp/AutoStyle-Clustering
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
refs/heads/master
2020-12-11T07:27:19.291038
2016-03-16T03:18:00
2016-03-16T03:18:42
59,454,921
4
0
null
2016-05-23T05:40:56
2016-05-23T05:40:56
null
UTF-8
Python
false
false
607
py
from re import search class Bob(): """Speech in the eyes of Mighty Bob""" def hey(s, speech): """hey(speech) will return response""" # Speech may be in unicode - will interfere with Yelling speech = speech.decode('unicode-escape') empty_speech = search(r"^\s*$", speech) question = search(r"\w\?\s*$", speech) yelling = speech.isupper() if not speech or empty_speech: return 'Fine. Be that way!' if yelling: return 'Woah, chill out!' if question: return "Sure." return 'Whatever.'
1ef26af31307dda04ef2b82987de30f296a7289d
e85ef6454e3237a50fbed0c57a0096952aa415b9
/HomeWork7/ex2.py
0085ae2ee287ef892ca25ff9bdddc74c70806146
[]
no_license
mazh661/distonslessons
b4098093969319d8465b61cdd1fa2f8fe8f9456e
040aacf5b710462e78326b05f468fccd35817ef8
refs/heads/master
2022-06-20T22:09:05.793342
2020-05-12T12:48:05
2020-05-12T12:48:05
250,292,431
0
0
null
null
null
null
UTF-8
Python
false
false
369
py
from random import randint def sel_sort(array): for i in range(len(array) - 1): m = i j = i + 1 while j < len(array): if array[j] < array[m]: m = j j = j + 1 array[i], array[m] = array[m], array[i] a = [] for i in range(10): a.append(randint(1, 99)) print(a) sel_sort(a) print(a)
2dc3d133dff1965bf2ef33a60d5273159f63b35b
10154a211cf46bd5161f849d42ebb5a065633600
/src/chapter03/logclient1.py
cedcf447d8bd0a3188bf4dacb3c72ad7699edda2
[]
no_license
akitanak/tcpip_socket_programming_by_python
2f7f1ff731614ecc642af18a2d7427ded7183737
c3ada712ec71ddcc2c33fdf0ca57a9f8f41342f0
refs/heads/master
2022-12-30T19:13:32.270165
2020-10-19T12:49:36
2020-10-19T12:49:44
294,952,504
0
0
null
null
null
null
UTF-8
Python
false
false
359
py
import socket import sys HOST = "localhost" PORT = 50000 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: client.connect((HOST, PORT)) except Exception as ex: print(f"cannot connect server. {ex}") sys.exit(-1) while True: msg = input() if msg == "q": break client.sendall(msg.encode("UTF-8")) client.close()
e260630b10228a6c87c6e7e3b1fed1758bf70df6
73c2d498769265d359b129899fe3288559617358
/config/settings.py
a18421b134dbd6cec3237cc03e8fece956c6b041
[]
no_license
seiya0723/assets_manager_02
5ae94634c576a69c575a7372be90dd9bf3b5e01d
c8045ee525e17181d10b11cebebb661cfeec426f
refs/heads/master
2023-05-24T15:17:21.221179
2021-06-26T01:08:22
2021-06-26T01:08:22
380,166,124
0
0
null
null
null
null
UTF-8
Python
false
false
3,662
py
""" Django settings for config project. Generated by 'django-admin startproject' using Django 2.2.6. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '%l+*kitk)=#!ptx)89ljgo_o8_y$^f)bb==r79i5^%5k+ph_ov' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] NUMBER_GROUPING = 3 # Application definition SITE_ID = 1 LOGIN_REDIRECT_URL = '/' ACCOUNT_LOGOUT_REDIRECT_URL = '/' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'django.contrib.humanize', "asset.apps.AssetConfig", ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,"templates"), os.path.join(BASE_DIR,"templates","allauth"), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'config.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'ja' TIME_ZONE = 'Asia/Tokyo' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
[ "seiya@asahina" ]
seiya@asahina
2eda07bf02819c05da11d1a94fd0a7706798cd08
32eeb97dff5b1bf18cf5be2926b70bb322e5c1bd
/benchmark/materialistic/testcase/interestcases/testcase0_4_1_016.py
91259aaa8195df59a1eef4d665319b70059c3af3
[]
no_license
Prefest2018/Prefest
c374d0441d714fb90fca40226fe2875b41cf37fc
ac236987512889e822ea6686c5d2e5b66b295648
refs/heads/master
2021-12-09T19:36:24.554864
2021-12-06T12:46:14
2021-12-06T12:46:14
173,225,161
5
0
null
null
null
null
UTF-8
Python
false
false
11,072
py
#coding=utf-8 import os import subprocess import time import traceback from appium import webdriver from appium.webdriver.common.touch_action import TouchAction from selenium.common.exceptions import NoSuchElementException, WebDriverException desired_caps = { 'platformName' : 'Android', 'deviceName' : 'Android Emulator', 'platformVersion' : '4.4', 'appPackage' : 'io.github.hidroh.materialistic', 'appActivity' : 'io.github.hidroh.materialistic.LauncherActivity', 'resetKeyboard' : True, 'androidCoverage' : 'io.github.hidroh.materialistic/io.github.hidroh.materialistic.JacocoInstrumentation', 'noReset' : True } def command(cmd, timeout=5): p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True) time.sleep(timeout) p.terminate() return def getElememt(driver, str) : for i in range(0, 5, 1): try: element = driver.find_element_by_android_uiautomator(str) except NoSuchElementException: time.sleep(1) else: return element os.popen("adb shell input tap 50 50") element = driver.find_element_by_android_uiautomator(str) return element def getElememtBack(driver, str1, str2) : for i in range(0, 2, 1): try: element = driver.find_element_by_android_uiautomator(str1) except NoSuchElementException: time.sleep(1) else: return element for i in range(0, 5, 1): try: element = driver.find_element_by_android_uiautomator(str2) except NoSuchElementException: time.sleep(1) else: return element os.popen("adb shell input tap 50 50") element = driver.find_element_by_android_uiautomator(str2) return element def swipe(driver, startxper, startyper, endxper, endyper) : size = driver.get_window_size() width = size["width"] height = size["height"] try: driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper), end_y=int(height * endyper), duration=1000) except WebDriverException: time.sleep(1) driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper), end_y=int(height * endyper), duration=1000) return def scrollToFindElement(driver, str) : for i in range(0, 5, 1): try: element = driver.find_element_by_android_uiautomator(str) elements = driver.find_elements_by_android_uiautomator(str) if (len(elements) > 1) : for temp in elements : if temp.get_attribute("enabled") == "true" : element = temp break except NoSuchElementException: swipe(driver, 0.5, 0.55, 0.5, 0.2) else : return element for i in range(0, 4, 1): try: element = driver.find_element_by_android_uiautomator(str) elements = driver.find_elements_by_android_uiautomator(str) if (len(elements) > 1): for temp in elements: if temp.get_attribute("enabled") == "true": element = temp break except NoSuchElementException: swipe(driver, 0.5, 0.2, 0.5, 0.55) else : return element return def scrollToClickElement(driver, str) : element = scrollToFindElement(driver, str) if element is None : return else : element.click() def clickInList(driver, str) : element = None if (str is None) : candidates = driver.find_elements_by_class_name("android.widget.CheckedTextView") if len(candidates) >= 1 and checkWindow(driver): element = candidates[len(candidates)-1] else : element = scrollToFindElement(driver, str) if element is not None : element.click() else : if checkWindow(driver) : driver.press_keycode(4) def clickOnCheckable(driver, str, value = "true") : parents = driver.find_elements_by_class_name("android.widget.LinearLayout") for parent in parents: try : parent.find_element_by_android_uiautomator(str) lists = parent.find_elements_by_class_name("android.widget.LinearLayout") if len(lists) == 1 : innere = parent.find_element_by_android_uiautomator("new UiSelector().checkable(true)") nowvalue = innere.get_attribute("checked") if (nowvalue != value) : innere.click() break except NoSuchElementException: continue def typeText(driver, value) : element = getElememt(driver, "new UiSelector().className(\"android.widget.EditText\")") element.clear() element.send_keys(value) enterelement = getElememt(driver, "new UiSelector().text(\"OK\")") if (enterelement is None) : if checkWindow(driver): driver.press_keycode(4) else : enterelement.click() def checkWindow(driver) : dsize = driver.get_window_size() nsize = driver.find_element_by_class_name("android.widget.FrameLayout").size if dsize['height'] > nsize['height']: return True else : return False def testingSeekBar(driver, str, value): try : if(not checkWindow(driver)) : element = seekForNearestSeekBar(driver, str) else : element = driver.find_element_by_class_name("android.widget.SeekBar") if (None != element): settingSeekBar(driver, element, value) driver.find_element_by_android_uiautomator("new UiSelector().text(\"OK\")").click() except NoSuchElementException: time.sleep(1) def seekForNearestSeekBar(driver, str): parents = driver.find_elements_by_class_name("android.widget.LinearLayout") for parent in parents: try : parent.find_element_by_android_uiautomator(str) lists = parent.find_elements_by_class_name("android.widget.LinearLayout") if len(lists) == 1 : innere = parent.find_element_by_class_name("android.widget.SeekBar") return innere break except NoSuchElementException: continue def settingSeekBar(driver, element, value) : x = element.rect.get("x") y = element.rect.get("y") width = element.rect.get("width") height = element.rect.get("height") TouchAction(driver).press(None, x + 10, y + height/2).move_to(None, x + width * value,y + height/2).release().perform() y = value def clickInMultiList(driver, str) : element = None if (str is None) : candidates = driver.find_elements_by_class_name("android.widget.CheckedTextView") if len(candidates) >= 1 and checkWindow(driver): element = candidates[len(candidates)-1] else : element = scrollToFindElement(driver, str) if element is not None : nowvalue = element.get_attribute("checked") if (nowvalue != "true") : element.click() else : if checkWindow(driver) : driver.find_element_by_android_uiautomator("new UiSelector().text(\"OK\")") # preference setting and exit try : starttime = time.time() driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) os.popen("adb shell am start -n io.github.hidroh.materialistic/io.github.hidroh.materialistic.SettingsActivity -a test") scrollToClickElement(driver, "new UiSelector().text(\"List\")") scrollToClickElement(driver, "new UiSelector().text(\"Swipe right to\")") clickInList(driver, "new UiSelector().text(\"Refresh\")") driver.press_keycode(4) time.sleep(2) except Exception, e: print 'FAIL' print 'str(e):\t\t', str(e) print 'repr(e):\t', repr(e) print traceback.format_exc() else: print 'OK' finally: cpackage = driver.current_package endtime = time.time() print 'consumed time:', str(endtime - starttime), 's' command("adb shell am broadcast -a com.example.pkg.END_EMMA --es name \"1_016_pre\"") jacocotime = time.time() print 'jacoco time:', str(jacocotime - endtime), 's' driver.quit() # testcase016 try : starttime = time.time() driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) element = getElememtBack(driver, "new UiSelector().text(\"...\")", "new UiSelector().className(\"android.widget.TextView\").instance(21)") TouchAction(driver).long_press(element).release().perform() element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageView\").description(\"More options\")") TouchAction(driver).tap(element).perform() element = getElememtBack(driver, "new UiSelector().text(\"List display options\")", "new UiSelector().className(\"android.widget.TextView\")") TouchAction(driver).tap(element).perform() swipe(driver, 0.5, 0.2, 0.5, 0.8) element = getElememtBack(driver, "new UiSelector().text(\"Other\")", "new UiSelector().className(\"android.widget.TextView\").instance(10)") TouchAction(driver).long_press(element).release().perform() element = getElememtBack(driver, "new UiSelector().text(\"Other\")", "new UiSelector().className(\"android.widget.TextView\").instance(1)") TouchAction(driver).tap(element).perform() element = getElememtBack(driver, "new UiSelector().text(\"Droid Serif\")", "new UiSelector().className(\"android.widget.TextView\").instance(5)") TouchAction(driver).tap(element).perform() element = getElememtBack(driver, "new UiSelector().text(\"Extra small\")", "new UiSelector().className(\"android.widget.TextView\")") TouchAction(driver).tap(element).perform() element = getElememtBack(driver, "new UiSelector().text(\"Article\")", "new UiSelector().className(\"android.widget.TextView\").instance(7)") TouchAction(driver).tap(element).perform() element = getElememtBack(driver, "new UiSelector().text(\"Readability\")", "new UiSelector().className(\"android.widget.TextView\").instance(2)") TouchAction(driver).tap(element).perform() element = getElememtBack(driver, "new UiSelector().text(\"Extra small\")", "new UiSelector().className(\"android.widget.TextView\").instance(3)") TouchAction(driver).long_press(element).release().perform() element = getElememtBack(driver, "new UiSelector().text(\"Droid Serif\")", "new UiSelector().className(\"android.widget.TextView\").instance(2)") TouchAction(driver).tap(element).perform() element = getElememtBack(driver, "new UiSelector().text(\"Droid Sans\")", "new UiSelector().className(\"android.widget.TextView\").instance(5)") TouchAction(driver).long_press(element).release().perform() driver.press_keycode(4) element = getElememtBack(driver, "new UiSelector().text(\"Other\")", "new UiSelector().className(\"android.widget.TextView\").instance(10)") TouchAction(driver).long_press(element).release().perform() element = getElememtBack(driver, "new UiSelector().text(\"Same\")", "new UiSelector().className(\"android.widget.TextView\")") TouchAction(driver).tap(element).perform() element = getElememtBack(driver, "new UiSelector().text(\"Large\")", "new UiSelector().className(\"android.widget.TextView\").instance(3)") TouchAction(driver).long_press(element).release().perform() element = getElememtBack(driver, "new UiSelector().text(\"Extra small\")", "new UiSelector().className(\"android.widget.TextView\")") TouchAction(driver).tap(element).perform() swipe(driver, 0.5, 0.2, 0.5, 0.8) except Exception, e: print 'FAIL' print 'str(e):\t\t', str(e) print 'repr(e):\t', repr(e) print traceback.format_exc() else: print 'OK' finally: cpackage = driver.current_package endtime = time.time() print 'consumed time:', str(endtime - starttime), 's' command("adb shell am broadcast -a com.example.pkg.END_EMMA --es name \"1_016\"") jacocotime = time.time() print 'jacoco time:', str(jacocotime - endtime), 's' driver.quit() if (cpackage != 'io.github.hidroh.materialistic'): cpackage = "adb shell am force-stop " + cpackage os.popen(cpackage)
63132fcbb62843e51c44bd4314bd6e9b20c9b746
3b05502b5daded001558007ad474ae6fa4cd5001
/virtual/bin/django-admin
00de6bcff4c3f17d137a99cc8abd9aead9eec8ff
[ "MIT" ]
permissive
sharon0812/Instagram
3317d02df5adc229814080d378d832fde9725521
727de920ef5ae1bf2ce3ff4dab908991b3b60ea6
refs/heads/master
2023-02-20T17:30:20.078518
2021-01-18T18:52:09
2021-01-18T18:52:09
330,000,266
0
0
null
null
null
null
UTF-8
Python
false
false
297
#!/home/moringa/Desktop/Instagram/virtual/bin/python # -*- coding: utf-8 -*- import re import sys from django.core.management import execute_from_command_line if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(execute_from_command_line())
43d617c482d3746efa0d42d70aec11705491f2e0
c4ecbe5850c81dcc7c382fa1f579ce7715ac79f7
/Python/Python第8讲/chapter8_5_1.py
ee2f5faf6573bf131473ecdf60978d2b17c65f03
[ "MIT" ]
permissive
Text-Related/reference-materials-for-review
ef47126a7df5a53abe1cb8a55b8be69e55d3b84d
75795dae531adb57408d0c5a67dd7a6a9985dae4
refs/heads/master
2022-11-10T22:47:36.864755
2020-06-28T02:32:36
2020-06-28T02:32:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
568
py
class Person: # 基类 def __init__(self,name,age): # 构造函数 self.name = name self.age = age def say_hi(self): print("Hello, My name is {0}, I'm {1}".format(self.name,self.age)) class Student(Person): # 派生类 def __init__(self,name,age,stu_id): Person.__init__(self,name,age) self.stu_id = stu_id def say_hi(self): Person.say_hi(self) print("I'm a student, My student ID is ",self.stu_id) p1 = Person('Jack',30) p1.say_hi() p2 = Student('John',20,'201611210001') p2.say_hi()
993f11bbd3b432faf87ee54d7e09f7832748f98b
84290c584128de3e872e66dc99b5b407a7a4612f
/Statistical Thinking in Python (Part 1)/hinking probabilistically-- Continuous variables/The Normal CDF.py
37f4e63e736c79ea2d0e24ae46a6aa24ff144e39
[]
no_license
BautizarCodigo/DataAnalyticEssentials
91eddc56dd1b457e9e3e1e3db5fbbb2a85d3b789
7f5f3d8936dd4945ee0fd854ef17f04a04eb7b57
refs/heads/main
2023-04-11T04:42:17.977491
2021-03-21T19:05:17
2021-03-21T19:05:17
349,784,608
0
1
null
null
null
null
UTF-8
Python
false
false
434
py
# Generate CDFs x_std1, y_std1 = ecdf(samples_std1) x_std3, y_std3 = ecdf(samples_std3) x_std10, y_std10 = ecdf(samples_std10) # Plot CDFs _ = plt.plot(x_std1, y_std1, marker='.', linestyle='none') _ = plt.plot(x_std3, y_std3, marker='.', linestyle='none') _ = plt.plot(x_std10, y_std10, marker='.', linestyle='none') # Make a legend and show the plot _ = plt.legend(('std = 1', 'std = 3', 'std = 10'), loc='lower right') plt.show()
8fc1eecf108777b0bed1a119ea374a8fef2a052c
fb553880396ea9dc22b3726c0b9b67ea18f6e129
/jobapp/migrations/0019_applicant_image.py
6654906806e70c71f2a6acd25a1f0198ea831cac
[]
no_license
Chessy11/joblisting
3e051176b9aa4c578af239230d8dc63d8f064ab5
9454bc24264b1593e03d1e5a990a7915de846f58
refs/heads/main
2023-06-30T12:36:19.342819
2021-08-07T12:28:50
2021-08-07T12:28:50
393,678,183
0
0
null
null
null
null
UTF-8
Python
false
false
425
py
# Generated by Django 3.2.5 on 2021-08-03 14:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jobapp', '0018_alter_job_header_image'), ] operations = [ migrations.AddField( model_name='applicant', name='image', field=models.ImageField(blank=True, null=True, upload_to='static/images'), ), ]
c9b93f157a3e964bceaecb67720ffe65138722e6
84b28b409b1795b477368ea9fb3768b004c0f71c
/vgg16ModelTransferLearning.py
3a5487753f259fd6a3e2a8f3bb456ebfaae454ee
[]
no_license
Zumbalamambo/cancer_nn
284a9d801677bb9ce57687f431b59b8c59ba0121
27ca45fb0f92606e25b50c4698dba3973d12a75e
refs/heads/master
2021-06-29T00:55:19.675876
2017-09-19T08:21:33
2017-09-19T08:21:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,376
py
import numpy as np import matplotlib.pyplot as plt from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Dropout, Flatten, Dense from keras import applications from keras import regularizers from keras import optimizers img_width, img_height = 224, 224 top_model_weights_path = "isic-vgg16-transfer-learning.h5" train_data_dir = '/home/openroot/Tanmoy/Working Stuffs/myStuffs/havss-tf/ISIC-2017/data/train' validation_data_dir = '/home/openroot/Tanmoy/Working Stuffs/myStuffs/havss-tf/ISIC-2017/data/validation' train_aug_data_dir = '/home/openroot/Tanmoy/Working Stuffs/myStuffs/havss-tf/ISIC-2017/data/aug/train' validation_aug_data_dir = "/home/openroot/Tanmoy/Working Stuffs/myStuffs/havss-tf/ISIC-2017/data/aug/validation" nb_train_samples = 9216 nb_validation_samples = 2304 epochs = 300 batch_size = 16 def saveBottleneckTransferValues(): # VGG16 Model model = applications.VGG16(include_top = False, weights = "imagenet") datagen = ImageDataGenerator( rescale = 1./255 ) # Training train_datagen = ImageDataGenerator( rescale = 1./255, # rotation_range = 40, # width_shift_range = 0.1, # height_shift_range = 0.1, # shear_range = 0.1, # zoom_range = 0.1, # horizontal_flip = True, # fill_mode = "nearest" ) train_generator = train_datagen.flow_from_directory( train_aug_data_dir, target_size = (img_height, img_width), batch_size = batch_size, class_mode = None, shuffle = False ) train_transfer_values = model.predict_generator( train_generator, nb_train_samples // batch_size ) print("Train Transfer Values Shape : {0} ".format(train_transfer_values.shape)) np.save(open("train-transfer-values.npy", "w"), train_transfer_values) # Validation validation_datagen = ImageDataGenerator( rescale=1./255 ) validation_generator = validation_datagen.flow_from_directory( validation_aug_data_dir, target_size = (img_height, img_width), batch_size = batch_size, class_mode = None, shuffle = False ) validation_transfer_values = model.predict_generator( validation_generator, nb_validation_samples // batch_size ) print("Validation Transfer Value Shape : {0}".format(validation_transfer_values.shape)) np.save(open("validation-tansfer-values.npy", "w"), validation_transfer_values) def trainTopModel(): train_data = np.load(open("train-transfer-values.npy")) train_labels = np.array( [0] * (nb_train_samples / 2) + [1] * (nb_train_samples / 2)) validation_data = np.load(open("validation-tansfer-values.npy")) validation_labels = np.array( [0] * (nb_validation_samples / 2) + [1] * (nb_validation_samples / 2)) model = Sequential() model.add(Flatten(input_shape = train_data.shape[1:])) model.add(Dense(512, activation = "relu")) model.add(Dropout(0.7)) model.add(Dense(256, activation = "relu")) model.add(Dropout(0.7)) model.add(Dense(1, activation = "sigmoid")) # model.compile(optimizer = "rmsprop", # loss = "binary_crossentropy", # metrics = ["accuracy"] # ) model.compile(loss='binary_crossentropy', optimizer=optimizers.SGD(lr=1e-4, momentum=0.9), metrics=['accuracy'] ) history = model.fit(train_data, train_labels, epochs = epochs, batch_size = batch_size, validation_data = (validation_data, validation_labels) ) # list all data in history print(history.history.keys()) # summarize history for accuracy plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() # summarize history for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() model.save_weights(top_model_weights_path) def main(): # saveBottleneckTransferValues() trainTopModel() if __name__ == '__main__': main()
0e961088587c4d26499d0e50d40a84d62c3939ac
ce6ad72a93b27015af32549bb28828bb78f5acf4
/heap/test_Heap.py
becfac88c39017600ad028418589f9b55e7ff0aa
[]
no_license
shaowei1/algorithms
5c012a9550fe5c307c33ac69f0928822e3847c71
6c6419fa794b4d4cf6f464256af39ee10d96ba2f
refs/heads/master
2020-04-16T02:31:29.309388
2020-03-28T12:27:50
2020-03-28T12:27:50
165,199,053
0
0
null
null
null
null
UTF-8
Python
false
false
759
py
from heap.Heap import swap, Heap def test_swap(): data = [1, 2, 3] swap(data, 0, 2) assert data == [3, 2, 1] def test_math(): assert 2 / 2 == 1.0 def test_heap(): given = [33, 17, 21, 16, 13, 15, 9, 5, 6, 7, 8, 1, 2, 22] heap = Heap(capacity=len(given)) for key in given: heap.insert(key) assert heap.a == [0, 33, 17, 22, 16, 13, 15, 21, 5, 6, 7, 8, 1, 2, 9] heap.remove_max() assert heap.a == [0, 22, 17, 21, 16, 13, 15, 9, 5, 6, 7, 8, 1, 2, 9] heap.show() sort_given = [0, 33, 17, 21, 16, 13, 15, 9, 5, 6, 7, 8, 1, 2, 22] Heap().sort(sort_given, len(sort_given) - 1) assert sort_given == [0, 1, 2, 5, 6, 7, 8, 9, 13, 15, 16, 17, 21, 22, 33] if __name__ == '__main__': test_heap()
2b708896244dc81483ba670c605a1aeb71aca52f
3bc67ddddaee36ee63daf25cfd802629d30ac22a
/films/migrations/0001_initial.py
e4846b0acfa4cb009ceaaefa9f9ed05b37af8847
[]
no_license
Santa29/films_blog
57430d47767f9caf4e1e65113311d98e6ccae2c8
7611c8bc28864a4c5128538e2e39dabbb3d99c66
refs/heads/master
2022-12-22T08:36:05.157317
2020-09-28T16:57:26
2020-09-28T16:57:26
298,570,884
0
0
null
null
null
null
UTF-8
Python
false
false
1,021
py
# Generated by Django 3.1.1 on 2020-09-25 11:29 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='FilmReview', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('film_name', models.CharField(max_length=256)), ('actors', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('body', models.TextField()), ], ), migrations.CreateModel( name='ReviewComment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('review_comment', models.CharField(max_length=250)), ('date', models.DateTimeField(auto_now_add=True)), ], ), ]
8e45431cafbed8d8492dfbf9e778047ab20269c4
cd5077e11b651758ebd4b5b5d164762dc34d3efe
/smart_ads/main_app/client/views.py
423e05167f068c05517382a191f31c49c9a80250
[]
no_license
abhijitbangera/smart_ads
72b333aca6034538af724d2a48e91b9c76fe759a
6b54ac6ed6615b6ec3866f0573443baa9ac92ed3
refs/heads/master
2020-03-28T16:56:30.851291
2018-10-01T10:50:52
2018-10-01T10:50:52
148,743,166
1
0
null
null
null
null
UTF-8
Python
false
false
3,832
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from client.models import adsDetails, clientDetails from client.forms import adsDetailsForm, clientDetailsForm from django.contrib import messages from django.shortcuts import render from django.http import Http404 from rest_framework.views import APIView from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from client.serializers import AdsSerializer from django.http import JsonResponse from django.core import serializers from django.conf import settings import json from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User # Create your views here. @login_required def clientads(request): try: my_record = adsDetails.objects.get(client_id_id=request.user.id) except adsDetails.DoesNotExist: my_record = None form = adsDetailsForm(instance=my_record) if request.POST: print ('inside') form= adsDetailsForm(request.POST or None, instance=my_record) if form.is_valid(): save_it = form.save(commit = False) print ('...') print (request.user.id) save_it.client_id_id = request.user.id save_it.update_flag=1 form.save() print ('Ads updated successfully.') messages.success(request,'Ads updated successfully.') context = {'form': form} return render(request,'dashboard.html',context=context) @login_required def client_profile(request): try: my_record = clientDetails.objects.get(client_id_id=request.user.id) except clientDetails.DoesNotExist: my_record = None form = clientDetailsForm(instance=my_record) if request.POST: print ('inside') form = clientDetailsForm(request.POST or None, instance=my_record) if form.is_valid(): save_it = form.save(commit=False) print ('...') print (request.user.id) save_it.client_id_id = request.user.id form.save() print ('Ads updated successfully.') messages.success(request, 'Ads updated successfully.') context = {'form': form} return render(request, 'profile.html', context=context) @api_view(['GET','POST']) def clientads_api(request): if request.method == 'GET': # contacts = adsDetails.objects.all() fallback_page_num = 'None' id = request.GET.get('id', fallback_page_num) ads = adsDetails.objects.filter(client_id_id=id) serializer = AdsSerializer(ads, many=True) print ("**** page ***: ", id) return Response(serializer.data) elif request.method == 'POST': print ("in post...") print (request.data[0]) print (".......") data = request.data[0] # data['client_id']= User.objects.get(id=request.data[0]['client_id']) # print (data) # test_data = json.dumps(data) serializer = AdsSerializer(data=request.data[0]) print (serializer) print (serializer.is_valid()) if serializer.is_valid(): print ('serializer is valid!') print (request.data[0]['client_id']) # serializer.client_id= User.objects.get(id=request.data[0]['client_id']) # serializer.save() my_record = adsDetails.objects.get(client_id_id=request.data[0]['client_id']) print ("/////") my_record.update_flag=0 my_record.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
9f25f23e4a3b38e0b1707293624c45509668fa73
ca1e432c66ca9289cc25039f6c035c292e298d15
/content_management_portal/tests/interactors/test_delete_prefilled_code_interactor.py
6fb0d6be8ca9884c895d26570a10ebb0604b1d5f
[]
no_license
raviteja1766/ib_mini_projects
9bf091acf34e87d7a44bec51a504bdb81aceae27
3fa36b97cfa90b5f5853253480934cf27714aa15
refs/heads/master
2022-11-19T07:08:27.061315
2020-07-02T16:54:42
2020-07-02T16:54:42
272,033,119
1
0
null
null
null
null
UTF-8
Python
false
false
5,707
py
import pytest from unittest.mock import create_autospec from django_swagger_utils.drf_server.exceptions import NotFound, Forbidden from content_management_portal.interactors.presenters.presenter_interface\ import PresenterInterface from content_management_portal.interactors.storages\ .question_storage_interface import QuestionStorageInterface from content_management_portal.interactors.storages\ .prefilled_code_storage_interface import PrefilledCodeStorageInterface from content_management_portal.interactors\ .delete_prefilled_code_interactor import DeletePrefilledCodeInteractor def test_delete_prefilled_code_given_invalid_details_returns_exception(): # Arrange question_id = 1 prefilled_code_id = 1 presenter = create_autospec(PresenterInterface) question_storage = create_autospec(QuestionStorageInterface) prefilled_code_storage = create_autospec(PrefilledCodeStorageInterface) interactor = DeletePrefilledCodeInteractor( question_storage=question_storage, presenter=presenter, prefilled_code_storage=prefilled_code_storage ) question_storage.validate_question_id.return_value = False presenter.raise_exception_for_invalid_question.side_effect = NotFound # Act with pytest.raises(NotFound): interactor.delete_prefilled_code_to_question( question_id=question_id, prefilled_code_id=prefilled_code_id ) # Assert question_storage.validate_question_id.assert_called_once_with( question_id=question_id ) presenter.raise_exception_for_invalid_question.assert_called_once() def test_delete_question_given_invalid_details_returns_invalid_prefilled_code( ): # Arrange question_id = 1 prefilled_code_id = 1 presenter = create_autospec(PresenterInterface) question_storage = create_autospec(QuestionStorageInterface) prefilled_code_storage = create_autospec(PrefilledCodeStorageInterface) interactor = DeletePrefilledCodeInteractor( question_storage=question_storage, presenter=presenter, prefilled_code_storage=prefilled_code_storage ) question_storage.validate_question_id.return_value = True prefilled_code_storage.validate_prefilled_code.return_value = False presenter.raise_exception_for_invalid_prefilled_code\ .side_effect = NotFound # Act with pytest.raises(NotFound): interactor.delete_prefilled_code_to_question( question_id=question_id, prefilled_code_id=prefilled_code_id ) # Assert question_storage.validate_question_id.assert_called_once_with( question_id=question_id ) prefilled_code_storage.validate_prefilled_code.assert_called_once_with( prefilled_code_id=prefilled_code_id ) presenter.raise_exception_for_invalid_prefilled_code.assert_called_once() def test_delete_question_given_different_question_raises_exception(): # Arrange question_id = 1 prefilled_code_id = 1 another_question_id = 2 presenter = create_autospec(PresenterInterface) question_storage = create_autospec(QuestionStorageInterface) prefilled_code_storage = create_autospec(PrefilledCodeStorageInterface) interactor = DeletePrefilledCodeInteractor( question_storage=question_storage, presenter=presenter, prefilled_code_storage=prefilled_code_storage ) question_storage.validate_question_id.return_value = True prefilled_code_storage.validate_prefilled_code.return_value = True prefilled_code_storage.get_question_to_prefilled_code\ .return_value = another_question_id presenter.raise_exception_for_different_question\ .side_effect = Forbidden # Act with pytest.raises(Forbidden): interactor.delete_prefilled_code_to_question( question_id=question_id, prefilled_code_id=prefilled_code_id ) # Assert question_storage.validate_question_id.assert_called_once_with( question_id=question_id ) prefilled_code_storage.validate_prefilled_code.assert_called_once_with( prefilled_code_id=prefilled_code_id ) prefilled_code_storage.get_question_to_prefilled_code.assert_called_once_with( prefilled_code_id=prefilled_code_id) presenter.raise_exception_for_different_question\ .assert_called_once() def test_delete_question_given_valid_details_deletes_prefilled_code(): # Arrange question_id = 1 prefilled_code_id = 1 presenter = create_autospec(PresenterInterface) question_storage = create_autospec(QuestionStorageInterface) prefilled_code_storage = create_autospec(PrefilledCodeStorageInterface) interactor = DeletePrefilledCodeInteractor( question_storage=question_storage, presenter=presenter, prefilled_code_storage=prefilled_code_storage ) question_storage.validate_question_id.return_value = True prefilled_code_storage.validate_prefilled_code.return_value = True prefilled_code_storage.get_question_to_prefilled_code\ .return_value = question_id # Act interactor.delete_prefilled_code_to_question( question_id=question_id, prefilled_code_id=prefilled_code_id ) # Assert question_storage.validate_question_id.assert_called_once_with( question_id=question_id ) prefilled_code_storage.validate_prefilled_code.assert_called_once_with( prefilled_code_id=prefilled_code_id ) prefilled_code_storage.get_question_to_prefilled_code.assert_called_once_with( prefilled_code_id=prefilled_code_id) prefilled_code_storage.delete_prefilled_code.assert_called_once_with( prefilled_code_id=prefilled_code_id )
e603fc70dd7dba09f23e20f9c6dd48458e6c39c7
a4f8fc197c9bf6cd451ec11769a6a95609ef6b01
/Mainlab3.py
cbbe955b6bb2c45d83e36804484e447675905d1b
[]
no_license
Abhimagic1/Labs-Final-project
17802f52ba43fc52e716aaf2178659c7aeb2b4fd
5909872565b60bfd9e80e91f8fd7187fdc5e160b
refs/heads/main
2023-05-13T20:20:42.282759
2021-06-10T03:10:00
2021-06-10T03:10:00
362,699,395
0
0
null
null
null
null
UTF-8
Python
false
false
950
py
from Lab3 import CircularQueue queue = CircularQueue() for number in range(5): queue.enqueue(number) print(queue.get_raw_contents()) queue.dequeue() queue.dequeue() print(queue.get_raw_contents()) for number in range(7): queue.enqueue(number) print(queue.get_raw_contents()) queue.dequeue() queue.dequeue() print(queue.get_raw_contents()) for number in range(5, 9): queue.enqueue(number) print(queue.get_raw_contents()) queue.dequeue() queue.dequeue() print(queue.get_raw_contents()) for number in range(2, 8): #cls queue.enqueue(number) print(queue.get_raw_contents()) queue.dequeue() queue.dequeue() print(queue.get_raw_contents()) for number in range(6, 12): queue.enqueue(number) print(queue.get_raw_contents()) for number in range(11, 18): queue.enqueue(number) print(queue.get_raw_contents()) for number in range(0, 15): # Furthest range queue.enqueue(number) print(queue.get_raw_contents())
c643ad462dac111c5a51019399f2510ddf02e6ef
57edf4fc537a162a940c3342ebdec5d17ead086c
/ros_src/cv_ros/devel/lib/python3/dist-packages/cv_bridge/__init__.py
f26954034eca47a5bb21364dab9ead3ed9c2545a
[]
no_license
chindimaga/MoPAT_Design
f7da614680f8be8a03a7119971dd4857ac039496
048b260ca2f9ac49384a05fd3840c2e40126acb5
refs/heads/master
2022-12-18T21:08:54.099146
2020-10-03T02:42:22
2020-10-03T02:42:22
285,557,414
0
0
null
2020-08-06T11:49:30
2020-08-06T11:49:29
null
UTF-8
Python
false
false
94
py
/home/otoshuki/cv_ros/devel/.private/cv_bridge/lib/python3/dist-packages/cv_bridge/__init__.py
d088cf5bd12cc6c2c1ef60a1887186e1c10d4cf5
af7050b659e48a979809a705066baf7cd1a84255
/107_Binary Tree Level Order Traversal II.py
bf88bc31854dd8320e7de7b9655975222e3854b1
[]
no_license
zyk930/leetcode
b9547cbbeaf0202c2bb3e1a22d30f1ecddd4244e
27c9da844550080c41fae60906274347f9e62919
refs/heads/master
2020-04-10T15:13:45.886717
2019-06-04T01:37:10
2019-06-04T01:37:10
161,101,906
0
0
null
null
null
null
UTF-8
Python
false
false
1,224
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/12/14 21:12 # @Author : zyk # 给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) # # 例如: # 给定二叉树 [3,9,20,null,null,15,7], # # 3 # / \ # 9 20 # / \ # 15 7 # 返回其自底向上的层次遍历为: # # [ # [15,7], # [9,20], # [3] # ] # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] queue = [root] res = [] while queue: nodes = [] nodes_value = [] for node in queue: if node.left: nodes.append(node.left) if node.right: nodes.append(node.right) nodes_value.append(node.val) res.append(nodes_value) queue = nodes return res[::-1]
18dca538aae212a269fd1272386df357db3f819d
ec33d47aaf946c0ef7aefe5bd8c01ab72beacedf
/z_training.py
cb538d5f5dae7b05d89fd57993a400097f136dfc
[]
no_license
shivampandoh2000/Chatbot-Recommendation-Sys
881346438c6644b9d4a57abe5aa6c4c10082b77d
0fcdab74f8071b34aaecc90245007cd2328fe2fd
refs/heads/master
2022-12-17T03:31:24.131733
2020-01-03T09:16:10
2020-01-03T09:16:10
231,544,212
1
1
null
2022-11-29T16:28:04
2020-01-03T08:22:20
Python
UTF-8
Python
false
false
1,698
py
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer import os import random def get_feedback(): text = input() if 'yes' in text.lower(): return True elif 'no' in text.lower(): return False else: print('Please type either "Yes" or "No"') return get_feedback() no_res=["Sorry, couldn't answer it.","It seems I am unable to answer it."] bot=ChatBot('Main_Bot',read_only=True, storage_adapter='chatterbot.storage.MongoDatabaseAdapter', logic_adapters=[ { 'import_path':'chatterbot.logic.BestMatch', 'maximum_similarity_threshold':0.90, #'excluded_words':'["Artificial"]', 'input_text':'Hi', 'output_text':'Hi there', 'default_response':'I am sorry, but I do not understand.' }, {'import_path':'chatterbot.logic.MathematicalEvaluation'}, {'import_path':'chatterbot.logic.SpecificResponseAdapter', 'input_text':'Hi', 'output_text':'Hi there' }],database_uri='mongodb://localhost:27017/db13' ) trainer=ListTrainer(bot) for files in os.listdir('/home/shivam007/cht_bot/dbses/dses/'): data=open('/home/shivam007/cht_bot/dbses/dses/' + files ,'r').readlines() trainer.train(data) while True: message = input('You :') if message.strip() != 'Bye' or message.strip() != 'bye': reply=bot.get_response(message) print('confidence =', reply.confidence) print('ChatBot :',reply) elif message.strip()=='Bye' or message.strip()=='bye': print('ChatBot :Bye') break
736b79623797c54f3348fce18f4d3da4d49d040c
d4a34fcbf5125168f08222d7814196b23fa1ef39
/setup.py
e8b59831856fdebfa2fb44e4fb17a25b8f39250b
[ "Apache-2.0" ]
permissive
ntk148v/hypercontainer-py
41772fed1b9021db4285c935c33a7a5f306dc261
e1ea21b986d0d8d4339e9b3ddf8ac23954f13a56
refs/heads/master
2022-05-16T01:35:39.133653
2022-03-22T04:24:33
2022-03-22T04:24:33
100,349,612
0
0
NOASSERTION
2022-03-22T04:24:33
2017-08-15T07:09:22
Python
UTF-8
Python
false
false
1,671
py
#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" from setuptools import setup, find_packages with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ # TODO: put package requirements here ] setup_requirements = [ # TODO(ntk148v): put setup requirements (distutils extensions, etc.) here ] test_requirements = [ # TODO: put package test requirements here ] setup( name='hypercontainer_py', version='0.1.0', description="Python client for HyperContainer", long_description=readme + '\n\n' + history, author="Kien Nguyen Tuan ", author_email='[email protected]', url='https://github.com/ntk148v/hypercontainer_py', packages=find_packages(include=['hypercontainer_py']), include_package_data=True, install_requires=requirements, license="Apache Software License 2.0", zip_safe=False, keywords='hypercontainer_py', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], test_suite='tests', tests_require=test_requirements, setup_requires=setup_requirements, )
dda5a58793d1aabda39f28987589f813332b4b85
43f31db07775d1552193b8d05aca098b4ee5a659
/dice_or_no_dice/dice_dataset.py
fd6da80eae23398ece4948633acf95971ef9beaf
[]
no_license
edinpeter/ftfd
9a3b955ab13065d773a0e1c3b006fc739a7ba93e
23e85d7d67706be71802a16c1099f7cc334ca7a3
refs/heads/master
2021-09-15T02:34:03.603117
2018-03-04T14:26:49
2018-03-04T14:26:49
122,796,254
0
0
null
null
null
null
UTF-8
Python
false
false
2,835
py
import os import torch import random import torchvision import numpy as np from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils from skimage import io, transform, color import matplotlib.pyplot as plt from dice_image_dataset import DiceImageDataset from no_dice_image_dataset import NoDiceImageDataset class DiceDataset(Dataset): """ Dice Dataset """ def __init__(self, dice_dir, no_dice_dir, train, no_dice_max=200, train_percent=0.75, equal_datasets=False, transform=None): self.no_dice_dir = no_dice_dir self.dice_dir = dice_dir self.dice_image_dataset = DiceImageDataset(dice_dir) self.no_dice_image_dataset = NoDiceImageDataset(no_dice_dir) self.dice = list() self.no_dice = list() if train: last_dice_image = int(len(self.dice_image_dataset) * train_percent) last_no_dice_image = int(len(self.no_dice_image_dataset) * train_percent) last_no_dice_image = min(last_no_dice_image, no_dice_max) for i in range(0, last_dice_image): self.dice.append(self.dice_image_dataset[i]) for i in range(0, last_no_dice_image): self.no_dice.append(self.no_dice_image_dataset[i]) else: last_dice_image = int(len(self.dice_image_dataset) * (1.0 - train_percent)) last_no_dice_image = int(len(self.no_dice_image_dataset) * (1.0 - train_percent)) last_no_dice_image = min(last_no_dice_image, no_dice_max) for i in range(0, last_dice_image): self.dice.append(self.dice_image_dataset[i]) for i in range(0, last_no_dice_image): self.no_dice.append(self.no_dice_image_dataset[i]) self.data = self.dice + self.no_dice def __len__(self): return len(self.data) def __getitem__(self, id): dice_dataset = bool(random.getrandbits(1)) image = self.data[id]['image'] label = 1 if id < len(self.dice) else 0 filename = self.data[id]['filename'] image = np.transpose(image, (2,0,1)) return torch.from_numpy(image).float(), label, filename def len_dice(self): return len(self.dice) def len_no_dice(self): return len(self.no_dice) if __name__ == "__main__": d = DiceDataset("/home/peter/Desktop/dice/dice_small", "/home/peter/Desktop/dice/randoms_small/", train=False) print "Len set: ", len(d) print "Len dice: ", d.len_dice() print "Len nodice: ", d.len_no_dice() p = DataLoader(d, batch_size=4, num_workers=2, shuffle=True) dataiter = iter(p) images, labels, filenames = dataiter.next() print images[1] #plt.imshow(torchvision.utils.make_grid(images['image'])) plt.imshow(images[2]) plt.show()
1829d719397e47c63fad2fb9281e14daca1b201d
fb5554eeaf170ff2939ca716d158bafe5f17455f
/formats/__init__.py
7c36463bc23d0aedcd267efd88d807f73473c995
[]
no_license
hmacdope/QMTOOLS
438cc0adba917a87c1b0c3dfed836b554e12ef2e
b16634decb123b338424d9458063a1a6ac2d2764
refs/heads/master
2020-05-28T09:48:31.760914
2019-05-28T05:44:10
2019-05-28T05:44:10
188,961,340
0
0
null
null
null
null
UTF-8
Python
false
false
254
py
from .gaussian import GaussianInp as _g from .molpro import MolProInp as _m from .qchem import QChemInp as _qc from .qmoutp import PKARef from .gaussian_ import mass_read qm_packages = dict( gaussian = _g, molpro = _m, qchem = _qc )
43ce7a654a6759c19001b3a60945926d1e5e70c0
77275c84cc29d09527199edd9f120b920e781e66
/reg.py
00564c69b2b90a43c18a601521e870f70b085d28
[]
no_license
hyong2016/hyong
dccaeabda6547a83e0a77353bf2dd2f047da2273
9ea4b28f5f5498dfae7f1988c44a3436f8ab4163
refs/heads/master
2020-03-12T03:57:32.976494
2018-04-20T15:21:56
2018-04-20T15:21:56
130,434,686
0
0
null
null
null
null
UTF-8
Python
false
false
5,918
py
#coding=UTF-8 import logging, traceback import time, md5, random import datetime import MySQLdb import simplejson as json import config, db_util, tool logger = logging.getLogger(__name__) _g_uid = 0 def do_add_user(phone,uid,reg_pwd,agentId,expireDate,itype): if (itype == 0): atype = 0 #0:分钟数帐户 else: atype = 1 #1:正常预付费帐户 try: sql = "insert into v_field(field_name, pstn_num, field_desc, agent_id, fee_table_id, enable_flag, create_time, active_time) values ('%s','','',%d,%d,'1',now(),now())" %(uid, agentId, 2) ret = db_util.modify_db(sql) if not ret: logger.info("插入v_field表失败:%s" %phone) return False sql = "select field_id from v_field where field_name='%s' limit 1" % uid row = db_util.query_db(sql) if not row: logger.warning("v_field中不存在field_id,查询失败, please contact the system admin") return False fieldId = int(row['field_id']) if (itype != 1): #不是正常的终端用户注册均不赠送 sql = "insert into field_account(field_id,balance,discount,account_type,quota,money_id) values (%d,%d,100,%d,0,1)" % (fieldId, 0, atype) else: sql = "insert into field_account(field_id,balance,discount,account_type,quota,money_id) values (%d,%d,100,%d,0,1)" % (fieldId, config.given, atype) ret = db_util.modify_db(sql) if not ret: logger.info("插入field_account表失败:%s" %phone) return False sql = "select field_account_id from field_account where field_id='%s' limit 1" % fieldId row = db_util.query_db(sql) if not row: logger.warning("field_account中不存在field_account_id,查询失败, please contact the system admin") return False sql = "insert into user(user_type,user_name,reg_pwd,long_name,rep_name,email,phone,address,field_id,enable_flag,user_desc,create_time,active_time,valid_date) values('%s','%s','%s','%s','','','','',%d,'1','',NOW(),NOW(),'%s')" % (itype, uid, reg_pwd, phone, fieldId, expireDate) ret = db_util.modify_db(sql) if not ret: logger.info("插入user表失败:%s" %phone) return False sql = "select user_id from user where field_id='%s' limit 1" % fieldId row = db_util.query_db(sql) if not row: logger.warning("user中不存在user_id,查询失败, please contact the system admin") return False sql = "UPDATE agent SET customer=customer+1 WHERE agent_id='%s'" %agentId db_util.modify_db(sql) return fieldId except: logger.info("do_add_user proc exception: %s" % traceback.format_exc()) return False def get_uid(itype): try: if itype == 0: #1255577注册绑定,注意:如果注册用户超过5万,此查找将非常慢 limit = [2,3,4,5] imin = [10,100,1000,10000] imax = [99,999,9999,99999] while True: for i in limit: fld = str(i) + str(random.randint(imin[i-2], imax[i-2])) sql = "SELECT field_name FROM v_field WHERE field_name = '%s' LIMIT 1" %fld row = db_util.query_db(sql, 1) if (not row) or (not row['field_name']): break return fld global _g_uid if _g_uid: _g_uid = _g_uid + 1 else: sql = "SELECT field_name FROM v_field WHERE field_name >= '600000' ORDER BY field_id DESC LIMIT 1" row = db_util.query_db(sql, 1) if (not row) or (not row['field_name']): _g_uid = 600000 else: _g_uid = int(row['field_name'])+1 return _g_uid except : logger.info("get_uid proc exception: %s" % traceback.format_exc()) return None def register(phone,password,agentid,itype,ip=''): try: agent_id = int(agentid) except : logger.info("注册agentid=%s格式错误,用默认1" %agentid) agent_id = 1 if agent_id != -1: sql = "SELECT 1 FROM agent WHERE agent_id=%d LIMIT 1" %agent_id row = db_util.query_db(sql, 1) if not row: agent_id = 1 if (phone[0] >= '2' and phone[0] <= '9') or (not tool.number_deal(phone)): logger.info("注册手机号码格式错误") return '{"result":"-3"}' if (phone[0] == '0' and phone[1] == '1'): phone = phone[1:] uid = tool.check_phone_pwd(phone,password) if uid == -1: logger.info("密码错误:%s" %phone) return '{"result":"-2"}' elif uid: logger.info("登录请求成功:phone=%s pwd=%s uid=%s ip=%s" % (phone,password,str(uid),ip)) return '{"result":"0","uid":"%s"}' %(uid) elif agent_id == -1: logger.info("登录失败,账户未注册") return '{"result":"-1"}' itype = int(itype) #0:1255577业务之移动直拨 1:终端用户 2:代理商用户 uid = get_uid(itype) if not uid: logger.info("取UID异常:%s" %phone) return '{"result":"-13"}' expireDate = (datetime.datetime.now() + datetime.timedelta(days=30)).strftime('%Y-%m-%d %H:%M:%S') if ((agent_id == 236 or agent_id == 544 or agent_id == 534 or agent_id == 332 or agent_id == 764 or agent_id == 546 or agent_id == 215 or agent_id == 121) and (uid%3 == 0)): logger.info("agent_id:%s-->1" %agent_id) agent_id = 1 res = do_add_user(phone,uid,password,agent_id,expireDate,itype) if not res: #logger.info("添加用户信息失败:%s" %phone) return '{"result":"-1"}' logger.info("注册请求成功:phone=%s pwd=%s uid=%s ip=%s" % (phone,password,uid,ip)) return '{"result":"0","uid":"%s","field_id":"%s"}' %(uid, res)
[ "root@bogon.(none)" ]
root@bogon.(none)
76a6fea80e4b22bc5819066d3818f8e550984c3b
f3bd271bf00325881fb5b2533b9ef7f7448a75ec
/classes/_pz811.py
dce8157fdb79198a3fc175afd088f4c6978c1fe9
[]
no_license
obaica/xcp2k
7f99fc9d494859e16b9b0ea8e217b0493f4b2f59
6e15c2c95658f545102595dc1783f5e03a9e6916
refs/heads/master
2020-07-15T17:27:43.378835
2019-02-11T16:32:24
2019-02-11T16:32:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
402
py
from xcp2k.inputsection import InputSection class _pz811(InputSection): def __init__(self): InputSection.__init__(self) self.Section_parameters = None self.Parametrization = None self.Scale_c = None self._name = "PZ81" self._keywords = {'Scale_c': 'SCALE_C', 'Parametrization': 'PARAMETRIZATION'} self._attributes = ['Section_parameters']
a2780c1dd829a1ceec61444b55ce78e22514d36e
356684be03e7e2538cfbfb586d0fcd502ce9ecfd
/results_server/setup.py
c2107825b23b660d1b957d181239afba1eef8525
[]
no_license
jonstewart/picarus
b31ef9d7a7aa9582317bf695289abc18dc06a86d
e141996f24cc66023cafb3f9033932ab1dce0484
refs/heads/master
2021-01-23T22:06:55.831163
2011-08-15T02:40:35
2011-08-15T02:40:35
1,944,336
0
0
null
null
null
null
UTF-8
Python
false
false
311
py
#!/usr/bin/env python from distutils.core import setup setup(name='results_server', version='0.0.1', packages=['results_server'], author='Andrew Miller', author_email='[email protected]', license='GPL', package_data={'results_server':['static/*/*','*.html']} )
08b6e91749c63df89a1ebe4e8765d80330714a7b
6871a311cc143af01542f21811e8ff385fe10ecb
/tools/classifi_mode/classifi_data_process.py
f750ab1b7151ae56afe6df88ace1c503eb674bd3
[]
no_license
freak-junhao/igarss2021_dse
1534a40f824df70f1bf329c3f92781851e2a5a20
dd37a504e7cee335e52d86f02284f8b9a1fec62f
refs/heads/main
2023-03-24T03:54:30.447811
2021-03-21T11:23:52
2021-03-21T11:23:52
349,913,920
0
0
null
null
null
null
UTF-8
Python
false
false
9,629
py
from skimage.io import imread from PIL import Image import numpy as np import random import os from os.path import join import shutil import tqdm import argparse def make_dirs(path): if os.path.exists(path) is not True: os.makedirs(path) def read_txt(txt_dir): txt_list = open(txt_dir) txt = txt_list.readlines() txt = [i.strip() for i in txt] txt_list.close() return txt def change_num(arr, index, num): for x, y in index: arr[x][y] = num return arr def transform_label(label, interest_class): x, y = label.shape label_new = np.zeros((x, y), dtype=np.uint8) for i in interest_class: index = np.argwhere(label == i) label_new = change_num(label_new, index, 1) return label_new def select_channels(channel_lst, out_dir, in_dir, is_train=True): channels = read_txt(channel_lst) tile_list = os.listdir(in_dir) outpath_name = 'Train/' if is_train else 'Val' for tile in tile_list: pic_list = os.listdir(join(in_dir, tile)) index_list = [pic_list.index(y) for y in channels] target_tile_path = join(out_dir, outpath_name, tile) make_dirs(target_tile_path) for mv in index_list: old_file = join(in_dir, tile, pic_list[mv]) new_file = join(out_dir, outpath_name, tile, pic_list[mv]) if os.path.exists(new_file) is not True: shutil.copyfile(old_file, new_file) if is_train: gt_name = "groundTruth.tif" shutil.copyfile(join(in_dir, tile, gt_name), join(out_dir, outpath_name, tile, gt_name)) def mean_std(channel_lst, train_dir, val_dir): channels = read_txt(channel_lst) class_list = [ train_dir, val_dir ] all_mean = [] all_std = [] print("Start compute mean : ") for i in tqdm.tqdm(channels): channel_mean = 0 pixel_num = 0 for t_or_v in class_list: tile_lst = os.listdir(t_or_v) pixel_num += len(tile_lst) for tile in tile_lst: image_path = join(t_or_v, tile, i) image = imread(image_path) channel_mean += np.sum(image) pixel_num *= 800 * 800 mean = channel_mean / pixel_num all_mean.append(mean) mean = np.asarray(all_mean, dtype=np.float32) np.savetxt('./txt_files/mean.txt', mean, fmt="%.4f") print("Start compute std : ") for i in tqdm.trange(len(channels)): channel_std = 0 pixel_num = 0 for t_or_v in class_list: tile_lst = os.listdir(t_or_v) pixel_num += len(tile_lst) for tile in tile_lst: image_path = join(t_or_v, tile, channels[i]) image = imread(image_path) _mean = all_mean[i] channel_std += np.sum((image - _mean) ** 2) pixel_num *= 800 * 800 std = np.sqrt(channel_std / pixel_num) all_std.append(std) all_std = np.asarray(all_std, dtype=np.float32) np.savetxt('./txt_files/std.txt', all_std, fmt="%.4f") def pic_cut(out_dir, in_dir, cut_mode=None, is_train=True, class_num=2): if cut_mode is None: cut_mode = [1, 3] patch_num = np.zeros(class_num, dtype=np.uint16) tile_list = os.listdir(in_dir) count = 1 for tile in tile_list: ch_lst = os.listdir(in_dir + tile) # channels_list if is_train: print(tile + ' {}-train: '.format(count)) ch_lst.remove("groundTruth.tif") else: print(tile + ' {}-test: '.format(count)) count += 1 full_tif = [] # multiple channels for channel in ch_lst: read_tif = Image.open(join(in_dir, tile, channel)) read_tif = np.asarray(read_tif, dtype=np.float64) full_tif.append(read_tif) full_tif = np.asarray(full_tif, dtype=np.float64) gt = '' # ground truth if is_train: gt = Image.open(join(in_dir, tile, 'groundTruth.tif')) gt = np.asarray(gt, dtype=np.uint8) if class_num < 4: gt = transform_label(gt, cut_mode) gt_new = Image.fromarray(np.uint8(gt)) gt_new.save(join(in_dir, tile, 'groundTruth_new.tif')) else: patch_num[0] = 0 for width in tqdm.trange(16): for height in range(16): w_start = int(50 * width) h_start = int(50 * height) patch = full_tif[:, w_start:w_start + 50, h_start:h_start + 50] if is_train: label_rgb = gt[width][height] patch_num[label_rgb] += 1 save_path = join(out_dir[0], out_dir[label_rgb + 1], "patch_{:0>4d}/".format(patch_num[label_rgb])) else: patch_num[0] += 1 save_path = join(out_dir, tile, "patch_{:0>3d}/".format(patch_num[0])) make_dirs(save_path) channel_size, _, _ = patch.shape for i in range(channel_size): patch_save = patch[i] patch_save = Image.fromarray(np.float64(patch_save)) patch_save.save(join(save_path, ch_lst[i])) def channel_aver(name_list, out_dir, in_dir, is_train=True): combined_name = name_list[0][-7:] outpath_name = 'Train/' if is_train else 'Val' tile_list = os.listdir(in_dir) for tile in tile_list: target_tile_path = join(out_dir, outpath_name, tile) make_dirs(target_tile_path) array_temp = np.zeros((800, 800)) for pic in name_list: read_tif = Image.open(join(in_dir, tile, pic)) read_tif = np.asarray(read_tif, dtype=np.float64) array_temp += read_tif array_temp /= len(name_list) save_path = join(out_dir, outpath_name, tile, combined_name) saved = Image.fromarray(np.float64(array_temp)) saved.save(save_path) def create_train_list(out_dir, in_dir): class_list = os.listdir(in_dir) train = [] for cls in class_list: cls_num = 1 - class_list.index(cls) pic_list = os.listdir(join(in_dir, cls)) random.shuffle(pic_list) train_list = ["{}/{} {}".format(cls, i, cls_num) for i in pic_list] train.extend(train_list) random.shuffle(train) train = np.asarray(train) np.savetxt(join(out_dir, "train.txt"), train, fmt='%s') def create_val_list(out_dir, in_dir): tile_list = os.listdir(in_dir) val = [] for tile in tile_list: patch = os.listdir(join(in_dir, tile)) patch = ["{}/{} 0".format(tile, i) for i in patch] patch.sort() val.extend(patch) val = np.asarray(val) np.savetxt(join(out_dir, "val.txt"), val, fmt='%s') def generate_list(output_path, input_path): create_train_list(output_path, input_path[0]) create_val_list(output_path, input_path[1]) def trans_to_image(result_lst, tile_dir, out_dir): tile_order = os.listdir(tile_dir) count = 0 for k in tile_order: # 19 image = [] for i in range(16): row = [] for j in range(16): result_cls = result_lst[count] count += 1 row.append(result_cls) image.append(row) image_save = np.asarray(image, dtype=np.uint8) image_save = Image.fromarray(np.uint8(image_save)) image_save.save(join(out_dir, "{}.tif".format(k[4:]))) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Trains ResNeXt on IEEE GRSS') parser.add_argument('select_txt', type=str, help='Selected channels txt.') parser.add_argument('--classifi_mode', type=int, default=0, help='Classify mode choice.') args = parser.parse_args() data_root = "/root/data/cls/" classifi_path = join(data_root, "classifi_data_/") data_path = [join(data_root, "Train/"), join(data_root, "Val/")] selected_txt = "./txt_files/{}.txt".format(args.select_txt) select_channels(selected_txt, classifi_path, data_path[0]) select_channels(selected_txt, classifi_path, data_path[1], is_train=False) """average_path = "./txt_files/average_list.txt" average_lst = read_txt(average_path) average_path = join(classifi_path, "Average/") channel_aver(average_lst, average_path, data_path[0]) channel_aver(average_lst, average_path, data_path[1], is_train=False) """ """ train_cut_path = ["../../data/classifi_data/cut_train/", "H_without_E/", "NoH_without_E/", "H_with_E/", "NoH_with_E/"] """ train_cut_path = [ ["/root/data/cls/classifi_data_/cut_train/", "NoH/", "H/"], ["/root/data/cls/classifi_data_/cut_train/", "E/", "NoE/"], ["/root/data/cls/classifi_data_/cut_train/", "Others", "H_without_E/"], ] set_one = [ [1, 3], [1, 2], [1], ] train_data_path = "/root/data/cls/classifi_data_/Train/" pic_cut(train_cut_path[args.classifi_mode], train_data_path, cut_mode=set_one[args.classifi_mode]) val_cut_path = "/root/data/cls/classifi_data_/cut_val" val_data_path = "/root/data/cls/classifi_data_/Val/" pic_cut(val_cut_path, val_data_path, is_train=False) generate_list(classifi_path, [train_cut_path[args.classifi_mode][0], val_cut_path]) mean_std("./txt_files/{}.txt".format(args.select_txt), train_data_path, val_data_path)
ee9d810a2db28974058a23b562e6a40f9e7955ff
00cc592e2c1bda6b77ab11e9f6aed7ed02b95dfe
/scripts/publishBoatPosition.py
4a3cc3adc5cd469ae949f1ac8167002c279d6cd0
[]
no_license
ChristianHorst/hippocampus_trajectory
101f516390ff27d11376800d8a8048bfa009f693
9b5d221f572726d3592be8e6ed1534e798c424f6
refs/heads/master
2023-02-10T07:20:51.510178
2021-01-08T18:02:03
2021-01-08T18:02:03
276,424,085
0
0
null
null
null
null
UTF-8
Python
false
false
1,416
py
#!/usr/bin/env python import numpy as np from pyquaternion import Quaternion import rospy import tf from geometry_msgs.msg import Pose, PoseArray, PoseStamped from visualization_msgs.msg import Marker, MarkerArray publisher_marker = rospy.Publisher('/pose_boat_NED', Marker, queue_size=1) def callback(msg): """""" global rate marker = Marker() marker.header.frame_id = "global_tank" marker.id = 0 marker.type = marker.MESH_RESOURCE marker.action = marker.ADD marker.scale.x = 1 marker.scale.y = 1 marker.scale.z = 1 marker.color.r = 1.0 marker.color.g = 0 marker.color.b = 0 marker.color.a = 1 # transparency marker.pose.orientation.w = msg.pose.orientation.w marker.pose.orientation.x = msg.pose.orientation.x marker.pose.orientation.y = msg.pose.orientation.y marker.pose.orientation.z = msg.pose.orientation.z marker.pose.position.x = msg.pose.position.x # x marker.pose.position.y = msg.pose.position.y # y marker.pose.position.z = msg.pose.position.z # z marker.mesh_resource = "package://hippocampus_test/models/uuv_hippocampus.stl" publisher_marker.publish(marker) def main(): rospy.init_node('rviz_boatpose') global rate rate = rospy.Rate(30) rospy.Subscriber("/uuv00/pose_px4", PoseStamped, callback) while not rospy.is_shutdown(): pass if __name__ == '__main__': main()
45afff34446a7a9e266886806b4cf379237e3bf8
5e8b4f7feff7e02e83ca7f0d96e0047861984936
/leetcode/leetcode_intervals.py
dece262e04127ae9724b73e216bb997671575035
[ "Apache-2.0" ]
permissive
yenbohuang/online-contest-python
2f494809c50e2daff377f4c3fee5daa1140f368a
c60b332866caa28e1ae5e216cbfc2c6f869a751a
refs/heads/master
2022-12-01T11:00:40.888395
2020-08-05T06:59:29
2020-08-05T06:59:29
277,729,126
0
0
null
null
null
null
UTF-8
Python
false
false
420
py
class IntervalQuestions: def overlap(self, i1, i2): """ :type i1: List[] :type i1: List[] :rtype: boolean """ front = i1 end = i2 if i1[0] > i2[0]: front = i2 end = i1 return (front[0] <= end[0] and front[1] >= end[1]) or \ (front[0] <= end[0] and front[1] > end[0]) or \ (front[1] == end[0])
3f468c8ac6451af651eee3e26dfcf89fa14ffa1e
89201cc4dd51fc4f8c7b29d10e12e571031bcb63
/Project3/functions_z1.py
dae8464d8e3f583e99ee1f70324fc6903f7f4b02
[]
no_license
Ada1248/Grafy
ad9321b1a693f83bbddd9b65bfb17d96e5fb05d4
cb9e3598bc8c4a2e882911efe33a14fd69bc044a
refs/heads/master
2022-07-31T22:23:07.058305
2020-05-21T13:37:49
2020-05-21T13:37:49
246,426,119
0
1
null
null
null
null
UTF-8
Python
false
false
2,459
py
###################################### # funkcja transponująca macierz def transpose(matrix): t_matrix = [[0 for _ in range(len(matrix))] for _ in range(len(matrix[0]))] for i in range(len(matrix)): for j in range(len(matrix[0])): t_matrix[j][i] = matrix[i][j] return t_matrix #zmiana listy sąsiedztwa na macierz sąsiedztwa def adj_list_to_adj_matrix(li): size = range(len(li)) return [[1 if i in el else 0 for i in size] for el in li] #zamiana listy na macierz incydencji def adj_list_to_i_matrix(adj_list): adj_matrix = [] i_matrix = [] adj_matrix = adj_list_to_adj_matrix(adj_list) i_matrix = adj_matrix_to_i_matrix(adj_matrix) return i_matrix #zmiana macierzy sąsiedztwa na listę sąsiedztwa def adj_matrix_to_list(adj_matrix): return [[idx for idx, val in enumerate(el) if val] for el in adj_matrix] #zmiana macierzy sąsiedztwa na macierz incydencji def adj_matrix_to_i_matrix(adj_matrix): t_i_matrix = [] i_matrix = [] number_of_edge = 0 for i in range(len(adj_matrix)): for j in range(len(adj_matrix)): if i > j and adj_matrix[i][j] == 1: number_of_edge += 1 t_i_matrix = [[0 for _ in range(len(adj_matrix))] for _ in range(number_of_edge)] edge = 0 for i in range(len(adj_matrix)): for j in range(len(adj_matrix)): if i > j and adj_matrix[i][j] == 1: t_i_matrix[edge][i] = 1 t_i_matrix[edge][j] = 1 edge += 1 i_matrix = transpose(t_i_matrix) return i_matrix #zamiana macierze incydencji na macierz sąsiedztwa def i_matrix_to_adj_matrix(i_matrix): adj_matrix = [] t_i_matrix = transpose(i_matrix) adj_matrix = [[0 for _ in range(len(t_i_matrix[0]))] for _ in range(len(t_i_matrix[0]))] indexes = [] for i in range(len(t_i_matrix)): indexes.clear() for j in range(len(t_i_matrix[0])): if t_i_matrix[i][j] == 1: indexes.append(j) if not len(indexes) == 0: for j in range(len(adj_matrix[0])): adj_matrix[indexes[0]][indexes[1]] = 1 adj_matrix[indexes[1]][indexes[0]] = 1 return adj_matrix def i_matrix_to_list(i_matrix): adj_list = [] adj_matrix = [] adj_matrix = i_matrix_to_adj_matrix(i_matrix) adj_list = adj_matrix_to_list(adj_matrix) return adj_list ######################################
2bfdf5f05d657a916d3b89394a6bdd2003099665
093945c186582c63552ce61505a1d368c546b890
/Desafios/045.py
55ac801dd6e9ab51900fbe091d4fc7e4b57f937c
[]
no_license
erickapsilva1/desafios-python3-cev
11b9619765cbecd97e7d6481144658967a5f0040
ed1e607b905a24676d477b6777bff9743d4d30cc
refs/heads/master
2023-07-03T22:52:38.726401
2021-08-03T23:09:30
2021-08-03T23:09:30
392,478,473
0
0
null
null
null
null
UTF-8
Python
false
false
1,379
py
# programa que jogue jokenpô import random opcao = int(input('''Escolha: --- 1. Pedra --- 2. Papel --- 3. Tesoura --->''')) sorteio = int(random.randrange(1, 3)) if opcao == 1: escolha = 'Pedra' elif opcao == 2: escolha = 'Papel' elif opcao == 3: escolha = 'Tesoura' if sorteio == 1: escolha2 = 'Pedra' elif sorteio == 2: escolha2 = 'Papel' elif sorteio == 3: escolha2 = 'Tesoura' print('_____________________') print(' JOKENPÔ!!!!') print('') print('JOGADOR: ', escolha) print('PC: ', escolha2) print('_____________________') print('') if sorteio == 1 and opcao == 1 or sorteio == 2 and opcao == 2 or sorteio == 3 and opcao == 3: print('EMPATE!, pois {} é igual a {}'.format(escolha, escolha2)) elif opcao == 1 and sorteio == 3: print('Jogador VENCEU, pois {} ganha de {}'.format(escolha, escolha2)) elif opcao == 2 and sorteio == 1: print('Jogador VENCEU, pois {} ganha de {}'.format(escolha, escolha2)) elif opcao == 3 and sorteio == 2: print('Jogador VENCEU, pois {} ganha de {}'.format(escolha, escolha2)) elif opcao == 1 and sorteio == 2: print('PC VENCEU, pois {} ganha de {}'.format(escolha2, escolha)) elif opcao == 2 and sorteio == 1: print('PC VENCEU, pois {} ganha de {}'.format(escolha2, escolha)) elif opcao == 3 and sorteio == 1: print('PC VENCEU, pois {} ganha de {}'.format(escolha2, escolha))
1d9dc2360837dc70533d48d4fb614d7f3899017a
ea352574d99c65e70662473815467b9638fee821
/wsgiapp.py
5d0b2da729ca0524c2e9c4f35c790b003325d152
[]
no_license
dogezhou/simple_web_server
360eafff013641ac8b232927d87a4e0acf97d9cc
7375e7f12de0533807702c31b4515ef1c8f98257
refs/heads/master
2021-01-12T14:51:09.507176
2016-10-28T13:00:39
2016-10-28T13:00:39
72,107,231
0
0
null
null
null
null
UTF-8
Python
false
false
1,257
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import urllib.parse def run_application(application): """Server code.""" # This is where an application/framework stores # an HTTP status and HTTP response headers for the server # to transmit to the client headers_set = [] # Environment dictionary with WSGI/CGI variables environ = {} def start_response(status, response_headers, exc_info=None): headers_set[:] = [status, response_headers] # Server invokes the ‘application' callable and gets back the # response body result = application(environ, start_response) # Server builds an HTTP response and transmits it to the client def app(environ, start_response): """A barebones WSGI application. This is a starting point for your own Web framework :) """ status = '200 OK' response_headers = [('Content-Type', 'text/html')] start_response(status, response_headers) print(environ) name = environ['PATH_INFO'] # >>> urllib.parse.unquote('/%E5%91%A8%E4%BC%9F') # '/周伟' # 把 URL 解码 name = urllib.parse.unquote(name)[1:] # '周伟' return ['<h1>Hello {name} from a simple WSGI application!</h1>'.format(name=name)] # run_application(app)
543826d5d0d30a109322d67293b3f853877f7b14
fb33b689b8ebd54695828dab3f9d1db074203d34
/practice/test/testadb/test_threading.py
c75e487ad28080f27e89632b45fcc412e4ca8bd9
[]
no_license
takumikaka/workspace
471ab6e60d47f61ae36e4b95e8d58b0840188f65
f72946ff5f46b549dfab51a0038f05478b301490
refs/heads/master
2021-05-06T11:58:24.334256
2019-03-22T08:32:18
2019-03-22T08:32:18
113,008,406
1
0
null
2018-02-23T12:28:54
2017-12-04T07:14:00
Python
UTF-8
Python
false
false
201
py
# coding:UTF-8 -*- import time import threading def run(): print("this is test....") def tick(): run() timer = threading.Timer(5, tick) timer.start() def main(): tick() main()
4cf6029856b2d611bf0468b0fc89f179b151ac7c
624ef425d93cca8639e7b3adc82b3165b815c61e
/utils/Anova.py
6938842688cd84532a7916e989bd65827ba4a773
[ "MIT" ]
permissive
pptrick/Fittslaw-Analyzer
ee7eec7453667612151cb779aaf2c1561b2f11a4
3ee34aff6d8fd28a93fc111d2c721d1653da74b9
refs/heads/main
2023-02-28T21:11:42.042152
2021-02-03T03:30:37
2021-02-03T03:30:37
312,497,020
3
1
null
null
null
null
UTF-8
Python
false
false
904
py
import pandas as pd from statsmodels.formula.api import ols from statsmodels.stats.anova import anova_lm def multi_analyze(raw_data, params): # change data format to string for d in raw_data: d['width'] = str(d['width']) d['distance'] = str(d['distance']) pd_data = pd.DataFrame(raw_data) columns = pd_data.columns assert('time' in columns) formula = "time~ " for i in range(len(params)): assert(params[i] in columns) formula = formula + f" {params[i]} " if i<len(params)-1: formula = formula + "+" anova_results = anova_lm(ols(formula,pd_data).fit()) print("====================== anova analyze report =======================") print(anova_results) print(" ") # change data format back to float for d in raw_data: d['width'] = float(d['width']) d['distance'] = float(d['distance'])