- 1
За "PHP"!
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−7
За "PHP"!
−2
argc
Зачем нужен argc? Нельзя просто смотреть NULL-terminated argv?
−2
import re
brabrebrized = lambda s, repl = r"бр\1": (
re.sub(
"[йцкнгшщзхъфвпрлджчсмтьб]+([аеёиоуыэюя])",
repl,
s,
flags = re.IGNORECASE
)
)
Я ебрабрубря и брабрибрал брабрибраброр бребров. брибрер:
брибрит брёбра бра брабробре,
бробрит ябра в абребробре.
брибрия! брибрия!
бря брабрубра брибряя!
−1
std::function<CPlayer*> pickedUp = nullptr;
+1
// https://github.com/Navadvipa-Chandra-das/prabhupada_calendar/blob/master/source/Prabhupada_convert.d
bool день_ли_это;
Тип_строки вид_строки;
Класс_Хитрый_накопитель Хитрый_накопитель = new Класс_Хитрый_накопитель( !Нужно_ли_удалять_пустые_дни, !Нужно_ли_удалять_пустые_дни_окончания_поста, Выходной_файл );
// цикл не простой, а с меткой "цикл"
цикл: while ( ( строка = Входной_файл.readln() ) !is null ) {
if ( Нужно_ли_удалять_служебные_строки ) {
if ( строка.length < 3 )
// чудо, а не возможность! Можно делать любые переходы и вылеты из множества вложенных циклов!
continue цикл;
служебная_строка = matchFirst( строка, выражение_служебная_строка );
if ( служебная_строка.captures.length > 0 )
continue цикл;
}
день_месяца = matchFirst( строка, выражение_день );
день_ли_это = день_месяца.captures.length > 0;
if ( день_ли_это ) {
вид_строки = Тип_строки.День;
if ( Нужна_ли_табуляция ) {
строка = "\t"c ~ день_месяца.captures[ 1 ] ~ "\t"c ~ день_месяца.captures[ 2 ] ~ "\t"c ~ день_месяца.captures[ 3 ] ~
"\t"c ~ день_месяца.captures[ 4 ] ~ "\t"c ~ день_месяца.captures[ 6 ].stripRight() ~ "\t"c ~ день_месяца.captures[ 7 ] ~
"\t"c ~ день_месяца.captures[ 8 ] ~ "\t"c ~ день_месяца.captures[ 10 ];
// обрабатываем "звездочку" поста
if ( день_месяца.captures[ 11 ].indexOf( '*' ) != -1 )
строка ~= "\t*"c;
строка ~= "\n";
}
// Удаляем, при желании комментрий к Экадаши - подходит для поста и не додходит для поста. Все равно есть еще символ звездочка и
// строка с именем Экадаши и явным упоминанием о посте!
if ( Нужно_ли_удалять_комментарий_Экадаши ) {
строка = replaceFirst( строка, выражение_для_чистки_комментария_Экадаши, ""c );
}
} else {
проверка_месяца = matchFirst( строка, выражение_месяц_ли_это );
if ( проверка_месяца.captures.length > 0 ) {
вид_строки = Тип_строки.Месяц;
// Просто удаляем цепочку начальных пробелов в строках месяца, если готовим табуляцию
if ( Нужна_ли_табуляция )
строка = replaceFirst( строка, выражение_цепочка_пробелов_в_начале_строки, ""c );
} else {
// Заменяем цепочку пробелов вначале строки на один единственный символ табуляции для праздников, но только если нужна табуляция
пробелы_в_начале_строки = matchFirst( строка, выражение_цепочка_пробелов_в_начале_строки );
if ( пробелы_в_начале_строки.captures.length > 0 ) {
окончание_поста = matchFirst( строка, выражение_окончание_поста );
if ( окончание_поста.captures.length > 0 )
вид_строки = Тип_строки.Окончание_поста;
else
вид_строки = Тип_строки.Праздник;
if ( Нужна_ли_табуляция )
строка = replaceFirst( строка, выражение_цепочка_пробелов_в_начале_строки, "\t"c );
} else
вид_строки = Тип_строки.Солнце;
}
}
// Удаляем строки из тире и GCal, но только если нужна табуляци. В книге они не нужны.
// Можно указать номер версии программы GCal в колонтитулах книги при желании
if ( Нужна_ли_табуляция ) {
if ( вид_строки == Тип_строки.Месяц )
строка = replaceAll( строка, выражение_для_чистки_Месяца, ""c );
if ( вид_строки == Тип_строки.Солнце )
строка = replaceAll( строка, выражение_для_чистки_Солнца, ""c );
}
// Переводим сначала фразы. Длительная операция, так как переводятся все имеющиеся фразы, не зависимо от того, встречаются ли они в строке или нет
foreach ( ref фраза; фразы )
строка = replaceAll( строка, regex( фраза ), _Словарь_фраз[ фраза ] );
// Переводим слова. Быстрее, так как переводятся только те слова, которые встречаются в данной конкретной строке
слова = std.regex.split( строка, выражение_разделитель );
// сортируем, чтобы короткие слова не позаменялись в более длинных словах внутри
// Вдохнули поглубже! Такого чуда я еще не видел! Не иначе как mixin в действии!
слова.sort!( "a.length > b.length" );
foreach ( ref слово; слова )
if ( слово.length > 0 )
строка = replaceAll!( Чудо_слов )( строка, regex( слово ) );
Хитрый_накопитель.В_копилку( строка, вид_строки );
}
// Пропихнем в файл последнюю строку
Хитрый_накопитель.В_копилку( ""c, Тип_строки.День );
window.showMessageBox( UIString.fromId( "ЧЕСТЬ_ИМЕЮ_ДОЛОЖИТЬ"c ),
UIString.fromId( "ЗАДАНИЕ_ВЫПОЛНЕНО!"c ) );
}
Кришнаит, пишущий на языке D в стиле 1С
−6
/* Q: Can someone recommend a more elegant way to achieve these compile-time constants? */
template <int> struct Map;
template <> struct Map<0> {static const int value = 4;};
template <> struct Map<1> {static const int value = 8;};
template <> struct Map<2> {static const int value = 15;};
template <int> struct MapInverse;
template <> struct MapInverse<4> {static const int value = 0;};
template <> struct MapInverse<8> {static const int value = 1;};
template <> struct MapInverse<15> {static const int value = 2;};
/* A: Another TMP approach for a linear search using C++11: */
#include <type_traits>
// === Types:
// Usage:
// Function<Map<x1,y1>,Map<x2,y2>,...>
template<int D, int R> struct Map { enum { domain=D, range=R }; };
template<typename ...A> struct Function {};
// === Metafunctions:
// Usage:
// ApplyFunction<x,F>::value
template<int I, typename M> struct ApplyFunction;
// Usage:
// ApplyFunctionInverse<x,F>::value
template<int I, typename M> struct ApplyFunctionInverse;
// ==== Example:
// Define function M to the mapping in your original post.
typedef Function<Map<0,4>,Map<1,8>,Map<2,15>> M;
// ==== Implementation details
template<typename T> struct Identity { typedef T type; };
template<int I, typename A, typename ...B> struct ApplyFunction<I, Function<A,B...> > {
typedef typename
std::conditional <I==A::domain
, Identity<A>
, ApplyFunction<I,Function<B...>> >::type meta;
typedef typename meta::type type;
enum { value = type::range };
};
template<int I, typename A> struct ApplyFunction<I, Function<A>> {
typedef typename
std::conditional <I==A::domain
, Identity<A>
, void>::type meta;
typedef typename meta::type type;
enum { value = type::range };
};
// Linear search by range
template<int I, typename A> struct ApplyFunctionInverse<I, Function<A>> {
typedef typename
std::conditional <I==A::range
, Identity<A>
, void>::type meta;
typedef typename meta::type type;
enum { value = type::domain };
};
template<int I, typename A, typename ...B> struct ApplyFunctionInverse<I, Function<A,B...> > {
typedef typename
std::conditional <I==A::range
, Identity<A>
, ApplyFunctionInverse<I,Function<B...>> >::type meta;
typedef typename meta::type type;
enum { value = type::domain };
};
// ==============================
// Demonstration
#include <iostream>
int main()
{
// Applying function M
std::cout << ApplyFunction<0,M>::value << std::endl;
std::cout << ApplyFunction<1,M>::value << std::endl;
std::cout << ApplyFunction<2,M>::value << std::endl;
// Applying function inverse M
std::cout << ApplyFunctionInverse<4,M>::value << std::endl;
std::cout << ApplyFunctionInverse<8,M>::value << std::endl;
std::cout << ApplyFunctionInverse<15,M>::value << std::endl;
}
Элегантненько.
s: https://stackoverflow.com/questions/26075969/compile-time-map-and-inverse-map-values
−109
Админ, забань Ильяса.
0
unit Unit1;
interface
uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, jpeg, ExtCtrls, ComCtrls;
type
TForm1 = class(TForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
...
RadioButton1: TRadioButton;
RadioButton2: TRadioButton;
RadioButton3: TRadioButton;
RadioButton4: TRadioButton;
GroupBox2: TGroupBox;
RadioButton5: TRadioButton;
RadioButton6: TRadioButton;
RadioButton7: TRadioButton;
RadioButton8: TRadioButton;
GroupBox3: TGroupBox;
RadioButton9: TRadioButton;
RadioButton10: TRadioButton;
...
GroupBox14: TGroupBox;
RadioButton52: TRadioButton;
RadioButton53: TRadioButton;
RadioButton54: TRadioButton;
RadioButton55: TRadioButton;
GroupBox15: TGroupBox;
RadioButton56: TRadioButton;
RadioButton57: TRadioButton;
RadioButton58: TRadioButton;
RadioButton59: TRadioButton;
...
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.BitBtn1Click(Sender: TObject);
begin
form1.Close;
end;
procedure TForm1.Button2Click(Sender: TObject);
var s: integer;
begin
Button3.enabled:=true;
s:=0;
if Form1.RadioButton2.Checked then s:=s+1;
if Form1.RadioButton6.Checked then s:=s+1;
if Form1.RadioButton20.Checked then s:=s+1;
if Form1.RadioButton15.Checked then s:=s+1;
if Form1.RadioButton11.Checked then s:=s+1;
if Form1.RadioButton21.Checked then s:=s+1;
if Form1.RadioButton24.Checked then s:=s+1;
if Form1.RadioButton28.Checked then s:=s+1;
if Form1.RadioButton33.Checked then s:=s+1;
if Form1.RadioButton39.Checked then s:=s+1;
if Form1.RadioButton43.Checked then s:=s+1;
if Form1.RadioButton44.Checked then s:=s+1;
if Form1.RadioButton50.Checked then s:=s+1;
if Form1.RadioButton54.Checked then s:=s+1;
if Form1.RadioButton56.Checked then s:=s+1;
if s=15 then Label3.Caption:=' Молодец, ты ответил на все вопросы!(Твоя оценка 5)';
if s=14 then Label3.Caption:=' Молодец, ты ответил на четырнадцать вопросов!(Твоя оценка 5)';
if s=13 then Label3.Caption:=' Молодец, ты ответил на 13 вопросов!(Твоя оценка 5)';
if s=12 then Label3.Caption:=' Хорошо, ты ответил на 12!(Твоя оценка 4)';
if s=11 then Label3.Caption:=' Ты ответил на все 11!(Твоя оценка 4)';
if s=10 then Label3.Caption:='10 парвильных ответов молодец!(Твоя оценка 4)";
if s=9 then Label3.Caption:='9 ПРАВИЛЬНЫХ ОТВЕТОВ!(Твоя оценка 3)';
if s=8 then Label3.Caption:='Отлично! Ты ответил на 8 вопрос(Твоя оценка 3)';
if s=7 then Label3.Caption:='Молодец! Ты ответил на 7 вопрос(Твоя оценка 3)';
if s=6 then Label3.Caption:='6 Вопросов? Ты не плох!(Твоя оценка 3)';
if s=5 then Label3.Caption:='5 правильных вопросов! ура!(Твоя оценка 2)';
if s=4 then Label3.Caption:='Учи предмет лучше! Всего 4 правильных вопроса!(Твоя оценка 2)';
if s=3 then Label3.Caption:=' Слабо! Всего 3 правильных ответа!(Твоя оценка 2)';
if s=2 then label3.Caption:=' Всего 2 правильных ответа!( Твоя оценка 2)';
if s=1 then label3.Caption:=' Тебе не быть программистом! Всего 1 правильный ответ!(Твоя оценка 2)';
if s=0 then label3.Caption:=' Давай заново!(Твоя оценка 2)';
end;
Автор пытается сделать тест по информатике. Вроде бы для диплома.
−4
if ($memberInfo['member_profile_image'] != ''):
$memberInfo['photoCount'] = $memberInfo['photoCount'] ;
else:
$memberInfo['photoCount'] = $memberInfo['photoCount'];
endif;
6 строчек кода, а этот код не делает ничего. От слова совсем
−1
Antony Polukhin
in
pro.cxx
Кстати, в EWG одобрили constexpr контейнеры http://open-std.org/JTC1/SC22/WG21/docs/papers/2018/p0784r1.html
так что есть все шансы к С++20 писать:
constexpr std::string result = foo();
t.me/ProCxx
/184343
Mar 16 at 10:47
Library pragmatism
Current implementations of standard libraries sometimes perform various raw storage operations through interfaces other than the standard allocator and allocator traits. That may make it difficult to make the associated components usable in constexpr components. Based on a cursory examination of current practices, we therefore propose to start only with the requirement that the container templates in the [containers] clause be usable in constexpr evaluation, when instantiated over literal types and the default allocator. In particular, this excludes std::string, std::variant, and various other allocating components. Again, it is our hope we will be able to extend support to more components in the future.
With regards to the default allocator and allocator traits implementation, the majority of the work is envisioned in the constexpr evaluator: It will recognize those specific components and implement their members directly (without necessarily regarding the library definition).
We might, however, consider decorating the class members with the constexpr keyword. Also, some implementations provide extra members in these class templates (such as libc++'s allocator_traits<A>::__construct_forward ) that perform non-constexpr-friendly operations (memcpy, in particular). Lifting such members to standard status would help interoperability between library and compiler implementations.