- 1
if (new Boolean(false)) {
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+215
if (new Boolean(false)) {
Отвратная вещь этот new.
+131
double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.4, 2.5 };
double[] numbers2 = { 2.2 };
IEnumerable<double> onlyInFirstSet = numbers1.Except(numbers2);
foreach (double number in onlyInFirstSet)
Console.WriteLine(number);
/*
This code produces the following output:
2
2.1
2.3
2.4
2.5
*/
Привет с msdn
http://msdn.microsoft.com/en-us/library/bb300779%28v=vs.110%29.aspx
+129
package main
import "fmt"
type буква string
var (
наТрубе буква
)
func сидели(а, б буква) буква {
return а + б
}
func aпропало(буква буква) буква {
return буква[1:]
}
func бупало(буква буква) буква {
return буква[:1]
}
func main() {
наТрубе = сидели(буква("а"), буква("б"))
наТрубе = aпропало(наТрубе)
наТрубе = бупало(наТрубе)
fmt.Printf("на трубе %s\n", наТрубе)
}
+32
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <iterator>
#include <iomanip>
using namespace std;
vector<string> bracesExpressionExamples = {
"({[{}]{}[]})",
"({}}{[{}]{}[]})",
"({[{}]{}[]}",
"({[{}]{}]})",
"({[{}{}[]})",
"",
"{}"
};
string openBrace = "({[";
string closeBrace = ")}]";
typedef map<char, char> otc;
const otc& openToCloseBrace(){
static const otc o2c([](){
otc o2c;
transform(
openBrace.begin(), openBrace.end(),
closeBrace.begin(),
inserter(o2c, o2c.begin()),
[](const char open, const char close){return make_pair(open, close);}
);
return o2c;
}());
return o2c;
}
bool checkBraces (const string& e){
vector<char> s;
for(const char b: e)
if(string::npos!=openBrace.find(b))
s.push_back(openToCloseBrace().at(b));
else if(string::npos!=closeBrace.find(b) && (!s.empty()) && b==s.back())
s.pop_back();
else return false;
return s.empty();
}
int main() {
cout<<boolalpha;
transform(
bracesExpressionExamples.begin(),
bracesExpressionExamples.end(),
ostream_iterator<bool>(cout, "\n"),
checkBraces);
return 0;
}
http://ideone.com/AbO4tw
Кот с собеседований.
Проверка правильности расстановки скобок для каждого выражения из bracesExpressionExamples.
+49
...
#define POW2 65536
#define TRUE 1
#define FALSE 0
#define VAL_TEN 20
#define VAL_TWEN 10
#define VAL_HUN 100
...
Просто поржать. Пока была в отпуске, получила письмо от коллеги с этим примером того что я слишком сильно прижала индусов за константы и они все цифры в коде поменяли на "слова".
+2
void KateQuickOpen::update () {
// пропущено
QModelIndex idxToSelect;
int linecount = 0;
QMapIterator<qint64, KTextEditor::View *> i2(sortedViews);
while (i2.hasNext()) {
i2.next();
KTextEditor::Document *doc = i2.value()->document();
if (alreadySeenDocs.contains(doc))
continue;
alreadySeenDocs.insert (doc);
QStandardItem *itemName = new QStandardItem(doc->documentName());
itemName->setData(qVariantFromValue(QPointer<KTextEditor::Document> (doc)), DocumentRole);
itemName->setData(QString("%1: %2").arg(doc->documentName()).arg(doc->url().pathOrUrl()), SortFilterRole);
itemName->setEditable(false);
QFont font = itemName->font();
font.setBold(true);
itemName->setFont(font);
QStandardItem *itemUrl = new QStandardItem(doc->url().pathOrUrl());
itemUrl->setEditable(false);
base_model->setItem(linecount, 0, itemName);
base_model->setItem(linecount, 1, itemUrl);
linecount++;
if (!doc->url().isEmpty() && doc->url().isLocalFile())
alreadySeenFiles.insert (doc->url().toLocalFile());
// select second document, that is the last used (beside the active one)
if (linecount == 2)
idxToSelect = itemName->index();
}
// get all open documents
QList<KTextEditor::Document*> docs = Kate::application()->documentManager()->documents();
foreach(KTextEditor::Document *doc, docs) {
// skip docs already open
if (alreadySeenDocs.contains (doc))
continue;
QStandardItem *itemName = new QStandardItem(doc->documentName());
itemName->setData(qVariantFromValue(QPointer<KTextEditor::Document> (doc)), DocumentRole);
itemName->setData(QString("%1: %2").arg(doc->documentName()).arg(doc->url().pathOrUrl()), SortFilterRole);
itemName->setEditable(false);
QFont font = itemName->font();
font.setBold(true);
itemName->setFont(font);
QStandardItem *itemUrl = new QStandardItem(doc->url().pathOrUrl());
itemUrl->setEditable(false);
base_model->setItem(linecount, 0, itemName);
base_model->setItem(linecount, 1, itemUrl);
linecount++;
if (!doc->url().isEmpty() && doc->url().isLocalFile())
alreadySeenFiles.insert (doc->url().toLocalFile());
}
// insert all project files, if any project around
if (Kate::PluginView *projectView = m_mainWindow->mainWindow()->pluginView ("kateprojectplugin")) {
QStringList projectFiles = projectView->property ("projectFiles").toStringList();
foreach (const QString &file, projectFiles) {
// skip files already open
if (alreadySeenFiles.contains (file))
continue;
QFileInfo fi (file);
QStandardItem *itemName = new QStandardItem(fi.fileName());
itemName->setData(qVariantFromValue(KUrl::fromPath (file)), UrlRole);
itemName->setData(QString("%1: %2").arg(fi.fileName()).arg(file), SortFilterRole);
itemName->setEditable(false);
QFont font = itemName->font();
font.setBold(true);
itemName->setFont(font);
QStandardItem *itemUrl = new QStandardItem(file);
itemUrl->setEditable(false);
base_model->setItem(linecount, 0, itemName);
base_model->setItem(linecount, 1, itemUrl);
linecount++;
}
}
// swap models and kill old one
m_model->setSourceModel (base_model);
delete m_base_model;
m_base_model = base_model;
// пропущено
}
Адская копипаста. У меня мозг сегфолтится при попытке ее формализировать.
https://projects.kde.org/projects/kde/applications/kate/repository/revisions/master/entry/kate/app/katequickopen.cpp#L135
+58
template <typename T>
class MySharedPtr{
public:
explicit MySharedPtr(T* obj) : _obj(obj){}
// --> я дописал
MySharedPtr(const MySharedPtr& other) : _obj(other._obj){ inc_ref_count(_obj);}
// <-- я дописал
MySharedPtr& operator=(const MySharedPtr& other) {
// --> я дописал
if (this == &other)
return *this;
// <-- я дописал
_obj = other._obj;
inc_ref_count(_obj);
}
~MySharedPtr(){
dec_ref_count(_obj);
}
private:
static void inc_ref_count(T* obj){
std::lock_guard<std::mutex> lock(_mutex);
_ref_count[obj] ++ ;
}
static void dec_ref_count(T* obj){
std::lock_guard<std::mutex> lock(_mutex);
if (--_ref_count[obj]){
delete obj;
_ref_count.erase(_ref_count.find(obj));
}
}
T* _obj;
static std::mutex MySharedPtr<T>::_mutex;
static std::map<T*,int> MySharedPtr<T>::_ref_count;
};
template <typename T>
std::map<T*,int> MySharedPtr<T>::_ref_count;
template <typename T>
std::mutex MySharedPtr<T>::_mutex;
сегодня приходил чел-выпускник, написал на листочке shared_ptr, какое ваше мнение?
+126
-- Подключим нужные библиотеки
-- http://codepad.org/
-- import Control.Exception
import Data.Array
import Data.Ord
import Data.List
import System.Random
import Control.Arrow
import Text.Printf
--Тестовая карта. Можно менять.
testMapList2D = [
" ",
" X X ",
" X XX XX",
"XX X ",
" X X ",
" XX ",
" X ",
" X "]
--Топографические знаки:
void = ' '
wall = 'X'
step = '*'
-- Не удобно без |> из F#. Няшная же функция. Чего её вдруг нет? Не выдержал, добавил.
infixl 0 $>
($>) = flip ($)
-- Получаем карту произвольного размера WxH. Генератор простейший, но впрочем не годен для генерации красивых лабиринтов.
-- Можно использовать для измерения производительности.
generateList2D wh wallFactor seed =
(randomRs (0, 1000) (mkStdGen seed) ::[Float]) $>
map (\randNumber -> if randNumber/1000 > wallFactor then void else wall ) >>>
listToList2D wh
-- Вспомогательные функции
listToList2D (w, h) =
take (w*h) >>>
iterate (drop w) >>>
take h >>>
map (take w)
widthHeightOfList2D l = (length $ head l, length l)
makeArray2D (w, h) values = listArray ((0,0), (h-1, w-1)) values
list2DToArray2D l = makeArray2D (widthHeightOfList2D l) $ concat l
widthHeightOfArray2D a = let (mx, my) = snd $ bounds a in (mx+1, my+1)
putIntoArray2D valueForInsertion a positionsForInsertion = a // (zip positionsForInsertion $ repeat valueForInsertion)
mapPathAdd map_ path = putIntoArray2D step map_ path
generateMap wh wallFactor seed = list2DToArray2D $ generateList2D wh wallFactor seed
outputArray2D a =
elems a $>
listToList2D (widthHeightOfArray2D a) >>>
mapM print -- В самом конце в последней строке функция outputArray2D стала грязной. Поплачем над её участью и идём дальше.
-- Приступим к функции поиска пути findPath.
-- UB findPath при использовании не прямоугольной карты.
-- UB findPath для карт меньше 2x2 точек (из-за реализации getNearestPoint) (из-за лени добавить одну короткую строчку с учетом того что карт таких не бывает обычно).
-- Также использование неподходящих в карте топографичексих знаков не контролируется.
-- Тесты не писал.
{-
Я честно пытался использовать assert в чистом коде, но возможно из-за лени он работает через раз.
В коде выглдяит отвратительно.
Самое не приятное что он не сообщает ничего подробнее чем то, что произошл ассерт. Не номер строки, не описание ошибки, не выражение. Видимо чисто недоделанная стандартная библиотека.
Пытался написать свой ассерт, чтобы хоть какое-то сообщение выдавал. Ну видимо руки кривые сделали ещё ассерт хуже, тк вообще ни разу проверил. Видимо нужны всякие бенги секи и прочее для форсирования ленивых вычислений. Так что даже не стал пытаться.
-}
-- Функция findPath все ещё чиста как слеза младенца.
findPath map_ (sx, sy) (dx, dy) = getPath $ waveField (-1) initialFieldAndYetNotFindedDestinationPoint (dx, dy)
where
wh = widthHeightOfArray2D map_
(w, h) = wh
fieldMax = w*h+1
initialField = makeArray2D wh $ repeat fieldMax
initialFieldAndYetNotFindedDestinationPoint = (initialField, False)
posibleSteps (cx, cy) = [(cx+1, cy), (cx-1, cy), (cx, cy+1), (cx, cy-1)]
isInMapRange (cx, cy) = cx>=0 && cy>=0 && cx<w && cy<h
getNearestPoint field = (minimumBy (comparing (field!))) . (filter isInMapRange) . posibleSteps
getPath (field, True) = (takeWhile (/=(dx,dy)) $ iterate (getNearestPoint field) (sx,sy)) ++ [(dx, dy)]
getPath (field, False) = []
waveField waveDistance waveFieldWithFindResult (cx, cy)
| not $ isInMapRange (cx, cy) = waveFieldWithFindResult
| map_!(cx, cy) == wall = waveFieldWithFindResult
| ((fst waveFieldWithFindResult) ! (cx, cy)) <= waveDistance = waveFieldWithFindResult
| (cx, cy)==(sx, sy) = ((fst waveFieldWithFindResult) // [((cx, cy), waveDistance+1)], True)
| otherwise =
let waveFieldWithFindResult1 = ((fst waveFieldWithFindResult) // [((cx, cy), waveDistance+1)], snd waveFieldWithFindResult) in
foldl (waveField (waveDistance+1)) waveFieldWithFindResult1 $ posibleSteps (cx, cy)
-- Копипасте-бой
pathView map_ mapName sourcePoint destinationPoint = do
let mapInfo = mapName ++ " with size " ++ (show $ widthHeightOfArray2D map_) ++ ":"
print mapInfo
let sd = (sourcePoint, destinationPoint)
printf "Path for %s: " (show sd)
let path = findPath map_ (fst sd) (snd sd)
print path
let mapWithPath = mapPathAdd map_ path
print "Map with path: "
outputArray2D mapWithPath
putStr "\n"
-- Точка входа
main = do
let map1 = list2DToArray2D testMapList2D
pathView map1 "MapFromCode" (0,0) (5,5)
let mapGenerated1 = generateMap (4,4) 0.2 90
pathView mapGenerated1 "MapGenerated1" (0,2) (3,3)
let mapGenerated3 = generateMap (5,5) 0.1 15
pathView mapGenerated3 "MapGenerated3" (0,0) (2,2)
+55
#include <iostream>
#include <thread>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <iterator>
#include <future>
constexpr std::size_t array_size = 1e7;
constexpr std::size_t chunks_number = 1e3;
double local_pi(const std::size_t array_length)
{
std::vector<std::pair<double, double>> array_xy;
array_xy.reserve(array_length);
std::generate_n(std::back_inserter(array_xy), array_length, [](){
return std::make_pair(rand()/static_cast<double>(RAND_MAX),
rand()/static_cast<double>(RAND_MAX));
});
std::vector<bool> bool_z;
bool_z.reserve(array_length);
auto bool_z_insterter = std::back_inserter(bool_z);
std::for_each(array_xy.cbegin(), array_xy.cend(), [&](const std::pair<double, double>& ref){
const auto func = [](const std::pair<double, double>& ref){
return sqrt(pow(ref.first, 2) + pow(ref.second, 2)) <= 1.0;
};
bool_z_insterter = func(ref);
});
const auto sum = 4.0 * (std::accumulate(bool_z.cbegin(), bool_z.cend(), 0.0)/array_length);
return sum;
}
int main(){
const auto concurrency_level = std::thread::hardware_concurrency();
std::vector< double > chunks_vector;
chunks_vector.reserve(chunks_number);
for (std::size_t j = 0; j < chunks_number; ++j) {
std::vector<std::future<double>> futures;
futures.reserve(concurrency_level-1);
for (std::size_t i = 0; i < concurrency_level-1; ++i){
auto f = std::async(std::launch::async, local_pi, array_size/concurrency_level);
futures.push_back(std::move(f));
}
auto pi = local_pi(array_size/concurrency_level);
for (auto&& x : futures ){
pi += x.get();
}
pi /= concurrency_level;
chunks_vector.push_back(pi);
}
const auto total_pi = std::accumulate(chunks_vector.cbegin(), chunks_vector.cend(), 0.0)/chunks_vector.size();
std::cout << "Pi equals = " << std::scientific << total_pi << std::endl;
return 0;
}
Вычисляем pi методом Монте-Карло
+19
boost::unordered::unordered_set<const WindowName> _windowNameSet;
//...
return (std::find(_windowNameSet.begin(),_windowNameSet.end(), Name) != _windowNameSet.end());