- 1
return i == -1 ? true : false;
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+155
return i == -1 ? true : false;
Ну это, если true, так true, а иначе false, чисто чтобы всем было понятно...
+136
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <math.h>
#include <stdlib.h>
struct thread_arg
{
int a;
int b;
int c;
double d;
};
void *ret_x1(void *arg)
{
struct thread_arg targ = *(struct thread_arg *)arg;
double x1;
x1 = (-targ.b + sqrt(targ.d)) / (2*targ.a);
fprintf(stderr, "x1 = %f\n", x1);
return NULL;
}
void *ret_x2(void *arg)
{
struct thread_arg targ = *(struct thread_arg*)arg;
double x2;
x2 = (-targ.b - sqrt(targ.d)) / (2*targ.a);
fprintf(stderr, "x2 = %f\n", x2);
return NULL;
}
int main(void)
{
pthread_t thread1, thread2;
struct thread_arg args;
fprintf(stderr, "Enter a, b and c\n");
scanf("%d %d %d", &args.a, &args.b, &args.c);
args.d = args.b*args.b - 4*args.a*args.c;
if(args.d < 0)
{
fprintf(stderr,"There is no roots\n");
return 0;
}
else
{
if(pthread_create(&thread1, NULL, &ret_x1, &args) != 0)
{
fprintf(stderr, "Error1\n");
return 1;
}
if(pthread_create(&thread2, NULL, &ret_x2, &args) != 0)
{
fprintf(stderr, "Error2\n");
return 1;
}
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
}
return 0;
}
Многопоточное решение квадратного уравнения...
+137
if (messages[i].description != "")
if (messages[i].description.StartsWith("<![CDATA["))
{
messages[i].description = messages[i].description.Substring(9);
messages[i].description = messages[i].description.Substring(0, messages[i].description.Length - 3);
}
для строк типа <![CDATA[******]!>
Возникает устойчивое ощущение говнокода. Как нормально написать? :)
+133.8
public static XmlNode FindNodeXPath(XmlNode root, string xPath)
{
string[] paths = xPath.Split(new char[] { '/' });
XmlNode node = root;
for (int i = 0; i < paths.Length; i++)
{
XmlNode childNode = null;
for (int j = 0; j < node.ChildNodes.Count; j++)
{
if (node.ChildNodes[j].Name == paths[i])
{
childNode = node.ChildNodes[j];
node = childNode;
break;
}
}
if (childNode == null)
{
return null;
}
}
return node;
}
public static XmlNode FindNodeXPath(XmlNode root, string nodeName, string xPath)
{
XmlNode node = FindNodeXPath(root, xPath);
if (node != null)
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
if (node.ChildNodes[i].Name == nodeName)
{
node = node.ChildNodes[i];
}
}
}
return node;
}
public static void UpdateBaseAddress(string url, string fileConfig)
{
// Create config file to create
XmlDocument xmlDom = new XmlDocument();
xmlDom.Load(fileConfig);
XmlNode root = xmlDom.DocumentElement;
// Get XML node
XmlNode xmlNode = FindNodeXPath(root, "endpoint", "system.serviceModel/services/service");
xmlNode.Attributes["address"].Value = url;
xmlNode = FindNodeXPath(root, "add", "system.serviceModel/services/service/host/baseAddresses");
xmlNode.Attributes["baseAddress"].Value = url;
xmlDom.Save(fileConfig);
}
Виетнамский XPath эквивалент :)
+153
function strum($text, $simb)
{
if(mb_strlen($text, 'UTF-8') > $simb){
}
if(mb_strlen($text, 'UTF-8') > $simb)
{
$start = 0;
for($i = 0; $i <= (ceil(mb_strlen($text, 'UTF-8') / $simb)); $i++)
{
$tmp = mb_strpos($text, '. ', $start + $simb, 'UTF-8');
if(is_numeric($tmp))
{
$num[] = $tmp;
}
$tmp = mb_strpos($text, '! ', $start + $simb, 'UTF-8');
if(is_numeric($tmp))
{
$num[] = $tmp;
}
$tmp = mb_strpos($text, '? ', $start + $simb, 'UTF-8');
if(is_numeric($tmp))
{
$num[] = $tmp;
}
if($num != '')
{
$end = min($num) + 1;
}
if($end <= $start)
{
$end = mb_strlen($text, 'UTF-8');
}
$str = mb_substr($text, $start, $end, 'UTF-8');
$string[] = mb_substr($str, 0, ($end - $start), 'UTF-8');
$start = $end;
unset($num);
unset($str);
unset($tmp);
if($end == mb_strlen($text, 'UTF-8'))
{
break;
}
}
}
else
{
$string[] = $text;
}
return $string;
}
Функция для умной разбивки
+144.8
rem = 1;/*
@cls
@cscript %~s0 //E:JScript //Nologo
@exit /b
*/
str = WScript.StdIn.ReadLine();
WScript.StdOut.Write(1+2+3);
Файл сохранять в *.BAT
Это мой первый полиглот полиглот BAT и JScript.
Про полиглоты на вики: http://en.wikipedia.org/wiki/Polyglot_(computing)
+57.7
@echo off
cls
pushd "%~d0%~p0"
echo Current DIR: "%CD%"
if "%~1" == "talk_widget" goto talker
rem ////////////////////
:auth
echo Enter chat filename to connect ("abc" for example):
set /p chat=^>
echo Enter your nick:
set /p nick=^>
start call %0 talk_widget %chat% %nick%
rem ////////////////////
:listener
cls
call title "| Chat: %chat% | User: %nick% |"
if exist %chat%_history type %chat%_history
:list_go
ping 127.0.0.1 -n 1 -w 20 > nul
set oldtext=%text%
set /p text=<%chat%
if not "%text%" == "%oldtext%" echo %text%
goto list_go
rem ////////////////////
rem ////////////////////
rem // %2 - chat name //
rem // %3 - user nick //
rem ////////////////////
:talker
set chat=%~2
set nick=%~3
cls
call title "| Chat: %chat% | User: %nick% |"
call ::cs_in
echo (%TIME% %nick% connected)>%chat%
call ::cs_out
echo (%TIME% %nick% connected)>>%chat%_history
:talkloop
cls
echo Dear %nick%, type message to send:
set /p msg=^>
rem call ::cs_in
echo [%TIME% %nick%]: %msg%>%chat%
rem call ::cs_out
echo [%TIME% %nick%]: %msg%>>%chat%_history
goto talkloop
rem ////////////////////
rem ////////////////////
:cs_in
if exist "%chat%_cs" ping 127.0.0.1 -n 1 -w 50 > nul
set cs_value=%RANDOM%
:cs_in_loop
echo %cs_value%>%chat%_cs
set /p ret=<%chat%_cs
if "%ret%" == "%cs_value%" exit /b
ping 127.0.0.1 -n 1 -w 10 > nul
goto :cs_in_loop
rem ////////////////////
rem ////////////////////
:cs_out
del %chat%_cs
exit /b
rem ////////////////////
rem =========================================================
Чат на BAT. Сколько угодно народу.
Выложите батник в сетевую папку и оттуда запускайте с разных ПК.
Статья с тонкостями: http://k06a.blogspot.com/2009/06/blog-post_27.html
+6.9
#ifndef SOCHET_H
#define SOCHET_H
// Сдвигает самую младшую единицу в сторону младшего разряда
#define shiftLast1Right(x) ( (x-1)^((x^(x-1)) >> 2) )
// Дописывает 1 после самой младшей единицы
#define add1AfterLast1(x) ( x | ((x^(x-1))+1) >> 2 )
template<class T>
class Sochet
{
public:
T value;
//////////////////////////////////////////////////////////////////////////
Sochet():value(0) { }
Sochet(int n, int k) {
firstTurn(n, k);
}
~Sochet() {
value = 0;
}
//////////////////////////////////////////////////////////////////////////
// Первая комбинация
// В первоначальной ситуации все К единиц располагаются в старших битах
void firstTurn(int n, int k) {
value = ( ( T(1) << k ) - 1 ) << (n - k);
}
// Нахождение следующей комбинации
// Возвращает false в случае последней комбинации
bool nextTurn()
{
// Отлов последней комбинации
if (value & (value+1) == 0)
return false;
// Условие по младшему биту: 1 или 0
if (value & 1)
{
value >>= 1;
nextTurn();
value = add1AfterLast1(value << 1);
} else
value = shiftLast1Right(value);
return true;
}
}
#endif // SOCHET_H
Шаблон перебора всех сочетаний/выборок в много разрядных числах.
Пример перебираемых чисел для N=5, K=3:
11100
11010
11001
10110
10101
10011
01110
01101
01011
00111
// Код выглядит сочно(особенно дефайны), зато всё работает максимально быстро.
// Статья про этот алгоритм: http://k06a.blogspot.com/2009/04/blog-post_08.html
+86.2
with (VirNode^) do
begin
VirNode^.ImageIndex := vir.iNum;
VirNode^.Txt := vir.sAttr[1] + ' - ' + vir.sAttr[3];
end;
сначала было без with а потом забыл убрать "VirNode^." :)
+148.7
// Any fool can write code that a computer can understand. Good programmers write code that humans can understand. (C) Martin Fowler.
function changeLogo() {
var pane = document.getElementById("pane");
if(pane != null) {
pane.height = 240;
pane.width = document.body.clientWidth;
} else {
alert("it's sad, so sad...");
}
var logo = document.getElementById("logoJpg");
if(logo != null) {
logo.height = 50;
logo.width = document.body.clientWidth * 0.23;
} else {
alert(" ...it's a sad, sad situation, and it's getting more and more absurd");
}
}
Код совсем ничего, но камменты рулят