- 1
- 2
- 3
if err != nil {
return nil, err
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+3
if err != nil {
return nil, err
}
Как же заебало
0
interface F1 {
a: number;
a2: boolean;
}
interface F2 {
b: string;
b2: number;
}
type t = F1 & F2 & { c: number };
interface t2 extends F1, F2 {
c: number;
}
type tt = { a: boolean };
type tt2 = { b: number };
type tt3 = { c: string };
type r = tt & tt2 & tt3;
function main() {
const f1: F1 = { a: 10.0, a2: true };
print(f1.a, f1.a2);
const f2: F2 = { b: "Hello1", b2: 20.0 };
print(f2.b, f2.b2);
const a: t = { a: 10.0, a2: true, b: "Hello", b2: 20.0, c: 30.0 };
print(a.a, a.a2, a.b, a.b2);
const b: t2 = { a: 10.0, a2: true, b: "Hello", b2: 20.0, c: 30.0 };
print(b.a, b.a2, b.b, b.b2, b.c);
const c: r = { a: true, b: 10.0, c: "Hello" };
print(c.a, c.b, c.c);
print("done.");
}
я вам тут conjunctions наговнокодил.... а нужен дампик?
0
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
typedef struct
{
int32_t x;
int32_t y;
} coord;
coord stack[1000000] = {{0,0}};
size_t stack_end = 1;
int checkstack(coord in)
{
for(size_t i = 0; i < stack_end; i++)
{
if((stack[i].x == in.x) && (stack[i].y == in.y))
{
return 0;
}
}
stack[stack_end] = in;
stack_end += 1;
return 1;
}
void consume_char(char ch, coord *c, uint32_t *sum)
{
switch( ch )
{
case '>':
c->x += 1;
break;
case '<':
c->x -= 1;
break;
case '^':
c->y += 1;
break;
case 'v':
c->y -= 1;
break;
default:
printf("ERROR!!");
exit(-1);
}
*sum += checkstack(*c);
}
const char *arr = "^><^>>>^<^v<v^^vv^><<^.....";
int main(void)
{
const char *arr_ptr = arr;
coord crd = {0,0};
uint32_t sum = 1;
while (*arr_ptr != '\0')
{
//printf("test\n");
consume_char(*arr_ptr, &crd, &sum);
arr_ptr++;
}
printf("%" PRIu32 "\n", sum);
return EXIT_SUCCESS;
}
Решил от нехуй делать попроходить https://adventofcode.com/
Вот например https://adventofcode.com/2015/day/3
−4
Гритингс, мои будущие жертвы!..
Лысое Хуйло пытается насильно колоть и пичкать лекарствами своих агнцев - то есть, Вас, в надежде спасти свою жопу от импичмента - а он неминуем.
Странно, но с началом вакцинации мор только усилился.
−5
В бота добавлены 2 новые фичи:
- можно писать сообщения без reply, тогда появятся кнопки в какой оффтоп запостить
- бота можно добавлять в группы*, и если кто-то на ваш комментарий отвечает - срабатывает mention
Ссылка на бота - https://t.me/GovnokodBot
А также подписывайтесь на канал Говнокода в телеграме: https://t.me/GovnokodChannel
* в группу 1*1 с ботом можно, на группах больше не тестировал
0
Хрюкни #21
._ __,
|\,../'\
,'. . `.
.-- '`.
( `' , ;
,`--' _, ,'\
,`.____ `.
/ `, |
' \, '
| / /`,
`, . ,` ./ |
' `. ,' |;,' ,@
______| | _________,_____jv______
`. `. ,'
,'_,','_,
`' `'
#1: (vanished) https://govnokod.xyz/_26863
#2: (vanished) https://govnokod.xyz/_26868
#3: https://govnokod.ru/26881 https://govnokod.xyz/_26881
#4: https://govnokod.ru/26896 https://govnokod.xyz/_26896
#5: https://govnokod.ru/26928 https://govnokod.xyz/_26928
#6: (vanished) https://govnokod.xyz/_26952
#7: https://govnokod.ru/26955 https://govnokod.xyz/_26955
#8: https://govnokod.ru/27043 https://govnokod.xyz/_27043
#9: https://govnokod.ru/27175 https://govnokod.xyz/_27175
#10: https://govnokod.ru/27472 https://govnokod.xyz/_27472
#11: https://govnokod.ru/27517 https://govnokod.xyz/_27517
#12: https://govnokod.ru/27636 https://govnokod.xyz/_27636
#13: (vanished) https://govnokod.xyz/_27711
#14: https://govnokod.ru/27713 https://govnokod.xyz/_27713
#15: https://govnokod.ru/27721 https://govnokod.xyz/_27721
#16: https://govnokod.ru/27722 https://govnokod.xyz/_27722
#17: https://govnokod.ru/27723 https://govnokod.xyz/_27723
#18: https://govnokod.ru/27724 https://govnokod.xyz/_27724
#19: https://govnokod.ru/27726 https://govnokod.xyz/_27726
#20: https://govnokod.ru/27727 https://govnokod.xyz/_27727
0
https://250bpm.com/blog:36/
> At that point every semi-decent programmer curses spaghetti code in general and the author of the function in particular and embarks on the task of breaking it into managable chunks, trying to decompose the problem into orthogonal issues, layer the design properly, move the common functionality into base classes, create convenient and sufficiently generic extension points et c.
<…>
It turns out that the 1500-line function was parsing a network protocol. It is a 30-year old, complex and convoluted Behemoth of a protocol, defined by many parties fighting over the specification, full of compromises and special cases, dragged through multiple standardisation bodies and then anyway slightly customised by each vendor.
<...>
Unfortunately, it turns out that the tweak intersects the boundary between two well-defined components in the implementation. The right thing to do would be to re-think the architecture of the parser and to re-factor the codebase accordingly. <
Вот так вот. Не стоит спешить любую портянку из 100+ строк кода называть "спагетти-кодом". Код может быть функцией микроконтроллера в котором вызов функции достаточно дорогой по памяти/времени, сложным алгоритмом и пр. Спагетти - это про организацию кода. Монолитный (но хорошо мапящийся на домен) код понять проще, чем солянку из функций, классов и пр. которые решают непонятно какую задачу (это и есть спагетти-код). Алсо https://en.wikipedia.org/wiki/Wikipedia:Chesterton%27s_fence
−1
#!/usr/bin/python
import sys
cache = {}
def count(start, end):
if start < end:
if start not in cache:
cache[start] = count(start + 1, end) + count(start * 2, end) + count(start ** 2, end)
return cache[start]
elif start == end:
return 1
else:
return 0
print(count(int(sys.argv[1]), int(sys.argv[2])))
Подсчитать количество путей из a в b с помощью прибавления единицы, умножения на 2 и возведения в квадрат
Чем формально ограничены возможности преобразовать рекурсию в хвостовую? Вот такое ведь не преобразовать?
+2
def export_to_csv(model, fields=None, related_models=[]):
def export(request):
meta = model._meta
queryset = model.objects.all()
if fields is not None:
field_names = fields
elif 'Shops' in related_models and 'Spots' in related_models:
field_names = [field.name for field in Shops._meta.fields] +\
[field.name for field in Spots._meta.fields]
elif 'Products' in related_models and 'Spots' in related_models:
field_names = [field.name for field in Products._meta.fields] +\
[field.name for field in Spots._meta.fields]
else:
field_names = []
for field in meta.fields:
if not field.name in FORBIDDEN_FIELDS:
field_names.append(field.name)
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta)
response.write(u'\ufeff'.encode('utf8'))
writer = csv.writer(response, delimiter=',', lineterminator='\n', quoting=csv.QUOTE_ALL, dialect='excel')
writer.writerow(field_names)
if len(related_models) == 0:
for obj in queryset:
row = writer.writerow([getattr(obj, field) for field in field_names])
elif 'Shops' in related_models and 'Spots' in related_models:
shops_fields = [field.name for field in Shops._meta.fields]
contact_fields = [field.name for field in Spots._meta.fields]
for obj in queryset:
row = []
if obj.Shops is not None:
row += [getattr(obj.Shops, field) for field in shops_fields]
else:
row += ['' for field in shops_fields]
if obj.Contact is not None:
row += [getattr(obj.Contact, field) for field in contact_fields]
else:
row += ['' for field in contact_fields]
writer.writerow(row)
elif 'Products' in related_models and 'Spots' in related_models:
products_fields = [field.name for field in Products._meta.fields]
contact_fields = [field.name for field in Spots._meta.fields]
for obj in queryset:
row = []
if obj.Products is not None:
row += [getattr(obj.Products, field) for field in products_fields]
else:
row += ['' for field in products_fields]
if obj.Contact is not None:
row += [getattr(obj.Contact, field) for field in contact_fields]
else:
row += ['' for field in contact_fields]
writer.writerow(row)
return response
return export
В юности нагородила вот такую портянку для экспорта в csv связных между собой таблиц. Связка данных на уровне DAO-шки (в терминологии Джанго - Managers)? Пфф... Только инжект if-else с копипастой связки данных, только хардкор!
0
type NetworkLoadingState = {
state: "loading";
};
type NetworkFailedState = {
state: "failed";
code: number;
};
type NetworkSuccessState = {
state: "success";
response: {
title: string;
duration: number;
summary: string;
};
};
type NetworkState =
| NetworkLoadingState
| NetworkFailedState
| NetworkSuccessState;
function logger(state: NetworkState): string {
switch (state.state) {
case "loading":
return "Downloading...";
case "failed":
// The type must be NetworkFailedState here,
// so accessing the `code` field is safe
return `Error ${state.code} downloading`;
case "success":
return `Downloaded ${state.response.title} - ${state.response.summary}`;
default:
return "<error>";
}
}
function main() {
print(logger({ state: "loading" }));
print(logger({ state: "failed", code: 1.0 }));
print(logger({ state: "success", response: { title: "title", duration: 10.0, summary: "summary" } }));
print(logger({ state: "???" }));
print("done.");
}
Ура... радуйтесь.... я вам еще говнокодца поднадкинул... ну и перекопал же говна в коде что бы это сделать. Дампик тут.. https://pastebin.com/u7XZ00LV Прикольно получается если скомпилить с оптимизацией то нихрена от кода не остается. и результат работы
C:\temp\MLIR_to_exe>1.exe
Downloading...
Error 1 downloading
Downloaded title - summary
<error>
done.