Форум сайта python.su
corpus = NLPTaskDataFetcher.load_classification_corpus(Path('../'), test_file='test.csv', dev_file='dev.csv', train_file='train.csv') word_embeddings = [WordEmbeddings('glove'), FlairEmbeddings('news-forward-fast'), FlairEmbeddings('news-backward-fast')] document_embeddings = DocumentLSTMEmbeddings(word_embeddings, hidden_size=512, reproject_words=True, reproject_words_dimension=256) classifier = TextClassifier(document_embeddings, label_dictionary=corpus.make_label_dictionary(), multi_label=False) trainer = ModelTrainer(classifier, corpus) trainer.train('../', max_epochs=10) # error cpuinfo
import threading import tornado.websocket import tornado.web import tornado.ioloop import lxml.etree as ET #обработчик запросов к http серверу strfile="client.html" class MainHandler(tornado.web.RequestHandler): #обработка запроса get def get(self): print('Get') #передаем нашу страницу в которой реализована работа с клиентом self.render(strfile) #обработчик событий вебсоккетов class EchoWebSocket(tornado.websocket.WebSocketHandler): clients = []#массив клиентов fl = True index = 0 #процедура отправки клиенту текущего индекса через 3 сек def go(self,client): print('ok') if(self.fl): self.index=self.index+1 s = u'{"type": "chat", "data": "' +str(self.index) +'"}' print("send message : "+s) #посылаем сообщение клиенту client.write_message(s) #проверяются и датся права на действия с соккетом, здесь права даются всем def check_origin(self, origin): return True #обработка события открытия соединения def open(self): print("Client open") #добавляем клиента в список self.clients.append(self) self.fl = True #запускаем поток отправки сообщение клиенту self.go(self) #обработка прихода события от сервера######################## def on_message(self, message): print("Client message "+message) #парсим xml файл в dom dom = ET.parse("file.xml") #парсим шаблон в dom xslt = ET.parse("file.xslt") #получаем трансформер transform = ET.XSLT(xslt) #преобразуем xml с помощью трансформера xslt newhtml = transform(dom) #преобразуем из памяти dom в строку, возможно, понадобится указать кодировку strfile = ET.tostring(newhtml)###новая сгенерированная страница #обработка события закрытия соккета клиента############################ def on_close(self): self.fl = False #удаляем клиента из списка self.clients.remove(self) print("WebSocket closed") #создаем приложение tornado с обработчиком вебсоккетов и http сервером app = tornado.web.Application([(r"/ws", EchoWebSocket),(r'/', MainHandler)]) #прослушиваем на порту app.listen(10556) print("Start Server") #запускаем цикл прослушивания и обработки событий tornado.ioloop.IOLoop.instance().start()
@csrf_exempt
def http_notification(request):
response = HttpResponse(status=404)
if request.method == 'POST':
line_notification_options = '%s&%s&%s&%s&%s&%s&%s&%s&%s' % (
request.POST['notification_type'], request.POST['operation_id'], request.POST['amount'],
request.POST['currency'], request.POST['datetime'], request.POST['sender'], request.POST['codepro'],
settings.YANDEX_MONEY_SECRET_WORD, request.POST['label'])
if request.POST['sha1_hash'] == hashlib.sha1(line_notification_options.encode()).hexdigest():
YadTransaction.objects.create(
notification_type=request.POST['notification_type'],
currency=int(request.POST['currency']),
operation_id=request.POST['operation_id'],
amount=request.POST['amount'],
withdraw_amount=request.POST['withdraw_amount'] if 'withdraw_amount' in request.POST else 0,
datetime_transfer=dateutil.parser.parse(request.POST['datetime']),
sender=request.POST['sender'],
codepro=False if request.POST['codepro'] == 'false' else True,
label=request.POST['label'],
test_notification=True if 'test_notification' in request.POST else False,
)
lab = request.POST['label']
aaa = request.POST.get('withdraw_amount')
moss = Money.objects.get(moneyname=lab)
moss.moneyvalue += aaa
moss.save()
response = HttpResponse(status=200)
Models.py
....
withdraw_amount = models.DecimalField('Сумма, которая списана со счета отправителя', max_digits=12, decimal_places=2, null=True, blank=True)
.......
class Money(models.Model):
moneyname = models.CharField(max_length=120)
moneyvalue = models.DecimalField(decimal_places=2 ,max_digits=20)
class Account(Base): __tablename__ = 'account' id = Column(Integer, primary_key=True) taxes = relationship('Tax', primaryjoin='and_(Account.id == Tax.account_id,' 'Tax.removed == False)', collection_class=attribute_mapped_collection('id'), cascade='all') def create_tax(self, id_, name): c = Tax(id=id_, name=name) self.taxes[c.id] = c def remove_tax(self, id_): contribution = self.taxes[id_] contribution.removed = True class Tax(Base): __tablename__ = 'tax' id = Column(Integer, primary_key=True) name = Column(String(50), nullable=False) account_id = Column(Integer, ForeignKey(Account.id), nullable=False) removed = Column(Boolean, nullable=False, default=False) Base.metadata.drop_all(engine) Base.metadata.create_all(engine) if __name__ == '__main__': account = Account(id=1) account.create_tax(id_=1, name='General tax') account.create_tax(id_=2, name='Selective tax') assert len(account.taxes) == 2 account.remove_tax(id_=1) assert len(account.taxes) == 1
import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as p3 import matplotlib.animation as animation from scipy.integrate import odeint from scipy.optimize import curve_fit def show(fun, arg): print(type(fun), ':', fun) print('arg =',arg,'=> fun(arg) =', fun(arg)) def f() t = np.linspace( 0, 20, 50) # vector of time y0 = [100, 300] # start value w = odeint(f, y0, t) # solve eq. y1 = w[:,0] y2 = w[:,1] fig = plt.figure(facecolor='white') #plt.plot(t, y1, '-o', t, y2, '-o', linewidth=2) plt.plot(y1, y2, '-o', linewidth=2) plt.ylabel("z") plt.xlabel("t") plt.grid(True) plt.show() # display # T=2pi/sqrt(ab) U=b/gamma2 V=a/gamma1 # U= 1/T int (ot 0 do T) U(t)dt # V= 1/T int (ot 0 do T) V(t)dt # U0=199 V0=200 U=50/500 U_fig = range(50,500,25) V_fig = range(50,500,25) for u_t in U_fig: for v_t in V_fig: F=[u_t, v_t] #X = open('test.txt', 'r') b = np.array
import numpy as np import math import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as p3 import matplotlib.animation as animation from scipy.integrate import odeint def show(fun, arg): print(type(fun), ':', fun) print('arg =',arg,'=> fun(arg) =', fun(arg)) x = np.linspace(-5, 2, 100) def P(x,y): return 1/(1+math.pow(math.e, y)) t = np.linspace( 0, 20, 100) # vector of time x0 = [10, 300] # start value w = odeint(P, x0, t) # solve eq. x1 = w[:,0] x2 = w[:,1] fig = plt.figure(facecolor='white') #plt.plot(t, y1, '-o', t, y2, '-o', linewidth=2) plt.plot(x1, x2, '-o', linewidth=2) plt.ylabel("z") plt.xlabel("t") plt.grid(True) plt.show() # display # T=2pi/sqrt(ab) U=b/gamma2 V=a/gamma1 # U= 1/T int (ot 0 do T) U(t)dt # V= 1/T int (ot 0 do T) V(t)dt # U0=199 V0=200 U=50/500 U_fig = range(50,500,25) V_fig = range(50,500,25) for u_t in U_fig: for v_t in V_fig: F=[u_t, v_t]
from kits_config import Kit from kits_config import Kits import unittest as _t class TestKit(_t.TestCase): def setUp(self) -> None: Kit.kit_ids = list() Kit.kit_names = list() self.kit = Kit('TestKit', 'testdata/TestKitSamples', -5) self.kit._nka_path = 'testdata/' def tearDown(self) -> None: del self.kit def test_errors(self) -> None: """test for proper raising errors""" self.kit._samples_path = 'testdata/TestKitWrongSamples' with self.subTest(): with self.assertRaises(Kit.Error) as e: self.kit.zones self.assertEqual(str(e.exception), 'length of zones and names lists is not equal.' ' Probably, zones have to be updated for ' f'{self.kit.name}') def test_lists(self) -> None: """test contents of arrays""" print(__file__) print(__name__) with self.subTest(): self.assertEqual(len(self.kit.zones), len(self.kit.names)) self.assertEqual(self.kit.zones, [1, 2, 3]) self.assertEqual(self.kit.names, ['TestKit_sample_1', 'TestKit_sample_2', 'TestKit_sample_3']) class TestKits(_t.TestCase): def runTest(self) -> None: self.kits = Kits() Kit1 = Kit('Kit1', '.', -1) Kit2 = Kit('Kit2', '.', -2) self.kits.append(Kit1) self.kits.append(Kit2) with self.assertRaises(NameError): Kit('Kit2', '.', -3) with self.assertRaises(IndexError): Kit('Kit3', '.', -2) self.assertEqual(self.kits.Kit1, Kit1) self.assertEqual(self.kits[0], Kit1) self.assertEqual(self.kits.Kit2, Kit2) self.assertEqual(self.kits[1], Kit2) if __name__ == '__main__': _t.main()
EE. ====================================================================== ERROR: test for proper raising errors ---------------------------------------------------------------------- Traceback (most recent call last): File "F:\Leo Percussion\source\test_kits_config.py", line 23, in test_errors self.kit.zones File "F:\Leo Percussion\source\kits_config.py", line 62, in zones self._check_actuality() File "F:\Leo Percussion\source\kits_config.py", line 51, in _check_actuality self.update_sample_zones() File "F:\Leo Percussion\source\kits_config.py", line 38, in update_sample_zones with open(self._nka_path + self.name + '.nka') as f: FileNotFoundError: [Errno 2] No such file or directory: 'testdata/TestKit.nka' ====================================================================== ERROR: test contents of arrays ---------------------------------------------------------------------- Traceback (most recent call last): File "F:\Leo Percussion\source\test_kits_config.py", line 33, in test_lists self.assertEqual(len(self.kit.zones), len(self.kit.names)) File "F:\Leo Percussion\source\kits_config.py", line 62, in zones self._check_actuality() File "F:\Leo Percussion\source\kits_config.py", line 51, in _check_actuality self.update_sample_zones() File "F:\Leo Percussion\source\kits_config.py", line 38, in update_sample_zones with open(self._nka_path + self.name + '.nka') as f: FileNotFoundError: [Errno 2] No such file or directory: 'testdata/TestKit.nka' -------------------- >> begin captured stdout << --------------------- F:\Leo Percussion\source\test_kits_config.py --------------------- >> end captured stdout << ---------------------- ---------------------------------------------------------------------- Ran 3 tests in 0.054s FAILED (errors=2) [Finished in 0.4s with exit code 1] [shell_cmd: nosetests ./source] [dir: F:\Leo Percussion]
import mainmdi class MyWin(QtWidgets.QMainWindow): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.ui = mainmdi.Ui_MainWindow() self.ui.setupUi(self) # self.setWindowFlag(Qt.MSWindowsFixedSizeDialogHint) date_time = QDateTime.currentDateTime() self.ui.Period.setDate(date_time.date())
def NewUvedoml_ur_clicked(parent): ur_w = NewUvedomlenie() # w.ui.get_data_btn.setHidden(False) sWindow = QtWidgets.QMdiSubWindow(parent.mdiArea) sWindow.setWidget(ur_w) parent.mdiArea.addSubWindow(sWindow) sWindow.setAttribute(Qt.WA_DeleteOnClose) sWindow.setWindowFlag(Qt.MSWindowsFixedSizeDialogHint) sWindow.setWindowTitle("Новое уведомление по юридическим лицам и приравненным") sWindow.adjustSize() ur_w.ui.comboTypePotr.setCurrentIndex(0) sWindow.show() def add_menus_to_main(parent): # parent = self.ui # создаем подменю модуля parent.new_sub_menu = QtWidgets.QMenu("&Новые уведомления") parent.uvedoml_menu.insertMenu(parent.uvedoml_menu.actions()[0], parent.new_sub_menu) # добавляем новую кнопку (юр) в меню и выставляем на исполнение parent.ur_new_uvedoml_action = QtWidgets.QAction("Новое уведомление &Юр") parent.ur_new_uvedoml_action.setShortcut("Ctrl+U") #clicked_ur = NewUvedoml_ur_clicked(parent) #parent.ur_new_uvedoml_action.triggered.connect(clicked_ur) parent.new_sub_menu.insertAction(parent.uvedoml_menu.actions()[0], parent.ur_new_uvedoml_action) class NewUvedomlenie(QtWidgets.QDialog): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.setWindowFlag(Qt.MSWindowsFixedSizeDialogHint) self.ui = new_uvedoml.Ui_Dialog()
import subfolder.new_uvedoml_form as new_uvedoml_form
new_uvedoml_form.add_menus_to_main(self.ui)
clicked_ur
parent.ur_new_uvedoml_action.triggered.connect(clicked_ur)