- 1
IT Оффтоп #86
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
0
IT Оффтоп #86
#56: https://govnokod.ru/26862 https://govnokod.xyz/_26862
#57: https://govnokod.ru/26890 https://govnokod.xyz/_26890
#58: https://govnokod.ru/26916 https://govnokod.xyz/_26916
#59: https://govnokod.ru/26934 https://govnokod.xyz/_26934
#60: https://govnokod.ru/26949 https://govnokod.xyz/_26949
#61: https://govnokod.ru/26980 https://govnokod.xyz/_26980
#62: https://govnokod.ru/26999 https://govnokod.xyz/_26999
#63: https://govnokod.ru/27004 https://govnokod.xyz/_27004
#64: https://govnokod.ru/27020 https://govnokod.xyz/_27020
#65: https://govnokod.ru/27027 https://govnokod.xyz/_27027
#66: https://govnokod.ru/27040 https://govnokod.xyz/_27040
#67: https://govnokod.ru/27049 https://govnokod.xyz/_27049
#68: https://govnokod.ru/27061 https://govnokod.xyz/_27061
#69: https://govnokod.ru/27071 https://govnokod.xyz/_27071
#70: https://govnokod.ru/27097 https://govnokod.xyz/_27097
#71: https://govnokod.ru/27115 https://govnokod.xyz/_27115
#72: https://govnokod.ru/27120 https://govnokod.xyz/_27120
#73: https://govnokod.ru/27136 https://govnokod.xyz/_27136
#74: https://govnokod.ru/27160 https://govnokod.xyz/_27160
#75: https://govnokod.ru/27166 https://govnokod.xyz/_27166
#76: https://govnokod.ru/27168 https://govnokod.xyz/_27168
#77: https://govnokod.ru/27186 https://govnokod.xyz/_27186
#78: https://govnokod.ru/27219 https://govnokod.xyz/_27219
#79: https://govnokod.ru/27254 https://govnokod.xyz/_27254
#80: https://govnokod.ru/27270 https://govnokod.xyz/_27270
#81: https://govnokod.ru/27280 https://govnokod.xyz/_27280
#82: https://govnokod.ru/27284 https://govnokod.xyz/_27284
#83: https://govnokod.ru/27296 https://govnokod.xyz/_27296
#84: https://govnokod.ru/27336 https://govnokod.xyz/_27336
#85: https://govnokod.ru/27381 https://govnokod.xyz/_27381
+1
INTERRUPT_TABLE section:
00> FF FF | . .
02> 9F 00 | . .
DATA section:
32> 48 65 6C 6C 6F 20 77 6F | Hello.wo
3A> 72 6C 64 21 00 00 00 00 | rld . . . . .
42> 00 00 00 00 00 00 00 00 | . . . . . . . .
4A> 00 00 00 00 00 00 00 00 | . . . . . . . .
_START section:
8F> 9B 00 32 00 PUSH 32
93> 18 00 00 00 INT 0
97> 18 00 01 00 INT 1
9B> 94 40 01 00 ADD %B 1
EXIT interrupt:
9F> 81 40 16 E8 MOV %B E816
A3> 20 00 00 00 RET
RUNFLOW:
8F> 9B 00 32 00 PUSH 32
93> 18 00 00 00 INT 0 DEBUG OUTPUT: Hello world!
97> 18 00 01 00 INT 1
9F> 81 40 16 E8 MOV %B E816
A3> 20 00 00 00 RET
9B> 94 40 01 00 ADD %B 1
HALT SEQUENCE REACHED: 0xE817
Закодил свою виртуальную машину и ассемблер под неё.
Заспидранил Hello world за неделю.
https://pastebin.com/NmLEuGMU
0
#include <cstdio>
template<size_t Len>
struct Literal
{
constexpr static size_t StrLen = Len;
char m_data[Len];
constexpr Literal(const char (&data)[Len])
{
for (size_t i = 0; i < Len; ++i)
m_data[i] = data[i];
}
};
template<Literal Lit>
void withString()
{
printf("%zu %s\n", Lit.StrLen, Lit.m_data);
}
int main()
{
withString<"foobar">();
}
Какой багор )))
https://i.imgur.com/1q9UfVW.png
0
// Define the man site module
define(function(require) {
// Require function that runs when button is clicked
var run = require('./run').run;
// Where the application starts its work
var genTextButton = document.getElementById("button-gen-text");
genTextButton.onclick = run;
});
define(function(require) {
// Require value error
var ValueError = require('./errors/value_errors').ValueError;
// Require EmptyListError
var EmptyListError = require('./errors/property_errors').EmptyListError;
// Require functions that returns data for text generation
var getData = require('./utils/get_data');
var getTextLength = getData.getTextLength;
var getTemplateList = getData.getTemplateList;
var getWordList = getData.getWordList;
var getStyleOption = getData.getStyleOption;
// Require function for setting output text
var makeText = require('./utils/set_text');
// Require function for validating form and validate form
var validateForm = require('./utils/validateForm');
validateForm({
formId : 'form-text-gen',
inputErrorClass : 'input-error',
formInvalidClass : 'form-invalid'
});
// Runs tasks for text generation
var run = function() {
try {
var textLength = getTextLength();
var templateList = getTemplateList();
var wordList = getWordList();
var styleOption = getStyleOption();
makeText({
styleOption : styleOption,
textLength : textLength,
templateList : templateList,
wordList : wordList
});
} catch (error) {
if (error instanceof ValueError) {
console.log(error.stack);
} else if (error instanceof EmptyListError) {
console.log(error.stack);
} else {
throw error;
}
}
}
return {
run : run
}
});
Божественная кнопка
+1
vector<int> res;
...
for (int i = 0; i < res.size(); i++) {
printf("%d%c", res[i], " \n"[i + 1 == res.size()]);
}
Решил вспомнить как олимпиадные задачки решать.
+1
%% Generates a Normal-distributed random variable using Box-Muller method
%% from: https://github.com/basho/basho_stats/blob/develop/src/basho_stats_rv.erl
-spec rnd_normal(integer(), integer()) -> non_neg_integer().
rnd_normal(Mean, Sigma) ->
Rv1 = random:uniform(),
Rv2 = random:uniform(),
Rho = math:sqrt(-2 * math:log(1-Rv2)),
abs(trunc(Rho * math:cos(2 * math:pi() * Rv1) * Sigma + Mean)).
Это норма.
0
function display(id:number, name:string)
{
print("Id = " + id + ", Name = " + name);
}
function main() {
display(1, "asd");
}
А ваш говно компайлер умеет так делать?
>> Output:
Id = 1., Name = asd
0
template<typename T>
struct method_traits;
template<typename T, typename RetT, typename... Args>
struct method_traits<RetT(T::*)(Args...)> {
using this_type = T;
using ret_type = RetT;
template<size_t ArgIdx>
using arg_type = typename std::tuple_element<ArgIdx, std::tuple<Args...>>::type;
static constexpr size_t args_count = sizeof...(Args);
static constexpr bool is_const = false;
static constexpr bool is_lvalue = false;
static constexpr bool is_rvalue = false;
};
template<typename T, typename RetT, typename... Args>
struct method_traits<RetT(T::*)(Args...) const> : public method_traits<RetT(T::*)(Args...)> {
static constexpr bool is_const = true;
};
template<typename T, typename RetT, typename... Args>
struct method_traits<RetT(T::*)(Args...) &> : public method_traits<RetT(T::*)(Args...)> {
static constexpr bool is_lvalue = true;
};
template<typename T, typename RetT, typename... Args>
struct method_traits<RetT(T::*)(Args...) &&> : public method_traits<RetT(T::*)(Args...)> {
static constexpr bool is_rvalue = true;
};
template<typename T, typename RetT, typename... Args>
struct method_traits<RetT(T::*)(Args...) const &> : public method_traits<RetT(T::*)(Args...)> {
static constexpr bool is_const = true;
static constexpr bool is_lvalue = true;
};
template<typename T, typename RetT, typename... Args>
struct method_traits<RetT(T::*)(Args...) const &&> : public method_traits<RetT(T::*)(Args...)> {
static constexpr bool is_const = true;
static constexpr bool is_rvalue = true;
};
А вдруг в новом стандарте ещё модификаторов в тип завезут? Страшня стало...
0
// https://habr.com/ru/company/yandex_praktikum/blog/555704/
// Стандарт C++20: обзор новых возможностей C++. Часть 2 «Операция ''Космический Корабль''»
// Предположим, вы определили структуру, содержащую одно число:
struct X {
int a;
};
// Мы хотим сделать так, чтобы значения этой структуры можно было сравнивать друг с другом.
// Для этого придётся написать шесть операций:
bool operator== (X l, X r) { return l.a == r.a; }
bool operator!= (X l, X r) { return l.a != r.a; }
bool operator>= (X l, X r) { return l.a >= r.a; }
bool operator<= (X l, X r) { return l.a <= r.a; }
bool operator< (X l, X r) { return l.a < r.a; }
bool operator> (X l, X r) { return l.a > r.a; }
// А теперь представьте, что мы хотим сравнивать элементы этой структуры не только между собой,
// но также с числами int. Количество операций возрастает с шести до 18:
bool operator== (X l, int r) { return l.a == r; }
bool operator!= (X l, int r) { return l.a != r; }
bool operator>= (X l, int r) { return l.a >= r; }
bool operator<= (X l, int r) { return l.a <= r; }
bool operator< (X l, int r) { return l.a < r; }
bool operator> (X l, int r) { return l.a > r; }
bool operator== (int l, X r) { return l == r.a; }
bool operator!= (int l, X r) { return l != r.a; }
bool operator>= (int l, X r) { return l >= r.a; }
bool operator<= (int l, X r) { return l <= r.a; }
bool operator< (int l, X r) { return l < r.a; }
bool operator> (int l, X r) { return l > r.a; }
// Что делать? Можно позвать штурмовиков. Их много, и они быстро напишут 18 операций.
// Или воспользоваться «космическим кораблём». Эту новую операцию в C++ называют
// «космический корабль», потому что она на него похожа: <=>. Более формальное название
// «трёхстороннее сравнение» фигурирует в документах Стандарта.
А можно добавить гомоиконность, которой можно наметушить не только какой-то там космический корабль (ради которого в крестокомпиляторах надо синтаксический анализатор менять, чтоб добавить новое синтаксиальное говно для этого <=>), а хоть целую, блядь, эскадрилью космических кораблей, которая работает не только для "больше меньше равно", но и для любой вообразимой поебени
Но крестушкам конечно привычней добавить какой-то ad-hoc хуиты для частных случаев.
+1
// Define the module
define(function(require) {
// Require empty list error
var EmptyListError = require('../errors/property_errors').EmptyListError;
// Character-rank list class
function WeightedList(/* ...keys */) {
this._total = 0;
this._generateList.apply(this, arguments);
}
WeightedList.prototype._generateList = function() {
var collection;
if (typeof arguments[0] == 'object') {
collection = arguments[0];
} else {
collection = arguments;
}
for (var i = 0; i < collection.length; i++) {
this[collection[i]] = this[collection[i]] === undefined ? 1 : this[collection[i]] + 1;
this._total++;
}
}
WeightedList.prototype.getRandomKey = function() {
if (this._total < 1)
throw new EmptyListError();
var num = Math.random();
var lowerBound = 0;
var keys = Object.keys(this);
for (var i = 0; i < keys.length; i++) {
if (keys[i] != "_total") {
if (num < lowerBound + this[keys[i]] / this._total) {
return keys[i];
}
lowerBound += this[keys[i]] / this._total;
}
}
return keys[keys.length - 1];
};
WeightedList.prototype.increaseRank = function(key) {
if (key !== undefined && key != "_total") {
if (this[key] !== undefined) {
this[key]++;
} else {
this[key] = 1;
}
this._total++;
}
};
WeightedList.prototype.clearRanks = function() {
var keys = Object.keys(this);
for (var i = 0; i < keys.length; i++) {
if (keys[i] != "_total") {
this._total -= this[keys[i]] - 1;
this[keys[i]] = 1;
}
}
};
return WeightedList;
});
Вот почему я за четкое разделение объектов/структур и хэшей (ассоциативных массивов).