- 1
- 2
- 3
- 4
$result_max = mysql_query("SELECT MAX(id)+1 as max FROM cms_competition;");
$row_max = mysql_fetch_object($result_max);
if(!$row_max->max)
$row_max->max = 1;
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+158
$result_max = mysql_query("SELECT MAX(id)+1 as max FROM cms_competition;");
$row_max = mysql_fetch_object($result_max);
if(!$row_max->max)
$row_max->max = 1;
Так ведь проще
+165
/* Здесь мы имеем сраный унаследованный пиздец: количество товара передается в параметрах POST-запроса,
имеющих имена вида productX_count, где X - ИД товара. Как предыдущие разработчики разобирали это счастье?
Правильно, перебирали все (блядь, ВСЕ, блядь, 20000 штук!) товары и проверяли, есть ли соответствующее
значение в запросе.
*/
$items5 = GetIBlockElementList(5);
while($arItem = $items5->GetNext())
if(isset($_POST['product'.$arItem['ID']."_id"]) && is_numeric($_POST['product'.$arItem['ID']."_id"]))
{
$_PRODUCTS[$arItem['ID']]['count'] = $_POST['product'.$arItem['ID']."_count"];
}
В этом коде меня утешает только боль и ненависть комментария.
−94
import time
def inttime():
return int(''.join(str(time.time()).split('.')))
def rand():
while True:
s = bin(inttime())[2:]
for x in s:
yield x
Этим "рандомом" заполняется клеточный автомат "Жизнь". Нечего было делать.
+157
var allowed = [ 0xfe, 0xfc, 0xf8, 0xf0,
0xe0, 0xc0, 0x80, 0x00 ];
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
// ...
if ($.grep(allowed, function(a) { return part == a; }).length > 0) {
max = 0x00;
} else {
FocusObject(object);
show_alert( jstextTemplate("<jstext>field_contains_bad_IP_mask</jstext>", {name: name}) );
return false;
}
}
Кусочек валидации для маски подсети. Мы не ищем лёгких путей.
+137
using System;
using System.Collections.Generic;
namespace Builder
{
public class MainApp
{
public static void Main()
{
// Create director and builders
Director director = new Director();
Builder b1 = new ConcreteBuilder1();
Builder b2 = new ConcreteBuilder2();
// Construct two products
director.Construct(b1);
Product p1 = b1.GetResult();
p1.Show();
director.Construct(b2);
Product p2 = b2.GetResult();
p2.Show();
// Wait for user
Console.Read();
}
}
// "Director"
class Director
{
// Builder uses a complex series of steps
public void Construct(Builder builder)
{
builder.BuildPartA();
builder.BuildPartB();
}
}
// "Builder"
abstract class Builder
{
public virtual void BuildPartA(){}
public virtual void BuildPartB(){}
public virtual Product GetResult(){}
}
// "ConcreteBuilder1"
class ConcreteBuilder1 : Builder
{
private readonly Product product = new Product();
public override void BuildPartA()
{
product.Add("PartA");
}
public override void BuildPartB()
{
product.Add("PartB");
}
public override Product GetResult()
{
return product;
}
}
// "ConcreteBuilder2"
class ConcreteBuilder2 : Builder
{
private readonly Product product = new Product();
public override void BuildPartA()
{
product.Add("PartX");
}
public override void BuildPartB()
{
product.Add("PartY");
}
public override Product GetResult()
{
return product;
}
}
// "Product"
class Product
{
private readonly List<string> parts = new List<string>();
public void Add(string part)
{
parts.Add(part);
}
public void Show()
{
Console.WriteLine("\nProduct Parts -------");
foreach (string part in parts)
Console.WriteLine(part);
}
}
}
"Хороший","годный" пример паттерна билдер с википедии, не соответствующие лежащей там же Uml схеме чуть больше чем полностью
Схема
http://upload.wikimedia.org/wikipedia/ru/2/28/Builder.gif
+129
string fileName = Path.GetFileName(f);
string fileExt = Path.GetExtension(f);
string i=fileName.IndexOf(fileExt);
if (i > -1) fileName = fileName.Remove(i, fileExt.Length);
Получение имени файла
+157
function currSnowCalcPrice(type, square, height){
var price = false;
switch (type) {
//скатная крыша
case 1:
switch (true) {
case square < 125:
price = 'min';
break
//0 - 20см
case height < 20:
switch (true) {
case square < 500:
price = 39;
break
case square < 1000:
price = 34;
break
case square < 2000:
price = 32;
break
default:
price = 0;
}
break
//20 - 30 см
case height < 30:
switch (true) {
case square < 500:
price = 44;
break
default:
price = 39;
}
break
default:
price = 0;
}
break
case 2:
switch (true) {
case square < 250:
price = 'min';
break
//0 - 14см
case height < 14:
switch (true) {
case square < 500:
price = 21.5;
break
case square < 4500:
price = 19.5;
break
case square < 9500:
price = 17.5;
break
case square < 15000:
price = 15.5;
break
default:
price = 0;
}
break
//14 - 30 см
case height < 30:
switch (true) {
case square < 500:
price = 23.5;
break
case square < 4500:
price = 21.5;
break
case square < 9500:
price = 19.5;
break
case square < 15000:
price = 17.5;
break
default:
price = 0;
}
break
default:
price = 0;
}
break
default:
price = false;
}
return price;
}
Функция возвращает цену за уборку одного метра квадратного поверхности. Есть минимальное количество когда будет возвращено значение min. false или 0 в случае не существующего типа поверхности или значений площади или глубины вне загаданного диапазона.
+159
var a, vr, curq;
function bgbuild(num1){document.write("<head><title>Річне тематичне оцінювання з астрономії</title><meta http-equiv=\"Content-Type\" content=\"text/html\" charset=unicode\"></head><body bgcolor=#8080ff><img src='library/bgrnd.jpg' height=100% width=100% style='z-index:",num1,";position:absolute;top:0;left:0;right:0;bottom:0'>")};
function fio(){document.write("<form><input type=\"text\" name=\"pib\" style='z-index:4;position:relative;top:0;left:0;font:normal 15px Lucida Console;'>")};
function capt(qustn){document.write("<div style='z-index:3;text-align:justify;position:absolute;top:30;left:30;font:normal 30px System;color:black'>",qustn,"</div>")};
function fld(){document.write("<textarea name=answ rows=30 cols=90 style='z-index:4;position:absolute;top:160;left:30;font:normal 15px Lucida Console;'></textarea>")};
function kg(qst){document.write("<input style=\"z-index:6;position:absolute;top:0;right:0\" type=\"button\" value=\"Наступне питання\" onclick=\"return q",qst,"()\">")};
function registr(){document.write("<input type=\"button\" onclick=\"return crfol()\" value=\"Реєстрація\"></form>")};
function cnctscr(){document.write("<script lang=\"Javascript\" src=\"library/cobuild.js\"></script>");};
function svr(vr){var fs, b;
fs = new ActiveXObject("Scripting.FileSystemObject");
b = fs.OpenTextFile("C:\\variant.tmp", 2, true, true);
b.write(vr);
b.close();
};
function gvr(){var fs, b;
fs = new ActiveXObject("Scripting.FileSystemObject");
b = fs.OpenTextFile("C:\\variant.tmp", 1, true, true);
vr = b.readall();
b.close();
};
function start(){
bgbuild(0);
document.write("<div style='z-index:1;position:absolute;top:30;left:30;right:30;font:normal 25px System;color:black;text-align:justify'>Ви маєте можливість пройти річне тематичне оцінювання з астрономії. Буде запропоновано 6 варіантів по 15 питань різної складності кожний. Ваші відповіді перевіряє вчитель, але приблизно оцінити себе Ви можете самі, ознайомившись після проходження опитування із правильною відповіддю і оцінивши вірність своєї відповіді. Не намагайтесь втрутитись у хід опитування і підкорегувати свої відповіді, адже це може скінчитися порушенням ходу програми, яке призведе до її неповного проходження, а в результаті - нижчої оцінки. Файл із Вашою відповіддю збережеться у спеціальному місці.<br>Для початку введіть своє прізвище та ім'я (не використовуйте ніяких спецсимволів!):<br>");
fio();
registr();
document.write("<br>Оберіть варіант:<br><table><tr><td><form><input type='button' value='1' onclick='svr(1);return q1()'></td><td><input type='button' onclick='svr(2);return q1()' value='2'></td><td><input type='button' onclick='svr(3);return q1()' value='3'></td><td><input type='button' onclick='svr(4);return q1()' value='4'></td><td><input type='button' onclick='svr(5);return q1()' value='5'></td><td><input type='button' onclick='svr(6);return q1()' value='6'></td></form></div>");};
function crfol(){var fs, n, b;
fs = new ActiveXObject("Scripting.FileSystemObject");
n = document.all.pib.value;
if(n==""){er()};
nm = "answ/"+n+".dat";
a = fs.OpenTextFile(nm, 2, true, true);
a.writeline("Це не підробка, це справжній файл із відповідями!\rУчень: "+n+"\rВаріант: ");
a.close();
b = fs.OpenTextFile("C:\\username.tmp", 2, true, true);
b.write(n);
b.close();
}
function crf(dt){var fs, n, b, nm;
fs = new ActiveXObject("Scripting.FileSystemObject");
b = fs.OpenTextFile("C:\\username.tmp", 1, true, true);
n = b.readall();
b.close();
nm = "answ/"+n+".dat";
a = fs.OpenTextFile(nm, 8, true, true);
a.writeline(dt);
a.close();
}
function er(){alert("Ану не балуйся! Думаєш, ти розумніше за комп'ютер?!");window.close();}
function q1(){
try{
gvr();
crf(vr);
bgbuild(0);
cnctscr();
};catch(e){er()};
if (vr=="1"){curq = "1.1.1. Що вивчає астрономія?"};
if (vr=="2"){curq = "1.1.2. Що означає слово \"астрономія\"?"};
if (vr=="3"){curq = "1.1.9. Що таке астрологія?"};
if (vr=="4"){curq = "1.1.12. Назвіть прізвища відомих вам астрономів минулих часів."};
if (vr=="5"){curq = "1.1.13. Назвіть небесні тіла, що утворюють Сонячну систему."};
if (vr=="6"){curq = "2.1.1. Що означає слово \"космос\"?"};
capt(curq);
crf(curq);
fld();
kg(2);
}
start();
Короче, первый мой более-менее крупный высер на JS. Писал HTA-приложение для школы (тестирование по астрономии). Интернета у меня тогда ещё не было, компилятор чего-либо нормального взять, соответственно, было негде, поэтому писал на чём можно. JS (точнее, JScript) изучал по справке MSE7 (недо-IDE, которая поставляется с M$Office). Результат немного предсказуем, многие части кода - модифицированные примеры тамошние. Вбрасываю основную либу (там ещё дополнительная, с вхардкоженными вопросами и несколькими функциями, и HTA-оболочка). Остальное будет по просьбам:3
//Я в этот код даже не заглядываю, боюсь суицидальных приступов от осознания того, что я это написал *HEADBANG*
+119
Well, there were other factors in play there. htmlspecialchars was a
very early function. Back when PHP had less than 100 functions and the
function hashing mechanism was strlen(). In order to get a nice hash
distribution of function names across the various function name lengths
names were picked specifically to make them fit into a specific length
bucket. This was circa late 1994 when PHP was a tool just for my own
personal use and I wasn't too worried about not being able to remember
the few function names.
-Rasmus
http://news.php.net/php.internals/70691
+78
private int compareDates(java.sql.Date date1, java.sql.Date date2) {
if (date1.getYear() < date2.getYear())
return 1;
if (date1.getYear() > date2.getYear())
return -1;
if (date1.getMonth() < date2.getMonth())
return 1;
if (date1.getMonth() > date2.getMonth())
return -1;
if (date1.getDate() < date2.getDate())
return 1;
if (date1.getDate() > date2.getDate())
return -1;
return 0;
}
Сравнение двух дат