C# async/await in depth

01. C# Async/Await/Task Explained (Deep Dive). (Channel “Raw Coding”).
“In this tutorial we conver the asynchronous programming style in C# we take a deep diving looking at the state machine that the async keyword spawns. How the await keyword creates checkpoints in the state machine. And how the Task class allows us to bridge our code to use the asynchronous programming model.”

02. How to use Async/Await/Task in C#. (Channel “Raw Coding”)
“In this tutorial we take a look at how to use async, await and Task in C#. Primarily looking at good practices and how to avoid common pitfalls such as creating unecessary state machines, blocking threads, using ConfigureAwait when making libraries and how to avoid async in constructors.”

Related videos…

Smart Hasher – hasher with many convenient features implemented on python

Smart Hasher is an Open Source command-line tool with many convenient features.

It is available on GitHub https://github.com/sergtk/smart_hasher

I have just completed the implementation of many features I wanted to have and I didn’t find in other tools.

The story of this project

Before starting this project I needed to calculate a hash function for many large files to be confident that they are not corrupted. These files were in the cloud.

So I tried some Windows native tools, and found some non-native ones, and started to use them. Many of them support just MD5 hash which is now considered obsolete.
I would prefer the SHA-1. I also added support for some other popular hash algorithms, the full list follows: md5, sha1, sha224, sha256, sha384, sha512. All of them are supported by python out of the box by the library hashlib.

The following thing happened when I tried to calculate hash for files in the cloud. Some of the 4 Gb files were handled about 10-20 minutes, some are much longer. I could not realize what is going on. During the whole night the hash was calculated for several files only. Something similar happened in the next several days.
Sometimes tools calculated hash fastly, but not always. Speed was very unstable.
Moreover, other sites, like Youtube, were working fast. When I took my notebook to another network, everything was good with the calculation of the hashes. But again, it was difficult to understand the situation.

So I decided to write a tool to calculate the hashes. And I wanted to see progress easily and conveniently.
I didn’t found any of the hash calculation tools with such features. I could consider using some other tools for diagnostics of network speed but it was not clear what is faster: to use other tools or to write my own which allows me to change it as I want without any restrictions by feature set.

I implemented the tool with the feature to show speed for the whole current file and the last several seconds.
With this data, I already started to mail to cloud support and to call my ISP.
After all, I reached a guy from my ISP. It was quite easy to go through the call center “guards” with speed numbers. That sysadmin guy said to me that there is some strange bug in their software, that occurs on a large amount of data. So actually that guy just needed to close my session and everything worked fast again from my side.
To close the session without reaching the support he suggested me to shut down the Wi-Fi router for half an hour.
Strange story.

Another convenient feature for a large amount of data is to resume calculation after interruption.
This is implemented just by skipping calculation of the hashes for the files for which the hash is already calculated.

Another issue with existing tools is that sometimes a network connection is interrupted for a small period of time. So it is good to retry to read data from the file after a small pause. It is supported by Smart Hasher.

By default for every input data file, the one hash file is created as many other tools do. But it is not always convenient.
For example, if you have a lot of user files, it is not convenient to bloat the directory with a lot of hash files. So I implemented a feature to store all hashes in a single file. After some time, say a year, the hashes can be recalculated again. New and old files may be compared to find differences and to get an idea how user files are changed.
To simplify finding differences, file names are sorted in the hash file.
To find renames there is an option to sort the hash file by hash values because hashes for files are not changed if files are just renamed or moved.
These features are very convenient to check the integrity of our valuable data, e.g. photo archives.

To make it easy to parse file programmatically I also implemented saving data in JSON with python json library. But actually, this is more for practice with python, I didn’t use this feature yet.

There are other features that I didn’t describe here. You may find a description of them in file USAGE.md.

Continue reading “Smart Hasher – hasher with many convenient features implemented on python”

Painless update of third party libraries

Introduction

Sometimes you need to recompile several or all third party libraries in the project you develop. This may happen if you need to switch to another compiler or upgrade version of existing ones.

If you have a lot of libraries in the project you will fix error by error. Third party interfaces are changed. But you can not test everything while you complete fixing all errors.

So it would be good to update piece by piece.

Approaches to achieve update with small pieces described below. Probably you will not find something tricky, but it is good to have small tricks collected in one place. This may be especially useful when you are stuck and bored. This article may help quickly refresh approaches which may be considered to go on.

Continue reading…

Using Git with SVN repository – simple case howto and benefits

Introduction

If you use Apache Subversion repository you may want to use some benefits of Git source control managment system. But you may not have possibilities to switch from SVN repository to Git completely.

One of the large benefits of Git over Subversion is possibility to commit when you don’t have internet connection. Another one is availablility of commit history when there is no internet connection as well.

You may achieve mentioned benefits with Git-SVN functionality described at Git Book chapter “Git and Other Systems – Git and Subversion. There is also git svn man page available.

You will find below how to set up and use some Git benefits when you still continue to work with SVN centralized repository.

It is expected you have some basic knowledge about Subversion and Git before setting up communication between them.

Continue reading…

iOS7 с плоским дизайном – эволюционный шаг вперед

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

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

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

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

Здесь  еще офис Майкрософт вспомнился – весь успех благодаря привычкам людей пользоваться бумагой и разбиением на страницы.

Примерно так я и вижу переход к плоскому дизайну (метро-дизайн) – люди уже довольно хорошо научились пользоваться мобильными устройствам, да и компьютерами в целом.
Поэтому уже нет необходимости проводить аналогии со старым и “привычным”, чтобы легче было учиться – кнопками, тумблерами и тому подобным механическим устройствам управления.
И появляется больше степеней свободы.

Итак.
Дело даже не в плоском интерфейсе, дело даже не в том, будет ли новый интерфейс успешен или нет. А в том, что начался уход от интерфейса, симулирующего объемные объекты.
А что нового покажет Apple еще предстоит увидеть.

Ссылки по теме:
1. “iOS 7” by Matt Gemmell
2. История скевоморфизма в продуктах Apple

Устанавливаем Git под Mac OS X / XCode

Когда начал писать под Mac OS X в XCode, то увидел, что в нем есть поддержка Git.
Решил его и использовать.

Знакомство с git

Если с Git-ом не сталкивались, то може быть полезным сайт git – fast-version-control (есть русский перевод).

Для тех, кто знаком с SVN, может быть полезной статья Git Svn Crash Course. Пользователям Subversion по началу Git может показаться слегка наркоманским 🙂

Поддержка Git в XCode 

Установить Git можно, начиная со страницы git-osx-installer


Если появилось желание существующий XCode проект посадить под Git, то могут быть полезными следующий ссылки:
1. Using Git with an existing XCode project
2. Setting up a git repository in XCode for a pre-existing project

Клиент с графическим интерфейсом можно найти на странице gitx.
Клиент очень удобный, но, похоже, уже 2 года не поддерживается.
Последний раз я скачивал его со страницы http://gitx.frim.nl.
OpenInGitX позволяет добавить кнопку в панель инструментов Finder-а, чтобы можно было открывать GitX, нажимая на нее, если вы находитесь в репозитории git.

Напомню, чтобы увидеть служебные файлы Git, нужно включить отображений скрытых файлов.

Есть также еще один клиент с графическим интерфейсом gitk, но я его не использовал.

Далее используем в XCode c помощью команды File -> Source control -> Commit… и близ-лежащих.

Некоторые полезные операции

Git ignore file for Xcode projects describe at :

Checkout the revision you want to work with.
$ git reset --hard abcd93

More info: http://stackoverflow.com/a/890006/13441

To follow history after file renamed:
git log --follow
More info: http://stackoverflow.com/a/1321962/13441

Revert changes:
git checkout path/to/file/to/revert
git checkout -- .
More info: http://stackoverflow.com/a/52713/13441

Сommit all deleted files to Git
git add -u
This tells git to automatically stage tracked files – including deleting the previously tracked files.
More info: http://stackoverflow.com/a/1402793/13441

Find children revisions (commits)
git log -g
More info: http://www.kernel.org/pub/software/scm/git/docs/git-log.html

Rename project in XCode:
1. Rename project itself: http://stackoverflow.com/q/5416677/13441
2. Rename folder with sources with git to preserve history with git mv
3. Fix XCode project: http://stackoverflow.com/q/8262613/13441

Apple, планшеты, телефоны

Из этого интервью Стива Джобса 2010 года очень много чего стало понятно о мобильных телефонах, планшетах, как все возникло, почему и куда движется интернет. А также многое из того, что сейчас происходит, например чрезвычайно агрессивное и очень необычное поведение Гугла относительно развития Андройда, да и не только его:
https_www.youtube.com/watch?v=2o4sd3oVQK8

Steve Jobs in 2010, at D8 Conference (Full Video, in English)

Сюрпризы при 3d-печати

Оригинал статьи: https_habr.com/ru/company/materialise/blog/99314/

Блог компании Materialise

С помощью трехмерной печати можно воспроизвести практически любую трехмерную модель, которая помещается на платформу принтера с достаточным уровнем детализации.
Казалось бы, все просто – создал модель в 3D редакторе, передал на принтер и получил ее в объемном виде. Но на практике все выглядит немного сложнее. Далее мы более детально опишем сюрпризы, возникающие в процессе 3D печати, а так же то, как их можно избежать.

Continue reading “Сюрпризы при 3d-печати”

О головоломках и собеседованиях

Выложил пост с головоломкой, как попалась книга о них в посте.

Книги вот такая:

Как сдвинуть гору Фудзи? Подходы ведущих мировых компаний к поиску талантов

Уильям Паундстоун

Вот такая аннотация:
“Методику интервьюирования при приеме на работу в корпорацию Microsoft, основанную на решении задач и головоломок, теперь перенимают многие компании, которые хотят выявить наиболее творческих кандидатов среди просто способных. В книге «Как сдвинуть гору Фудзи?» излагается эта методика и предлагается более тридцати трудных задач и головоломок. Книга показывает, как при помощи эффективного творческого и аналитического
мышления можно отыскать ответы на самые нестандартные вопросы.”

Google тоже использует головоломки, некоторые из них можно найти на страницах 15 Вопросов на собеседовании в Google, из-за которых вы можете почувствовать себя глупым и Previous Entry Google job

Мне интересна книга тем, что я не понимал, как можно по головоломке что-то определить, но потом практика показала, что это работает и очень хорошо.

Хотя есть и негативные стороны: интервьюер сам должен уметь решать головоломки и собеседование не получается проводить “на автомате”, поскольку кандидат может предложить другое решение и в него нужно вникнуть.

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

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

Книгу не читал, но вероятнее всего, почерпнул бы очень много полезного.
Скачать ее можно здесь http_www.klex.ru/books/superlearning/kak_sdvinut_goru_fudzi.zip

Ну и ответ к задаче о Колпаках из поста “Задача о Колпаках”:

Первый мегамозг предполагает, что остаток от деления на 100 суммы всех чисел на всех 100-а шапках равна 1, второй – 2, … 99 – 99, 100 – 0.

Один из мегамозгов сделает правильное предположение.

А по остатку и 99-и числам уже легко вычислить неизвестное, сотое, число, которое написано на своей шапке.