Виртуальная песочница (тм)

Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Friday, January 31, 2020

Java Microservices in Docker?..



- А ты точно маргинал?
- Да.
- А скажи что-нибудь на маргинальном!
- В чём смысл пихать Java Spring Boot микросервисы внутрь Docker контейнеров?
Read more...

Tuesday, January 31, 2017

Rewrite from scratch

A "quote-style conspect" of the (IMO) main points from the famous article by Joel Spolsky.
Read more...

Monday, May 23, 2016

When you have converted everything to microservices

После того, как вы перевели все на микросервисы:


Read more...

Wednesday, January 27, 2016

Hashtable and nulls

Если коротко, то Hashtable не поддерживает null'ы ни в каком виде:
Read more...

Friday, January 22, 2016

Wednesday, January 6, 2016

Что будет, если в switch по enum попадет null?

Энумы -- это не только ценный мех, хороши ещё и тем, что по ним можно делать switch-case. Что будет, если в такой switch-case попадет null-значение? Ответ: NullPointerException. Конструкция switch кидает NPE, как только в нее попадает null. Надежды на исполнение, например, default ветки в случае null, тщетны.
Код под катом.
Read more...

Wednesday, August 14, 2013

To some people, C is just a bunch of macros


A friend once said to me: "You know, to some people, C is just a bunch of macros that expand to assembly".
[Python’s Innards: Introduction]
Read more...

Wednesday, June 26, 2013

Sunday, March 3, 2013

How to create UI using Apps Script

Three ways users access UI developed in Apps Script:

  • Google Spreadsheet
  • Google Sites
  • Standalone (accessed by URL)

Read more...

Wednesday, January 23, 2013

How to generate a random number?

int getRandomNumber() {
 return 4; // chosen by fair dice roll; guaranteed to be random
}
Read more...

Tuesday, January 22, 2013

Difference in Cross-Platform Mobile Development – Native vs Hybrid vs HTML5

Notes from the talk "Difference in Cross-platform mobile development – native vs hybrid vs HTML5" by Dmitry Ivanov from C.T.Co

Native
        ++
                + Speed and reaction
                + Consumer focus
                + Native look and feel
                + Native API
                + Debug + Profile
        --
                - Only 1 Platform
                - New language
                - Costs
                - App review time (publishing & updates)
Read more...

Wednesday, October 10, 2012

Wednesday, September 26, 2012

If William Shakespeare wrote JavaScript

function theSeriesOfFIBONACCI(theSize) {

  //a CALCKULATION in two acts.
  //employ'ng the humourous logick of JAVA-SCRIPTE

  //Dramatis Personae
  var theResult; //an ARRAY to contain THE NUMBERS
  var theCounter; //a NUMBER, serv'nt to the FOR LOOP

  //ACT I: in which a ZERO is added for INITIATION

  //[ENTER: theResult]

  //Upon the noble list bestow a zero
  var theResult = [0];

  //ACT II: a LOOP in which the final TWO NUMBERS are QUEREED and SUMM'D

  //[ENTER: theCounter]

  //Commence at one and venture o'er the numbers
  for (theCounter = 1; theCounter < theSize; theCounter++) {
    //By divination set adjoining members
    theResult[theCounter] = (theResult[theCounter-1]||1) + theResult[Math.max(0, theCounter-2)];
  }

  //'Tis done, and here's the answer.
  return theResult;

  //[Exuent]
}

Read more...

Thursday, March 29, 2012

How many zeros are there at the end of 123456789! or how does a Java developer get a job in Munich

Step #1. The Job Listing


Step #2. The Job Ad

Все детали на
{Number of zeroes at the end of 123456789!}.com
en.wikipedia.org/wiki/Factorial

Step #3. The Problem
Find the number of zeroes at the end of 123456789!

Step #4. The Solution

 01 public class FactorialTrailingZeros {
02 public static void main(String[] args) {
03 int n = Integer.parseInt(args[0]);
04 double d = n;
05 int z = 0; // zeros
06 while (d>1) {
07 d /= 5.0;
08 z += (int)Math.floor(d);
09 }
10 System.out.println(n + "! has " + z + " trailing zeros");
11 }
12 }


Step #5. The Prize




Home

Welcome at Ravensburger Digital

We are a new company of Ravensburger Group, internationally well-known for its games, puzzles and books. Our aim is to develop Ravensburger products for all major digital platforms, as well as creating innovative new product lines that fit with our brand and core values. This includes online & social platforms, PC games and mobile games & apps.

The quality that makes our games, puzzles and books stand out, will also set the standard for our digital products: high-quality entertainment for the whole family.



Read more...

Friday, February 17, 2012

База данных как Крепость



База данных как Крепость

В базе данных хранится вся информация - как вводимая сотрудниками, так и полученная от клиента. Пользовательские интерфейсы, бизнес-логика и прикладная логика (и даже сотрудники) приходят и уходят, а данные остаются. Трудно выразить словами то, насколько важно в первые же дни работы над проектом построить надежную модель данных.

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

В то время как бизнес-логика и пользовательские интерфейсы эволюционируют довольно быстро, структурам данных и их отношениям это обычно не свойственно. Следовательно, очень важно с самого начала четко определить модель данных как на структурном, так и на аналитическом уровнях. Миграция данных из одной системы в другую "на месте" в лучшем случае сложна, всегда занимает много времени и часто чревата ошибками. Если с ошибками уровня приложения еще можно какое-то время мириться, ошибки в базе данных могут привести к катастрофическим последствиям. Даже если вы нашли и исправили ошибку проектирования на уровне данных, это не восстановит поврежденную информацию.

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

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

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

Дэн Чак (Dan Chak) - директор по разработке ПО в CourseAdvisor Inc., компании Washington Post. Является автором книги "Enterprise Rails" (O'Reilly)

Из книги "97 Things Every Software Architect Should Know: Collective Wisdom from the Experts"

Read more...

Wednesday, November 2, 2011


"Какую бы программу вы ни писали, всё равно получается компилятор".

Вот, например, некто metaclass делится своими довольно характерными переживаниями по поводу:

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

В связи с этим иногда бывает полезно повторять мантру "c'mon, guys, we're building an application, not a Christmas tree". Read more...

Tuesday, September 27, 2011

"Hall of API Shame: Boolean Trap" by ariya.ofilabs.com

The nice thing working for Trolltech was (among others) learning the principles behind the good API. The article Designing Qt-Style C++ API from Matthias 6 years ago is still a good reading till today. The content itself is now expanded into the wiki page API Design Principles.

The major premise behind a good API is rather straightforward:

the code is usually written once but read many times.

When writing the code, the developer has the time she needs to look at the API documentation and digest it. When someone else reads the code (for review or bug fix), she may not always have the API documentation handy. While this is just common sense, wait until you finish reading and see why this important fact is still overlooked these days.

Note: Qt is in C++, but surprisingly the same API design principles apply to the (wonderful) world of JavaScript, which is the focus in this blog post.

George Boole, inventor of the Boolean logic.

For this particular discussion, I’ll pick my favorite API design mistake: boolean trap. On this topic, the above API Design Principle wiki page says that

it’s almost invariably a mistake to add a bool parameter to an existing function

Let’s start with the textbook example: guess what this code means?

widget.repaint(false);

Without looking at the documentation, the usual suspect is don’t repaint the widget. Then, you look at the documentation and it refers the function argument as immediate, which is true if you want immediate painting or false for deferred painting. Thus, the correct behavior implied by the above code is actually repaint this widget later, which is miles away from your initial guess.

One possible solution to this problem is to use explicit function argument. In the C++ world, this can be solved using enum, e.g. widget.repaint(WidgetClass::Deferred). In the JavaScript world, the alternative is using an object literal such as,

widget.repaint({ immediate: false });

or the more verbose variant:

widget.repaint({ mode: "immediate" });

or just create a different function for that purpose:

widget.repaintLater();

There will be a concern of performance since an object is more expensive than just a simple boolean literal. Thus, profile your code carefully and set a sensible compromise if this above line is in your hot path. On the other hand, I also do believe that modern future JavaScript engines would be smart enough to optimize such usages that the speed penalty is negligible.

Another classic is the confusion during construction. Your user interface needs a bunch of sliders to allow the user to choose some values. Here is one line in the code for you to review:

var opacitySlider = new Slider(true);

Mysteriously, there are also lines similar to:

var volumeSlider = new Slider(false);

It turns out that true there means a horizontal slider and false means a vertical slider. Of course, the easiest way to clear this confusion is to actually name the object HorizontalSlider and VerticalSlider and get rid of the boolean argument. Heck, who knows someday you’ll need a diagonal slider!

You may scream, "Of course, I won’t be too idiot to make those rookie mistakes!". Well, in the following paragraphs I’ll give examples of actual boolean traps in the API of several well-known JavaScript libraries and frameworks out there (I try to be unbiased). Consider that there are millions of developers using the libraries in real-world web applications, imagine the exposure of the traps.

For each of this case, imagine you are doing a code review. Your amazing coworker wants to commit a patch and he consults you to check your opinion.

to be or not to be

This is the same as the textbook example, but coming from a real framework:

stackView.updateHeight(false);

Yes, that false again refers to immediate or not. To the untrained developer, the above line feels like don’t update the height. A real crazy one might even stretch it to update the width!

Here is another one. To facilitate easy iteration of child widgets, you can use next() function which would get you the next sibling. But then, the code looks like:

widget.next(true);

which actually does the extra magic (because of the true value) that the very first child widget will be returned if you hit the last one. In other words, true there stands for circular. An innocent value which does too much behind your back. Well, good luck trying to review that kind of code.

Another dangerous venture:

widget.destroy(false);

which potentially leads you to think don’t destroy this widget. You can’t be more wrong, the function actually still destroys your widget, but it leaves the DOM associated with the widget intact. Only if the argument is true then actually every related DOM pieces is also tore torn down.

optionally undecipherable

Now that we have the slider for the UI, we need to preset the value:

volumeSlider.setValue(90, false);

Another boolean horror! The documentation reveals that false there indicates that the slider should not animate the movement of its indicator from the old value to the new value. By default, it will show the animation but since we want to set the initial value, the animation will be distracting and needs to be off. How about writing it like this instead?

volumeSlider.setValue(90, { animation: false } );

There is this list view of all your customers. We want to find out who live in a certain city. Can you guess what the last optional argument refers to?

customerView.filter('address', 'sunnyvale', false);

Oh, apparently the API documentation refers it to caseSensitive! Just by looking at it, this is not obvious and it could mean an entirely different thing, anything from exactMatch to highlightMatchedLine. One possible workaround:

customerView.filter('address', 'sunnyvale', { caseSensitive: false });

the more, the merrier

While one boolean argument is already confusing, two boolean arguments can’t be more fun.

To handle layout, often there is a line of code that looks like:

cmp.setCentered(true, false);

Again, a trip to the API doc enlightens the reviewer that the function signature is actually setCentered(centered, autoUpdate). This is confusing as setCentered(centered) only is probably fine, it’s just like a property setter, but the interplay of the autoUpdate argument forces the brain to think harder.

Note that a pair of values like that, especially in the context of centering/geometry purpose, might provoke a different interpretation: center vertically and horizontally. This is arguably the most sensible one which comes to mind if one sees that code.

Here is another one:

menu.stop(true, false);

The boolean values there refer to clear the animation queue or not and go to the animation or not, respectively. They are not even remotely related. What is your best educated guess if you did not know this beforehand?

Of course, why stop at two if you can have more?

event.initKeyEvent("keypress", true, true, null, null,     false, false, false, false, 9, 0);

double negative

Now, coming back to property setter, this is one valid use of boolean argument, e.g. dialogBox.setVisible(true). However, care must be taken so that there is no such double negative. Especially for non-native speakers, double negative requires an extra careful measure to make sure that the right meaning is communicated.

If I wake you at midnight and ask you this question "if invisible is false, does that mean my component is shown or hidden?", there is a chance you answer it incorrectly.

Real-world examples of double negative follow:

volumeSlider.setThumbsDisabled(false); component.setDisabled(false); filter.setCaseInsensitive(false);

Would you be less confused if this is what you read instead?

volumeSlider.setThumbsEnabled(true); component.setEnabled(true); filter.setCaseSensitive(true);

The same principle applies to active vs inactive, modified vs unmodified, defined vs undefined, selected vs unselected, etc.

By now, hopefully you got the idea of various risky uses of boolean argument. Feel free to share your favorite freak-out moment as you encounter such a similar trap.

Most importantly, next time you design an API function, remember George Boole and don’t let him down!

Update: Some people on Reddit pointed out that they would not interpret widget.repaint(false) as do not repaint. First of all, it’s subjective. In some languages it can be understood as repaint not, which is effectively a negation. Also, the context might pollute, e.g. if there is fooWidget.show(false) (which means do not show) right before, then it may influence a similar conclusion for the repaint issue. I was also not clear that any crazy possible interpretations are just examples, substitute them with your own imaginations. The fact that everyone can propose a different interpretation is the premise: ambiguity begets insanity.

[source]

Read more...

User Interface Engineering: "Do users change their settings?"

Jared Spool

September 14th, 2011

Back in the early days of PC computing, we were interested in how people used all those options, controls, and settings that software designers put into their applications. How much do users customize their applications?

We embarked on a little experiment. We asked a ton of people to send us their settings file for Microsoft Word. At the time, MS Word stored all the settings in a file named something like config.ini, so we asked people to locate that file on their hard disk and email it to us. Several hundred folks did just that.

We then wrote a program to analyze the files, counting up how many people had changed the 150+ settings in the applications and which settings they had changed.

What we found was really interesting. Less than 5% of the users we surveyed had changed any settings at all. More than 95% had kept the settings in the exact configuration that the program installed in.

This was particularly curious because some of the program’s defaults were notable. For example, the program had a feature that would automatically save your work as edited a document, to prevent losing anything in case of a system or program failure. In the default settings for the version we analyzed, this feature was disabled. Users had to explicitly turn it on to make it work.

Of course, this mean that 95% of the users were running with autosave turned off. When we interviewed a sample of them, they all told us the same thing: They assumed Microsoft had delivered it turned off for a reason, therefore who were they to set it otherwise. “Microsoft must know what they are doing,” several of the participants told us.

We thought about that and wondered what the rationale was for keeping such an important feature turned off. We thought that maybe they were concerned about people running off floppies or those who had slow or small disks. Autosave does have performance implications, so maybe they were optimizing the behavior for the worst case, assuming that users who had the luxury to use the feature would turn it on.

We had friends in the Microsoft Office group, so we asked them about the choice of delivering the feature disabled. We explained our hypothesis about optimizing for performance. They asked around and told us our hypothesis was incorrect.

It turns out the reason the feature was disabled in that release was not because they had thought about the user’s needs. Instead, it was because a programmer had made a decision to initialize the config.ini file with all zeroes. Making a file filled with zeroes is a quick little program, so that’s what he wrote, assuming that, at some point later, someone would tell him what the “real defaults” should be. Nobody ever got around to telling him.

Since zero in binary means off, the autosave setting, along with a lot of other settings, were automatically disabled. The users’ assumption that Microsoft had given this careful consideration turned out not to be the case.

We also asked our participants for background information, like age and occupation, to see if that made a difference. It didn’t, except one category of people who almost always changed their settings: programmers and designers. They often had changed more than 40% (and some had changed as much as 80%) of the options in the program.

It seems programmers and designers like to customize their environment. Who would’ve guessed? Could that be why they chose their profession?

(Big takeaway: If you’re a programmer or designer, then you’re not like most people. Just because you change your settings in apps you use doesn’t mean that your users will, unless they are also programmers and designers.)

We’ve repeated this experiment in various forms over the years. We’ve found it to be consistently true: users rarely change their settings.

If your application has settings, have you looked to see what your users do? How many have changed them? Are the defaults the optimal choice? Does your settings screen explain the implications of each setting and give your users a good reason for mucking with the defaults?

Read more...

Saturday, March 19, 2011

4 easy steps to start Perl CGI programming on Windows in 10 seconds or less

1. Download Active Perl and install it.
2. Download Apache for Windows and install it.


03/19/2011 01:11 PM 25,704,148 ActivePerl-5.12.3.1204-MSWin32-x86-294330.msi
03/19/2011 01:20 PM 5,400,576 httpd-2.2.17-win32-x86-no_ssl.msi
2 File(s) 31,104,724 bytes

(now start counting those 10 seconds)

3. Go to
C:\Program Files\Apache Software Foundation\Apache2.2\cgi-bin
and create test.cgi file with the following contents
#!C:\perl\bin\perl.exe -wT
use strict;
use CGI;
my $query = new CGI;
print $query->header( "text/html" );
print <<END_HERE;
<html>
<head>
<title>My First CGI Script</title>
</head>
<body bgcolor="#FFFFCC">
<h1>This is a pretty lame Web page</h1>
<p>Who is this Ovid guy, anyway?</p>
</body>
</html>
END_HERE

(make sure to hit "enter" a couple of times after END_HERE, otherwise it won't work)

4. Open
http://localhost/cgi-bin/test.cgi
in the browser. Enjoy.

Thanks to PerlMonks.org for the article.

P.S. PerlTutorial.org gives a bit more consequent example:
#!C:\perl\bin\perl.exe -wT
# It's always a good idea to use the strict pragma while developing
# Perl code, it makes Perl warn about dangerous code
use strict;

# We're also going to include the CGI module, so that we can take
# advantage of other programmer's efforts (One of Larry Wall's basic
# tennants is that programmers are fundamentally lazy -- he's probably
# right, but I can't be bothered to prove it right now)
use CGI;

# instantiate a new CGI object
my $cgi = new CGI;

# perform a single print statement, with liberal use of the perl
# string concatenator "." and some CGI methods
print
$cgi->header .
$cgi->start_html('Hello World!') .
$cgi->h1('Hello World!') .
$cgi->end_html;

# Tell the web server everything is fine
exit (0);
Read more...

Tuesday, February 15, 2011

C# Learning Resources

C# Station Tutorial
The tutorial that promises to teach C# programming in the good old-fashioned way:

"To get started, you will need a compiler and an editor. There are several options for obtaining a compiler to write C# programs. A free option is to download the .NET Frameworks SDK and use Notepad. Most of the examples in these tutorials run as console programs."


MSDN C# Reference

MSDN C# Programming Guide Read more...