let vy = 5;
let scrollStarted = false;
let userInteracting = false;
function step() {
if (!userInteracting) { // Продолжаем прокрутку, только если пользователь не взаимодействует
window.scrollBy(0, vy);
window.requestAnimationFrame(step);
}
}
$(document).bind('DOMMouseScroll mousewheel', function(e) {
userInteracting = true; // Пользователь начал прокрутку
clearTimeout(window.scrollTimeout);
window.scrollTimeout = setTimeout(function() {
userInteracting = false; // Предполагаем, что пользователь закончил прокрутку после задержки
if (!scrollStarted) {
scrollStarted = true;
window.requestAnimationFrame(step);
}
}, 200); // Задержка в 200 мс, после которой считаем, что пользовательские действия прекратились
});
// Начальный запуск анимации
if (!scrollStarted) {
scrollStarted = true;
window.requestAnimationFrame(step);
}
const { Sequelize, DataTypes } = require('sequelize');
// Подключение к базе данных
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql',
});
// Определение модели UsersModel
const UsersModel = sequelize.define('User', {
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
// Другие поля пользователя
});
// Определение модели RolesModel
const RolesModel = sequelize.define('Role', {
title_role: {
type: DataTypes.STRING,
allowNull: false,
},
// Другие поля роли
});
// Определение отношения "один к одному"
UsersModel.hasOne(RolesModel);
RolesModel.belongsTo(UsersModel);
// Пример создания записи пользователя с ролью
sequelize.sync()
.then(async () => {
const user = await UsersModel.create({
email: 'example@example.com',
// Другие поля пользователя
});
const role = await RolesModel.create({
title_role: 'Admin',
// Другие поля роли
});
// Связываем пользователя с ролью
await user.setRole(role);
// Запрос на получение пользователя с ролью
const foundUser = await UsersModel.findOne({
where: { email: 'example@example.com' },
include: RolesModel, // указываем, что хотим включить связанную модель
});
if (!foundUser) {
console.error('Пользователь не найден');
} else {
console.log(foundUser.email + ' - ' + foundUser.Role.title_role);
}
})
.catch((error) => {
console.error('Ошибка при синхронизации с базой данных:', error);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scroll Animation</title>
<style>
body {
margin: 0;
padding: 0;
height: 200vh; /* чтобы создать прокрутку */
}
.road {
position: relative;
height: 100vh; /* высота видимой области */
overflow: hidden;
}
.container {
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
}
.car {
width: 50px;
height: 30px;
background-color: red;
position: absolute;
bottom: 0;
transition: transform 0.3s ease-in-out; /* плавный переход */
}
</style>
</head>
<body>
<section class="road">
<div class="container">
<div class="car"></div>
</div>
</section>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
$(document).ready(function () {
$(window).on('scroll', function () {
var scrollTop = $(this).scrollTop();
var windowHeight = $(this).height();
var car = $('.car');
var roadHeight = $('.road').outerHeight();
// Проверка, виден ли автомобиль в текущей области видимости
if (scrollTop <= roadHeight && (scrollTop + windowHeight) >= roadHeight) {
// Изменение размера и положения автомобиля
var scale = 1 + (scrollTop / roadHeight); // регулируйте это значение по вашему вкусу
var translateX = -scrollTop / 5; // регулируйте это значение по вашему вкусу
car.css({
'transform': 'translateX(' + translateX + 'px) scale(' + scale + ')'
});
}
});
});
</script>
</body>
</html>
import fetch from 'node-fetch'; // Подключите библиотеку fetch, если еще не подключили
import { HttpsProxyAgent } from 'https-proxy-agent';
export async function getLinkApi() {
try {
const proxyAgent = new HttpsProxyAgent('http://176.31.129.223:8080');
const response = await fetch('https://livefootball.su/wp-json/wp/v2/pages', {
agent: proxyAgent,
headers: {
// Если требуется, добавьте дополнительные заголовки
// 'Authorization': 'Bearer YourAccessToken',
// 'User-Agent': 'YourUserAgent',
},
});
const data = await response.json();
const link = ""; // Обработка данных
return link;
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
}
<p id="shortText">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum nec mi eget nisi rhoncus efficitur sit amet at quam. Cras non venenatis ipsum, in dictum libero. Aenean gravida tristique ultrices.
<a href="#" id="expandLink" onclick="expandText()">Развернуть</a>
</p>
<script>
function expandText() {
var shortText = document.getElementById('shortText');
var expandLink = document.getElementById('expandLink');
var fullText = shortText.textContent;
if (fullText.length > 200) {
var truncatedText = fullText.substring(0, 200);
var remainingText = fullText.substring(200);
// Создаем новый элемент <span> для скрытого текста
var extraTextElement = document.createElement('span');
extraTextElement.textContent = remainingText;
extraTextElement.style.display = 'none'; // Скрываем его изначально
// Добавляем скрытый текст после оригинального параграфа
shortText.appendChild(extraTextElement);
// Переключаем текст ссылки и показываем/скрываем дополнительный текст при клике
expandLink.textContent = 'Свернуть';
expandLink.onclick = function() {
extraTextElement.style.display = extraTextElement.style.display === 'none' ? 'inline' : 'none';
expandLink.textContent = extraTextElement.style.display === 'none' ? 'Развернуть' : 'Свернуть';
};
// Отображаем ссылку только если есть скрытый текст
if (remainingText.trim() !== '') {
expandLink.style.display = 'inline';
} else {
expandLink.style.display = 'none';
}
}
}
</script>
window.addEventListener("DOMContentLoaded", function() {
[].forEach.call(document.querySelectorAll('.tel'), function(input) {
var keyCode;
function mask(event) {
event.keyCode && (keyCode = event.keyCode);
var pos = this.selectionStart;
if (pos < 3) event.preventDefault();
var matrix = "+7 (____) ____-___",
i = 0,
def = matrix.replace(/\D/g, ""),
val = this.value.replace(/\D/g, ""),
new_value = matrix.replace(/[_\d]/g, function(a) {
return i < val.length ? val.charAt(i++) || def.charAt(i) : a;
});
i = new_value.indexOf("_");
if (i != -1) {
i < 5 && (i = 3);
new_value = new_value.slice(0, i);
}
var reg = matrix
.substr(0, this.value.length)
.replace(/_+/g, function(a) {
return "\\d{1," + a.length + "}";
})
.replace(/[+()]/g, "\\$&");
reg = new RegExp("^" + reg + "$");
if (!reg.test(this.value) || this.value.length < 5 || (keyCode > 47 && keyCode < 58))
this.value = new_value;
if (event.type == "blur" && this.value.length < 5) this.value = "";
}
input.addEventListener("input", mask, false);
input.addEventListener("focus", mask, false);
input.addEventListener("blur", mask, false);
input.addEventListener("keydown", mask, false);
});
});
const pizzaTimer = (ms) => {
const target = new Date().getTime() + ms + 100; // 100 это смещение для setInterval, так-как setInterval не всегда точно спустя 1 секунду обновляется
const interval = setInterval(() => {
const remainingTime = target - new Date().getTime(); // Вычисление оставшегося времени в миллисекундах
if (ms > 3_600_000) {
console.log(
new Intl.DateTimeFormat(navigator.language, {
hourCycle: 'h23',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
}).format(remainingTime)
);
} else {
console.log(
new Intl.DateTimeFormat(navigator.language, {
minute: 'numeric',
second: 'numeric',
}).format(remainingTime)
);
}
}, 1000);
setTimeout(() => {
console.log('pizza time');
clearInterval(interval);
}, ms);
};
console.log(pizzaTimer(3_610_000));
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action === "playSound" && request.sound) {
var audio = new Audio(chrome.runtime.getURL(request.sound));
audio.play();
}
});
function refreshPage() {
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
var tabId = tabs[0].id;
chrome.tabs.reload(tabId);
});
}
setInterval(refreshPage, 30 * 1000);
$data = array(
"update_id" => 1111111,
"message" => array(
"message_id" => 111,
"from" => array(
"id" => 1111111,
"is_bot" => false,
"first_name" => "2222222",
"last_name" => "3333333",
"username" => "4444444444",
"language_code" => "ru"
),
"chat" => array(
"id" => -5555555555,
"title" => "Test 666666",
"type" => "supergroup"
),
"date" => 77777777,
"message_thread_id" => 8888,
"reply_to_message" => array(
"message_id" => 9999,
"from" => array(
"id" => 0000000000000,
"is_bot" => true,
"first_name" => "---------test",
"username" => "9999999"
),
"chat" => array(
"id" => -00000000000000,
"title" => "Test --------",
"type" => "supergroup"
),
"date" => "=====99999",
"text" => "ghbdtn"
),
"text" => "Аоатт"
)
);
$text = $data["message"]["text"];
echo $text; // Выведет "Аоатт"
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Мой лендинг</title>
</head>
<body>
<h1>Мой лендинг</h1>
<iframe src="https://www.demoslot.com/milkshake-xxxtreme-slot.html" width="800" height="600" frameborder="0"></iframe>
</body>
</html>
npm install jspdf
npm install jspdf-autotable
npm install @types/jspdf
npm install @types/jspdf-autotable
import jsPDF from "jspdf";
import "jspdf-autotable";
import bwipjs from "bwip-js";
// Функция, которая создает баркод на странице
const createBarcode = (doc, x, y, text) => {
bwipjs.toCanvas("canvas", {
bcid: "code128", // тип штрих-кода
text: text, // текст, который нужно закодировать
scale: 3, // масштабирование
});
const canvas = document.getElementById("canvas");
const imgData = canvas.toDataURL("image/png");
doc.addImage(imgData, "PNG", x, y, 50, 10);
};
// Создаем новый документ PDF
const doc = new jsPDF({
orientation: "portrait",
unit: "mm",
format: "a4",
});
// Добавляем первую страницу
doc.addPage();
// Создаем баркоды на первой странице
createBarcode(doc, 10, 10, "123456789");
createBarcode(doc, 10, 30, "987654321");
// Добавляем вторую страницу
doc.addPage();
// Создаем баркоды на второй странице
createBarcode(doc, 10, 10, "55555555");
createBarcode(doc, 10, 30, "77777777");
// Добавляем третью страницу
doc.addPage();
// Создаем баркоды на третьей странице
createBarcode(doc, 10, 10, "11111111");
createBarcode(doc, 10, 30, "22222222");
// Сохраняем PDF файл
doc.save("barcodes.pdf");
let proc = get_proc();
let s = [0, 0];
let q = [s];
const algorithm = (processor, queue) => new Promise((resolve, reject) => {
let qu = queue;
let point = queue.shift();
processor.check(point[0], point[1]).then(x => {
if (!x.allowed) {
processor.move_left(point[0], point[1]).then(() => {
qu.push([point[0] - 1, point[1]]);
resolve(qu);
});
} else {
resolve(true);
}
}).then(st => {
if (st) {
s = point;
resolve(point);
} else {
return algorithm(processor, qu);
}
}).catch(err => reject(err));
});
algorithm(proc, q).then((result) => {
if (result !== null) {
q = result;
return algorithm(proc, q);
}
}).then(() => console.log(s));
const chat = document.getElementById('chat');
// Создание нового наблюдателя за изменениями в chat
const observer = new MutationObserver(() => {
// Если chat.scrollHeight изменилось, прокрутите до нижнего края chat
if (chat.scrollHeight !== chat.dataset.scrollHeight) {
chat.scrollTo(0, chat.scrollHeight);
chat.dataset.scrollHeight = chat.scrollHeight;
}
});
// Настройка конфигурации наблюдателя
const config = { attributes: true, childList: true, subtree: true };
// Запуск наблюдателя за изменениями
observer.observe(chat, config);
const swiper = new Swiper('.swiper-container', {
// настройки Swiper
});
swiper.on('transitionEnd', function () {
const activeSlide = swiper.slides[swiper.activeIndex];
const section4 = activeSlide.querySelector('.section-4');
if (section4) {
section4.scrollIntoView({ behavior: 'smooth' });
}
});
const hero_slider = new Swiper('.hero-slider', {
modules: [Navigation, EffectFade],
effect: "fade",
fadeEffect: {
crossFade: true
},
autoplay: {
delay: 5000, // время задержки между слайдами
disableOnInteraction: false, // слайды будут продолжать автоматически переключаться при нажатии на кнопки навигации
},
navigation: {
nextEl: '.khutorok-slider-button_next',
prevEl: '.khutorok-slider-button_prev',
disabledClass: "khutorok-slider-button_disabled",
},
});
function exportSheetToPDF() {
// Получаем активный Spreadsheet (гугл таблицу)
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Получаем лист по его имени
var sheet = ss.getSheetByName('Имя листа');
// Экспортируем лист в PDF
var url = ss.getUrl();
url = url.replace(/edit$/,'');
var sheetId = sheet.getSheetId();
var pdfName = sheet.getName() + ".pdf";
var pdfUrl = url + 'export?exportFormat=pdf&format=pdf' +
'&size=letter' +
'&portrait=true' +
'&fitw=true' +
'&sheetnames=false&printtitle=false' +
'&pagenumbers=false&gridlines=false' +
'&fzr=false' +
'&gid=' + sheetId;
var options = {
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken(),
}
}
var response = UrlFetchApp.fetch(pdfUrl, options);
var blob = response.getBlob().setName(pdfName);
// Сохраняем PDF в Google Drive
var folder = DriveApp.getFolderById('ID папки');
folder.createFile(blob);
}
window.addEventListener('scroll', function() {
var myBlock = document.getElementById('myBlock');
var scrollPosition = window.scrollY + window.innerHeight;
var blockPosition = myBlock.offsetTop + myBlock.offsetHeight;
if (scrollPosition >= blockPosition) {
window.scrollTo(0, blockPosition - window.innerHeight);
}
});
<!DOCTYPE html>
<html>
<head>
<title>Scroll to Element</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body onload="scrollToElement()">
<div style="height: 1000px;"></div>
<div id="myElement">This is my element.</div>
<div style="height: 1000px;"></div>
<script>
function scrollToElement() {
const element = document.getElementById("myElement");
element.scrollIntoView();
}
</script>
</body>
</html>