def __init__(self): super().__init__() exitShortcut = QShortcut(QKeySequence('Ctrl+W'), self, qApp.quit) self.connect = Connect() self.all_models = self.connect.session.query(Models).all() self.table = self.table = QTableWidget(5, 3, self) self.setTableHeaders() self.organiseTable() self.populate('M1') self.createconnections() self.table.move(100, 100) self.createList() self.list.currentItemChanged.connect(self.listClicked) # print('Current Item :', self.list.currentItem()) self.positionWidgets() self.mainhbox = QHBoxLayout() self.mainhbox.addWidget(self.list) self.mainhbox.addWidget(self.table) self.setLayout(self.mainhbox) self.setGeometry(0, 0, 640, 440) self.show()
def CreateSuggestionsTable(suggestions_dir): db = Connect() suggestions = db.suggestions # By default, the suggestions for a particular host will be an empty list of # pathogens and an empty list of controls. all_suggestions = defaultdict(lambda: defaultdict(lambda: { 'pathogens': [], 'controls': [] })) # Each suggestion file is read one by one. for host_suggestions_file in os.listdir(suggestions_dir): match = re.match(r'(.*)_(\w+)_(controls|pathogens).txt', host_suggestions_file) if not match: logging.info('Skipping %s' % host_suggestions_file) continue else: logging.info('Working on %s' % host_suggestions_file) host = match.group(1) subtype = match.group(2) is_p = 1 if match.group(3) == 'pathogens' else 0 # Stores all organism ids that were matched. matched = [] # Reads the organism names from the hits table and creates a mapping from # host cannonical name to host id. hits = db['%s_hits' % host] organisms = {} for result in hits.find({}, {'organism': 1}): organisms[_NormalizedName(result['organism'])] = str(result['_id']) # For each line in the suggestions file, checks if the cononical organism # name is a prefix of an organism in the hits collection. full_path = os.path.join(suggestions_dir, host_suggestions_file) with open(os.path.join(suggestions_dir, host_suggestions_file)) as f: for suggestion in f: target_name = _NormalizedName(suggestion) for organism_name, organism_id in organisms.iteritems(): if organism_name.startswith(target_name): matched.append(organism_id) # Adds the list of pathogen or control suggestions to the host. all_suggestions[host][subtype][ 'pathogens' if is_p else 'controls'] = matched # Adds the suggestions per organism to the mongo collection. for host, val in all_suggestions.iteritems(): try: suggestions.insert({'host': host, 'suggestions': val}) except DuplicateKeyError: pass # There should only be one entry per host. suggestions.ensure_index([('host', pymongo.ASCENDING)], unique=True, dropDups=True)
def __init__(self): self.connection = Connect('ora-scsp.srv.mst.edu', 1521, os.environ['DBEAVER_USERNAME'], os.environ['DBEAVER_PASSWORD'], 'scsp.mst.edu') self.connection.establish_connection()
def __init__(self): super().__init__() exitShortcut = QShortcut(QKeySequence('Ctrl+W'), self, qApp.quit) self.connect = Connect() self.all_models = self.connect.session.query(Models).all() self.labelkey_name = QLabel('Name', self) self.labelkey_parts = QLabel('Parts', self) self.labelkey_current_quantity = QLabel('Current Quantity', self) self.labelval_name = QLabel('Name', self) self.labelval_parts = QLabel('Parts', self) self.labelval_current_quantity = QLabel('Current Quantity', self) self.showInfo('M1') self.list = QListView(self) self.list_model = QStandardItemModel(self.list) self.createList() print('Current index of view: ', self.list.currentIndex()) self.hboxlayout = QHBoxLayout() self.label_grid = QGridLayout() self.buildLayout() self.show()
def query_page(request): dbchoice1 = base64.decodestring(request.GET.get('dbchoice1')) page_id = request.GET.get('page_id') sqltext = open('/tmp/1.txt', 'r').read() db_connect = Connect(host=dbchoice1, sqltext1=sqltext) (result_desc, messages, page_counts) = db_connect.connectexec(page_id=int(page_id)) if re.compile(r'v\$').search(sqltext) or re.compile(r'V\$').search( sqltext) or re.compile(r'dba_\$').search(sqltext) or re.compile( r'DBA_\$').search(sqltext): cols = [] rows = [] for row in messages: for col in row: cols.append(str(col).decode('utf-8', 'ignore')) rows.append(cols) messages = rows return render_to_response( 'result.html', { 'dbchoice1': base64.encodestring(dbchoice1), 'messages': messages, 'page_counts': page_counts, 'result_descs': result_desc }) else: return render_to_response( 'result.html', { 'dbchoice1': base64.encodestring(dbchoice1), 'messages': messages, 'page_counts': page_counts, 'result_descs': result_desc })
def run(self): print("Welcome to Bronzer") connect = Connect() connect.startConnect() welcome_msg = connect.retriveMsg() print(welcome_msg) handler = Handler() while (True): cmd = input("Bronzer>> ") if not cmd.strip(): continue if cmd.strip() == "exit": connect.sendCmd(cmd) break else: print(handler.handle(cmd)) # if cmd.strip() == "shell": # os.system("adb shell") # msg = connect.sendCmd(cmd) # print(msg) # handler = Handler() # rtn_msg = handler.handle(cmd) # print(rtn_msg) connect.stopConnect() exit(0)
def connect(self, *args): """ Called via our connect thread... Attempt to create a new connection with our Connect class and store the value to our self.connection instance variable """ # With the potential dropped internet connections, sessions ending and more, # which have caused errors, it's easier and safer if we attempt to create a # new instance of Connect which provides a clean session. Future improvements # could be made to rectify this action to help memory/performance. self.connection = Connect() self.title = GumpyTitles.CONNECTING try: self.connection.connect() rumps.notification(GumpyTitles.CONNECTION_SUCCESS, '', 'Have a cookie') # This explicitly calls get_tickets method on a rumps.Timer (new thread) interval if self.refresh_interval_timer is None: self.refresh_interval_thread() else: # If this isn't the first time connect is being called, we will update # our ticket results by refreshing our interval thread which calls get_tickets self.refresh_interval_thread(force_refresh=True) except Exception as e: rumps.alert(e) finally: self.title = GumpyTitles.GUMPY
def get(team): a = Connect() a.connect() page = 1 with open('twitter_scrape_file.txt', 'a') as file: while True: re = requests.get( 'https://sportspyder.com/teams/{}/tweeter_types/3/tweets?page={}' .format(team, page)) bs = BeautifulSoup(re.content, 'html.parser') tweets = bs.find_all('div', attrs={'class': 'twitter_content'}) if len(tweets) == 0: return for i in tweets: t = Tweet(team, i.find('span', attrs={ 'class': 'username' }).text, i.find('span', attrs={ 'class': 'time' }).text, i.find('div', attrs={ 'class': 'text' }).text) file.write(str(t.time)) file.write('\n') a.insert(t.insert()) page += 1 print(page)
def __init__(self): Config.__init__(self) self.si = Connect().si self.utl = Utils(label='wait') self.queue = Queue() self.content = self.si.RetrieveContent() self.vms = [] self.MAX_DEPTH = 10 self.migration_between_hosts = self.migration_possible(self.esxi_hosts) self.migration_between_datasources = self.migration_possible(self.ds_names)
def __init__(self): id = unique_id() self.hex_id = b'{:02x}{:02x}{:02x}{:02x}'.format( id[0], id[1], id[2], id[3]) # Alimentação self.p4 = Pin(4, Pin.OUT) self.p4.value(1) # Buzzer e LED self.p2 = Pin(2, Pin.OUT) # LED self.p5 = Pin(5, Pin.OUT) # BUZZER # Deixa pré-definido para não reenviar, caso se conecte a rede, ativa o reenvio self.reenvio = True # Botão self.alimentacao = Timer(2) self.p15 = Pin(15, Pin.IN, Pin.PULL_DOWN) self.p15.irq(trigger=Pin.IRQ_RISING, handler=self.button) # Acelerômetro self.z = ADC(Pin(32)) self.y = ADC(Pin(35)) self.x = ADC(Pin(34)) # Pino da bateria self.p33 = ADC(Pin(33)) self.p33.width(ADC.WIDTH_10BIT) self.p33.atten(ADC.ATTN_11DB) # Timer da bateria self.bateria_timer = Timer(1) self.bateria_timer.init(period=1800000, mode=Timer.PERIODIC, callback=self.bateria) self.acelerometro() self.t_rede = Timer(-1) self.t_rede.init(period=300000, mode=Timer.PERIODIC, callback=self.reiniciar) self.c = Connect() self.connection = self.c.start() self.client = Client(self.connection) self.t_rede.deinit() self.t_reenvio = Timer(3) self.reenvio = False
def result(request): logger = logging.getLogger('testdj') key = request.POST.get('m1') dbchoice1 = request.POST.get('dbchoice') p = re.compile(r'^select') if key == '': return render_to_response('search.html', {'error': 'NULL'}) if not (p.search(key)): return render_to_response('search.html', {'error': 'notValidSelect'}) if re.compile(r'for update').search(key): return render_to_response('search.html', {'error': 'forUpdate'}) logger.warning('SQL: ' + key + ' DB EXEUTION:' + dbchoice1 + ' USER: '******'REMOTE_ADDR']) db_connect = Connect(host=dbchoice1, sqltext1=key) (result_desc, messages, page_counts) = db_connect.connectexec() p2 = re.compile(r'ORA-') if (p2.search(str(messages))): return render_to_response('search.html', {'dberrormsg': messages}) else: open('/tmp/1.txt', 'w+').write(key) if re.compile(r'v\$').search(key) or re.compile(r'V\$').search( key) or re.compile(r'dba_\$').search(key) or re.compile( r'DBA_\$').search(key): cols = [] rows = [] for row in messages: for col in row: cols.append(str(col).decode('utf-8', 'ignore')) rows.append(cols) messages = rows return render_to_response( 'result.html', { 'dbchoice1': base64.encodestring(dbchoice1), 'messages': messages, 'page_counts': page_counts, 'result_descs': result_desc }) else: return render_to_response( 'result.html', { 'dbchoice1': base64.encodestring(dbchoice1), 'messages': messages, 'page_counts': page_counts, 'result_descs': result_desc })
def __init__(self): self.hotelAttributes = [ "name", "pageLink", "description", "address", "city", "nation", "numberReview", "averageVote", "position", "cleanliness", "service", "qualityPrice" ] self.reviewAttributes = ["reviewer", "text", "vote", "month", "year"] self.typeStatistics = [ "averageVote", "position", "cleanliness", "service", "qualityPrice" ] self.classValutation = ["none", "bad", "average", "good"] self.columns = os.popen('stty size', 'r').read().split()[1] self.connection = Connect() self.graphConnection = GraphConnect()
def connect(): win = Connect() win.setWindowTitle('FASWU') r = win.showModal() if r: global ip, port ip = win.ip.text() port = win.port.text() print(ip) print(port) con = win.con if con == 1: print('server clicked...') server(ip, port) elif con == 2: print('client clicked...') client(ip, port)
def main(): params = [ "&", "2", "-4508.7", "-4508.7", "400", "015", "165", "2", "1", "1", "500", "0" ] test = Connect() test.importParam(params) mode_num = input("Enter 1 for OCP, 2 for ASV: ") if (mode_num == '1'): test.readOCP() print(test.ocpData) print(test.ocp_average) if (mode_num == '2'): test.readData() plt.plot(test.xData, test.yData, 'r-') plt.title("Potential: {}, Scan Rate: {}, Gain: {}".format( params[3], params[4], params[5])) plt.show()
def __init__(self, training=False, tensorboard=False, graph=False, lr=1e-5, gamma=0.95, batch=5000, sample=100, epis=250): # HYPER PARAMETERS self.LEARNING_RATE = lr self.GAMMA = gamma self.EXPLORE_START = 0.95 self.EXPLORE_STOP = 0.01 self.DECAY_RATE = 1e-4 self.BATCH_SIZE = batch self.SAMPLE_SIZE = sample self.N_EPISODES = epis self.NAME = f"lr({self.LEARNING_RATE})_gamma({self.GAMMA})_batch({self.BATCH_SIZE})_sample({self.SAMPLE_SIZE})" print(self.NAME) self.memory = deque(maxlen=100000) self.last_dist = 0 self.conn = Connect() self.create_dqn() print("Model successfully set up!") if training: if tensorboard: self.tensorboard() reward, loss = self.train(tensorboard) if graph: self.graph(reward, loss) else: self.run() self.conn.close()
def __init__(self): super().__init__() self.connect = Connect() self.all_stock = self.connect.session.query(Models).all() self.setGeometry(0, 0, 640, 440) self.setWindowTitle('JPro') # self.setStyleSheet('background-color: #444444') self.buildTable() self.setData(self.all_stock) self.bargraph = PlotCanvas(self, self.connect, width=4, height=3) self.bargraph.move(0, 0) iboxlayout = QHBoxLayout() iboxlayout.addWidget(self.table) iboxlayout.addWidget(self.bargraph) self.setLayout(iboxlayout) self.show()
def __init__(self): super().__init__() exitShortcut = QShortcut(QKeySequence('Ctrl+W'), self, qApp.quit) self.connect = Connect() self.all_models = self.connect.session.query(Models).all() self.labelval_name = QLabel('Model / 模型 ', self) self.labelkey_parts = QLabel('Parts / 零件', self) self.labelkey_current_quantity = QLabel('Current Quantity / 数量', self) self.labelval_parts = QLabel('N/A', self) self.labelval_current_quantity = QLabel('N/A', self) self.createList() self.list.currentItemChanged.connect(self.listClicked) # print('Current Item :', self.list.currentItem()) self.positionWidgets() self.styling() self.setGeometry(0, 0, 640, 440) self.show()
from connect import Connect conn1 = Connect() cur = conn1.connectdb() cur01 = cur.cursor() cur01.execute("update db1.t2 set a=a+1") cur01.execute("commit")
import pytest from connect import Connect from clients import clients from items import items import time from datetime import datetime, timedelta CLIENTS = clients ITEMS = items skip_marker = False connect = Connect() def if_skip_all(statement): global skip_marker if not statement: skip_marker = True @pytest.fixture(scope="class", autouse=True) def prepare(): connect.db_connect("DELETE FROM \"ClientCard\";") connect.db_connect("DELETE FROM \"Order\";") connect.orders = {} yield def test_create_clients(): for client in CLIENTS: connect.create_client(client) if_skip_all(connect.response.status_code == 200) assert connect.response.status_code == 200
from connect import Connect from algosdk import algod, transaction forAlgo = Connect() algAddr = forAlgo.algod_address algTok = forAlgo.algod_token head = forAlgo.headers forParam = algod.AlgodClient(algTok, algAddr, head) params = forParam.suggested_params() note = "Hi, sent you some Algo".encode() def create_transaction(privateKey, my_address, receiver, amount): txn = { "sender": my_address, "receiver": receiver, "fee": params.get('minFee'), "flat_fee": True, "amt": amount, "first": params.get('lastRound'), "last": params.get('lastRound') + 1000, "note": note, "gen": params.get('genesisID'), "gh": params.get('genesishashb64') } return transaction.PaymentTxn(**txn)
#Serve bootstrap files locally instead of from a CDN app.config['BOOTSTRAP_SERVE_LOCAL'] = True app.secret_key = os.urandom(24) #Used by the error callback to determine login status invalid_login = False @ffi.callback('void(SpError error, void *userdata)') def web_error_callback(error, userdata): global invalid_login if error == lib.kSpErrorLoginBadCredentials: invalid_login = True connect_app = Connect(web_error_callback, web_arg_parser) if os.environ.get('DEBUG') or connect_app.args.debug: app.debug = True ##Routes #Home page @app.route('/') def index(): return render_template('index.html') ##API routes
from asgn03 import supp_key_member_count from connect import Connect # Constants conn = Connect("dcris.ini") # member id v1 = 70 if v1 == None: rows = supp_key_member_count(conn) else: rows = supp_key_member_count(conn, supp_key_id=v1) for row in rows: print(row)
from connect import Connect from sendtransaction import private_key_alc, defaultAddr, sendTransaction, alc_1_addr, alc_2_addr, alc_1_pk from generateaccount import generateAccounts, accounts import time import json toConnect = Connect() getConnected = toConnect.connectToNetwork() # generate the two accounts from generateAccount Module creatAlcs = generateAccounts() print("Accounts generate: ", creatAlcs) print('\n') # visit https://bank.testnet.algorand.network/ with account 1 to get testnet Algo Token # prints the information of the first account that send Token print(getConnected.account_info(defaultAddr)) print('\n') #Get addresses and private key of account_2 alc_1_addr = (accounts['account_1']['alc_address']) alc_2_addr = (accounts['account_2']['alc_address']) alc_3_addr = (accounts['account_3']['alc_address']) alc_1_pk = (accounts['account_1']['pkey']) alc_2_pk = (accounts['account_2']['pkey']) # Call the he function from sendtransaction.py file # Default account sends token to account 1 trxn_1 = sendTransaction(private_key_alc, defaultAddr, alc_1_addr, 303000) print(trxn_1) print('\n') time.sleep(60)
import gevent import gpiozero from connect_ffi import ffi, lib from connect import Connect connect_app = Connect() def playback_play(): lib.SpPlaybackPlay() def playback_pause(): lib.SpPlaybackPause() def playback_prev(): lib.SpPlaybackSkipToPrev() def playback_next(): lib.SpPlaybackSkipToNext() # Loop to pump events def pump_events(): lib.SpPumpEvents() gevent.spawn_later(0.1, pump_events) pump_events()
from connect import Connect a = Connect() a.connect() a.insert("SELECT DISTINCT gameid,datetime FROM gameData_datetime") with open("games_inserted_already.txt", "w") as file: for i in a.cur.fetchall(): file.write(str(i[0]) + '\n')
#Serve bootstrap files locally instead of from a CDN app.config['BOOTSTRAP_SERVE_LOCAL'] = True app.secret_key = os.urandom(24) #Used by the error callback to determine login status invalid_login = False @ffi.callback('void(SpError error, void *userdata)') def web_error_callback(error, userdata): global invalid_login if error == lib.kSpErrorLoginBadCredentials: invalid_login = True connect_app = Connect(web_error_callback) if os.environ.get('DEBUG') or connect_app.args.debug: app.debug = True ##Routes #Home page @app.route('/') def index(): return render_template('index.html') ##API routes
def make_connection(self): print("make_connection") self.connection_one = Connect() self.connection_one.make_connection()
def handle_remote_cmd(self, cmd): tokens = str.split(cmd) action = tokens[0] rtn_msg = "Handle remote cmd failed." print("remote action " + action) connect = Connect() if action == "list": rtn_msg = connect.sendCmd(action) elif action == "attacksurface": if self.package_name.strip(): rtn_msg = connect.sendCmd(action + " " + self.package_name) else: rtn_msg = "Please use set action to set a package" elif action == "assess": print("Phase 1:") print(connect.sendCmd("assess")) print("Phase 2:") _packages = connect.sendCmd("list") packages = str.split(_packages) for package in packages: # print(package) _exported_activities = connect.sendCmd( "_exported_activities " + package) _exported_services = connect.sendCmd("_exported_services " + package) exported_activities = str.split(_exported_activities) exported_services = str.split(_exported_services) # exported_activities[0] is a placeholder for exported_activity in exported_activities[1:]: command = "adb shell am start -n " + package + "/" + exported_activity # print(command) output = os.popen(command) output = output.readlines() # print(output) if len(output) > 2: continue print(package, "/", exported_activity, "can be called in outer environment.") # break # print("OS: ", os.system(command)) # exported_services[0] is a placeholder for exported_service in exported_services[1:]: command = "adb shell am startservice -n " + package + "/" + exported_service output = os.popen(command) output = output.readlines() # print(output) if len(output) > 2: continue print(package, "/", exported_service, "can be manipulated in outer environment.") # break # print("OS: ", os.system(command)) return rtn_msg
def make_connection2(self): print("make_connection2") self.connection_two = Connect() self.connection_two.make_connection()
def __init__(self): id = unique_id() self.hex_id = b'{:02x}{:02x}{:02x}{:02x}'.format( id[0], id[1], id[2], id[3]) # Listas self.lista = {Tipo.EMERGENCIA: [], Tipo.AJUDA: [], Tipo.BATERIA: []} self.iterador = { 'tipo': Tipo.EMERGENCIA, 'tamanho': { Tipo.EMERGENCIA: 0, Tipo.AJUDA: 0, Tipo.BATERIA: 0, 'total': 0 }, 'iterador': -1 } self.cadastrados = {self.hex_id: {'nome': 'Receptor', 'quarto': None}} # Pino da bateria self.p33 = ADC(Pin(33)) self.p33.width(ADC.WIDTH_10BIT) self.p33.atten(ADC.ATTN_11DB) # Pino de alimentação self.p15 = Pin(15, Pin.OUT) self.p15.value(1) # Botão de remover self.p4 = Pin(4, Pin.IN, Pin.PULL_DOWN) # Timer que ativa o botão depois de 400ms self.t = Timer(0) self.t.init(period=400, mode=Timer.PERIODIC, callback=self.ativa) # OLED self.oled = SSD1306_I2C(128, 64, I2C(sda=Pin(21), scl=Pin(22))) self.oled.fill(0) escreve_SOS(self.oled) self.oled.show() self.bateria_timer = Timer(1) self.bateria_timer.init(period=1800000, mode=Timer.PERIODIC, callback=self.bateria) # Buzzer self.p19 = Pin(19, Pin.OUT) self.p19.value(0) self.t_boot = Timer(2) self.t_boot.init(period=300000, mode=Timer.ONE_SHOT, callback=self.reiniciar) self.c = Connect() self.connection = self.c.start() self.t_boot.deinit() self.server = Server(self.connection) self.carregar_cadastros() while self.p4.value() == 0 and reset_cause() != SOFT_RESET: self.t_boot.init(period=120000, mode=Timer.ONE_SHOT, callback=self.reiniciar) self.oled.fill(0) self.oled.text("CADASTRO", 0, 32) self.oled.show() mac = self.server.servidor(device=self, cadastro=True) self.connection.active(False) self.oled.fill(0) self.oled.text("ID:", 0, 20) self.oled.text(mac, 0, 32) self.oled.show() dados = cadastro.start(mac) self.escreve_oled(nome=dados[b'nome'].decode(), quarto=dados[b'quarto'].decode()) self.cadastrados.update({ mac: { 'nome': dados[b'nome'].decode(), 'quarto': dados[b'quarto'].decode() } }) self.connection = self.c.start() utime.sleep(1) try: self.t_boot.deinit except: pass # Recupera estado anterior try: f = open('estado.json', 'r') l = ujson.loads(f.read()) f.close() self.lista[Tipo.EMERGENCIA] = l[Tipo.EMERGENCIA] self.iterador['tamanho'][Tipo.EMERGENCIA] = len(l[Tipo.EMERGENCIA]) self.lista[Tipo.AJUDA] = l[Tipo.AJUDA] self.iterador['tamanho'][Tipo.AJUDA] = len(l[Tipo.AJUDA]) self.lista[Tipo.BATERIA] = l[Tipo.BATERIA] self.iterador['tamanho'][Tipo.BATERIA] = len(l[Tipo.BATERIA]) self.iterador['tamanho']['total'] = len(l[Tipo.BATERIA]) + len( l[Tipo.AJUDA]) + len(l[Tipo.EMERGENCIA]) remove("estado.json") except: pass # Botão de próximo self.p2 = Pin(2, Pin.IN, Pin.PULL_DOWN) self.p2.irq(trigger=Pin.IRQ_RISING, handler=self.proximo) # IRQ de remover self.p4.irq(trigger=Pin.IRQ_RISING, handler=self.remove) self.inatividade = Timer(2) self.inatividade.init(period=300000, mode=Timer.ONE_SHOT, callback=self.inativo)