"function$((1 + ($RANDOM % 3)))"
$RANDOM
при каждом вызове вернёт случайное 16-битное целое от 0 до 32767. Можно брать остаток от деления его на 3 – будет 0, 1 или 2 – и добавив единицу приклеить к слову "function" – получится имя нужной функции. Остаётся её вызвать – просто эта строка в bash скрипте, собственно, и вызывает полученную функцию.$ ./rand.sh
пукпук
$ ./rand.sh
пукпук
$ ./rand.sh
пукпук3
$ ./rand.sh
пукпук3
$ ./rand.sh
пукпук3
$ ./rand.sh
пукпук3
$ ./rand.sh
пукпук3
$ ./rand.sh
пукпук2
$ ./rand.sh
пукпук2
$ ./rand.sh
пукпук2
$ ./rand.sh
пукпук2
$ ./rand.sh
пукпук
$ cat ./rand.sh
#!/bin/bash
function1() {
echo пукпук
}
function2() {
echo пукпук2
}
function3() {
echo пукпук3
}
"function$((1 + ($RANDOM % 3)))"
[func1, func2, func3]
// обернуть каждую в Promise:
.map((f) => () => new Promise((res, rej) => {
f();
setTimeout(res, 2000));
})
// и собрать цепочку из этих промисов:
.reduce((acc, c) => acc.then(c()), Promise.resolve());
- f();
- setTimeout(res, 2000));
+ f()
+ .then(() => setTimeout(res, 2000)));
async componentDidMount() {
const lastSongsResponse = await fetch("https://api.laut.fm/station/key/last_songs");
const lastSongs = await lastSongsResponse.json();
lastSongs.length = Math.min(7, lastSongs.length);
const promises = lastSongs.map((song) => new Promise((resolve, reject) => {
const params = {
method : 'album.getInfo',
artist : song.artist.name.replace(' & ', ', '),
album : song.album,
api_key : 'apikey',
format : 'json',
};
const url = "https://ws.audioscrobbler.com/2.0/?" + Object.keys(params).map((key) => `${key}=${params[key]}`).join('&');
const cover = await fetch(url)
.then((response) => response.json())
.then((songData) => songData.album.image[4]["#text"])
.catch(err => reject(err));
const date = new Date(song.started_at);
const songData = {
id1 : song.id,
id2 : song.id + 1,
artist : song.artist.name,
title : song.title,
cover : cover,
started_at : date.getHours() + ':' + date.getMinutes().toString().padStart(2, '0')
}
resolve(songData);
}));
const results = await Promise.all(promises);
this.setState({ results: results })
}
const deferred = () => {
Promise.prototype.resolve = () => {}; // чтобы не было ошибок )
return Promise.resolve("web");
}
// проверка
deferred()
.then(function(res) {
console.log(200, res);
return "lab";
})
.then(function(res) {
console.log(100, res);
})
.resolve("web");
// реализация
function deferred() {
function Box() {
this.queue = [];
}
Box.prototype.then = function(func) {
this.queue.push(func);
return this;
}
Box.prototype.resolve = function(first_arg) {
let arg = first_arg;
while (this.queue.length)
arg = this.queue.shift().call(this, arg);
}
return new Box;
}
-t ???
:ffmpeg -i SOURCE
// найти duration
ffmpeg \
-i SOURCE \
-t XXX \
-codec copy \
DESTINATION
При отсутствии перекодирования , т.к. кодеки те же, процесс должен быть очень быстрым."<div class=\"$array[key]\"> </div>";
"<div class=\"{$array['key']}\"> </div>";
"<div class=\"$object->property\"> </div>";
См. Variable parsing var groups = "apiclub,55293029"; // сюда подставить ваши группы
var counts = API.groups.getById({
group_ids: groups,
fields: "members_count",
})@.members_count;
var total = 0;
while (counts.length > 0) total = total + counts.pop();
return total;
$code = <<<EOFVK
var groups = "apiclub,55293029";
var counts = API.groups.getById({
group_ids: groups,
fields: "members_count",
})@.members_count;
var total = 0;
while (counts.length > 0) total = total + counts.pop();
return total;
EOFVK;
// токен сообщества получить в Настройках своего сообщества, Работа с API
// нажать кнопку Создать ключ и выбрать любую галочку.
$token = '123123123';
$method = 'execute';
$params = [
'access_token' => $token,
'v' => '5.130',
];
$post_data = [
'code' => $code,
];
$url = sprintf(
'https://api.vk.com/method/%s?%s',
$method,
http_build_query($params)
);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $post_data,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
]);
$curl_result = curl_exec($ch);
$data = json_decode($curl_result);
$count = $data->response;
printf('<h2>Сейчас в группах %d участников</h2>', $count);
const appendByAttr = (title, subtitle) => jQuery(`a[title="${title}"] ~ .ammenu-submenu-container .ammenu-item.-child.-col-4 a[title="${subtitle}"] ~ ul li:last-child`)
.append($(`a[title="${title}"] ~ .ammenu-submenu-container .ammenu-item__extra`));
appendByAttr('Title 1', 'Subtitle 1');
appendByAttr('Title 2', 'Subtitle 2');
appendByAttr('Title 3', 'Subtitle 3');
Number(num_string)
/^[\*\/\+-]$/
"23к1с2".split(/[а-яй]+/) // [ "23", "1", "2" ]
"23к1с2".match(/([а-яй]+)/g) // [ "к", "с" ]
YaParse = (str) => {
const nums = str.split(/[а-яй]+/) // [ "23", "1", "2" ]
const parts = str.match(/([а-яй]+)/g) // [ "к", "с" ]
parts.unshift("дом");
return nums.reduce((acc, c, i) => (acc[parts[i]] = c, acc), {});
}
console.log(YaParse("23к1с2")); // { "дом": "23", "к": "1", "с": "2" }
example.com/profile
покажет кажому залогиненному пользователю именно его инфу, которую он, к тому же, сможет редактировать.example.com/user/12345
доступная всем, покажет только публичную информацию о юзере с id = 12345.