Форум сайта python.su
# -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui import sys class MyThread(QtCore.QThread): def __init__(self, parent, n): QtCore.QThread.__init__(self) self.parent_ = parent self.n = n #self.connect(self, QtCore.SIGNAL("finished()"), self, QtCore.SLOT("deleteLater()")) - а иначе с криками """QThread::wait: Thread tried to wait on itself QThread: Destroyed while thread is still running""" падает def run(self): print self.n self.emit(QtCore.SIGNAL("signalMyThread(PyQt_PyObject)"), {'result': 'ok', 'n': self.n}) class Application(QtGui.QApplication): def __init__(self, argv): QtGui.QApplication.__init__(self, argv) self.prepare() def prepare(self): self.threads_ = {} self.working_threads = 0 self.n = -1 for x in xrange(50): QtCore.QTimer().singleShot(100, self.start) def start(self): self.n += 1 if self.n > 1000000000: QtCore.QTimer().singleShot(100, self.finish) return n = self.n QtCore.QTimer().singleShot(100, lambda: self.start2(n)) def start2(self, n): self.threads_[n] = MyThread(self, n) self.threads_[n].moveToThread(self.threads_[n]) self.connect(self.threads_[n], QtCore.SIGNAL("signalMyThread(PyQt_PyObject)"), self.receive) self.working_threads += 1 self.threads_[n].start() def receive(self, result): n = result.get('n') QtCore.QTimer().singleShot(100, lambda: self.killThread(n)) QtCore.QTimer().singleShot(100, self.start) def killThread(self, n): if n not in self.threads_: return if self.threads_[n].isRunning(): QtCore.QTimer().singleShot(100, lambda: self.killThread(n)) return self.threads_[n].deleteLater() self.threads_.pop(n, None) self.working_threads -= 1 def finish(self): if self.working_threads > 0: QtCore.QTimer().singleShot(100, self.finish) return self.quit() if __name__=='__main__': app = Application(sys.argv) sys.exit(app.exec_())
import random, re with open("infile.txt",'r') as f: lines = f.read() component_1 = re.findall('([^\s].*?Components="Cd".*?)', lines) # что ищем component_2 = re.findall('([^\s].*?Components="Pb".*?)', lines) def count(com1, com2): result = [] if com1 != 0: l_1 = len(com1) a = input('Cd ') else: l_1 = 0 if com2 != 0: l_2 = len(com2) b = input('Pb ') else: l_2 = 0 if round(l_1//100) < 1: nominal_1_proc = round(l_1//100)+1 else: nominal_1_proc = round(l_1//100) if round(l_2//100) < 1: nominal_2_proc = round(l_2//100)+1 else: nominal_2_proc = round(l_2//100) if com1 != 0: for x in range(0, int(a*nominal_1_proc)): result.append(com1[x]) if com2 != 0: for y in range(0, int(b*nominal_2_proc)): result.append(com2[y]) random.shuffle(result) return result fo = open("demooutfile.txt", "w") for y in count(component_1, component_2): fo.write(y) fo.write('\n') fo.close() regex3= re.compile('Components="Pb"|Components="Cd"') # что ищем with open("infile.txt",'r') as f3: lines3 = f3.read() endpos3=0 match3= regex3.search(lines3,endpos3) matches3=[] # массив с совпадениями strings3=[] # все остальное что не совпало, при этом если два совпадения подряд, или начало (конец) строки и совпадение, то в этот массив попадает пустая строка # поэтому значения в массивах чередуются относительно целевой строки while (match3): strings3+= [ lines3[endpos3:match3.start()] ] endpos3= match3.end() matches3+=[match3.group(0)] match3= regex3.search(lines3,endpos3) if (endpos3==len(lines3)): strings3+= [ "" ] random.shuffle(matches3) regex2= re.compile('Components="Pb"|Components="Cd"') # что ищем with open("demooutfile.txt",'r') as f2: lines2 = f2.read() endpos2=0 match2= regex2.search(lines2,endpos2) matches2=[] # массив с совпадениями strings2=[] # все остальное что не совпало, при этом если два совпадения подряд, или начало (конец) строки и совпадение, то в этот массив попадает пустая строка # поэтому значения в массивах чередуются относительно целевой строки while (match2): strings2+= [ lines2[endpos2:match2.start()] ] endpos2= match2.end() matches2+=[match2.group(0)] match2= regex2.search(lines2,endpos2) if (endpos2==len(lines2)): strings2+= [ "" ] random.shuffle(matches2) result3= "" # собираем строку обратно с перемешанными данными for i in range(len(matches2)): result3+=strings3[i]+matches2[i] # вместо исходного массива вставляем искомый result3+=strings3[-1] with open("outfilenew.txt", "w") as f4: f4.write(result3)
import random, re with open("infile.txt",'r') as f: lines = f.read() component_1 = re.findall('([^\s].*?Components="Cd".*?)', lines) # что ищем component_2 = re.findall('([^\s].*?Components="Pb".*?)', lines) def count(com1, com2): result = [] if com1 != 0: l_1 = len(com1) a = input('Cd ') else: l_1 = 0 if com2 != 0: l_2 = len(com2) b = input('Pb ') else: l_2 = 0 if round(l_1//100) < 1: nominal_1_proc = round(l_1//100)+1 else: nominal_1_proc = round(l_1//100) if round(l_2//100) < 1: nominal_2_proc = round(l_2//100)+1 else: nominal_2_proc = round(l_2//100) if com1 != 0: for x in range(0, int(a*nominal_1_proc)): result.append(com1[x]) if com2 != 0: for y in range(0, int(b*nominal_2_proc)): result.append(com2[y]) random.shuffle(result) return result fo = open("demooutfile.txt", "w") for y in count(component_1, component_2): fo.write(y) fo.write('\n') fo.close() regex3= re.compile('Components="Pb"|Components="Cd"') # что ищем with open("infile.txt",'r') as f3: lines3 = f3.read() endpos3=0 match3= regex3.search(lines3,endpos3) matches3=[] # массив с совпадениями strings3=[] # все остальное что не совпало, при этом если два совпадения подряд, или начало (конец) строки и совпадение, то в этот массив попадает пустая строка # поэтому значения в массивах чередуются относительно целевой строки while (match3): strings3+= [ lines3[endpos3:match3.start()] ] endpos3= match3.end() matches3+=[match3.group(0)] match3= regex3.search(lines3,endpos3) if (endpos3==len(lines3)): strings3+= [ "" ] random.shuffle(matches3) regex2= re.compile('Components="Pb"|Components="Cd"') # что ищем with open("demooutfile.txt",'r') as f2: lines2 = f2.read() endpos2=0 match2= regex2.search(lines2,endpos2) matches2=[] # массив с совпадениями strings2=[] # все остальное что не совпало, при этом если два совпадения подряд, или начало (конец) строки и совпадение, то в этот массив попадает пустая строка # поэтому значения в массивах чередуются относительно целевой строки while (match2): strings2+= [ lines2[endpos2:match2.start()] ] endpos2= match2.end() matches2+=[match2.group(0)] match2= regex2.search(lines2,endpos2) if (endpos2==len(lines2)): strings2+= [ "" ] random.shuffle(matches2) result3= "" # собираем строку обратно с перемешанными данными for i in range(len(matches2)): result3+=strings3[i]+matches2[i] # вместо исходного массива вставляем искомый result3+=strings3[-1] with open("outfilenew.txt", "w") as f4: f4.write(result3)
class Executor(list): Dependence = namedtuple('Dependence', ['executable', 'path']) def run(self): "Исполнение последовательности команд" self.check_depends() # тут запуск последовательности команд @classmethod def depend_on(cls, executable, path=None): "Добавляет зависимость в список в атрибуте функции __depend_on__" def wrapper(f): dependence = cls.Dependence(executable, path) if hasattr(f, '__depend_on__'): f.__depend_on__.append(dependence) else: f.__depend_on__ = [dependence] return f return wrapper def check_depends(self): "Проверка наличия зависимостей для последовательности команд" def check(dependence): "Проверка зависимости" for x in chain(*(getattr(x.func, '__depend_on__', ()) for x in self)): check(x)
@Executor.depend_on('hg.exe') def load_sources(revision): pass def build_executive(): pass @Executor.depend_on('hhc.exe') def build_help(): pass @Executor.depend_on('candle.exe', WIX_PATH) @Executor.depend_on('light.exe', WIX_PATH) def build_installer(): pass
executor = Executor() executor.append(build_executive) executor.append(build_help) executor.run()
executor.append(partial(load_sources, options.revision))
def MyFormDynamic(request): form = MyForm(request) form.predpr_id.choices = [(g.id, g.name) for g in Predpr.query.order_by('name')] form.devices_id.choices = [(g.id, g.number) for g in Devices.query.order_by('id')] return form class MyForm(form.Form): predpr_id = fields.SelectField(u'Предприятия', choices=[], coerce=int) devices_id = fields.SelectField(u'Устройства', choices=[], coerce=int) display = fields.RadioField(u'Куда выложить:', choices=[ (True, u'На сервер'), (False, u'Локально'), ], default=True, )
from sqlalchemy import Column, Integer, String, ForeignKey from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Association(Base): __tablename__ = 'exmp_association' parent_id = Column(Integer, ForeignKey('exmp_parent.id', ondelete='CASCADE'), primary_key=True) child_id = Column(Integer, ForeignKey('exmp_child.id', ondelete='CASCADE'), primary_key= extra_data = Column(String(50)) class Parent(Base): __tablename__ = 'exmp_parent' id = Column(Integer, primary_key=True) associations = relationship("Association", backref="parent") class Child(Base): __tablename__ = 'exmp_child' id = Column(Integer, primary_key=True) associations = relationship("Association", backref="child")
s = get_session() p = Parent() a = Association() c = Child() a.child = c p.associations.append(a) s.add(p) s.commit() a = s.query(Association).get([1, 1]) print(s.query(Parent).count()) print(s.query(Association).count()) print(a.parent) print(a.child) s.query(Parent).delete() s.commit() print(s.query(Parent).count()) print(s.query(Association).count())
class Association(Base): __tablename__ = 'exmp_association' parent_id = Column(Integer, ForeignKey('exmp_parent.id'), primary_key=True) child_id = Column(Integer, ForeignKey('exmp_child.id'), primary_key=True) extra_data = Column(String(50)) class Parent(Base): __tablename__ = 'exmp_parent' id = Column(Integer, primary_key=True) associations = relationship("Association", backref="parent", cascade='all, delete-orphan') class Child(Base): __tablename__ = 'exmp_child' id = Column(Integer, primary_key=True) associations = relationship("Association", backref="child", cascade='all, delete-orphan')
sqlalchemy.exc.IntegrityError: (IntegrityError) update or delete on table "exmp_parent" violates foreign key constraint "exmp_association_parent_id_fkey" on table "exmp_association" DETAIL: Key (id)=(1) is still referenced from table "exmp_association". 'DELETE FROM exmp_parent' {}
from multiprocessing import Process