Форум сайта python.su
from binance.spot import Spot client = Spot() print(client.time()) client = Spot(key="<api_key>", secret="<api_secret>") { "timezone": "UTC", "serverTime": 1565246363776, } # Get account information print(client.account()) # Post a new order params = { "symbol": "BTCBUSD", "side": "BUY", "type": "LIMIT", "timeInForce": "GTC", "quantity": "0.00001" , "price": "60000" } # Post a new order params = { "symbol": "BTCBUSD", "side": "SELL", "type": "LIMIT", "timeInForce": "GTC", "quantity": "0.00001", "price": "63000" }
#Models.py class Worker(models.Model): names = models.CharField('Продавец', max_length=30) sum = models.DecimalField('Доход за смену', max_digits=7, decimal_places=0) time_create = models.DateTimeField('Время записи данных', auto_now_add=True) class Supervisor(models.Model): sum = models.DecimalField('Сумма расхода, руб.', max_digits=7, decimal_places=0) description = models.CharField('Статья расхода', max_length=50) time_create = models.DateTimeField('Время записи данных', auto_now_add=True) #Views.py queryset_1 = Worker.objects.all() \ .filter(time_create__year=2021) \ .filter(time_create__month=10) \ .values('sum') \ .annotate(date_item=TruncDate('time_create')) \ .order_by('date_item') queryset_2 = Supervisor.objects.all() \ .filter(time_create__year=2021) \ .filter(time_create__month=10) \ .values('sum') \ .annotate(date_item=TruncDate('time_create')) \ .order_by('date_item') categories = list() data_series_1 = list() data_series_2 = list() for entry in queryset_1: categories.append('%s' % entry['date_item']) data_series_1.append(entry['sum']) return render(request, 'line1/boss.html', { 'categories': json.dumps(categories), 'data_series_1': json.dumps(data_series_1, default=custom_serializer) # 'data_series_2': json.dumps(data_series_2, default=custom_serializer) })
from math import sqrt from numpy import concatenate from matplotlib import pyplot from pandas import read_csv from pandas import DataFrame from pandas import concat from sklearn import metrics from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import LabelEncoder from sklearn.metrics import mean_squared_error from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM # convert series to supervised learning def series_to_supervised(data, n_in=1, n_out=1, dropnan=True): n_vars = 1 if type(data) is list else data.shape[1] df = DataFrame(data) cols, names = list(), list() # input sequence (t-n, ... t-1) for i in range(n_in, 0, -1): cols.append(df.shift(i)) names += [('var%d(t-%d)' % (j + 1, i)) for j in range(n_vars)] # forecast sequence (t, t+1, ... t+n) for i in range(0, n_out): cols.append(df.shift(-i)) if i == 0: names += [('var%d(t)' % (j + 1)) for j in range(n_vars)] else: names += [('var%d(t+%d)' % (j + 1, i)) for j in range(n_vars)] # put it all together agg = concat(cols, axis=1) agg.columns = names # drop rows with NaN values if dropnan: agg.dropna(inplace=True) return agg # load dataset dataset = read_csv('pollution.csv', header=0, index_col=0) values = dataset.values # integer encode direction encoder = LabelEncoder() values[:, 4] = encoder.fit_transform(values[:, 4]) # ensure all data is float values = values.astype('float32') # normalize features scaler = MinMaxScaler(feature_range=(0, 1)) scaled = scaler.fit_transform(values) # frame as supervised learning reframed = series_to_supervised(scaled, 1, 1) # drop columns we don't want to predict reframed.drop(reframed.columns[[9, 10, 11, 12, 13, 14, 15]], axis=1, inplace=True) print(reframed.head()) # split into train and test sets values = reframed.values n_train_hours = 365 * 24 train = values[:n_train_hours, :] test = values[n_train_hours:, :] # split into input and outputs train_X, train_y = train[:, :-1], train[:, -1] test_X, test_y = test[:, :-1], test[:, -1] # reshape input to be 3D [samples, timesteps, features] train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1])) test_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1])) print(train_X.shape, train_y.shape, test_X.shape, test_y.shape) # design network model = Sequential() model.add(LSTM(100, input_shape=(train_X.shape[1], train_X.shape[2]))) model.add(Dense(1)) model.compile(loss='mae', optimizer='adam', metrics=['accuracy']) # fit network history = model.fit(train_X, train_y, epochs=5, batch_size=54, validation_data=(test_X, test_y), verbose=2) train_acc = model.evaluate(train_X, train_y, verbose=2) test_acc = model.evaluate(test_X, test_y, verbose=2) # plot history pyplot.subplot(211) pyplot.title('Loss') pyplot.plot(history.history['loss'], label='train') pyplot.plot(history.history['val_loss'], label='test') pyplot.legend() pyplot.subplot(212) pyplot.title('Accuracy') pyplot.plot(history.history['accuracy'], label='train') pyplot.plot(history.history['val_accuracy'], label='test') pyplot.legend() pyplot.show() # make a prediction yhat = model.predict(test_X) test_X = test_X.reshape((test_X.shape[0], test_X.shape[2])) # invert scaling for forecast inv_yhat = concatenate((yhat, test_X[:, 1:]), axis=1) inv_yhat = scaler.inverse_transform(inv_yhat) inv_yhat = inv_yhat[:, 0] # invert scaling for actual test_y = test_y.reshape((len(test_y), 1)) inv_y = concatenate((test_y, test_X[:, 1:]), axis=1) inv_y = scaler.inverse_transform(inv_y) inv_y = inv_y[:, 0] # calculate RMSE rmse = sqrt(mean_squared_error(inv_y, inv_yhat)) print('Test RMSE: %.3f' % rmse)
import socket import time import threading import os HOST = '127.0.0.1' PORT = 8888 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((HOST, PORT)) def send_message(): print('Enter name: ') name = input() while True: data = client.recv(1024) print(data.decode('utf-8')) msg = (f'{name} send message {data}') client.send(msg.encode('utf-8')) # this def send_server(): listen_thread = threading.Thread(target=send_message) listen_thread.start() while True: client.send(input('you: ').encode('utf-8')) if __name__ == '__main__': os.system('clear') print('***** Welcome in Security Chat. *****') send_server()
import socket import time import threading import os HOST = '127.0.0.1' PORT = 8888 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((HOST, PORT)) def send_message(): print('Введите имя: ') name = input() while True: data = client.recv(1024) print(data.decode('utf-8')) msg = (f'{name} send message {data}') # здесь ошибка client.send(msg.encode('utf-8')) # и может здесь def send_server(): listen_thread = threading.Thread(target=send_message) listen_thread.start() while True: client.send(input('you: ').encode('utf-8')) if __name__ == '__main__': os.system('clear') print('***** Welcome in Security Chat. *****') send_server()
{“type”: “FeatureCollection”, “features”: [пробовал 2 способа:
{“type”: “Feature”, “geometry”: {“type”: “Point”, “coordinates”: }, “properties”: {“id”: 1563301, “gibdd_id”: “195406532”, “point”: {“lat”: 55.961122, “long”: 37.412325}, “participant_categories”: , “severity”: “Тяжёлый”, “region”: “Молжаниновский”, “parent_region”: “Москва”, “datetime”: “2016-07-11 21:20:00”, “address”: “г Москва, ш Международное”, “participants_count”: 2, “injured_count”: 1, “dead_count”: 0, “category”: “Наезд на пешехода”, “light”: “Светлое время суток”, “nearby”: , “weather”: , “road_conditions”: , “vehicles”: [{“brand”: “ВАЗ”, “model”: “Kalina”, “color”: “Серый”, “year”: 2011, “category”: “А-класс (особо малый) до 3,5 м”, “participants”: [{“health_status”: “Не пострадал”, “role”: “Водитель”, “gender”: “Мужской”, “years_of_driving_experience”: 6, “violations”: }]}], “participants”: [{“health_status”: “Раненый, находящийся (находившийся) на стационарном лечении”, “role”: “Пешеход”, “gender”: “Мужской”, “violations”: }], “tags”: , “scheme”: “820”}},
{“type”: “Feature”, “geometry”: {“type”: “Point”, “coordinates”: }, “properties”: {“id”: 1529678, “gibdd_id”: “192559706”, “point”: {“lat”: 55.883, “long”: 37.606}, “participant_categories”: , “severity”: “Легкий”, “region”: “Бибирево”, “parent_region”: “Москва”, “datetime”: “2016-04-14 19:10:00”, “address”: “г Москва, ул Плещеева, 4”, “participants_count”: 3, “injured_count”: 2, “dead_count”: 0, “category”: “Наезд на пешехода”, “light”: “Светлое время суток”, “nearby”: , “weather”: , “road_conditions”: , “vehicles”: [{“brand”: “SKODA”, “model”: “Octavia”, “color”: “Серый”, “year”: 2012, “category”: “В-класс (малый) до 3,9 м”, “participants”: [{“health_status”: “Не пострадал”, “role”: “Водитель”, “gender”: “Женский”, “years_of_driving_experience”: 16, “violations”: }]}], “participants”: [{“health_status”: “Раненый, находящийся (находившийся) на амбулаторном лечении, либо которому по характеру полученных травм обозначена необходимость амбулаторного лечения (вне зависимости от его фактического прохождения)”, “role”: “Пешеход”, “gender”: “Женский”, “violations”: }, {“health_status”: “Раненый, находящийся (находившийся) на амбулаторном лечении, либо которому по характеру полученных травм обозначена необходимость амбулаторного лечения (вне зависимости от его фактического прохождения)”, “role”: “Пешеход”, “gender”: “Мужской”, “violations”: }], “tags”: , “scheme”: “820”}},
import json import pandas as pd with open(r'moskva.geojson', encoding="utf-8") as f: data = json.loads(f.read()) data_nested = pd.json_normalize(data, record_path =['features'], max_level=3) print(data_nested.head())
import json from flatten_json import flatten import pandas as pd with open(r'moskva.geojson', encoding="utf-8") as f: data = json.loads(f.read()) flat = flatten(data) data_nested = pd.json_normalize(flat) print(data_nested.head())
import random from tkinter import * SIZE = 400 GRID_LEN = 4 GRID_PADDING = 10 BACKGROUND_COLOR_GAME = "#92877d" BACKGROUND_COLOR_CELL_EMPTY = "#9e948a" BACKGROUND_COLOR_DICT = {2: "#eee4da", 4: "#ede0c8", 8: "#f2b179", 16: "#f59563", 32: "#f67c5f", 64: "#f65e3b", 128: "#edcf72", 256: "#edcc61", 512: "#edc850", 1024: "#edc53f", 2048: "#edc22e"} CELL_COLOR_DICT = {2: "#776e65", 4: "#776e65", 8: "#f9f6f2", 16: "#f9f6f2", 32: "#f9f6f2", 64: "#f9f6f2", 128: "#f9f6f2", 256: "#f9f6f2", 512: "#f9f6f2", 1024: "#f9f6f2", 2048: "#f9f6f2"} FONT = ("Verdana", 40, "bold") KEY_UP = "'w'" KEY_DOWN = "'s'" KEY_LEFT = "'a'" KEY_RIGHT = "'d'" mainframe = Frame() grid_cells = [] matrix = [] def init_matrix(): for i in range(GRID_LEN): matrix.append([0] * GRID_LEN) add_two() add_two() # add_two() def add_two(): a = random.randint(0, len(matrix)-1) b = random.randint(0, len(matrix)-1) while(matrix[a][b] != 0): a = random.randint(0, len(matrix)-1) b = random.randint(0, len(matrix)-1) matrix[a][b] = 2 def game_state(): for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 2048: return 'win' for i in range(len(matrix)-1): for j in range(len(matrix[0])-1): if matrix[i][j] == matrix[i+1][j] or matrix[i][j+1] == matrix[i][j]: return 'not over' for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 0: return 'not over' for k in range(len(matrix)-1): if matrix[len(matrix)-1][k] == matrix[len(matrix)-1][k+1]: return 'not over' for j in range(len(matrix)-1): if matrix[j][len(matrix)-1] == matrix[j+1][len(matrix)-1]: return 'not over' return 'lose' def reverse(mat): new = [] for i in range(len(mat)): new.append([]) for j in range(len(mat[0])): new[i].append(mat[i][len(mat[0])-j-1]) return new def transpose(mat): new = [] for i in range(len(mat[0])): new.append([]) for j in range(len(mat)): new[i].append(mat[j][i]) return new def cover_up(mat): new = [] for i in range(len(mat)): new.append([0] * len(mat)) done = False for i in range(len(mat)): count = 0 for j in range(len(mat)): if mat[i][j] != 0: new[i][count] = mat[i][j] if j != count: done = True count += 1 return (new, done) def merge(mat): done = False for i in range(len(mat)): for j in range(len(mat)-1): if mat[i][j] == mat[i][j+1] and mat[i][j] != 0: mat[i][j] *= 2 mat[i][j+1] = 0 done = True return (mat, done) def up(): global matrix matrix = transpose(matrix) game, done = cover_up(matrix) temp = merge(matrix) matrix = temp[0] done = done or temp[1] matrix = cover_up(matrix)[0] matrix = transpose(matrix) return done def down(): global matrix matrix = reverse(transpose(matrix)) matrix, done = cover_up(matrix) temp = merge(matrix) matrix = temp[0] done = done or temp[1] matrix = cover_up(matrix)[0] matrix = transpose(reverse(matrix)) return done def left(): global matrix matrix, done = cover_up(matrix) temp = merge(matrix) matrix = temp[0] done = done or temp[1] matrix = cover_up(matrix)[0] return done def right(): global matrix matrix = reverse(matrix) matrix, done = cover_up(matrix) temp = merge(matrix) matrix = temp[0] done = done or temp[1] matrix = cover_up(matrix)[0] matrix = reverse(matrix) return done def init_grid(): background = Frame(bg=BACKGROUND_COLOR_GAME, width=SIZE, height=SIZE) background.grid() for i in range(GRID_LEN): grid_row = [] for j in range(GRID_LEN): cell = Frame(background, bg=BACKGROUND_COLOR_CELL_EMPTY, width=SIZE / GRID_LEN, height=SIZE / GRID_LEN) cell.grid(row=i, column=j, padx=GRID_PADDING, pady=GRID_PADDING) t = Label(master=cell, text="", bg=BACKGROUND_COLOR_CELL_EMPTY, justify=CENTER, font=FONT, width=5, height=2) t.grid() grid_row.append(t) grid_cells.append(grid_row) def update_grid_cells(): for i in range(GRID_LEN): for j in range(GRID_LEN): if matrix[i][j] == 0: grid_cells[i][j].configure(text="", bg=BACKGROUND_COLOR_CELL_EMPTY) else: grid_cells[i][j].configure(text=str(matrix[i][j]), bg=BACKGROUND_COLOR_DICT[matrix[i][j]], fg=CELL_COLOR_DICT[matrix[i][j]]) def key_down(event): key = repr(event.char) if key in mainframe.commands: done = mainframe.commands[repr(event.char)]() if done: add_two() update_grid_cells() if game_state() == 'win': grid_cells[1][1].configure(text="You", bg=BACKGROUND_COLOR_CELL_EMPTY) grid_cells[1][2].configure(text="Win!", bg=BACKGROUND_COLOR_CELL_EMPTY) if game_state() == 'lose': grid_cells[1][1].configure(text="You", bg=BACKGROUND_COLOR_CELL_EMPTY) grid_cells[1][2].configure(text="Lose!", bg=BACKGROUND_COLOR_CELL_EMPTY) grid_cells[2][1].configure(text="Score:", bg=BACKGROUND_COLOR_CELL_EMPTY) grid_cells[2][2].configure(text=get_score, bg=BACKGROUND_COLOR_CELL_EMPTY) score = 0 def get_score(): score = 0 for r in _map_data: for c in range(len(matrix)): score += 0 if c < 4 else c * int((math.log(c, 2) - 1.0)) return score # Импортировать математический модуль def main(): mainframe.master.title('2048') mainframe.master.bind("<Key>", key_down) mainframe.commands = {KEY_UP: up, KEY_DOWN: down, KEY_LEFT: left, KEY_RIGHT: right} init_grid() init_matrix() update_grid_cells() mainloop() if __name__ == '__main__': main()
import pyowm import random2 import telebot from time import sleep from random import choice @bot.message_handler(commands =['Game'] ) def game(message): bot.send_message(message.chat.id, "Введите ваш цвет(список:Зеленый Желтый Красный Синий)") colors = ['Желтый', 'Зеленый', 'Красный', 'Синий'] random_color = (choice(colors)).lower() color_user = message.text.lower() if color_user == random_color: bot.send_message(message.chat.id, 'Ты угадал!Цвет был ' + random_color) else: bot.send_message(message.chat.id,'Ты не угадал!Цвет был ' + random_color)
openapi_client.exceptions.ApiTypeError: Invalid type for variable 'activated'. Required value type is datetime and passed type was NoneType at ['received_data'][0]['activated']