- 1
if (!("" instanceof String)) throw new Error("Empty string is not a string");
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+157
if (!("" instanceof String)) throw new Error("Empty string is not a string");
Майкрософт. JScript, ASP.
+119
<?php
session_start();
if(empty($_SESSION['login']) or empty($_SESSION['id']) or empty($_SESSION['auth_key']))
{
header("Location: index.php");
}
else
{
$user_name = $_POST['name'];
$user_sname = $_POST['sname'];
$user_gender = $_POST['gender'];
$user_about = $_POST['about'];
$user_phone = $_POST['phone'];
$user_mail = $_POST['email'];
$user_company = $_POST['company'];
$user_company_position = $_POST['position'];
$user_login = $_POST['login'];
$user_password = $_POST['password'];
include 'includes/xd4sw.php';
$update_query = mysql_query("UPDATE users SET user_name='$user_name', user_sname='$user_sname', user_gender='$user_gender',
user_about='$user_about', user_phone='$user_phone', user_mail='$user_mail', user_company='$user_company',
user_company_position='$user_company_position', user_login='$user_login', user_password='$user_password' WHERE user_id=".$_SESSION['id']);
mysql_close($db);
header('Location: settings.php?act=good');
}
?>
НА НАХ!!!!
+18
template <typename Derived>
class Base {
public:
void doSmth() {
// ...
static_cast<Derived*>(this)->OnParseAndHandle();
//...
}
};
class MyClass: public Base<MyClass> {
public:
void OnParseAndHandle() {
// ...
}
};
Если Вы не верите в виртуальные методы, то шаблоны Вам в помощь.
А может я идиот и чего-то не понял?
−109
- (void)countDown
{
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = ([currentDate timeIntervalSinceDate:startDate]);
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
if ([timeString isEqualToString:@"02"])
{
[logoTimer invalidate];
logoTimer = nil;
// some other code
}
}
- (void)updateCounter
{
startDate = [NSDate dateWithTimeIntervalSinceNow:00];
logoTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(countDown)
userInfo:nil
repeats:YES];
}
Вот так незатейливо можно поставить задержку на 2 секунды
+136
public override int GetHashCode()
{
if (this.FileName == null)
{
return base.GetHashCode();
}
return this.FileName.GetHashCode() + 13;
}
почему 13?
+141
//void wyslij(int pin, char mode[] = "open") { //было
void wyslij(int pin, int mode) { //стало
if (pin != -1)
{
if (mode == "open")
{
//...
else if ( (mode == "touch") && ( (error != 1) || (olej_error == 1) ) )
Кусок дипломной работы польского студента, код для ардуино. Выцарапано отсюда: http://vimeo.com/47656204, примерно с 1:15.
+129
-- Подготовка
(.-) :: ot -> (ot -> rt) -> rt
object .- method = method object
to_string () self = show self
my_array = [1..]
-- ООП в действии
main = putStrLn( my_array.-take(10).-drop(5).-to_string() )
Хаскелл и ООП.
+124
data = load('ex1data1.txt');
X = data(:, 1); y = data(:, 2);
m = length(y); % number of training examples
X = [ones(m, 1), data(:,1)]; % Add a column of ones to x
theta = zeros(2, 1); % initialize fitting parameters
% Some gradient descent settings
iterations = 1500;
alpha = 0.01;
function J = computeCost(X, y, theta)
m = length(y); % number of training examples
hypothesis = theta' * X';
J = 1 / (2 * m) * sum((hypothesis' - y) .^ 2);
endfunction
% compute and display initial cost
computeCost(X, y, theta)
Язык: Матлаб / Октава.
Что происходит: из массива создается матрица путем добавления еще одного такого же массива полностью заполненного единицами, а потом эта матрица умножается на вектор из двух элементов (первая колонка, соответственно, умножается на первый элемент вектора, вторая - на второй). Т.е. это равносильно вызову функции вида y(x) = Kx + b для всех членов исходного массива X. По сути происходит следующее: y(x_0, x_1) = K * x_1 + b * x_0, где x_0 всегда равен единице.
Источник разглашать не буду.
+128
rotate n xs = b ++ a
where n' = n `mod` (length xs)
(a, b) = splitAt ((length xs) - n') xs
rotateAmount xs = _ra 0 ((length xs) - 1) (listArray (0, ((length xs) - 1)) xs)
where _ra s e ys = if (e - s) == 1
then (if ((ys ! s) < (ys ! e)) then s else e) -- base case
else let h = ys ! s -- first item
l = ys ! e -- last item
mi = s + ((e - s) `div` 2) -- middle index
m = ys ! mi -- middle item
in if (h < l)
then s -- return start index
else if (h > m)
then _ra s mi ys
else _ra mi e ys
A “rotated array” is an array of integers in ascending order, after which for every element i, it has been moved to element (i + n) mod sizeOfList. Write a function that takes a rotated array and, in less-than-linear time, returns n (the amount of rotation). http://techguyinmidtown.com/2008/07/05/my-answers-to-the-microsoft-interview-questions
+74
reader = new BufferedReader(new FileReader(file));
//null means file end
while ((tempString = reader.readLine()) != null) {
if(tempString !=null && tempString.indexOf('=')>0){
sheet.addCell(new Label(KEY_COLUMN,++ROW, tempString.substring(0,tempString.indexOf('='))));
sheet.addCell(new Label(ENGLISH_COLUMN,ROW, tempString.substring(tempString.indexOf('=')+1)));
}
}
reader.close();
Вот так мы парсим файл *.properties в Java.