def setComputerComment(search, comments): cpu = getComputer(search) if cpu is None: return 'ERR_NO_COMPUTER' database.update('computers', { 'comments': comments }, { 'cid': cpu['cid'] }) return True
def patch(self): id = self.get_argument('id') name = self.get_argument('name', default=None) quantity = self.get_argument('quantity', default=None) if name == None and quantity == None: return database.update(int(id), name, quantity)
def check_time(): update_read_from_db = 0 db_list = database.read("alarm") while True: if update_read_from_db >= 20: update_read_from_db = 0 db_list = database.read("alarm") curr_timestamp = datetime.datetime.now() for row in db_list: if len(row) == 0: continue # row[0] is id # row[1] is timestamp # row[2] is running # row[3] is snooze count alarm_timestamp = datetime.datetime.fromtimestamp( int(float( row[1]))) + (int(row[3]) * datetime.timedelta(minutes=8)) if alarm_timestamp < curr_timestamp and int(row[2]) == 0: print("Alarm trigger") row[2] = 1 database.update("alarm", row, row[0]) strings = ["resp", "alarm", "sound"] resp = '&'.join(strings) client.publish("openhome/controller", resp) else: continue update_read_from_db += 1 time.sleep(.05)
def handle_starttag(self, tag, attrs) -> None: attrs_dict = dict(attrs) if (tag == 'h2'): self.incomingFilename = True if (tag == 'a'): if ('download' in attrs_dict): if attrs_dict['download'] == 'true': path = attrs_dict['href'] print(f"\t\t\t\tdownloading {self.filename}") for retry_count_index in range(10): try: downloadResponse = requests.get(HOST + path, headers=headers) totalbits = 0 if downloadResponse.status_code == 200: with open( os.path.join(DOWNLOAD_DIR, DOWNLOAD_SUBDIR, self.filename), 'wb') as f: for chunk in downloadResponse.iter_content( chunk_size=1024): if chunk: totalbits += 1024 f.write(chunk) break except ssl.SSLError as e: print(e) database.update(item_id=self.item_id, finished=True) print(f"\t\t\t\tdownload completed") elif (tag == 'div'): if 'style' in attrs_dict: if attrs_dict['style'] == 'margin: 10px 50px;': self.is_delayed = True
def withdrawal_operation(user_account_number, user_details, balance): # get_current_balance(user_details, balance) user_details[4] = int(user_details[4]) balance = user_details[4] print("\nWithdrawal Menu") print(f'You would like to make a withdrawal \nIs that correct?') confirm_withdrawal = int(input('Press (1) for Yes (2) for No \n')) if confirm_withdrawal == 1: print(f'Your current balance is {balance}') withdrawal_amount = int( input('How much would you like to withdraw?: \n')) print(f'You have chosen to withdrawal ${withdrawal_amount}') database.update(user_account_number, balance) if balance < withdrawal_amount: print( f'Sorry, the requested transaction cannot be completed \n' f'The amount you are seeking to withdrawal exceeds your current balance of ${balance} \n' f'Please try your transaction again') withdrawal_operation(user_account_number, user_details, balance) else: balance = balance - withdrawal_amount print( f'Your remaining balance is ${balance} \nPlease take your cash \nHave a nice day!' ) init() elif confirm_withdrawal == 2: bank_operation(user_details) else: print('Invalid option selected, please try again') withdrawal_operation(user_account_number, user_details, balance)
def findItemIdsFromGETracker(): db.connect() idNum = 0 #highest id is 23754 errorCount = 0 while idNum < 23755: try: print("Checking idNum", idNum) r = requests.get( "http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=%s" % str(idNum)) time.sleep(2) r.raise_for_status() json = r.json() if r.status_code == 200 and json != None: id = json['item']['id'] name = json['item']['name'] cell = db.itemSheet.find(name) if id and name and cell: print("Updating %s with id %d" % (name, id)) db.update(0, cell.row, 1, id) errorCount = 0 idNum = idNum + 1 except Exception as e: if errorCount == 3: idNum = idNum + 1 errorCount = 0 errorCount = errorCount + 1
def edit(self): confirmation = tk.messagebox.askquestion( 'Edit Data', 'Are you sure you want to edit this entry') if confirmation == 'yes': if (self.status_ingredient.get() == 1): self.ingredient_id = database.selectone( "SELECT ingredient_id FROM INGREDIENTS where ingredients.name = ?", (self.ingredient_selected.get(), )) else: database.insert("Ingredients", "(Null,?,?,?,?)", (self.entry_ingredient_name.get(), self.entry_ingredient_stock.get(), self.entry_ingredient_minimun_stock.get(), self.entry_ingredient_unit.get())) self.ingredient_id = database.selectone( "SELECT ingredient_id FROM INGREDIENTS where ingredients.name = ?", (self.entry_ingredient_name.get(), )) if (self.status_product.get() == 1): self.product_id = database.selectone( "SELECT product_id FROM products where products.name = ?", (self.product_selected.get(), )) else: database.insert( "Product", "(Null,?,?,?)", (self.entry_product_name.get(), self.entry_price.get(), self.entry_description.get())) self.product_id = database.selectone( "SELECT product_id FROM Products where products.name = ?", (self.entry_product_name.get(), )) data = (self.ingredient_id[0], self.product_id[0], self.entry_quantity.get(), product_details_data[0]) database.update("Product_details ", "ingredient_id = ?, product_id = ?, quantity = ?", "product_details_id like ?", data)
def withdrawlOperation(user): confirmWithdrawl = int( input( 'Would you like to continue with your Withdrawl?\n[1] Continue with Withdrawl\n[2] Logout\n[3] Exit\n' )) if (confirmWithdrawl == 1): print(f"You have ${user['Balance']} in your account") while True: amountWithdrawn = input("How much would you like to withdraw? \n") if validation.isNumber(amountWithdrawn): amountWithdrawn = float(amountWithdrawn) break if (amountWithdrawn <= user["Balance"]): user["Balance"] = user["Balance"] - amountWithdrawn database.update(user) print(f"Take your cash. Your new balance is ${user['Balance']}") elif (amountWithdrawn > user["Balance"]): print( f"You do not have enough money in your account for this withdrawal, please select a number smaller than {user['Balance']}" ) withdrawlOperation(user) elif (confirmWithdrawl == 2): logout(user) elif (confirmWithdrawl == 3): exit() else: print("Invalid Option") withdrawlOperation(user)
def update_analytic_fields(): """ Updates all statistics columns in the habit table automatically. These values are required for and retrieved by the following methods. Returns ------- None. """ all_habits = db.get_all_habit_names() for name in all_habits: habit = Habit.load(name[0], 1) if habit is not None: query = """ UPDATE habit SET current_streak=?, longest_streak=?, latest_check_date=?, next_check_date=? WHERE name=? """ values = (habit.streak.current_streak, habit.streak.longest_streak, habit.streak.latest_check_date, habit.streak.next_check_date, name[0]) db.update(query, values) return None
def edit(self): confirmation = tk.messagebox.askquestion( 'Edit Data', 'Are you sure you want to edit this data') if confirmation == 'yes': if (self.status_ingredient.get() == 1): self.ingredient_id = database.selectone( "SELECT ingredient_id FROM INGREDIENTS where ingredients.name = ?", (self.ingredient_selected.get(), )) else: database.insert("Ingredients", "(Null,?,?,?,?)", (self.entry_ingredient_name.get(), self.entry_ingredient_stock.get(), self.entry_ingredient_minimun_stock.get(), self.entry_ingredient_unit.get())) self.ingredient_id = database.selectone( "SELECT ingredient_id FROM INGREDIENTS where ingredients.name = ?", (self.entry_ingredient_name.get(), )) data = (self.ingredient_id[0], self.entry_restock_quantity.get(), self.entry_cost.get(), self.entry_supplier.get(), self.entry_date.get(), restock_data[0]) database.update( "Restocks ", "Ingredient_id = ?, quantity = ?, total_cost = ?, supplier = ?, date = ?", "restock_id like ?", data) self.ingredient_quantity = database.selectone( "SELECT stock FROM INGREDIENTS where ingredient_id = " + (str(self.ingredient_id[0])), None) self.added_stock = int(self.entry_restock_quantity.get()) - int( restock_data[2]) + int(self.ingredient_quantity[0]) self.stock_data = (self.added_stock, self.ingredient_id[0]) database.update("Ingredients ", "stock = ?", "Ingredient_id = ?", self.stock_data)
def upgrade_fec(): if "submit" in request.form: q = "select * from facilities" res = db.select(q) print(len(res)) for row in res: print(row) fecility = request.form['feci' + str(row['fec_id'])] fec_id = row['fec_id'] log_id = session['login_data']['login_id'] q = "SELECT ins_id FROM `institution` WHERE login_id='%s'" % log_id ins_id = db.select(q)[0]['ins_id'] r = "select * from insti_feci WHERE ins_id='%s' and fec_id='%s'" % ( ins_id, fec_id) res1 = db.select(r) if (len(res1) > 0): q = "UPDATE insti_feci SET status='%s' WHERE ins_id='%s' and fec_id='%s'" % ( fecility, ins_id, fec_id) db.update(q) else: q = "insert into insti_feci(ins_id,fec_id,status) values('%s','%s','%s')" % ( ins_id, fec_id, fecility) db.insert(q) return redirect(url_for('grade')) q = "select * from facilities" res = db.select(q) return render_template('institution/upgrade_fec.html', data=res)
async def update_all(self, ctx): """Update all entries in the data base""" players = list(classes.Player._players.values()) guilds = list(classes.Guild._guilds.values()) db.update(*players) db.update(*guilds) await ctx.send("DONE")
def test_get_events(self): add_match(0,0) add_event(0,0) rv = self.app.get('/getEventsForMatchId/0') data = json.loads(rv.get_data(as_text=True)) self.assertEqual(len(data),1) self.assertEqual(data[0][0], 0) self.assertEqual(data[0][1], 'Sat, 21 Jan 2017 10:10:10 GMT') self.assertEqual(data[0][2], 'Arsenal') self.assertEqual(data[0][3], 'Hull') self.assertEqual(data[0][4], 'BPL') self.assertEqual(data[0][5], 0) self.assertEqual(data[0][6], 0) self.assertEqual(data[0][7], 'Sample description') self.assertEqual(data[0][8], 'Sample question') add_event(1,0) add_match(1,0) update(1, 'events') rv = self.app.get('/getEventsForMatchId/1') data = json.loads(rv.get_data(as_text=True)) #print(data) self.assertEqual(len(data),1) self.assertEqual(data[0][0], 1) self.assertEqual(data[0][1], 'Sat, 21 Jan 2017 10:10:10 GMT') self.assertEqual(data[0][2], 'Arsenal') self.assertEqual(data[0][3], 'Hull') self.assertEqual(data[0][4], 'BPL') self.assertEqual(data[0][5], 0) self.assertEqual(data[0][6], 1) self.assertEqual(data[0][7], 'Changed description') self.assertEqual(data[0][8], 'Changed question')
def callback_inline(call): global users_dict database.update(str(call.message.chat.id), call.data, config.FILE_WITH_USERS) users_dict.update({str(call.message.chat.id): call.data.split()}) bot.delete_message(call.message.chat.id, call.message.message_id) bot.send_message(call.message.chat.id, "Вы выбрали " + users_dict.get(str(call.message.chat.id))[0])
def update_job(context): with db.connection() as cursor: updates = jobs.check_updates( jobs.get_last_data(db.get(cursor, "*", "country", multiple=True)), jobs.get_current(), ) for country in updates.keys(): for data in updates[country].keys(): if "difference" not in data and "today" not in data: with db.connection() as cursor: db.update( cursor, "country", data, updates[country][data]["total"], "name", country, ) with db.connection() as cursor: users = db.get_users(cursor) messages = jobs.generate_update_message(updates) for user in users: if user[1] in messages.keys(): try: context.bot.send_message(chat_id=user[0], text=messages[user[1]]) except telegram.error.Unauthorized: with db.connection() as cursor: db.delete_user(cursor, user[0])
def moveComputer(search, x, y): cpu = getComputer(search) if cpu is None: return False database.update('computers', { 'x': x, 'y': y }, { 'cid': cpu['cid'] }) return True
def update(self): """ 如果该行的字段属性有 updatable,代表该字段可以被更新 用于定义的表(继承Model的类)是一个 Dict对象,键值会变成实例的属性 所以可以通过属性来判断 用户是否定义了该字段的值 如果有属性, 就使用用户传入的值 如果无属性, 则调用字段对象的 default属性传入 具体见 Field类 的 default 属性 通过的db对象的update接口执行SQL SQL: update `user` set `passwd`=%s,`last_modified`=%s,`name`=%s where id=%s, ARGS: (u'******', 1441878476.202391, u'Michael', 10190 """ self.pre_update and self.pre_update() L = [] args = [] for k, v in self.__mappings__.iteritems(): if v.updatable: if hasattr(self, k): arg = getattr(self, k) else: arg = v.default setattr(self, k, arg) L.append('`%s`=?' % k) args.append(arg) pk = self.__primary_key__.name args.append(getattr(self, pk)) database.update('update `%s` set %s where %s=?' % (self.__table__, ','.join(L), pk), *args) return self
def update(params): try: database.update('insert or replace into settings(key, value_1, value_2) values ("' + params['setting'] + '", "' + params['value_1'] + '", "' + params['value_2'] + '")') return {'class': 'alert-success', 'message': 'Settings updated successfully.'} except: print "Error updating settings: " + sys.exc_info()[0] return {'class': 'alert-error', 'message': 'Sorry but something went wrong! Check the log for details.'}
async def open_queue(ctx): for queue_channel in db.queues_ref(ctx.guild.id).stream(): channel = ctx.guild.get_channel(int(queue_channel.id)) await channel.set_permissions(ctx.guild.default_role, overwrite=None) await queue_update(ctx.guild, int(queue_channel.id)) await delete_queue_status_message(ctx.guild) db.update(db.guild_ref(ctx.guild.id), db.Key.queue_status, True) embed = discord.Embed( title=u"Join the voice channel for the queue you want", colour=discord.Colour.blue(), description= "Once in your waiting room feel free to join someone else's while you wait." ) embed.set_author( name="Queues are Open!", icon_url= "https://cdn.discordapp.com/icons/812343984294068244/69241d42f3661678d61b3af3cfb04f45.png" ) embed.set_footer( text= "If you leave a voice channel in this server you will be removed from the queue!" ) message = await ctx.send(embed=embed) await message.pin() db.update(db.guild_ref(ctx.guild.id), db.Key.queue_status_message, [ctx.channel.id, message.id])
async def create_temp_channel(guild: discord.Guild, name: str, channel_type, category=None, position: int = None, overwrites=None, parent_id=None): if channel_type == "voice": channel = await guild.create_voice_channel(name, category=category, position=position, overwrites=overwrites) else: channel = await guild.create_text_channel(name, category=category, position=position, overwrites=overwrites) if parent_id is None: db.update(db.temp_channel_ref(guild.id, channel.id), db.Key.related, []) else: db.append_array(db.temp_channel_ref(guild.id, parent_id), db.Key.related, channel.id) return channel
def update_client(): ''' Updates Client Information --- put: description: Updates editable client information. tags: - User requestBody: required: true content: application/json: schema: type: object properties: NAME: type: string description: Updated User Name. NIF: type: number description: Updated User NIF. responses: 200: description: A JSON containing the result of payment. content: application/json: schema: properties: SUCCESS: type: boolean 400: description: A JSON containing the ERROR that identifies the problem. content: application/json: schema: properties: ERROR: type: string ''' if 'user_id' in session and db.exists('USER', 'id', session['user_id']): # request.form looks ugly and takes too much space... param = request.json keys = param.keys() expected_keys = ['NAME', 'NIF'] # Checking for required parameters if not param or not check_keys(expected_keys, keys): return jsonify({'ERROR': error_message('invalid_request')}), 400 try: db.update('CLIENT', ['nif', 'name'], [param['NIF'], param['NAME']], 'id', session['user_id']) except Exception as e: print(e) return jsonify({'SUCCESS': False, 'ERROR': error_message('db_error')}), 200 # Everything went well return jsonify({'SUCCESS': True}), 200 return jsonify({'SUCCESS': False, 'ERROR': error_message('no_login')}), 200
def create_subscription(data): query = 'insert into subscriptions(search_type, term, quality, release_type) values (' + \ '"' + data['search_type'] + '", ' + \ '"' + data['term'] + '", ' + \ '"' + data['quality'] + '", ' + \ '"' + data['release_type'] + '")' database.update(query)
def set_outstanding(self): print("At documents") db.update(title=self.get_title(), queue=list()) if self.get_owner() != None: mail = str(self.get_owner().get_mail()) title_str = self.get_title() message = "You need to return book: " + title_str + " due that this is book is outstanding now" sm(mail, message)
def setDates(person, start_date, end_date): person = int(person) start_date = datetime.datetime.strptime(start_date, FORMAT_DATE).date() end_date = datetime.datetime.strptime(end_date, FORMAT_DATE).date() data = collections.OrderedDict({ 'start_date': start_date.toordinal(), 'end_date': end_date.toordinal() }) database.update('persons', data, { 'pid': person })
def award_xp(self): """Awards all game players XP""" for player in self.players: player.update(game=self.name, won=player.id in self.winners, draw=not self.winners) db.update(*self.players)
def add_document(self, title, date): if title in self.__info[user_document_list]: self.__info[user_document_list][title] = self.__info[ user_document_list][title] + ";" + str(date) else: self.__info[user_document_list][title] = str(date) new_doc_list = self.get_docs_list() db.update(id=self.get_id(), docs=str(new_doc_list).replace("\'", "\""))
def edit(self): confirmation = tk.messagebox.askquestion( 'Edit Data', 'Are you sure you want to edit this data') if confirmation == 'yes': data = (self.entry_product_name.get(), self.entry_price.get(), self.entry_description.get(), product_data[0]) database.update("Products ", "Name = ?, Price = ?, Description = ?", "product_id like ?", data)
def bot(request): body = json.loads(request.body) if body == {"type": "confirmation", "group_id": 194135907}: return HttpResponse('2e71f495') if body['type'] == 'message_new': print(body['object']['message']) if body['object']['message'].get('payload'): user_id = body['object']['message']['from_id'] payload = json.loads(body['object']['message'].get('payload')) if payload == {"command": "start"}: keyboard = getKeyboard() send(user_id, "Нажми на кнопку", json.dumps(keyboard)) elif payload.get('button'): button = payload.get('button') if not database.get('user', 'id=' + str(user_id)): database.insert('user', ['id', 'groupId'], [(user_id, button)]) else: database.update('user', ['groupId'], [button], 'id=' + str(user_id)) send(user_id, "Спасибо за ответ") else: message = body['object']['message']['text'] user_id = body['object']['message']['from_id'] if len(message) > 0: session_client = dialogflow.SessionsClient() df_session = session_client.session_path( DIALOGFLOW_PROJECT_ID, user_id) text_input = dialogflow.types.TextInput( text=message, language_code=DIALOGFLOW_LANGUAGE_CODE) query_input = dialogflow.types.QueryInput(text=text_input) try: response = session_client.detect_intent( session=df_session, query_input=query_input) if response.query_result.action == "update_group": keyboard = getKeyboard() send(user_id, response.query_result.fulfillment_text, json.dumps(keyboard)) else: send(user_id, response.query_result.fulfillment_text) print("Query text:", response.query_result.query_text) print( "intent/action:", response.query_result.intent.display_name + "/" + response.query_result.action) print("Detected intent confidence:", response.query_result.intent_detection_confidence) print("Fulfillment text:", response.query_result.fulfillment_text) except InvalidArgument: raise else: send(user_id, "Ого, а где текст? Я такого не понимаю") return HttpResponse('ok')
def fetch_from_url_and_store(session, url): """Fetches url from url and stores data into database Returns data """ soup = yield soup_from_url(url) ads = find_all_ads(soup) data = ads_to_string(ads) database.update(session, url, data) raise gen.Return(data)
def delete_credit_card(): ''' Turns Credit Card invisible for the user --- delete: description: Deletes credit card for the user (invisible) tags: - User requestBody: required: true content: application/json: schema: type: object properties: ID: type: number description: ID of credit card to delete responses: 200: description: A JSON containing the result of payment. content: application/json: schema: properties: SUCCESS: type: boolean 400: description: A JSON containing the ERROR that identifies the problem. content: application/json: schema: properties: ERROR: type: string ''' if 'user_id' in session and db.exists('USER', 'id', session['user_id']): # request.form looks ugly and takes too much space... param = request.json keys = param.keys() expected_keys = ['ID'] # Checking for required parameters if not param or not check_keys(expected_keys, keys): return jsonify({'ERROR': error_message('invalid_request')}), 400 try: db.update('CREDIT_CARD', ['visibility'], [0], 'id', param['ID']) except Exception as e: print(e) return jsonify({'SUCCESS': False, 'ERROR': error_message('db_error')}), 200 # Everything went well return jsonify({'SUCCESS': True}), 200 return jsonify({'SUCCESS': False, 'ERROR': error_message('no_login')}), 200
def create_plan_clicked(self): all_checkboxes = self.findChildren(QtGui.QCheckBox) all_checkboxes.reverse() checkboxes = [] counter = 0 #Go through and make sure there are 3 checked boxes for each day for i in range(0, 3): day_checkboxes = all_checkboxes[counter: counter + 7] checked_checkboxes = [] for checkbox in day_checkboxes: if checkbox.isChecked(): checked_checkboxes.append(checkbox) checkboxes.append(checked_checkboxes) if len(checked_checkboxes) < 3: self.label_CreateValidation.setText("Three muscle groups required for each day.") return counter += 7 sql_statement = "UPDATE User SET Count = 1 Where User_ID = %d" % self.user_id database.update(sql_statement) database.delete_workout(self.user_id) for checked_list in checkboxes: # For each list of 3 for each day for checked_checkbox in checked_list: # For each workout in checkbox list workout_session = WorkoutSession() workout_session.workout_number = checked_list.index(checked_checkbox) + 1 workout_session.day_number = checkboxes.index(checked_list) + 1 workout_session.user_id = self.user_id muscle_group = str(checked_checkbox.text()) if muscle_group == "Biscep": muscle_group = "Bicep" workout_session.muscle_group = muscle_group exercises = self.exercise_dict[muscle_group] random_exercise = exercises[random.randint(0, len(exercises) - 1)] workout_session.exercise = random_exercise database.insert_workout_session(workout_session) self.stackedWidget.setCurrentIndex(2) self.DisableCheckBoxes()
def delete(self): """ 通过db对象的 update接口 执行SQL SQL: delete from `user` where `id`=%s, ARGS: (10190,) """ self.pre_delete and self.pre_delete() pk = self.__primary_key__.name args = (getattr(self, pk), ) database.update('delete from `%s` where `%s`=?' % (self.__table__, pk), *args) return self
def queue(data): data = json.loads(data) query = 'insert into torrents(id, artist, album, release, quality, added, downloaded) values ("' + \ str(data['id']) + '", "' + \ data['artist'] + '", "' + \ data['album'] + '", "' + \ data['displayTitle'] + '", "' + \ data['media'] + " / " + data['format'] + " " + \ data['encoding'] + '", ' + \ 'datetime("now"), 0)' database.update(query)
def download_torrent(torrent_id): download_link = wat.download_link(torrent_id) download_path = settings.get('torrent')[1] save_to = download_path + torrent_id + ".torrent" opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] torrent = opener.open(download_link).read() output = open(save_to,'wb') output.write(torrent) output.close() print "Downloaded " + torrent_id + ".torrent" database.update('update torrents set downloaded = 1 where id = "' + torrent_id + '"')
def action_4(self): """ `action_4` -> Update If everything works finde -> create self.response If something goes wrong -> raise Exception """ if len(self.parsed_request) != 4: raise Exception(response.error_invalid_request) try: pk = self.parsed_request["pk"] if invalid_pk(pk): raise nonce = nacl.encoding.Base64Encoder.decode(self.parsed_request["nonce"].encode("utf-8")) except: raise Exception(response.error_invalid_request) if not database.reverse_lookup(pk): raise Exception(response.error_update) try: payload_encrypted = self.parsed_request["encrypted"].encode("utf-8") payload_encrypted = nacl.encoding.Base64Encoder.decode(payload_encrypted) pk_byte = pk.encode("utf-8") client_pk = PublicKey(pk_byte, nacl.encoding.HexEncoder) payload_decrypted = crypto.decrypt_request(crypto.secKey, client_pk, payload_encrypted, nonce) new_toxid = payload_decrypted.decode("utf-8") if len(new_toxid) != 76: raise if not pk == new_toxid[:64]: raise if crypto.compute_checksum(new_toxid[:64], new_toxid[64:72]) != new_toxid[72:]: raise except: raise Exception(response.error_invalid_request) database.update(new_toxid) self.response = {"success_action_4": "The username has been updated."}
def put(self, email): self.isLegalUser(email) if self.request.url.endswith(email): self.checkData(update(email, self.request.body)) elif self.request.url.endswith('retreat'): self.isAdmin(email) self.checkData(retreatUpdate(self.request.body)) else: self.abort(404)
def put(self, email): if not self.isLegalUser(email): self.error(404) else: if self.request.url.endswith('apply'): data = mafUpdate(email, self.request.body) else: data = update(email, self.request.body) self.checkData(data)
def edit_menu_item(object_kind, menu_item_id): response = '' post_data = request.get_json() print post_data print type(post_data) if post_data['action'] == 'update': response = database.update(api_db_mapping.mapping[object_kind]['object_type'], post_data['store']) return jsonify(response)
def deploy(): """ Deploy the web application to remote server(s) """ require('environment', provided_by=('staging', 'production')) ## TODO: early initialization steps go here if env.get('initial_deploy'): code.copy_website_skeleton() solr.make_common_skeleton() with settings(warn_only=True): webserver.stop() code.update() venv.update_requirements() db.update() solr.update_app() solr.update_index() static.collect_files() webserver.clear_logs() webserver.start()
def saveProgress(self): workout_sessions = database.get_current_workouts(self.user_id) weight = -1 set1 = -1 set2 = -1 set3 = -1 week = -1 day = -1 workout_number = -1 if self.tabWidget.currentIndex() == 0: week = workout_sessions[0].week_number day = workout_sessions[0].day_number workout_number = 1 weight = self.lineEditWeight_2.text() set1 = self.lineEditSet1.text() set2 = self.lineEditSet2.text() set3 = self.lineEditSet3.text() if self.tabWidget.currentIndex() == 1: week = workout_sessions[1].week_number day = workout_sessions[1].day_number workout_number = 2 weight = self.lineEditWeight_3.text() set1 = self.lineEditSet1_2.text() set2 = self.lineEditSet2_2.text() set3 = self.lineEditSet3_2.text() if self.tabWidget.currentIndex() == 2: week = workout_sessions[2].week_number day = workout_sessions[2].day_number workout_number = 3 weight = self.lineEditWeight_4.text() set1 = self.lineEditSet1_3.text() set2 = self.lineEditSet2_3.text() set3 = self.lineEditSet3_3.text() sql_statement = "UPDATE Workout_Session SET Weight = %d, Set_1 = %d, Set_2 = %d, Set_3 = %d WHERE Workout_Number = %d and Week_Number = %d and Day_Number = %d and User_ID = %d" % \ (int(weight), int(set1), int(set2), int(set3), workout_number, week, day, self.user_id) completed = database.update(sql_statement) self.nextTab()
def do_POST(self): try: parsed_url = urlparse(self.path) self.path = parsed_url.path # initialize mime type to be application/json mime_type = mime_types.get('json') # initialize response to client response = '' # api request if is_api(self.path): api_regex_match = get_api_match(self.path) # extract api call from request api_call = api_regex_match.group(3) api_params = parse_qs(parsed_url.query) # load post data and convert to dict post_data = from_json(self.rfile.read(int(self.headers.getheader('Content-Length')))) if post_data['action'] == 'update': response = to_json(database.update(api_db_mapping.mapping[api_call]['object_type'], from_json(post_data['store']))) elif post_data['action'] == 'delete': response = to_json(database.delete(api_db_mapping.mapping[api_call]['object_type'], from_json(post_data['store']))) self.send_response(200) self.send_header('Content-type', mime_type) self.end_headers() self.wfile.write(response) print response return except IOError: self.send_error(404, 'File not found: %s' % self.path)
def _value_added_process(entries=None, language=None, transcoder_type='chengdujin'): """ add more value to an entry tts, transcode, images, redis_entry_expiration, database_entry_expiration """ if not entries: logger.error('Method malformed!') return None if not language or language not in LANGUAGES: logger.error("Language not found or not supported!") return None updated_entries = [] for i, entry in enumerate(entries): try: logger.info('... Working on %i of %d ...' % (i + 1, len(entries))) logger.info(entry['title']) logger.info(entry['link']) # [MUST-HAVE] transcoding # get a random int from 100 million possibilities rand = random.randint(0, 100000000) transcoded_relative_path = '%s_%s_%s_%i' % ( entry['language'], entry['feed_id'], entry['updated'], rand) # high chances transcoder cannot work properly entry['transcoded'], entry[ 'transcoded_local'], raw_transcoded_content, \ images_from_transcoded = transcoder.convert( entry['language'], entry['title'], entry['link'], entry['updated'], entry['feed'], transcoder_type, transcoded_relative_path) if entry['transcoded']: # [OPTIONAL] summary if entry['summary'] or raw_transcoded_content: summary_found = summarizer.extract(entry['language'], entry['title'], str( raw_transcoded_content), entry[ 'summary'], entry['link'], entry['feed'], '*|*'.join( entry['categories'])) entry['summary'] = summary_found #entry['summary'] = entry['summary'] if 'summary' in entry # and entry['summary'] else None # [OPTIONAL] images # process images found in the transcoded data if images_from_transcoded: # images from transcoded are already normalized entry['images'].extend(images_from_transcoded) # remove duplicated images images_deduped = illustrator.dedup_images( entry['images']) if entry.has_key('images') and entry[ 'images'] else None # be cautious dedup_images might return None if network # sucks if images_deduped: entry['images'] = images_deduped entry['images'] = entry[ 'images'] if 'images' in entry and entry['images'] else None # [OPTIONAL] generate 3 types of images: thumbnail, # category image and hot news image if entry.has_key('images') and entry['images']: biggest = illustrator.find_biggest_image(entry['images']) if biggest: entry = _generate_images(biggest, entry, rand) # for older version users entry['image'] = entry['thumbnail_image'][ 'url'] if 'thumbnail_image' in entry and entry[ 'thumbnail_image'] else None # [OPTIONAL] text image # if no category_image is found, generate a text-image if 'category_image' not in entry or ( 'category_image' in entry and not entry[ 'category_image']): image_relative_path = '%s_%s_%s_%i' % ( entry['language'], entry['feed_id'], entry['updated'], rand) try: text_img = text2img.Text2Image( language, entry['title'], '%s_textimage.png' % image_relative_path) entry['text_image'] = text_img.get_image() except Exception as k: logger.error( 'Problem [%s] generating text2image for [%s]' % ( str(k), entry['link'])) # [OPTIONAL] google tts not for indonesian if entry['language'] != 'in': # you dont get None in _get_tts # at worst the original entry is returned entry = _get_tts(entry, rand) # [MUST-HAVE] add expiration data def _expired(updated, days_to_deadline): """ compute expiration information return time string and unix time """ deadline = datetime.utcfromtimestamp( updated) + timedelta(days=days_to_deadline) return time.asctime( time.gmtime(calendar.timegm(deadline.timetuple()))) entry['memory_expired'] = _expired( entry['updated'], MEMORY_EXPIRATION_DAYS) entry['database_expired'] = _expired( entry['updated'], DATABASE_REMOVAL_DAYS) # [OPTIONAL] if logger is used, this could be removed entry['error'] = entry[ 'error'] if 'error' in entry and entry['error'] else None # [MUST-HAVE] update new entry to db_news # each entry is added with _id entry = db_news.update(entry) if entry: # [MUST-HAVE] store in memory result = memory.update(entry) if result: updated_entries.append(entry) else: logger.error('Error found in updating memory') # remove entry in database if clean_database.clean_by_item(entry): logger.info( 'Cleaned %s in database' % entry['title']) else: logger.error( 'Error cleaning %s in database' % entry[ 'title']) # remove entry-created files on disk if clean_disk.clean_by_item(entry): logger.info('Cleaned %s on disk' % entry['title']) else: logger.error( 'Error cleaning %s on disk' % entry['title']) continue else: logger.error('Error found in updating to news database') # remove entry-created files on disk if clean_disk.clean_by_item(entry): logger.info('Cleaned %s on disk' % entry['title']) else: logger.error( 'Error cleaning %s on disk' % entry['title']) continue else: logger.info('Error found in transcoding') continue except Exception as k: logger.error(str(k)) continue # the FINAL return if updated_entries: return True else: logger.info('No entry got value added!') return False
WHERE websites.id_domains = domains.id AND domains.name = '%s' AND websites.id_users = '%s'""" % (domain, id_user)) if len(sites) == 0: print 'Aucun site portant ce domaine n\'existe sous votre nom' sys.exit() site = list(sites)[0] site_id = site.id try: if site.enabled == "yes": enabled = choices('Voulez-vous Éditer ou Désactiver le site ?', dict(e='edit', d='no'), default='e') else: enabled = choices('Voulez-vous Éditer ou Activer le site ?', dict(e='edit', a='yes'), default='e') except KeyboardInterrupt: print sys.exit() if enabled == "edit": config = editor(filling=site.config.encode('utf8')).decode('utf8') db.update('websites', where='id = $site_id', config=config, vars=locals()) print 'La configuration de %s a été mise à jour.' % domain else: db.update('websites', where='id = $site_id', enabled=enabled, vars=locals()) print 'Le site %s a été %s' % (domain, {'yes':'activé', 'no':'désactivé'}[enabled]) print 'N\'oubliez pas de relancer Lighttpd pour l\'appliquer' print 'avec restart-lighttpd.'
name = input("name: ") found = str(database.select_one('directory.txt', name)) if found == "None": print("Name not in directory") else: print(found) if type=="d": name = input("name: ") found = str(database.select_one('directory.txt', name)) if found == "None": print("Name not in directory") else: database.delete('directory.txt', name) if type=="u": name = input("name: ") found = str(database.select_one('directory.txt', name)) if found == "None": print("Name not in directory") else: number = input("new number: ") database.update('directory.txt', name, number) if type=="q": break
id_user = list(userfromdb)[0].id while True: email = text('Adresse email à modifier :') if re.match(r'''^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$''', email): break (username, domain) = email.split('@') password = passwd('Nouveau mot de passe :') mailboxes = db.query('''SELECT mailboxes.id FROM mailboxes, domains WHERE mailboxes.domain_id = domains.id AND id_users = $id_user AND name = $domain AND user = $username''', vars=locals()) if len(mailboxes) == 0: print 'Cette adresse mail n\'existe pas !' print sys.exit() mailbox_id = list(mailboxes)[0].id db.update('mailboxes', password=md5(password).hexdigest(), where='id = $mailbox_id', vars=locals()) print 'Le mot de passe pour la boite mail `%s@%s`' % (username, domain) print 'a été changé pour `%s`.' % password
def update(id): data = request.form count = database.update(data) resp = Response(status=200, content_type='application/json') resp.data = {'count': count} return resp