- 1
- 2
- 3
- 4
- 5
- 6
- 7
sub removeSpaces {
my $str = $_[0];
while ( $str =~ /[\t ]+/ ) {
$str = $`.$';
}
return $str;
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−121
sub removeSpaces {
my $str = $_[0];
while ( $str =~ /[\t ]+/ ) {
$str = $`.$';
}
return $str;
}
Найдено при разборе скрипта подготовки данных для тестов.
+138
uses crt;
var c1,c2,c3,k,s:integer;
begin
clrscr;
s:=0;
for c1:=1 to 9 do
for c2:=0 to 9 do
for c3:=0 to 9 do
k:=c1*100+c2*10+c3+k;
if (k mod 5 =0) then writeln('LOADING...');
else if (k mod 7 = 0) then writeln('LOADING...');
else s:=s+k;
writeln('Obshie symaя=',s);
readln;
end.
Вот как можно посчитать количество всех трехзначных чисел, которые не делятся на 5 или 7.
+165
<script>
var IllegalChars=new Array("select", "drop", ";", "--", "insert", "delete", "xp_", "update", "/", ":", "char(", "?", "`", "|", "declare", "convert", "cast(", "@@", "varchar", "2D2D", "4040", "00400040", "[", "]");
var IllegalFound=new Array();
var IllegalCharsCount=0;
function ResetCharsCount()
{
IllegalCharsCount=0;
}
function wordFilter(form,fields)
{
ResetCharsCount();
var CheckTextInput;
var fieldErrArr=new Array();
var fieldErrIndex=0;
for(var i=0; i<fields.length; i++)
{
CheckTextInput = document.forms[form].elements[fields[i]].value;
for(var j=0; j<IllegalChars.length; j++)
{
for(var k=0; k<(CheckTextInput.length); k++)
{
if(IllegalChars[j]==CheckTextInput.substring(k,(k+IllegalChars[j].length)).toLowerCase())
{
IllegalFound[IllegalCharsCount]=CheckTextInput.substring(k,(k+IllegalChars[j].length));
IllegalCharsCount++;
fieldErrArr[fieldErrIndex]=i;
fieldErrIndex++;
}
}
}
}
var alert_text="";
for(var k=1; k<=IllegalCharsCount; k++)
{
alert_text+="\n" + "(" + k + ") " + IllegalFound[k-1];
eval('CheckTextInput=document.' + form + '.' + fields[fieldErrArr[0]] + '.select();');
}
if(IllegalCharsCount>0)
{
alert("The form cannot be submitted.\nThe following errors were found:\n_______________________________\n" + alert_text + "\n_______________________________\n");
return false;
}
else
{
return true;
document.forms[form].submit();
}
}
</script>
...
<FORM NAME="FormHome" ACTION="search.asp" METHOD="post" onSubmit="return wordFilter('FormHome',['criteria']);">
http://www.cadw.wales.gov.uk/
Инъекция не пройдет.
+155
insert_image.php:
<?php
require_once('../config.inc.php');
if ((!isset($_SESSION['user_type'])) || ($_SESSION['user_type'] != 0)) {
header('Location: /');
die;
}
require('admin_image.inc.php');
settitle.php:
<?php
require_once('../config.inc.php');
if ((!isset($_SESSION['user_type'])) || ($_SESSION['user_type'] != 0)) {
header('Location: /');
die;
}
$id = intval($_POST['image']);
$title = $_POST['imgtitle'];
mysql_query("UPDATE images SET title='$title' WHERE id=$id");
require('admin_image.inc.php');
upload_image.php:
<?php
require_once('../config.inc.php');
if ((!isset($_SESSION['user_type'])) || ($_SESSION['user_type'] != 0)) {
header('Location: /');
die;
}
if ((isset($_POST['upload'])) && (isset($_FILES['newimage']))) {
$title = (isset($_POST['title'])) ? $_POST['title'] : '';
$file = $_FILES['newimage'];
if ($file['error'] != 0) {
$msg = 'An error occured during uploading file. (Error code:' . $file['error'] . ')';
} else {
$type = $file['type'];
$tmp_name = $file['tmp_name'];
//check if we are uploading image or not
if (!(((preg_match('/\.gif/i', $file['name'])) || (preg_match('/\.jpg/i', $file['name'])) ||
(preg_match('/\.jpeg/i', $file['name'])) || (preg_match('/\.bmp/i', $file['name'])) ||
(preg_match('/\.png/i', $file['name'])))
&& ((preg_match('/gif/i', $file['type'])) || (preg_match('/jpg/i', $file['type'])) ||
(preg_match('/jpeg/i', $file['type'])) || (preg_match('/bmp/i', $file['type'])) ||
(preg_match('/png/i', $file['type']))))) {
$msg = 'You are trying to upload a non-image file.';
} elseif (filesize($tmp_name) <= 0) {
$msg = 'You are trying to upload file which size is 0 bytes.';
} else {
$img_data = fread(fopen($tmp_name, 'r'), filesize($tmp_name));
if (mysql_query("INSERT INTO images (id, image, type, title)"
. " VALUES ('',"
. " '" . mysql_escape_string($img_data) . "',"
. " '" . mysql_escape_string($type) . "',"
. " '" . mysql_escape_string($title) . "')"))
$msg = 'Image uploaded.';
else
$msg = 'An error occured during inserting image in DB.';
}
}
}
if (isset($msg))
$MyPage->assign('msg', $msg);
require('admin_image.inc.php');
Какая экспрессия, какое необычное именование файлов... lower_case_with_underscores + просто текст
А главное какое необычное представление о модульности: 2 файла по 10 строк, и один на 40, в каждом из которых прописана авторизация и которые инклюдят главный файл
+174
(addNewItem) ? (isVideoAudioAttached = true) : (isVideoAudioAttached = false);
addNewItem и isVideoAudioAttached типа bool
−181
from django.db import models
# Класс Студент
class Student(models.Model):
name = models.CharField(max_length=50) # ФИО студента
group = models.CharField(max_length=10) # Группа студента
starosta = models.BooleanField(default=False) # Является ли студент старостой группы?
# Класс Пара
class Pair(models.Model):
name = models.CharField(max_length=30) # Название пары
auditory = models.CharField(max_length=7) # Аудитория
lecturer = models.CharField(max_length=50) # ФИО преподавателя
# Класс День
class Day(models.Model):
pair1 = models.ForeignKey(Pair) # Первая пара
pair2 = models.ForeignKey(Pair) # Вторая пара
pair3 = models.ForeignKey(Pair) # Третья пара
pair4 = models.ForeignKey(Pair) # Четвёртая пара
pair5 = models.ForeignKey(Pair) # Пятая пара
pair6 = models.ForeignKey(Pair) # Шестая пара
pair7 = models.ForeignKey(Pair) # Седьмая пара
# Класс Расписание
class TimeTable(models.Model):
group = models.CharField(max_length=10) # Группа, к которой относится расписание
weekcolor = models.BooleanField() # False, 0 - Красная неделя; True, 1 - Синяя неделя
monday = models.ForeignKey(Day) # Понедельник
tuesday = models.ForeignKey(Day) # Вторник
wednesday = models.ForeignKey(Day) # Среда
thursday = models.ForeignKey(Day) # Четверг
friday = models.ForeignKey(Day) # Пятница
saturday = models.ForeignKey(Day) # Суббота
Очередной шедевр от Magister Yoda
Попытка сделать модель расписания для студентов.
−97
if row[0].find('lk_s_du') > -1 or row[0].find('lk_s_su') > -1:
price = ''
if row[6] == 'incoming_external':
if tariff['ie_price_second'] == 0:
price = row[5] * tariff['ie_price_first'] / 102400
elif ie_global > tariff['ie_price_switch']:
price = row[5] * tariff['ie_price_second'] / 102400
else:
price = overhead(tariff['ie_price_switch']-ie_global,tariff['ie_price_switch'])*tariff['ie_price_first'] / 102400 + hev((row[5]+ie_global-tariff['ie_price_switch']))*tariff['ie_price_second'] / 102400
ie_global += row[5]
unit = 'kb'
if tariff['price_per_unit'] == 1:
price = price /1024
unit = 'mb'
if tariff['price_per_unit'] == 2:
price = price /1024/1024
unit = 'gb'
if tariff['price_per_unit'] == 3:
price = price /1024/1024/1024
unit = 'tb'
if row[6] == 'internal':
if tariff['il_price_second'] == 0:
price = row[5] * tariff['il_price_first'] / 102400
elif il_global > tariff['il_price_switch']:
price = row[5] * tariff['il_price_second'] / 102400
else:
price = overhead(tariff['il_price_switch']-il_global,tariff['il_price_switch'])*tariff['il_price_first'] / 102400 + hev((row[5]+il_global-tariff['il_price_switch']))*tariff['il_price_second'] / 102400
il_global += row[5]
unit = 'kb'
if tariff['price_per_unit'] == 1:
price = price /1024
unit = 'mb'
if tariff['price_per_unit'] == 2:
price = price /1024/1024
unit = 'gb'
if tariff['price_per_unit'] == 3:
price = price /1024/1024/1024
unit = 'tb'
if row[6] == 'outgoing_any':
if tariff['oe_price_second'] == 0:
price = row[5] * tariff['oe_price_first'] / 102400
elif oe_global > tariff['oe_price_switch']:
price = row[5] * tariff['oe_price_second'] / 102400
else:
price = overhead(tariff['oe_price_switch']-oe_global,tariff['oe_price_switch'])*tariff['oe_price_first'] / 102400 + hev((row[5]+oe_global-tariff['oe_price_switch']))*tariff['oe_price_second'] / 102400
oe_global += row[5]
unit = 'kb'
if tariff['price_per_unit'] == 1:
price = price /1024
unit = 'mb'
if tariff['price_per_unit'] == 2:
price = price /1024/1024
unit = 'gb'
if tariff['price_per_unit'] == 3:
price = price /1024/1024/1024
unit = 'tb'
price = str(price).replace('.',',')
Черная магия непосредственно тарификации интернет-трафика.
−83
for row in rows:
service = row[0].split('_')
if row[0].find('lk_s_du') > -1:
loki_cursor.execute("""select tariff_id from inet_inetsessionlog where id = %s;""", (service[-1],))
tariff_id = str(loki_cursor.fetchall()[0][0])
else:
if row[1] == 'inet_dynamic_ip':
cursor.execute('select tariff_plan from inet_dynamic_ip_services where id = %s', (service[-1],))
tariff = str(cursor.fetchall()[0][0])
elif row[1] == 'inet_fixed_ip':
if row[0].split('_')[-1].find('.') == -1:
cursor.execute('select tariff_plan from inet_fixed_ip_services where id = %s', (service[-1],))
else:
cursor.execute('select tariff_plan from inet_fixed_ip_services where id = %s', (service[-2],))
tariff = str(cursor.fetchall()[0][0])
loki_cursor.execute("select tariff_ptr_id from inet_inettariff where cherry_id = %s", (tariff,))
tariff_id = str(loki_cursor.fetchall()[0][0])
loki_cursor.execute("select * from inet_inettariff where tariff_ptr_id = %s", (tariff_id,))
tariff = loki_cursor.fetchall()[0]
tariff = dict(zip(('tariff_ptr_id', 'price_per_unit', 'is_dynamic', 'cherry_id', 'ie_price_first', 'ie_price_second', 'ie_price_switch', 'oe_price_first', 'oe_price_second', 'oe_price_switch', 'il_price_first', 'il_price_second', 'il_price_switch', 'ol_price_first', 'ol_price_second', 'ol_price_switch'), tariff))
if login in row[0]:
print>>o, (str(row[2]) + ';' + row[4] + ';' + str(row[5]).replace('.000000', '').replace('.', ',') + ';' + row[6] + ';' + str(price)).decode('utf-8').replace(u'incoming_external', u'Входящий внешний').replace(u'internal', u'Внутренний').replace(u'outgoing_any',u'Исходящий внешний').encode('utf-8')
else:
print>>o, (str(row[2]) + ';' + row[4] + ';' + str(row[5]).replace('.000000', '').replace('.', ',') + ';' + row[6] + ';' + str(price)).decode('utf-8').replace(u'incoming_external', u'Входящий внешний').replace(u'internal', u'Внутренний').replace(u'outgoing_any',u'Исходящий внешний').replace(date_start,u'Суммарно').encode('utf-8')
else:
price = str(row[7]).replace('.',',')
if login in row[0]:
print>>o, (str(row[2]) + ';' + row[4] + ';' + str(row[5]).replace('.000000', '').replace('.', ',') + ';' + row[6] + ';' + str(price)).decode('utf-8').replace(u'incoming_external', u'Входящий внешний').replace(u'internal', u'Внутренний').replace(u'outgoing_any',u'Исходящий внешний').encode('utf-8')
else:
print>>o, (str(row[2]) + ';' + row[4] + ';' + str(row[5]).replace('.000000', '').replace('.', ',') + ';' + row[6] + ';' + str(price)).decode('utf-8').replace(u'incoming_external', u'Входящий внешний').replace(u'internal', u'Внутренний').replace(u'outgoing_any',u'Исходящий внешний').replace(date_start,u'Суммарно').encode('utf-8')
Кусочек интернет-тарификатора.
+172
CString convertInt2Str(int i_Number, int i_NumDigits)
{
CString str = "";
for(int j=1; j<i_NumDigits; j++)
{
int digits = (int) pow((float) 10, j);
if(i_Number<digits) str += "0";
}
CString num;
num.Format("%d", i_Number);
return str+num;
}
Adding leading zeros...
+162
Speed = ini.GetInt("Speed" , Speed /(1 mm_s )) * (-1 mm_s);
Скорость задается изначально как положительное число, но в ресчетах используется ее отрицательное значение.