- 1
- 2
- 3
- 4
- 5
- 6
- 7
private bool CheckBool(string value)
{
if (value == "on")
return true;
else
return false;
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−1
private bool CheckBool(string value)
{
if (value == "on")
return true;
else
return false;
}
////
+5
inline int ms_001(int x){ return x ;} // x * 1
inline int ms_002(int x){ return x<<1 ;} // x * 2
inline int ms_003(int x){ return x<<2 - x ;} // x * 3
...
inline int ms_799(int x){ return x<<10 - x<<8 + x<<5 - x ;} // x * 799
inline int ms_800(int x){ return x<<10 - x<<8 + x<<5 ;} // x * 800
// массив указателей
int ( *mult_shift[800] ) (int) = {
ms_001,
ms_002,
...
ms_799,
ms_800 };
Очень быстрое целочисленное умножение
+1
if (!empty($tickets)) {
if (count($tickets)) {
$c_start = strtotime($convetion_details['start']);
$c_end = strtotime($convetion_details['end']);
$i = 0;
while ($c_start <= $c_end) {
if (is_int($i / 4) && $i > 0) $convetion_days_html .= '</tr><tr>';
$convetion_days_html .= '<td>' . date('d.m', $c_start) . ' ' . __t($days_of_week[date('w', $c_start)]) . ' <img src="' . str_replace('https', 'http', TEMPLATE_WWWPATH) . '/images/checkbox.png"/></td>';
$c_start = strtotime('+1 day', $c_start);
$i++;
}
//...
код из легаси 2007 года от индусов
+2
/**
* "Smart" Escape String
*
* Escapes data based on type
* Sets boolean and null types
*/
function escape($str)
{
if (is_string($str))
{
$str = "'".$this->escape_str($str)."'";
}
elseif (is_bool($str))
{
$str = ($str === FALSE) ? 0 : 1;
}
elseif (is_null($str))
{
$str = 'NULL';
}
return $str;
}
CodeIgniter 2, "Smart"
+2
defmodule Utils.String do
@moduledoc false
def comma_split(str), do: String.split(str, " ", trim: true)
end
0
import csv
import json
import requests
from io import StringIO
from lxml import etree
class DayPicParser(object):
url = 'урл_до_сайта'
def get_info(self):
handler = open('daypic.csv', 'w+')
page = 1
rows = []
tags = set()
while page <= 1077:
response = requests.get('{}/page/{}'.format(self.url, page))
response.connection.close()
parser = etree.HTMLParser()
tree = etree.parse(StringIO(response.text), parser)
posts = tree.xpath('//div[@class="posts"]/div[@class="post"]')
for i, post in enumerate(posts):
title = post.find('./h2/a')
link_to_fulltext = title.attrib['href']
short_text = post.find('./div[@class="text"]//p[1]')
response = requests.get(link_to_fulltext)
full_parser = etree.HTMLParser()
full_tree = etree.parse(StringIO(response.text), full_parser)
full_post = full_tree.xpath('//div[@class="text"]//p')
main_image = None
full_text = []
for inner in full_post:
if inner.find('.//noindex') is not None:
continue
if inner.find('.//img') is not None:
src = inner.find('.//img').attrib['src']
if not main_image:
main_image = src
full_text.append({'image': src})
for paragraph in etree.tostring(inner, method="text", encoding='utf-8').decode('utf-8').strip().split("\n"):
if paragraph:
full_text.append({'text': paragraph})
rows.append({'title': title.text.strip(),
'preview': main_image if main_image else '',
'short_text': short_text.text.strip(),
'full_text': full_text})
print('Post {} of {}'.format(i, len(posts)))
page += 1
print(page)
handler.write(json.dumps(rows))
handler.close()
print(tags)
DayPicParser().get_info()
−1
<?php
$_POST['sum'] = (float)number_format(preg_replace('~[^0-9.,]~ui', '',$_POST['sum']), 2);
?>
Получили float
0
int32 documentColorIndex(DocumentData *document, QString &ext) {
int32 colorIndex = 0;
QString name = document ? (document->name.isEmpty() ? (document->sticker() ? lang(lng_in_dlg_sticker) : qsl("Unknown File")) : document->name) : lang(lng_message_empty);
name = name.toLower();
int32 lastDot = name.lastIndexOf('.');
QString mime = document ? document->mime.toLower() : QString();
if (name.endsWith(qstr(".doc")) ||
name.endsWith(qstr(".txt")) ||
name.endsWith(qstr(".psd")) ||
mime.startsWith(qstr("text/"))
) {
colorIndex = 0;
} else if (
name.endsWith(qstr(".xls")) ||
name.endsWith(qstr(".csv"))
) {
colorIndex = 1;
} else if (
name.endsWith(qstr(".pdf")) ||
name.endsWith(qstr(".ppt")) ||
name.endsWith(qstr(".key"))
) {
colorIndex = 2;
} else if (
name.endsWith(qstr(".zip")) ||
name.endsWith(qstr(".rar")) ||
name.endsWith(qstr(".ai")) ||
name.endsWith(qstr(".mp3")) ||
name.endsWith(qstr(".mov")) ||
name.endsWith(qstr(".avi"))
) {
colorIndex = 3;
} else {
QChar ch = (lastDot >= 0 && lastDot + 1 < name.size()) ? name.at(lastDot + 1) : (name.isEmpty() ? (mime.isEmpty() ? '0' : mime.at(0)) : name.at(0));
colorIndex = (ch.unicode() % 4);
}
ext = document ? ((lastDot < 0 || lastDot + 2 > name.size()) ? name : name.mid(lastDot + 1)) : QString();
return colorIndex;
}
https://github.com/telegramdesktop/tdesktop/blob/5f5770dd46491133b135a71fc2d4f92d13107ade/Telegram/SourceFiles/layout.cpp#L170-L2110
/* сделать логику переводчика из 10 системы в 2, 8 и 16, что бы на вход было десятичное число,
а на выходе двоичное, восьмеричное и шеснадцатиричное представление */
// для проверки, функциями php
$i=378;
echo "$i в двоичной системе = " . base_convert ($i, 10, 2) . PHP_EOL;
echo "$i в восьмеричной системе = " . base_convert ($i, 10, 8) . PHP_EOL;
echo "$i в шестнадцатиричной системе = " . base_convert ($i, 10, 16) . PHP_EOL;
unset ($i);
// десятичное в двоичное, используя алгоритм http://vestikinc.narod.ru/AB/dec_bin_tr.htm
$a = 378;
$b = ''; // пустая строковая переменная
while ($a != 0) {
$b = ($a % 2) . $b; //добавляем в начало остаток от деления, как младший бит двоичного числа
$a = (int)($a / 2); //принимаем целую часть частного за новое делимое
}
echo $b . PHP_EOL;
unset ($a, $b);
// десятичное в восьмеричное, используя алгоритм http://vestikinc.narod.ru/AB/dec_oct_tr.htm
$a = 378;
$b = ''; // пустая строковая переменная
while ($a != 0 & $a % 8 < 8) {
$b = ($a % 8) . $b; //добавляем в начало остаток от деления, как младший бит двоичного числа
$a = (int)($a / 8); //принимаем целую часть частного за новое делимое
}
echo $b . PHP_EOL;
unset ($a, $b);
// десятичное в шестнадцатеричное, через двоичное
$a = 378;
$b = ''; // пустая строковая переменная
while ($a != 0) {
$b = ($a % 2) . $b; //добавляем в начало остаток от деления, как младший бит двоичного числа
$a = (int)($a / 2); //принимаем целую часть частного за новое делимое
}
$count = strlen($b);
while(($count % 4) != 0) { // если количество символов не кратно 4
$b='0'. $b; // то добавляем в начало 0
$count = strlen($b); // снова вычисляем длину
}
$c = ''; // пустая строковая переменная
for($d = 0; $d < $count; $d = $d + 4) //пока счётчик меньше количества символов, прибавляем 4
{
$c = $c . strtr(substr($b, $d,4), //добавляем к $c замену 4-х символов $b с позиции $d
array('0000'=>'0',
'0001'=>'1',
'0010'=>'2',
'0011'=>'3',
'0100'=>'4',
'0101'=>'5',
'0110'=>'6',
'0111'=>'7',
'1000'=>'8',
'1001'=>'9',
'1010'=>'A',
'1011'=>'B',
'1100'=>'C',
'1101'=>'D',
'1110'=>'E',
'1111'=>'F'));
}
echo $c . PHP_EOL;
unset ($a, $b, $c, $d);
// десятичное в шестнадцатеричное, используя алгоритм http://vestikinc.narod.ru/AB/dec_hex_tr.htm
$a = 378;
$b = ''; // пустая строковая переменная
while ($a != 0) {
if ($a % 16 > 0 & $a % 16 < 10):
$b = ($a % 16) . $b;
elseif ($a % 16 == 10):
$b = 'A' . $b;
elseif ($a % 16 == 11):
$b = 'B' . $b;
elseif ($a % 16 == 12):
$b = 'C' . $b;
elseif ($a % 16 == 13):
$b = 'D' . $b;
elseif ($a % 16 == 14):
$b = 'E' . $b;
elseif ($a % 16 == 15):
$b = 'F' . $b;
endif;
$a = (int)($a / 16); //принимаем целую часть частного за новое делимое
}
echo $b . PHP_EOL;
логика переводчика из 10 системы исчисления в 2, 8 и 16, чтобы на входе было десятичное число, а на выходе двоичное, восьмеричное и шеснадцатиричное представление
прошу сильно гавном не бросать - на старости лет, впервые в жизни учу программирование, месяц всего-то как заглянул за экран
+2
class StreamRailBase:
__metaclass__ = ABCMeta
def __init__(self): pass
# @abstractmethod
# def create_connection(self): pass
#
# @abstractmethod
# def send_to_sr(self, method, path, params=None): pass
# @abstractmethod
# def get_advertisers(self): pass
#
# @abstractmethod
# def get_targeting_conditions(self, env, geos, os, size, white_list, black_list): pass
#
# @abstractmethod
# def create_ad_source(self, name, price, partner, tag_url, env, geos, os, size, req_cap, imp_cap, white_list=None, black_list=None): pass
#
# @abstractmethod
# def create_sr_tag(self, tag_instance): pass
#
# @abstractmethod
# def create_domain_list(self, f, list_type, adsource_name): pass
#
# @abstractmethod
# def activate_adsource(self, adsource_id): pass
#
# @abstractmethod
# def deactivate_adsource(self, adsource_id): pass
#
# @abstractmethod
# def set_caps(self, params, new_req_cap, new_imp_cap): pass
#
# @abstractmethod
# def set_geos(self, params, new_geos): pass
#
# @abstractmethod
# def edit_domain_list(self, f, list_id): pass
#
# @abstractmethod
# def set_list(self, params, new_list, list_type): pass
#
# @abstractmethod
# def set_size(self, params, size): pass
#
# @abstractmethod
# def edit_adsource(self, tag_instance, form_data): pass
#
# @abstractmethod
# def create_new_partner(self, name): pass
#
# @abstractmethod
# def sync_tag(self, tag_instance): pass
#
# @abstractmethod
# def add_new_tag_to_template(self, tag_name, price, tag_id, adv_id): pass
В человеке умер рахитектор, и в отчаянии, он закомитил эту хуйню в мастер.