- 1
there are java.io.FileNotFoundException and java.nio.file.NoSuchFileException . Both are subclasses of IOException, neither of them is a subclass of the opposite.
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+1
there are java.io.FileNotFoundException and java.nio.file.NoSuchFileException . Both are subclasses of IOException, neither of them is a subclass of the opposite.
+1
// если пользователь авторизован
if($user->get('id')) {
$_SESSION['city-select'] = '';
// если пользователь авторизован - определяем город
$profile = $user->getOne('Profile');
if ($profile) {
$city = $profile->get('city');
}
// проходим все города и ищем подходящий
$cities = $modx->runSnippet('pdoResources', array(
'parents' => 205,
'limit' => 0,
'includeTVs' => 'setCityForHome',
'where' => '{ "template" : "25" }',
'tpl' => '@CODE:{"id":"[[+id]]","city":"[[+tv.setCityForHome]]"}',
'outputSeparator' => ','
));
$redirectTo = 0;
if($cities) {
$cities = $modx->fromJson('['.$cities.']');
foreach( $cities as $c ) {
if($c['city'] == $city) {
$redirectTo = $c['id'];
break;
}
}
}
} else {
// если не авторизован - проверяем сессию
$session = $_SESSION['city-select'];
// если сессия пустая - проверяем, на какой странице находимся
// если страница города и пустая сессия - записываем в сессию
if($modx->resource->get('template') == 25) {
$_SESSION['city-select'] = $modx->resource->get('pagetitle');
$city = $modx->resource->get('pagetitle');
} else {
$city = (!empty($_SESSION['city-select']))? $_SESSION['city-select'] : $city;
}
}
Сумрачный гений, сука. Строки 11-28 особенно примечательны.
+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
Немного богословия.
In the beginning was the word; and version of this Word was 1.0
−2
This would raise the true nightmare. A type variable is a different beast than the actual type of a concrete instance.
A type variable could resolve to a, e.g. ? extends Comparator<? super Number> to name one (rather simple) example.
Providing the necessary meta information would imply that not only object allocation becomes much more expensive,
every single method invocation could impose these additional cost, to an even bigger extend as we are now not only
talking about the combination of generic classes with actual classes, but also every possible wildcarded combination,
even of nested generic types.
https://stackoverflow.com/a/38060012
Джавист-долбоеб с пеной у рта защищает type erasure, задавая вопросы "Does it [c#] have an equivalent of Function.identity()? " в комментариях и собирая плюсы таких же поехавших.
В качестве аргументов он предлагает:
1) сложна
2) хранить информацию о типах в рантайме означает что в рантайме придется хранить информацию о типах!!!
3) [s]ма-те-ма-ти-ка[/x] реф-лек-си-я
Причем ведь наверняка знает и про темплейты в крестах, и про то что шарп такой хуйней не страдает.
0
#include <iostream>
#include <string>
using namespace std;
class Govnokod {
bool _flag_dot;
bool _flag_mant;
int _index_mant;
bool vetka1(int i, const string stroka) {
for (int j = i++; j < stroka.length(); j++) {
switch (stroka[j]) {
case '.':
if (_flag_dot) return false;
_flag_dot = true;
break;
case '0' ... '9': break;
default:
return false;
break; }}
return true;}
bool vetka2_dalshe(const string stroka) {
for (int j = 1; j < stroka.length(); j++) {
switch (stroka[j]) {
case '0' ... '9': break;
default:
return false;
break; }}
return true; }
bool vetka2(const string stroka) {
switch (stroka[0]) {
case '+':
case '-':
if (stroka.length() < 2) return false;
return vetka2_dalshe(stroka);
break;
case '0' ... '9':
return vetka2_dalshe(stroka);
break;
default:
return false;
break; }}
bool mantissa(const string stroka) {
for (int j = 0; j < stroka.length(); j++) {
switch (stroka[j]) {
case 'e':
case 'E':
if ((_flag_mant) or (j == (stroka.length() - 1))) return false;
_flag_mant = true;
_index_mant = j;
break; }}
return true; }
bool Dalshe(int i, const string stroka) {
_flag_dot = false;
_flag_mant = false;
if (not mantissa(stroka)) return false;
else if (_flag_mant) {
string sub1 = stroka.substr(0, _index_mant);
string sub2 = stroka.substr(_index_mant+1);
return (vetka1(i, sub1) and vetka2(sub2)); }
else return vetka1(i, stroka); }
bool proverka(const string stroka) {
switch (stroka[1]) {
case '0' ... '9':
return Dalshe(1, stroka);
break;
default:
return false;
break; }}
bool general_proverka(const string stroka) {
switch (stroka[0]) {
case '-':
case '+':
if (stroka.length() > 1) return proverka(stroka);
else return false;
break;
case '0' ... '9':
return Dalshe(0, stroka);
break;
default:
return false;
break; }}
public:
long double opros(char s) {
string argument;
while (true) {
cout << "Введите значение " << s << ": ";
getline(cin, argument);
if (argument.length() == 0)
cout << "Вы не ввели значение!" << endl;
else if (not general_proverka(argument))
cout << "Некорректное значение!" << endl;
else
return strtold(argument.c_str(), nullptr); }
}
} obj;
int main() {
for (char c = 'a'; c < 'd'; c++) {
long double result = obj.opros(c);
cout << "Значение: " << result << " -- корректное!" << endl;
}
}
Решил попробовать в стиле ООП переписать.
0
#include <iostream>
#include <string>
using namespace std;
bool vetka1(bool &flag, int i, const string stroka) {
int j = 1;
for (j += i; j < stroka.length(); j++) {
switch (stroka[j]) {
case '.':
if (flag) return false;
flag = true;
break;
case '1' ... '9': break;
default: return false; } }
return true; }
bool vetka2_dalshe(const string stroka) {
for (int j = 1; j < stroka.length(); j++) {
switch (stroka[j]) {
case '0' ... '9': break;
default: return false; } }
return true; }
bool vetka2(const string stroka) {
switch (stroka[0]) {
case '+':
case '-':
if (stroka.length() < 2) return false;
return vetka2_dalshe(stroka);
break;
case '0' ... '9': return vetka2_dalshe(stroka); break;
default: return false; break; } }
bool mantissa(const string stroka, bool &flag, int &index) {
for (int j = 0; j < stroka.length(); j++) {
switch (stroka[j]) {
case 'e':
case 'E':
if (flag) return false;
if (j == (stroka.length() - 1)) return false;
flag = true;
index = j;
break; } }
return true; }
bool Dalshe(int i, const string stroka) {
int index_mant;
bool flag_dot = false;
bool flag_mant = false;
if (not mantissa(stroka, flag_mant, index_mant)) return false;
else {
if (flag_mant) {
string sub1 = stroka.substr(0, index_mant);
string sub2 = stroka.substr(index_mant+1);
return (vetka1(flag_dot, i, sub1) and vetka2(sub2)); }
else return vetka1(flag_dot, i, stroka); } }
bool proverka(const string stroka) {
switch (stroka[1]) {
case '0' ... '9': return Dalshe(1, stroka); break;
default: return false; break; } }
bool general_proverka(const string stroka) {
switch (stroka[0]) {
case '-':
case '+':
if (stroka.length() > 1) return proverka(stroka);
else return false;
break;
case '0' ... '9': return Dalshe(0, stroka); break;
default: return false; break; } }
long double opros(char s) {
string argument;
do {
cout << "Введите значение " << s << ": ";
getline(cin, argument);
if (argument.length() == 0) cout << "Вы не ввели значение!" << endl;
else if (not general_proverka(argument)) cout << "Некорректное значение!" << endl;
else break;
} while (true);
return atof(argument.c_str()); }
int main() {
for (char i = 'a'; i < 'd'; i++) {
long double a = opros(i);
cout << "Значение: " << a << " - корректное!" << endl;
}
}
В общем, частично переписал некоторые куски кода. Отчасти тут предыдущая версия (с дублированием кода),
что, конечно, не менее говно, но зато стало чуть читабельнее и работает без очевидных багов, как в исходной версии,
например: если в исходной версии ввести - "3w", то значение отображалось, как корректное, что не верно.
+3
class Metapetuh(type):
def __subclasscheck__(cls, C):
return True
def __instancecheck__(self, other):
return True
class Petuh(metaclass=Metapetuh):
pass
issubclass(object, Petuh) # True
isinstance(42, Petuh) # True
Мы зашкварили весь «Питон», и теперь все классы в нём — петухи.
По просьбам трудящихся: https://govnokod.ru/27166#comment602776.
+3
data:text/html,<body onload=z=c.getContext`2d`,setInterval(`c.width=W=150,Y<W&&P<Y&Y<P+E|9<p?z.fillText(S++${Y=`,9,9|z.fillRect(p`}*0,Y-=--M${Y+Y},P+E,9,W),P))):p=M=Y=S=6,p=p-6||(P=S%E,W)`,E=49) onclick=M=9><canvas id=c>
Энтузиаст создал Flappy Bird на минималках весом всего лишь 228 байт.
А чтобы запустить игру, достаточно скопировать этот код в адресную строку браузера.
−3
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace Filter
{
class MainClass
{
/// <summary>
/// Filter ver. 1.0
/// Matching only one word
/// <created>Aleksandr 23.10.2020</created>
/// </summary>
/// <param name="args"></param>
///
public static void Main(string[] args)
{
try
{
string str = "ехал грека через редиска че за редиска кек";
//Настройки=====================================================================
////Уберите комментарий строки 20 если хотите ввести свое слово, и уберите строку 21
///
//string str1 = Console.ReadLine(); //<==== decomment
//==================================================================================
string str1 = "редиска";
//если разкомментировали строку 21, то замените слово "тварь" на слвоо которое ввели //<==== decomment
Regex regex = new Regex(@"редиска(\w*)");
MatchCollection matches = regex.Matches(str);
if (matches.Count > 0)
{
foreach (Match match in matches)
{
Console.WriteLine(match.Value);
}
var arrS = str.Split(' ').Select(s => s.Trim(',', '?', '.', '!')).ToArray();
for (var i = 0; i < arrS.Length; i++)
{
if (arrS[i].ToLower() == str1)
arrS[i] = "***";
}
var newStr = string.Join(" ", arrS);
Console.WriteLine(newStr);
Console.ReadLine();
}
else
{
Console.WriteLine("Совпадений не найдено");
}
}
catch (Exception ex)
{
Console.WriteLine($"Исключение: {ex.Message}");
Console.WriteLine($"Метод: {ex.TargetSite}");
Console.WriteLine($"Информация об исключении: { ex.InnerException}");
}
}
}
}