- 1
- 2
def removeDuplicate(store):
return [x for x in store if x not in locals()['_[1]']]
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−90
def removeDuplicate(store):
return [x for x in store if x not in locals()['_[1]']]
Удаление дубликатов в списке, set(store) религия не позволила сделать:)
+166
<!--CAPCHA-->
<?php
$input = array ("0283", "0830", "1541", "3510", "7269", "0110", "2500", "4998", "7203", "9480",
"1540", "1581", "1891", "0064", "0128", "0256", "0512", "1024", "2048", "4096");
$rand_keys = array_rand($input);
$img = $input[$rand_keys];
$_SESSION['img'] = $img;
print ("<img src=\"/images/$img.gif\">");
?>
<!--CAPHA answer-->
понятно и без слов ;)
+176
<a id="hide" href ="javascript:
var text = $('#ccc').html();
function hide(){
$('#ccc').html('');
$('#hide').attr('href', 'javascript: show(); ');
}
function show(){
$('#ccc').html(text);
$('#hide').attr('href', 'javascript: hide(); ');
}
hide();
">Скрыть/Показать</a>
<div id="ccc">скрываемвый текст</div>
Я думаю комментарии излишни. Я считаю что это идеальный говнокод. И отличная замена $('#ccc').toggle();
−182
HOME_DIR = "/home/user"
LAST_DIR = HOME_DIR + "/.habralast"
HTML_DIR = HOME_DIR + "/.habr.html"
SHOW_FIRST_TIME = 5
n = 1
new_addr = 0
count = 0
if os.path.isfile(LAST_DIR):
fp = open(LAST_DIR, "r")
topic1 = fp.readline()
fp.close()
last_existed = 1
else:
fp = open(LAST_DIR, "w")
topic1 = ""
fp.close()
last_existed = 0
while(1):
if n == 1:
url = "habrahabr.ru"
else: url = "habrahabr.ru/page" + str(n) + "/"
wget = "wget " + url + " -O " + HTML_DIR
try:
os.system(wget)
except:
print "Cannot connect to server"
sys.exit()
index = open(HTML_DIR, "r")
s = ' <a href="http://habrahabr.ru/'
ss = ' <a'
sss = ' <div class="published"><!-- Дата в формате ISO пихается в title -->'
for i in range(2000):
line = index.readline()
if s in line:
blog_s = line.find('">')
blog_e = line.find("</a>")
blog = line[blog_s+2:blog_e]
for j in range(50):
line = index.readline()
if ss in line:
topic_s = line.find('">')
topic_e = line.find("</a>")
topic = line[topic_s+2:topic_e]
if topic.find("</span>") != -1:
topic = topic[topic.find("</span>")+7:]
if topic != topic1:
if new_addr == 0:
fp = open(LAST_DIR, "w")
fp.write(topic)
fp.close()
new_addr = 1
print "Blog:\t" + blog
print "Topic:\t" + topic
for k in range(100):
line = index.readline()
if sss in line:
line = index.readline()
time_s = line.find("<span>")
time_e = line.find("</span>")
date = line[time_s+6:time_e]
print "Date:\t" + date + "\n"
notify = "notify-send 'Habrahabr.ru: " + blog + "' '" + topic + "\n<i>" + date + "</i>'"
os.system(notify)
count += 1
if count == SHOW_FIRST_TIME and last_existed == 0:
os.system("rm -f " + HTML_DIR)
sys.exit()
break
break
else:
os.system("rm -f " + HTML_DIR)
sys.exit()
n += 1
index.close()
http://habrahabr.ru/blogs/python/127806/
Мне нравится, когда программа/код полностью своя… понимаешь назначение каждой буквы и почему решение именно такое. В данном топике хочу предложить свой парсер топиков Хабрахабра на Python без сторонних библиотек.
При появлении нового топика — всплывающее окошко сообщает об этом.
+136
/* My favorite names for boolean values */
#define No 0
#define Yes 1
#define Maybe 2 /* tri-state boolean, actually */
Исходный код юниксовой утилиты top. Файл boolean.h.
+161
class CmyBuffaer{};
template< typename TYPE > CmyBuffaer& operator,( CmyBuffaer& buffer, typename TYPE arg);
template<> CmyBuffaer& operator,<double>( CmyBuffaer& buffer, double arg)
{
printf("%f",arg);
return buffer;
}
template<> CmyBuffaer& operator,<const char*>( CmyBuffaer& buffer, const char* arg)
{
printf("%s",arg);
return buffer;
}
template<> CmyBuffaer& operator,<int>( CmyBuffaer& buffer, int arg)
{
printf("%i",arg);
return buffer;
}
//...
CmyBuffaer(),34.5,"+",54,"+\n";
+167
return parse(
str,
( ( lexeme_d[+alnum_p][assign_a(key)] >> ':' >> lexeme_d[ '"' >> ( *~ch_p('"') )[insert_at_a(mp,key)] >> '"' ] ) % ',' ),
space_p
).full;
+161
String str=String::Format("a=<^>, b=<^>, c=\"<^>\"")(a)(b, 4)(c); //str будет равно: a=234, b=32422.1231, c="Текст"
str=String::Format(nullptr)(a)("+")(b, 4)("=")(a+b, 4); //str будет равно: 234+32422.1231=32656.1231
str=String::Format("<^><^>")(5); //Выбрасывает исключение, так как переданы не все аргументы
str=String::Format("<^>")(3252)(3.1415926); //Выбрасывает исключение, так как передан лишний аргумент
Форматирование строк с помощью смайликов.
http://www.gamedev.ru/code/forum/?id=148200&page=4#m55
+167
$resultat = mysql_query("SELECT * FROM tovar WHERE t_akcia='1' ");
$myrowat = mysql_fetch_array($resultat);
if (isset($myrowat[t_name])){$rstt=$myrowat[t_name]; if ($rstt==''){unset($rstt);}}
if (isset($rstt)){
$ft=0;
do
{
$t_namet=$myrowat[t_name];
if ($t_namet==''){unset($t_namet);}
if (isset($t_namet)){ $ft=$ft+1; }
}
while ($myrowat = mysql_fetch_array($resultat));
$vidt=rand(1,$ft);
$vidst=$vidt-1;
$resultact = mysql_query("SELECT * FROM tovar WHERE t_akcia='1' LIMIT $vidst,1 ");
$myrowact = mysql_fetch_array($resultact);
print<<<HERE
<div style="margin-top:11px;">
<table width="182" border="0" cellspacing="0" cellpadding="0">
<tr><td height="29" align="center" valign="middle" bgcolor="#fe0000"><div class="tit_block"><a class="tit_block" href="akcia.php">ÀÊÖÈÈ</a></div></td></tr>
<tr><td>
<div style="margin-top:11px; margin-bottom:11px;">
<table width="182" border="0" cellspacing="0" cellpadding="0" style="background-image:url(../img/block_center.jpg); background-position:center; background-repeat:repeat-y;">
<tr>
<td>
<img src="../img/block_top.jpg" align="top" border='0' />
<div style="margin-top:11px; margin-bottom:11px;">
HERE;
if (isset($myrowact[t_name]))
{
$t_namet=$myrowact[t_name];
$t_fotot=$myrowact[t_foto];
$t_pricet=$myrowact[t_price];
$t_old_rpicet=$myrowact[t_old_rpice];
$t_idt=$myrowact[t_id];
$t_valutt=$myrowact[t_valut];
if (isset($t_valutt)){
$resultvt = mysql_query("SELECT * FROM valut WHERE v_id='$t_valutt' ");
$myrowvt = mysql_fetch_array($resultvt);
$valutt=$myrowvt[v_name];
$kurst=$myrowvt[v_kurs];
$v_znakt=$myrowvt[v_znak];
$t_pricet=ceil($t_pricet*$kurst);
$t_old_rpicet=ceil($t_old_rpicet*$kurst);
}
if ($t_namet==''){unset($t_namet);}
if (isset($t_namet))
{
$size_imgt=imagecreatefromjpeg("img_tovar/$t_fotot");
$w_srct = imagesx($size_imgt);
$h_srct = imagesy($size_imgt);
if ($w_srct > $h_srct){$widtht=120; $heightt='';}else{$widtht=''; $heightt=120;}
print<<<HERE
<table width='182' border='0' cellspacing='0' cellpadding='0'>
<tr><td><div class='block_left' style='margin-left:2px; margin-right:2px;'>
<a class='text' style='text-decoration:none;' href='tovar.php?t_id=$t_idt'>
HERE;
if ($heightt > $widtht){echo"<img src='img_tovar/$t_fotot' height='$heightt' hspace='5' vspace='5' align='middle' border='0' />";}
if ($widtht > $heightt){echo"<img src='img_tovar/$t_fotot' width='$widtht' hspace='5' vspace='5' align='middle' border='0' />";}
print<<<HERE
<br><br><strong>$t_namet</strong><br><br>
<div style='text-align:center' class='price' style='margin-top:15px; margin-bottom:15px;'><span class='old_price'>$t_old_rpicet</span>$t_pricet<span class='valut'>ãðí</span></div></a><br>
<a href='buy.php?t_id=$t_idt' title='$t_namet'><img src='../img/kypit.jpg' alt='$t_titlet' border='0' /></a><br>
<div>
</td></tr>
</table>
HERE;
}
}
print<<<HERE
</div>
<img src="../img/block_down.jpg" align="bottom" border='0' />
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</div>
HERE;
}
Хотел накласть только кусочек, но оно всё такое вкусное :)
Показывает 1 рандомный товар
+150
// don't show any errors to end user
error_reporting(0);
// error handler function
function my_error_handler($errno, $errstr, $errfile, $errline) {
$date = date('d/M/Y:H:i:s O');
// \r\n for cozy look on win machines
$error_str = "{$date} | [error] #{$errno}: {$errfile}:{$errline} {$errstr} \r\n";
// *.txt for win machines
error_log($error_str, 3, 'C:\AppServ\www\error_log.txt');
// don't execute php internal error handler
return true;
}
set_error_handler('my_error_handler');
// throws error
echo date();
Рубрика: Советы от Говнокода.
В связи с #7594. Fatal errors не ловит (пхп, хуле), но их и не нужно показывать пользователю, все остальные ошибки пишем в лог на сервер.
Ошибка в логе выглядит так:
21/Aug/2011:16:50:52 +0000 | [error] #2: C:\AppServ\www\4.php:22 date() expects at least 1 parameter, 0 given