- 1
$fails = readdir($handle);
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+168
$fails = readdir($handle);
Не удивительно, что скрипт у автора никак не хотел работать как надо.
+162
protected function getMebelNavigationHtml()
{
$nav = <<<EODD
<td>
<div class="g-c right">
<div class="tab">
<nobr><a href="/mebel">Мебель</a></nobr>
</div>
<div class="body">
<table>
<tr>
<td class="col">
<ul>
<li class="head"><a href="/mebel/stulchiki">Стульчики</a></li>
<li class="head"><a href="/mebel/krovatki">Кроватки</a></li>
<li class="head"><a href="/mebel/manezhi">Манежи</a></li>
<li class="head"><a href="/mebel/komody">Комоды</a></li>
<li class="head"><a href="/mebel/pelenalnye-stoliki">Пеленальные столики</a></li>
<li class="head"><a href="/mebel/electrokacheli">Электрокачели</a></li>
<li class="head"><a href="/mebel/napolnie-ka4eli">Напольные качели</a></li>
<li class="head"><a href="/mebel/kresla-kachalki">Кресла-качалки</a></li>
<li class="head"><a href="/mebel/hodunki">Ходунки</a></li>
<li class="head"><a href="/mebel/kolybeli">Колыбели</a></li>
<li class="head"><a href="/mebel/shkafy">Шкафы</a></li>
<li class="head"><a href="/mebel/detskie-komnaty">Детские комнаты</a></li>
<li class="head"><a href="/mebel/matrasy">Матрасы</a></li>
<li class="head"><a href="/mebel/aksessuary">Аксессуары</a></li>
</ul>
</td>
<td class="col">
<ul>
<li class="head"><a href="/mebel/postel">Постельные принадлежности</a></li>
<li><a href="/mebel/postel/odeyala">Одеяла</a></li>
<li><a href="/mebel/postel/podushki">Подушки</a></li>
<li><a href="/mebel/postel/komplekty-postelnogo-belya">Комплекты постельного белья</a></li>
<li><a href="/mebel/postel/spalnye-meshki">Спальные мешки</a></li>
<li><a href="/mebel/postel/komplekty-na-vypisku">Комплекты на выписку</a></li>
<li><a href="/mebel/postel/baldahiny">Балдахины</a></li>
<li><a href="/mebel/postel/aksessuary">Аксессуары</a></li>
<li><a href="/mebel/postel/prosini-i-kleenki">Простыни и клеенки</a></li>
<li><a href="/mebel/postel/bortiki">Бортики</a></li>
</ul>
</td>
</tr>
</table>
</div>
</div>
<a href="/mebel">Мебель</a>
</td>
EODD;
return $nav;
}
Хардкоженая навигация. Даже не в шаблоне...
+166
TagsTree ParseXML(const char file_name[])
{
ifstream input_file(file_name, std::ios::in);
string content;
if(!input_file.good())
{
throw "can't open xml";
}
while(!input_file.eof())
{
char buffer[256];
input_file.read(buffer, 256);
streamsize read_count = input_file.gcount();
content.append(buffer, buffer+read_count);
}
input_file.close();
auto Cleanup = [&content](const string& what_to_del) -> void
{
string::size_type pos = content.find(what_to_del);
while(pos != string::npos)
{
content.erase(pos, what_to_del.size());
pos = content.find(what_to_del, pos);
}
};
Cleanup("\n");
Cleanup("\t");
Cleanup(" ");
string::size_type comment_begin = 0;
string::size_type comment_end = 0;
for(;;)
{
string::size_type comment_begin = content.find("<!--", comment_end);
if(comment_begin == string::npos)
{
break;
}
string::size_type comment_end = content.find(">", comment_begin+3);
if(comment_end == string::npos)
{
throw "invalid xml: no comment closing brace";
}
content.erase(comment_begin, comment_end-comment_begin+1);
comment_end = comment_begin;
}
string::size_type header_begin = content.find("<?xml");
if(header_begin == string::npos)
{
throw "invalid xml: no header";
}
string::size_type header_end = content.find(">", header_begin+4);
if(header_end == string::npos)
{
throw "invalid xml: no header closing brace";
}
content.erase(comment_begin, header_end-header_begin+1);
auto CutTagAndContent = [](string& from, string& tag, string& content) -> void
{
string::size_type position = from.find('>');
if(position == string::npos)
{
throw "invalid xml: no tag closing brace";
}
tag = from.substr(1, position-1);
position = from.find("</"+tag+'>', position);
if(position == string::npos)
{
throw "invalid xml: no closing tag";
}
content = from.substr(tag.size()+2, position-tag.size()-2);
from.erase(0, position+tag.size()+3);
};
if(content[0] != '<')
{
throw "invalid xml: to root tag";
}
TagsTree result;
CutTagAndContent(content, result.Node.name, result.Node.content);
TagsTree::children_vectorT children;
children.push_back(&result);
do
{
for(auto i = children.begin(); i!= children.end(); i++)
{
while(!(**i).Node.content.empty())
{
if((**i).Node.content[0]!='<')
{
break;
}
TAG temporary;
CutTagAndContent((**i).Node.content, temporary.name, temporary.content);
(**i).Push(temporary);
}
}
children = EnlistChildren(children);
}
while(!children.empty());
return result;
}
Говнонедопарсер недоговноXML. Дерево тэгов - отдельная кучка.
+144
#catalog { width: 100$ }
+157
{{sectionelse}}
<script language="javascript">
window.location = '/megasection/megapage.html?step='+{{if $step eq '2'}}'3'{{else}}'1'{{/if}};
</script>
{{/section}}
PHP, Smarty, редиректы уже не в моде
+165
Ckey::Ckey(const String& name, const String& suffix1, const String& suffix2, const String& suffix3)
{
ASSERT(name.Size(), "Key with emty name are invalid!");
if (!name.Size())
{
return;
}
PushBack(name);
if (!suffix1.Size())
{
return;
}
PushBack(suffix1);
if (!suffix2.Size())
{
return;
}
PushBack(suffix2);
if (!suffix3.Size())
{
return;
}
PushBack(suffix3);
}
Ну просто замечательный конструктор класса.
Собственно сам класс унаследован (public-ом, причем) от местной реализации класса vector, отсюда загадочные методы PushBack.
А String - это не менее замечательная, местная, реализация строк.
+160
//create a list of rules to block
var blockRules = ["http://example.com/images/*",
"*://example.org/css/*"];
// add them to the content blocker
for (var rule in blockRules) {
opera.extension.urlfilter.block.add(blockRules[rule])
}
Экзампле из официальной документации одного браузера, отчаянно пытающегося прекратить катиться в сраное говно и набрать популярность.
Будет растащено хомячками на копипасту.
И, striker, убери уже этот долбанный trim для leading spaces
+132
<A\n <BR / href="http://www.site.ru" >Некий текст</A>
<P Иванов id=Значение_без_кавычек_кирилицей><P>Некий текст</P>
<SPAN><SPAN Л.И. Некий текст</SPAN>
Вот несколько кривых кусков HTML кода с одного государственного портала
+74
public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWrapper {
@SuppressWarnings("unchecked")
private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
String propertyName = tokens.canonicalName;
String actualName = tokens.actualName;
if (tokens.keys != null) {
// Apply indexes and map keys: fetch value for all keys but the last one.
PropertyTokenHolder getterTokens = new PropertyTokenHolder();
getterTokens.canonicalName = tokens.canonicalName;
getterTokens.actualName = tokens.actualName;
getterTokens.keys = new String[tokens.keys.length - 1];
System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
Object propValue;
try {
propValue = getPropertyValue(getterTokens);
}
catch (NotReadablePropertyException ex) {
throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
"Cannot access indexed value in property referenced " +
"in indexed property path '" + propertyName + "'", ex);
}
// Set value for last key.
String key = tokens.keys[tokens.keys.length - 1];
if (propValue == null) {
throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
"Cannot access indexed value in property referenced " +
"in indexed property path '" + propertyName + "': returned null");
}
else if (propValue.getClass().isArray()) {
PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
Class requiredType = propValue.getClass().getComponentType();
int arrayIndex = Integer.parseInt(key);
Object oldValue = null;
try {
if (isExtractOldValueForEditor()) {
oldValue = Array.get(propValue, arrayIndex);
}
Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), requiredType));
Array.set(propValue, arrayIndex, convertedValue);
}
catch (IndexOutOfBoundsException ex) {
throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
"Invalid array index in property path '" + propertyName + "'", ex);
}
}
else if (propValue instanceof List) {
PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
Class requiredType = GenericCollectionTypeResolver.getCollectionReturnType(
pd.getReadMethod(), tokens.keys.length);
List list = (List) propValue;
int index = Integer.parseInt(key);
Object oldValue = null;
if (isExtractOldValueForEditor() && index < list.size()) {
oldValue = list.get(index);
}
Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), requiredType));
if (index < list.size()) {
list.set(index, convertedValue);
}
else if (index >= list.size()) {
for (int i = list.size(); i < index; i++) {
try {
list.add(null);
}
catch (NullPointerException ex) {
throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
"Cannot set element with index " + index + " in List of size " +
list.size() + ", accessed using property path '" + propertyName +
"': List does not support filling up gaps with null elements");
}
}
list.add(convertedValue);
}
}
else if (propValue instanceof Map) {
//...
}
}
}
}
Spring...
+162
function db_date_time($time = null) {
if (is_null($time)) {
$time = time();
}
$s = explode('.', date("d.m.Y.H.i.s", $time));
return $s[2] . '-' . $s[1] . '-' . $s[0] . ' ' . $s[3] . ':' . $s[4] . ':' . $s[5];
}