- 1
- 2
- 3
- 4
- 5
- 6
В боте @GovnokodBot обновление:
Теперь говнокоды отправляются скриншотами.
Также создан канал "Говнокода" в "Telegram": https://t.me/GovnokodChannel
Баги и пожелания можно писать сюда.
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+2
В боте @GovnokodBot обновление:
Теперь говнокоды отправляются скриншотами.
Также создан канал "Говнокода" в "Telegram": https://t.me/GovnokodChannel
Баги и пожелания можно писать сюда.
Зеркала Говнокода и полезные ресурсы:
* https://govnokod.xyz/
* https://gcode.space/
* индекс оффтопов: https://index.gcode.space/
* https://t.me/GovnokodBot
* https://pethu.ru
0
<?php
/* -= Developed by [email protected] =- */
// -= О П Ц И И =-
require("config.php");
// Технические настройки скрипта
header('Content-Type: text/html; charset=utf-8');
ini_set('memory_limit', '-1');
// -=-=-=-=-=-=-=-
// -= Функции инкапсуляции технических аспектов =-
// Функция печати логов, добавляет "date n time now" и перенос строки
function printLog($text) { echo sprintf("[%s] %s", date("Y-m-d H:i:s"), $text) . "\n"; }
// Функция преобразования текста в ключ индекса, убирает пробелы, переводит в верхний регистр и добавляет префикс "_"
function str2idx($str) { return "_" . strtoupper( str_replace(' ', '', (string)$str) ); }
// Функция генерации ассоциативного массива индексов, использует str2idx
function genIdxs($array, $val_key, $idx_keys, $filter_func=NULL) {
$idxs = [];
foreach ($array as $item) {
if ($filter_func && !$filter_func($item)) { continue; }
if (is_string($idx_keys)){
foreach (preg_split("/\s?;\s?/", $item[$idx_keys]) as $idx) {
if ($idx) { $idxs[str2idx($idx)] = str2idx((string)$item[$val_key]); }
} unset($idx);
} else {
foreach ($idx_keys as $idx_key) {
foreach (preg_split("/\s?;\s?/", $item[$idx_key]) as $idx) {
if ($idx) { $idxs[str2idx($idx)] = str2idx((string)$item[$val_key]); }
}
} unset($idx_key);
}
} unset($item);
return $idxs;
}
// Функция сравнения изображений
function compareImages($image1, $image2) {
$compare_result = $image1->compareImages($image2, IMAGICK_METRIC);
return (int)$compare_result[1] > THRESHOLD_SIMILARITY_VALUE;
}
// Функция исполнения SQL-запросов в БД, инкапсулирующая все ужасы взаимодействия с БД MySQL на PHP
function execSQL($sql, $mode="fetch_assoc") {
// Проверяем коннект к БД, в случае проблем - пытаемся переподключ
if (!$GLOBALS["mysqli"] || $GLOBALS["mysqli"]->connect_errno) {
$GLOBALS["mysqli"] = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($GLOBALS["mysqli"]->connect_errno) {
throw new Exception("Can't connect to DB: (".$GLOBALS["mysqli"]->connect_errno.") ".$GLOBALS["mysqli"]->connect_error);
}
printf("default charset: %s\n", $GLOBALS["mysqli"]->character_set_name());
/* изменение набора символов на utf8 */
if (!$GLOBALS["mysqli"]->set_charset("utf8")) {
throw new Exception("set charset utf8 error: %s\n", $GLOBALS["mysqli"]->error);
} else { printf("current charset: %s\n", $GLOBALS["mysqli"]->character_set_name()); }
}
$_result = $GLOBALS["mysqli"]->query($sql);
if (!$_result) { printLog("SQL ERROR: ". $GLOBALS["mysqli"]->error . "\n executable SQL: " . $sql . "\n\n"); }
if (is_bool($_result)) { return $_result; }
elseif ($mode==="num_rows") { return $_result->num_rows; }
elseif ($mode==="fetch_assoc") {
$result = [];
while($row = $_result->fetch_assoc()) {
reset($row);
$key = str2idx($row[key($row)]);
$result[$key] = $row;
} unset($row);
return $result;
}
throw new Exception("Recieved unexpected mode (".$mode.") or query result by execute SQL: ".$sql );
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// -= Старт работы скрипта =-
$start = microtime(true);
printLog("Updater script started");
// Инициализация глобальных переменных, счетчиков
$GLOBALS["mysqli"] = NULL;
$kingsilk_offers_count = 0;
// Проверка хранилища фотографий
if (!is_dir(IMAGES_PATH)) throw new Exception("ERROR: images path not found!");
$IMAGES_FULL_PATH = IMAGES_PATH . IMAGE_PATH_PREFIX;
if (!is_dir($IMAGES_FULL_PATH)) mkdir($IMAGES_FULL_PATH);
// -=-=-=-=-=-=-=-=-=-=-=-=-=-
// -= Получение YML-данных от поставщика Кингсилк, формирование индексов =-
$yml_catalog = new SimpleXMLElement(
file_get_contents(YML_URL_KINGSILK)
);
// Формирование индекса импортируемых категорий по id'шнику категории поставщика
$GLOBALS['cats_outer_idxs'] = [];
foreach ($yml_catalog->categories->category as $cat){
$GLOBALS['cats_outer_idxs'][str2idx((string)$cat["id"])] = $cat;
} unset($cat);
// Группировка предложений поставщика по схожести картинок,
// формирование древовидного индекса по md5 хэшу картинок
$offers_groups_idxs = [];
foreach ($yml_catalog->offers->offer as $offer) {
// Отсеиваем не опубликованные товары
if ((string)$offer["available"] != "true"){
continue;
}
$kingsilk_offers_count++;
$hash = NULL;
- = А ЧО ТУТ НЕЛЬЯ ПОСТИТЬ ПОЛНЫЙ КОД = - ???
===~ ТАМ ДОХРЕНА ЕЩЁ ~==
P.S - вот как кодят питонисты на php
продолжение: <a href="https://raw.githubusercontent.com/Siyet/goods-updater-oc3-php7/master/updater.php">Перейти</a>
+1
$data = [];
$firstGenreId = Genre::where('homepage_filter_band', 1)->first()->id;
$bandSearch = [
'limit' => request('limit') ?? 6,
'genre' => $firstGenreId,
'category' => BandCategory::where('homepage_filter', 1)->first()->id,
'status' => 1
];
$subGenres = Genre::getGenresByCategory($bandSearch['genre']);
$bandSearch['genre'] = [$bandSearch['genre']];
foreach ($subGenres as $subGenre){
array_push($bandSearch['genre'], $subGenre->id);
}
$data['bandsGenre']['bands'] = Band::getBandsLimitListByGenre($bandSearch);
$data['bandsGenre']['filters'] = Genre::isExistGenreByBandFilter();
$data['bandsGenre']['active_filter'] = $firstGenreId;
$data['bandsGenre']['type'] = 'genre';
$data['bandsCategories']['bands'] = Band::getBandsLimitListByCategory($bandSearch);
$data['bandsCategories']['filters'] = BandCategory::isExistCategoryByBandFilter();
$data['bandsCategories']['active_filter'] = $bandSearch['category'];
$data['bandsCategories']['type'] = 'category';
$data['bandsStatus']['bands'] = Band::getBandsLimitListByStatus($bandSearch);
$data['bandsStatus']['active_filter'] = 1;
$data['bandsStatus']['filters'] = (object)[
0 => [
'id' => 1,
'name' => trans('validation-custom.newest')
],
1 => [
'id' => 2,
'name' => trans('validation-custom.lastUpdated')
]
];
$data['bandsStatus']['type'] = 'status';
$firstGenreId = Genre::where('homepage_filter_musician', 1)->first()->id;
$firstInstrumentId = Instrument::where('homepage_filter', 1)->first()->id;
$musicianSearch = [
'limit' => request('limit') ?? 6,
'genre' => $firstGenreId,
'instrument' => $firstInstrumentId,
'status' => 1
];
$subGenres = Genre::getGenresByCategory($musicianSearch['genre']);
$musicianSearch['genre'] = [$musicianSearch['genre']];
foreach ($subGenres as $subGenre){
array_push($musicianSearch['genre'], $subGenre->id);
}
$subInstruments = Instrument::getInstrumentsByCategory($musicianSearch['instrument']);
$musicianSearch['instrument'] = [$musicianSearch['instrument']];
foreach ($subInstruments as $subInstrument){
array_push($musicianSearch['instrument'], $subInstrument->id);
}
$data['musiciansGenre']['musicians'] = User::getMusiciansLimitListByGenre($musicianSearch);
$data['musiciansGenre']['filters'] = Genre::isExistGenreByFilter();
$data['musiciansGenre']['active_filter'] = $firstGenreId;
$data['musiciansGenre']['type'] = 'genre';
$data['musiciansInstrument']['musicians'] = User::getMusiciansLimitListByInstrument($musicianSearch);
$data['musiciansInstrument']['filters'] = Instrument::isExistInstrumentByFilter();
$data['musiciansInstrument']['active_filter'] = $firstInstrumentId;
$data['musiciansInstrument']['type'] = 'instrument';
$data['musiciansStatus']['musicians'] = User::getMusiciansLimitListByStatus($musicianSearch);
$data['musiciansStatus']['active_filter'] = 1;
$data['musiciansStatus']['filters'] = (object)[
0 => [
'id' => 1,
'name' => trans('validation-custom.newest')
],
1 => [
'id' => 2,
'name' => trans('validation-custom.lastUpdated')
]
];
$data['musiciansStatus']['type'] = 'status';
return response()->json($data, 200);
Кажуть - шота сторінка довго грузиться :)
+1
class MyEvents extends \Event\EventsHandler {
static $key = 1;
public function BeforeQuery() {
Timer::start(self::$key);
}
public function AfterQuery() {
Timer::step(self::$key++);
if(Timer::$last['different'] > 1) {
$debug_backtrace = debug_backtrace();
foreach($debug_backtrace as $k=>$v) {
if($v['function'] == 'q') {
$error = "QUERY: ".$v['args'][0]."\n".
"file: ".$v['file']."\n".
"line: ".$v['line']."\n".
"date: ".date("Y-m-d H:i:s")."\n".
"===================================";
file_put_contents('./logs/slowquery.log',$error."\r\n",FILE_APPEND);
break;
}
}
}
}
public function ShutDownSystem() {
echo microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
}
}
Event::setEventHandler('MyEvents');
q("SELECT * FROM `table` ORDER BY RAND()");
q("SELECT NOW()");
echo Timer::result();
Измеряем время запросов и время загрузки страницы
https://school-php.com/tricks/23/dokumentatsiya-po-fw
+1
while (true) {
if ($current === $requested) {
break;
}
if (! in_array($requested, $available)) {
break;
}
session()->put('locale', $requested);
break;
}
0
Именно поэтому я за «PHP» #3
#1: https://govnokod.ru/26462 https://govnokod.xyz/_26462
#2: https://govnokod.ru/26827 https://govnokod.xyz/_26827
+1
// Both set_time_limit(...) and ini_set('max_execution_time',...); won't count the time cost of sleep,
// file_get_contents,shell_exec,mysql_query etc, so i build this function my_background_exec(),
// to run static method/function in background/detached process and time is out kill it:
// my_exec.php:
<?php
function my_background_exec($function_name, $params, $str_requires, $timeout=600)
{$map=array('"'=>'\"', '$'=>'\$', '`'=>'\`', '\\'=>'\\\\', '!'=>'\!');
$str_requires=strtr($str_requires, $map);
$path_run=dirname($_SERVER['SCRIPT_FILENAME']);
$my_target_exec="/usr/bin/php -r \"chdir('{$path_run}');{$str_requires} \\\$params=json_decode(file_get_contents('php://stdin'),true);call_user_func_array('{$function_name}', \\\$params);\"";
$my_target_exec=strtr(strtr($my_target_exec, $map), $map);
$my_background_exec="(/usr/bin/php -r \"chdir('{$path_run}');{$str_requires} my_timeout_exec(\\\"{$my_target_exec}\\\", file_get_contents('php://stdin'), {$timeout});\" <&3 &) 3<&0";//php by default use "sh", and "sh" don't support "<&0"
my_timeout_exec($my_background_exec, json_encode($params), 2);
}
// ...
Шедевр (заплюсованный) из https://www.php.net/manual/ru/function.set-time-limit.php.
0
Именно поэтому я за «PHP».
0
https://github.com/moscow-technologies/blockchain-voting/tree/voting2020/elec2020/ballot
https://github.com/moscow-technologies/blockchain-voting/blob/voting2020/elec2020/ballot/public/js/forms/mgik/LeavingPageCheckerInit.js
https://github.com/moscow-technologies/blockchain-voting/blob/voting2020/elec2020/frontend-library-source/crypto-lib/src/util/numberFromLeBytes.js
Как и всё в этой стране, обнуление написано на PHP, jQuery и (да-да) местами Rust, а управляется supervisord, ибо для редактирования юнитов systemd нужно sudo, который не дали.
Какой блокчейн )))
0
/**
* @param int $filterType
* @return int
*/
public static function performanceFarmerStatFilterTranslator(int $filterType): int
{
switch (true) {
case 1 === $filterType:
return Task::TYPE_PREPARE_ACCOUNTS_BY_REQUEST;
case 2 === $filterType:
return Task::TYPE_PREPARE_GOOGLE_ACCOUNTS_BY_REQUEST;
case 3 === $filterType:
return Task::TYPE_PREPARE_TWITTER_ACCOUNTS_BY_REQUEST;
case 4 === $filterType:
return Task::TYPE_PASSWORD_MATCHING;
case 6 === $filterType:
return Task::TYPE_ACCOUNT_MARKUP;
case 7 === $filterType:
return Task::TYPE_REPLACE_ACCOUNTS;
}
return 0;
}