localStorage.setItem("notepadText", 'Lorem ipsum...');
document.getElementById("notepad").innerHTML = localStorage.notepadText;
from django.forms import ModelForm
from django.forms.models import inlineformset_factory
from models import Receipt, Ingredient
ReceiptFormSet = inlineformset_factory(Receipt, Ingredient, fields=('name', 'count', 'value'))
from forms import ReceiptFormSet
def receipt_new(request):
if request.method == "POST":
formset = ReceiptFormSet(request.POST)
if formset.is_valid():
formset.save()
return redirect('/receipts')
else:
formset = ReceiptFormSet()
return render(request, 'admin_site/receipt_edit.html', {'formset': formset})
<form method="post" action="">
<table>
{{ formset }}
</table>
</form>
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>526</width>
<height>373</height>
</rect>
</property>
<property name="windowTitle">
<string>Threading Demo</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="label_log_list">
<property name="text">
<string>Отчёт:</string>
</property>
</widget>
</item>
<item>
<widget class="QListWidget" name="list_log"/>
</item>
<item>
<widget class="QProgressBar" name="progress_bar">
<property name="value">
<number>0</number>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="buttons_layout">
<item>
<widget class="QPushButton" name="btn_stop">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>Стоп</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btn_start">
<property name="text">
<string>Старт</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>
from PyQt4 import QtGui, uic
from PyQt4.QtCore import QThread, SIGNAL
import sys
import time
class xmlParserThread(QThread):
def __init__(self, xml):
QThread.__init__(self)
self.xml = xml
def __del__(self):
self.wait()
def run(self):
for x in range(25):
self.emit(SIGNAL('notify_progress(QString)'), str(x))
self.sleep(1)
class ThreadingDemo(QtGui.QMainWindow):
def __init__(self):
super(self.__class__, self).__init__()
uic.loadUi('design.ui', self)
self.btn_start.clicked.connect(self.start_getting_top_posts)
def start_getting_top_posts(self):
self.progress_bar.setMaximum(25)
self.progress_bar.setValue(0)
self.xml_parser_thread = xmlParserThread('some.xml')
self.connect(self.xml_parser_thread, SIGNAL("notify_progress(QString)"), self.notify_progress)
self.connect(self.xml_parser_thread, SIGNAL("finished()"), self.done)
self.xml_parser_thread.start()
self.btn_stop.setEnabled(True)
self.btn_stop.clicked.connect(self.xml_parser_thread.terminate)
self.btn_start.setEnabled(False)
def notify_progress(self, counter):
self.list_log.addItem(counter)
self.progress_bar.setValue(self.progress_bar.value() + 1)
def done(self):
self.btn_stop.setEnabled(False)
self.btn_start.setEnabled(True)
self.progress_bar.setValue(0)
QtGui.QMessageBox.information(self, "Done!", "Done parsing XML!")
def main():
app = QtGui.QApplication(sys.argv)
form = ThreadingDemo()
form.show()
app.exec_()
if __name__ == '__main__':
main()
@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
list_display = ('__str__', 'customer_link')
def customer_link(self, obj):
if obj.customer:
return u'<a href="{0}">{1}</a>'.format(reverse('admin:auth_user_change', args=(obj.customer.pk,)), obj.customer)
else:
return obj.customer_fio
customer_link.allow_tags = True
customer_link.admin_order_field = 'customer'
customer_link.short_description = Order._meta.get_field('customer').verbose_name.title()
@python_2_unicode_compatible
class Order(models.Model):
customer = models.ForeignKey(User, verbose_name=u'Заказчик', null=True, blank=True, related_name='orders')
customer_fio = models.CharField(u'ФИО заказчика', max_length=150)
from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver
@receiver(pre_delete, sender=AdvertPhoto)
def advert_photo_delete(sender, instance, **kwargs):
instance.file.delete(False)
import os
for instance in AdvertPhoto.objects.all():
os.remove(instance.photo.path)
import string
from collections import Counter
punctuation_map = dict((ord(char), None) for char in string.punctuation)
prepositions = ['в', 'без', 'до', 'из', 'к', 'на', 'по', 'о', 'от', 'перед', 'при', 'через', 'с', 'у', 'за', 'над', 'об', 'под', 'про', 'для']
text = open('WarAndPeace_rus.txt').read()
clean_data = text.translate(punctuation_map) #Убираем знаки пунктуации
words = Counter([word.strip().lower() for word in clean_data.split() if word not in prepositions]) #Приводим все слова к нижнему регистру и убираем предлоги
with open('words.txt', 'w') as fh:
fh.write('\n'.join([w[0] for w in words.most_common(1000)]))
d = {'первый элемент':[1,2,3,4,5,6,7,8,9,10], 'второй элемент':[1,2,3,4,5,6,7,8,9,10], ...}
with open(file_name, 'w') as fh:
fh.write(repr(d))
import json
with open(file_name, 'w') as fh:
fh.write(json.dumps(d, ensure_ascii=False).encode('utf-8'))
function currentYPosition() {
// Firefox, Chrome, Opera, Safari
if(self.pageYOffset) return self.pageYOffset;
// Internet Explorer 6 - standards mode
if(document.documentElement && document.documentElement.scrollTop)
return document.documentElement.scrollTop;
// Internet Explorer 6, 7 and 8
if(document.body.scrollTop) return document.body.scrollTop;
return 0;
}
function elmYPosition(eID) {
var elm = document.getElementById(eID);
var y = elm.offsetTop;
var node = elm;
while(node.offsetParent && node.offsetParent != document.body) {
node = node.offsetParent;
y += node.offsetTop;
}
return y;
}
function smoothScroll(eID) {
var startY = currentYPosition();
var stopY = elmYPosition(eID);
var distance = stopY > startY ? stopY - startY : startY - stopY;
if(distance < 100) {
scrollTo(0, stopY);
return;
}
var speed = Math.round(distance / 100);
if(speed >= 20) speed = 20;
var step = Math.round(distance / 25);
var leapY = stopY > startY ? startY + step : startY - step;
var timer = 0;
if(stopY > startY) {
for(var i=startY; i<stopY; i+=step) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY += step; if (leapY > stopY) leapY = stopY;
timer++;
}
return;
}
for(var i=startY; i>stopY; i-=step) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY -= step;
if(leapY < stopY) leapY = stopY;
timer++;
}
}
<nav id="n"></nav>
<table id="t">
<tr>
<th>Буква</th>
</tr>
</table>
a {
margin-right: 5px;
}
var table = document.getElementById('t'); //Таблица с буквами
var nav = document.getElementById('n'); //Контейнер, содержащий ссылки на строки таблицы
var chars = 'abcdefghigklmnopqrstuvwxyz';
for(var i = 0; i < chars.length; i++) {
var a = document.createElement('a');
a.setAttribute('href', '#' + chars[i]);
a.innerHTML = chars[i];
nav.appendChild(a);
for(var x = 0; x < 25; x++) { //Для наглядности увеличим количество строк в таблице в 25 раз
var tr = document.createElement('tr');
var td = document.createElement('td');
var text = document.createTextNode(chars[i] + x);
if(x == 0) { //На каждую первую строку с буквой назначим якорь
var a = document.createElement('a');
a.setAttribute('name', chars[i]);
a.setAttribute('id', chars[i]);
a.appendChild(text);
td.appendChild(a);
}
else {
td.appendChild(text);
}
tr.appendChild(td);
table.appendChild(tr);
}
}
for(var i = 0; i < nav.childNodes.length; i++) {
nav.childNodes[i].addEventListener('click', function(event) {
event.preventDefault();
var href = this.getAttribute('href');
var id = href[1];
smoothScroll(id);
});
}