<script type="text/javascript">
if (history.pushState) {
var baseUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
var newUrl = baseUrl + `?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page={{ page }}&size={{ size }}&order={{ order }}&direction={{ direction }}`;
history.replaceState(null, null, newUrl);
}
</script>
<script type="text/javascript">
function catSelect(event) {
var cat_id = $(event.currentTarget).attr('cat_id');
if (event.ctrlKey) {
window.location.href = "/publication/?cat={{ cat_id_join }}," + cat_id + "{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page=1&size={{ size }}&order={{ order }}&direction={{ direction }}"
return;
}
if (event.altKey) {
window.location.href = "/publication/?cat={{ cat_id_join }}," + cat_id + "(del){% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page=1&size={{ size }}&order={{ order }}&direction={{ direction }}"
return;
}
window.location.href = "/publication/?cat=" + cat_id + "&page=1&size={{ size }}&order={{ order }}&direction={{ direction }}"
}
</script>
<script type="text/javascript">
window.need_page={{ page|add:"1" }};
window.addEventListener('scroll', function() {
let windowRelativeBottom = document.documentElement.getBoundingClientRect().bottom;
if (windowRelativeBottom < document.documentElement.clientHeight + 100) {
if (window.need_load_more == 1) {
window.need_load_more = 0;
var myDivPaginator = document.getElementById("paginatorTop");
var myDivContent = document.getElementById("publication_content_block");
$.ajax({
url: "/ajaxMorePub/?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page=" + window.need_page + "&size={{ size }}&order={{ order }}&direction={{ direction }}",
success: function(response){
var parser = new DOMParser();
var ajax_html = parser.parseFromString(response, "text/html");
var container = ajax_html.getElementsByClassName("container")[0];
if (container.id != "empty") {
myDivContent.insertAdjacentHTML('beforeEnd', ajax_html.getElementById("pubcontent").outerHTML);
myDivPaginator.innerHTML = ajax_html.getElementById("paginatorTop").outerHTML;
if (history.pushState) {
var baseUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
var newUrl = baseUrl + `?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page=` + window.need_page + `&size={{ size }}&order={{ order }}&direction={{ direction }}`;
history.pushState(null, null, newUrl);
}
window.need_page = window.need_page + 1;
window.need_load_more = 1;
}
else { var text_on_spinner = document.getElementById("text_on_spinner");
text_on_spinner.innerHTML = "Это все публикации, загляните позже или измените фильтр!!!";
var spinner = document.getElementById("spinner_class");
spinner.className="alert alert-danger";
return;
}
}
});
};
};
}); </script>
from django.core.paginator import Paginator
====================================
# получаем список pub_id по параметрам
pubidlist=get_pub_id_by_params(cat_id=set(cat_id), tag=set(tag),
order=order, direction=direction)
# осуществляем пагинацию
paginator = Paginator(pubidlist, size)
if page>paginator.num_pages:
if template=="ajaxMorePub.html":
return render(request, "emptypublist.html")
page=paginator.num_pages
pubidlist = paginator.get_page(page)
# запрашиваем модель данных
pubmodel=get_pub_model(pubidlist,
order=order, direction=direction)
====================================
response = render(request, template, {
'pub_sorted': pubmodel.items(),
'order': order, 'size': size, 'direction': direction,
'page_range': paginator.page_range,
'num_pages': paginator.num_pages,
'paginator': paginator.page(page),
'page': page
})
{% if pub_sorted|length != 0 %}
<nav aria-label="pagination">
<ul class="pagination justify-content-center">
<!-- Первая страница -->
<li class="page-item {% if page == 1 %}disabled{% endif %}"> <a class="page-link" href="/mytestblog/publication/?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page=1&size={{ size }}&order={{ order }}&direction={{ direction }}">Первая</a> </li>
<!-- Если существует предыдущая страница --> {% if paginator.has_previous %}
<li class="page-item"> <a class="page-link" href="/mytestblog/publication/?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page={{ paginator.previous_page_number }}&size={{ size }}&order={{ order }}&direction={{ direction }}">«</a> </li>
{% else %} <li class="page-item disabled"> <a class="page-link" href="#">«</a> </li>
{% endif %} <!-- Если нет страницы +1, но есть страница -6 --> {% if page|add:"1" not in page_range and page|add:"-6" in page_range %}
<li class="page-item"> <a class="page-link" href="/mytestblog/publication/?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page={{ page|add:"-6" }}&size={{ size }}&order={{ order }}&direction={{ direction }}">{{ page|add:"-6" }}</a> </li>
{% endif %} <!-- Если нет страницы +2, но есть страница -5 --> {% if page|add:"2" not in page_range and page|add:"-5" in page_range %}
<li class="page-item"> <a class="page-link" href="/mytestblog/publication/?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page={{ page|add:"-5" }}&size={{ size }}&order={{ order }}&direction={{ direction }}">{{ page|add:"-5" }}</a> </li>
{% endif %} <!-- Если нет страницы +3, но есть страница -4 --> {% if page|add:"3" not in page_range and page|add:"-4" in page_range %}
<li class="page-item"> <a class="page-link" href="/mytestblog/publication/?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page={{ page|add:"-4" }}&size={{ size }}&order={{ order }}&direction={{ direction }}">{{ page|add:"-4" }}</a> </li>
{% endif %} <!-- Если существует страница текущая - 3 --> {% if page|add:"-3" in page_range %}
<li class="page-item"> <a class="page-link" href="/mytestblog/publication/?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page={{ page|add:"-3" }}&size={{ size }}&order={{ order }}&direction={{ direction }}">{{ page|add:"-3" }}</a> </li>
{% endif %} <!-- Если существует страница текущая - 2 --> {% if page|add:"-2" in page_range %}
<li class="page-item"> <a class="page-link" href="/mytestblog/publication/?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page={{ page|add:"-2" }}&size={{ size }}&order={{ order }}&direction={{ direction }}">{{ page|add:"-2" }}</a> </li>
{% endif %} <!-- Если существует страница текущая - 1 --> {% if page|add:"-1" in page_range %}
<li class="page-item"> <a class="page-link" href="/mytestblog/publication/?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page={{ page|add:"-1" }}&size={{ size }}&order={{ order }}&direction={{ direction }}">{{ page|add:"-1" }}</a> </li>
{% endif %} <!-- Текущая активная страница -->
<li class="page-item active"> <a class="page-link" href="#">{{ page }}</a> </li>
<!-- Если существует страница текущая + 1 --> {% if page|add:"1" in page_range %}
<li class="page-item"> <a class="page-link" href="/mytestblog/publication/?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page={{ page|add:"1" }}&size={{ size }}&order={{ order }}&direction={{ direction }}">{{ page|add:"1" }}</a> </li>
{% endif %} <!-- Если существует страница текущая + 2 --> {% if page|add:"2" in page_range %}
<li class="page-item"> <a class="page-link" href="/mytestblog/publication/?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page={{ page|add:"2" }}&size={{ size }}&order={{ order }}&direction={{ direction }}">{{ page|add:"2" }}</a> </li>
{% endif %} <!-- Если существует страница текущая + 3 --> {% if page|add:"3" in page_range %}
<li class="page-item"> <a class="page-link" href="/mytestblog/publication/?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page={{ page|add:"3" }}&size={{ size }}&order={{ order }}&direction={{ direction }}">{{ page|add:"3" }}</a> </li>
{% endif %} <!-- Если нет страницы -3, но есть страница +4 --> {% if page|add:"-3" not in page_range and page|add:"4" in page_range %}
<li class="page-item"> <a class="page-link" href="/mytestblog/publication/?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page={{ page|add:"4" }}&size={{ size }}&order={{ order }}&direction={{ direction }}">{{ page|add:"4" }}</a> </li>
{% endif %} <!-- Если нет страницы -2, но есть страница +5 --> {% if page|add:"-2" not in page_range and page|add:"5" in page_range %}
<li class="page-item"> <a class="page-link" href="/mytestblog/publication/?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page={{ page|add:"5" }}&size={{ size }}&order={{ order }}&direction={{ direction }}">{{ page|add:"5" }}</a> </li>
{% endif %} <!-- Если нет страницы -1, но есть страница +6 --> {% if page|add:"-1" not in page_range and page|add:"6" in page_range %}
<li class="page-item"> <a class="page-link" href="/mytestblog/publication/?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page={{ page|add:"6" }}&size={{ size }}&order={{ order }}&direction={{ direction }}">{{ page|add:"6" }}</a> </li>
{% endif %} <!-- Если существует следующая страница --> {% if paginator.has_next %}
<li class="page-item"> <a class="page-link" href="/mytestblog/publication/?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page={{ paginator.next_page_number }}&size={{ size }}&order={{ order }}&direction={{ direction }}">»</a> </li>
{% else %}
<li class="page-item disabled"> <a class="page-link" href="#">»</a> </li>
{% endif %} <!-- Последняя страница -->
<li class="page-item {% if page == num_pages %}disabled{% endif %}"> <a class="page-link" href="/mytestblog/publication/?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page={{ num_pages }}&size={{ size }}&order={{ order }}&direction={{ direction }}">Последняя</a> </li>
</ul>
</nav>
{% endif %}
SELECT category.cat_id, category.name, category.description, COUNT(catinpub.pub_id) as "count", MAX(publication.date) as "lastdate",
COUNT(CASE WHEN publication.date BETWEEN '2021-03-27 00:00:00' AND '2021-04-01 23:59:59' THEN 1 ELSE NULL END) FROM category
LEFT JOIN catinpub ON catinpub.cat_id = category.cat_id
LEFT JOIN publication ON publication.pub_id = catinpub.pub_id
WHERE category.archive is NULL
GROUP BY category.cat_id
ORDER BY count DESC
{% block сontent %}
<nowrap id="contentBlock">
{% include "pubcontent.html" %}
</nowrap>
<div class="col-md-12">
<div class="alert alert-info">
<div class="clearfix">Загрузка публикаций ...
<div class="spinner-border float-right" role="status">
<span class="sr-only">Загрузка публикаций ...</span>
</div>
</div>
</div>
</div>
<script type="text/javascript">
window.need_load_more=1;
window.need_page=2;
window.addEventListener('scroll', function() {
let windowRelativeBottom = document.documentElement.getBoundingClientRect().bottom;
if (windowRelativeBottom < document.documentElement.clientHeight + 100) {
if (window.need_load_more == 1) {
window.need_load_more = 0;
var myDiv = document.getElementById("contentBlock");
$.ajax({
url: "/mytestblog/pubcontent?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page=" + window.need_page + "&size={{ size }}&order={{ order }}&direction={{ direction }}",
success: function(data){
myDiv.insertAdjacentHTML('beforeEnd', data);
window.need_page = window.need_page + 1;
window.need_load_more = 1;
}
});
}; }
});
</script>
{% endblock %}
child.stdout.read()
from subprocess import Popen
import subprocess as sp
with open("test.txt", "r") as file:
child=Popen(['python', 'child.py'], stdin=file, stdout=sp.PIPE)
s=' '
while s:
s=child.stdout.read()
print (s.rstrip().decode(errors='ignore'))
print(input(), '- all is good')
time.sleep(1)
print(input(), '- all is good')
time.sleep(1)
print(input(), '- all is good')
time.sleep(1)
hello1
hello2
hello3
hello1 - all is good
hello2 - all is good
hello3 - all is good
child.stdout.read()
. sys.stdout.flush()
, а в родительском заменить child.stdout.read()
на child.stdout.readline()
from subprocess import Popen
import subprocess as sp
with open("test.txt", "r") as file:
child=Popen(['python', 'child.py'], stdin=file, stdout=sp.PIPE)
s=' '
while s:
s=child.stdout.readline()
print (s.rstrip().decode(errors='ignore'))
print(input(), '- all is good')
time.sleep(1); sys.stdout.flush()
print(input(), '- all is good')
time.sleep(1); sys.stdout.flush()
print(input(), '- all is good')
time.sleep(1); sys.stdout.flush()
sys.stdout.flush()
может не быть. Поэтому вывод будет доступен только по завершению дочернего процесса. В таком случае замена инструкции child.stdout.read()
на child.stdout.readline()
в родительском процессе ничего не даст, цикл в коде позволит вам прочитать построчно весь вывод. Но по времени этот вывод, естественно, будет не синхронизирован с тем, когда эти строки генерировал дочерний процесс with open (r"C:\Users\user_name\Desktop\Telegram.lnk", "rb") as file:
source=file.read()
source = base64.b64encode(source)
source
source=b'TAAAAAEUAgAAAAAAwA...........AAAAAAAAAA'
source = base64.b64decode(source)
with open (r"C:\Users\user_name\Desktop\Telegram.lnk", "wb") as file:
file.write(source)
df["start_date"]=[k+" "+str(l) for k,l in list(zip(df.index.month_name(locale='ru_RU.UTF-8'),df.index.year))]
df=df.set_index("start_date")
import locale
locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8')
...
ticktext=[datetime.strptime(elem, "%Y-%m-%d").strftime('%d-%b-%Y %a')
for elem in df.index]
fig.update_xaxes(tickformat='%d-%b-%Y %a')
fig.update_xaxes(tickvals=df.index)
fig.update_xaxes(ticktext=ticktext)
if array.name[-5:]=='DATES':
width=20*60*60*1000
if array.name[-4:]=='WEEK':
width=6*24*60*60*1000
if array.name[-5:]=='MONTH':
width=0.9
....
fig.add_trace(go.Bar(x=array.index, y=data, marker_color='blue', name='',
width=[width]*len(array), showlegend=False))
pub_sorted=sorted(publist.items(),
key=lambda elem: datetime.strptime(elem[1]["date"], "%d.%m.%Y %H:%M:%S"),
reverse=True)
И судя по данным реально сортирует, но данные в итоге не в виде словаря, [(key, dict-value), (key, dict-value)
(key, dict-value)]
import pandas as pd
lst=[{'id': 2785280, 'score': 13},
{'id': 66560002, 'score': 4},
{'id': 180432899, 'score': 7},
{'id': 52793348, 'score': 5},
{'id': 86411270, 'score': 5},
{'id': 2334728, 'score': 2},
{'id': 2523146, 'score': 4},
{'id': 159318028, 'score': 5},
]
df=pd.DataFrame(lst)
df=df.groupby('id')['score'].sum()
SESSION_REPORT=[]
# ЧИТАЕМ ФАЙЛЫ SESSION REPORT В PYTHON-СЛОВАРЬ #
for SESSION_REPORT_FILE in os.listdir(SESSION_REPORT_PATH):
with open(SESSION_REPORT_PATH+SESSION_REPORT_FILE, "r", newline="",
encoding="utf-8") as file:
start_date=datetime.strptime(SESSION_REPORT_FILE[14:len(SESSION_REPORT_FILE)-4], '%Y-%m-%d')
reader = csv.reader(file, delimiter = ';')
for line in reader:
if line[2]=="Длина текста": continue
start_time=datetime.combine(start_date.date(),
datetime.strptime(line[1], '%H:%M:%S').time())
voice_length=datetime.combine(start_date.date(),
datetime.strptime(line[3], '%H:%M:%S').time())-start_date
SESSION_REPORT.append({"v2m_guid": line[0], "start_date": start_date,
"start_time": start_time,
"voice_length": voice_length,
"end_time": start_time+voice_length,
"text_length": int(line[2])})
# СОЗДАЕМ DATAFRAME PANDAS #
SESSION_REPORT=pd.DataFrame(SESSION_REPORT)
IndexError: too many indices for array
сбивает с толкуarr=np.array([tpl], dtype=dt)
arr=np.array(tpl, dtype=dt)
В первом случае элементы доступны через индекс arr[0]["v2m_guid"]
arr["v2m_guid"]