def data1(): item = request.args.get("value") lists = request.args.get("lists") res = [] selected_data = tuple(lists) print("jbj", selected_data) for i in selected_data: s = "select * from product where cid='" + i + "'" cur, conn = connection() cur.execute(s) res.extend(cur) print("mmlmlm", res) length = len(res) print(length) result = [] for i in range(0, length): print(i) for j in range(res[0][4]): product = "select * from product where pname like '" + item + "%' and cid='" + str( res[i][j]) + "' group by pname" cur, conn = connection() cur.execute(product) result.extend(cur) print(result) if result is not None: row_header = [x[0] for x in cur.description] json_data = [] for results in result: json_data.append(dict(zip(row_header, results))) print(json_data) return jsonify(json_data) else: return "no match found"
def p_add(): sq = "select max(pid) from product" cur, conn = connection() cur.execute(sq) res = cur.fetchone() if res is not None: mid = res[0] + 1 else: mid = 0 img = request.files['img'] img.save("C:\\Users\\babbu\\PycharmProjects\\project\\static\\image\\" + str(mid) + ".png") path = ("./static/image/" + str(mid) + ".png") name = request.form['product'] price = request.form['price'] category = request.form['category'] s = "insert into product(pname,price,image,cid) values('" + name + "','" + price + "','" + path + "','" + category + "')" s1, s2 = connection() s1.execute(s) s2.commit() return "product added"
def drop_collection (collection): """ Drop a collection """ with connection.protect(): connection.connection().drop_collection(collection) logger.debug("Collection '%s' was dropped." % collection)
def drop_collection(collection): """ Drop a collection """ with connection.protect(): connection.connection().drop_collection(collection) logger.debug("Collection '%s' was dropped." % collection)
def lambda_handler(event, context): connection.connection() if event['httpMethod'] == 'GET': return get_handler(event, context) elif event['httpMethod'] == 'POST': return post_handler(event, context) else: return lambda_helper.proxy_response( 405, "Method not allowed " + event.httpMethod)
def repeat(event): write_on_line_one('repeat:') with connection(): write_on_line_two(client.currentsong()['artist']) for index, song in enumerate(client.playlistsearch('artist', client.currentsong()['artist'])): with connection(): new_pos = index + 1 print('move', song['id'], 'to', new_pos) client.moveid(song['id'], new_pos) print('now play at position 1')
def remove_object (object): """ Remove an object from a collection """ collection_name = object.__class__.__name__ with connection.protect(): connection.connection()[collection_name].remove({"_id": object["_id"]}) del _cache[object["_id"]] logger.debug("Object %s was removed from collection '%s'." % (object, collection_name))
def lambda_handler(event, context): connection.connection() try: account = Account.objects.get( {'_id': UUID('d2f702a1-36f8-11e9-8305-acde48001122')}) return { 'statusCode': 200, 'body': json.dumps(account.summary.to_son(), default=date_decoder) } except Account.DoesNotExist: return {'statusCode': 404, 'body': json.dumps('Account not found')}
def remove_object(object): """ Remove an object from a collection """ collection_name = object.__class__.__name__ with connection.protect(): connection.connection()[collection_name].remove({"_id": object["_id"]}) del _cache[object["_id"]] logger.debug("Object %s was removed from collection '%s'." % (object, collection_name))
def createEmpleado(nombre, sueldo): if (connection.connection() != None): conexion = connection.connection() try: with conexion.cursor() as cursor: consulta = "INSERT INTO empleados(nombre, sueldo) VALUES (%s, %s);" cursor.execute(consulta, (nombre, sueldo)) conexion.commit() finally: conexion.close() else: print("Error de conexion")
def deleteEmpleado(clave): if (connection.connection() != None): conexion = connection.connection() try: with conexion.cursor() as cursor: consulta = "DELETE FROM empleados WHERE clave=%s" cursor.execute(consulta, (clave)) conexion.commit() finally: conexion.close() else: print("Error de conexion")
def updateEmpleado(clave, nombre, sueldo): if (connection.connection() != None): conexion = connection.connection() try: with conexion.cursor() as cursor: consulta = "UPDATE empleados SET nombre=%s, sueldo=%s WHERE clave=%s " cursor.execute(consulta, (nombre, sueldo, clave)) conexion.commit() finally: conexion.close() else: print("Error de conexion")
def main(): if (connection.connection() != None): conexion = connection.connection() try: with conexion.cursor() as cursor: consulta = "SELECT * FROM empleados" cursor.execute(consulta) empleados = cursor.fetchall() for empleado in empleados: print(empleado) finally: conexion.close() else: print("Error de conexion")
def readEmpleado(ID): if (connection.connection() != None): conexion = connection.connection() try: with conexion.cursor() as cursor: consulta = "SELECT clave, nombre, sueldo FROM empleados WHERE clave='%s'" cursor.execute(consulta, (ID)) empleado = cursor.fetchall() finally: conexion.close() else: print("Error de conexion") return empleado
def show_sysinfo(): global mode while True: if mode != 'recording': with connection(): try: write_on_line_one(client.currentsong()['artist']) except KeyError: write_on_line_one('hmm, unknown') with connection(): try: write_on_line_two(client.currentsong()['title']) except KeyError: write_on_line_one('hmm, unknown') sleep(UPDATE_INTERVAL)
def copy_database (target_db, admin_user = None, admin_password = None, force = False): """ Copy the current database to a new database name (see http://www.mongodb.org/display/DOCS/Clone+Database) """ with connection.protect(): # save the current connection db_connection = connection.connection() db_connection_ = connection.connection_information() source_db = db_connection_["db"] if (source_db == target_db): logger.debug("Ignored request to copy '%s' into itself." % target_db) return # open a connection to the admin collection admin_connection = connection.connect(db = "admin", user = admin_user, password = admin_password) if (target_db in admin_connection.connection.database_names()): if (force): logger.debug("'%s' already exists and will be merged with content of '%s'." % (source_db, target_db)) else: raise errors.DBOperationError("Unable to copy database '%s' to '%s': target already exists." % (source_db, target_db)) # copy the database try: admin_connection.connection.copy_database(source_db, target_db) # restore the current connection finally: connection._connection = db_connection connection._connection_information = db_connection_ logger.debug("Copy of '%s' into '%s' successful." % (source_db, target_db))
def log1(): user = request.form['user'] paswd = request.form['pswd'] s = "select * from login where username='******' and password='******'" cur, conn = connection() cur.execute(s) result = cur.fetchone() if result is not None: if result[3] == 'user': session["id"] = result[0] return redirect(url_for('user_home')) #return user_home() #s = "select * from category" #cur, conn = connection() #cur.execute(s) #res = cur.fetchall() #return render_template('userhome.html', r=res) #result=user_home() elif result[3] == 'admin': return hm() else: return render_template('user.html') else: return render_template('user.html')
def show(id): s = "select pname,price,image from product where cid='" + id + "'" s1, s2 = connection() s1.execute(s) s2.commit() res = s1.fetchall() return render_template('pro_list.html', d=res)
def find (collection, query, find_one = False, count = False): """ Return objects matching a given query (expressed as a JSON object, see http://www.mongodb.org/display/DOCS/Querying), as PersistentObject instances """ cursor = connection.connection()[collection] query_t = type(query) if (query_t == str): try: query = {"_id": bson.objectid.ObjectId(query)} except bson.errors.InvalidId: raise errors.InvalidObjectOperationError("Invalid identifier: %s" % query) if (query_t == bson.objectid.ObjectId): query = {"_id": query} elif (query_t == dict): # no query argument: returns all objects in this collection if (query == {}): query = None elif (query != None): raise errors.InvalidObjectOperationError("Invalid query: %s" % query) logger.debug("Querying %s in collection '%s'." % (query, collection)) if (count): return cursor.find(query, timeout = False).count() if (find_one): return _forge_from_entry(collection, cursor.find_one(query)) else: return _forge_from_entries(collection, cursor.find(query, timeout = False))
def ds2_insert(): col_list = [ "STATION ID", "STATION NAME", "LATITUDE", "LONGITUDE", "ELEVATION", "DATE", "PRCP", "TAVG", "TMAX", "TMIN" ] cursor = connection("DataSource2") df = pd.read_csv("d2.csv") df.columns = [c.replace(' ', '_') for c in df.columns] df['PRCP'] = df['PRCP'].fillna(0.0).astype(float) df['TAVG'] = df['TAVG'].fillna(0).astype(int) df['TMAX'] = df['TMAX'].fillna(0).astype(int) df['TMIN'] = df['TMIN'].fillna(0).astype(int) for row in df.itertuples(index=True, name='Pandas'): STATION_ID = str(row.STATION_ID) STATION_NAME = str(row.STATION_NAME) LATITUDE = str(row.LATITUDE) LONGITUDE = str(row.LONGITUDE) ELEVATION = str(row.ELEVATION) DATE = str(row.DATE) PRCP = row.PRCP if row.PRCP else None TAVG = row.TAVG if row.TAVG else None TMAX = row.TMAX if row.TMAX else None TMIN = row.TMIN if row.TMIN else None cursor.execute( "INSERT INTO DataSource2.dbo.Data_Source2 VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", STATION_ID, STATION_NAME, LATITUDE, LONGITUDE, ELEVATION, DATE, PRCP, TAVG, TMAX, TMIN)
def get_dbSelect_comment_list(pno): conn = connection.connection() try: cursor = conn.cursor() cursor.execute("SELECT * FROM test.comment WHERE pno = %d"%int(pno)) conn.commit() row_num = cursor.rowcount finally: cursor.close() if row_num > 0: row = cursor.fetchall() comment_list=[] comment_list.append(row_num) for row_data in row: comment_list.append( { 'cno': row_data[0], 'cbody': row_data[1], 'userId': row_data[2], 'pno': row_data[3] } ) return comment_list else: comment_list=[] comment_list.append(0) return comment_list
def get_dbSelect_post(): conn = connection.connection() try: cursor = conn.cursor() sql = "SELECT * FROM test.post" cursor.execute(sql) row_num = cursor.rowcount finally: cursor.close() post=[] post.append(row_num) if row_num > 0: row = cursor.fetchall() for row_data in row: post.append( { 'pno': row_data[0], 'ptitle': row_data[1], 'pbody': row_data[2], 'email': row_data[3] } ) return post else: return post
def __init__(self, host, port, alias): try: #problem set requirements self.alias = alias self.id = -1 self.__ready = False #other fields self.__clientsocket = socket.socket() self.__clientconnection = connection.connection( self.__clientsocket) print 'trying to connect to server ' + host + ':' + str(port) self.__clientsocket.connect((host, port)) print 'connected!!' self.__players = [['None', 'None', 'None'], ['None', 'None', 'None'], ['None', 'None', 'None'], ['None', 'None', 'None']] #thread stoppers self.__server = threading.Event() #start client threading.Thread(target=self.__servermsgs).start() #game status self.__status = None except Exception as e: traceback.print_exc()
def rmv(id): uid = str(session["id"]) s = "delete from cart where uid='" + uid + "' and pid='" + id + "'" s1, s2 = connection() s1.execute(s) s2.commit() return redirect(url_for('shp'))
def get_dbChange_changeMyinfo(email, name, pw, phone_num): print(email, name, pw, phone_num,"디비 시작") conn = connection.connection() try: cursor = conn.cursor() cursor.execute("UPDATE test.os_member SET name = '%s', pw = '%s', phone_num = '%s' WHERE email= '%s'"%(name, pw, phone_num, email)) conn.commit() finally: cursor.close() cursor = conn.cursor() sql = "SELECT name, email, pw, phone_num FROM test.os_member where email=" + "'" + email + "'" cursor.execute(sql) row_num = cursor.rowcount cursor.close() if row_num > 0: row = cursor.fetchall() for row_data in row : json_object = { "name": row_data[0], "email": row_data[1], "pw": row_data[2], "phone_num": row_data[3] } print(json_object,"디비 끝") return json_object else: return "fail"
def connect(self): if self.cnx is None: self.cnx = connection() yield self.cnx.connect() self.context = yield self.cnx.context() yield self.setupListeners() self.start_loops()
def get_dbSelect_diary(result): conn = connection.connection() try: cursor = conn.cursor() sql = "SELECT diary_id, diary_title, diary_body, diary_date FROM test.diary WHERE diary_login_id = '" + result + "'" cursor.execute(sql) conn.commit() row_num = cursor.rowcount finally: cursor.close() if row_num > 0: row = cursor.fetchall() post=[] for row_data in row: post.append( { 'diary_id': row_data[0], 'diary_title': row_data[1], 'diary_body': row_data[2], 'diary_date': row_data[3] } ) #json.dumps(row) # print(json.dumps(row)) return post #json.dumps(row) else: return "fail"
def welcome(message): cur = connection.connection().cursor() data = { 'chat_id': cgi.escape(123, True), 'mobile': cgi.escape(123, True), 'date': cgi.escape('29.01.2019', True), 'description': cgi.escape('des', True) } cur.execute( """INSERT INTO `rememberbot.remember` (`chat_id`,`mobile`,`date`,`description`) VALUES ({name},{mobile},{date},{decription})""", data) cur.execute("SELECT * FROM remember") rows = cur.fetchall() for row in rows: print("{0} {1} {2} {3}".format(row[0], row[1], row[2], row[3])) sti = open('static/welcome.webp', 'rb') bot.send_sticker(message.chat.id, sti) print(message.chat.id) # keyboard markup = types.ReplyKeyboardMarkup(resize_keyboard=True) item1 = types.KeyboardButton("🎲 Рандомное число") item2 = types.KeyboardButton("😊 Как дела?") markup.add(item1, item2) bot.send_message( message.chat.id, "Добро пожаловать, {0.first_name}!\nЯ - <b>{1.first_name}</b>, бот созданный чтобы помочь вам не забывать о важных датах связаных с людьми." .format(message.from_user, bot.get_me()), parse_mode='html', reply_markup=markup)
def get_dbSelect_stop2(email): conn = connection.connection() try: cursor = conn.cursor() sql = "SELECT * FROM test.stop_smoke where email=" + "'" + email + "'" cursor.execute(sql) row_num = cursor.rowcount finally: cursor.close() post=[] if row_num > 0: row = cursor.fetchall() now = datetime.datetime.now().date() for row_data in row : post.append( { "email": row_data[0], "smoke_amount": row_data[1], "smoke_date": row_data[2], "smoke_now_date": now, "smoke_reason": row_data[3] } ) result_date = post[0]['smoke_now_date'] - post[0]['smoke_date'] post.append(result_date.days) return post else: return "fail"
def handle(self): conn = connection(self.request) try: msg = conn.recv() while len(msg) > 0: data_t = eval(msg) command = "./bench_srv" return_output = data_t[0] # First parameter says if the output of execution need to be sent back for i in data_t[1:]: # Excludes the first parameter command += " " + str(i) print "Running %s..." % command pipe_obj = subprocess.Popen(args=command, shell=True, stdout=subprocess.PIPE) bench_srv_out = pipe_obj.stdout ans = "" line = bench_srv_out.readline() while line: print line[:-1] if return_output: ans += line #conn.send_part(line) line = bench_srv_out.readline() #conn.end_part() if return_output: conn.send(ans) else: conn.end_part() msg = conn.recv() except ConnectionClosedException: pass self.request.shutdown(socket.SHUT_WR)
def __init__(self): config = ConfigParser.ConfigParser() if not config.read('muninrc'): raise ValueError("Expected configuration in muninrc, not found.") self.loader = Loader() self.loader.populate('munin') self.ircu_router = self.loader.get_module(self.IRCU_ROUTER) self.client = connection(config) self.client.connect() self.client.wline("NICK %s" % config.get("Connection", "nick")) self.client.wline("USER %s 0 * : %s" % (config.get("Connection", "user"), config.get("Connection", "name"))) self.config = config router=self.ircu_router.ircu_router(self.client,self.config,self.loader) while True: try: self.reboot() break except socket.error, s: print "Exception during command at %s: %s" %(time.asctime(),s.__str__()) traceback.print_exc() raise except socket.timeout, s: print "Exception during command at %s: %s" %(time.asctime(),s.__str__()) traceback.print_exc() raise
def register(): if 'auth' in session: try: c, conn = connection() if request.method == "POST": username = request.form['username'] password = sha256_crypt.encrypt(str(request.form['password'])) fname = request.form['fname'] mail = request.form['mail'] type=request.form['type'] data = c.execute("SELECT * FROM userdetails WHERE username=(%s)", (thwart(username))) if int(data) > 0: return render_template("regi.html", data="username is already exist") else: c.execute("INSERT INTO userdetails (fname,username,password,email,type,status) values(%s,%s,%s,%s,%s,%s)", (thwart(fname), thwart(username), thwart(password), thwart(mail), thwart(type), thwart("Active"))) conn.commit() c.close() conn.close() return render_template("regi.html", data="user registered sucessfully") except Exception as e: return (str(e)) else: return render_template("login.html",data="please log in") return render_template("regi.html")
def find(collection, query, find_one=False, count=False): """ Return objects matching a given query (expressed as a JSON object, see http://www.mongodb.org/display/DOCS/Querying), as PersistentObject instances """ cursor = connection.connection()[collection] query_t = type(query) if (query_t == str): try: query = {"_id": bson.objectid.ObjectId(query)} except bson.errors.InvalidId: raise errors.InvalidObjectOperationError("Invalid identifier: %s" % query) if (query_t == bson.objectid.ObjectId): query = {"_id": query} elif (query_t == dict): # no query argument: returns all objects in this collection if (query == {}): query = None elif (query != None): raise errors.InvalidObjectOperationError("Invalid query: %s" % query) logger.debug("Querying %s in collection '%s'." % (query, collection)) if (count): return cursor.find(query, timeout=False).count() if (find_one): return _forge_from_entry(collection, cursor.find_one(query)) else: return _forge_from_entries(collection, cursor.find(query, timeout=False))
def main(): pre = 0 connect = connection.connection() with connect.cursor() as cursor: sql = "SELECT * FROM `StockTweets` ORDER BY Date" cursor.execute(sql, ()) connect.commit() result = cursor.fetchall() numrows = cursor.rowcount Dates = [] for row in result: Date = row["Date"] if Date in Dates: pre = 0 # This does nothing else: Dates.append(Date) for Date in Dates: db = {} stock = [] with connect.cursor() as cursor: sql = "SELECT * FROM `StockTweets` WHERE Date=%s" cursor.execute(sql, (Date)) connect.commit() resultinputs = cursor.fetchall() numrows = cursor.rowcount print("Current Date", Date) for Input in resultinputs: Tick = Input["Ticker"] if Tick in db: db[Tick] += 1 else: db[Tick] = 0 for each in db: val = db[each] with connect.cursor() as cursor: quer = "SELECT * FROM `Stocks` WHERE Ticker=%s" cursor.execute(quer, (each)) connect.commit() avgresult = cursor.fetchall() for Resulting in avgresult: vol = Resulting["AvgTweetVolumeThirty"] vol = float(vol) vol = round(vol, 0) if (val < (0.70 * vol)): pre = 0 # This does nothing #print("Low Volume For", each) else: stock.append(each) print(stock)
def connect_labrad(self): if self.cxn is None: from connection import connection self.cxn = connection() yield self.cxn.connect() self.create_layout() self.connect_tab_signals()
def findnic(): if 'auth' in session: c, conn = connection() try: if request.method == "POST": id = request.form['nic'] print(id) c.execute("SELECT * FROM criminalinfo WHERE nic=(%s)", (thwart(id))) result = c.fetchone() print(result) c.execute("SELECT * FROM commitedcrime WHERE nic=(%s)", (thwart(id))) result1 = c.fetchall() print(result1) if not result: return render_template("searchone.html", data=result, result1=result1 , message="Criminal Not Found") else: return render_template("searchone.html", data=result, result1=result1,message="Crimiinal Found Sucessfully") except Exception as e: return (str(e)) print(e) else: return render_template("login.html",data="please log in")
def play_now(artist): with connection(): try: tracks = client.find('artist', artist) except: pass if len(tracks): print(len(tracks), 'tracks') track = random.choice(tracks)['file'] print('so adding', track) with connection(): id = client.addid(track) if id: print('added track, id is', id) with connection(): client.playid(id)
def login(): try: session['auth'] = "true" c, conn = connection() if request.method == "POST": username = request.form['username'] password = request.form['password'] data = c.execute("SELECT * FROM userdetails WHERE username=(%s)", (thwart(username))) data = c.fetchone() print(data[3]) if sha256_crypt.verify(password, data[3]): session['auth'] = "true" if data[5] == "Admin": print (data[5]) return redirect(url_for("criminalinfo",data="login sucessfully")) print(data[5]) else: return redirect(url_for("find", data="login sucessfully")) print(data[5]) else: return redirect(url_for("find", data="Invalid login Credential")) gc.collect() except Exception as e: print(e) return render_template("login.html",data="Invalid login Cridential")
def ds1_insert(): col_list = [ "STATIONID", "STATIONNAME", "ST_LATITUDE", "ST_LONGITUDE", "ST_ELEVATION", "DATE", "SNOW", "SNWD", "PRCP_VAL", "TEMP_AVG", "TEMP_MAX", "TEMP_MIN" ] cursor = connection("DataSource1") df = pd.read_csv("d1.txt") df['SNWD'] = df['SNWD'].fillna(0.0).astype(float) df['SNOW'] = df['SNOW'].fillna(0.0).astype(float) df['PRCP_VAL'] = df['PRCP_VAL'].fillna(0.0).astype(float) df['TEMP_AVG'] = df['TEMP_AVG'].fillna(0).astype(int) df['TEMP_MAX'] = df['TEMP_MAX'].fillna(0).astype(int) df['TEMP_MIN'] = df['TEMP_MIN'].fillna(0).astype(int) for row in df.itertuples(index=True, name='Pandas'): STATIONID = str(row.STATIONID) STATIONNAME = str(row.STATIONNAME) ST_LATITUDE = str(row.ST_LATITUDE) ST_LONGITUDE = str(row.ST_LONGITUDE) ST_ELEVATION = str(row.ST_ELEVATION) DATE = str(row.DATE) SNOW = row.SNOW if row.SNOW else None SNWD = row.SNWD if row.SNWD else None PRCP_VAL = row.PRCP_VAL if row.PRCP_VAL else None TEMP_AVG = row.TEMP_AVG if row.TEMP_AVG else None TEMP_MAX = row.TEMP_MAX if row.TEMP_MAX else None TEMP_MIN = row.TEMP_MIN if row.TEMP_MIN else None cursor.execute( "INSERT INTO DataSource1.dbo.Data_Source1 VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", STATIONID, STATIONNAME, ST_LATITUDE, ST_LONGITUDE, ST_ELEVATION, DATE, SNOW, SNWD, PRCP_VAL, TEMP_AVG, TEMP_MAX, TEMP_MIN)
def main(): connect = connection.connection() names = [ "LULU", "KOF", "FLO", "TSN", "IRBT", "HOFT", "OPTT", "DYN", "SO", "WGL", "EQT", "AZO", "CVS", "WMT", "OMC", "TDW", "TOPS", "MNKD", "VRX", "AZN", "ACAD", "TSLA", "NKE", "PG", "BBY", "DIS", "DAL", "GPRO", "AAPL", "FB", "TWTR", "SBUX", "MSFT", "QCOM", "AMZN", "V", "NEM", "NWL", "XOM", "JNJ", "MRK", "PG", "BA", "GILD", "KO" ] for stock in names: result = fetchdata.price_data(connect, stock) pprint.pprint(result) #old = read_from_file(FILENAME) new = fetchdata.get_tweets_list(names) #new = append_no_duplicates(old, new) new = cull(new) write_to_file(FILENAME, new) for stock in names: output = pulldata.fetch_saved_tweets(connect, FILENAME, stock) print(output) for ticker in names: pulldata.pull_tweets_not_analyzed(connect, ticker) #Erase the temporary file contents erase_temporary_file(FILENAME)
def __init__(self, host, port, alias): try: #problem set requirements self.alias = alias self.id = -1 self.__ready = False #other fields self.__clientsocket = socket.socket() self.__clientconnection = connection.connection(self.__clientsocket) print 'trying to connect to server '+host+':'+str(port) self.__clientsocket.connect((host, port)) print 'connected!!' self.__players = [['None','None','None'], ['None','None','None'], ['None','None','None'], ['None','None','None']] #thread stoppers self.__server = threading.Event() #start client threading.Thread(target = self.__servermsgs).start() #game status self.__status = None except Exception as e: traceback.print_exc()
def run(self): with connection() as channel: self.channel = channel channel.queue_declare(queue=self.queue, durable=True) channel.basic_consume(self.callback, queue=self.queue) channel.basic_qos(prefetch_count=1) channel.start_consuming()
def rate_it(delta): rating = None file = None with connection(): file = '/mnt/share/' + client.currentsong()['file'] if file != None: tagr.rate_it(file, delta) return rating
def count (collection, query): """ Return the number of objects matching a given query in a given collection """ if (query == {}): cursor = connection.connection()[collection] return cursor.count() else: return find(collection, query, count = True)
def checkins(): sites = [] conn, cur = connection() cur.execute("select DISTINCT x, y from parkmovement1 where type = 'check-in' ORDER BY x") fetchRes = cur.fetchall(); for item in fetchRes: coord = str(item[0]) + ',' + str(item[1]) sites.append(coord) return sites
def connect(self): try: self.sock.connect(self.addr) self.conn = connection(self.sock) print "Connected to %s:%d." % self.addr self.connected = True self.start() except: print "Couldn't connect to %s:%d." % self.addr
def setupDDS(self): if self.cxn is None: self.cxn = connection() yield self.cxn.connect() self.context = yield self.cxn.context() try: yield self.initialize() except Exception, e: print 'DDS CONTROL: Pulser not available' self.setDisabled(True)
def run(self): with connection() as channel: channel.queue_declare(queue=self.queue, durable=True) while self.count < self.max_count: channel.basic_publish(exchange="", routing_key=self.queue, body=self.message) self.count += 1 time.sleep(0.5)
def createconn(self): #creates a conn with the hostname. If a parser for this object does not yet exist, create that #as well. #no connection, keep this unplugged for now if self.hostname == '': return None; #we have a hostname to connect to. self.conn = connection.connection(self.hostname, 6661, incomingq=self.incoming, outgoingq=self.outgoing) self.conn.startthread() return self.conn
def test_check_testtable_exist(): con_details = { 'dbpath': '.', 'dbname': 'test.db' } con_utils = connection.connection(**con_details) res = con_utils.check_if_table_exist('testtable') return res
def connect(self): if self.cxn is None: self.cxn = connection() yield self.cxn.connect() self.context = yield self.cxn.context() try: yield self.initializeGUI() yield self.setupListeners() except Exception, e: print 'SWTICH CONTROL: Pulser not available' self.setDisabled(True)
def connectToServer(): udpsocket=socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udpsocket.sendto(CONNECTION_REQUEST_MESSAGE, (DEFAULT_SERVER_IP, DEFAULT_SERVER_PORT)) data, addr = udpsocket.recvfrom(BUFFER_SIZE) myServerPort = int(data) print "Will connect to ", data s = socket.socket() s.connect((DEFAULT_SERVER_IP, myServerPort)) global myConnection myConnection = connection.connection(s) print myConnection.getMessage() #or add this to the GUI later on
def favourite(event): global mode favourites = load_favourites() if mode == 'recording': mode = 'playing' print(event.ir_code) write_on_line_one(event.ir_code) with connection(): write_on_line_two('FAVE: ' + client.currentsong()['artist']) with connection(): favourites[event.ir_code] = client.currentsong()['artist'] save_favourites(favourites) else: print('play track by artist saved as', event.ir_code) try: print(event.ir_code, favourites[event.ir_code]) play_now(favourites[event.ir_code]) except KeyError: print('nothing saved as', event.ir_code) pass print(favourites)
def __init__(self,ip,port, pythonPath): self.connection = connection.connection() if not self.connection.connect(ip, port): return cur_version = '{0}.{1}.{2};'.format(sys.version_info[0], sys.version_info[1], sys.version_info[2]) + getModulesList() self.connection.sendMessage('Join', cur_version) self.status = 'disconnected' self.codePath = '' self.result = '' self.name = 'defaultNodeName' self.worker = worker.worker(pythonPath) self.run()
def connect(self): if self.cxn is None: self.cxn = connection() yield self.cxn.connect() self.context = yield self.cxn.context() # initUI seems to need to be called from here # rather than __init__(), otherwise it doesn't # recognize self.context. Something about the order # of things getting called by the reactor self.initUI() yield self.initialize()
def _commit (object): db = connection.connection() collection_name = object.__class__.__name__ collection = db[collection_name] # if the collection this object belongs to doesn't exist in # the database, we create it with its indices (if any) if (not collection_name in db.collection_names()): msg = "Collection '%s' created" % collection_name if (len(object._indices) > 0): msg += " with indices %s" % ', '.join(["'%s'" % key for key in sorted(object._indices.keys())]) for (index, is_unique) in object._indices.iteritems(): collection.create_index(index, unique = is_unique) logger.debug(msg + '.') # second case: the object is not committed, and is not in the database if (not "_id" in object): object._properties["_creation_time"] = datetime.datetime.utcnow() verb = "created" # third case: the object is not committed, but a former version exists in the database else: object._properties["_modification_time"] = datetime.datetime.utcnow() verb = "updated" try: object_id = collection.save( object.get_properties(), safe = True ) object._properties["_id"] = object_id _cache[object_id] = object except pymongo.errors.OperationFailure as e: # we process index-related errors independently if ("E11000" in str(e)): properties = [(key, object[key]) for key in filter(lambda x: "$%s_" % x in str(e), object._indices)] raise errors.DuplicateObjectError(collection_name, properties) raise e except bson.errors.InvalidDocument as e: if ("too large" in str(e)): raise errors.DBOperationError("Object is too large to be committed") raise e logger.debug("Object %s %s in collection '%s'." % (object, verb, collection_name))
def acceptClients(self, s): self.log( "start acceptClients") while True: clinetsocket, clientaddr = s.accept() self.log( "%s connected" %(str(clientaddr) ) ) id = str(clientaddr) section = connection.connection(clinetsocket) self.clients[id] = {"socket": clinetsocket, "ip": clientaddr, "Section" : section} self.log("fake data") newClinet = threading.Thread( target=self.client, args = (self.clients[id],)) newClinet.start()
def setupDDS(self): if self.cxn is None: self.cxn = connection() yield self.cxn.connect() self.context = yield self.cxn.context() try: from labrad.types import Error self.Error = Error yield self.initialize() except Exception, e: print e print 'DDS CONTROL: Pulser not available' self.setDisabled(True)
def __wait_for_players(self): while not self.__waiting.is_set(): remote_socket, addr = self.__serversocket.accept() remote_connection = connection.connection(remote_socket) #if server leaves if self.__waiting.is_set(): #to be recieved by the dummy client that closed this thread remote_connection.sendMessage('SETID SERVER_DEAD') remote_socket.close() break #room is busy if self.__playing == True: remote_connection.sendMessage('SETID SERVER_BUSY') remote_socket.close() else: #determine if room is full ind = -1 for i in range(len(self.__plist)): if self.__plist[i] == None: ind = i break #room is full if ind == -1: remote_connection.sendMessage('SETID SERVER_FULL') remote_socket.close() #room can accommodate else: #add identifier to client remote_connection.sendMessage('SETID '+str(self.__idctr)) self.__players.update({self.__idctr: (addr, remote_connection, threading.Event())}) #add to list of players self.__plist[ind] = self.__idctr self.__pready[ind] = False #receive client messages msg_thread = threading.Thread(target = self.__clientmsgs, args = (self.__idctr,)) msg_thread.start() print(str(addr) + ' connected! '+str(self.__idctr)) self.__playercount+=1 self.__idctr+=1 print 'done waiting for players'
def connect(self): if self.cxn is None: self.cxn = connection() yield self.cxn.connect() from labrad.types import Error self.Error = Error self.context = yield self.cxn.context() try: displayed_channels = yield self.get_displayed_channels() yield self.initializeGUI(displayed_channels) yield self.setupListeners() except Exception, e: print e print 'SWTICH CONTROL: Pulser not available' self.setDisabled(True)