tag:blogger.com,1999:blog-86574870338515007572024-03-05T15:35:45.524+02:00Век живи - век учисьUnknownnoreply@blogger.comBlogger89125tag:blogger.com,1999:blog-8657487033851500757.post-4046862724088891232017-02-19T00:28:00.000+02:002017-02-19T14:34:15.535+02:00Магазин для своего сервера Minecraft.<div dir="ltr" style="text-align: left;" trbidi="on">
<h2 style="text-align: left;">
<span style="text-align: justify;">Установка магазина на Apache</span></h2>
<h3 style="text-align: left;">
</h3>
<h3 style="text-align: left;">
Установка mod_wsgi</h3>
<div style="text-align: justify;">
В первую очередь необходимо установить модуль wsgi. Либо воспользовавшись исходным кодом (что я и сделал, когда впервые потребовалось прикрутить python к apache) следуя по <a href="http://code.google.com/p/modwsgi/wiki/QuickInstallationGuide" target="_blank">инструкции</a>. Либо взять готовый модуль из репозитория:</div>
<blockquote class="tr_bq">
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;">~$ sudo apt-get install libapache2-mod-wsgi</span></blockquote>
<h3 style="text-align: left;">
</h3>
<h3 style="text-align: left;">
Настройка виртуального хоста</h3>
Для этого перейдем в директорию:<br />
<blockquote class="tr_bq">
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;">~$ cd /etc/apache2/sites-enabled/</span></blockquote>
и отредактируем наш конфигурационный файл:<br />
<blockquote class="tr_bq">
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;">~$ sudo vi kalinchyk-ssl.conf</span></blockquote>
<div>
должно получиться что-то в этом роде:<br />
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"><br /></span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"><VirtualHost *></span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> ServerName www.kalinchyk.com</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> ServerAdmin viacheslav@kalinchyk.com</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> DocumentRoot /var/www/minecraft</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"><br /></span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> WSGIDaemonProcess wsgi user=www-data group=www-data processes=1 threads=5</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> WSGIScriptAlias /api /var/www/wsgi/app.wsgi</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> <Directory /var/www/wsgi></span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> WSGIProcessGroup wsgi</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> WSGIApplicationGroup %{GLOBAL}</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> Require all granted</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> </Directory></span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"></VirtualHost></span></div>
</div>
<div>
<br /></div>
<div style="text-align: justify;">
Здесь мы сообщили Apache, что необходимо при обращении клиента к директории /api выполнять python wsgi-скрипт (который физически размещен в директории /var/www/wsgi/app.wsgi) от имени пользователя www-data.</div>
<div style="text-align: justify;">
<i>Обязательно проверьте, что вашему пользователю доступны импортируемые библиотеки и все файлы он может читать, а при необходимости и вносить изменения.</i></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Также в настройках виртуального хоста указана основная директория с которой будет клиент работать (/var/www/minecraft).</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
В этом кусочке конфигурации я убрал строки для настройки ssl-сертификата, логирования и т.д., чтобы не перегружать пример.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
После изменений конфигурационных файлов Apache требуется перезапустить:</div>
<blockquote class="tr_bq" style="text-align: justify;">
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;">~$ sudo service apache2 restart</span></blockquote>
<div style="text-align: justify;">
<br /></div>
<h3 style="text-align: justify;">
BackEnd</h3>
<div style="text-align: justify;">
Сначала устанавливаем backend (API магазина). Для этого забираем исходные коды с <a href="https://gitlab.com/kalinchyk/shop-mc/repository/archive.zip?ref=master" target="_blank">git-репозитория</a>. Распаковываем архив и содержимое wsgi копируем в нашу wsgi директорию (в моем случае это /var/www/wsgi/). </div>
<div style="text-align: justify;">
Т.к. мы для повышения безопасности указали, что python скрипты должны выполняться от имени www-data, то необходимо проверить чтобы директория и содержимое принадлежат этому пользователю.</div>
<blockquote class="tr_bq" style="text-align: justify;">
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;">~$ sudo chmod -R 644 /var/www/wsgi<br />~$ sudo chown -R www-data:www-data /var/www/wsgi</span></blockquote>
<div style="text-align: justify;">
Первым делом необходимо создать базу данных, выполнив db_update.py от имени нашего пользователя.</div>
<blockquote class="tr_bq" style="text-align: justify;">
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;">~$ python db_update.py</span></blockquote>
<div style="text-align: justify;">
А также при последующих обновлениях необходимо не забывать про эту операцию. Этот скрипт выполняет важные изменения в структуре базы данных. Хоть скрипт самостоятельно сделает резервную копию базы, но необходимо об этом также не забывать и периодически самостоятельно архивировать критически важные данные.</div>
<div style="text-align: justify;">
<br /></div>
<h3 style="text-align: justify;">
Устанавливаем зависимости</h3>
<div style="text-align: justify;">
Для корректной работы python приложения необходимо установить несколько зависимостей, а именно bottle, bottle_sqlite, bottle_errorrest. Их можно установить из пакетного менеджера pip:<br />
<blockquote class="tr_bq">
<span style="font-family: "courier new", courier, monospace; font-size: x-small;">~$ sudo apt-get install python-pip</span></blockquote>
<blockquote class="tr_bq">
<span style="font-family: "courier new", courier, monospace; font-size: x-small;">~$ sudo -u www-data -H pip install pip</span></blockquote>
<blockquote class="tr_bq">
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;">~$ sudo -u www-data -H pip install bottle</span></blockquote>
<blockquote class="tr_bq">
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;">~$ sudo -u www-data -H pip install bottle_sqlite</span></blockquote>
<blockquote class="tr_bq">
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;">~$ sudo -u www-data -H pip install bottle_errorsrest</span></blockquote>
<div>
И обязательно устанавливаем их для нашего пользователя (параметр <b>-u ww-data</b>), под которым будет выполняться скрипт (параметр <b>-H</b>).<br />
<br /></div>
</div>
<h3>
Проверяем работу приложения</h3>
<div style="text-align: justify;">
В браузере указав адрес своего сервера и директорию, которая обслуживает wsgi, а также суффикс /whoami мы должны получить положительный отклик от сервера.</div>
<div style="text-align: justify;">
<blockquote class="tr_bq">
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;">~$ curl https://test.kalinchyk.com/api/whoami<br />{"object": "CUSTOMER"}</span></blockquote>
</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<br /></div>
<h3 style="text-align: justify;">
Настраиваем приложение</h3>
<div style="text-align: justify;">
Для настройки приложения необходимо создать файл с именем minecraft.json:</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;">{</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> "minecraft": {</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> "acquiring": {</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> "form_method": "post",</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> "form_url": "https://sci.interkassa.com/",</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> "id": "<b>[идентификатор_кассы_в_interkassa]</b>",</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> "sign": "<b>[секретный_ключ_для_формирования_подписи]</b>",</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> "sign_test": "<b>[секретный_ключ_для_проверки_подписи_(тест)]</b>",</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> "type": "interkassa"</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> },</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> "admin_username": "<b>[логин_администратора]</b>",</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> "admin_password": "<b>[пароль_администратора]</b>",</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> "cookie_name": "minecraft_cookie",</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> "cookie_sign": "minecraft_secret",</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> "server_host": "<b>[адрес_к_серверу_minecraft]</b>",</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> "server_query_port": 25565,</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> "server_rcon_password": "<b>[пароль_к_rcon]</b>",</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> "server_rcon_port": 25575,</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> "server_url": "<b>https://test.kalinchyk.com/</b>",</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> "server_api": "<b>https://test.kalinchyk.com/</b>"</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"> }</span></div>
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;">}</span></div>
</div>
<div style="text-align: justify;">
<br /></div>
Жирным выделены параметры, которые необходимо заполнить в первую очередь.<br />
<br />
<br />
<h3 style="text-align: left;">
FrontEnd</h3>
<div>
<div style="text-align: justify;">
Теперь можно приступить к установке веб-интерфейса магазина. Из ранее извлеченного архива, который был получен на <a href="https://gitlab.com/kalinchyk/shop-mc/repository/archive.zip?ref=master" target="_blank">сайте</a>, содержимое minecraft копируем в нашу minecraft директорию (в моем случае это /var/www/minecraft/).</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<h3 style="text-align: left;">
Настраиваем frontend</h3>
В директории /var/www/minecraft/ создаем файл .htaccess<br />
<br />
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;">Options -Indexes +FollowSymLinks<br />RewriteEngine on<br />RewriteCond %{REQUEST_FILENAME} !-f<br />RewriteCond %{REQUEST_FILENAME} !-d<br />RewriteRule .* /var/www/minecraft/index.html [L]<br />DirectoryIndex index.html</span><br />
<div>
<span style="font-family: "courier new" , "courier" , monospace; font-size: x-small;"><br /></span>
<br />
<div style="text-align: justify;">
Здесь мы включаем модуль rewrite и перенаправляем все запросы на несуществующие файлы/директории будут перенаправлены на index.html</div>
<br />
<br /></div>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8657487033851500757.post-70342689075072820282015-10-05T00:00:00.000+03:002015-10-05T21:08:56.346+03:00WebLogic Server. Encrypt & Decrypt password.<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
На днях возникла задача хранения некоторой части данных в базе данных. Из темы ясно, что данные должны быть зашифрованы. Чтобы не изобретать велосипед, первым делом отправился в www.google.com с вопросом как же шифруются пароли weblogic'а.<br />
<br />
В результате получился маленький класс для шифровки и расшифровки паролей по аналогии как это делает weblogic server.</div>
<div style="text-align: justify;">
<br /></div>
<div style="font-size: x-small;">
<pre class="brush: java">package com.kalinchyk.util;
import weblogic.security.internal.SerializedSystemIni;
import weblogic.security.internal.encryption.*;
public final class WebLogicSecure {
private static EncryptionService es = null;
private static ClearOrEncryptedService ces = null;
public static String decrypt(String pwd) throws Exception {
es = SerializedSystemIni.getExistingEncryptionService();
if (es == null)
throw new Exception("Unable to initialize decryption service");
ces = new ClearOrEncryptedService(es);
return ces.decrypt(pwd);
}
public static String encrypt(String pwd) throws Exception {
es = SerializedSystemIni.getExistingEncryptionService();
if (es == null)
throw new Exception("Unable to initialize encryption service");
ces = new ClearOrEncryptedService(es);
return ces.encrypt(pwd);
}
}
</pre>
</div>
<br />
<div style="text-align: justify;">
Но необходимо учесть, что данные зашифрованные на одном сервере не могут быть расшифрованы на другом, т.к. мы используем ключ самого wls, который формируется (генерируется) в момент установки и будет уникальным для всех серверов.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Для тестирования на локальной машине можно использовать файл SerializedSystemIni.dat из IntegratedWebLogicServer, который необходимо сохранить в директорию с вашим проектом.</div>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8657487033851500757.post-87677408938282537322015-04-27T00:00:00.000+03:002015-04-27T22:44:46.703+03:00JavaScript Frameworks Day 2015<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
На прошедших выходных (26 апреля 2015 года) прошел очередной ивент от frameworksdays по тематике JavaScript. Как обычно было очень много интересных докладов, конкурсов, подарков!</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Спасибо организаторам за яркое воскресенье. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Есть желание посетить следующие ивенты? <a href="http://frameworksdays.com/event/js-frameworks-day-2015?ref=cd4af8ed4018f906d22c7249097e7443" target="_blank">Регистрируйтесь</a> и приходите.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<br /></div>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8657487033851500757.post-52265889993393916852015-04-22T00:00:00.000+03:002015-04-22T12:37:33.770+03:00PL/SQL. Транслитерация украинского языка<div dir="ltr" style="text-align: left;" trbidi="on">
Моя функция для транслитерации украинского языка в pl/sql.<br />
Правила описаны в законе Украины: <br />
<a href="http://zakon4.rada.gov.ua/laws/show/55-2010-%D0%BF">http://zakon4.rada.gov.ua/laws/show/55-2010-п</a><br />
<br />
<a name='more'></a>
<br />
<pre><span style="font-size: x-small;">create or replace function fn_embossing_name(p_name varchar2) return varchar2
/* http://zakon4.rada.gov.ua/laws/show/55-2010-п
ТАБЛИЦЯ
транслітерації українського алфавіту латиницею
------------------------------------------------------------------
| Український | Латиниця | Позиція у | Приклади написання |
| алфавіт | | слові |--------------------------|
| | | |українською | латиницею |
| | | | мовою | |
|-------------+----------+------------+------------+-------------|
| Аa | Aа | |Алушта |Alushta |
| | | |Андрій |Andrii |
|-------------+----------+------------+------------+-------------|
| Бб | Bb | |Борщагівка |Borshchahivka|
| | | |Борисенко |Borysenko |
|-------------+----------+------------+------------+-------------|
| Вв | Vv | |Вінниця |Vinnytsia |
| | | |Володимир |Volodymyr |
|-------------+----------+------------+------------+-------------|
| Гг | Hh | |Гадяч |Hadiach |
| | | |Богдан |Bohdan |
| | | |Згурський |Zghurskyi |
|-------------+----------+------------+------------+-------------|
| Ґґ | Gg | |Ґалаґан |Galagan |
| | | |Ґорґани |Gorgany |
|-------------+----------+------------+------------+-------------|
| Дд | Dd | |Донецьк |Donetsk |
| | | |Дмитро |Dmytro |
|-------------+----------+------------+------------+-------------|
| Ее | Ee | |Рівне |Rivne |
| | | |Олег |Oleh |
| | | |Есмань |Esman |
|-------------+----------+------------+------------+-------------|
| Єє | Ye | на початку |Єнакієве |Yenakiieve |
| | | слова |Гаєвич |Haievych |
| | ie | в інших |Короп'є |Koropie |
| | | позиціях | | |
|-------------+----------+------------+------------+-------------|
| Жж | Zh zh | |Житомир |Zhytomyr |
| | | |Жанна |Zhanna |
| | | |Жежелів |Zhezheliv |
|-------------+----------+------------+------------+-------------|
| Зз | Zz | |Закарпаття |Zakarpattia |
| | | |Казимирчук |Kazymyrchuk |
|-------------+----------+------------+------------+-------------|
| Ии | Yy | |Медвин |Medvyn |
| | | |Михайленко |Mykhailenko |
|-------------+----------+------------+------------+-------------|
| Іі | Ii | |Іванків |Ivankiv |
| | | |Іващенко |Ivashchenko |
|-------------+----------+------------+------------+-------------|
| Її | Yi | на початку |Їжакевич |Yizhakevych |
| | | слова |Кадиївка |Kadyivka |
| | i | в інших |Мар'їне |Marine |
| | | позиціях | | |
|-------------+----------+------------+------------+-------------|
| Йй | Y | на початку |Йосипівка |Yosypivka |
| | | слова |Стрий |Stryi |
| | i | в інших |Олексій |Oleksii |
| | | позиціях | | |
|-------------+----------+------------+------------+-------------|
| Кк | Kk | |Київ |Kyiv |
| | | |Коваленко |Kovalenko |
|-------------+----------+------------+------------+-------------|
| Лл | Ll | |Лебедин |Lebedyn |
| | | |Леонід |Leonid |
|-------------+----------+------------+------------+-------------|
| Мм | Mm | |Миколаїв |Mykolaiv |
| | | |Маринич |Marynych |
|-------------+----------+------------+------------+-------------|
| Нн | Nn | |Ніжин |Nizhyn |
| | | |Наталія |Nataliia |
|-------------+----------+------------+------------+-------------|
| Оо | Oo | |Одеса |Odesa |
| | | |Онищенко |Onyshchenko |
|-------------+----------+------------+------------+-------------|
| Пп | Pp | |Полтава |Poltava |
| | | |Петро |Petro |
|-------------+----------+------------+------------+-------------|
| Рр | Rr | |Решетилівка |Reshetylivka |
| | | |Рибчинський |Rybchynskyi |
|-------------+----------+------------+------------+-------------|
| Сс | Ss | |Суми |Sumy |
| | | |Соломія |Solomiia |
|-------------+----------+------------+------------+-------------|
| Тт | Tt | |Тернопіль |Ternopil |
| | | |Троць |Trots |
|-------------+----------+------------+------------+-------------|
| Уу | Uu | |Ужгород |Uzhhorod |
| | | |Уляна |Uliana |
|-------------+----------+------------+------------+-------------|
| Фф | Ff | |Фастів |Fastiv |
| | | |Філіпчук |Filipchuk |
|-------------+----------+------------+------------+-------------|
| Хх | Kh kh | |Харків |Kharkiv |
| | | |Христина |Khrystyna |
|-------------+----------+------------+------------+-------------|
| Цц | Ts ts | |Біла Церква |Bila Tserkva |
| | | |Стеценко |Stetsenko |
|-------------+----------+------------+------------+-------------|
| Чч | Ch ch | |Чернівці |Chernivtsi |
| | | |Шевченко |Shevchenko |
|-------------+----------+------------+------------+-------------|
| Шш | Sh sh | |Шостка |Shostka |
| | | |Кишеньки |Kyshenky |
|-------------+----------+------------+------------+-------------|
| Щщ |Shch shch | |Щербухи |Shcherbukhy |
| | | |Гоща |Hoshcha |
| | | |Гаращенко |Harashchenko |
|-------------+----------+------------+------------+-------------|
| Юю | Yu | на початку |Юрій |Yurii |
| | | слова |Корюківка |Koriukivka |
| | iu | в інших | | |
| | | позиціях | | |
|-------------+----------+------------+------------+-------------|
| Яя | Ya | на початку |Яготин |Yahotyn |
| | | слова |Ярошенко |Yaroshenko |
| | ia | в інших |Костянтин |Kostiantyn |
| | | позиціях |Знам'янка |Znamianka |
| | | |Феодосія |Feodosiia |
------------------------------------------------------------------
_______________
Примітка: 1. Буквосполучення "зг" відтворюється латиницею як "zgh"
(наприклад, Згорани - Zghorany, Розгон - Rozghon) на
відміну від "zh" - відповідника української літери
"ж".
2. М'який знак і апостроф латиницею не відтворюються.
3. Транслітерація прізвищ та імен осіб і географічних
назв здійснюється шляхом відтворення кожної літери
латиницею.
Проверка преобразований по списку из "постановы":
with name_test as ( select 'Алушта' name_1, 'Alushta' name_2 from dual union all
select 'Андрій', 'Andrii' from dual union all
select 'Борщагівка', 'Borshchahivka' from dual union all
select 'Борисенко', 'Borysenko' from dual union all
select 'Вінниця', 'Vinnytsia' from dual union all
select 'Володимир', 'Volodymyr' from dual union all
select 'Гадяч', 'Hadiach' from dual union all
select 'Богдан', 'Bohdan' from dual union all
select 'Згурський', 'Zghurskyi' from dual union all
select 'Ґалаґан', 'Galagan' from dual union all
select 'Ґорґани', 'Gorgany' from dual union all
select 'Донецьк', 'Donetsk' from dual union all
select 'Дмитро', 'Dmytro' from dual union all
select 'Рівне', 'Rivne' from dual union all
select 'Олег', 'Oleh' from dual union all
select 'Есмань', 'Esman' from dual union all
select 'Єнакієве', 'Yenakiieve' from dual union all
select 'Гаєвич', 'Haievych' from dual union all
select 'Короп''є', 'Koropie' from dual union all
select 'Житомир', 'Zhytomyr' from dual union all
select 'Жанна', 'Zhanna' from dual union all
select 'Жежелів', 'Zhezheliv' from dual union all
select 'Закарпаття', 'Zakarpattia' from dual union all
select 'Казимирчук', 'Kazymyrchuk' from dual union all
select 'Медвин', 'Medvyn' from dual union all
select 'Михайленко', 'Mykhailenko' from dual union all
select 'Іванків', 'Ivankiv' from dual union all
select 'Іващенко', 'Ivashchenko' from dual union all
select 'Їжакевич', 'Yizhakevych' from dual union all
select 'Кадиївка', 'Kadyivka' from dual union all
select 'Мар''їне', 'Marine' from dual union all
select 'Йосипівка', 'Yosypivka' from dual union all
select 'Стрий', 'Stryi' from dual union all
select 'Олексій', 'Oleksii' from dual union all
select 'Київ', 'Kyiv' from dual union all
select 'Коваленко', 'Kovalenko' from dual union all
select 'Лебедин', 'Lebedyn' from dual union all
select 'Леонід', 'Leonid' from dual union all
select 'Миколаїв', 'Mykolaiv' from dual union all
select 'Маринич', 'Marynych' from dual union all
select 'Ніжин', 'Nizhyn' from dual union all
select 'Наталія', 'Nataliia' from dual union all
select 'Одеса', 'Odesa' from dual union all
select 'Онищенко', 'Onyshchenko' from dual union all
select 'Полтава', 'Poltava' from dual union all
select 'Петро', 'Petro' from dual union all
select 'Решетилівка', 'Reshetylivka' from dual union all
select 'Рибчинський', 'Rybchynskyi' from dual union all
select 'Суми', 'Sumy' from dual union all
select 'Соломія', 'Solomiia' from dual union all
select 'Тернопіль', 'Ternopil' from dual union all
select 'Троць', 'Trots' from dual union all
select 'Ужгород', 'Uzhhorod' from dual union all
select 'Уляна', 'Uliana' from dual union all
select 'Фастів', 'Fastiv' from dual union all
select 'Філіпчук', 'Filipchuk' from dual union all
select 'Харків', 'Kharkiv' from dual union all
select 'Христина', 'Khrystyna' from dual union all
select 'Біла Церква', 'Bila Tserkva' from dual union all
select 'Стеценко', 'Stetsenko' from dual union all
select 'Чернівці', 'Chernivtsi' from dual union all
select 'Шевченко', 'Shevchenko' from dual union all
select 'Шостка', 'Shostka' from dual union all
select 'Кишеньки', 'Kyshenky' from dual union all
select 'Щербухи', 'Shcherbukhy' from dual union all
select 'Гоща', 'Hoshcha' from dual union all
select 'Гаращенко', 'Harashchenko' from dual union all
select 'Юрій', 'Yurii' from dual union all
select 'Корюківка', 'Koriukivka' from dual union all
select 'Яготин', 'Yahotyn' from dual union all
select 'Ярошенко', 'Yaroshenko' from dual union all
select 'Костянтин', 'Kostiantyn' from dual union all
select 'Знам''янка', 'Znamianka' from dual union all
select 'Феодосія', 'Feodosiia' from dual union all
select 'Згорани', 'Zghorany' from dual union all
select 'Розгон', 'Rozghon' from dual )
select case fn_embossing_name(name_1)
when name_2
then 'TRUE'
else 'FALSE'
end status
, name_1
, name_2
from name_test
*/
is
m_name varchar2(255);
m_ukr varchar2(100) := q'[АаБбВвГ㥴ДдЕеЗзИиІіЙйКкЛлМмНнОоПпРрСсТтУуФфїCc -]';
m_lat varchar2(100) := q'[AaBbVvHhGgDdEeZzYyIiYiKkLlMmNnOoPpRrSsTtUuFfiCc -]';
m_itm number;
m_sym varchar2(1);
m_res varchar2(255);
m_pos number;
begin
m_name := lower(p_name);
m_name := replace(m_name, '`', '');
m_name := replace(m_name, 'ь', '');
m_name := replace(m_name, '''', '');
m_name := replace(m_name, 'зг', 'зґг');
m_name := replace(m_name, 'я', 'йа');
m_name := replace(m_name, 'є', 'йе');
m_name := replace(m_name, 'ю', 'йу');
m_name := replace(m_name, 'ж', 'зг');
m_name := replace(m_name, 'х', 'кг');
m_name := replace(m_name, 'ц', 'тс');
m_name := replace(m_name, 'щ', 'шч');
m_name := replace(m_name, 'ч', 'cг');
m_name := replace(m_name, 'ш', 'сг');
m_name := initcap(m_name);
m_name := replace(m_name, 'Ї', 'Иі');
for m_itm in 1..length(m_name) loop
m_sym := substr(m_name, m_itm, 1);
m_pos := instr(m_ukr, m_sym);
if m_pos > 0 then
m_res := m_res || substr(m_lat, m_pos, 1);
else
m_res := m_res || '?';
end if;
dbms_output.put_line(instr(m_ukr, m_sym));
end loop;
return m_res;
end;
</span></pre>
</div>
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8657487033851500757.post-2033546589601301222015-03-20T00:00:00.000+02:002015-03-22T10:31:45.561+02:00Отчеты BI Publisher и шрифт Times New Roman (кириллица)<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Столкнулся с необходимостью формировать отчеты в старой версии Oracle BI Publisher Enterprise (10.1.3.4.1) и сразу возникла сложность со шрифтам. Причем проблема возникала только при формировании отчета в формате pdf. Вместо правильных шрифтов статически указывался Alban WT J и вся кириллица смотрелась ужасно, стили не соответствовали шаблону - небыло выделения жирным и остальные странные артефакты.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>Решение:</b></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Первым делом скопировать необходимые шрифты из windows (c:\windows\fonts\), например, Times New Roman, Arial и т.д. в директорию jre/lib/fonts (тут необходимо четко понимать, какой из jre использует ваш BIP, так например на нашей тестовой среде используется не родной).</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Следующим шагом прописать группу шрифтов в конфигурационный файл (xdo.cfg). В зависимости от задачи - это может быть глобальный файл (расположен %BIP%/xmlp/XMLP/Admin/Configuration) или локальный для определенного отчета. Мой конфиг выглядит теперь так:</div>
<div style="text-align: justify;">
<span style="font-size: x-small;">
<pre class="brush: xml"><config version="1.0.0" xmlns="http://xmlns.oracle.com/oxp/config/">
<properties>
<property name="pdf-compression">true</property>
</properties>
<fonts>
<font family="Arial" style="normal" weight="normal">
<truetype path="/arial.ttf" />
</font>
<font family="Arial" style="italic" weight="normal">
<truetype path="/ariali.ttf" />
</font>
<font family="Arial" style="normal" weight="bold">
<truetype path="/arialbd.ttf" />
</font>
<font family="Arial" style="italic" weight="bold">
<truetype path="/arialbi.ttf" />
</font>
<font family="Times New Roman" style="normal" weight="normal">
<truetype path="/times.ttf" />
</font>
<font family="Times New Roman" style="italic" weight="normal">
<truetype path="/timesi.ttf" />
</font>
<font family="Times New Roman" style="normal" weight="bold">
<truetype path="/timesbd.ttf" />
</font>
<font family="Times New Roman" style="italic" weight="bold">
<truetype path="/timesbi.ttf" />
</font>
<font family="Default" style="normal" weight="normal">
<truetype path="/times.ttf" />
</font>
<!--Font substitute setting (for PDFForm filling etc...) -->
<font-substitute name="MSGothic">
<truetype path="/msgothic.ttc" ttcno="0" />
</font-substitute>
</fonts>
</config></pre></span>
</div>
</div>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8657487033851500757.post-12623116467393252702015-03-11T00:00:00.000+02:002015-03-11T00:00:05.819+02:00CodenJoy. 2048<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<div style="text-align: justify;">
В предыдущем посте я написал о посещении frameworksdays, на котором нас познакомили с проектом <a href="http://www.codenjoy.com/" target="_blank">codenjoy</a>. Очередные головоломки для разработчиков. В перечне задачек была предложена игра 2048 - суть задания написать алгоритм (бота), позволяющий набрать максимальное количество баллов из всех зарегистрированных участников.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Взаимодействие с сервером осуществляется посредством websoсket'ов. Значит нет привязки к языку программирования - что не может не радовать. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Установил себе модуль https://pypi.python.org/pypi/websocket-client для работы с вебсокетами через python и начеркал примитивный алгоритм, который может прийти в голову - постоянно жмем кнопку вниз, когда строка (двумерный массив разложенный в строку) не изменилась от предыдущего действия, то нажимаем влево. В результате имеем следующий код:</div>
<span style="font-size: x-small;"><br />
</span><br /><span style="font-size: x-small;">
<pre class="brush: python">import websocket
def on_message(ws, message):
ws.send("LEFT" if message == ws.last_message else "DOWN")
ws.last_message = message
if __name__ == "__main__":
ws = websocket.WebSocketApp( "ws://tetrisj.jvmhost.net:12270/codenjoy-contest/ws?user=[user]"
, on_message = on_message)
ws.last_message = ""
ws.run_forever()
</pre></span>
<br />
<div style="text-align: justify;">
</div>
<div style="text-align: justify;">
<br />
Такой бот смог набрать 7938 и занять 3е место в рейтинге, к заметке - второе место имеет такое же количество баллов.</div>
<br />
Для сброса текущего счета (перерегистрация) клиента:<br />
<span style="font-size: x-small;">curl http://codenjoy.com/codenjoy-contest/register -d "name=[user]&password=[pass]&gameName=a2048"</span><br />
<div>
<br />
<div style="text-align: justify;">
Если будет возможность написать обновленного бота, который выйдет на первую строчку рейтинга, то обязательно выложу исходный код. И напоследок - советую всем попробовать свои силы в написании алгоритмов для подобных задачек.</div>
<span style="text-align: justify;"><br /></span></div>
</div>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8657487033851500757.post-13572299521246510332015-03-10T00:00:00.000+02:002015-04-27T22:45:40.607+03:00Java Frameworks Day 2015<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
7 марта посетил великолепный ивент <a href="http://www.frameworksdays.com/" target="_blank">frameworksdays</a> с тематиками для java разработчиков, хоть java не моя стихия, но было очень захватывающе. Спасибо большое организаторам за проведенное мероприятие и докладчикам за интересные презентации.</div>
<br /></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8657487033851500757.post-81552197536410965792014-01-14T08:22:00.000+02:002014-01-14T08:22:29.799+02:00Codility. Train. Brackets ★<div dir="ltr" style="text-align: left;" trbidi="on">
<div id="brinza-task-description" style="font-family: Verdana, Arial; font-size: 12px;">
<div style="padding: 0px;">
A string S consisting of N characters is considered to be <i>properly nested</i> if any of the following conditions is true:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">S is empty;</li>
<li style="list-style-type: disc;">S has the form "<tt>(U)</tt>" or "<tt>[U]</tt>" or "<tt>{U}</tt>" where U is a properly nested string;</li>
<li style="list-style-type: disc;">S has the form "<tt>VW</tt>" where V and W are properly nested strings.</li>
</ul>
</blockquote>
<div style="padding: 0px;">
For example, the string "<tt>{[()()]}</tt>" is properly nested but "<tt>([)()]</tt>" is not.</div>
<div style="padding: 0px;">
Write a function:</div>
<blockquote>
<div class="lang-c" style="font-family: monospace; font-size: 9pt; padding: 0px;">
<tt>int solution(char *S);</tt></div>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<div style="padding: 0px;">
that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise.</div>
<div style="padding: 0px;">
For example, given S = "<tt>{[()()]}</tt>", the function should return 1 and given S = "<tt>([)()]</tt>", the function should return 0, as explained above.</div>
<div style="padding: 0px;">
Assume that:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">N is an integer within the range [0..200,000];</li>
<li style="list-style-type: disc;">string S consists only of the following characters: "<tt>(</tt>", "<tt>{</tt>", "<tt>[</tt>", "<tt>]</tt>", "<tt>}</tt>" and/or "<tt>)</tt>".</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Complexity:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">expected worst-case time complexity is O(N);</li>
<li style="list-style-type: disc;">expected worst-case space complexity is O(N) (not counting the storage required for input arguments).</li>
</ul>
</blockquote>
<br />
<a name='more'></a><br />
Solution:<br />
</div>
<pre class="brush: python">
from string import maketrans
def solution(S):
b, t = [], maketrans('}])','{[(')
for i in S:
if i in '{[(':
b.append(i); continue
if len(b) == 0 or \
i.translate(t) != b.pop():
return 0
return 1 if len(b) == 0 else 0
</pre>
</div>
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8657487033851500757.post-781791318036794502014-01-13T00:00:00.002+02:002014-01-13T17:47:46.157+02:00Codility. Train. Number-of-disc-intersections ★★★<div dir="ltr" style="text-align: left;" trbidi="on">
<div id="brinza-task-description" style="font-family: Verdana, Arial; font-size: 12px;">
<div style="padding: 0px;">
Given an array A of N integers, we draw N discs in a 2D plane such that the I-th disc is centered on (0,I) and has a radius of A[I]. We say that the J-th disc and K-th disc intersect if J ≠ K and J-th and K-th discs have at least one common point.</div>
<div style="padding: 0px;">
Write a function:</div>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
<div class="lang-py" style="font-family: monospace; font-size: 9pt; padding: 0px;">
<tt>def solution(A)</tt></div>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<div style="padding: 0px;">
that, given an array A describing N discs as explained above, returns the number of pairs of intersecting discs. For example, given N=6 and:</div>
<blockquote>
<div style="padding: 0px;">
</div>
<pre><tt>A[0] = 1 A[1] = 5 A[2] = 2
A[3] = 1 A[4] = 4 A[5] = 0 </tt></pre>
<div style="padding: 0px;">
</div>
</blockquote>
<div style="padding: 0px;">
intersecting discs appear in eleven pairs of elements:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">0 and 1,</li>
<li style="list-style-type: disc;">0 and 2,</li>
<li style="list-style-type: disc;">0 and 4,</li>
<li style="list-style-type: disc;">1 and 2,</li>
<li style="list-style-type: disc;">1 and 3,</li>
<li style="list-style-type: disc;">1 and 4,</li>
<li style="list-style-type: disc;">1 and 5,</li>
<li style="list-style-type: disc;">2 and 3,</li>
<li style="list-style-type: disc;">2 and 4,</li>
<li style="list-style-type: disc;">3 and 4,</li>
<li style="list-style-type: disc;">4 and 5.</li>
</ul>
</blockquote>
<div style="padding: 0px;">
so the function should return 11.</div>
<div style="padding: 0px;">
The function should return −1 if the number of intersecting pairs exceeds 10,000,000.</div>
<div style="padding: 0px;">
Assume that:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">N is an integer within the range [0..100,000];</li>
<li style="list-style-type: disc;">each element of array A is an integer within the range [0..2147483647].</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Complexity:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">expected worst-case time complexity is O(N*log(N));</li>
<li style="list-style-type: disc;">expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Elements of input arrays can be modified.</div>
<div>
<br />
<a name='more'></a><br /><br />
Solution:</div>
</div>
<pre class="brush: python">
def solution(A):
B, M = [], 0
for i in xrange(len(A)):
M += len(B) - binF(B, i - A[i])
if M > 10000000:
return -1
B.insert(binF(B, i + A[i]), i + A[i])
return M
def binF(A, B):
iF, iL = 0, len(A)
if iL == 0 or \
A[iL - 1] < B:
return iL
if A[0] > B:
return iF
while iF < iL:
iM = iF + (iL - iF) / 2
if B <= A[iM]:
iL = iM
else:
iF = iM + 1
return iF
</pre>
</div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8657487033851500757.post-74156990329027771302014-01-13T00:00:00.001+02:002014-01-13T09:45:23.612+02:00Codility. Train. Max-product-of-three ★★<div dir="ltr" style="text-align: left;" trbidi="on">
<div id="brinza-task-description" style="font-family: Verdana, Arial; font-size: 12px;">
<div style="padding: 0px;">
A non-empty zero-indexed array A consisting of N integers is given. The <i>product</i> of triplet (P, Q, R) equates to A[P] * A[Q] * A[R] (0 ≤ P < Q < R < N).</div>
<div style="padding: 0px;">
For example, array A such that:</div>
<div style="padding: 0px;">
</div>
<pre><tt> A[0] = -3
A[1] = 1
A[2] = 2
A[3] = -2
A[4] = 5
A[5] = 6</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
contains the following example triplets:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">(0, 1, 2), product is −3 * 1 * 2 = −6</li>
<li style="list-style-type: disc;">(1, 2, 4), product is 1 * 2 * 5 = 10</li>
<li style="list-style-type: disc;">(2, 4, 5), product is 2 * 5 * 6 = 60</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Your goal is to find the maximal product of any triplet.</div>
<div style="padding: 0px;">
Write a function:</div>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
<div class="lang-py" style="font-family: monospace; font-size: 9pt; padding: 0px;">
<tt>def solution(A)</tt></div>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<div style="padding: 0px;">
that, given a non-empty zero-indexed array A, returns the value of the maximal product of any triplet.</div>
<div style="padding: 0px;">
For example, given array A such that:</div>
<div style="padding: 0px;">
</div>
<pre><tt> A[0] = -3
A[1] = 1
A[2] = 2
A[3] = -2
A[4] = 5
A[5] = 6</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
the function should return 60, as the product of triplet (2, 4, 5) is maximal.</div>
<div style="padding: 0px;">
Assume that:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">N is an integer within the range [3..100,000];</li>
<li style="list-style-type: disc;">each element of array A is an integer within the range [−1,000..1,000].</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Complexity:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">expected worst-case time complexity is O(N*log(N));</li>
<li style="list-style-type: disc;">expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Elements of input arrays can be modified.</div>
<div>
<a name='more'></a><br /></div>
<div>
Solution:</div>
</div>
<pre class="brush: python">def solution(A):
L, A = len(A), list(A); A.sort()
return (lambda x, y: x if x > y else y)\
(A[L-1]*A[L-2]*A[L-3], A[0]*A[1]*A[L-1])</pre>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8657487033851500757.post-61150642093549527372014-01-13T00:00:00.000+02:002014-01-13T09:44:54.557+02:00Codility. Train. Triangle ★<div dir="ltr" style="text-align: left;" trbidi="on">
<div id="brinza-task-description" style="font-family: Verdana, Arial; font-size: 12px;">
<div style="padding: 0px;">
A zero-indexed array A consisting of N integers is given. A triplet (P, Q, R) is <i>triangular</i> if 0 ≤ P < Q < R < N and:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">A[P] + A[Q] > A[R],</li>
<li style="list-style-type: disc;">A[Q] + A[R] > A[P],</li>
<li style="list-style-type: disc;">A[R] + A[P] > A[Q].</li>
</ul>
</blockquote>
<div style="padding: 0px;">
For example, consider array A such that:</div>
<div style="padding: 0px;">
</div>
<pre><tt> A[0] = 10 A[1] = 2 A[2] = 5
A[3] = 1 A[4] = 8 A[5] = 20</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
Triplet (0, 2, 4) is triangular.</div>
<div style="padding: 0px;">
Write a function:</div>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
<div class="lang-py" style="font-family: monospace; font-size: 9pt; padding: 0px;">
<tt>def solution(A)</tt></div>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<div style="padding: 0px;">
that, given a zero-indexed array A consisting of N integers, returns 1 if there exists a triangular triplet for this array and returns 0 otherwise. For example, given array A such that:</div>
<div style="padding: 0px;">
</div>
<pre><tt> A[0] = 10 A[1] = 2 A[2] = 5
A[3] = 1 A[4] = 8 A[5] = 20</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
the function should return 1, as explained above. Given array A such that:</div>
<div style="padding: 0px;">
</div>
<pre><tt> A[0] = 10 A[1] = 50 A[2] = 5
A[3] = 1</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
the function should return 0.</div>
<div style="padding: 0px;">
Assume that:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">N is an integer within the range [0..1,000,000];</li>
<li style="list-style-type: disc;">each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Complexity:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">expected worst-case time complexity is O(N*log(N));</li>
<li style="list-style-type: disc;">expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Elements of input arrays can be modified.</div>
<div>
<a name='more'></a><br /></div>
<div>
Solution:</div>
</div>
<pre class="brush: python">def solution(A):
A.sort()
for i in xrange(len(A) - 2):
P, Q, R = A[i], A[i + 1], A[i + 2]
if P + Q > R and Q + R > P and R + P > Q:
return 1
else:
return 0</pre>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8657487033851500757.post-64857971901266098262014-01-10T00:00:00.000+02:002014-01-12T11:53:44.339+02:00Codility. Train. Genomic-range-query ★★★<div dir="ltr" style="text-align: left;" trbidi="on">
<div id="brinza-task-description" style="font-family: Verdana, Arial; font-size: 12px;">
<div style="padding: 0px;">
A non-empty zero-indexed string S is given. String S consists of N characters from the set of upper-case English letters <tt>A, C, G, T</tt>.</div>
<div style="padding: 0px;">
This string actually represents a DNA sequence, and the upper-case letters represent single nucleotides.</div>
<div style="padding: 0px;">
You are also given non-empty zero-indexed arrays P and Q consisting of M integers. These arrays represent queries about minimal nucleotides. We represent the letters of string S as integers 1, 2, 3, 4 in arrays P and Q, where <tt>A</tt> = 1, <tt>C</tt> = 2, <tt>G</tt> = 3, <tt>T</tt> = 4, and we assume that <tt>A < C < G < T</tt>.</div>
<div style="padding: 0px;">
Query K requires you to find the minimal nucleotide from the range (P[K], Q[K]), 0 ≤ P[i] ≤ Q[i] < N.</div>
<div style="padding: 0px;">
For example, consider string S = <tt>GACACCATA</tt> and arrays P, Q such that:</div>
<div style="padding: 0px;">
</div>
<pre><tt> P[0] = 0 Q[0] = 8
P[1] = 0 Q[1] = 2
P[2] = 4 Q[2] = 5
P[3] = 7 Q[3] = 7</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
The minimal nucleotides from these ranges are as follows:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">(0, 8) is <tt>A</tt> identified by 1,</li>
<li style="list-style-type: disc;">(0, 2) is <tt>A</tt> identified by 1,</li>
<li style="list-style-type: disc;">(4, 5) is <tt>C</tt> identified by 2,</li>
<li style="list-style-type: disc;">(7, 7) is <tt>T</tt> identified by 4.</li>
</ul>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<div style="padding: 0px;">
Write a function:</div>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
<div class="lang-py" style="font-family: monospace; font-size: 9pt; padding: 0px;">
<tt>def solution(S, P, Q)</tt></div>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<div style="padding: 0px;">
that, given a non-empty zero-indexed string S consisting of N characters and two non-empty zero-indexed arrays P and Q consisting of M integers, returns an array consisting of M characters specifying the consecutive answers to all queries.</div>
<div style="padding: 0px;">
The sequence should be returned as:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">a Results structure (in C), or</li>
<li style="list-style-type: disc;">a vector of integers (in C++), or</li>
<li style="list-style-type: disc;">a Results record (in Pascal), or</li>
<li style="list-style-type: disc;">an array of integers (in any other programming language).</li>
</ul>
</blockquote>
<div style="padding: 0px;">
For example, given the string S = <tt>GACACCATA</tt> and arrays P, Q such that:</div>
<div style="padding: 0px;">
</div>
<pre><tt> P[0] = 0 Q[0] = 8
P[1] = 0 Q[1] = 2
P[2] = 4 Q[2] = 5
P[3] = 7 Q[3] = 7</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
the function should return the values [1, 1, 2, 4], as explained above.</div>
<div style="padding: 0px;">
Assume that:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">N is an integer within the range [1..100,000];</li>
<li style="list-style-type: disc;">M is an integer within the range [1..50,000];</li>
<li style="list-style-type: disc;">each element of array P, Q is an integer within the range [0..N − 1];</li>
<li style="list-style-type: disc;">P[i] ≤ Q[i];</li>
<li style="list-style-type: disc;">string S consists only of upper-case English letters <tt>A, C, G, T</tt>.</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Complexity:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">expected worst-case time complexity is O(N+M);</li>
<li style="list-style-type: disc;">expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Elements of input arrays can be modified.</div>
<div>
<a name='more'></a><br /></div>
<div>
Solution:</div>
</div>
<pre class="brush: python">def solution(S, P, Q):
vMap = dict(A = 1, C = 2, G = 3, T = 4)
vLst = dict(A =[], C =[], G =[], T =[])
for i in xrange(len(S)):
vLst[S[i]].append(i)
for i in xrange(len(P)):
for j in sorted(vLst):
iF, iL = 0, len(vLst[j])
if iL == iF or \
vLst[j][iF] > Q[i] or \
vLst[j][iL - 1] < P[i]:
continue
while iF < iL:
iM = iF + (iL - iF) / 2
if P[i] <= vLst[j][iM]:
if vLst[j][iM] <= Q[i]:
P[i] = vMap[j]
break
iL = iM
else:
iF = iM + 1
else:
continue
break
return P</pre>
</div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8657487033851500757.post-32923553688734591762013-12-25T00:00:00.002+02:002013-12-25T17:37:44.850+02:00Codility. Train. Passing-cars ★★<div dir="ltr" style="text-align: left;" trbidi="on">
<div id="brinza-task-description" style="font-family: Verdana, Arial; font-size: 12px;">
<div style="padding: 0px;">
A non-empty zero-indexed array A consisting of N integers is given. The consecutive elements of array A represent consecutive cars on a road.</div>
<div style="padding: 0px;">
Array A contains only 0s and/or 1s:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">0 represents a car traveling east,</li>
<li style="list-style-type: disc;">1 represents a car traveling west.</li>
</ul>
</blockquote>
<div style="padding: 0px;">
The goal is to count passing cars. We say that a pair of cars (P, Q), where 0 ≤ P < Q < N, is passing when P is traveling to the east and Q is traveling to the west.</div>
<div style="padding: 0px;">
For example, consider array A such that:</div>
<div style="padding: 0px;">
</div>
<pre><tt> A[0] = 0
A[1] = 1
A[2] = 0
A[3] = 1
A[4] = 1</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).</div>
<div style="padding: 0px;">
Write a function:</div>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
<div class="lang-py" style="font-family: monospace; font-size: 9pt; padding: 0px;">
<tt>def solution(A)</tt></div>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<div style="padding: 0px;">
that, given a non-empty zero-indexed array A of N integers, returns the number of passing cars.</div>
<div style="padding: 0px;">
The function should return −1 if the number of passing cars exceeds 1,000,000,000.</div>
<div style="padding: 0px;">
For example, given:</div>
<div style="padding: 0px;">
</div>
<pre><tt> A[0] = 0
A[1] = 1
A[2] = 0
A[3] = 1
A[4] = 1</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
the function should return 5, as explained above.</div>
<div style="padding: 0px;">
Assume that:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">N is an integer within the range [1..100,000];</li>
<li style="list-style-type: disc;">each element of array A is an integer within the range [0..1].</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Complexity:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">expected worst-case time complexity is O(N);</li>
<li style="list-style-type: disc;">expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Elements of input arrays can be modified.</div>
<div><div>
<br /></div>
<a name='more'></a>Solution:</div>
<div>
<br /></div>
</div>
<pre class="brush: python">def solution(A):
c, z = 0, 0
for i in A:
if i == 0:
z += 1
else:
c += z
if c > 1000000000:
return -1
return c
</pre>
</div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8657487033851500757.post-18835899400628565542013-12-25T00:00:00.001+02:002013-12-25T15:41:36.474+02:00Codility. Train. Max-Counters ★★★<div dir="ltr" style="text-align: left;" trbidi="on">
<div id="brinza-task-description" style="font-family: Verdana, Arial; font-size: 12px;">
<div style="padding: 0px;">
You are given N counters, initially set to 0, and you have two possible operations on them:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;"><i>increase(X)</i> − counter X is increased by 1,</li>
<li style="list-style-type: disc;"><i>max_counter</i> − all counters are set to the maximum value of any counter.</li>
</ul>
</blockquote>
<div style="padding: 0px;">
A non-empty zero-indexed array A of M integers is given. This array represents consecutive operations:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),</li>
<li style="list-style-type: disc;">if A[K] = N + 1 then operation K is max_counter.</li>
</ul>
</blockquote>
<div style="padding: 0px;">
For example, given integer N = 5 and array A such that:</div>
<div style="padding: 0px;">
</div>
<pre><tt> A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
the values of the counters after each consecutive operation will be:</div>
<div style="padding: 0px;">
</div>
<pre><tt> (0, 0, 1, 0, 0)
(0, 0, 1, 1, 0)
(0, 0, 1, 2, 0)
(2, 2, 2, 2, 2)
(3, 2, 2, 2, 2)
(3, 2, 2, 3, 2)
(3, 2, 2, 4, 2)</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
The goal is to calculate the value of every counter after all operations.</div>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<div style="padding: 0px;">
Write a function:</div>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
<div class="lang-py" style="font-family: monospace; font-size: 9pt; padding: 0px;">
<tt>def solution(N, A)</tt></div>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<div style="padding: 0px;">
that, given an integer N and a non-empty zero-indexed array A consisting of M integers, returns a sequence of integers representing the values of the counters.</div>
<div style="padding: 0px;">
The sequence should be returned as:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">a structure Results (in C), or</li>
<li style="list-style-type: disc;">a vector of integers (in C++), or</li>
<li style="list-style-type: disc;">a record Results (in Pascal), or</li>
<li style="list-style-type: disc;">an array of integers (in any other programming language).</li>
</ul>
</blockquote>
<div style="padding: 0px;">
For example, given:</div>
<div style="padding: 0px;">
</div>
<pre><tt> A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
the function should return [3, 2, 2, 4, 2], as explained above.</div>
<div style="padding: 0px;">
Assume that:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">N and M are integers within the range [1..100,000];</li>
<li style="list-style-type: disc;">each element of array A is an integer within the range [1..N + 1].</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Complexity:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">expected worst-case time complexity is O(N+M);</li>
<li style="list-style-type: disc;">expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Elements of input arrays can be modified.</div>
<div>
<br /></div>
<div>
<a name='more'></a>Solution:</div>
<div>
<br /></div>
</div>
<pre class="brush: python">def solution(N, A):
iMin, iMax = 0, 0
iMas = [iMax] * N
for i in A:
if i == N + 1:
iMin = iMax
else:
if iMas[i - 1] < iMin:
iMas[i - 1] = iMin + 1
else:
iMas[i - 1] = iMas[i - 1] + 1
if iMas[i - 1] > iMax:
iMax = iMas[i - 1]
for i in xrange(len(iMas)):
if iMas[i] < iMin:
iMas[i] = iMin
return iMas
</pre>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8657487033851500757.post-17479248886296989332013-12-25T00:00:00.000+02:002013-12-25T13:17:28.370+02:00Codility. Train. Frog-River-One ★★<div dir="ltr" style="text-align: left;" trbidi="on">
<div id="brinza-task-description" style="font-family: Verdana, Arial; font-size: 12px;">
<div style="padding: 0px;">
A small frog wants to get to the other side of a river. The frog is currently located at position 0, and wants to get to position X. Leaves fall from a tree onto the surface of the river.</div>
<div style="padding: 0px;">
You are given a non-empty zero-indexed array A consisting of N integers representing the falling leaves. A[K] represents the position where one leaf falls at time K, measured in minutes.</div>
<div style="padding: 0px;">
The goal is to find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X.</div>
<div style="padding: 0px;">
For example, you are given integer X = 5 and array A such that:</div>
<div style="padding: 0px;">
</div>
<pre><tt> A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
In minute 6, a leaf falls into position 5. This is the earliest time when leaves appear in every position across the river.</div>
<div style="padding: 0px;">
Write a function:</div>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
<div class="lang-py" style="font-family: monospace; font-size: 9pt; padding: 0px;">
<tt>def solution(X, A)</tt></div>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<div style="padding: 0px;">
that, given a non-empty zero-indexed array A consisting of N integers and integer X, returns the earliest time when the frog can jump to the other side of the river.</div>
<div style="padding: 0px;">
If the frog is never able to jump to the other side of the river, the function should return −1.</div>
<div style="padding: 0px;">
For example, given X = 5 and array A such that:</div>
<div style="padding: 0px;">
</div>
<pre><tt> A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
the function should return 6, as explained above. Assume that:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">N and X are integers within the range [1..100,000];</li>
<li style="list-style-type: disc;">each element of array A is an integer within the range [1..X].</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Complexity:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">expected worst-case time complexity is O(N);</li>
<li style="list-style-type: disc;">expected worst-case space complexity is O(X), beyond input storage (not counting the storage required for input arguments).</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Elements of input arrays can be modified.</div>
<div><br />
<a name='more'></a>Solution:</div>
<br />
</div>
<pre class="brush: python">def solution(X, A):
j = set()
for i in xrange(len(A)):
if A[i] <= X:
j.add(A[i])
if len(j) + 1 > X:
return i
return -1
</pre>
</div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8657487033851500757.post-31506462309344826782013-12-24T00:00:00.003+02:002013-12-24T18:20:28.777+02:00Codility. Train. Perm-Check ★<div dir="ltr" style="text-align: left;" trbidi="on">
<div id="brinza-task-description" style="font-family: Verdana, Arial; font-size: 12px;">
<div style="padding: 0px;">
A non-empty zero-indexed array A consisting of N integers is given.</div>
<div style="padding: 0px;">
A <i>permutation</i> is a sequence containing each element from 1 to N once, and only once.</div>
<div style="padding: 0px;">
For example, array A such that:</div>
<div style="padding: 0px;">
</div>
<pre><tt> A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
is a permutation, but array A such that:</div>
<div style="padding: 0px;">
</div>
<pre><tt> A[0] = 4
A[1] = 1
A[2] = 3</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
is not a permutation.</div>
<div style="padding: 0px;">
The goal is to check whether array A is a permutation.</div>
<div style="padding: 0px;">
Write a function:</div>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
<div class="lang-py" style="font-family: monospace; font-size: 9pt; padding: 0px;">
<tt>def solution(A)</tt></div>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<div style="padding: 0px;">
that, given a zero-indexed array A, returns 1 if array A is a permutation and 0 if it is not.</div>
<div style="padding: 0px;">
For example, given array A such that:</div>
<div style="padding: 0px;">
</div>
<pre><tt> A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
the function should return 1.</div>
<div style="padding: 0px;">
Given array A such that:</div>
<div style="padding: 0px;">
</div>
<pre><tt> A[0] = 4
A[1] = 1
A[2] = 3</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
the function should return 0.</div>
<div style="padding: 0px;">
Assume that:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">N is an integer within the range [1..100,000];</li>
<li style="list-style-type: disc;">each element of array A is an integer within the range [1..1,000,000,000].</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Complexity:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">expected worst-case time complexity is O(N);</li>
<li style="list-style-type: disc;">expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Elements of input arrays can be modified.</div>
<div>
<a name='more'></a><div>
<br /></div>
Solution:</div>
</div>
<pre class="brush: python">def solution(A):
A.sort(reverse=True)
return 1 if A[0] == len(A) and len(set(A)) == len(A) else 0
</pre>
</div>
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8657487033851500757.post-6391675042867411482013-12-24T00:00:00.002+02:002013-12-24T16:04:45.001+02:00Codility. Train. Tape-Equilibrium ★★★<div dir="ltr" style="text-align: left;" trbidi="on">
<div id="brinza-task-description" style="font-family: Verdana, Arial; font-size: 12px;">
<div style="padding: 0px;">
A non-empty zero-indexed array A consisting of N integers is given. Array A represents numbers on a tape.</div>
<div style="padding: 0px;">
Any integer P, such that 0 < P < N, splits this tape into two non−empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].</div>
<div style="padding: 0px;">
The <i>difference</i> between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|</div>
<div style="padding: 0px;">
In other words, it is the absolute difference between the sum of the first part and the sum of the second part.</div>
<div style="padding: 0px;">
For example, consider array A such that:</div>
<div style="padding: 0px;">
</div>
<pre><tt> A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 4
A[4] = 3</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
We can split this tape in four places:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">P = 1, difference = |3 − 10| = 7 </li>
<li style="list-style-type: disc;">P = 2, difference = |4 − 9| = 5 </li>
<li style="list-style-type: disc;">P = 3, difference = |6 − 7| = 1 </li>
<li style="list-style-type: disc;">P = 4, difference = |10 − 3| = 7 </li>
</ul>
</blockquote>
<div style="padding: 0px;">
Write a function:</div>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
<div class="lang-py" style="font-family: monospace; font-size: 9pt; padding: 0px;">
<tt>def solution(A)</tt></div>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<blockquote>
</blockquote>
<div style="padding: 0px;">
that, given a non-empty zero-indexed array A of N integers, returns the minimal difference that can be achieved.</div>
<div style="padding: 0px;">
For example, given:</div>
<div style="padding: 0px;">
</div>
<pre><tt> A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 4
A[4] = 3</tt></pre>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
the function should return 1, as explained above.</div>
<div style="padding: 0px;">
Assume that:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">N is an integer within the range [2..100,000];</li>
<li style="list-style-type: disc;">each element of array A is an integer within the range [−1,000..1,000].</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Complexity:</div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">expected worst-case time complexity is O(N);</li>
<li style="list-style-type: disc;">expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).</li>
</ul>
</blockquote>
<div style="padding: 0px;">
Elements of input arrays can be modified.</div>
<div style="padding: 0px;">
</div>
<div style="padding: 0px;">
<br /></div>
<a name='more'></a>Solution:<br />
<div style="padding: 0px;">
<br /></div>
</div>
<pre class="brush: python">def solution(A):
iMin, iTmp, i1st, i2nd = None, None, 0, sum(A)
for i in range(len(A) - 1):
i1st, i2nd = i1st + A[i], i2nd - A[i]
iTmp = abs(i1st - i2nd)
if iMin > iTmp or iMin == None:
iMin = iTmp
return iMin
</pre>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8657487033851500757.post-3252883139253924112013-12-24T00:00:00.001+02:002013-12-24T15:05:48.355+02:00Codility. Train. Perm-Missing-Elem ★★<div dir="ltr" style="text-align: left;" trbidi="on">
<div id="brinza-task-description">
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
A zero-indexed array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.</div>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
Your goal is to find that missing element.</div>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
Write a function:</div>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
<div class="lang-py" style="font-family: monospace; font-size: 9pt; padding: 0px;">
<tt>def solution(A)</tt></div>
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
that, given a zero-indexed array A, returns the value of the missing element.</div>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
For example, given array A such that:</div>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
</div>
<pre style="font-family: Verdana, Arial; font-size: 12px;"><tt> A[0] = 2
A[1] = 3
A[2] = 1
A[3] = 5</tt></pre>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
</div>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
the function should return 4, as it is the missing element.</div>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
Assume that:</div>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">N is an integer within the range [0..100,000];</li>
<li style="list-style-type: disc;">the elements of A are all distinct;</li>
<li style="list-style-type: disc;">each element of array A is an integer within the range [1..(N + 1)].</li>
</ul>
</blockquote>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
Complexity:</div>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">expected worst-case time complexity is O(N);</li>
<li style="list-style-type: disc;">expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).</li>
</ul>
</blockquote>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
Elements of input arrays can be modified.</div>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
</div>
<a name='more'></a><br /><br />
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
Solution</div>
<pre class="brush: python">def solution(A):
j = 1
A.sort()
for i in A:
if i != j:
break
j = j + 1
return j
</pre>
<div style="font-family: Verdana, Arial; font-size: 12px;">
<br /></div>
</div>
</div>Unknownnoreply@blogger.com6tag:blogger.com,1999:blog-8657487033851500757.post-30655888501604734322013-12-24T00:00:00.000+02:002013-12-24T14:51:56.531+02:00Codility. Train. Frog-Jmp ★<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.</div>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
Count the minimal number of jumps that the small frog must perform to reach its target.</div>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
Write a function:</div>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
<div class="lang-c" style="font-family: monospace; font-size: 9pt; padding: 0px;">
<tt>def solution(X, Y, D)</tt></div>
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
</blockquote>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.</div>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
For example, given:</div>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
</div>
<pre style="font-size: 12px;"><tt> X = 10
Y = 85
D = 30</tt></pre>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
</div>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
the function should return 3, because the frog will be positioned as follows:</div>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">after the first jump, at position 10 + 30 = 40</li>
<li style="list-style-type: disc;">after the second jump, at position 10 + 30 + 30 = 70</li>
<li style="list-style-type: disc;">after the third jump, at position 10 + 30 + 30 + 30 = 100</li>
</ul>
</blockquote>
<div style="font-family: Verdana, Arial; font-size: 12px; padding: 0px;">
Assume that:</div>
<blockquote style="font-family: Verdana, Arial; font-size: 12px;">
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="list-style-type: disc;">X, Y and D are integers within the range [1..1,000,000,000];</li>
<li style="list-style-type: disc;">X ≤ Y.</li>
</ul>
</blockquote>
<div style="font-size: 12px; padding: 0px;">
<span style="font-family: Verdana, sans-serif;">Complexity:</span></div>
<blockquote>
<ul style="list-style-type: none; margin: 10px; padding: 0px;">
<li style="font-size: 12px; list-style-type: disc;"><span style="font-family: Verdana, sans-serif;">expected worst-case time complexity is O(1);</span></li>
<li style="font-size: 12px; list-style-type: disc;"><span style="font-family: Verdana, sans-serif;">expected worst-case space complexity is O(1).</span></li>
</ul>
</blockquote>
<br />
<a name='more'></a><span style="font-family: Verdana, sans-serif; font-size: 12px;">Solution:</span><br />
<pre class="brush: python">import math
def solution(X, Y, D):
return int(math.ceil((Y-X)/float(D)))
</pre>
</div>
Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-8657487033851500757.post-75019254733842449812013-09-30T00:00:00.000+03:002013-09-30T20:34:39.103+03:00WebLogic + JDeveloper = Remote Debugging<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Иногда возникает необходимость проверить работу enterprise приложения на WebLogic сервере в debug-режиме.</div>
<div style="text-align: justify;">
</div>
<a name='more'></a><br />
<div style="text-align: justify;">
Для этого необходимо перевести wls в данный режим, а делается это одной новой строкой в конфигурационном файле $DOMAIN_HOME/bin/setDomainEnv.sh:</div>
<blockquote class="tr_bq">
debugFlag="true"</blockquote>
<div style="text-align: justify;">
После перезапускаем сервер приложений и приступаем к настройке проекта в jDeveloper. </div>
<div style="text-align: justify;">
1. Правым кликом мыши на проекте вызываем меню и выбираем пункт "Project Properties" (либо двойной клик на проекте - откроется тоже самое окно настроек).</div>
<div style="text-align: justify;">
2. Слева, в дереве свойств, выбираем пункт "Run/Debug/Profile". И щелкаем по кнопке "Edit".</div>
<div style="text-align: justify;">
3. В открывшемся окне "Edit Run Configuration ..." для пункта "Launch Settings" устанавливаем галочку напротив элемента "Remote Debugging".</div>
<div style="text-align: justify;">
4. В том же окне для пункта "Tool Settings/Debugger/Remote" у нас должны быть выставлены следующие параметры:</div>
<blockquote class="tr_bq">
Protocol: "Attach to JPDA"<br />Host: IP-адрес или имя сервера<br />Port: порт, по умолчанию 8453</blockquote>
<div style="text-align: justify;">
5. Сохраняем настройки и можем теперь запускать приложение в debug-режиме.</div>
<div style="text-align: justify;">
6. Правой клавишей мыши щелкаем на проекте и выбираем в выпадающем меню пункт "Start Remote Debugger". Подтверждаем наши намерения подключиться к Remote Debugger.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Вот и все. Устанавливаем точки останова в исходном коде вашего проекта и наслаждаетесь debug-режимом.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Примечание: пункт 6 данной инструкции не устанавливает приложение на weblogic-сервере поэтому deploy необходимо выполнить заранее.</div>
<div style="text-align: justify;">
<br /></div>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8657487033851500757.post-17988790535623362772013-03-13T00:00:00.000+02:002013-03-13T10:34:19.620+02:00Удалить BOM маркер из UTF файлов<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Многие продукты при работе с UTF файлами не корректно работают если присутствует на нем <a href="http://ru.wikipedia.org/wiki/Byte_order_mark" target="_blank">BOM</a> маркер. В моей работе частенько приходят файлы, сформированные из Microsoft Visual Studio с указанным префиксом. Для лечения сделал небольшой <a href="http://ru.wikipedia.org/wiki/VBScript" target="_blank">VBScript</a>:</div>
<div style="text-align: justify;">
<br /></div>
<blockquote class="tr_bq">
<div style="text-align: justify;">
<span style="font-size: x-small;">' Removes the Byte Order Mark - BOM from a text file with UTF-8 encoding<br />' The BOM defines that the file was stored with an UTF-8 encoding.<br />Public function RemoveBOM(filePath)<br /> ' Create a reader and a writer<br /> Dim writer,reader, fileSize<br /> Set writer = CreateObject("Adodb.Stream")<br /> Set reader = CreateObject("Adodb.Stream")<br /> ' Load from the text file we just wrote<br /> reader.Open<br /> reader.LoadFromFile filePath<br /> ' Copy all data from reader to writer, except the BOM<br /> writer.Mode=3<br /> writer.Type=1<br /> writer.Open<br /> reader.position=5<br /> reader.copyto writer,-1<br /> ' Overwrite file<br /> writer.SaveToFile filePath,2<br /> ' Return file name<br /> RemoveBOM = filePath<br /> ' Kill objects<br /> Set writer = Nothing<br /> Set reader = Nothing<br />end Function<br /><br />Set objArgs = WScript.Arguments<br />Set objFSO = CreateObject("Scripting.FileSystemObject")<br />Set objFolder = objFSO.GetFolder(objArgs(0))<br />Set colFiles = objFolder.Files<br />For Each objFile in colFiles<br /> RemoveBOM(objArgs(0) + "\" + objFile.Name)<br />Next<br />WScript.Echo "Ok"</span></div>
</blockquote>
<div style="text-align: justify;">
Использовать просто - перетянуть папку, в которой живут неправильные файлы, на этот скрипт.
</div>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8657487033851500757.post-74481076226349189912013-02-11T00:00:00.000+02:002013-02-11T11:10:09.968+02:00PostgreSQL & WebLogic<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Появилась задача в Oracle SOA Suite выбирать дополнительную информацию из СУБД PostgreSQL. Заглянув в настройки создания нового JDBC-подключения для WebLogic сначала обрадовался когда в поле Database Type нашел пункт "PostgreSQL". Но на этапе тестирования нового подключения получил ошибку - модуль org.postgresql.Driver не найден.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Ниже краткая инструкция, как добавить драйвер в WebLogic.</div>
<div style="text-align: justify;">
</div>
<a name='more'></a><br />
<div style="text-align: justify;">
1. Идем на официальный сайт PostgreSQL за нашим драйвером:</div>
<blockquote class="tr_bq">
<div style="text-align: justify;">
<a href="http://jdbc.postgresql.org/download.html">http://jdbc.postgresql.org/download.html</a></div>
</blockquote>
<div style="text-align: justify;">
2. В разделе "Current Version" выбираем драйвер jdbc4:</div>
<blockquote class="tr_bq">
<div style="text-align: justify;">
<a href="http://jdbc.postgresql.org/download/postgresql-9.2-1002.jdbc4.jar">Например, версия (на дату поста): postgresql-9.2-1002.jdbc4.jar</a></div>
</blockquote>
<div style="text-align: justify;">
3. Копируем наш драйвер в директорию WebLogic:</div>
<blockquote class="tr_bq">
<div style="text-align: justify;">
/opt/oracle/product/Middleware/wlserver_10.3/server/lib</div>
</blockquote>
<div style="text-align: justify;">
4. Устанавливаем необходимые права на файл:</div>
<blockquote class="tr_bq">
$ chown oracle:oinstall postgresql-9.2-1002.jdbc4.jar<br />$ chmod 750 postgresql-9.2-1002.jdbc4.jar</blockquote>
<div style="text-align: justify;">
5. Переходим в директорию:</div>
<blockquote class="tr_bq">
<div style="text-align: justify;">
/opt/oracle/product/Middleware/wlserver_10.3/common/bin</div>
</blockquote>
<div style="text-align: justify;">
6. Открываем файл commEnv.sh на редактирования и находим раздел:</div>
<blockquote class="tr_bq">
<div style="text-align: justify;">
<span style="font-size: xx-small;"># set up WebLogic Server's class path<br />WEBLOGIC_CLASSPATH="${JAVA_HOME}/lib/tools.jar${CLASSPATHSEP}${WL_HOME}/server/lib/weblogic_sp.jar${CLASSPATHSEP}${WL_HOME}/server/lib/weblogic.jar${CLASSPATHSEP}${FEATURES_DIR}/weblogic.server.modu<br />les_10.3.6.0.jar${CLASSPATHSEP}${WL_HOME}/server/lib/webservices.jar${CLASSPATHSEP}${ANT_HOME}/lib/ant-all.jar${CLASSPATHSEP}${ANT_CONTRIB}/lib/ant-contrib.jar"<br />export WEBLOGIC_CLASSPATH</span></div>
</blockquote>
<div style="text-align: justify;">
7. Дополняем строку объявления переменной WEBLOGIC_CLASSPATH:</div>
<blockquote class="tr_bq">
<div style="text-align: justify;">
<span style="font-size: xx-small;">${CLASSPATHSEP}${WL_HOME}/server/lib/postgresql-9.2-1002.jdbc4.jar</span></div>
</blockquote>
<div style="text-align: justify;">
8. Сохраняем изменения и перезапускаем сервер WebLogic / Oracle SOA Suite.</div>
</div>
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8657487033851500757.post-17940825153010136662012-10-03T00:00:00.000+03:002014-05-29T11:46:20.181+03:00Хаки АБС Б2<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Узнал хак для АБС Б2, который очень полезен для тестирования и доработки функционала продукта. В рабочем окне необходимо нажать кнопку тильды "~", в результате появится маленькое окошко для ввода текста. Вводим только один символ "z" и жмем Enter. Получаем волшебное окно "Debug". Дальше уже все понятно.</div>
<div style="text-align: justify;">
Для активации данной возможности необходимо, чтобы в директории ADDINS был модуль Pb2Tracer.bpl и конфигурационный файл к нему Pb2Tracer.add.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
</div>
<br />
<div style="text-align: justify;">
Большое спасибо разработчикам!</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
П.С.: На продуктивной среде данную функцию включать не рекомендую! </div>
<br />
<div style="text-align: justify;">
UPD: Содержимое файла Pb2Tracer.add<br />
<blockquote class="tr_bq">
<span style="font-size: x-small;"><?xml version="1.0" encoding="UTF-8" standalone="yes"?><br /><taskmap><br /><modulelist><br /> <module name="b2Tracer" type="cs-plugin" filename="ADDINS\Pb2Tracer.bpl" load="startup"/><br /></modulelist><br /><tasklist/><br /></taskmap> </span></blockquote>
</div>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8657487033851500757.post-24453246825062229332012-07-23T00:00:00.000+03:002012-07-23T09:32:00.747+03:00Talend Open Studio for ESB. Установка.<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Для установки и работы с Talend Open Studio необходимо в первую очередь позаботиться о наличии java machine на своей рабочей станции. Компания Talend рекомендует использовать Oracle JDK версии 1.6 (update 11 или выше). Для себя я решил оставить текущую версия, ранее установленный OpenJDK.</div>
<br />
<span style="font-family: inherit;">1. Идем скачивать дистрибутив с официального сайта компании Talend: <a href="http://www.talend.com/products/open-studio-esb.php">http://www.talend.com/products/open-studio-esb.php</a></span><br />
<blockquote class="tr_bq">
<span style="font-size: xx-small;">(если нет желания заполнять анкету, то можно воспользоваться ниже приложенной ссылкой, она позволяет сразу начать закачку файла, но работает только для версии 5.1.1: <a href="http://www.talend.com/downloads/download.php?version=tosesb_511">http://www.talend.com/downloads/download.php?version=tosesb_511</a>)</span></blockquote>
<br />
<div style="text-align: -webkit-auto;">
<span style="white-space: pre-wrap;"><span style="font-family: inherit;">2. Распаковываем полученный архив TOS_ESB в рабочую директорию, например сюда:</span></span></div>
<blockquote class="tr_bq">
<span style="white-space: pre-wrap;"><span style="font-family: inherit; font-size: xx-small;">~/TOS_ESB</span></span></blockquote>
<div style="text-align: -webkit-auto;">
<span style="white-space: pre-wrap;"><span style="font-family: inherit;"><br /></span></span></div>
<div style="text-align: -webkit-auto;">
<span style="white-space: pre-wrap;">Сразу же после установки Studio не запустилось, точнее падало из-за ошибки. В журнале нашел следующее стек сообщений:</span></div>
<blockquote class="tr_bq">
<div style="text-align: justify;">
<span style="background-color: white; font-size: xx-small; white-space: pre-wrap;">!MESSAGE Ошибка приложения</span></div>
<span style="white-space: pre-wrap;"></span><br />
<div style="text-align: justify;">
<span style="white-space: pre-wrap;"><span style="background-color: white; font-size: xx-small;">!STACK 1</span></span></div>
<span style="white-space: pre-wrap;"><span style="font-size: xx-small;"></span></span><br />
<div style="text-align: justify;">
<span style="white-space: pre-wrap;"><span style="font-size: xx-small;"><span style="background-color: white;">org.eclipse.swt.SWTError: No more handles [MOZILLA_FIVE_HOME='/usr/lib/xulrunner-addons'] (java.lang.UnsatisfiedLinkError: Could not load SWT library. Reasons: </span></span></span></div>
<span style="white-space: pre-wrap;"><span style="font-size: xx-small;">
</span></span><span style="white-space: pre-wrap;"></span><br />
<div style="text-align: justify;">
<span style="white-space: pre-wrap;"><span style="background-color: white; font-size: xx-small;">/home/TOS_ESB/Studio/configuration/org.eclipse.osgi/bundles/481/1/.cp/libswt-mozilla-gtk-3655.so: libxpcom.so: невозможно открыть разделяемый объектный файл: Нет такого файла или каталога </span><span style="background-color: white; font-size: xx-small;">no swt-mozilla-gtk in java.library.path </span><span style="background-color: white; font-size: xx-small;">/tmp/swtlib-32/libswt-mozilla-gtk-3655.so: libxpcom.so: невозможно открыть разделяемый объектный файл: Нет такого файла или каталога </span><span style="background-color: white; font-size: xx-small;">Can't load library: /tmp/swtlib-32/libswt-mozilla-gtk.so </span><span style="background-color: white; font-size: xx-small;">)</span></span></div>
</blockquote>
<div style="text-align: -webkit-auto;">
<span style="white-space: pre-wrap;"><br /></span><br />
<span style="white-space: pre-wrap;">Поэтому следующим этапом была установка недостающего компонента xulrunner. </span></div>
<div style="text-align: -webkit-auto;">
<span style="white-space: pre-wrap;"><br /></span></div>
<div style="text-align: justify;">
<span style="background-color: white; font-family: inherit; white-space: pre-wrap;">3. Переходим на официальный сайт Mozilla и скачиваем архив с бинарными файлами. Ссылка: </span><a href="https://ftp.mozilla.org/pub/mozilla.org/xulrunner/releases/1.9.2.19/runtimes/" style="background-color: white; font-family: inherit; text-align: left;">https://ftp.mozilla.org/pub/mozilla.org/xulrunner/releases/1.9.2.19/runtimes/</a></div>
<div style="text-align: -webkit-auto;">
<br /></div>
4. Извлекаем содержимое, полученного архива, например, в директорию: <br />
<blockquote class="tr_bq">
<span style="font-size: xx-small;">~/TOS_ESB/xulrunner-1.9.2/</span></blockquote>
<br />
<div style="text-align: justify;">
5. Открываем конфигурационный файл <span style="font-size: x-small;"><b>~/TOS_ESB/Studio/TOS_ESB-linux-gtk-x86.ini</b></span> и в конец документа добавляем строку, следующего вида:</div>
<blockquote class="tr_bq">
<span style="font-size: xx-small;">-Dorg.eclipse.swt.browser.XULRunnerPath=~/TOS_ESB/xulrunner-1.9.2/</span></blockquote>
<br />
P.S.: Более поздняя версия xulrunner не подошла, ошибка в журнале выглядела так:<br />
<blockquote class="tr_bq">
<span style="font-size: xx-small;">!MESSAGE Ошибка приложения<br />!STACK 1<br />org.eclipse.swt.SWTError: XPCOM error -2147467261</span></blockquote>
<div>
<br /></div>
</div>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8657487033851500757.post-54898712402860447342012-01-06T00:00:00.000+02:002012-01-06T12:05:38.612+02:00Рыцарь VS ГипноЖаба<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyxUYhMikcn1E1bXL9hTvRg7ckKU8X93KOXTO7xtyo2xqK9zxmN0VziBZgwm6bZskSM82OpP27UVHgA7gcAaSyE-C1FaVsHlxZJbg5fPP3L-exoKgTTTIjzZo2xlUFa5QNJk59LNz78AU/s1600/IMAG0116.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="300" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyxUYhMikcn1E1bXL9hTvRg7ckKU8X93KOXTO7xtyo2xqK9zxmN0VziBZgwm6bZskSM82OpP27UVHgA7gcAaSyE-C1FaVsHlxZJbg5fPP3L-exoKgTTTIjzZo2xlUFa5QNJk59LNz78AU/s400/IMAG0116.jpg" width="400" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5pzOJisNdyAxJKir5zt87etsOAj4jYBduwCGceptIacPJcs1ildSKOgxeJtiiUoM9MdKeOwsiSmyw5Cc32v_lvpsvWYm9klxDPq6Hrb99qEGFg7lY-hgV7KM_kKjHKXQzzwYl11zlsmM/s1600/IMAG0117.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="400" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5pzOJisNdyAxJKir5zt87etsOAj4jYBduwCGceptIacPJcs1ildSKOgxeJtiiUoM9MdKeOwsiSmyw5Cc32v_lvpsvWYm9klxDPq6Hrb99qEGFg7lY-hgV7KM_kKjHKXQzzwYl11zlsmM/s400/IMAG0117.jpg" width="301" /></a></div>
<br /></div>Unknownnoreply@blogger.com1