Каков лучший комментарий в исходном коде, с которым Вы когда-либо встречались? [закрытый]

360
задан 14 revs, 11 users 61% 17 September 2011 в 14:54
поделиться

518 ответов

Это - от старого IOCCC завоевание записи, я должен был загрузить целый архив победителей - огромные 1,4 М - и grep для нескольких фраз, которые я помнил неправильно прежде, чем найти его.

Синтаксически это - вероятно, не комментарий. Или может быть он. Я не понял его. Это определенно не имеет разделителей комментария, но это не имеет Строковых разделителей также.

C="Lint says "argument Manual isn't used."  What's that
mean?";

Никакие цены за предположение вывода от линта.

И для любопытного, та запись здесь .

0
ответ дан Miserable Variable 23 November 2019 в 00:15
поделиться
[onload_1;block=begin;when 1=0]

Some of the techinques in this template are rather obscure, just trust me, they need to be there.
OTOH a better sollution would be to create a few seperate templates and pick one in the php-script...

[onload_1;block=end]
0
ответ дан John Nilsson 23 November 2019 в 00:15
поделиться

Я только что поместил этот комментарий:

// this control (Resistance) is FUTILE! 
1
ответ дан 2 revs, 2 users 80% 23 November 2019 в 00:15
поделиться

На латыни, Abandon hope all ye who enter here от "божественной комедии Dante".

1
ответ дан 2 revs, 2 users 67% 23 November 2019 в 00:15
поделиться
try {
  dataSource.close();
}
catch (SQLException ex) {
  // Do nothing, since we're going to trash this anyway
}

, Конечно, этот вид вещи является на самом деле wtf в JDBC (или по крайней мере драйвер Oracle JDBC), поскольку это может бросить SQLExceptions при закрытии соединения...

1
ответ дан 2 revs, 2 users 60% 23 November 2019 в 00:15
поделиться

Фаворит шахты был именем переменной в части бизнес-логики школьного проекта, записанного в Java.

int StupidJava = -1;
0
ответ дан Stephen Curial 23 November 2019 в 00:15
поделиться
// Hack-er-ama
0
ответ дан Paul Suart 23 November 2019 в 00:15
поделиться

Из /System/Library/Frameworks/AppKit.framework/Versions/C/Headers/NSTextView.h:

- (void)smartInsertForString:(NSString *)pasteString replacingRange:(NSRange)charRangeToReplace beforeString:(NSString **)beforeString afterString:(NSString **)afterString;
- (NSString *)smartInsertBeforeStringForString:(NSString *)pasteString replacingRange:(NSRange)charRangeToReplace;
- (NSString *)smartInsertAfterStringForString:(NSString *)pasteString replacingRange:(NSRange)charRangeToReplace;

/* Java note: The second and third methods are the primitives and are the 
methods exposed in Java.  The first method calls the other two.  All 
Objective-C code calls the first method.  In either Objective-C or Java any 
overriding should be done for the second and third methods, not the first 
method.  This will all work out correctly with the exception of existing code 
that overrides the first method.  Existing subclasses that do this will not 
have their implementations available to Java developers. Isn't Java wonderful? */
1
ответ дан 23 November 2019 в 00:15
поделиться

Найдено в старом Perl-скрипте, который генерирует HTML:

# I would be _very_ brain farting if I said this code didn't need reviewing.
# It will make babies cry, and hair grow on your back, so please don't use it
1
ответ дан 23 November 2019 в 00:15
поделиться
double t = 0.0; /* that's generally my opinion of the diner, too. */
1
ответ дан 23 November 2019 в 00:15
поделиться

Из источника ядра Linux:

linux / include / asm-i386 / hw_irq.h:

/*
 * subtle. orig_eax is used by the signal code to distinct between
 * system calls and interrupted 'random user-space'. Thus we have
 * to put a negative value into orig_eax here. (the problem is that
 * both system calls and IRQs want to have small integer numbers in
 * orig_eax, and the syscall code has won the optimization conflict ;)
 *
 * Subtle as a pigs ear.  VY
 */
1
ответ дан 23 November 2019 в 00:15
поделиться
<cftry>
...code...
<cfcatch>
  <!--- Gobble --->
</cfcatch>
<cftry>

Это по всей базе данных моей компании. Это ColdFusion, и он просто игнорирует ошибки.

0
ответ дан 23 November 2019 в 00:15
поделиться
$dnstime = time() + 60 * 60 * 24 * 7 * 2; //how long are you staying for vacation on mars? twooo weeeeeks. give dees people air
1
ответ дан 23 November 2019 в 00:15
поделиться

От http://www.madore.org/~david/computers/callcc.html :

/* Yow!  DEMONS are flying through my NOSE! */
1
ответ дан 23 November 2019 в 00:15
поделиться
/**
 * Hexadecimal digit
 */
protected $version = -1;
1
ответ дан 23 November 2019 в 00:15
поделиться
// repopulate, slight hax (or strong assumptions :P) below
1
ответ дан 23 November 2019 в 00:15
поделиться
//this is a crap way to do this but I ran out of patience

DelButton.click(); 
1
ответ дан 23 November 2019 в 00:15
поделиться

Мне действительно больше нравится тег oh_my_gawd, чем комментарий ...

    /*
     * IOC3 is fucked fucked beyond believe ...  Don't even give the
     * generic PCI code a chance to look at it for real ...
     */
    if (cf == (PCI_VENDOR_ID_SGI | (PCI_DEVICE_ID_SGI_IOC3 b_type0_cfg_dev[slot].f[fn].c[where ^ (4 - size)];

    if (size == 1)
        res = get_dbe(*value, (u8 *) addr);
    else if (size == 2)
        res = get_dbe(*value, (u16 *) addr);
    else
        res = get_dbe(*value, (u32 *) addr);

    return res ? PCIBIOS_DEVICE_NOT_FOUND : PCIBIOS_SUCCESSFUL;

oh_my_gawd:

    /*
     * IOC3 is fucked fucked beyond believe ...  Don't even give the
     * generic PCI code a chance to look at the wrong register.
     */
    if ((where >= 0x14 && where = 0x48)) {
        *value = 0;
        return PCIBIOS_SUCCESSFUL;
    }
1
ответ дан 23 November 2019 в 00:15
поделиться
TextBox1.Text = TextBox1.Text; //Point less yes, who writes this crap?
1
ответ дан 23 November 2019 в 00:15
поделиться

I was doing a database in Access, very simple thing - at least it was supposed to be at the start or I would have done it in Delphi. The client wanted to be able to get the customer info out of the database but they would not enter enough information to reliably identify the customer. I told them to use the phone number as the key as each customer (the way they worked, not for everyone) would have a different number. After a few frantic calls from them, (It's not working we can't enter the customer) I discovered that they were too lazy to look up the phone numbers from their old system and were trying to enter all the numbers they did not know as "n/a". In trying to sort this out for them I ended up with a lot of checking loops in the code and had the comment beside one outcome "This should never be reached if they do what they are supposed to do!!!!!!!!!"

They also asked me once "How can we find the right customer even if we put in the wrong address?" And all for peanuts.

0
ответ дан 23 November 2019 в 00:15
поделиться

Повторное употребление собственного собачьего корма: у нас на рабочем месте один и тот же термин (да, только потому, что я его ввел). Мой код усыпан комментариями, которые говорят «TODO» и указывают на то, что должно быть сделано в конце концов, но комментарий «DOGFOOD» (оба ключевых слова всегда в начале комментария, во всех заглавных буквах) означает что-то, что должно быть сделано до того, как эта программа может быть использована даже внутри страны. Это удобная вещь для поиска, так как слово «dogfood» никогда не появится в строке в кавычках - если это произойдет, я всегда могу просто сказать «собачья еда» или что-то в этом роде - так что даже поиск без учета регистра произойдет с правильными результатами.

Относительно обнуления аккумулятора: I ' мы сделали то же самое при программировании Intel 80x86 (я начал с 8086 и перешел оттуда в современные Pentiums). XORing регистра с собой - самый быстрый и надежный способ очистить его. Для использования «MOV AX, 0» требуется три байта (код операции и два байта буквального 16-битного нуля), тогда как «XOR AX, AX» - только два; это еще более заметно с расширенными регистрами 386 и выше, где «MOV EAX, 0» требует пять байтов (четыре байта 32-битного нуля). Мой компилятор C / C ++ всегда обнуляет регистры таким образом, поэтому я предположил бы, что это все еще лучший способ (хотя я давно не изучал таблицы синхронизации кодов операций, и, вероятно, XOR reg, reg и MOV reg, imm занимают один такт) .

0
ответ дан 23 November 2019 в 00:15
поделиться

Хорошо написанный Лисп - один из самых простых для чтения языков, и мне это нравится. Но плохо написанный Lisp может быть кошмаром намного хуже, чем плохая Java и т. Д.

Здесь нам нужно создать «групповой файл», если существует 3 варианта исходного файла с суффиксами a, b и c. Я пытался отследить странную ошибку, когда мы получали ненужные групповые файлы ...

  (let ((varianta (format nil "~aa" problem))
        (variantb (format nil "~ab" problem))
        (variantc (format nil "~ac" problem)))
    ;;if the A and B variants exist, create a group file
    ;;(why not just check for a? I don't know, this just feels right)
    (when (and (probe-file varianta)
               (probe-file variantb))
      ...)))

Ошибка: 1, Гут: 0.

Видимо, никому не пришло в голову, что кто-то написал это, возможно, проверяя все три варианты были бы хорошей идеей. Конечно, это была ошибка, которую я обнаружил через десять лет после того, как этот код был изначально написан (он предшествует первому журналу SVN).

0
ответ дан 23 November 2019 в 00:15
поделиться

При кодировании приложений MAPPER у нас было некоторых стандартов, и одним из них было то, что во всем комплекте использовался список стандартных переменных. Один из них - «V43» всегда использовался для фамилии. Так что представьте мое раздражение, когда только комментарий в большом загадочном куске кода MAPPER, который меня попросили исправить, был:

Here V43 contains the Surname
1
ответ дан 23 November 2019 в 00:15
поделиться
[vrk:Cloud ID="cTags" runat="server" DataTextField="Tag" DataWeightField="Total"
    Width="100%" DataHrefField="Tag" DataHrefFormatString="~/tags.aspx?tag={0}"]
[/vrk:Cloud]

[!--if anybody would like to change the control's color contact with FLORJON--]
1
ответ дан 23 November 2019 в 00:15
поделиться

Сначала в начале Обновления к огромному объекту:

/*General note to all who tread in the <ObjectName>() code...
 * The SetOriginals() method from the BaseEntity class should be called (and only called) right after the Get() method
 * call as seen above.  Calling the SetOriginals method elsewhere will result in bugs and all kinds of other nasty suprises.
 */

Затем, после примерно 200 строк логики, чтобы обновить объект:

//Attempt to explain this confusing mess of code:
//First time you save an actual absence this is what happens:
//0. The first save saves to the <TableName> table (among other things). (Fig. A)
//1. The <CalculationMethod> method is called next which inserts to the <OtherTableName> table. 
//(This is the table that keeps track of credits to the case.) (Fig. B)
//2. So then you have to call <UpdateCalculations> to move the <TableName> records to the <ThirdTableName> table. (Fig. C)
//3. Then you go back and run calculations since you have the debits table (<ThirdTableName>) populated. (Fig D.)
//4. Then a final save to save the calculations back to the case. (Fig. E)
//Yeah, I know what you're thinking:  this sucks. 10/01/07 XXX

И разработчик был прав ... Это отстой, ЖЕСТКО!

1
ответ дан 23 November 2019 в 00:15
поделиться
// Holy moses! I've never seen anything so ridiculous in all my life. 

// Why do we need to query the AlarmIDs table twice.

// Please tell me sir; I would really like to know. 

// This like all the other services have been mangled

// to the point where they are nearly impossible to determine what kind of side affects might occur.

// I am making the smallest changes I can to this code. 

// The GetAlarmId method gets the alarm id from the AlarmIDs table.

// Novel idea, why didn't we query for the values be get below all in the same place.

// This should be changed, but right now it will have to remain as is due to time constraints.

// This like all other services really don't do anything fantastically hard, but after the original coders got

// done with them; they are difficult to work with and have an acceptable comfort level.
1
ответ дан 23 November 2019 в 00:15
поделиться
// This interface defines method signatures<br>
interface IWhatever { ... }
1
ответ дан 23 November 2019 в 00:15
поделиться

It» Как правило, рекомендуется использовать только те ошибки, которые вас интересуют. В случае с shutil.rmtree , вероятно, OSError :

>>> shutil.rmtree("/fake/dir")
Traceback (most recent call last):
    [...]
OSError: [Errno 2] No such file or directory: '/fake/dir'

Если вы хотите игнорировать эту ошибку в молчании , вы бы сделали:

try:
    shutil.rmtree(path)
except OSError:
    pass

Почему? Скажем, вы (как-то) случайно передали функции целое число вместо строки, например:

shutil.rmtree(2)

Это выдаст ошибку «TypeError: приведение к Unicode: нужна строка или буфер, int найдено» - вы, вероятно, не хочу игнорировать это, что может быть трудно отладить.

Если вы определенно хотите игнорировать все ошибки, поймайте Exception , а не голое за исключением: заявление. Опять же, почему?

Не указав исключение, перехватывает каждое исключение , включая исключение SystemExit , которое, например, sys.exit () использует:

1
ответ дан 23 November 2019 в 00:15
поделиться

Технически это не комментарий, а кодирование чего-то в 2 часа ночи или около того:

consent = False

... эта переменная никогда не используется снова НИКОГДА и появляется в начале цикла прослушивания для гнездо.

1
ответ дан 23 November 2019 в 00:15
поделиться
//Maybe you should make anyone knows your code's purpose. 
1
ответ дан 23 November 2019 в 00:15
поделиться
Другие вопросы по тегам:

Похожие вопросы: