- 1
https://github.com/oskusalerma/trelby/issues/85
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+1
https://github.com/oskusalerma/trelby/issues/85
Сорян за пост-ссылку, но я тут валяюсь под столом просто.
Есть тулза для написания сценариев (для чего только нет тулзы, правда?). Она опенсурсная и при этом выглядит не как говно. Но, когда начинаешь её щупать, ВНЕЗАПНО оказывается, что буквы кириллицы в ней тупо не набираются. Лезешь в FAQ, там лежит ссылка на issue из поста. А уже там просто сказка!
Короч, автор примерно в 2007 году сходил почитал спеку пдф, обнаружил, что "PDF spec is oriented towards Latin-1" и решил, что это даёт ему моральное право забить болт на Unicode, а заодно utf-8 и унтерменш, которые не осилили самый тривиальный сабсет латиницы.
В 2012-ом после, судя по всему, многочисленных недоумённых вопросов автор снова появился на горизонте с тикетом на гитхабе и объяснениями в духе "Unicode нет и не будет, потому что не для тебя моя черешня цвела". Цитата для понимания майндсета чувака: "That's how it was 5 years ago anyway when I last looked at it; maybe the spec has improved since then?"
В общем, выглядело так, будто дядя устал и решил, что пора бы всю эту хуйню переложить на чужие хрупкие плечи, у нас тут опенсурс тем более и все дела.
Но, когда в 2015-ом году появился некий анон с предложением все починить и даже какими-то наработками, автор ему сказал, что иди сука гоняй тесты (видимо, руками, потому что CI настроить он тоже не смог) на всех платформах, а то, вишь, "the old "I'll do the fun bits and let others do the boring bits" strategy. Good luck with that."
Короч чуваки ещё немного поспорили с этим аутистом, после чего съебались в туман, а тулза так кириллицу и не поддерживает.
Смешно и грустно.
+3
template<typename T>
concept Addable = requires (T x) { x + x; }; // requires-expression
template<typename T> requires Addable<T> // requires-clause, not requires-expression
T add(T a, T b) { return a + b; }
все решено.. перехожу писать код на "конецепты"
+1
private IDictionary<string, Value> valueIndex;
...
var result = this.valueIndex
.Where(v => v.Key == prefix + hashCode.ToString())
.Select(v => new
{
path = v.Value.Path,
field = v.Value.Field
})
.FirstOrDefault();
Трушный способ достать значение из словаря.
В словаре 10000 записей, за каждой полезут хотя бы раз
0
IT Оффтоп #45
#11: (vanished) https://govnokod.xyz/_25436
#12: (vanished) https://govnokod.xyz/_25471
#13: (vanished) https://govnokod.xyz/_25590
#14: https://govnokod.ru/25684 https://govnokod.xyz/_25684
#15: https://govnokod.ru/25694 https://govnokod.xyz/_25694
#16: https://govnokod.ru/25725 https://govnokod.xyz/_25725
#17: https://govnokod.ru/25731 https://govnokod.xyz/_25731
#18: https://govnokod.ru/25762 https://govnokod.xyz/_25762
#19: https://govnokod.ru/25767 https://govnokod.xyz/_25767
#20: https://govnokod.ru/25776 https://govnokod.xyz/_25776
#21: https://govnokod.ru/25798 https://govnokod.xyz/_25798
#22: https://govnokod.ru/25811 https://govnokod.xyz/_25811
#23: https://govnokod.ru/25863 https://govnokod.xyz/_25863
#24: https://govnokod.ru/25941 https://govnokod.xyz/_25941
#25: https://govnokod.ru/26026 https://govnokod.xyz/_26026
#26: https://govnokod.ru/26050 https://govnokod.xyz/_26050
#27: https://govnokod.ru/26340 https://govnokod.xyz/_26340
#28: https://govnokod.ru/26372 https://govnokod.xyz/_26372
#29: https://govnokod.ru/26385 https://govnokod.xyz/_26385
#30: https://govnokod.ru/26413 https://govnokod.xyz/_26413
#31: https://govnokod.ru/26423 https://govnokod.xyz/_26423
#32: https://govnokod.ru/26440 https://govnokod.xyz/_26440
#33: https://govnokod.ru/26449 https://govnokod.xyz/_26449
#34: https://govnokod.ru/26456 https://govnokod.xyz/_26456
#35: https://govnokod.ru/26463 https://govnokod.xyz/_26463
#36: https://govnokod.ru/26508 https://govnokod.xyz/_26508
#37: https://govnokod.ru/26524 https://govnokod.xyz/_26524
#38: https://govnokod.ru/26539 https://govnokod.xyz/_26539
#39: https://govnokod.ru/26556 https://govnokod.xyz/_26556
#40: https://govnokod.ru/26568 https://govnokod.xyz/_26568
#41: https://govnokod.ru/26589 https://govnokod.xyz/_26589
#42: https://govnokod.ru/26600 https://govnokod.xyz/_26600
#43: https://govnokod.ru/26604 https://govnokod.xyz/_26604
#44: https://govnokod.ru/26627 https://govnokod.xyz/_26627
+3
class Person {
protected name: string;
constructor(name: string) { this.name = name; }
}
class Employee extends Person {
private department: string;
constructor(name: string, department: string) {
super(name);
this.department = department;
}
public get ElevatorPitch() {
return `Hello, my name is ${this.name} and I work in ${this.department}.`;
}
}
const howard = new Employee("Howard", "Sales");
console.log(howard.ElevatorPitch);
//===============================================>>>>>>>>>>>>>>>>>>
#ifndef TEST_H
#define TEST_H
#include "core.h"
using namespace js;
class Person;
class Employee;
class Person : public object, public std::enable_shared_from_this<Person> {
public:
string name;
Person(string name);
};
class Employee : public Person, public std::enable_shared_from_this<Employee> {
public:
string department;
Employee(string name, string department);
virtual any get_ElevatorPitch();
Employee(string name);
};
extern std::shared_ptr<Employee> howard;
#endif
#include "test.h"
using namespace js;
Person::Person(string name) {
this->name = name;
}
Employee::Employee(string name, string department) : Person(name) {
this->department = department;
}
any Employee::get_ElevatorPitch()
{
return "Hello, my name is "_S + this->name + " and I work in "_S + this->department + "."_S;
}
Employee::Employee(string name) : Person(name) {
}
std::shared_ptr<Employee> howard = std::make_shared<Employee>("Howard"_S, "Sales"_S);
void Main(void)
{
console->log(howard->get_ElevatorPitch());
}
int main(int argc, char** argv)
{
Main();
return 0;
}
Было делать нехрен в жизни и решил наговнокодить транспайлер с TypeScript в С++
https://github.com/ASDAlexander77/TypeScript2Cxx
0
Срочно нужна помощь с засылкой на хабр!
Желательно перед этим почитать от того, что не пропустит анальная модерация и сектанты.
Предложения так же жду в комментах. По тексту и в целом.
https://tsar1997.blogspot.com/2020/05/blog-post_54.html
Исходник пасты - просьба кидать патчи. Позже зашлю на хабр.
https://pastebin.com/raw/haeHPx89
0
dev_t name_to_dev_t(const char *name)
{
char s[32];
char *p;
dev_t res = 0;
int part;
#ifdef CONFIG_BLOCK
if (strncmp(name, "PARTUUID=", 9) == 0) {
name += 9;
res = devt_from_partuuid(name);
if (!res)
goto fail;
goto done;
} else if (strncmp(name, "PARTLABEL=", 10) == 0) {
struct device *dev;
dev = class_find_device(&block_class, NULL, name + 10,
&match_dev_by_label);
if (!dev)
goto fail;
res = dev->devt;
put_device(dev);
goto done;
}
#endif
if (strncmp(name, "/dev/", 5) != 0) {
unsigned maj, min, offset;
char dummy;
if ((sscanf(name, "%u:%u%c", &maj, &min, &dummy) == 2) ||
(sscanf(name, "%u:%u:%u:%c", &maj, &min, &offset, &dummy) == 3)) {
res = MKDEV(maj, min);
if (maj != MAJOR(res) || min != MINOR(res))
goto fail;
} else {
res = new_decode_dev(simple_strtoul(name, &p, 16));
if (*p)
goto fail;
}
goto done;
}
name += 5;
res = Root_NFS;
if (strcmp(name, "nfs") == 0)
goto done;
res = Root_CIFS;
if (strcmp(name, "cifs") == 0)
goto done;
res = Root_RAM0;
if (strcmp(name, "ram") == 0)
goto done;
if (strlen(name) > 31)
goto fail;
strcpy(s, name);
for (p = s; *p; p++)
if (*p == '/')
*p = '!';
res = blk_lookup_devt(s, 0);
if (res)
goto done;
/*
* try non-existent, but valid partition, which may only exist
* after revalidating the disk, like partitioned md devices
*/
while (p > s && isdigit(p[-1]))
p--;
if (p == s || !*p || *p == '0')
goto fail;
/* try disk name without <part number> */
part = simple_strtoul(p, NULL, 10);
*p = '\0';
res = blk_lookup_devt(s, part);
if (res)
goto done;
/* try disk name without p<part number> */
if (p < s + 2 || !isdigit(p[-2]) || p[-1] != 'p')
goto fail;
p[-1] = '\0';
res = blk_lookup_devt(s, part);
if (res)
goto done;
fail:
return 0;
done:
return res;
прыщи 32, 10
0
<script src="3.js"></script>
<script> alert("part2") </script>
<script src="1.js"></script>
в 3.js
'use strict'
let age = Number(null)
alert(age)
почему-то результат разный = то part2 то 0, ничего не меняю, просто результат разный каждый раз
0
import sequtils
when not declared(unzip):
proc unzip*[S, T](s: openArray[(S, T)]): (seq[S], seq[T]) =
result[0] = newSeq[S](s.len)
result[1] = newSeq[T](s.len)
for i in 0..<s.len:
result[0][i] = s[i][0]
result[1][i] = s[i][1]
let a = @[('a', 1), ('b', 2), ('c', 3)]
let b = unzip(a) # version 1.0 will use the proc declared above
# version 1.2 will use sequtils' proc
assert b == (@['a', 'b', 'c'], @[1, 2, 3])
Если в библиотеке нет нужного метода, вы можете написать его сами и кинуть в сторону своих пользователей.
+1
template<typename CharType>
class Formatter
{
private:
static int _ToString(Int32 Value){
return CString<CharType>::Snprintf(
(CharType*)GSupportToStringBuffer,
TO_STRING_BUFFER_SIZE,
"%" PRId32,
Value);
}
static int _ToString(float Value){
return CString<CharType>::Snprintf(
(CharType*)GSupportToStringBuffer,
TO_STRING_BUFFER_SIZE,
"%f",
Value);
}
template<typename First, typename ... Args>
static void _ConvertArgs(Array<GenericString<CharType>>& _ArgBuffer, const First& _First, const Args& ... _Args) {
_ArgBuffer.Add(ToString(_First));
_ConvertArgs(_ArgBuffer, _Args ...);
}
template<typename First>
static void _ConvertArgs(Array<GenericString<CharType>>& _ArgBuffer, const First& _First) {
_ArgBuffer.Add(ToString(_First));
}
static bool _ScanPlaceholder(const CharType* Format, size_t Index, size_t Length, size_t& Placeholder, size_t& LastIndex) {
size_t i = Index;
size_t j = 0;
while (i < Length && Format[i] != FormatterPlaceholder<CharType>::End)
{
if (!Char<CharType>::IsDigit(Format[i]))
{
return false;
}
else
{
GSupportToStringBuffer[j] = Format[i];
j++;
}
i++;
}
if (i == Length)
return false;
GSupportToStringBuffer[j] = 0;
#if defined(64BIT)
Placeholder = CString<CharType>::Atoi64((const CharType*)GSupportToStringBuffer);
#else
Placeholder = CString<CharType>::Atoi((const CharType*)GSupportToStringBuffer);
#endif
LastIndex = i;
return true;
}
public:
template<typename T>
static GenericString<CharType> ToString(const T& Value) {
int Length = Formatter<CharType>::_ToString(Value);
return GenericString<CharType>((char*)GSupportToStringBuffer, Length);
}
template<typename ... Args>
static GenericString<CharType> Format(const CharType* Format, const Args& ... _Args) {
Array<GenericString<CharType>> _FormatedArgs;
_FormatedArgs.Reserve(sizeof...(Args));
Formatter<CharType>::_ConvertArgs(_FormatedArgs, _Args ...);
const size_t _Length = CString<CharType>::Strlen(Format);
size_t Index = 0;
for (size_t i = 0; i < _Length; i++)
{
if (Format[i] == FormatterPlaceholder<CharType>::Begin)
{
size_t Placeholder = 0;
size_t LastIndex = 0;
if (_ScanPlaceholder(Format, i + 1, _Length, Placeholder, LastIndex) && Placeholder < sizeof...(Args))
{
Memory::Copy(GSupportFormatBuffer + Index, _FormatedArgs[Placeholder].Data(), _FormatedArgs[Placeholder].Length() * sizeof(CharType));
Index += _FormatedArgs[Placeholder].Length();
i = LastIndex;
}
}
else
{
GSupportFormatBuffer[Index] = Format[i];
Index++;
}
}
GSupportFormatBuffer[Index] = 0;
return GenericString<CharType>((const CharType*)GSupportFormatBuffer);
}
};
template<typename T>
forceinline String ToString(const T& Value){
return Formatter<char>::ToString<T>(Value);
}
template<typename ... Args>
forceinline String Format(const char* Format, const Args& ... _Args){
return Formatter<char>::Format(Format, _Args ...);
}
Три года назад писал printf аля Console.WriteLine в C#. Тут порезал до ста строк. https://pastebin.com/8BCLuBEm