1. PHP / Говнокод #12795

    +151

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    public static function checkCurl()
    {
    	if (in_array("curl", get_loaded_extensions()))
    		return TRUE;
    	else
    		return FALSE;
    }

    function_exist? Не, не слышал. Мануалы для лохов.

    DrFreez, 25 Марта 2013

    Комментарии (19)
  2. PHP / Говнокод #12794

    +157

    1. 1
    2. 2
    3. 3
    4. 4
    $targetFolder = 'uploads/'; // Relative to the root
    // ...
    $targetPath = dirname(__FILE__) . '/' . $targetFolder;
    $targetFile = rtrim($targetPath,'/') . '/' . $_FILES['file']['name'];

    "Непостоянство слеша", Pedro Molina, 2013. Холст, масло
    https://github.com/pekebyte/pekeUpload/blob/940cf27e5fef5038e2e414c72be6e34d68f2881d/upload.php

    scriptin, 24 Марта 2013

    Комментарии (2)
  3. PHP / Говнокод #12793

    +158

    1. 1
    2. 2
    3. 3
    4. 4
    if (Database::getDbType() == 'pgsql')
          $stmt = Database::getInstance()->dbh->prepare("SELECT COUNT(*) AS count FROM torrent WHERE tracker = :tracker AND torrent_id = :id");
    else
          $stmt = Database::getInstance()->dbh->prepare("SELECT COUNT(*) AS `count` FROM `torrent` WHERE `tracker` = :tracker AND `torrent_id` = :id");

    https://github.com/ElizarovEugene/TorrentMonitor/blob/master/class/Database.class.php#L625 УПРЛС

    DrFreez, 24 Марта 2013

    Комментарии (6)
  4. PHP / Говнокод #12792

    +154

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    public static function checkPath($path)
    {
    	if (substr($path, -1) == '/')
    		$path = $path;
    	else
    		$path = $path.'/';
    	return $path;
    }

    facepalm.jpg

    DrFreez, 24 Марта 2013

    Комментарии (13)
  5. PHP / Говнокод #12791

    +158

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    public static function checkWriteToTorrentPath($path)
    {
    	if (file_put_contents($path.'file.txt', ' '))
    	{
    		unlink($path.'file.txt');
    		return TRUE;
    	}
    	else
    		return FALSE;
    }

    is_writable ? Не, не слышал!
    https://github.com/ElizarovEugene/TorrentMonitor/blob/master/class/System.class.php#L48 Эпик!

    DrFreez, 24 Марта 2013

    Комментарии (3)
  6. C++ / Говнокод #12789

    +13

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    CompoundExpression*
    CompoundExpression::newBinaryExpression(
    	BasicBinaryOperation::Type operation,
    	const Expression *x,
    	const Expression *y
    ) {
    	vector<Expression::const_pointer> params(2);
    	params[0] = x;
    	params[1] = y;
    	
    	// integer power optimization
    	if (operation == BasicBinaryOperation::POWER) {
    		if (y->isNumber()) {
    			Number::const_pointer number_y = dynamic_cast<typeof number_y>(y);
    			if (number_y != NULL && number_y->isIntegerNumber()) {
    				IntegerNumber::const_pointer integer_y = dynamic_cast<typeof integer_y>(number_y);
    				if (integer_y != NULL) {
    					operation = BasicBinaryOperation::INT_POWER;
    					return new CompoundExpression(BinaryOperation::getOperation(operation), params);
    				}
    			}
    		}
    	}
    	
    	// x^(y/n), where 'n' is odd integer
    	// transform to '(x^y)^(1/n)'
    	if (operation == BasicBinaryOperation::POWER) {
    		if (y->isCompoundExpression()) {
    			auto compoundExpressionY = dynamic_cast<CompoundExpression::const_pointer>(y);
    			if (compoundExpressionY != NULL && compoundExpressionY->operation->isBinary()) {
    				auto innerOperation = compoundExpressionY->operation;
    				auto binaryOperation = dynamic_cast<BinaryOperation const *>(innerOperation);
    				if (binaryOperation != NULL && binaryOperation->getType() == BasicBinaryOperation::DIVIDE) {
    					Expression::const_pointer   numerator = compoundExpressionY->params[0];
    					Expression::const_pointer denominator = compoundExpressionY->params[1];
    					if (denominator->isNumber()) {
    						auto numberDenominator = dynamic_cast<Number::const_pointer>(denominator);
    						if (numberDenominator != NULL && numberDenominator->isIntegerNumber()) {
    							auto integerDenominator = dynamic_cast<IntegerNumber::const_pointer>(numberDenominator);
    							if (integerDenominator != NULL && (integerDenominator->intValue() % 2) != 0) {
    								auto base = CompoundExpression::newBinaryExpression(BasicBinaryOperation::POWER, x, numerator);
    								return CompoundExpression::newBinaryExpression(BasicBinaryOperation::NTH_ROOT, integerDenominator, base);
    							}
    						}
    					}
    				}
    			}
    		}
    	}
    
    	return new CompoundExpression(BinaryOperation::getOperation(operation), params);
    }

    Моё. Потребовалось воткнуть оптимизацию арифметического выражения некоторого вида. В результате родился вот такой костыль.

    UncleAli, 24 Марта 2013

    Комментарии (4)
  7. Objective C / Говнокод #12788

    −116

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    { 
        NSString *xContent = myTextView.text;
        
        //temp file filename
        NSString *tmpFileName = @"test1.html";
        
        //temp dir
        NSString *tempDir = NSTemporaryDirectory();
        NSLog(@"tempDirectory: %@",tempDir);
        
        //create NSURL
        NSString *path4 = [tempDir stringByAppendingPathComponent:tmpFileName];
        NSURL* url = [NSURL fileURLWithPath:path4]; 
        
        //setup HTML file contents
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"MathJax" ofType:@"js" inDirectory:@"mathjax-MathJax-v2.0"];
        NSLog(@"filePath = %@",filePath);
        
        //write to temp file "tempDir/tmpFileName", set MathJax JavaScript to use "filePath" as directory, add "xContent" as content of HTML file
        [self writeStringToFile:tempDir fileName:tmpFileName pathName:filePath content:xContent];
        
        NSURLRequest* req = [[NSURLRequest alloc] initWithURL:url]; 
        
        //original request to show MathJax stuffs
        [myWebView loadRequest:req];
    }
    
     -(void)writeStringToFile:(NSString *)dir fileName:(NSString *)strFileName pathName:(NSString *)strPath content:(NSString *)strContent{
        
        NSString *path = [dir stringByAppendingPathComponent:strFileName];
        
        NSString *foo0 = @"<html><head><meta name='viewport' content='initial-scale=1.0' />"
    "<script type='text/javascript' src='";
        
        NSString *foo1 = @"?config=TeX-AMS-MML_HTMLorMML-full'></script>"
        "</head>"
        "<body>";
        NSString *foo2 = @"</body></html>";
        NSString *fooFinal = [NSString stringWithFormat:@"%@%@%@%@%@",foo0,strPath,foo1,strContent,foo2];
        
        [fooFinal writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }

    http://new2objectivec.blogspot.com/2012/03/tutorial-how-to-setup-mathjax-locally.html

    Здорово, правда?

    UncleAli, 23 Марта 2013

    Комментарии (2)
  8. PHP / Говнокод #12787

    +151

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    83. 83
    84. 84
    85. 85
    86. 86
    if (anidub::$exucution)
    		{
    			//получаем страницу для парсинга
    			$page = anidub::getContent($torrent_id, anidub::$sess_cookie);
    
    			if ( ! empty($page))
    			{
    				//ищем на странице дату регистрации торрента
    				if (preg_match("/<td width=\"\" class=\"heading\" valign=\"top\" align=\"right\">Добавлен<\/td><td valign=\"top\" align=\"left\">(.*)<\/td>/", $page, $array))
    				{
    					//проверяем удалось ли получить дату со страницы
    					if (isset($array[1]))
    					{
    						//если дата не равна ничему
    						if ( ! empty($array[1]))
    						{
    							//сбрасываем варнинг
    							Database::clearWarnings($tracker);
    							//приводим дату к общему виду
    							$date = $array[1];
    							$date_str = anidub::dateNumToString($array[1]);
    							//если даты не совпадают, перекачиваем торрент
    							if ($date != $timestamp)
    							{
                                    preg_match('/<a href=\"download\.php\?id=(\d{2,6})&name=(.*)\">/U', $page, $array);
                                    $torrent_id = $array[1];
                                    $torrent_id_name = $array[2];
    								//сохраняем торрент в файл
    								$torrent = anidub::getTorrent($torrent_id, $torrent_id_name, anidub::$sess_cookie);
    								$client = ClientAdapterFactory::getStorage('file');
    								$client->store($torrent, $id, $tracker, $name, $torrent_id, $timestamp);
    								//обновляем время регистрации торрента в базе
    								Database::setNewDate($id, $date);
    								//отправляем уведомлении о новом торренте
    								$message = $name.' обновлён.';
    								Notification::sendNotification('notification', $date_str, $tracker, $message);
    							}
    						}
    						else
    						{
    							//устанавливаем варнинг
    							if (anidub::$warning == NULL)
    							{
    								anidub::$warning = TRUE;
    								Errors::setWarnings($tracker, 'not_available');
    							}
    							//останавливаем процесс выполнения, т.к. не может работать без кук
    							anidub::$exucution = FALSE;
    						}
    					}
    					else
    					{
    						//устанавливаем варнинг
    						if (anidub::$warning == NULL)
    						{
    							anidub::$warning = TRUE;
    							Errors::setWarnings($tracker, 'not_available');
    						}
    						//останавливаем процесс выполнения, т.к. не может работать без кук
    						anidub::$exucution = FALSE;
    					}
    				}
    				else
    				{
    					//устанавливаем варнинг
    					if (anidub::$warning == NULL)
    					{
    						anidub::$warning = TRUE;
    						Errors::setWarnings($tracker, 'not_available');
    					}
    					//останавливаем процесс выполнения, т.к. не может работать без кук
    					anidub::$exucution = FALSE;
    				}
    			}			
    			else
    			{
    				//устанавливаем варнинг
    				if (anidub::$warning == NULL)
    				{
    					anidub::$warning = TRUE;
    					Errors::setWarnings($tracker, 'not_available');
    				}
    				//останавливаем процесс выполнения, т.к. не может работать без кук
    				anidub::$exucution = FALSE;
    			}
    		}

    Классическая лесенка пыхомакаки.

    Stallman, 23 Марта 2013

    Комментарии (16)
  9. PHP / Говнокод #12786

    +153

    1. 1
    2. 2
    $object = __CLASS__;
    self::$instance = new $object;

    Stallman, 23 Марта 2013

    Комментарии (0)
  10. PHP / Говнокод #12785

    +149

    1. 1
    preg_match_all('/<td class=\"f\">\n\t\t\t\t\n\t\t\t\t\t(.*)\n\t\t\t\t<\/td>/', $page, $section)

    https://github.com/ElizarovEugene/TorrentMonitor/blob/master/trackers/tfile.me.search.php#L34
    ну и много всякой другой вкуснятины

    DrFreez, 22 Марта 2013

    Комментарии (12)