Форум сайта python.su
from aiohttp import web import asyncio async def send_msg1(app): while True: for ws in app['admin_sockets']: await ws.send_str('msg1') await asyncio.sleep(10) async def send_msg2(app): while True: for ws in app['admin_sockets']: await ws.send_str('msg2') await asyncio.sleep(20) async def ws_handler(request): ws = web.WebSocketResponse() await ws.prepare(request) is_admin = request.path.startswith('/ws/admin') a_socks = request.app['admin_sockets'] u_socks = request.app['user_sockets'] if is_admin: a_socks.append(ws) else: u_socks.append(ws) try: async for msg in ws: await ws.send_str(msg.data) except Exception as e: pass finally: if is_admin: a_socks.remove(ws) else: u_socks.remove(ws) return ws app = web.Application() app.router.add_get('/ws', ws_handler) app.router.add_get('/ws/admin', ws_handler) app['admin_sockets'] = [] app['user_sockets'] = [] loop = asyncio.get_event_loop() loop.create_task(send_msg1(app)) loop.create_task(send_msg2(app))
myFile = open("input.txt", "r", encoding="utf8") k = int(myFile.readline()) myList = [] for line in myFile: newLine = line.split() if int(newLine[-1]) >= 40 and int(newLine[-2]) >= 40 \ and int(newLine[-3]) >= 40: myList.append(newLine) myFile.close() myList.sort(key=lambda a: int(a[-1]) + int(a[-2]) + int(a[-3])) myList.reverse() konk = [] for i in myList: sum = int(i[-1]) + int(i[-2]) + int(i[-3]) konk.append(sum) n = len(konk) def konkurs(n, k, konk): if n <= k: return 0 elif konk[k] == konk[0]: return 1 for i in range(k, 0, -1): if konk[i] < konk[i - 1]: return konk[i - 1] print(konkurs(n, k, konk))
fileInput = open('input.txt', 'r', encoding='utf8') scoreList = [] k = int(fileInput.readline()) for line in fileInput: i = line.split() if int(i[-1]) >= 40 and int(i[-2]) >= 40 and int(i[-3]) >= 40: scoreList.append(int(i[-1]) + int(i[-2]) + int(i[-3])) fileInput.close() lenScoreList = len(scoreList) scoreList.sort() def minScore(n, k, sL): if n <= k: return 0 elif sL[-k] == sL[n + 1]: return 1 for i in range(-k, -1): if sL[i] < sL[i + 1]: return sL[i + 1] print(minScore(lenScoreList, k, scoreList))
systemctl status gunicorn
[Unit] 2 Description=gunicorn daemon 3 After=network.target 4 5 [Service] 6 User=root 7 Group=www-data 8 WorkingDirectory=/root/projects/chat 9 ExecStart=/root/projects/chat/chat_env/bin/gunicorn --workers 3 --bind unix:/root/projects/chat/chat.sock chat.wsgi:application 10 11 [Install] 12 WantedBy=multi-user.target 13
Jan 24 21:16:02 localhost gunicorn[4856]: File "/root/projects/chat/chat_env/lib/python3.5/site-packages/gunicorn/util.py", line 352, in import_app Jan 24 21:16:02 localhost gunicorn[4856]: __import__(module) Jan 24 21:16:02 localhost gunicorn[4856]: ImportError: No module named 'chat.wsgi'
tree -L 3
├── chat 3 │ ├── chat 4 │ │ ├── __init__.py 5 │ │ ├── __pycache__ 6 │ │ ├── settings.py 7 │ │ ├── urls.py 8 │ │ └── wsgi.py 9 │ ├── manage.py 10 │ └── static 11 │ └── admin 12 ├── chat_env 13 │ ├── bin 14 │ │ ├── activate 15 │ │ ├── activate.csh 16 │ │ ├── activate.fish 17 │ │ ├── activate_this.py 18 │ │ ├── django-admin 19 │ │ ├── django-admin.py 20 │ │ ├── easy_install 21 │ │ ├── easy_install-3.5 22 │ │ ├── gunicorn 23 │ │ ├── gunicorn_paster 24 │ │ ├── pip 25 │ │ ├── pip3 26 │ │ ├── pip3.5 27 │ │ ├── __pycache__ 28 │ │ ├── python -> python3 29 │ │ ├── python3 30 │ │ ├── python3.5 -> python3 31 │ │ ├── python-config 32 │ │ └── wheel 33 │ ├── include 34 │ │ └── python3.5m -> /usr/include/python3.5m 35 │ ├── lib 36 │ │ └── python3.5 37 │ └── pip-selfcheck.json
import os import imaplib import email import base64 import email.message import base64 imaplib.IMAP4.debug = imaplib.IMAP4_SSL.debug = 1 con = imaplib.IMAP4_SSL('imap.mail.ru',993) con.login('pythonsutest@mail.ru','ktozdes90') con.select() typ, data = con.search(None, 'ALL') print(data) for num in data[0].split(): typ, data = con.fetch(num, '(RFC822)') print(num) msg = email.message_from_bytes(data[0][1]) print(msg['Subject']) msg2 = ascii(msg) print(msg2) my_file = open("text.txt", "a") my_file.close() msg3 = "" if msg.is_multipart(): for part in msg.get_payload(): if part.get_content_maintype() == 'text' and part.get('Content-Disposition') == None: msg_body = part.get_payload(decode=1) msg3 = ascii(msg_body) my_file = open("text.txt", "a") my_file.write(ascii(msg_body)) my_file.close() print(msg3) con.close() con.logout()
1) Написать программу, которая разделяет исходную выборку на обучающую и тестовую (training set, validation set, test set)И вот с третьим проблемы.
2) С использованием библиотеки scikit-learn (http://scikit-learn.org/stable/) обучить модель линейной регрессии по обучающей выборке (пример: http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html#sphx-glr-auto-examples-linear-model-plot-ols-py)
3) Построить модель с использованием полиномиальной функции (пример: http://scikit-learn.org/stable/auto_examples/model_selection/plot_underfitting_overfitting.html#sphx-glr-auto-examples-model-selection-plot-underfitting-overfitting-py). Построить графики зависимости ошибки от степени полиномиальной функции.
from sklearn import linear_model from sklearn.metrics import r2_score, mean_squared_error from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression from sklearn.pipeline import Pipeline from sklearn.model_selection import cross_val_score import numpy as np import pandas as pd import matplotlib.pyplot as plt подкл выборку df = pd.read_table ("tic/ticdata2000.txt") cols = ['Col'] x_train = pd.read_table ("tic/ticdata2000.txt", header = None).iloc [0:4000, 0:85] x_test = pd.read_table ("tic/ticeval2000.txt", header = None) y_train = df['Col'] = df.iloc[0:4000, 84] y_test = pd.read_table ("tic/tictgts2000.txt", header = None) обучение выборки regression = linear_model.LinearRegression() regression.fit (x_train, y_train) Предсказание на основе тестового набора train_predict = regression.predict (x_train) print('Коэффициенты: \n', regression.coef_) print("Cреднеквадратичная ошибка: %.2f" % mean_squared_error(y_train, train_predict)) print('Оценка отклонения: %.2f' % r2_score(y_train, train_predict)) Проверка точности модели по тестовой выборке и запись в файл¶ columns = ['y_pred'] y_pr = pd.DataFrame(train_predict) y_test = y_test.reset_index(drop = True) res = pd.concat([y_pr, y_test], axis=1) res.to_csv("result.txt", index = False) [b]Построение полинома[/b] degrees = [1,2,3] err = [1,2,3] for i in range(len(degrees)): polynomial_features = PolynomialFeatures(degree = degrees[i], include_bias = False) linear_regression = LinearRegression() pipeline = Pipeline([("polynomial_features", polynomial_features), ("linear_regression", linear_regression)]) pipeline.fit(x_train, y_train) scores = cross_val_score(pipeline, x_train, y_train, scoring="neg_mean_squared_error") predict_y = pipeline.predict(x_test) err[i] = -scores.mean() print("\nСтепень: {}\nСреднеквадратичная ошибка = {}(+/- {})".format(degrees[i], -scores.mean(), scores.std())) print('Показатель отклонения: %.3f' % r2_score(y_test, predict_y))
MemoryError Traceback (most recent call last) <ipython-input-7-4a868cb24d24> in <module>() 10 pipeline = Pipeline([("polynomial_features", polynomial_features), 11 ("linear_regression", linear_regression)]) ---> 12 pipeline.fit(x_train, y_train) 13 scores = cross_val_score(pipeline, x_train, y_train, 14 scoring="neg_mean_squared_error") /usr/local/lib/python3.5/dist-packages/sklearn/pipeline.py in fit(self, X, y, **fit_params) 257 Xt, fit_params = self._fit(X, y, **fit_params) 258 if self._final_estimator is not None: --> 259 self._final_estimator.fit(Xt, y, **fit_params) 260 return self 261 /usr/local/lib/python3.5/dist-packages/sklearn/linear_model/base.py in fit(self, X, y, sample_weight) 487 X, y, X_offset, y_offset, X_scale = self._preprocess_data( 488 X, y, fit_intercept=self.fit_intercept, normalize=self.normalize, --> 489 copy=self.copy_X, sample_weight=sample_weight) 490 491 if sample_weight is not None: /usr/local/lib/python3.5/dist-packages/sklearn/linear_model/base.py in _preprocess_data(X, y, fit_intercept, normalize, copy, sample_weight, return_mean) 166 167 X = check_array(X, copy=copy, accept_sparse=['csr', 'csc'], --> 168 dtype=FLOAT_DTYPES) 169 y = np.asarray(y, dtype=X.dtype) 170 /usr/local/lib/python3.5/dist-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator) 400 force_all_finite) 401 else: --> 402 array = np.array(array, dtype=dtype, order=order, copy=copy) 403 404 if ensure_2d: MemoryError:
my @result = $service->method(SOAP::Data->name('MyDate')->value('Value'));
result=client.service.method({'MyDate':'Value'})