- 1
- 2
- 3
- 4
- 5
- 6
fixed (char* p = "A")
{
p[0] = 'B';
}
Console.WriteLine("A");
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+140
fixed (char* p = "A")
{
p[0] = 'B';
}
Console.WriteLine("A");
Immutable strings
−107
- (void)viewDidLoad
{
[super viewDidLoad];
[self performSegueWithIdentifier:@"manWomanView" sender:self];
return;
//40 строк кода...
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
// 5 строк формируем реквест
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:&err];
if (!responseData) {
NSLog(@"Connection Error: %@", [err localizedDescription]);
}
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"Response: %@", responseString);
NSString *isSucces = [AYDataFetcher isSucces:responseString];
if ([isSucces isEqualToString:@"success"]) {
NSLog(@"Signup Succes");
// Проверяем и записываем оплату
NSNumber *isPlat = [AYDataFetcher isPlat:responseString];
//NSLog(@"%@", isPlat);
NSLog(@"%@", [isPlat boolValue]?@"Paid account":@"No paid account");
[[NSUserDefaults standardUserDefaults] setBool:[isPlat boolValue] forKey:PLAT];
[[NSUserDefaults standardUserDefaults] synchronize];
if(FALSE) // if([[MKStoreManager sharedManager] isSubscriptionActive:kMyFeatureIdentifier])
{
// 80 строк кода
} else {
if (FALSE) {
//50 строк кода......
Клиент обратился - Приложение сделано фрилансером по имени Андрей Андреев. При переходе с одного таба на другой приложение подвисало на 5-10 секунд. Смотрим код, радуемся - все запросы к апи шлются через NSURLConnection sendSynchronousRequest, в коде куча блоков вроде if(FALSE). И это уже в релизе.
+126
ZipWith[f_, vector1_, vector2_] := Table[ f[ vector1[[i]], vector2[[i]] ], {i, Min[Length[vector1], Length[vector2]] } ]
UnZip[list_] := {Map[First, list], Map[Rest, list]}
Zip[vector1_, vector2_] := ZipWith[{#1, #2} &, vector1, vector2]
ZipWithIndex[vector_] := Zip[vector, Range[1, Length[vector]]]
ZipWithIndexed[f_, vector1_, vector2_] := Map[f @@ # &, Map[Flatten, Zip[vector1, ZipWithIndex[vector2]]]]
Fold2[f_, initialState_, list1_ , list2_ ] := Fold[f @@ Prepend[#2, #1] &, initialState, Zip[list1, list2]]
ZipWith1[f_, {}, any_] := {}
ZipWith1[f_, any_, {}] := {}
ZipWith1[f_, {h1_, t1___}, {h2_, t2___}] := Prepend[ZipWith1[f, {t1}, {t2}], f[h1, h2]]; (*Extremal version, but recursion depth is 256 *)
GroupByIndex[list_, indexesOfGroup_] := (UnZip[#][[1]]) & /@ Gather[ZipWithIndex[list], (And @@ Map[(MemberQ[indexesOfGroup, #]) &, {#1[[2]], #2[[2]]}]) &]
Wolfram Mathematica
+149
Wreqr.Commands = (function(Wreqr){
"use strict";
return Wreqr.Handlers.extend({
execute: function(){
var name = arguments[0];
var args = Array.prototype.slice.call(arguments, 1);
this.getHandler(name).apply(this, args);
}
});
})(Wreqr);
из библиотеки которая претендует на популярность, шаблонность (в модном нынче смысле слова) и стэйт-оф-зэ-артность
вопрос - НАХ8Я СТРОКА 6???????
+67
class IntegerUtils
{
public static function isInteger($value)
{
return preg_match('/[0-9]+/', $value);
}
}
Must have класс, который должен быть у каждого в его библиотеке "велоприседов". Поистине краткий, лаконичный, гениальный. Даешь 100% говнокод!
−90
- (void)movementScreenUp
{
int shift;
switch (_numberCell) {
case 3:
if (clickButtonGameCells.tag == 1 || clickButtonGameCells.tag == 10) {
shift = startPosition.y;
break;
}
if (clickButtonGameCells.tag == 2 || clickButtonGameCells.tag == 20) {
shift = - 50;
break;
}
if (clickButtonGameCells.tag == 3 || clickButtonGameCells.tag == 30) {
shift = - 90;
break;
}
case 4:
if (clickButtonGameCells.tag == 1 || clickButtonGameCells.tag == 10) {
shift = startPosition.y;
break;
}
if (clickButtonGameCells.tag == 2 || clickButtonGameCells.tag == 20) {
shift = - 25;
break;
}
if (clickButtonGameCells.tag == 3 || clickButtonGameCells.tag == 30) {
shift = - 90;
break;
}
if (clickButtonGameCells.tag == 4 || clickButtonGameCells.tag == 40) {
shift = - 90;
break;
}
case 5:
if (clickButtonGameCells.tag == 1 || clickButtonGameCells.tag == 10) {
shift = startPosition.y;
break;
}
if (clickButtonGameCells.tag == 2 || clickButtonGameCells.tag == 20) {
shift = - 1;
break;
}
if (clickButtonGameCells.tag == 3 || clickButtonGameCells.tag == 30) {
shift = - 40;
break;
}
if (clickButtonGameCells.tag == 4 || clickButtonGameCells.tag == 40) {
shift = - 86;
break;
}
if (clickButtonGameCells.tag == 5 || clickButtonGameCells.tag == 50) {
shift = - 86;
break;
}
case 6:
if (clickButtonGameCells.tag == 1 || clickButtonGameCells.tag == 10) {
shift = startPosition.y;
break;
}
if (clickButtonGameCells.tag == 2 || clickButtonGameCells.tag == 20) {
shift = startPosition.y;
break;
}
if (clickButtonGameCells.tag == 3 || clickButtonGameCells.tag == 30) {
shift = - 2;
break;
}
if (clickButtonGameCells.tag == 4 || clickButtonGameCells.tag == 40) {
shift = - 52;
break;
}
if (clickButtonGameCells.tag == 5 || clickButtonGameCells.tag == 50) {
shift = - 105;
break;
}
if (clickButtonGameCells.tag == 6 || clickButtonGameCells.tag == 60) {
shift = - 105;
break;
}
default:
break;
}
[UIView animateWithDuration:0.25 animations:^{
CGRect view_frame = self.frame;
view_frame.origin = CGPointMake(self.frame.origin.x, shift);
self.frame = view_frame;
}];
}
Магия цифр
+46
$week['monday'] = date("d.m.Y", $week_start);
$week['tuesday'] = date("d.m.Y", $week_start + 1 * 86400);
$week['wednesday'] = date("d.m.Y", $week_start + 2 * 86400);
$week['thursday'] = date("d.m.Y", $week_start + 3 * 86400);
$week['friday'] = date("d.m.Y", $week_start + 4 * 86400);
$week['saturday'] = date("d.m.Y", $week_start + 5 * 86400);
$week['sunday'] = date("d.m.Y", $week_start + 6 * 86400);
+37
<?php
session_start();
if(!empty($_SESSION['UserLogin']) or !empty($_SESSION['UserId']))
{
header('Location: user');
}
if(isset($_POST['UserName']))
{
$UserName = $_POST['UserName'];
if($UserName == '')
{
unset($UserName);
}
}
if(isset($_POST['UserEmail']))
{
$UserEmail = $_POST['UserEmail'];
if($UserEmail == '')
{
unset($UserEmail);
}
}
if(isset($_POST['UserLogin']))
{
$UserLogin = $_POST['UserLogin'];
if($UserLogin == '')
{
unset($UserLogin);
}
}
if(isset($_POST['UserPassword']))
{
$UserPassword = $_POST['UserPassword'];
if($UserPassword == '')
{
unset($UserPassword);
}
}
if (empty($UserName) or empty($UserEmail) or empty($UserLogin) or empty($UserPassword))
{
header('Location: registration?error_code=1');
}
else
{
include("application/db.config.php");
$UserLogin = stripslashes($UserLogin);
$UserLogin = htmlspecialchars($UserLogin);
$UserLogin = trim($UserLogin);
$UserPassword = stripslashes($UserPassword);
$UserPassword = htmlspecialchars($UserPassword);
$UserPassword = trim($UserPassword);
$SelectQuery = mysql_query("SELECT id FROM Users WHERE UserLogin ='$UserLogin'", $db);
$QueryResult = mysql_fetch_array($SelectQuery);
if(!empty($QueryResult['id']))
{
header('Location: registration?error_code=2');
}
else
{
$InsertQuery = mysql_query("INSERT INTO Users(UserName, UserSName, UserLogin, UserPassword, UserEmail,
UserPhone, UserStatus) VALUES('$UserName', 'Фамилия не указана', '$UserLogin', '$UserPassword', '$UserEmail', 'Телефон не указан', 'Статус не указан')");
if($InsertQuery == true)
{
header("Location: action_status?reg_code=good&UserLogin=$UserLogin&UserPassword=$UserPassword");
}
else
{
header('Location: registration?error_code=3');
}
}
}
?>
Извержение.
+119
data Fuuu = Fuuu
instance Eq Fuuu
main = print $ if Fuuu == Fuuu then "I dosen't seen this" else "and this"
Вот за что мне нравится сверх надежный высокоуровневый хаскель, так за то, что если забыл переопределить какой-то метод или оператор из класа типов (в нормальных языках это интерфейс или один из базовых класов) стандартной библиотеки языка или неподходящим образом от него отнаследовался, то мы получаем надежное поведение:
http://ideone.com/6faPct
результат: Ошибка выполнения время: 0.01s память: 3580 kB сигнал: -1
ввод: нет
вывод: нет
stderr:
prog: <<loop>>
+50
if(!$category = $this->EE->product_model->get_category_by_key($key)){
$this->EE->functions->redirect($this->EE->functions->create_url($this->EE->config->item('site_404')));
exit();
}
// Эти 4 строчки достают все продукт которые относятся к выбранной категории. Дальше веселее ..
// Build our variable data
$vars[0] = array(
'site_id' => $category[0]['site_id'],
'category_id' => $category[0]['category_id'],
'category_image' => $img,
'category_detail' => $category[0]['detail'],
'parent_id' => $category[0]['parent_id'],
'category_title' => $category[0]['title'],
'url_title' => $category[0]['url_title'],
'meta_title' => $category[0]['meta_title'],
'meta_keyword' => $category[0]['meta_keyword'],
'meta_descr' => $category[0]['meta_descr'],
'total_results' => count($category[0]["products"]),
'results' => $category[0]["products"],
'no_results' => array(),
'result_filter_set' => '',
'breadcrumb_parent_categories' => $breadcrumb_parent_categories,
'catalog_guest_flag' => $flag_catalog,
'catalog_price_visible' => $catalog_visible
);
// Filter the results
if(count($category[0]["products"]) != 0)
$vars = $this->_filter_results($vars,$key,true);
// А теперь count($vars['results']) == $this->EE->config->products_per_page;
// И самое веселое -
foreach($vars[0]['results'] as $rst){
$tmp = $this->_get_product($rst["product_id"]);
$results[] = $tmp[0];
}
$vars[0]['results'] = $results;
// Функция _get_product() получает все данные о продукте: отзывы, описание, цена, куча опций. Пара строчек оттуда:
if($product_id == ''){
// Get product by param or dynamically
$product_id = $this->EE->TMPL->fetch_param('product_id');
$url_title = $this->EE->TMPL->fetch_param('url_title');
if($product_id != ''){
$products = $this->EE->product_model->get_products($product_id);
}else{
// get by url key
$key = ($url_title == '') ? $this->EE->uri->segment(2) : $url_title;
if(!$products = $this->EE->product_model->get_product_by_key($key)){
// Not a product page
return false;
}
}
}else{
if(!$products = $this->EE->product_model->get_products($product_id)){
return false;
}
}
// Очень интересен вызов функции get_products(), эта ф-ция вызывается и для продуктов в каталоге и на странице продукта.
// Каждый вызов тянет за собой 25 запросов в базу, если на странице 40 продуктов * 25 = 1000 запросов = ~ 20 секунд на загрузку страницы
кусочек кода который выводит продукты в каталог, взят из eCommerce плагина BrilliantRetail для ExpressionEngine. Плагин кстати говоря стоит 150 баксов, мда )