- 1
- 2
- 3
if req.Lang != "" {
req.Lang = "EN"
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+1
if req.Lang != "" {
req.Lang = "EN"
}
Я сказал английский!
[Поставленная задача: если пришёл запрос без поля, поставить значение по умолчанию]
0
// Since C++20
struct A {
int&& r;
};
A a1{7}; // OK, lifetime is extended
A a2(7); // well-formed, but dangling reference
Удачной отладки!
0
//glsl vertex shader
attribute float mass;
uniform vec3 center;
#define RAD 10.0
const float D = RAD * 2.0;
///////////////////THIS///////////////////
float repeat(float x, float z) {
float dx = distance(x, z);
while(dx > RAD) {
if (x > z) {
x -= D;
} else {
x += D;
}
dx = distance(x, z);
}
return x;
}
///////////////////////////////////////////
vec3 repeat(vec3 x, vec3 y) {
return vec3(dr(x.x, y.x), dr(x.y, y.y), dr(x.z, y.z));
}
void main() {
vec3 pos = position;
pos.z += time;
pos = repeat(pos, center);
vec4 mvPosition = modelViewMatrix * vec4(pos, 1.0);
gl_PointSize = 70.0 * mass;
gl_Position = projectionMatrix * mvPosition;
}
По сути функция repeat должна повторять текстуру (как background-repeat: repeat в css) в зависимости от положения точки центра, короче: двигается центр, двигается и текстура за ним. Мне даже ума не хватает описать это, поэтому формулу сам искал, хватило ума только на это говно. Спустя несколько недель додумался до следующего говна, уже без цикла:
float repeat(float x, float z) {
float mp = x > z ? -1.0 : 1.0;
z += RAD * mp;
float dx = distance(x, z);
float n = floor(dx / D) * D;
x += n*mp;
return x;
}
Тяжело не знать математики. Может местные шизы подскажут как называется такое поведение и как нормальную формулу?
0
function test3()
{
const a = 10.5
switch (a)
{
case 10.5:
print("cool. 10.5");
break;
}
}
function test3()
{
switch ("kokoko")
{
case "kokoko":
print("pituh");
break;
}
}
Продолжаем говнокомпилить...
А ваш С такое прокомпилирует? мой - запросто :)
0
template<typename T>
class SharedPtr {
T* value;
int* ref_count;
public:
SharedPtr(T* value) : value(value) {
ref_count = new int;
*ref_count = 1;
}
SharedPtr(const SharedPtr& other) {
value = other.value;
ref_count = other.ref_count;
(*ref_count)++;
}
SharedPtr(SharedPtr&& other) {
value = other.value;
ref_count = other.ref_count;
other.ref_count = nullptr;
}
~SharedPtr() {
if (ref_count == nullptr) {
return;
}
if (*ref_count == 1) {
delete value;
delete ref_count;
} else {
(*ref_count)--;
}
}
T& operator *() const {
return *value;
}
T* operator ->() const {
return value;
}
};
Реалейзовал минимальную версию shared_ptr. Есть ошибки/замечания?
https://ideone.com/g7gqBM
0
class MediaWiki {
// Поля, другие методы
private function performRequest() {
global $wgTitle;
$request = $this->context->getRequest();
$requestTitle = $title = $this->context->getTitle();
$output = $this->context->getOutput();
$user = $this->context->getUser();
if ( $request->getVal( 'printable' ) === 'yes' ) {
$output->setPrintable();
}
$this->getHookRunner()->onBeforeInitialize( $title, null, $output, $user, $request, $this );
// Invalid titles. T23776: The interwikis must redirect even if the page name is empty.
if ( $title === null || ( $title->getDBkey() == '' && !$title->isExternal() )
|| $title->isSpecial( 'Badtitle' )
) {
$this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
try {
$this->parseTitle();
} catch ( MalformedTitleException $ex ) {
throw new BadTitleError( $ex );
}
throw new BadTitleError();
}
// Check user's permissions to read this page.
// We have to check here to catch special pages etc.
// We will check again in Article::view().
$permissionStatus = PermissionStatus::newEmpty();
if ( !$this->context->getAuthority()->authorizeRead( 'read', $title, $permissionStatus ) ) {
// T34276: allowing the skin to generate output with $wgTitle or
// $this->context->title set to the input title would allow anonymous users to
// determine whether a page exists, potentially leaking private data. In fact, the
// curid and oldid request parameters would allow page titles to be enumerated even
// when they are not guessable. So we reset the title to Special:Badtitle before the
// permissions error is displayed.
// The skin mostly uses $this->context->getTitle() these days, but some extensions
// still use $wgTitle.
$badTitle = SpecialPage::getTitleFor( 'Badtitle' );
$this->context->setTitle( $badTitle );
$wgTitle = $badTitle;
throw new PermissionsError( 'read', $permissionStatus );
}
// Еще какая-то логика для хандлинга редиректов по заголовкам страниц
}
// ...
}
// ...
class MessageCache implements LoggerAwareInterface {
// ...
public function parse( $text, $title = null, $linestart = true,
$interface = false, $language = null
) {
global $wgTitle;
if ( $this->mInParser ) {
return htmlspecialchars( $text );
}
$parser = $this->getParser();
$popts = $this->getParserOptions();
$popts->setInterfaceMessage( $interface );
if ( is_string( $language ) ) {
$language = $this->langFactory->getLanguage( $language );
}
$popts->setTargetLanguage( $language );
if ( !$title || !$title instanceof Title ) {
$logger = LoggerFactory::getInstance( 'GlobalTitleFail' );
$logger->info(
__METHOD__ . ' called with no title set.',
[ 'exception' => new Exception ]
);
$title = $wgTitle;
}
// Sometimes $wgTitle isn't set either...
if ( !$title ) {
# It's not uncommon having a null $wgTitle in scripts. See r80898
# Create a ghost title in such case
$title = Title::makeTitle( NS_SPECIAL, 'Badtitle/title not set in ' . __METHOD__ );
}
$this->mInParser = true;
$res = $parser->parse( $text, $title, $popts, $linestart );
$this->mInParser = false;
return $res;
} // ...
}
Зачем в методах класса вообще использовать глобальные изменяемые состояния, если это нарушает принцип инкапсуляции (для обеспечения чего и была введена абстракция класса в языки)? И сидишь гадаешь, при вызове какого метода у какого объекта у тебя слетела верстка, контент и пр. Это усложняет написание безопасных расширений для системы.
0
// В одном файле
// Getting gif by url
const getGifUrl = (searchQuery, gifRating) => {
const fullUrl = `${giphyUrl}${giphyApiKey}&tag=${searchQuery}&rating=${gifRating}`;
let gifSource;
let girSourceOriginal;
fetch(fullUrl).then(response => {
return response.json();
}, networkError => {
console.log(networkError);
}).then(jsonResponse => {
if (!jsonResponse)
gifSource = '';
else {
gifSource = jsonResponse.data.images.preview_gif.url;
gifSoucreOriginal = jsonResponse.data.image_original_url;
}
renderGif(gifSource, gifSoucreOriginal);
});
};
// Где-то в другом файле
// incapsulating image
const incapsulateImage = (gifUrl, gifUrlOriginal) => {
// creating gif preview tile
const image = document.createElement('img');
image.src = gifUrl;
// create link to the original gif
const linkOriginal = document.createElement('a');
linkOriginal.href = gifUrlOriginal;
// incapsulating gif tile into link
linkOriginal.appendChild(image);
// create container-tile
const tile = document.createElement('div');
tile.className = "container-tile";
// incapsulating linked gif into tile
tile.appendChild(linkOriginal);
return tile;
}
// Rendering one gif image
const renderGif = (gifUrl, gifUrlOriginal) => {
if (gifUrl) {
const imageTile = incapsulateImage(gifUrl, gifUrlOriginal);
$gifContainer.append(imageTile);
} else if (!$gifContainer.html()) {
const notFoundHeading = document.createElement('h1');
notFoundHeading.innerHTML = NOT_FOUND_TEXT;
$gifContainer.append(notFoundHeading);
}
};
const render = () => {
// Rendering whole block of gifs
const renderContainer = (searchQuery, gifCount, gifRating) => {
for (let i = 0; i < gifCount; i++) {
getGifUrl(searchQuery, gifRating);
const heading = $gifContainer.find('h1');
if (heading && heading.text() == NOT_FOUND_TEXT) {
break;
}
}
}
// ...Сетап всяких обработчиков событий на элементы...
}
Когда толком не знал про промисы (а уж тем более про модули), городил такую дичь.
+2
Мир! Труд! Май!
С праздником, питухи!
+1
def main():
pipe(int(input('Введите неотрицательное целое число: ')),
lambda n: (n, reduce(lambda x, y: x * y, range(1, n + 1))),
lambda tup: print(f'Факториал числа {tup[0]} равняется {tup[1]}'))
Из https://habr.com/ru/post/555370/ (Функциональное ядро на Python).
+1
function main() {
(function () {
print("Hello World!");
})();
}
а ваш С компилятор может так говнокодить? а мой компилятор может :)