Записки программиста, обо всем и ни о чем. Но, наверное, больше профессионального.

2016-12-27

природоведение, дневник

Продолжаем наблюдения за природой.

В мордоре идет пятая неделя ежедневных осадков. Тепло, около нуля. Снег выпал и начал подтаивать. А потом подмерзнет и будет весело.

Охуевайтунг.






original post http://vasnake.blogspot.com/2016/12/blog-post_27.html

2016-12-21

Четвертая неделя

Не знаю, кому как, а по моему это эпично: четвертую неделю ежедневные осадки в мордоре.
Сегодня это снег переходящий в дождь. Скользко и мерзко.

Я думал, глядя на прогноз, где показывали слабый плюс и никаких осадков, поехать на машине. Потом, может, на мойку заглянуть, а то Прося вся в московском дристе. Но боженька решил иначе.
Вечером на кухне сорвало трубу и я с утра занимался "похозяйству". Посему до утренних пробок не успел. Оно и к лучшему, при такой-то погоде.





original post http://vasnake.blogspot.com/2016/12/blog-post_21.html

2016-12-15

В деревне Гадюкино дожди

Это просто анекдот какой-то.

Две недели в мордоре идет снег. Поэтому на работу я езжу на метро.
На третьей неделе прогноз пообещал, что осадков не будет и, в понедельник, я поехал на машине.
Пошел снег, ехать было скользко и страшно. И долго.
На вторник пообещали, что осадков не будет. Я опять поехал на машине.
Пошел снег. Выкапывать машину из сугроба, парковаться в сугроб и ехать в пробени по скользкой дороге -- не вставляет совсем.
В среду ... ну вы поняли, та же история.

В четверг я решил, ну его нах, поеду на метро.
И что бы вы думали? Светит солнце, осадков нет.
Ну не пиздец?

Вообще, три недели непрерывных осадков это перебор. Ятакщетаю.





original post http://vasnake.blogspot.com/2016/12/blog-post.html

2016-11-28

weekends & holidays

В связи с тем, что я искал (и успешно нашел) себе новую постоянную работу, на блог времени нет совершенно. Времени, походу, вообще хватает теперь только на то, чтобы поужинать, выпить чаю в процессе релакса под эпизод какого-нибудь сериала и ... всё. Но не будем терять надежду.

Заметка про нашего мальчика: понадобился мне список выходных и праздничных дней. Типа, для подсчета статистики всякой, бла-бла-бла "по выходным и праздничным дням". Грустно и смешно, но в удобоваримом виде такой информации нет.
Есть http://xmlcalendar.ru/ в xml.
Есть http://data.gov.ru/opendata/7708660670-proizvcalendar в csv.
Но оба требуют трансформации до состояния "список дат: выходные и праздничные дни".

Собственно, вот, трансформатор: https://github.com/vasnake/weekends
Поскольку я прокачиваю мышцу Scala, утилитка на написана на ей, родимой.
Enjoy.





original post http://vasnake.blogspot.com/2016/11/weekends-holidays.html

2016-09-11

Dog house

Интересно, как мысли/информация кругами ходит

Цитата

Разрешимость и даже complexity являются математическими игрушками и часто играют злые шутки с инженерами.
...
Представьте что надо написать программу, создающую будку на Х собак, где Х - натуральное. Но задача не решаема в общем виде! На 1-2 собаки надо делать классическую будку типа Плуто, на 3-10 - вольеры из сетки в ряд, а на большее число - уже целые комплексы в инете я видел, т.к. надо решать совершенно другие проблемы вроде массового выгула.

Но точно такая же ситуация например с задачей коммивояжёра. При некоторых размерах она тривиальным циклом решается, при некоторых требует распараллеливания, при некоторых требует суперкомпьютера с хорошим интерконнектом, а при некоторых вообще не имеет физического смысла т.к. ждать годы. Соответственно бред же доказывать что-то для стейт оф зе арт программы для суперкомпьютера за пределами суперкомпьютерных размеров задач.
...
Короче, основная масса работы - это неуниверсальный код, для которого доказывать что он валиден на всей бесконечности натуральных - это какой-то адов оверинжиниринг. Практики не поймут!

Конец цитаты
http://nponeccop.livejournal.com/507802.html

И это замечательно перекликается с выступлением
Alan Kay at OOPSLA 1997 - The computer revolution hasnt happened yet
https://youtu.be/oKg1hTOQXoY


Где у него, внимание, есть пример про собачью будку! Причем примерно в том же контексте.

Обожаю послушать умных людей.







original post http://vasnake.blogspot.com/2016/09/dog-house.html

2016-09-10

Design patterns

Об https://en.wikipedia.org/wiki/Software_design_pattern



Краткое содержание:
паттерны -- это типа словарь, чтобы люди могли говорить на одном языке, обсуждая код.
Культивировать надо понимание (и умение рассуждать об) применимости тех или иных паттернов.

Цитата

Here's the deal with design patterns ... They are observations, not rules. People noticed that programmers seemed to be approaching problems in similar ways in a bunch of different applications, and they decided that it would be pretty useful to be able to talk about those approaches using a common vocabulary so they wouldn't have to keep explaining what they were referring to. So they figured out general versions of these common practices and gave them names like "Visitor" and "Observer."

But the important part is "understand why." The skill you need to cultivate to become a good developer and to be attractive to the kinds of companies in the question isn't plugging together objects from a library of canned formulas, but rather understanding the reasoning behind them deeply enough that, when faced with the same problem, you will arrive at the same solution on your own. And much more importantly, when faced with a similar but not identical problem, you will do something else rather than try to shoehorn the solution into an existing design pattern that's an awkward fit.

Конец цитаты
https://www.quora.com/What-are-the-most-important-design-patterns-that-software-engineers-should-know-to-work-at-Google-Amazon-and-Facebook/answer/Steven-Grimm






original post http://vasnake.blogspot.com/2016/09/design-patterns.html

2016-09-01

UPS

Четыре года.
Четыре года продержались аккумуляторы в ИБП. Неплохой результат, на замену заказал похожие (точно таких уже не делают).
Как выяснилось, такие батарейки ценятся не только мною, на рынке цена у них в верхней части спектра.

Было:
Battery 12V 7AH Rechargeable battery 12 V 7 AH for UPS, Dimensions: 151 x 65 x 95 mm,
Yuasa NPW36-12 12V/7AH
Куплено в 2012 году в Джасте по 690 рублей/штука. + 290 доставка.

Стало:
Батарея Yuasa NP7-12 12В/7А, артикул 211231, Размеры (ШхГхВ),мм 65х151х97,5
Тоже в Джасте, 1330 руб./штука + 290 доставка.
Забавно, чисто локальный продукт, «доставка» в цене не изменился. Это как же упали доходы курьеров? Или объемами возмещают?


Посмотрим, как эти себя покажут.
ЧСХ, сам UPS пашет и пашет, лет 10 уже, наверное.
Правда, умершие батарейки не показал, хотя индикация всякая есть.
Просто на днях не смог удержать перебоя в питании, компы отключились.
Стал проверять: один комп держит, два уже нет.
UPS Powercom IMD-1025AP







original post http://vasnake.blogspot.com/2016/09/ups.html

2016-08-26

Decoupling

Замечательная идея: отсоединить I/O от конкретного протокола, скажем, HTTP.
Цитирую:

In a word: reusability. By implementing network protocols without any I/O and instead operating on bytes or text alone, libraries allow for reuse by other code regardless of their I/O decisions. In other words by leaving I/O out of the picture a network protocol library allows itself to be used by both synchronous and asynchronous I/O code. And by not simply abstracting out the I/O it allows users of the library to drive the network interactions themselves, not the network protocol library itself; not forcing I/O code to have to conform to a certain API provides the greatest flexibility for users of such low-level details such as network protocols. Working towards this unbinding of network protocols from I/O is very important as the Python community migrates from synchronous I/O code to using async/await for asynchronous I/O.

https://sans-io.readthedocs.io/

Не важно, как ты делаешь I/O, ты, главное, массив байтов или строку текста дай на вход и bob-your-uncle.



original post http://vasnake.blogspot.com/2016/08/decoupling.html

Cartobonus/Картобонус

Как сказал один умный человек, если хочешь сделать резервную копию для Х, выложи это Х в Интернет, пусть люди сами копируют.

Не то, чтобы я стремился сделать резервную копию Картобонуса, но времени, потраченного на его создание и развитие жаль. Поэтому, пусть будет общедоступен, может кому и пригодится.

Картобонус, проект, который не «выстрелил»:


Web map viewer, built on ArcGIS API for Silverlight.
Вместе с mapfeatureserver https://github.com/vasnake/mapfeatureserver
должен был образовать очень привлекательную комбинацию. Но, не судьба.

Информация по теме:

Когда стало понятно, что Silverlight должен умереть, мы начали пилить картобонус на JavaScript:
Кое-что сделать удалось: нормальную «легенду/TOC», репозиторий подключаемых слоев – базовые фишки картобонуса.

А потом кризис добрался и до нас. RIP, картобонус.





original post http://vasnake.blogspot.com/2016/08/cartobonus.html

2016-08-17

produce a random BigInt and convert it to base 36

В книжке Scala for the Impatient есть удивительная задачка:
produce a random BigInt and convert it to base 36,
yielding a string such as 'qsnvbevtomcj38o06kul' ...

Удивительна она не тем, что надо как-то сгенерить рандомный BigInt, или перевести его из base2 (or base10) в base36. Удивительна она тем, что масса народу дает неправильный (очевидно неправильный) ответ.
Просто загуглите и почитайте. Самый распространенный ответ:
BigInt.probablePrime(100, util.Random).toString(36)
Дурдом.

В задаче четко сказано: рандомный бигинт а не рандомный какбы прайм.
Что характерно, эта задачка дана сразу после главы, где разжевано, как пользоваться Scaladoc.
Мало того, в самой задачке сказано: Poke around Scaladoc to find a way...

Короче, внимательно поглядев на Scaladoc в раздел BigInt можно быстро найти правильный ответ:
BigInt(128, util.Random) toString 36


И эти люди пишут нам программы? Боже упаси.




original post http://vasnake.blogspot.com/2016/08/produce-random-bigint-and-convert-it-to.html

BerkeleyX: CS190.1x Scalable Machine Learning, digest

Курс
BerkeleyX: CS190.1x Scalable Machine Learning

и мои подробные конспекты

экстра

Пришла пора обновить память и скомпилять это все в дайджест.

Content

In this course, you will learn how to write and debug Python Spark (pySpark) programs in five weekly lab exercises

WEEK 0: Setup Course Software Environment
Topics: Step-by-step instructions for installing / using the course software environment, and submitting assignments to the course autograder.

WEEK 1: Course Overview and Introduction to Machine Learning
Topics: Course goals, Apache Spark overview, basic machine learning concepts, steps of typical supervised learning pipelines, linear algebra review, computational complexity / big O notation review.
Lab 1: NumPy, Linear Algebra, and Lambda Function Review.

WEEK 2: Introduction to Apache Spark
Topics: Big data and hardware trends, history of Apache Spark, Spark's Resilient Distributed Datasets (RDDs), transformations, and actions.
Lab 2: Learning Apache Spark. Perform your first course lab where you will learn about the Spark data model, transformations, and actions, and write a word counting program to count the words in all of Shakespeare's plays.

WEEK 3: Linear Regression and Distributed Machine Learning Principles
Topics: Linear regression formulation and closed-form solution, distributed machine learning principles (related to computation, storage, and communication), gradient descent, quadratic features, grid search.
Lab 3: Millionsong Regression Pipeline. Develop an end-to-end linear regression pipeline to predict the release year of a song given a set of audio features. You will implement a gradient descent solver for linear regression, use Spark's machine Learning library ( mllib) to train additional models, tune models via grid search, improve accuracy using quadratic features, and visualize various intermediate results to build intuition.

WEEK 4: Logistic Regression and Click-through Rate Prediction
Topics: Online advertising, linear classification, logistic regression, working with probabilistic predictions, categorical data and one-hot-encoding, feature hashing for dimensionality reduction.
Lab 4: Click-through Rate Prediction Pipeline. Construct a logistic regression pipeline to predict click-through rate using data from a recent Kaggle competition. You will extract numerical features from the raw categorical data using one-hot-encoding, reduce the dimensionality of these features via hashing, train logistic regression models using mllib, tune hyperparameter via grid search, and interpret probabilistic predictions via a ROC plot.

WEEK 5: Principal Component Analysis and Neuroimaging
Topics: Introduction to neuroscience and neuroimaging data, exploratory data analysis, principal component analysis (PCA) formulations and solution, distributed PCA.
Lab 5: Neuroimaging Analysis via PCA - Identify patterns of brain activity in larval zebrafish. You will work with time-varying images (generated using a technique called light-sheet microscopy) that capture a zebrafish's neural activity as it is presented with a moving visual pattern. After implementing distributed PCA from scratch and gaining intuition by working with synthetic data, you will use PCA to identify distinct patterns across the zebrafish brain that are induced by different types of stimuli.

Digest...

2016-08-11

Machine Learning (Andrew Ng, Coursera, Stanford)

В далеком 2014 году я открыл для себя новое измерение: возможность учиться у лучших.
Все, что нужно, это компьютер, интернет и знание английского языка.

Первый курс, который я прошел (с отличием!), назывался
Machine Learning
читал его Andrew Ng
на платформе Coursera, Stanford

Вот тут есть подробное изложение изученного:

Сегодня, с целью взбодрить память, я скомпилял типа дайджест курса.
Енджой.



Week 1
    Introduction
    Linear Regression with One Variable
    (Optional) Linear Algebra Review
Week 2
    Linear Regression with Multiple Variables
    Octave Tutorial
Week 3
    Logistic Regression
    Regularization
Week 4
    Neural Networks: Representation
Week 5
    Neural Networks: Learning
Week 6
    Advice for Applying Machine Learning
    Machine Learning System Design
Week 7
    Support Vector Machines (SVMs)
Week 8
    Clustering
    Dimensionality Reduction
Week 9
    Anomaly Detection
    Recommender Systems
Week 10
    Large-Scale Machine Learning
    Example of an application of machine learning

2016-08-04

Principles of Reactive Programming (Scala)

И снова про Reactive Programming.
На Курсере был такой курс «Principles of Reactive Programming». К сожалению – был. Больше нет.
К большому сожалению, ибо материал там убойный, на базе Scala.

Старые курсы они перетряхнули, получилось
но от реактивности там ничего не осталось. Зато параллельность появилась, тоже неплохо.

Но не все потеряно: я сохранил все видеолекции



а также все задачки-assignments, вместе с сопроводительной документацией
равно как и сниппеты кода, приводимые на лекциях.

И сегодня (вернее, вчера) я этот курс закончил: закодил решение последней задачки:
replicated KV store на акторах Akka.

Круто!

Кто хочет одолеть реактивное программирование на Scala – велкам, смотрите лекции, решайте задачки.






original post http://vasnake.blogspot.com/2016/08/principles-of-reactive-programming-scala.html

2016-07-31

Dynamic Programming

Всё, что вы хотели знать про Dynamic Programming
-- brute-force, memoization, subproblems, guess, recursion.

Лекции от Erik Demaine (MIT)
https://youtu.be/ENyox7kNKeY


http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-videos/

В частности,
1. что такое memoization, почему так называется?
2. Почему Dynamic Programming, откуда такое название?

1: Memo pad, внесение заметок в memo pad -- memoization.
2: Ученый работал на вояк и не мог сказать, что занимается "исследованиями", поэтому придумал загадочный термин, чтобы генералы не доебались.





original post http://vasnake.blogspot.com/2016/07/dynamic-programming.html

2016-07-20

Spark 2

Apache Spark 2: DataFrames, Datasets, Streaming.

Серьезные изменения в скорости и возможностях
https://www.youtube.com/playlist?list=PL-x35fyliRwiz70bTSSK4HmOZ4JazCFUj

https://www.google.com/search?q=spark+2+dataframe+dataset+streaming

https://spark-summit.org/2016/schedule/





original post http://vasnake.blogspot.com/2016/07/spark-2.html

2016-07-15

FP

Всем, кто начал вникать в functional programming, смотреть и слушать обязательно:

Основные принципы объясняются настолько доступно, что даже я всё понял.

О чём речь, собственно:

Core Principles of FP design
– functions, types, composition
Functions as parameters
– functions as interface
– partial application & dependency injection
– continuations, chaining & the pyramid of doom
Monads
– error handling, async
Maps
– dealing with wrapped data
– functors
Monoids
– aggregating data and operations


types are not classes (more like sets, valid input/output values)

types separate data from behaviour, can compose types

algebraic types; product types; sum types (choice/union)

totality, total/partial functions

for composition you need functions with one parameter:
currying – every function is a one parameter function

currying/partial application – dependency injection, continuations

chaining continuations takes us to monads: monadic bind;
use bind to chain error handlers, Railway Oriented Programming

Mappable types are 'functors':
Option.map: lifting operations to Option world / List, Future, … other monads and wrapped types

monoid: math term: closure + 'zero' (identity element) + associativity
semigroup = monoid – zero

any combination of monoids = monoid; define a combinator and get aggregation for free (reduce);
incremental updates, parallelizm, missing data handling

convert non-monoid (customer) to a monoid (customerStats), using map;
… reduce // 'Hadoop make me a sandwich'

convert expensive monoids to cheap monoids: map blocks to aggregated data, incremental updates;
monoid homomorphism

monoid from functions? input type == output type: endomorphism (remember monoid closure?);
all endomorphisms are monoids, you can aggregate them
example: Event Sourcing

monads are monoids: monoid in the category of endofunctors.


Hadoop make me a sandwich:
оригинал ищите в твиттере




Отсмотрено по наводке http://thedeemon.livejournal.com/112356.html









original post http://vasnake.blogspot.com/2016/07/fp.html

2016-07-06

Подрезово-1

Сегодня устроили себе каталку в Подрезово - 1, на Пироговском водохранилище.
Я про это место ранее писал: http://vasnake.blogspot.com/2016/07/blog-post.html

На парковку пляжную, за шлагбаумом, пустили за 250 рублей. Деньги пошли вратарю на карман -- ни чека, ни карточки я не видел. Несмотря на это, подъехать поближе к воде не разрешили, даже на 5 минут для разгрузки/погрузки. Не положено.
Пришлось матчасть на горбу тащить метров 150.

Пляж хороший, но грязновато.

Прогноз был: юго-западный ветер 8-12 м/с. На самом деле было что-то вроде 5-10 м/с с редкими порывами до 12. Что хуже -- ветер на редкость рваный, порывы по нескольку секунд, тольком разогнаться не успеешь. Все руки себе оборвал.

Хреновая каталка получилась.






original post http://vasnake.blogspot.com/2016/07/1.html

2016-07-04

Scala Type Classes

Что-то поперло про type classes, просто поперло.
Только на днях я упоминал зачетные слайды https://speakerdeck.com/raulraja/typeclasses-tour

Не прошло и недели, как мне попадается изумительный материал про тайп классы

Настолько все доступно изложено, что даже я всё понял.
И применил на практике:

Идея очень проста и отвечает на запрос: как нам облегчить ad-hoc polymorphism в системах со строгой типизацией? Нужно абстрагировать некий алгоритм, повысить степень DRY.

Ну как, делаем интерфейс, реализуем алгоритм в терминах этого интерфейса. Реализацию интерфейса подмешиваем в нужный класс – опля, этот класс можно пихать в упомянутый алгоритм.
Проверка типов в Scala делается через implicit переменные.


Повторюсь: как же люди без дактайпинга мучаются. Зато всё под контролем.




original post http://vasnake.blogspot.com/2016/07/scala-type-classes.html

2016-07-02

About Typeclasses, Spark and other FP shit

Я просто оставлю это здесь.

Пара материалов, опубликованных в недельной подборке на 47 Degrees
http://www.47deg.com/blog/fp-news-update-week-of-7-01

Как люди мучаются без ducktyping: вот, придумали typeclasses для выхода на следующий уровень абстракции. Зато всё под контролем
https://speakerdeck.com/raulraja/typeclasses-tour


12 видеороликов про Спарк
The video presentations from Spark Summit this June
https://www.youtube.com/watch?list=PL-x35fyliRwiz70bTSSK4HmOZ4JazCFUj&v=1a4pgYzeFwE






original post http://vasnake.blogspot.com/2016/07/about-typeclasses-spark-and-other-fp.html

2016-07-01

Пара пляжей на Пироговском

Сегодня разведали два пляжа на Пироговском водохранилище.
На обоих виндсерфер может выйти на воду относительно легко.
А если одолеет шлагбаум, так и вовсе заипца.
https://maps.yandex.ru/?um=constructor:WaVdZ4EoSLnD3jjLMAjycx1l4Y0d-XtV&source=constructor

Parallel computing: Amdahl's law

Закон Амдала ограничивает применимость параллельных вычислений.

Нет, не так. Закон устанавливает границы на количество параллельных процессов.
Обратно не так. Бляха. Короче:
любая задача, которую можно посчитать параллельно, имеет границу, после которой увеличение параллелизма уже не помогает ускорить вычисления.

Два прикольных видео на тему

Understanding Parallel Computing: Amdahl's Law



Understanding Parallel Computing (Part 2): The Lawn Mower Law



И одно серъезное

Amdahl's Law in the Multicore Era




original post http://vasnake.blogspot.com/2016/07/parallel-computing-amdahls-law.html

2016-06-30

2,3 from 5: Functional Programming in Scala Specialization

Еще одна зарубка: сегодня закончил очередной курс.

Месяц назад на Курсере открылся новый сет:
Functional Programming in Scala Specialization
4 курса и финальный проект, на тему функционального программирования в целом и Scala в частности.

Первый и второй курс сета сделаны на основе старых
-- Functional Programming Principles in Scala
-- Principles of Reactive Programming

К сожалению, большая часть Principles of Reactive Programming в новый сет не вошла, только малая часть про монады, фьючеры и стримы/эвенты.
Но это не беда, я сохранил все материалы и, со временем, изучу их в подробностях.

Как бы то ни было, чтобы участвовать в пятой части сета, финальном проекте, надо успешно пройти четыре предварительных курса. Чем я и занялся.

На сегодняшний день пройдены 3 курса:
-- Functional Programming Principles in Scala (дайджест составлен)
-- Functional Program Design in Scala (дайджест будет)
-- Parallel programming (дайджест будет)

Это было непросто, за месяц пройти аж 3 курса. Только благодаря тому, что с первыми двумя я уже был знаком, удалось прорваться в финал и не порваться.

Теперь жду, когда начнут вещать четвертый курс: Big Data Analysis with Scala and Spark.
А чтобы время не терять, займусь дайджестами пройденного. Stay tuned.




original post http://vasnake.blogspot.com/2016/06/23-from-5-functional-programming-in.html

2016-06-25

Пироговское водохранилище, Марабу

Съездили сегодня на разведку, на Пироговское водохранилище, Ореховая бухта, в клуб Марабу.
Заценить, как-что-почем в плане виндсерфинга.

Широта 55°58′26″N (55.973891) Долгота 37°39′52″E (37.664384)
https://yandex.ru/maps/-/CVXNB059
https://goo.gl/MnturU


Впечатления

Последний километр дороги -- полный пиздей подвеске, ямы, бетонные плиты вкривь и вкось.
Есть место, где при хорошем дожде дорогу может подмыть, есть риск провала.
После шлагбаума -- грунтовка терпимого качества, пока сухо.
На шлагбауме могут потребовать 200 рублей. Местные говорят, что можно бесплатно, если
"я везу оборудование в Марабу, туда и сразу обратно".
Удобного выхода к воде нет, надо лазить по горе вверх-вниз. Есть лестницы.
Все заросло деревьями, кустами, развернуться негде.
Где вооружаться -- неясно, то ли на мостках, то ли в лесу.
Стартовать с мостков (и возвращаться) -- сомнительное удовольствие, скорее всего парус будет порван.
Хранилка: 5000 руб/мес, паруса не в контейнере а под навесом. WTF!
http://www.marabou.ru/part.php?prt=service
На воде довольно много народу всякого.

Плюсы? Недалеко от нерезиновой, большой водоем, нет комаров, рядом цивилизация: кафе, яхт-клуб, все дела.
Вменяемые цены на аренду оборудования.

Фоток не сделал, что там фотать... вот, в тырнетах нашлось




По поводу хранилки посоветовали обратиться к Александру
89166068025 Александр





original post http://vasnake.blogspot.com/2016/06/blog-post.html

2016-06-01

super, MRO

Python, всё, что вам надо знать про функцию 'super' и Method Resolution Order

цитата

The super built-in function was introduced way back in Python 2.2. The super function will return a proxy object that will delegate method calls to a parent or sibling class of type. If that was a little unclear, what it allows you to do is access inherited methods that have been overridden in a class
...

class MyParentClass(object):
    def __init__(self):
        pass
 
class SubClass(MyParentClass):
    def __init__(self):
        MyParentClass.__init__(self)

class SubClass(MyParentClass):
    def __init__(self):
        super(SubClass, self).__init__()

Python 3 simplified this a bit. Let’s take a look:
class MyParentClass():
    def __init__(self):
        pass
 
class SubClass(MyParentClass):
    def __init__(self):
        super()

...
super knows how to interpret the MRO and it stores this information in the following magic propertie: __thisclass__ and __self_class__. Let’s look at an example:
class Base():
    def __init__(self):
        s = super()
        print(s.__thisclass__)
        print(s.__self_class__)
        s.__init__()
 
class SubClass(Base):
    pass
 
sub = SubClass()
http://www.blog.pythonlibrary.org/2016/05/25/python-201-super/

И про MRO 

цитата

 Everything started with a post by Samuele Pedroni to the Python development mailing list. In his post, Samuele showed that the Python 2.2 method resolution order is not monotonic and he proposed to replace it with the C3 method resolution order. Guido agreed with his arguments and therefore now Python 2.3 uses C3. The C3 method itself has nothing to do with Python, since it was invented by people working on Dylan ...
 The list of the ancestors of a class C, including the class itself, ordered from the nearest ancestor to the furthest, is called the class precedence list or the linearization of C.
...
 The Method Resolution Order (MRO) is the set of rules that construct the linearization. In the Python literature, the idiom "the MRO of C" is also used as a synonymous for the linearization of the class C.
 ...
 A MRO is monotonic when the following is true: if C1 precedes C2 in the linearization of C, then C1 precedes C2 in the linearization of any subclass of C. Otherwise, the innocuous operation of deriving a new class could change the resolution order of methods, potentially introducing very subtle bugs.
 ...
 C3 MRO the linearization of C is the sum of C plus the merge of the linearizations of the parents and the list of the parents.
 L[C(B1 ... BN)] = C + merge(L[B1] ... L[BN], B1 ... BN)
 ...
 take the head of the first list, i.e L[B1][0]; if this head is not in the tail of any of the other lists, then add it to the linearization of C and remove it from the lists in the merge, otherwise look at the head of the next list and take it, if it is a good head. Then repeat the operation until all the class are removed or it is impossible to find good heads. In this case, it is impossible to construct the merge, Python 2.3 will refuse to create the class C and will raise an exception.
 ...
 Guido points out in his essay that the classic MRO is not so bad in practice, since one can typically avoids diamonds for classic classes. But all new style classes inherit from object, therefore diamonds are unavoidable and inconsistencies shows up in every multiple inheritance graph.

  https://www.python.org/download/releases/2.3/mro/




original post http://vasnake.blogspot.com/2016/06/super-mro.html

2016-05-22

dynamic vs static

Попалась на глаза интересная диаграмма

 The following are some charts that compare the number of issues labelled "bug" versus the number of repositories in GitHub for different languages. I also tried removing some noise by just using repositories with some stars, on the assumption that repositories with no stars means that nobody is using them, so nobody will report bugs against them.

In green, in the "advanced" static typed languages corner: Haskell, Scala and F#.
In orange, in the "old and boring" static typed languages corner: Java, C++ and Go.
In red, in the dynamic typed language corner: JavaScript, Ruby, Python, Clojure and Erlang


http://labs.ig.com/static-typing-promise

Автор пытается разобраться в вопросе, правда ли, что статическая типизация помогает писать безбажные программы? И в конце делает вывод, что, похоже, нет, не помогает.

Лично я, глядя на эту диаграмму, вижу зависимость (корреляцию) количества багов от "элитарности" языка.
Упрощая, можно сказать, что языками из верхней, безбажной половины списка пользуются программеры с изрядным количеством опыта и мозгов. Очевидно, такие спецы пишут сразу практически без ошибок.
В связи с этим, печально видеть, что любимый Питончик находится в нижней части списка. Превратился в ширпотреб.

Ну а если рассуждать о пользе статической типизации, то в исследование надо добавить много дополнительного материала. Например, количество времени, которое тратит средний программист на написание и отладку некоего блока кода.





original post http://vasnake.blogspot.com/2016/05/dynamic-vs-static.html

2016-05-19

What are you doing? Teaching

“Hello, Professor McGonagall,” said Moody calmly, bouncing the ferret still higher.
“What — what are you doing?” said Professor McGonagall, her eyes following the bouncing ferret’s progress through the air.
“Teaching,” said Moody.
“Teach — Moody, is that a student?” shrieked Professor McGonagall, the books spilling out of her arms.
“Yep,” said Moody.

Совершенно изумительно это звучит в исполнении Стивена Фрая (аудиокнига Harry Potter and the Goblet of Fire, Book 4). Как я с утра это услышал, так на полдня прекрасное настроение.

В кино не совсем так
https://youtu.be/HobPkv5TELA?t=24s





original post http://vasnake.blogspot.com/2016/05/what-are-you-doing-teaching.html

To ensure the security and continuing stability

Бугагашеньки

Для обеспечения стабильности и безопасности ...

нарекаю себя императором

Это из
Star Wars Episode III - Revenge of the Sith (2005)
речь Путина Палпатина темного лорда в сенате.
Смотреть с 33 секунды


https://youtu.be/dO1QifRr3J0?t=33s

ЧСХ, несмотря на то, что это во всех учебниках обсосано, не в коня корм.

Кстати, Звездные Войны очень наглядно показывают, как, с помощью нехитрых интриг, захватить власть в галактике.



original post http://vasnake.blogspot.com/2016/05/to-ensure-security-and-continuing.html

2016-05-16

Чем отличается побитый молью программист

К вопросу о том, чем отличается побитый молью программист от зеленого новичка:

Здесь приводится 42 рекомендации по программированию, которые помогут избежать множества ошибок, сэкономить время и нервы. Автором рекомендаций выступает Андрей Карпов - технический директор компании "СиПроВер", разрабатывающей статический анализатор кода PVS-Studio. За свою практику он насмотрелся на огромное количество способов отстрелить себе ногу; ему явно есть, о чем поведать читателю. Каждая рекомендация сопровождается практическим примером, что подтверждает актуальность поднятого вопроса. Советы ориентированы на C/C++ программистов
http://www.viva64.com/ru/b/0391/

Опытный воин уже видел все эти грабли, многие из них оставили на его лбу памятные знаки.
Поэтому нет нужды объяснять синьору, что программы надо писать проще и понятнее, для людей. Чтобы люди их читали легко и непринужденно.
Чем меньше кода (привет функциональщикам) и чем он понятнее, тем легче избежать всяких разных ошибок.
Ошибки были, есть и будут. Надо стремиться к тому, чтобы находить и устранять их как можно раньше.




original post http://vasnake.blogspot.com/2016/05/blog-post.html

2016-05-12

Exercises

Упражнения и задачки к курсу
Algorithms, Part II. Princeton University, Robert Sedgewick

Algorithms, Part II. Princeton University, Robert Sedgewick

Краткое изложение 7-недельного курса

Очень полезный и относительно тяжелый курс для wannabe программеров:
Algorithms, Part II by Robert Sedgewick
Algorithms, 4th edition textbook libraries https://github.com/kevin-wayne/algs4

Допы
-- Python implementations of selected Princeton Java Algorithms and Clients by Robert Sedgewick and Kevin Wayne
-- Scala translations of Robert Sedgewick's Java Algorthms

Про первую часть курса ищите здесь http://vasnake.blogspot.com/2016/03/algorithms-part-i-princeton-university.html

This course covers the essential information that every serious programmer needs to know about algorithms and data structures, with emphasis on applications and scientific performance analysis of Java implementations.
Part II covers graph-processing algorithms, including minimum spanning tree and shortest paths algorithms,
and string processing algorithms, including string sorts, tries, substring search, regular expressions, and data compression,
and concludes with an overview placing the contents of the course in a larger context.

Курс тяжелый по двум причинам:
– Роберт, прямо скажу, хреново читает лекции. Лично на меня его голос действует как мощное снотворное.
Несколько бодрее дело идет, если скорость воспроизведения поставить 1.25.
Мало того, некоторые важные моменты он оставляет для самостоятельного изучения, типа, читайте мою книгу.
Придется читать, книга полезная.
– Трудоемкие упражнения; непростые задачки (особенно доставляет система тестов). Надо долго думать и изучать доп. материалы.

Поэтому времени уходит масса. Но оно того стоит.

За 6 недель изучено:

Chapter 4: Graphs surveys the most important graph processing problems, including depth-first search, breadth-first search, minimum spanning trees, and shortest paths.
Chapter 5: Strings investigates specialized algorithms for string processing, including radix sorting, substring search, tries, regular expressions, and data compression.
И прочее.

А именно:

Week 1

Lecture: Undirected Graphs. We define an undirected graph API and consider the adjacency-matrix and adjacency-lists representations. We introduce two classic algorithms for searching a graph—depth-first search and breadth-first search. We also consider the problem of computing connected components and conclude with related problems and applications.

Lecture: Directed Graphs. In this lecture we study directed graphs. We begin with depth-first search and breadth-first search in digraphs and describe applications ranging from garbage collection to web crawling. Next, we introduce a depth-first search based algorithm for computing the topological order of an acyclic digraph. Finally, we implement the Kosaraju-Sharir algorithm for computing the strong components of a digraph.

Week 2

Lecture: Minimum Spanning Trees. In this lecture we study the minimum spanning tree problem. We begin by considering a generic greedy algorithm for the problem. Next, we consider and implement two classic algorithm for the problem—Kruskal's algorithm and Prim's algorithm. We conclude with some applications and open problems.

Lecture: Shortest Paths. In this lecture we study shortest-paths problems. We begin by analyzing some basic properties of shortest paths and a generic algorithm for the problem. We introduce and analyze Dijkstra's algorithm for shortest-paths problems with nonnegative weights. Next, we consider an even faster algorithm for DAGs, which works even if the weights are negative. We conclude with the Bellman-Ford-Moore algorithm for edge-weighted digraphs with no negative cycles. We also consider applications ranging from content-aware fill to arbitrage.

Week 3

Lecture: Maximum Flow and Minimum Cut. In this lecture we introduce the maximum flow and minimum cut problems. We begin with the Ford-Fulkerson algorithm. To analyze its correctness, we establish the maxflow-mincut theorem. Next, we consider an efficient implementation of the Ford-Fulkerson algorithm, using the shortest augmenting path rule. Finally, we consider applications, including bipartite matching and baseball elimination.

Lecture: Radix Sorts. In this lecture we consider specialized sorting algorithms for strings and related objects. We begin with a subroutine (key-indexed counting) to sort integers in a small range. We then consider two classic radix sorting algorithms—LSD and MSD radix sorts. Next, we consider an especially efficient variant, which is a hybrid of MSD radix sort and quicksort known as 3-way radix quicksort. We conclude with suffix sorting and related applications.

Week 5

Lecture: Tries. In this lecture we consider specialized algorithms for symbol tables with string keys. Our goal is a data structure that is as fast as hashing and even more flexible than binary search trees. We begin with multiway tries; next we consider ternary search tries. Finally, we consider character-based operations, including prefix match and longest prefix, and related applications.

Lecture: Substring Search. In this lecture we consider algorithms for searching for a substring in a piece of text. We begin with a brute-force algorithm, whose running time is quadratic in the worst case. Next, we consider the ingenious Knuth-Morris-Pratt algorithm whose running time is guaranteed to be linear in the worst case. Then, we introduce the Boyer-Moore algorithm, whose running time is sublinear on typical inputs. Finally, we consider the Rabin-Karp fingerprint algorithm, which uses hashing in a clever way to solve the substring search and related problems.

Week 6

Lecture: Regular Expressions. A regular expression is a method for specifying a set of strings. Our topic for this lecture is the famous grep algorithm that determines whether a given text contains any substring from the set. We examine an efficient implementation that makes use of our digraph reachability implementation from Week 1.

Lecture: Data Compression. We study and implement several classic data compression schemes, including run-length coding, Huffman compression, and LZW compression. We develop efficient implementations from first principles using a Java library for manipulating binary data that we developed for this purpose, based on priority queue and symbol table implementations from earlier lectures.

Week 7

Lecture: Reductions. In this lecture our goal is to develop ways to classify problems according to their computational requirements. We introduce the concept of reduction as a technique for studying the relationship among problems. People use reductions to design algorithms, establish lower bounds, and classify problems in terms of their computational requirements.

Lecture (optional): Linear Programming. The quintessential problem-solving model is known as linear programming, and the simplex method for solving it is one of the most widely used algorithms. In this lecture, we given an overview of this central topic in operations research and describe its relationship to algorithms that we have considered.

Lecture: Intractability. Is there a universal problem-solving model to which all problems that we would like to solve reduce and for which we know an efficient algorithm? You may be surprised to learn that we do no know the answer to this question. In this lecture we introduce the complexity classes P, NP, and NP-complete, pose the famous P=NP question, and consider implications in the context of algorithms that we have treated in this course.


2016-04-27

KISS

Keep It Simple, Stupid

Занятное выступление Maciej Cegłowski: The Website Obesity Crisis
http://idlewords.com/talks/website_obesity.htm
https://vimeo.com/147806338

  1. The Crisis
  2. Fake Fixes
  3. Fat Ads
  4. Fat Assets
  5. Chickenshit Minimalism
  6. Interface Sprawl
  7. Heavy Clouds
  8. Stirring Conclusion

Вкратце, суть в том, что разработчики и паблишеры, в погоне за деньгами, засрали весь Интернет тяжеловесным говном, которое невозможно прокачать по слабым каналам и которым невозможно пользоваться.

Интересные наблюдения, живое изложение. СтОит ознакомиться.



original post http://vasnake.blogspot.com/2016/04/kiss.html

2016-04-15

left-pad

Да (задумчиво, растягивая гласные), господа-товарищи, мда.
Перефразируя, это было бы смешно, если бы не реакция публики.

Цитирую, с купюрами

... React, Babel и куча других популярных пакетов на NPM сломались. Причина довольно удивительная.

Простой пакет NPM под названием left-pad был установлен как зависимость в React, Babel и других пакетах. ... Весь пакет состоит из 11 простых строчек, которые реализуют примитивную функцию вставки пробелов в левой части строк
...
Узнав о бедствии, которое случилось из-за left-pad, я начал исследовать экосистему NPM. И вот что обнаружил, среди прочего:

    Есть пакет под названием isArray, который скачивают 880 000 раз в день, 18 млн скачиваний в феврале 2016 года. У него 72 зависимых NPM-пакета. И вот его целая 1 строчка кода:

    return toString.call(arr) == '[object Array]';

    Есть пакет под названием is-positive-integer ..., который состоит из 4 строчек и которому на вчерашний день требовалось 3 других пакета для работы. ...
    Свежая установка Babel включает 41 000 файлов
    Чистый шаблон приложения на базе jspm/npm начинается c 28 000+ файлов

Всё это заставляет задать вопрос…

http://www.haneycodes.net/npm-left-pad-have-we-forgotten-how-to-program/
https://habrahabr.ru/post/280099/

Вопрос автора, изложенный моими словами: говнокодеры, вы охуели в атаке?

Ситуация реально смешная: человекоподобные строят системы не приходя в сознание. Как будто их и не учили ничему, кроме как гуглить и копипастить.
Но вот реакция публики на заданный автором вопрос давит смех на корню. Охулиард пиплов не видит проблемы или видит ее в мутабельности репозитория пакетов.

Лично меня беспокоит только одно: когда уже наша цивилизация накроется ЖПП (ака медный таз)?
Запас прочности ниибацца, раз живы до сих пор.

P.S.
Вот, на близкую тему
http://blog.jdevelop.com/software/2016/04/07/opensource.html





original post http://vasnake.blogspot.com/2016/04/left-pad.html

2016-04-14

Колеса

Колеса в смысле шины, автомобильные.

Блин, что-то с погодой не то. Сижу, учу алгоритмы, десять минут, двадцать, … глазки начинают закатываться, голова падает на клавиатуру, раздается мощный храп.
Надо что-то бодрящее забацать. Вот, про шины псто.

Есть проблема: на переднеприводной машине образовалось два колеса относительно свежих и два относительно походивших.
Вопрос: на какую ось (переднюю али заднюю) ставить свежие шины?

Немаловажное уточнение: шины летние. С зимними шинами экспериментировать/экономить не надо. Трупам и калекам сэкономленные копейки не помогут.

К примеру: катались вы катались, года два-три, бац, порвали шину. Кто при деньгах и при уме, рваную выкинет, из оставшихся трех выберет самую уставшую и продаст ее. Купит две новых шины той же модели.
Кто без денег, рваную починит и сделает из нее запаску. А на бывшей запаске будет ездить.
Но оба будут думать: на какую ось, вперед или назад, поставить новую шину?

Существует два диаметрально противоположных мнения по этому поводу.
Давайте разберем.

Мнение первое: новую пару (ну, или одну шину, для бедных) надо ставить на переднюю ось.
Плюс у такого решения только один и к безопасности он отношения не имеет:
передние шины снашиваются быстрее, поэтому, поставив вперед более высокий протектор, можно добиться более равномерного износа всех четырех шин. Чтобы потом поменять все четыре сразу.

Мнение второе: более свежие (с более высоким протектором) шины надо ставить на заднюю ось.
У такого решения плюсов несколько.
– Если вам не повезло и новая шина оказалась с дефектом и лопнула – шансы сдохнуть в канаве или на встречке значительно меньше.
– Когда передняя пара сносится до невозможности, вы купите всего две новые шины. Это заметно дешевле, чем покупать сразу четыре.
– Если вы любите гонять по мокрой дороге, шансы уйти в занос снижаются. Более качественный протектор на задней оси дает несколько дополнительных км/ч до того волнительного момента, когда жопа перестает держать дорогу.
А занос на переднеприводной машине – удовольствие ниже среднего.

Вот, факты изложены, можете начинать говносрач остроконечников с тупоконечниками.
А я, глядя на это, взбодрюсь и пойду дальше штудировать алгоритмы.




origianl post http://vasnake.blogspot.com/2016/04/blog-post.html

Архив блога

Ярлыки

linux (241) python (191) citation (186) web-develop (170) gov.ru (159) video (124) бытовуха (115) sysadm (100) GIS (97) Zope(Plone) (88) бурчалки (84) Book (83) programming (82) грабли (77) Fun (76) development (73) windsurfing (72) Microsoft (64) hiload (62) internet provider (57) opensource (57) security (57) опыт (55) movie (52) Wisdom (51) ML (47) driving (45) hardware (45) language (45) money (42) JS (41) curse (40) bigdata (39) DBMS (38) ArcGIS (34) history (31) PDA (30) howto (30) holyday (29) Google (27) Oracle (27) tourism (27) virtbox (27) health (26) vacation (24) AI (23) Autodesk (23) SQL (23) Java (22) humor (22) knowledge (22) translate (20) CSS (19) cheatsheet (19) hack (19) Apache (16) Manager (15) web-browser (15) Никонов (15) functional programming (14) happiness (14) music (14) todo (14) PHP (13) course (13) scala (13) weapon (13) HTTP. Apache (12) Klaipeda (12) SSH (12) frameworks (12) hero (12) im (12) settings (12) HTML (11) SciTE (11) USA (11) crypto (11) game (11) map (11) HTTPD (9) ODF (9) купи/продай (9) Photo (8) benchmark (8) documentation (8) 3D (7) CS (7) DNS (7) NoSQL (7) cloud (7) django (7) gun (7) matroska (7) telephony (7) Microsoft Office (6) VCS (6) bluetooth (6) pidgin (6) proxy (6) Donald Knuth (5) ETL (5) NVIDIA (5) Palanga (5) REST (5) bash (5) flash (5) keyboard (5) price (5) samba (5) CGI (4) LISP (4) RoR (4) cache (4) car (4) display (4) holywar (4) nginx (4) pistol (4) spark (4) xml (4) Лебедев (4) IDE (3) IE8 (3) J2EE (3) NTFS (3) RDP (3) holiday (3) mount (3) Гоблин (3) кухня (3) урюк (3) AMQP (2) ERP (2) IE7 (2) NAS (2) Naudoc (2) PDF (2) address (2) air (2) british (2) coffee (2) fitness (2) font (2) ftp (2) fuckup (2) messaging (2) notify (2) sharepoint (2) ssl/tls (2) stardict (2) tests (2) tunnel (2) udev (2) APT (1) CRUD (1) Canyonlands (1) Cyprus (1) DVDShrink (1) Jabber (1) K9Copy (1) Matlab (1) Portugal (1) VBA (1) WD My Book (1) autoit (1) bike (1) cannabis (1) chat (1) concurrent (1) dbf (1) ext4 (1) idioten (1) join (1) krusader (1) license (1) life (1) migration (1) mindmap (1) navitel (1) pneumatic weapon (1) quiz (1) regexp (1) robot (1) science (1) serialization (1) spatial (1) tie (1) vim (1) Науру (1) крысы (1) налоги (1) пианино (1)