- 1
pubimbue, ate и ios
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+1
pubimbue, ate и ios
давайте ржать над крестостримами
+1
?check_trace(
begin
%% Inject some orderings to make sure the replicant
%% receives transactions in all states.
%%
%% 1. Commit some transactions before the replicant start:
?force_ordering(#{?snk_kind := trans_gen_counter_update, value := 5}, #{?snk_kind := state_change, to := disconnected}),
%% 2. Make sure the rest of transactions are produced after the agent starts:
?force_ordering(#{?snk_kind := subscribe_realtime_stream}, #{?snk_kind := trans_gen_counter_update, value := 10}),
%% 3. Make sure transactions are sent during TLOG replay:
?force_ordering(#{?snk_kind := state_change, to := bootstrap}, #{?snk_kind := trans_gen_counter_update, value := 15}),
%% 4. Make sure some transactions are produced while in normal mode
?force_ordering(#{?snk_kind := state_change, to := normal}, #{?snk_kind := trans_gen_counter_update, value := 25}),
...
Какой тест )))
+1
# PowerShell
switch ($true)
{
($firstNumber -gt $secondNumber) {Write-Output ("{0} > {1}" -F $firstNumber, $secondNumber)}
($firstNumber -eq $secondNumber) {Write-Output ("{0} == {1}" -F $firstNumber, $secondNumber)}
($firstNumber -lt $secondNumber) {Write-Output ("{0} < {1}" -F $firstNumber, $secondNumber)}
}
Интересный такой свитч-кейс (https://stackoverflow.com/questions/57063932/powershell-overriding-assignment-and-comparison-operators)
+1
#include <iostream>
template<typename T>
struct CrtpBase {
static float base_func()
{
std::cout << "CrtpBase::base_func(), " << typeid(T).name() << "::int_field == "
<< T::int_field << std::endl;
return 16.0f;
}
static inline float x = base_func();
};
struct A: public CrtpBase<A> {
void func_a()
{
base_func();
}
static inline int int_field = 16;
};
struct B : public CrtpBase<B> {
void func_b()
{
std::cout << "B::func_b(), no CrtpBase<B>::base_func() call" << std::endl;
}
};
int main()
{
A a;
a.func_a();
B b;
b.func_b();
}
[temp.inst]/2:
Unless a class template specialization is a declared specialization,
the class template specialization is implicitly instantiated when
the specialization is referenced in a context that requires a
completely-defined object type or when the completeness of the
class type affects the semantics of the program.
[temp.inst]/3:
The implicit instantiation of a class template specialization causes
(3.1) -- the implicit instantiation of the declarations, but not of the definitions, of
the non-deleted class member functions, member classes, scoped member enumerations,
static data members, member templates, and friends; and
(3.2) -- the implicit instantiation of the definitions of deleted member functions,
unscoped member enumerations, and member anonymous unions.
[temp.inst]/4:
Unless a member of a templated class is a declared specialization, the specialization
of the member is implicitly instantiated when the specialization is referenced in a
context that requires the member definition to exist or if the existence of the definition
of the member affects the semantics of the program; in particular, the initialization
(and any associated side effects) of a static data member does not occur unless the
static data member is itself used in a way that requires the definition of the static
data member to exist.
+1
namespace detail {
template<entity_event_t Event>
struct EventHasEntityStateConstructor {
// Sanity check
static_assert(static_cast<int32_t>(Event) >= 0
&& static_cast<int32_t>(Event) < ENTITY_EVENTS_COUNT);
private:
struct TwoChar {
char a, b;
};
template<typename T>
constexpr static TwoChar _check(
decltype(
T(std::declval<const entityState_t &>())
)*
);
template<typename T>
constexpr static char _check(...);
public:
constexpr inline static bool value = (sizeof(_check<EntityEvent<Event>>(nullptr)) == sizeof(TwoChar));
};
template<typename BusT, entity_event_t Event>
bool defaultEntityEventPublisher(const BusT & bus, const entityState_t & eventEntity)
{
static_assert(EventHasEntityStateConstructor<Event>::value,
"defaultEntityEventFactory<Event>() instantiated for a custom\n"
"event that does not have a (const entityState_t & eventEntity) constructor.\n"
"This should not happen (you'll get a more obscured compiler error anyway)!");
return bus.publishEmplace<EntityEvent<Event>>(eventEntity);
}
template<typename BusT, typename T, T... Is>
constexpr std::array<EntityEventPublisherPtr<BusT>, sizeof...(Is)>
createDefaultEntityEventFactories(std::integer_sequence<T, Is...>)
{
return {
[](auto i) -> EntityEventPublisherPtr<BusT> {
if constexpr (EventHasEntityStateConstructor<static_cast<entity_event_t>(i.value)>::value) {
return &defaultEntityEventPublisher<BusT, static_cast<entity_event_t>(i.value)>;
} else {
return nullptr;
}
}(std::integral_constant<T, Is>{})...
};
}
}
// An (event_number -> EntityState<event_number> 'publishing factory' function) mapping;
// if event N could not be constructed from a single entityState_t reference
// then this table would contain nullptr at the index N
template<typename BusT>
const std::array<EntityEventPublisherPtr<BusT>, ENTITY_EVENTS_COUNT> & getDefaultEntityEventsPublishers() noexcept
{
static auto factories = detail::createDefaultEntityEventFactories<BusT>(std::make_integer_sequence<int32_t, ENTITY_EVENTS_COUNT>());
return factories;
}
template<typename BusT>
EntityEventPublisherPtr<BusT> tryGetDefaultEntityEventPublisher(entity_event_t event) noexcept
{
auto eventNum = static_cast<int32_t>(event);
if (eventNum >= 0 && eventNum < ENTITY_EVENTS_COUNT) {
return getDefaultEntityEventsPublishers<BusT>()[eventNum];
} else {
return nullptr;
}
}
+1
Class HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor
https://javadoc.io/doc/org.aspectj/aspectjweaver/1.8.10/org/aspectj/weaver/patterns/HasThisTypePatternTriedToSneakInSomeGene ricOrParameterizedTypePatternMatchingStu ffAnywhereVisitor.html
+1
// https://gcc.gnu.org/onlinedocs/gcc-10.1.0/gcc/Common-Function-Attributes.html
access
access (access-mode, ref-index)
access (access-mode, ref-index, size-index)
// примеры:
__attribute__ ((access (read_only, 1))) int puts (const char*);
__attribute__ ((access (read_only, 1, 2))) void* memcpy (void*, const void*, size_t);
__attribute__ ((access (read_write, 1), access (read_only, 2))) char* strcat (char*, const char*);
__attribute__ ((access (write_only, 1), access (read_only, 2))) char* strcpy (char*, const char*);
__attribute__ ((access (write_only, 1, 2), access (read_write, 3))) int fgets (char*, int, FILE*);
В GCC 10 какой-то новый атрибут access появился, чтоб более строго что-то там гарантировать:
The access attribute enables the detection of invalid or unsafe accesses by functions to which they apply or their callers, as well as write-only accesses to objects that are never read from. Such accesses may be diagnosed by warnings such as -Wstringop-overflow, -Wuninitialized, -Wunused, and others.
The access attribute specifies that a function to whose by-reference arguments the attribute applies accesses the referenced object according to access-mode. The access-mode argument is required and must be one of three names: read_only, read_write, or write_only. The remaining two are positional arguments.
The required ref-index positional argument denotes a function argument of pointer (or in C++, reference) type that is subject to the access. The same pointer argument can be referenced by at most one distinct access attribute.
The optional size-index positional argument denotes a function argument of integer type that specifies the maximum size of the access. The size is the number of elements of the type referenced by ref-index, or the number of bytes when the pointer type is void*. When no size-index argument is specified, the pointer argument must be either null or point to a space that is suitably aligned and large for at least one object of the referenced type (this implies that a past-the-end pointer is not a valid argument). The actual size of the access may be less but it must not be more.
+1
function main() {
print("Hello", 1, false, true, parseInt("01"), parseFloat("00.1"));
}
// ASM
; ModuleID = 'LLVMDialectModule'
source_filename = "LLVMDialectModule"
target datalayout = "e-m:w-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-pc-windows-msvc"
@__true__ = internal constant [5 x i8] c"true\00"
@__false__ = internal constant [6 x i8] c"false\00"
@frmt_9481649210695450612 = internal constant [19 x i8] c"%s %d %s %s %d %f\0A\00"
@s_3144841719139014728 = internal constant [5 x i8] c"00.1\00"
@s_12300967985959445949 = internal constant [3 x i8] c"01\00"
@s_1772061916968062023 = internal constant [6 x i8] c"Hello\00"
declare i8* @malloc(i64)
declare void @free(i8*)
declare i32 @printf(i8*, ...)
declare float @atof(i8*)
declare i32 @atoi(i8*)
define void @main() !dbg !3 {
%1 = call i32 @atoi(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @s_12300967985959445949, i64 0, i64 0)), !dbg !7
%2 = call float @atof(i8* getelementptr inbounds ([5 x i8], [5 x i8]* @s_3144841719139014728, i64 0, i64 0)), !dbg !9
%3 = fpext float %2 to double, !dbg !10
%4 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([19 x i8], [19 x i8]* @frmt_9481649210695450612, i64 0, i64 0), i8* getelementptr inbounds ([6 x i8], [6 x i8]* @s_1772061916968062023, i64 0, i64 0), i32 1, i8* getelementptr inbounds ([6 x i8], [6 x i8]* @__false__, i64 0, i64 0), i8* getelementptr inbounds ([5 x i8], [5 x i8]* @__true__, i64 0, i64 0), i32 %1, double %3), !dbg !10
br label %5, !dbg !11
5: ; preds = %0
ret void, !dbg !11
}
!llvm.dbg.cu = !{!0}
!llvm.module.flags = !{!2}
Продолжение писания уе..(зачеркнуто) супер компилятора с TypeScript (JavaScript) в нативный код.
как обычно компилим просто
set LIBPATH=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\SDK\ScopeCppSDK\vc 15\VC\lib
set SDKPATH=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\SDK\ScopeCppSDK\vc 15\SDK\lib
tsc.exe --emit=llvm C:\temp\1.ts 2>1.ll
llc.exe --filetype=obj -o=out.o 1.ll
lld.exe -flavor link out.o "%LIBPATH%\libcmt.lib" "%LIBPATH%\libvcruntime.lib" "%SDKPATH%\kernel32.lib" "%SDKPATH%\libucrt.lib" "%SDKPATH%\uuid.lib"
получаетм Ехе и грузим его. и результат
=====================================
и выполнение
C:\>out.exe
Hello 1 false true 1 0.100000
+1
Просто оффтоп #16
#1: https://govnokod.ru/20162 https://govnokod.xyz/_20162
#2: https://govnokod.ru/25329 https://govnokod.xyz/_25329
#3: https://govnokod.ru/25415 https://govnokod.xyz/_25415
#4: (vanished) https://govnokod.xyz/_25472
#5: https://govnokod.ru/25693 https://govnokod.xyz/_25693
#6: (vanished) https://govnokod.xyz/_26649
#7: https://govnokod.ru/26672 https://govnokod.xyz/_26672
#8: https://govnokod.ru/26924 https://govnokod.xyz/_26924
#9: https://govnokod.ru/27072 https://govnokod.xyz/_27072
#10: https://govnokod.ru/27086 https://govnokod.xyz/_27086
#11: https://govnokod.ru/27122 https://govnokod.xyz/_27122
#12: https://govnokod.ru/27153 https://govnokod.xyz/_27153
#13: https://govnokod.ru/27159 https://govnokod.xyz/_27159
#14: https://govnokod.ru/27200 https://govnokod.xyz/_27200
#15: https://govnokod.ru/27237 https://govnokod.xyz/_27237
+1
// https://docs.docker.com/engine/api/v1.24/#create-a-container
POST /v1.24/containers/create HTTP/1.1
Content-Type: application/json
Content-Length: 12345
{
"Hostname": "",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": true,
"AttachStderr": true,
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"FOO=bar",
"BAZ=quux"
],
...
}
Ядро предоставляет сисколл execve. Execve принимает переменные окружения в виде массива строк A=B -
не знаю конкретных причин, почему так сделано, но скорее всего просто потому что писать хэшмапу под
это дело, которая еще и будет выкинута из памяти через относительно небольшое время - дело дорогое и
ненужное, плюс наверняка какой-нибудь лишний пердолинг со стеком.
https://man7.org/linux/man-pages/man2/execve.2.html
Го, "человеческий язык" с поддержкой обычных мап из коробки, ничтоже сумляшеся не замечает никакой
проблемы и заставляет пользователя передавать переменные окружения в том же формате, потому что у
языка не только синтаксис должен быть таким же тупым, как программист на нём и вообще мы же тут
делаем вид, что мы C, только лучше.
https://golang.org/pkg/os/exec/#example_Command_environment
Докер, "человеческий сервис" с HTTP API, использующим формат JSON с поддержкой обычных мап из коробки,
ничтоже сумляшеся не замечает никакой проблемы и заставляет пользователя передавать переменные
окружения в том же формате, потому что на программист на языке должен быть тупым, как этот язык.
https://docs.docker.com/engine/api/v1.24/#create-a-container
В результате мы имеем пачку долбоебов, из-за которых оперирующие (мапами / объектами / словарями / как угодно назовите)
нормальные люди должны вести себя как типичные гошники.