- 1
- 2
- 3
- 4
- 5
- 6
- 7
public static String padRight(String s, int n) {
return String.format("%-" + n + "s", s);
}
public static String padLeft(String s, int n) {
return String.format("%" + n + "s", s);
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
Всего: 33
−10
public static String padRight(String s, int n) {
return String.format("%-" + n + "s", s);
}
public static String padLeft(String s, int n) {
return String.format("%" + n + "s", s);
}
How can I pad a String in Java?
https://stackoverflow.com/questions/388461/how-can-i-pad-a-string-in-java/391978
Все ответы восхитительны в своей коричневости.
0
bool addPlayer(const Addr & addr,
Poco::Nullable<const std::string> serverAddr,
Poco::Nullable<bool> isKeyReceived,
Poco::Nullable<std::string> key,
Poco::Nullable<time_t> lastHashCheck,
Poco::Nullable<std::string> digest)
{
bool isPlaying = !serverAddr.isNull();
bool isKeyReceivedReal = isKeyReceived.isNull();
time_t lastHashCheckReal = lastHashCheck.isNull() ? time(0) : lastHashCheck.value();
std::string keyReal(key.isNull() ? "" : key.value());
std::string playerAddr = addr.getHost();
std::string serverAddrReal(serverAddr.isNull() ? "" : serverAddr.value());
std::string digestReal = digest.isNull() ? "" : digest.value();
Statement insert(*playersSession);
insert << "INSERT INTO Players VALUES(?, ?, ?, ?, ?, ?, ?)",
use(playerAddr), // Addr
use(serverAddrReal), // Server
use(isPlaying),
use(isKeyReceivedReal),
use(keyReal), // Key
use(lastHashCheckReal),
use(digestReal);
insert.execute();
return true;
}
0
-- Теперь мы можем легко получить отчёт по продажам на прошлую дату:
DELIMITER ;
BEGIN;
CALL set_prot_snapshot_date('2018-10-09 17:23:47', NULL, -1);
SELECT NOW() report_time, d.date, SUM(p.amount * p.price) sum
FROM docs d
INNER JOIN doc_pos p ON d.id = p.doc_id
GROUP BY d.date;
ROLLBACK;
https://habr.com/ru/post/425769/
Как научить MySQL заглядывать в прошлое
+1
public class Spot {
private Piece piece;
private int x;
private int y;
public Spot(int x, int y, Piece piece)
{
this.setPiece(piece);
this.setX(x);
this.setY(y);
}
public Piece getPiece() // метод возвращает объект фигуру
{
return this.piece;
}
public void setPiece(Piece p)
{
this.piece = p;
}
public int getX()
{
return this.x;
}
public void setX(int x)
{
this.x = x;
}
public int getY()
{
return this.y;
}
public void setY(int y)
{
this.y = y;
}
}
Дизайн шахматной игры
Эти виды вопросов задаются на интервью, чтобы судить о навыке объектно ориентированного дизайна кандидата. Итак, прежде всего, мы должны подумать о классах.
https://habr.com/ru/post/660003/
0
// Проверка активных ip-адресов
$is_active = false;
if ($dir = opendir($path_active)) {
while (false !== ($filename = readdir($dir))) {
// Выбирается ip + время активации этого ip
if (preg_match('#^(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})_(\d+)$#', $filename, $matches)) {
if ($matches[2] >= time() - self::intervalSeconds) {
if ($matches[1] == $ip_address) {
$times = intval(trim(file_get_contents($path_active . $filename)));
if ($times >= self::intervalTimes - 1) {
touch($path_block . $filename);
unlink($path_active . $filename);
} else {
file_put_contents($path_active . $filename, $times + 1);
}
$is_active = true;
}
} else {
unlink($path_active . $filename);
}
}
}
closedir($dir);
}
// Проверка заблокированных ip-адресов
$is_block = false;
if ($dir = opendir($path_block)) {
while (false !== ($filename = readdir($dir))) {
// Выбирается ip + время блокировки этого ip
if (preg_match('#^(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})_(\d+)$#', $filename, $matches)) {
if ($matches[2] >= time() - self::blockSeconds) {
if ($matches[1] == $ip_address) {
$is_block = true;
$time_block = $matches[2] - (time() - self::blockSeconds) + 1;
}
} else {
unlink($path_block . $filename);
}
}
}
closedir($dir);
}
// ip-адрес заблокирован
if ($is_block) {
header('HTTP/1.0 502 Bad Gateway');
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
echo '<html xmlns="http://www.w3.org/1999/xhtml">';
echo '<head>';
echo '<title>502 Bad Gateway</title>';
echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
echo '</head>';
echo '<body>';
echo '<h1 style="text-align:center">502 Bad Gateway</h1>';
echo '<p style="background:#ccc;border:solid 1px #aaa;margin:30px au-to;padding:20px;text-align:center;width:700px">';
echo 'К сожалению, Вы временно заблокированы, из-за частого запроса страниц сайта.<br />';
echo 'Вам придется подождать. Через ' . $time_block . ' секунд(ы) Вы будете автоматически разблокированы.';
echo '</p>';
echo '</body>';
echo '</html>';
exit;
}
PHP-скрипт для защиты от DDOS, парсинга и ботов
https://habr.com/ru/post/659811/
0
def _generate_greeting(self) -> str:
date = datetime.datetime.fromtimestamp(time.time(), pytz.timezone(config.TIMEZONE))
if 6 <= date.hour < 11:
return 'Доброе утро!'
elif 11 <= date.hour < 18:
return 'Добрый день.'
elif 18 <= date.hour < 23:
return 'Добрый вечер.'
else:
return 'Доброй ночи.'
+4
class ProjectIssue(
UserAgentDetailMixin,
SubscribableMixin,
TodoMixin,
TimeTrackingMixin,
ParticipantsMixin,
SaveMixin,
ObjectDeleteMixin,
RESTObject,
):
0
public function onAnswerPoll()
{
$data = request()->all();
ValidatePollForm::run($data);
try {
$options = Option::find($data['option_ids']);
$log = Crypt::decrypt($data['log']);
$log['options'] = array_merge(
array_get($log, 'options', []),
$options->lists('id')
);
$log['comments'] = array_get($log, 'comments', []) + array_get($data, 'comments', []);
$this->log = Crypt::encrypt($log);
$this->option = $options->first();
$this->poll = $this->loadPoll();
$this->locations = Location::get();
$this->step = ++$data['step'];
if ($this->option->is_last) {
Log::store($this->poll, $log);
Option::whereIn('id', $log['options'])->get()->each(function ($item) {
$item->increment('votes');
$item->logs()->create();
});
}
} catch (Exception $e) {
trace_log($e);
return response()
->json('Something was wrong.', 500);
}
}
/**
* onLoadDepartments
*/
public function onLoadDepartments()
{
$data = request()->all();
$validator = Validator::make($data, [
'location' => 'required|exists:kitsoft_polls_locations,slug',
'answer_id' => 'required|exists:kitsoft_polls_answers,id'
]);
if ($validator->fails()) {
throw new ValidationException($validator);
}
try {
$this->departments = Department::make()
->whereHas('locations', function ($query) use ($data) {
return $query->where('slug', $data['location']);
})
->whereHas('answers', function ($query) use ($data) {
return $query->where('id', $data['answer_id']);
})
->get();
} catch (Exception $e) {
trace_log($e);
return response()
->json('Something was wrong.', 500);
}
}
Из слитых сорцов «Дія.City».
+1
function test() {
const ws = new WebSocket('ws://127.0.0.1:445');
ws.addEventListener('close', event =>
console.log('event.code = ', event.code, '; event.reason = ', event.reason)
);
ws.close(3500, 'some reason');
}
test();
Кто угадает значения полей event.code и event.reason — тому два нихуя.
Кто угадает значение одного из полей — тому одно нихуя.
0
services:
zookeeper:
image: docker.io/bitnami/zookeeper:3.7
environment:
ALLOW_ANONYMOUS_LOGIN: yes
volumes:
- zookeeper_data:/bitnami
volumes:
zookeeper_data:
Кто найдёт ошибку в docker-compose.yaml — тому нихуя.