local mappings = {
n = {
["b"] = { "<Plug>Sneak_S", desc = "Sneak back" },
["<M-l>"] = { ":wa<CR>", desc = "close all" },
["<leader>;"] = { ":vsplit<CR>", desc = "split" },
["<S-l>"] = {
function() require("astronvim.utils.buffer").nav(vim.v.count > 0 and vim.v.count or 1) end,
desc = "Next buffer",
},
["<S-h>"] = {
function() require("astronvim.utils.buffer").nav(-(vim.v.count > 0 and vim.v.count or 1)) end,
desc = "Previous buffer",
},
},
i = {
["<C-l>"] = { "copilot#Accept('\\<CR>')", desc = "copilot expand", silent = true, expr = true, script = true },
},
}
-- Функция для удаления непечатных символов
local function removeNonPrintableChars(str)
return str:gsub("[%z\1-\31\127-\255]", "")
end
-- Удалить непечатные символы из значений таблицы mappings
for _, mode in pairs(mappings) do
for _, mapping in pairs(mode) do
if type(mapping) == "table" and mapping.desc then
mapping.desc = removeNonPrintableChars(mapping.desc)
end
end
end
return mappings
import time
from telebot import types
current_step = None
def family_buttons(message):
global current_step
email(message)
current_step = 'email'
def email(message):
markup = types.InlineKeyboardMarkup(row_width=1)
email_button = types.InlineKeyboardButton('Введите почту', callback_data='email')
markup.add(email_button)
bot.send_message(message.chat.id, 'Время заполнения поля 30 секунд', reply_markup=markup)
def phone_code(message):
markup = types.InlineKeyboardMarkup(row_width=1)
phone_code_button = types.InlineKeyboardButton('Введите код телефона', callback_data='phone_code')
markup.add(phone_code_button)
bot.send_message(message.chat.id, 'Нажмите для заполнения поля!', reply_markup=markup)
@bot.callback_query_handler(func=lambda call: True)
def callback(call):
global current_step
if call.message:
if call.data == 'email':
text_email = bot.send_message(chat_id=call.message.chat.id, text='Введите почту')
bot.register_next_step_handler(text_email, next)
elif call.data == 'phone_code':
text_phone_code = bot.send_message(chat_id=call.message.chat.id, text='Введите код телефона')
bot.register_next_step_handler(text_phone_code, next)
def next(message):
global current_step
if current_step == 'email':
# Обработка введенной почты
current_step = 'phone_code'
phone_code(message)
elif current_step == 'phone_code':
# Обработка введенного кода телефона
current_step = None
# Здесь можете выполнить какие-то действия после завершения обоих шагов
import React, { useEffect, useState } from "react";
import { useAppDispatch, useAppSelector } from "../hooks/hooks";
import "./styles/Tester.scss";
import { keyboardHandler, startTyping } from "../store/typer.slice";
const Tester: React.FC = () => {
const accuracy = useAppSelector((state) => state.typer.accuracy);
const text = useAppSelector(({ typer: { text } }) => Array.from(text));
const time = useAppSelector((state) => state.typer.time);
const words = useAppSelector((s) => s.typer.words);
const completeWords = useAppSelector((s) => s.typer.completeWords);
const key = useAppSelector((state) => state.typer.key);
const characters = useAppSelector((state) => state.typer.countCharacters);
const inputText = useAppSelector((s) => s.typer.inputText);
const dispatch = useAppDispatch();
const [printedText, setPrintedText] = useState(""); // Новое состояние для хранения текста с обернутыми символами
useEffect(() => {
const keyHandler = (event: KeyboardEvent) => {
dispatch(keyboardHandler(event.key));
};
dispatch(startTyping());
document.addEventListener("keydown", keyHandler);
return () => {
document.removeEventListener("keydown", keyHandler);
};
}, []);
const inputOnChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
let newPrintedText = "";
for (let i = 0; i < text.length; i++) {
if (i < value.length) {
// Проверка на наличие символа в введенном тексте
if (text[i] === value[i]) {
newPrintedText += `<span class="highlight">${text[i]}</span>`; // Обернуть символ в <span> с классом highlight
} else {
newPrintedText += text[i]; // Добавить символ без обертки
}
} else {
newPrintedText += text[i]; // Добавить символ без обертки
}
}
setPrintedText(newPrintedText);
};
return (
<div className="testWrapper">
<div>
<p
className="textForTest"
dangerouslySetInnerHTML={{ __html: printedText }} // Используйте dangerouslySetInnerHTML для отображения HTML-разметки
/>
<input
value={inputText}
onChange={inputOnChange}
type="text"
placeholder="text"
/>
<p>Last character: {key}</p>
<div className="typeStatistics">
<span className="statisticsItem">Accuracy: {accuracy}%</span>
<span className="statisticsItem">
Characters per minute: {characters}
</span>
<span className="statisticsItem">Time: {time} s.</span>
</div>
</div>
<div className="controls">
<button>Start</button>
<button>Restart</button>
</div>
</div>
);
};
export default Tester;
.highlight {
background-color: yellow;
}
// Подключение к БД
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'myusername';
$password = 'mypassword';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$pdo = new PDO($dsn, $username, $password, $options);
// Подготовленный запрос
$stmt = $pdo->prepare("INSERT INTO mytable (snippet, amp, date, anchor, link) VALUES (:snippet, :amp, :date, :anchor, :link)");
// Заполнение параметров запроса значениями из массива
foreach ($data as $values) {
$stmt->bindParam(':snippet', $values['snippet']);
$stmt->bindParam(':amp', $values['amp']);
$stmt->bindParam(':date', $values['date']);
$stmt->bindParam(':anchor', $values['anchor']);
$stmt->bindParam(':link', $values['link']);
// Выполнение запроса
$stmt->execute();
}
#include <vector>
const int voxel_size = 16;
std::vector<short> get_voxels_from_chunk(short (*voxels)[voxel_size][voxel_size][voxel_size], int world_length, int chunk_size_x, int chunk_size_y, int chunk_size_z, int chunk_id) {
std::vector<short> result;
int chunk_count_x = world_length / chunk_size_x;
int chunk_count_y = world_length / chunk_size_y;
int chunk_count_z = world_length / chunk_size_z;
int chunk_index_x = chunk_id % chunk_count_x;
int chunk_index_y = (chunk_id / chunk_count_x) % chunk_count_y;
int chunk_index_z = chunk_id / (chunk_count_x * chunk_count_y);
int x_offset = chunk_index_x * chunk_size_x;
int y_offset = chunk_index_y * chunk_size_y;
int z_offset = chunk_index_z * chunk_size_z;
for (int i = x_offset; i < x_offset + chunk_size_x; i++){
for (int ii = y_offset; ii < y_offset + chunk_size_y; ii++){
for (int iii = z_offset; iii < z_offset + chunk_size_z; iii++){
result.push_back(*(*(*(voxels + i) + ii) + iii));
}
}
}
return result;
}
int main() {
short voxels[voxel_size][voxel_size][voxel_size]; // пример массива вокселей
int world_length = voxel_size;
int chunk_size_x = 4;
int chunk_size_y = 8;
int chunk_size_z = 8;
int chunk_id = 3; // пример id чанка
std::vector<short> chunk_voxels = get_voxels_from_chunk(&voxels, world_length, chunk_size_x, chunk_size_y, chunk_size_z, chunk_id);
// обработка chunk_voxels
return 0;
}
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");
npm install socks
const { SocksClient } = require('socks');
const proxyOptions = {
proxy: {
ipaddress: '127.0.0.1',
port: 1080,
type: 5 // SOCKS5 proxy
},
target: {
host: 'mc.example.com',
port: 19132
}
};
const client = new SocksClient(proxyOptions);
client.connect().then(() => {
// подключаемся к серверу Minecraft Bedrock через прокси
});
import { Module, OnModuleInit } from '@nestjs/common';
import { KnexModule } from '@nestjsplus/knex';
import { MigrationConfig } from '@nestjsplus/knex/dist/interfaces/migration-config.interface';
import * as path from 'path';
@Module({
imports: [
KnexModule.forRootAsync({
useFactory: (): MigrationConfig => ({
config: {
client: 'sqlite3',
useNullAsDefault: true,
connection: ':memory:',
},
migrations: {
directory: path.resolve(__dirname, 'migrations'),
},
}),
}),
],
})
export class DatabaseModule implements OnModuleInit {
constructor(private readonly knexService: KnexService) {}
async onModuleInit() {
await this.knexService.client.migrate.latest();
}
}
import { defineConfig } from 'vite.js';
import laravel from 'laravel-vite-plugin.js';
export default defineConfig({
plugins: [
laravel({
input: ['resources/css/app.css', 'resources/sass/app.scss', 'resources/js/app.js'], // явно указываем путь к app.js
refresh: true,
}),
],
});
npm run clear && npm run build
<head>
...
<link rel="stylesheet" type="text/css" href="slick/slick.css"/>
<link rel="stylesheet" type="text/css" href="slick/slick-theme.css"/>
...
<script type="text/javascript" src="slick/slick.min.js"></script>
...
</head>
<div class="slider-container">
<div class="slider-item"><img src="image1.jpg" alt=""></div>
<div class="slider-item"><img src="image2.jpg" alt=""></div>
<div class="slider-item"><img src="image3.jpg" alt=""></div>
</div>
<style>
.slider-container {
width: 100%;
margin: 0 auto;
}
.slider-item {
width: 100%;
margin: 0 auto;
}
</style>
<script type="text/javascript">
$('.slider-container').slick({
dots: true, // показать точки навигации
infinite: true, // зациклить слайдер
speed: 300, // скорость анимации
slidesToShow: 1, // количество показываемых слайдов
adaptiveHeight: true // подгонять высоту слайдера под высоту изображения
});
</script>
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));
<?php
$post_ids = get_objects_in_term( get_query_var( 'cat' ), 'category' );
if ( ! empty( $post_ids ) && ! is_wp_error( $post_ids ) ) {
$tags = get_terms( array(
'taxonomy' => 'post_tag',
'object_ids' => $post_ids,
'orderby' => 'count',
'order' => 'DESC',
'number' => 10
) );
if ( ! empty( $tags ) && ! is_wp_error( $tags ) ) {
shuffle($tags);
?>
<ul>
<?php foreach( $tags as $tag ) { ?>
<li><a href="<?php echo get_term_link( $tag, 'post_tag' ); ?>"><?php echo $tag->name; ?></a></li>
<?php } ?>
</ul>
<?php } ?>
<?php } ?>
import itertools
start_date = pd.to_datetime('2023-01-01') # дата начала отчета
artists = ['ANNA ASTI', 'Три дня дождя', 'MACAN']
songs = {
'ANNA ASTI': ['Девочка танцуй','Грустный дэнс','Гармония'],
'Три дня дождя': ['Демоны','Где ты','Перезаряжай'],
'MACAN': ['Кино','Пополам','Бенз'],
}
# создаем комбинации артистов и песен
artist_song_combinations = list(itertools.product(artists, songs.keys()))
# создаем список дат для каждого артиста и каждой его песни
date_list = [start_date + pd.DateOffset(days=i) for i in range(len(artists) * len(songs))]
# создаем датафрейм с датами, артистами и песнями
audio = pd.DataFrame({'date': date_list})
audio[['artist', 'track']] = pd.DataFrame(artist_song_combinations)
audio['track'] = audio['track'].apply(lambda x: songs[x])
# создаем столбец с количеством прослушиваний
audio['start'] = np.random.choice(count_music, len(audio))
audio.head()
for i in range(n):
for j in range(m):
if field[i][j] != '.':
valid_move = True
for dx, dy in [(1,0),(-1,0),(0,1),(0,-1)]:
x, y = i+dx, j+dy
while 0 <= x < n and 0 <= y < m:
if field[x][y] != '.':
valid_move = False
break
x += dx
y += dy
if not valid_move:
break
if not valid_move:
print('NO')
exit()