- 1
- 2
#define FOR_INCLUSION (iostream) (studio.h) (stdlib.h) (boost/phoenix.hpp) (my_drugs_library.h)
#include <include_and_disable_some_warnings>
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+8
#define FOR_INCLUSION (iostream) (studio.h) (stdlib.h) (boost/phoenix.hpp) (my_drugs_library.h)
#include <include_and_disable_some_warnings>
+96
var m = map[int]string { 1: "one", 2: "two", 3: "three", }
if val, ok := m[3]; ok { fmt.Printf("Yes! %s\n",val) } else { fmt.Println("No!") }
Почему в Go первое присваивание надо писать через =
А то что в if через :=
http://ideone.com/cPf2cw
http://ideone.com/fork/cPf2cw
+150
<?php
$subjects = array (
0 =>
array (
'title' => 'ОС Unix',
'teacher' => 'Вася',
'mark' => '3'),
1 =>
array (
'title' => 'Компьютерные сети',
'teacher' => 'Петя',
'mark' =>'4'),
2 =>
array (
'title' => 'Алгоритмы',
'teacher' => 'Коля',
'mark' => '4'),
);?>
<table>
<? foreach ($subjects as $key=>$subject) :
$number = $key+1;
?>
<tr>
<td><?echo $number;?></td>
<td><?echo $subject['title'];?></td>
<td><?echo $subject['teacher'];?></td>
<td><?echo $subject['mark'];?></td>
</tr>
<? endforeach; ?>
</table>
<? var_dump($subject)?>
+73
int a = 1;
int b = 2;
int c = 2;
String d = " ";
System.out.print(a+d);
System.out.print(b+d);
System.out.print(b+a+d);
System.out.print(4+d);
System.out.print(5+d);
System.out.print(6+d);
System.out.print(7+d);
System.out.print(8+d);
System.out.print(9+d);
System.out.println(10+d);
System.out.print(2+d);
System.out.print(4+d);
System.out.print(6+d);
System.out.print(8+d);
System.out.print(10+d);
System.out.print(12+d);
System.out.print(14+d);
System.out.print(16+d);
System.out.print(18+d);
System.out.println(20+d);
System.out.print(3+d);
System.out.print(6+d);
System.out.print(9+d);
System.out.print(12+d);
System.out.print(15+d);
System.out.print(18+d);
System.out.print(21+d);
System.out.print(24+d);
System.out.print(27+d);
System.out.println(30+d);
System.out.print(4+d);
System.out.print(8+d);
System.out.print(12+d);
System.out.print(16+d);
System.out.print(20+d);
System.out.print(24+d);
System.out.print(28+d);
System.out.print(32+d);
System.out.print(36+d);
System.out.println(40+d);
System.out.print(5+d);
System.out.print(10+d);
System.out.print(15+d);
System.out.print(20+d);
System.out.print(25);
System.out.print(30+d);
System.out.print(35+d);
System.out.print(40+d);
System.out.print(45+d);
System.out.println(50+d);
System.out.print(6+d);
System.out.print(12+d);
System.out.print(18+d);
System.out.print(24+d);
System.out.print(30+d);
System.out.print(36+d);
System.out.print(42+d);
System.out.print(48+d);
System.out.print(54+d);
System.out.println(60+d);
System.out.print(7+d);
System.out.print(14+d);
System.out.print(21+d);
System.out.print(28+d);
System.out.print(35+d);
System.out.print(42+d);
System.out.print(49+d);
System.out.print(56+d);
System.out.print(63+d);
System.out.println(70+d);
System.out.print(8+d);
System.out.print(16+d);
System.out.print(24+d);
System.out.print(32+d);
System.out.print(40+d);
System.out.print(48+d);
System.out.print(56+d);
System.out.print(64+d);
System.out.print(72+d);
System.out.println(80+d);
System.out.print(9+d);
System.out.print(18+d);
System.out.print(27+d);
System.out.print(36+d);
System.out.print(45+d);
System.out.print(54+d);
System.out.print(63+d);
System.out.print(72+d);
System.out.print(81+d);
System.out.println(90+d);
System.out.print(10+d);
System.out.print(20+d);
System.out.print(30+d);
System.out.print(40+d);
System.out.print(50+d);
System.out.print(60+d);
Пытался таблицу умножения сделать в детстве...
+157
if (strlen($arResult["ERROR_MESSAGE"]) <= 0){
// любая ахинея
}
2014 год. Битрикс все так же терпеливо ожидает патент на строки отрицательной длины.
Полагаю, такой икспрешн используется не только в компоненте корзины, учитывая страсть авторов к копипасте.
+154
if ($_SERVER["REQUEST_METHOD"] == "POST" && strlen($_REQUEST["backButton"]) > 0 && ($arParams["DELIVERY_NO_SESSION"] == "N" || check_bitrix_sessid()))
{
if($arResult["POST"]["CurrentStep"] == 6 && $arResult["SKIP_FORTH_STEP"] == "Y")
$arResult["CurrentStepTmp"] = 3;
if($arResult["POST"]["CurrentStepTmp"] <= 5 && $arResult["SKIP_THIRD_STEP"] == "Y")
$arResult["CurrentStepTmp"] = 2;
if($arResult["POST"]["CurrentStepTmp"] <= 3 && $arResult["SKIP_SECOND_STEP"] == "Y")
$arResult["CurrentStepTmp"] = 1;
if(IntVal($arResult["CurrentStepTmp"])>0)
$arResult["CurrentStep"] = $arResult["CurrentStepTmp"];
else
$arResult["CurrentStep"] = $arResult["CurrentStep"] - 2;
$arResult["BACK"] = "Y";
}
if ($arResult["CurrentStep"] <= 0)
$arResult["CurrentStep"] = 1;
$arResult["ERROR_MESSAGE"] = "";
Компонент страницы заказа в магазине Битрикса, 14я версия.
Тут вам и отсутствие констант для осмысленных шагов, и отсутствие конфигурирования этих шагов, как они i18n-ятся, вообще не представляю.
КАК ЭТО ВСЁ РАБОТАЕТ??!!!
ЗЫ мало того, тут же в компонент вкопипащен (или переговнокоден заново, не сравнивал) процесс залогинивания/регистрации нового юзера, елси он не залогинен. Не смог перекопипастить эту копипасту лишь потому, что она содержит 310 строк. Неслабый DRY.
+72
public class PLock {
private Map<Thread, Integer> readLocks = new HashMap<Thread, Integer>();
private Thread writeLock = null;
private int writeLockCount = 0;
public synchronized void getReadLock() {
Thread currentThread = Thread.currentThread();
long startTimeMillis = System.currentTimeMillis();
boolean gotStuck = false;
while (canClaimReadLock(currentThread) == false) {
gotStuck = true;
try {
wait();
} catch (InterruptedException ex) {
Log.warn("Interrupted while attempting to get read lock.", ex);
}
}
report(gotStuck, startTimeMillis, "read");
if (readLocks.containsKey(currentThread)) {
readLocks.put(currentThread, 1 + readLocks.get(currentThread));
} else {
readLocks.put(currentThread, 1);
}
}
...
public synchronized void relinquishReadLock() {
Thread currentThread = Thread.currentThread();
if (readLocks.containsKey(currentThread) == false) {
throw new RuntimeException("Cannot relinquish read lock on thread " + currentThread + " because it does not hold a lock.");
}
int newLockCount = readLocks.get(currentThread) - 1;
if (newLockCount == 0) {
readLocks.remove(currentThread);
notifyAll(); // IMPORTANT: allow other threads to wake up and check if they can get locks now.
} else {
readLocks.put(currentThread, newLockCount);
}
}
public synchronized void getWriteLock() {
//Log.warn("getWriteLock() in thread " + Thread.currentThread());
//dumpLocks();
Thread currentThread = Thread.currentThread();
long startTimeMillis = System.currentTimeMillis();
boolean gotStuck = false;
while (canClaimWriteLock(currentThread) == false) {
gotStuck = true;
try {
wait();
} catch (InterruptedException ex) {
Log.warn("Interrupted while attempting to get write lock.", ex);
}
}
report(gotStuck, startTimeMillis, "write");
writeLock = currentThread;
writeLockCount++;
}
...
public synchronized void relinquishWriteLock() {
//Log.warn("relinquishWriteLock() in thread " + Thread.currentThread());
Thread currentThread = Thread.currentThread();
if (writeLock != currentThread) {
throw new RuntimeException("Cannot relinquish write lock on thread " + currentThread + " because it does not hold the lock.");
}
if (writeLockCount <= 0) {
throw new RuntimeException("Tried to relinquish write lock on thread " + currentThread + " while write lock count is " + writeLockCount);
}
writeLockCount--;
if (writeLockCount == 0) {
writeLock = null;
notifyAll(); // IMPORTANT: allow other threads to wake up and check if they can get locks now.
}
}
...
}
А у вас уже есть свой теплый ламповый ReentrantReadWriteLock?
Нет? Тогда https://github.com/orph/jujitsu/blob/master/src/e/ptextarea/PLock.java идет к вам...
+131
Шесть месяцев назад я нашёл в Интернете книжку "Dive into Python". Странная книжка, толстая,
да ещё на не русском языке.
Усердно прочитал её, методично и вдумываясь, но таки ничего и не понял.
Но что-то не отпускало меня - я пошёл на python.org и стал изучать стандартную библиотеку,
старательно, скурпулёзно, от корки до корки. Гугля примеры кода, я наткнулся на пост в блоге одного гуру,
где было написано про PEP8.
То, что рассказывал этот умудрённый опытом кодер, настолько впечатлило меня, что я словно в припадке
безумия бросился зубрить эту конвенцию по написанию питоньего кода.
У меня тряслись руки, по телу прокатывали волны возбуждения, я, можно сказать, бился в экстазе всё
это время - и теперь могу процитировать наизусть любой пункт, даже если меня разбудить посреди
глубокой ночи.
Новые знания окрыляли меня, я бросился писать (что бы вы подумали?) очередную имиджборду.
Я не писал раньше имиджборд, эта была моей первой. По пути пришлось освоить азы вёрстки на html и css,
но там всё оказалось совсем не сложно.
Я плавно двигался вперёд, наращивая функционал. И знаете что? Я упёрся в недостаток
производительности. Ну, так мне показалось. Я делал замеры, устранял места с тяжёлым кодом.
Тысячи раз запускал ab, но так и не сумел перейти порог в 300 запросов в секунду.
Я как-то ожидал большего и был немного разочарован.
Гугл, снова гугл. Десятки статей и тем на форуме… Довольно быстро я заметил, что люди часто пишут про
какие-то "асинхронные веб-сервера". Часто встречались названия Tornado и Gevent. Я прочитал про них
подробнее - и был просто ошеломлён. Как мне это раньше не приходило в голову?!
Это же, это просто гениально, чёрт меня побери!
Исходники в ведро, всё переписать! Меня переполняло новое знание, поток мыслей ровно ложился в
строчки кода. Я просто не мог остановиться. Чашка кофе… Ещё чашка…
Мой небольшой кусочек софта приобретал кристалльную чистоту,
я смертельно устал, но продолжал в умилении полировать его зудящими руками, нанося последние штрихи
Пять тысяч. Я получил производительность в пять тысяч запросов в секунду. В ту ночь я так и не смог заснуть.
Наиувлекательнейший мир хай-лоада открылся передо мной. Позже я изучил ещё много классных вещей
типа сверхбыстрых асинхронных key-value-хранилищ, или, например, такого необычного подхода к
обработке данных, как map-reduce.
Это уже был другой я, новый, обновлённый. С незашоренным взглядом, с жаждой новых знаний и
незнакомых концепций.
Я летел вперёд, оставляя за спиной ступень за ступенью.
За пол-года я сменил несколько мест работы, и моя зарплата взлетела до умопомрачительных сумм.
Сотни замечательных мест открыли передо мной свои двери. Любые, самые изысканные девушки
проявляли просто чудеса изобретательности, чтобы находиться рядом со мной.
А ещё, я никогда не забуду тот момент, когда на одной из конференций я впервые в жизни поймал на
себе завистливый взгляд.
Это был взгляд какого-то сливающегося с толпой неудачника, взгляд преисполненный ненависти,
презрения и желчного вожделения, направленного на мой Олимп. Наверное, он всю свою никчёмную
жизнь писал на каком-нибудь си-шарпе или там на джаве, проводя долгие дни в одиночестве.
И теперь начинал подсознательно догадываться, что долгие годы безуспешно пытался
построить замок из навоза.
+158
// weclome to main-menu-hover.js
function load(){
var url = window.location;
var m1 = document.getElementById("m1");
var m2 = document.getElementById("m2");
var m3 = document.getElementById("m3");
var m4 = document.getElementById("m4");
//var m5 = document.getElementById("m5");
var mm1 = document.getElementById("mm1");
var mm2 = document.getElementById("mm2");
var mm3 = document.getElementById("mm3");
var mm4 = document.getElementById("mm4");
var mm5 = document.getElementById("mm5");
var mm6 = document.getElementById("mm6");
var mm7 = document.getElementById("mm7");
var mm8 = document.getElementById("mm8");
if (m1.href == url){
m1.style.color = "#ffc12b";
//m1.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/menu-h-bg1.png)no-repeat top center";
m1.style.textDecoration = "none";
}
if (m2.href == url){
m2.style.color = "#ffc12b";
m2.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/menu-h-bg1.png)no-repeat center center";
m2.style.textDecoration = "none";
}
if (m3.href == url){
m3.style.color = "#ffc12b";
m3.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/menu-h-bg1.png)no-repeat center center";
m3.style.textDecoration = "none";
}
if (m4.href == url){
m4.style.color = "#ffc12b";
m4.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/menu-h-bg1.png)no-repeat center center";
m4.style.textDecoration = "none";
}
if (m5.href == url || url.href.indexOf(m5.href)!=-1){
m5.style.color = "#ffc12b";
m5.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/menu-h-bg2.png)no-repeat center center";
m5.style.textDecoration = "none";
}
if (url.href.indexOf(mm1.href)!=-1){
mm1.style.color = "#741f0c";
mm1.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/bg-min-menu-h.png)no-repeat center center";
m3.style.color = "#ffc12b";
m3.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/menu-h-bg1.png)no-repeat center center";
m3.style.textDecoration = "none";
}
if (url.href.indexOf(mm2.href)!=-1){
mm2.style.color = "#741f0c";
mm2.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/bg-min-menu-h.png)no-repeat center center";
m3.style.color = "#ffc12b";
m3.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/menu-h-bg1.png)no-repeat center center";
m3.style.textDecoration = "none";
}
if (url.href.indexOf(mm3.href)!=-1){
mm3.style.color = "#741f0c";
mm3.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/bg-min-menu-h.png)no-repeat center center";
m3.style.color = "#ffc12b";
m3.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/menu-h-bg1.png)no-repeat center center";
m3.style.textDecoration = "none";
}
if (url.href.indexOf(mm4.href)!=-1){
mm4.style.color = "#741f0c";
mm4.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/bg-min-menu-h.png)no-repeat center center";
m3.style.color = "#ffc12b";
m3.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/menu-h-bg1.png)no-repeat center center";
m3.style.textDecoration = "none";
}
if (url.href.indexOf(mm5.href)!=-1){
mm5.style.color = "#741f0c";
mm5.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/bg-min-menu-h.png)no-repeat center center";
m3.style.color = "#ffc12b";
m3.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/menu-h-bg1.png)no-repeat center center";
m3.style.textDecoration = "none";
}
if (url.href.indexOf(mm6.href)!=-1){
mm6.style.color = "#741f0c";
mm6.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/bg-min-menu-h.png)no-repeat center center";
m3.style.color = "#ffc12b";
m3.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/menu-h-bg1.png)no-repeat center center";
m3.style.textDecoration = "none";
}
if (url.href.indexOf(mm7.href)!=-1){
mm7.style.color = "#741f0c";
mm7.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/bg-min-menu-h.png)no-repeat center center";
m3.style.color = "#ffc12b";
m3.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/menu-h-bg1.png)no-repeat center center";
m3.style.textDecoration = "none";
}
if (url.href.indexOf(mm8.href)!=-1){
mm8.style.color = "#741f0c";
mm8.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/bg-min-menu-h.png)no-repeat center center";
m3.style.color = "#ffc12b";
m3.style.background = "url(%absolute_url_path%/wp-content/themes/%pattern%/images/menu-h-bg1.png)no-repeat center center";
m3.style.textDecoration = "none";
}
}
Пришел проект на поддержку... Сразу отказался=)
Естественно вкрапления %_some_text_% от меня.
Файл назывался main-menu-hover.js
+161
var percent = 0;
setInterval(function() {
if(percent < 100) {
percent += 10;
showprogress(percent);
}
}, 50);
Прогресс-бар асинхронной загрузки картинки