- 1
- 2
- 3
- 4
if (ch=='k' && ch!='t')
{
something
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+980
if (ch=='k' && ch!='t')
{
something
}
Найдено в довольно серьезном проекте.
−131
#!/bin/bash
######################################################################################
#
# Write a bash script that obtains active processes for the current user,
# breaks them into chains and prints all unique chains containing 3 or more
# PIDs in the following format:
# PID1:PID2:PID3:…:PIDn
# PID:PID:PID:…:PID
# …
# So that each next PID is a parent of the previous PID, the first PID in
# each chain does not have children and the last PID in each chain
# does not have parent.
#
######################################################################################
TEMPFILE="/tmp/$0$$" # file needs to save the process list
# it's really needed to divide columns
# generated 'ps'
# parameters:
# -H - sorts the list as process forest (it lets to find connection between child and parent faster)
# -o - sets the output format
# "%p %P" - thow columns in output: PID and PPID
# -u - sets username
# `whoami` - get the current user name
ps -H -o "%p %P" -u `whoami` > $TEMPFILE
PIDLIST=(`awk '/[0-9]/ {print $1}' $TEMPFILE`) # make an array using the first column
PPIDLIST=(`awk '/[0-9]/ {print $2}' $TEMPFILE`) # and the second
SIZE=${#PIDLIST[*]}
K=0
# bypassing the forest using stack which emulates LINKS array. K is the pointer to stack's top
for (( i=0; i<$SIZE; i++ ))
do
if [[ $K = 0 || ${PPIDLIST[$i]} = ${LINKS[$K-1]} ]] # new tree or new edge in the tree.
then
LINKS[$K]=${PIDLIST[$i]} # push PID to stack
K=`expr $K + 1`
else # the chain is complete.
if [[ $K > 2 ]] # enough size to print the chain
then # reversed formatted output the chain
echo ${LINKS[*]} | awk '{ printf $NF; for (i = NF-1; i > 0; --i) printf ":"$i}'
echo
fi
until [[ $K == 0 || ${PPIDLIST[$i]} == ${LINKS[$K-1]} ]]
do # deleting elements from stack until find a
# parent or tree is end
unset LINKS[$K-1]
K=`expr $K - 1`
done
LINKS[$K]=${PIDLIST[$i]} # push PID to stack
K=`expr $K + 1`
fi
done
rm -rf $TEMPFILE # removing temp file
+172
//Взятые из разных файлов варианты обращений к файлу конфигураций характеризуют о гибкости подхода к разработке приложения
require_once '../../../config.php';
require_once("../config.php");
require_once("../../../../config.php");
require_once(dirname(dirname(__FILE__)) . '/config.php');
require('../config.php');
require_once(dirname(__FILE__) . '/../../config.php');
require_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/config.php'); //included from messagelib (how to fix?)
Предлагаю обратить внимание на http://moodle.org/ -- это Система Управления Обучением.
Продукт поражает своей архитектурой. Предлагаю взглянуть одним глазком.
+152
BOOL NAKED CompareCurrentProcess(PCHAR pszName)
{
/*
1. Found PEB
2. Found _RTL_USER_PROCESS_PARAMETERS
3. Found _RTL_USER_PROCESS_PARAMETERS->ImagePathName
4. Convert UNICODE to ANSI
5. compare strings
*/
__asm {
MOV ESI,ESP // SAVE STACK PTR
MOV EAX,DWORD PTR FS:[0x30] // eax == PEB
MOV EAX,DWORD PTR DS:[EAX+0x10] // eax == _RTL_USER_PROCESS_PARAMETERS
ADD EAX,0x38 // eax == _RTL_USER_PROCESS_PARAMETERS->ImagePathName
XOR EDX,EDX //
XOR ECX,ECX //
XOR EDI,EDI //
MOV CL, BYTE PTR [EAX] // CL = UNICODE_STRING.Length in bytes
SUB ESP,ECX // reserve in stack CL bytes
ADD EAX,4 // EAX ptr to WCHAR ImagePathName
MOV EAX,DWORD PTR [EAX] // EAX = PWCHAR
next_char:
CMP CL,0 // WCHAR end
JZ end;
MOV DL,BYTE PTR [EAX] // DL == *(PCHAR)WCHAR
ADD EAX,2 // GOTO next WIDEchar
MOV BYTE PTR [ESP],DL // SAVE char in memory reserved in stack
INC ESP // pStr++
INC EDI // pStrLen++
SUB CL,2 // Length--;
jmp next_char // goto_next;
end:
MOV BYTE PTR [ESP],0 // *pStr = 0; null terminated
SUB ESP,EDI // pStr = (PCHAR)(pStr - pStrLen)
XOR EDX,EDX
XOR ECX,ECX
mov ecx,esp // ecx = pStr
mov edx,esp // edx = pStr
//
// HERE FOUND image file name
m_loop:
cmp edi,0
jz file_founded
cmp byte ptr [edx],0x5C // '\'
JZ founded;
inc edx
dec edi
jmp m_loop
founded:
dec edi
mov ecx,edx
inc edx
jmp m_loop
file_founded:
push esi
inc ecx
push ecx
push dword ptr [esi+4]
call my_strcmp
pop esi
mov esp,esi
ret
}
}
Источник: http://www.wasm.ru/forum/viewtopic.php?id=40652
Что может быть плохого в функции кроме того, что эту задачу можно было бы решить тонной адекватных вариантов?
+134
$i=10000;
while(true)
{
$i--;
if ($i==0) break;
// Какойто код с $i
}
Выкопал в одном серьезном проекте. Так там что не цикл так while(true) c точками выхода по телу цикла..
+161
<?php
class Cached_Query
{
function __construct()
{
$mem_cache = new Memcache;
$mem_cache->connect('localhost', 11211);
mysql_connect("localhost", "root", "");
}
function Query($query_text)
{
$ms_query = mysql_query("SELECT * FROM sometable WHERE somedata = `$query_text`");
$query_data = mysql_fetch_array($ms_query);
return $query_data;
}
function QueryCache($query_text, $seconds)
{
$query_data = $mem_cache->fetch("somedata", $query_text);
if(!$query_data)
{
$ms_query = mysql_query("SELECT * FROM sometable WHERE somedata = `$query_text`");
$query_data = mysql_fetch_array($ms_query);
$mem_cache->add("somedata", $query_text, false, $seconds)
}
return $query_data;
}
function FetchArray($result)
{
foreach($result as $key)
{
echo $key;
}
}
}
?>
Напишите класс-обертку для работы с php_mysql (либо mysqli), реализуйщий функции кеширования с помощью memcached. Достаточно трех методов:
Query($query_text);//обычный запрос
QueryCache($query_text,$seconds);//кеширование запроса
FetchArray($result);//вывод результатов
Да говно-вопрос.
+120
public class XXX
{
private Object m_ForLock = new object();
private String m_Path = "";
public XXX(String Path)
{
lock (m_ForLock)
{
m_Path = Path;
}
}
}
+163
<?php
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
sleep(3);
if($_POST[parent_id]) $parent_id = preg_replace('/\D+/i','', $_POST[parent_id]);
else $parent_id = 0;
$author = trim($_POST[author]);
$comment = trim($_POST[comment]);
if(!$author) $error[author] = 'Введите имя!';
if(!$comment) $error[comment] = 'Напишите комментарий!';
if($error)
exit(json_encode($error));
require_once 'blocks/bd.php';
$sql = "INSERT INTO comments (parent_id, name, comment, date_add) VALUES ($parent_id, '$author', '$comment', NOW())";
$result = mysql_query($sql);
if(!$result)
{
$error[] = 'Произошла ошибка, комментарий не сохранен';
exit(json_encode($error));
}
exit();
}
?>
+164
<?php
class Gcont extends Controller {
// ...
function gcont(){
$this->load->model('am_loader');
$title = $this->am_loader->gettitle();
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"';
echo '<html xmlns="http://www.w3.org/1999/xhtml">';
echo '<head><title>'.$title.'</title>';
// ...
$this->load->view('gcont');
}
}
Суровая генерация контента нубом из контроллера MVC.
+170
$p = array(1,0,0,0,0,0,0,0,0,0); // вероятность 1/10
$a = array();
for($i=0; $i<100; $i++)
$a[] = $p[mt_rand(0, count($p)-1)];
Это — заполнение массива случайными значениями с заданной вероятностью 1 к 10. =)