<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>CS Student / freetonik.com</title>
	
	<link>http://freetonik.com</link>
	<description>Сайт фритоника</description>
	<lastBuildDate>Sat, 12 May 2012 06:00:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/ComputerScienceStudent" /><feedburner:info uri="computersciencestudent" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId>ComputerScienceStudent</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>Моя лекция по операционным системам</title>
		<link>http://feedproxy.google.com/~r/ComputerScienceStudent/~3/baLQUx8g33Y/</link>
		<comments>http://freetonik.com/text/compsci/os_lecture_3/#comments</comments>
		<pubDate>Sun, 04 Mar 2012 19:25:31 +0000</pubDate>
		<dc:creator>freetonik</dc:creator>
				<category><![CDATA[Видео]]></category>
		<category><![CDATA[Информатика]]></category>
		<category><![CDATA[iitu]]></category>
		<category><![CDATA[лекция]]></category>

		<guid isPermaLink="false">http://freetonik.com/?p=3498</guid>
		<description><![CDATA[В этом году я решил попробовать преподавать информатику в международном университете информационных технологий в Алматы. Читаю лекции по интернет-программированию и операционным системам. Я записываю аудио всех своих лекций и обязательно выложу их позже, а пока могу показать третью лекцию по операционным системам, любезно снятую одним из студентов. Да, лекции в нашем университете – на английском [...]
Наши роботы считают, что вас заинтересует это:<ul>
<li><a href='http://freetonik.com/text/prilagatelnye-ot-imen-sobstvennyx/' rel='bookmark' title='Прилагательные от имен собственных'>Прилагательные от имен собственных</a> <small>В русском языке имена собственные пишутся с большой буквы, а...</small></li>
<li><a href='http://freetonik.com/text/uslovie-i-budushhee-vremya/' rel='bookmark' title='Условие и будущее время'>Условие и будущее время</a> <small>В русском языке можно поставить условие в будущем времени: Если...</small></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>В этом году я решил попробовать преподавать информатику в <a href="http://www.iitu.kz/">международном университете информационных технологий</a> в Алматы. Читаю лекции по интернет-программированию и операционным системам. Я записываю аудио всех своих лекций и обязательно выложу их позже, а пока могу показать третью лекцию по операционным системам, любезно снятую одним из студентов.</p>
<p>Да, лекции в нашем университете – на английском языке.</p>
<p><iframe width="560" height="315" src="http://www.youtube.com/embed/papyI24BGno?rel=0" frameborder="0" allowfullscreen></iframe></p>
<p> <img src="http://freetonik.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=3498" width="1" height="1" style="display: none;" /></p>
<p>Наши роботы считают, что вас заинтересует это:</p><ul>
<li><a href='http://freetonik.com/text/prilagatelnye-ot-imen-sobstvennyx/' rel='bookmark' title='Прилагательные от имен собственных'>Прилагательные от имен собственных</a> <small>В русском языке имена собственные пишутся с большой буквы, а...</small></li>
<li><a href='http://freetonik.com/text/uslovie-i-budushhee-vremya/' rel='bookmark' title='Условие и будущее время'>Условие и будущее время</a> <small>В русском языке можно поставить условие в будущем времени: Если...</small></li>
</ul><img src="http://feeds.feedburner.com/~r/ComputerScienceStudent/~4/baLQUx8g33Y" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://freetonik.com/text/compsci/os_lecture_3/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://freetonik.com/text/compsci/os_lecture_3/</feedburner:origLink></item>
		<item>
		<title>Советы мне-в-прошлом</title>
		<link>http://feedproxy.google.com/~r/ComputerScienceStudent/~3/GtdZT7izvCo/</link>
		<comments>http://freetonik.com/text/compsci/advices_to_myself/#comments</comments>
		<pubDate>Mon, 21 Nov 2011 06:00:26 +0000</pubDate>
		<dc:creator>freetonik</dc:creator>
				<category><![CDATA[Информатика]]></category>
		<category><![CDATA[разработка ПО]]></category>
		<category><![CDATA[советы]]></category>

		<guid isPermaLink="false">http://freetonik.com/?p=3377</guid>
		<description><![CDATA[У меня очень мало опыта (суммарно программистом я проработал 13 месяцев), тем не менее, я хотел бы дать несколько советов себе-в-прошлом, ну, или иными словами всем тем, кто сейчас учится в университете и планирует стать разработчиком ПО. Ни в коей мере не претендую на мудрость или опытность. Немного подумав, я понял, что все эти советы как [...]
Наши роботы искали похожие записи, но не нашли :(]]></description>
			<content:encoded><![CDATA[<p>У меня очень мало опыта (суммарно программистом я проработал 13 месяцев), тем не менее, я хотел бы дать несколько советов себе-в-прошлом, ну, или иными словами всем тем, кто сейчас учится в университете и планирует стать разработчиком ПО. Ни в коей мере не претендую на мудрость или опытность. Немного подумав, я понял, что все эти советы как никогда актуальны для меня и сегодня тоже. </p>
<p>Все советы автономны и их порядок не имеет значения.</p>
<h6><img src="http://freetonik.com/wp-content/uploads/2011/11/octocat.png" alt="octocat" title="octocat" width="145" height="145" class="alignnone size-full wp-image-3388" /></h6>
<p><strong>Программируйте.</strong> Программируйте. Программируйте. Менеджеры той компании, где я работаю, придерживаются мнения, что резюме программиста это github. Конечно, это лишь выражение, смысл в том, что от программиста в первую очередь ожидают код, а потом – оценки, рекомендации и сертификаты. Программируйте. Опыт важнее оценок и точка. Если работодатель настаивает на обратном, то подумайте дважды, перед тем, как устраиваться к нему на работу.</p>
<p><strong>Познакомьтесь с UNIX</strong><strong>.</strong> Установка Убунту и компиляция ядра – это не знакомство с UNIX. Почитайте о том инженерном и научном фундаменте который лежит в основе философии UNIX. Не обязательно становится крутым сисадмином и поднимать десяток серверов, лучше просто привыкните к принципам работы и UNIX way.</p>
<p><strong>Математика – это главное.</strong> Не смотря на сугубую потребительскую направленность многих софтверных компаний, фундаментальные науки остаются фундаментом всего.</p>
<p><strong>Задавайте вопросы.</strong> Естественно, если не нашели ответ в гугле. Соответственно, <strong>не задавайте вопросы</strong>, на которые может ответить гугл. Сайт <a href="http://www.google.ca/url?sa=t&amp;rct=j&amp;q=stackoverflow&amp;source=web&amp;cd=1&amp;ved=0CC8QFjAA&amp;url=http%3A%2F%2Fstackoverflow.com%2F&amp;ei=d9_JTsn4JqLx0gG7iv39Dw&amp;usg=AFQjCNERidL9Hb6OvGW93_Y6MRj3aTdMVA&amp;sig2=xTJPZs2WSyCXQPWYeWqf3w">StackOverflow</a> – ваш лучший друг. Задавайте вопросы в интернете, среди друзей, учителей, коллег. Глупый вопрос лучше незнания.</p>
<p><strong>Познакомьтесь с системами контроля версий.</strong>  Хотя бы с основными – SVN, Git, Mercurial. Откройте репозитарий на своей машине и используйте его для домашних заданий и собственных проектов.</p>
<h6><img src="http://freetonik.com/wp-content/uploads/2011/11/tools.jpg" alt="Инструменты" title="Инструменты" width="145" height="109" class="alignnone size-full wp-image-3384" /><br />
Знай свой инструмент<br />
</h6>
<p><strong>Познакомьтесь с современными инструментами разработки.</strong> Зачастую в университетах не уделяют внимания средам разработки и другим программам и утилитам, необходимым для полноценной работы. Многие IDE бесплатны, попробуйте Eclipse, NetBeans, Emacs, XCode, привыкните к принципам работы, найдите удобный для вас инструмент.</p>
<p><strong>Научитесь пользоваться отладчиком.</strong> Это настолько критично, что совершенно непонятно, почему университеты уделяют этому так мало внимания.</p>
<p><strong>Познакомьтесь с методологиями разработки.</strong>  Сложно им придумать применение в университетской жизни, но все же возможно. Как минимум, вы можете попробовать использовать какую-нибудь методологию в своем с другом проекте.</p>
<p><strong>Познакомьтесь с шаблонами (паттернами) проектирования.</strong> Про это уже сто раз говорили, но я повторюсь. Здесь вы не отвертитесь и применить хотя бы пару основных паттернов где-нибудь просто обязаны. Достаньте свой телефон и взгляните на первую попавшуюся программу: представьте, как можно к нему применить какой-нибудь паттерн.</p>
<p><strong>Программируйте в команде.</strong> Даже вдвоем вы получите неплохой опыт, особенно если примените вышестоящие советы: используйте систему контроля версий, примените какую-нибудь методологию, используйте какой-нибудь паттерн. Возможно, на этот момент вам будет казаться, что все это не имеет большого смысла и куда проще и быстрее было бы писать код не замарачиваясь, и, скорее всего, вы окажитесь правы, но не забывайте – вся учеба это скорее упражнение, чем работа.</p>
<p><strong>Работайте над собственными проектами.</strong> Обратно к первому пункту – программируйте, но не ограничивайтесь домашними заданиями или упражнениями из книг. Начните свой проект.</p>
<p><strong>Изучите новый для себя язык программирования.</strong> Иногда слышу нечто вроде «нас учат чему-то, я не знаю, где это будет применяться в жизни». Такие люди зачастую настолько уверены в бесполезности некоторых этих знаний, что после окончания университета работают по какой-то другой специальности потому, что их не научили программировать на популярном сегодня языке программирования. Забудьте фразу «мне это не понадобиться в будущем». Когда в детском саду учат читать, то никто не готовит профессиональных чтецов. Детей просто учат пользоваться инструментом для получения информации.</p>
<p><strong>Свыкнетесь с мыслью, что кодинг – далеко не единственное, что придётся делать.</strong> Скорее всего, разработчику нужно будет работать с клиентами, искать решения проблем, бороться с инструментами и технологиями.</p>
<h6><img src="http://freetonik.com/wp-content/uploads/2011/11/beer.jpg" alt="Пиво" title="Пиво" width="145" height="194" class="alignnone size-full wp-image-3386" /><br />
У нас на работе всегда есть пиво :-)<br />
</h6>
<p><strong>Настаивайте на приятной для вас обстановке.</strong> Хорошему работодателю главное – продуктивность разработчика, а если не нравится рабочее место, то сложно быть продуктивным. Это понятие включает в себя не только стол и стул, но и график работы, здание, офис, атмосферу, инструменты разработки и так далее.</p>
<p><strong>Не забывайте о принципе Парето.</strong> 20 процентов усилий дают 80 процентов результата. Это, естественно, не правило, но вполне очевидная тенденция.</p>
<p>И самое главное: <strong>если вам не нравится программирование, то не становитесь программистом.</strong> Очень просто :-) Ничем хорошим работа без удовольствия закончиться не может.</p>
<p>Надеюсь, еще через пять лет я дополню этот список новыми советами, а пока можете посоветовать что-нибудь сами.</p>
<p> <img src="http://freetonik.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=3377" width="1" height="1" style="display: none;" /></p>
<p>Наши роботы искали похожие записи, но не нашли :(</p><img src="http://feeds.feedburner.com/~r/ComputerScienceStudent/~4/GtdZT7izvCo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://freetonik.com/text/compsci/advices_to_myself/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		<feedburner:origLink>http://freetonik.com/text/compsci/advices_to_myself/</feedburner:origLink></item>
		<item>
		<title>Решения ребусов</title>
		<link>http://feedproxy.google.com/~r/ComputerScienceStudent/~3/6RgxZogNE7A/</link>
		<comments>http://freetonik.com/text/puzzles_solution/#comments</comments>
		<pubDate>Fri, 28 Oct 2011 01:11:09 +0000</pubDate>
		<dc:creator>freetonik</dc:creator>
				<category><![CDATA[Информатика]]></category>
		<category><![CDATA[Текст]]></category>
		<category><![CDATA[ребус]]></category>

		<guid isPermaLink="false">http://freetonik.com/?p=3134</guid>
		<description><![CDATA[Первый ребус: Сигма – сумма того, что получится в красных фигурных скобках Шеврон внизу и зеленая двойка – битовый сдвиг два раза (или просто деление на 4) Первая картинка – первый логотип компании, которая в последствии превратилась в IBM, а аббривеатура M. F. T. S. – The IBM Mathematical Formula Translating System – язык программирования [...]
Наши роботы искали похожие записи, но не нашли :(]]></description>
			<content:encoded><![CDATA[<p><strong><a href="http://freetonik.com/text/notes/puzzle_for_programmers">Первый ребус</a>:</strong></p>
<ul>
<li>Сигма – сумма того, что получится в красных фигурных скобках</li>
<li>Шеврон внизу и зеленая двойка – <a href="http://ru.wikipedia.org/wiki/%D0%91%D0%B8%D1%82%D0%BE%D0%B2%D1%8B%D0%B9_%D1%81%D0%B4%D0%B2%D0%B8%D0%B3">битовый сдвиг</a> два раза (или просто деление на 4)</li>
<li>Первая картинка – первый логотип компании, которая в последствии превратилась в IBM, а аббривеатура M. F. T. S. – The IBM Mathematical Formula Translating System – язык программирования Fortran. Четыре запятые в конце превращают это в &laquo;for&raquo;.</li>
<li>Пирог (pie, читается так же, как π)  – просто переменная</li>
<li>Знак равенства это знак равенства</li>
<li>На фотографии в компании пингвина Тукса изображен Эндрю Танненбаум, известный в том числе <a href="http://en.wikipedia.org/wiki/Tanenbaum%E2%80%93Torvalds_debate">спором</a> с создателем Линукса Линусом Торвальдсом, который произошел в 1992 году. Две запятые в начале превращают это в 92.</li>
<li>2 читается как &laquo;to&raquo;</li>
<li>printf (&laquo;goodbye, dad\n&raquo;); – смерть Денниса Ритчи, 2011 год. Можно по той же логике превратить это в 11, но это не так важно</li>
<li>Принтер – оператор PRINT</li>
<li>Девочка брызгает (squirt)  воду. Из букв 1, 2, 5, 6 получится SQRT – квадратный корень. (Другие ассоциации со словом &laquo;squirt&raquo;? Бывает)</li>
<li>Снова π</li>
</ul>
<p>Что получается?</p>
<blockquote>
<p>sum {<br />
&nbsp;&nbsp;&nbsp;for π = 92 to 2011<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print sqrt π<br />
} / 4</p>
</blockquote>
<p>Сам численный результат, конечно, не важен.</p>
<p><strong>Второй ребус:</strong></p>
<p><span id="more-3134"></span></p>
<h4>1. Домашний борщ</h4>
<p><img src="http://habrastorage.org/storage1/daee7c64/f75a96b0/593530a6/5e08be12.png" alt="" /><br />
<a name="habracut"></a><br />
<img src="http://habrastorage.org/storage1/53fa9491/4350afb5/7589aa3e/7dc3fe9e.png" alt="" /></p>
<h4>2. Майкл… ?</h4>
<p><img src="http://habrastorage.org/storage1/a567e23e/c3aa77a7/389318dc/b35fd56a.png" alt="" /></p>
<h4>3. Ваш ответ? (для третьего ребуса требуется разгадать первые два)</h4>
<p><img src="http://habrastorage.org/storage1/8af1636a/b9845e3a/b11769ef/9521b085.png" alt="" /></p>
<p><strong>
<p>Решение:</p>
<p></strong></p>
<p>Домашний борщ</p>
<ul>
</ul>
<ul>
<li>В первой таблице всякие выражения, написанный шрифтом webdings. Некоторые – правда, другие – ложь.</li>
<li>Если считать слева направо сверху вниз и соотнести номера ячеек с &laquo;правдой&raquo; с цифрами после таблицы, то получим другие индексы. Стэнли Ипкисс – это чувак из фильма &laquo;Маска&raquo;. Таблица правды/лжи будет использована как маска:</li>
<li>Выберем из таблицы куски QR-кода по полученным индексам, соберем воедино. QR-код ведет на <a href="http://freetonik.com/text/budni/">http://freetonik.com/text/budni/</a></li>
<li>Из подчеркнутых букв получим &laquo;пять&raquo;</li>
</ul>
<p>Майкл ... ?</p>
<ul>
</ul>
<ul>
<li>Чертик – символ FreeBSD. 6 запятых превращает это в F</li>
<li>Инфракрасное изображение кота – infrared = IR</li>
<li>Логоитип сайта StackOverflow, первые две буквы – ST</li>
<li>Ссылка дана с ошибкой, но она не очень важна. Должна вести <a href="http://www.youtube.com/watch?v=gsNaR6FRuO0">сюда</a> – звук дозвона диал-ап модема</li>
<li>Много скобок – это LISP. Запятая в начале превращает его в ISP</li>
<li>Получается &laquo;FIRST dial-up ISP&raquo; – первый интернет провайдер с диал-апом, компания The World.</li>
<li>Иконка домашней странички означает <a href="http://www.std.com/">домашнюю страницу</a> этого провайдера</li>
<li>В исходном HTML-тексте этой страницы на строке 585 в момент публикации ребуса был штат Оклахома</li>
<li>Высшая точка в этом штате – гора Black Mesa, название, известное по игре Half Life</li>
<li>С дипломатом в этой игре постоянно передвигался <a href="http://en.wikipedia.org/wiki/G-Man_(Half-Life)">G-Man</a></li>
<li>Микрофон – озвучка. Этого персонажа в игре озвучивал Майкл Шапиро</li>
</ul>
<p>Ваш ответ?</p>
<ul>
</ul>
<ul>
<li>На последней картинке изображен Barney Google</li>
<li>Забиваем в гугл &laquo;пять&raquo; и &laquo;шапиро&raquo; (или эти два ответа в любой другой форме)</li>
<li>Ищем на странице выдачи элемент с ID &laquo;resultStats&raquo; (это количество найденных страниц) – это и есть ответ</li>
</ul>
<p>Как и в случае с первым ребусом, сам численный ответ не важен.</p>
<p> <img src="http://freetonik.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=3134" width="1" height="1" style="display: none;" /></p>
<p>Наши роботы искали похожие записи, но не нашли :(</p><img src="http://feeds.feedburner.com/~r/ComputerScienceStudent/~4/6RgxZogNE7A" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://freetonik.com/text/puzzles_solution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://freetonik.com/text/puzzles_solution/</feedburner:origLink></item>
		<item>
		<title>Обращение к подписчикам</title>
		<link>http://feedproxy.google.com/~r/ComputerScienceStudent/~3/aQo_raXK_IM/</link>
		<comments>http://freetonik.com/text/notes/to_subscribers/#comments</comments>
		<pubDate>Fri, 21 Oct 2011 01:27:47 +0000</pubDate>
		<dc:creator>freetonik</dc:creator>
				<category><![CDATA[Астрономия]]></category>
		<category><![CDATA[Заметки]]></category>
		<category><![CDATA[Информатика]]></category>
		<category><![CDATA[Подкастинг]]></category>
		<category><![CDATA[обращение]]></category>

		<guid isPermaLink="false">http://freetonik.com/?p=3079</guid>
		<description><![CDATA[Уважаемые подписчики блогов &#171;Подкастим.ру&#187;, &#171;ruAPOD&#187; и &#171;Computer Science Student&#187;! Уже почти год все эти блоги являются разделами единого сайта freetonik.com. Я приглашаю вас подписаться на RSS-поток всего сайта: здесь публикуется намного больше постов, включая заметки о Вселенной &#171;APOD по-русски&#187; и статьи по информатике и ИТ. Адрес фида – http://feeds.feedburner.com/freetonik Старые фиды никуда не денутся, пока [...]
Наши роботы считают, что вас заинтересует это:<ul>
<li><a href='http://freetonik.com/text/notes/apod_ru/' rel='bookmark' title='Astronomy Picture of the Day по-русски'>Astronomy Picture of the Day по-русски</a> <small>Всем известная научная организация NASA довольно активна в интернете, на...</small></li>
<li><a href='http://freetonik.com/video/translations/openmind/' rel='bookmark' title='Непредубежденность'>Непредубежденность</a> <small>На youtube есть канал молодого британца по имени Doug 'QualiaSoup'....</small></li>
<li><a href='http://freetonik.com/text/t_tauri/' rel='bookmark' title='Тау Тельца и туманность Хинда'>Тау Тельца и туманность Хинда</a> <small>Желтоватая звезда ближе к центру снимка это Тау Тельца, которая дала...</small></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p><strong>Уважаемые подписчики блогов &laquo;Подкастим.ру&raquo;, &laquo;ruAPOD&raquo; и &laquo;Computer Science Student&raquo;!</strong></p>
<p>Уже почти год все эти блоги являются разделами единого сайта freetonik.com. Я приглашаю вас подписаться на <a href="http://feeds.feedburner.com/freetonik">RSS-поток</a> всего сайта: здесь публикуется намного больше постов, включая заметки о Вселенной &laquo;APOD по-русски&raquo; и статьи по информатике и ИТ. Адрес фида – <a href="http://feeds.feedburner.com/freetonik">http://feeds.feedburner.com/freetonik</a></p>
<p>Старые фиды никуда не денутся, пока там есть хотя бы один подписчик.</p>
<p>Спасибо!</p>
<p> <img src="http://freetonik.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=3079" width="1" height="1" style="display: none;" /></p>
<p>Наши роботы считают, что вас заинтересует это:</p><ul>
<li><a href='http://freetonik.com/text/notes/apod_ru/' rel='bookmark' title='Astronomy Picture of the Day по-русски'>Astronomy Picture of the Day по-русски</a> <small>Всем известная научная организация NASA довольно активна в интернете, на...</small></li>
<li><a href='http://freetonik.com/video/translations/openmind/' rel='bookmark' title='Непредубежденность'>Непредубежденность</a> <small>На youtube есть канал молодого британца по имени Doug 'QualiaSoup'....</small></li>
<li><a href='http://freetonik.com/text/t_tauri/' rel='bookmark' title='Тау Тельца и туманность Хинда'>Тау Тельца и туманность Хинда</a> <small>Желтоватая звезда ближе к центру снимка это Тау Тельца, которая дала...</small></li>
</ul><img src="http://feeds.feedburner.com/~r/ComputerScienceStudent/~4/aQo_raXK_IM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://freetonik.com/text/notes/to_subscribers/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://freetonik.com/text/notes/to_subscribers/</feedburner:origLink></item>
		<item>
		<title>Hello, World на Silverlight и C#</title>
		<link>http://feedproxy.google.com/~r/ComputerScienceStudent/~3/6qYTnhMYKtI/</link>
		<comments>http://freetonik.com/text/hello-world-silverlight-c-sharp/#comments</comments>
		<pubDate>Wed, 25 May 2011 19:51:39 +0000</pubDate>
		<dc:creator>freetonik</dc:creator>
				<category><![CDATA[Информатика]]></category>
		<category><![CDATA[Текст]]></category>

		<guid isPermaLink="false">http://freetonik.com/?p=2433</guid>
		<description><![CDATA[Пока на работе выдалась свободная минутка, давайте я вам расскажу как создать простое приложение с помощью Microsoft .NET Silverlight и C#. Имейте ввиду, что я сам только на днях начал знакомиться с .NET, никогда раньше не работал с технологиями Microsoft, лишь использовал замечательную Visual Studio Express 2005 для С/С++. Microsoft Silverlight — это программная платформа, [...]
Наши роботы считают, что вас заинтересует это:<ul>
<li><a href='http://freetonik.com/sound/heal-this-world/' rel='bookmark' title='Heal this world'>Heal this world</a> <small>- Мое рабочее место- Fastfood?- Скринкаст- Кризисная распродажа- Доставка цветов-...</small></li>
<li><a href='http://freetonik.com/sound/mfcast-15-vse-novinki-nokia-world-x3-i-x6-n97-mini-booklet-3g-i-n900-a-takzhe-anonsy-ot-se/' rel='bookmark' title='MFcast #15. Все новинки Nokia World (X3 и X6, N97 Mini, Booklet 3G и N900), а также анонсы от SE'>MFcast #15. Все новинки Nokia World (X3 и X6, N97 Mini, Booklet 3G и N900), а также анонсы от SE</a> <small>Минувшая неделя ознаменовалась мероприятием Nokia World, на котором было представлено...</small></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>Пока на работе выдалась свободная минутка, давайте я вам расскажу как создать простое приложение с помощью Microsoft .NET Silverlight и C#. Имейте ввиду, что я сам только на днях начал знакомиться с <a href="http://youtu.be/H7QVITAWdBQ">.NET</a>, никогда раньше не работал с технологиями Microsoft, лишь использовал замечательную Visual Studio Express 2005 для С/С++.</p>
<blockquote>
<p><em><strong>Microsoft Silverlight</strong> — это программная платформа, включающая в себя <a title="Плагин" href="http://ru.wikipedia.org/wiki/%D0%9F%D0%BB%D0%B0%D0%B3%D0%B8%D0%BD">плагин</a> для <a title="Браузер" href="http://ru.wikipedia.org/wiki/%D0%91%D1%80%D0%B0%D1%83%D0%B7%D0%B5%D1%80">браузера</a>, который позволяет запускать приложения, содержащие <a title="Мультипликация (технология)" href="http://ru.wikipedia.org/wiki/%D0%9C%D1%83%D0%BB%D1%8C%D1%82%D0%B8%D0%BF%D0%BB%D0%B8%D0%BA%D0%B0%D1%86%D0%B8%D1%8F_(%D1%82%D0%B5%D1%85%D0%BD%D0%BE%D0%BB%D0%BE%D0%B3%D0%B8%D1%8F)">анимацию</a>, <a title="Векторная графика" href="http://ru.wikipedia.org/wiki/%D0%92%D0%B5%D0%BA%D1%82%D0%BE%D1%80%D0%BD%D0%B0%D1%8F_%D0%B3%D1%80%D0%B0%D1%84%D0%B8%D0%BA%D0%B0">векторную графику</a> и <a title="Мультимедиа" href="http://ru.wikipedia.org/wiki/%D0%9C%D1%83%D0%BB%D1%8C%D1%82%D0%B8%D0%BC%D0%B5%D0%B4%D0%B8%D0%B0">аудио-видео ролики</a>, что характерно для <a title="RIA" href="http://ru.wikipedia.org/wiki/RIA">RIA</a> (Rich Internet application). </em>(Википедия)</p>
</blockquote>
<p>Для сегодняшнего вводного урока нам понадобится среда для разработки. Можно воспользоваться бесплатной <a href="http://www.microsoft.com/express/Downloads/">Microsoft Visual Web Developer 2010 Express</a> или приобрести <a href="http://www.microsoft.com/visualstudio/en-us/download">Microsoft Visual Studio 2010</a>. Также вам понадобится <a href="http://go.microsoft.com/fwlink/?LinkID=169402">Silverlight 4 Tools for Visual Studio 2010</a>. Можно также попробовать визуальный редактор <a href="http://www.microsoft.com/expression/products/Blend_Overview.aspx">Microsoft Expression Blend</a>, который позволяет создавать красивые интерфейсы без написания кода. Сегодня он нам не понадобится, я буду использовать MSVS 2010.</p>
<p><span id="more-2433"></span>Запустите Visual Studio, выберите File -&gt; New -&gt; Project, и выберите Silverlight Application и Visual C#. В следующем окне выберите ASP.NET Web Application Project, Silverlight 4 и нажмите OK. Вы увидите окно, разделенное на две части: сверху визуальное представление главной страницы сайта, а внизу XAML-код, который и описывает эту страницу. <a href="http://ru.wikipedia.org/wiki/XAML">XAML </a>(читается &laquo;замл&raquo;) это основанный на XML язык разметки, с помощью которого очень удобно создавать интерфейсы и графику. Если вы работали с HTML, то принцип XAML вам покажется знакомым.</p>
<p>Если файл MainPage.xaml у вас еще не открыт, то кликните дважды по нему в Solution Explorer&#39;е, и вы увидите автоматически сгенерированный XAML-код:</p>
<pre style="color: #000000; background: #ffffff;"><span style="color: #808030;">&lt;</span>UserControl x<span style="color: #800080;">:</span>Class<span style="color: #808030;">=</span><span style="color: #800000;">"</span><span style="color: #0000e6;">SilverlightApplication8.MainPage</span><span style="color: #800000;">"</span>
    xmlns<span style="color: #808030;">=</span><span style="color: #800000;">"</span><span style="color: #0000e6;">http://schemas.microsoft.com/winfx/2006/xaml/presentation</span><span style="color: #800000;">"</span>
<span style="color: #e34adc;">    xmlns:</span>x<span style="color: #808030;">=</span><span style="color: #800000;">"</span><span style="color: #0000e6;">http://schemas.microsoft.com/winfx/2006/xaml</span><span style="color: #800000;">"</span>
<span style="color: #e34adc;">    xmlns:</span>d<span style="color: #808030;">=</span><span style="color: #800000;">"</span><span style="color: #0000e6;">http://schemas.microsoft.com/expression/blend/2008</span><span style="color: #800000;">"</span>
<span style="color: #e34adc;">    xmlns:</span>mc<span style="color: #808030;">=</span><span style="color: #800000;">"</span><span style="color: #0000e6;">http://schemas.openxmlformats.org/markup-compatibility/2006</span><span style="color: #800000;">"</span>
<span style="color: #e34adc;">    mc:</span>Ignorable<span style="color: #808030;">=</span><span style="color: #800000;">"</span><span style="color: #0000e6;">d</span><span style="color: #800000;">"</span>
<span style="color: #e34adc;">    d:</span>DesignHeight<span style="color: #808030;">=</span><span style="color: #800000;">"</span><span style="color: #0000e6;">300</span><span style="color: #800000;">"</span> d<span style="color: #800080;">:</span>DesignWidth<span style="color: #808030;">=</span><span style="color: #800000;">"</span><span style="color: #0000e6;">400</span><span style="color: #800000;">"</span><span style="color: #808030;">&gt;</span>
    <span style="color: #808030;">&lt;</span>Grid x<span style="color: #800080;">:</span>Name<span style="color: #808030;">=</span><span style="color: #800000;">"</span><span style="color: #0000e6;">LayoutRoot</span><span style="color: #800000;">"</span> Background<span style="color: #808030;">=</span><span style="color: #800000;">"</span><span style="color: #0000e6;">White</span><span style="color: #800000;">"</span><span style="color: #808030;">&gt;</span>
    <span style="color: #808030;">&lt;</span><span style="color: #808030;">/</span>Grid<span style="color: #808030;">&gt;</span>
<span style="color: #808030;">&lt;</span><span style="color: #808030;">/</span>UserControl<span style="color: #808030;">&gt;</span></pre>
<p>Давайте добавим текст и кнопку. Текстовый блок описывается тегом TextBlock:</p>
<pre style="color: #000000; background: #ffffff;"><span style="color: #a65700;">&lt;</span><span style="color: #5f5035;">TextBlock</span> <span style="color: #274796;">Text</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #0000e6;">Hello, World!</span><span style="color: #0000e6;">"</span> <span style="color: #274796;">HorizontalAlignment</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #0000e6;">Center</span><span style="color: #0000e6;">"</span> <span style="color: #a65700;">/&gt;</span></pre>
<p>А кнопка тегом Button:</p>
<pre style="color: #000000; background: #ffffff;"><span style="color: #a65700;">&lt;</span><span style="color: #5f5035;">Button</span> <span style="color: #274796;">Name</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #0000e6;">myButton</span><span style="color: #0000e6;">"</span> <span style="color: #274796;">Width</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #0000e6;">100</span><span style="color: #0000e6;">"</span> <span style="color: #274796;">Content</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #0000e6;">Click</span><span style="color: #0000e6;">"</span> <span style="color: #274796;">Click</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #0000e6;">myButtonClick</span><span style="color: #0000e6;">"</span> <span style="color: #a65700;">/&gt;</span></pre>
<p>Но если вставить эти два элемента в сгенерированную для нас сетку , то кнопка &laquo;налезет&raquo; на надпись. Чтобы не вникать в детали, давайте изменим &laquo;подложку&raquo;&nbsp;&mdash; вместо элемента Grid будем использовать StackPanel: в этом случае каждый новый добавленный элемент будет отображаться после последнего. Вот что у меня получилось:</p>
<pre style="color: #000000; background: #ffffff;"><span style="color: #a65700;">&lt;</span><span style="color: #5f5035;">UserControl</span> <span style="color: #274796;">x:Class</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #0000e6;">SilverlightApplication8.MainPage</span><span style="color: #0000e6;">"</span>
    <span style="color: #666616;">xmlns</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #666616;">http</span><span style="color: #800080;">:</span><span style="color: #800000; font-weight: bold;">//</span><span style="color: #5555dd;">schemas.microsoft.com</span><span style="color: #40015a;">/winfx/2006/xaml/presentation</span><span style="color: #0000e6;">"</span>
    <span style="color: #666616;">xmlns</span><span style="color: #800080;">:</span><span style="color: #074726;">x</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #666616;">http</span><span style="color: #800080;">:</span><span style="color: #800000; font-weight: bold;">//</span><span style="color: #5555dd;">schemas.microsoft.com</span><span style="color: #40015a;">/winfx/2006/xaml</span><span style="color: #0000e6;">"</span>
    <span style="color: #666616;">xmlns</span><span style="color: #800080;">:</span><span style="color: #074726;">d</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #666616;">http</span><span style="color: #800080;">:</span><span style="color: #800000; font-weight: bold;">//</span><span style="color: #5555dd;">schemas.microsoft.com</span><span style="color: #40015a;">/expression/blend/2008</span><span style="color: #0000e6;">"</span>
    <span style="color: #666616;">xmlns</span><span style="color: #800080;">:</span><span style="color: #074726;">mc</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #666616;">http</span><span style="color: #800080;">:</span><span style="color: #800000; font-weight: bold;">//</span><span style="color: #5555dd;">schemas.openxmlformats.org</span><span style="color: #40015a;">/markup-compatibility/2006</span><span style="color: #0000e6;">"</span>
    <span style="color: #274796;">mc:Ignorable</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #0000e6;">d</span><span style="color: #0000e6;">"</span>
    <span style="color: #274796;">d:DesignHeight</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #0000e6;">300</span><span style="color: #0000e6;">"</span> <span style="color: #274796;">d:DesignWidth</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #0000e6;">400</span><span style="color: #0000e6;">"</span><span style="color: #a65700;">&gt;</span>
    <span style="color: #a65700;">&lt;</span><span style="color: #5f5035;">StackPanel</span> <span style="color: #274796;">x:Name</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #0000e6;">LayoutRoot</span><span style="color: #0000e6;">"</span> <span style="color: #274796;">Background</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #0000e6;">White</span><span style="color: #0000e6;">"</span><span style="color: #a65700;">&gt;</span>
        <span style="color: #a65700;">&lt;</span><span style="color: #5f5035;">TextBlock</span> <span style="color: #274796;">Text</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #0000e6;">Hello, World!</span><span style="color: #0000e6;">"</span> <span style="color: #274796;">HorizontalAlignment</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #0000e6;">Center</span><span style="color: #0000e6;">"</span> <span style="color: #a65700;">/&gt;</span>
        <span style="color: #a65700;">&lt;</span><span style="color: #5f5035;">Button</span> <span style="color: #274796;">Name</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #0000e6;">myButton</span><span style="color: #0000e6;">"</span> <span style="color: #274796;">Width</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #0000e6;">100</span><span style="color: #0000e6;">"</span> <span style="color: #274796;">Content</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #0000e6;">Click</span><span style="color: #0000e6;">"</span> <span style="color: #274796;">Click</span><span style="color: #808030;">=</span><span style="color: #0000e6;">"</span><span style="color: #0000e6;">myButtonClick</span><span style="color: #0000e6;">"</span> <span style="color: #a65700;">/&gt;</span>
    <span style="color: #a65700;">&lt;/</span><span style="color: #5f5035;">StackPanel</span><span style="color: #a65700;">&gt;</span>
<span style="color: #a65700;">&lt;/</span><span style="color: #5f5035;">UserControl</span><span style="color: #a65700;">&gt;</span></pre>
<p>Наш волшебный интерфейс готов, теперь пора заняться логикой. Прелесть .NET в том, что вы можете использовать практически любой популярный язык программирования, или даже несколько разных языков в одном проекте. Все они будут без проблем передавать друг другу информацию, будут иметь общие или совместимые типы данных и т.д.</p>
<p>Кликните по треугольнику рядом с MainPage.xaml в Solution Explorer&#39;е и откройте появившийся там файл MainPage.xaml.cs (в случае, если вы, как и я, выбрали C# в качестве основного языка при первом запуске Visual Studio). В этом файле находится <a href="http://sergeyteplyakov.blogspot.com/2011/03/blog-post.html">частичный класс</a> MainPage с конструктором с одной единственной функцией InitializeComponent (). Мы хотим добавить функцию, которая будет выполняться при нажатии на кнопку. Добавим в класс следующий код:</p>
<pre style="color: #000000; background: #ffffff;"><span style="color: #800000; font-weight: bold;">private</span> <span style="color: #800000; font-weight: bold;">void</span> myButtonClick<span style="color: #808030;">(</span><span style="color: #800000; font-weight: bold;">object</span> sender<span style="color: #808030;">,</span> RoutedEventArgs e<span style="color: #808030;">)</span>
<span style="color: #800080;">{</span>
   myButton<span style="color: #808030;">.</span>Content <span style="color: #808030;">=</span> <span style="color: #800000;">"</span><span style="color: #0000e6;">Goodbye, World!</span><span style="color: #800000;">"</span><span style="color: #800080;">;</span>
<span style="color: #800080;">}</span></pre>
<p>Для сравнения и полноты примера, вот идентичный код на Visual Basic:</p>
<pre style="color: #000000; background: #ffffff;"><span style="color: #800000; font-weight: bold;">Private</span> <span style="color: #800000; font-weight: bold;">Sub</span> myButtonClick<span style="color: #808030;">(</span><span style="color: #800000; font-weight: bold;">ByVal</span> sender <span style="color: #800000; font-weight: bold;">As</span> <span style="color: #800000; font-weight: bold;">Object</span><span style="color: #808030;">,</span> <span style="color: #800000; font-weight: bold;">ByVal</span> e <span style="color: #800000; font-weight: bold;">As</span> RoutedEventArgs<span style="color: #808030;">)</span>
    myButton<span style="color: #008c00;">.</span>Content <span style="color: #808030;">=</span> <span style="color: #0000e6;">"Goodbye, World!"</span>
<span style="color: #800000; font-weight: bold;">End</span> <span style="color: #800000; font-weight: bold;">Sub</span></pre>
<p>Возможно, ваша версия Visual Studio автоматически создала пустой метод в тот момент, когда вы указали его название при описании кнопки в XAML, но моя MSVS2010 не пошла мне на встречу.</p>
<p>XML-подход для описания интерфейса это очень удобно и наглядно, но всегда нужно иметь ввиду, какие параметры следует указать в теге. Например, если бы мы хотели сделать что-то с текстовым блоком по нажатию на кнопку, то, не внося изменений в XAML, ничего бы не вышло: у текстблока нет имени, непонятно, как к нему обратиться из кода. Но это не самое страшное. <a href="http://weblogs.asp.net/okloeten/archive/2007/12/22/5489157.aspx">Некоторые</a> разработчики не любят XAML по весьма веским причинам.</p>
<p>&nbsp;</p>
<h2>Заключение</h2>
<p>Честно говоря, впечатления от .NET и Windows Presentation Framework двоякие: с одной стороны, это по-настоящему мощная система, позволяющая создавать практически любые приложения для платформы windows (включая windows 7 phone) и интернета. Не нужно больше работать напрямую с Win32 API или с ужасным COM. Команда программистов могут работать над одним проектом, каждый со своим любимым языком, не заботясь о совместимости и передаче данных. С другой стороны, как и другие технологии Майкрософт, все это выглядит чудовищно неэлегантно: куча составных частей, множество &laquo;слоев&raquo;, множество переизобретенных велосипедов.</p>
<p>Месяца через два у меня будет чуточку опыта реальной разработки c Silverlight, посмотрим, что из этого выйдет.</p>
<p>&nbsp;</p>
<p><span style="font-size: 15px; font-weight: bold;">Продукты Майкрософт</span></p>
<ul>
<li><a title="Microsoft Visual Studio" href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio">Microsoft Visual Studio</a> все, что нужно, для разработки .net и WPF, включает визуальный редактор</li>
<li><a title="Microsoft Visual Studio Express" href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio_Express">Microsoft Visual Studio Express</a> &laquo;легкая&raquo; версия, включает редактор WPF</li>
<li><a title="Microsoft Expression Blend" href="http://en.wikipedia.org/wiki/Microsoft_Expression_Blend">Microsoft Expression Blend</a> мощный инструмент для визуального дизайна XAML</li>
<li><a title="Microsoft Expression Design" href="http://en.wikipedia.org/wiki/Microsoft_Expression_Design">Microsoft Expression Design</a> позволяет экспортировать векторные и растровые изображения в XAML</li>
<li><a title="XAMLPad" href="http://en.wikipedia.org/wiki/XAMLPad">XAMLPad</a> простой удобный редактор XAML</li>
</ul>
<h3>Продукты других компаний</h3>
<ul>
<li><a rel="nofollow" href="http://www.wpf-graphics.com/">WPF Graphics Tools</a></li>
<li>XamlPadX v4 <a rel="nofollow" href="http://blogs.msdn.com/llobo/archive/tags/XamlPadX/default.aspx">blog</a>.</li>
<li><a rel="nofollow" href="http://icsharpcode.net/OpenSource/SD">SharpDevelop</a></li>
<li><a rel="nofollow" href="http://www.danetsoft.com/">Danet Studio</a></li>
<li><a rel="nofollow" href="http://www.kaxaml.com/">Kaxaml</a></li>
<li><a rel="nofollow" href="http://www.ultimatexaml.com/">Ultimate XAML for Softimage</a></li>
<li><a rel="nofollow" href="http://xam3d.com/Products/ZAM3D/DefaultPDC.asp">ZAM 3D</a></li>
<li><a rel="nofollow" href="http://www.3dpaintbrush.com/content/xaml.aspx">3DPaintBrush</a></li>
<li><a rel="nofollow" href="http://www.sybase.com/products/modelingdevelopment/powerbuilder">PowerBuilder .NET</a></li>
<li><a rel="nofollow" href="http://snoopwpf.codeplex.com/">Snoop</a></li>
</ul>
<p>&nbsp;</p>
<p> <img src="http://freetonik.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=2433" width="1" height="1" style="display: none;" /></p>
<p>Наши роботы считают, что вас заинтересует это:</p><ul>
<li><a href='http://freetonik.com/sound/heal-this-world/' rel='bookmark' title='Heal this world'>Heal this world</a> <small>- Мое рабочее место- Fastfood?- Скринкаст- Кризисная распродажа- Доставка цветов-...</small></li>
<li><a href='http://freetonik.com/sound/mfcast-15-vse-novinki-nokia-world-x3-i-x6-n97-mini-booklet-3g-i-n900-a-takzhe-anonsy-ot-se/' rel='bookmark' title='MFcast #15. Все новинки Nokia World (X3 и X6, N97 Mini, Booklet 3G и N900), а также анонсы от SE'>MFcast #15. Все новинки Nokia World (X3 и X6, N97 Mini, Booklet 3G и N900), а также анонсы от SE</a> <small>Минувшая неделя ознаменовалась мероприятием Nokia World, на котором было представлено...</small></li>
</ul><img src="http://feeds.feedburner.com/~r/ComputerScienceStudent/~4/6qYTnhMYKtI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://freetonik.com/text/hello-world-silverlight-c-sharp/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://freetonik.com/text/hello-world-silverlight-c-sharp/</feedburner:origLink></item>
		<item>
		<title>Прозрачные и проверяемые выборы</title>
		<link>http://feedproxy.google.com/~r/ComputerScienceStudent/~3/hl5UX5ky69U/</link>
		<comments>http://freetonik.com/video/translations/e-vote/#comments</comments>
		<pubDate>Wed, 16 Feb 2011 01:06:37 +0000</pubDate>
		<dc:creator>freetonik</dc:creator>
				<category><![CDATA[Видео]]></category>
		<category><![CDATA[Информатика]]></category>
		<category><![CDATA[Переводы]]></category>
		<category><![CDATA[Текст]]></category>

		<guid isPermaLink="false">http://freetonik.com/?p=2073</guid>
		<description><![CDATA[Сегодня я хочу рассказать вам о том, как можно сделать процедуру голосования лучше и надежнее. Во-первых, советую посмотреть речь Дэвида Бисмарка на TED или здесь в моей озвучке (перевод Андрея Новика): Как это работает? Я расскажу о системе электронного голосования на примере системы Бена Адида, которая отличается от системы Дэвида Бисмарка, но в конечном итоге обладает всеми теми же важными для людей свойствами. Оба варианта — лишь [...]
Наши роботы искали похожие записи, но не нашли :(]]></description>
			<content:encoded><![CDATA[<p>Сегодня я хочу рассказать вам о том, как можно сделать процедуру голосования лучше и надежнее. Во-первых, советую <a href="http://www.ted.com/talks/david_bismark_e_voting_without_fraud.html">посмотреть</a> речь <a href="http://evoting.bismark.se/verifiable-electronic-voting/">Дэвида Бисмарка</a> на TED или здесь в моей озвучке (перевод Андрея Новика):</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="560" height="450" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/wmj0qjTLakc?fs=1&amp;hl=en_US" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="560" height="450" src="http://www.youtube.com/v/wmj0qjTLakc?fs=1&amp;hl=en_US" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<p><strong>Как это работает?</strong> <span id="more-2073"></span></p>
<p>Я расскажу о системе электронного голосования на примере системы <a href="http://adida.net/">Бена Адида</a>, которая отличается от системы Дэвида Бисмарка, но в конечном итоге обладает всеми теми же важными для людей свойствами. Оба варианта — лишь примеры, подобных систем можно придумать огромное количество.</p>
<p>Проблема современных систем голосования (как классических, так и компьютеризованных): человек не может удостовериться в том, что его голос учтен. Объясняется это, обычно, принципом анонимности голосования, но это сугубо техническая причина. Если хорошенько подумать, то можно найти способ проверки собственного голоса без нарушения принятых норм. Хорошее сравнение — банкоматы. Мы все ими пользуемся и доверяем, при этом наши деньги остаются в сохранности, и, что самое главное, мы всегда можем проверить каждую операцию (на сайте или в банке). Хорошая система электронных выборов должна быть проверяема на всех стадиях.</p>
<p>Для такой системы были определены следующие требования:</p>
<ul>
<li>система публичных/частных ключей: голосующие зашифровывают голос, кандидаты — расшифровывают</li>
<li>легко-генерируемые случайные ключи: для каждого голосующего генерируется случайный ключ, так что голоса за одного кандидата от разных людей не являются идентичными в зашифрованном виде</li>
<li>гомоморфизм</li>
</ul>
<p>Про последний пункт мы поговорим чуть позже.</p>
<p>В такой системе можно использовать любой алгоритм шифрования, подобный RSA, который основан на использовании пары публичный-частный ключ. В этом примере мы будем использовать схему <a href="http://ru.wikipedia.org/wiki/%D0%A1%D1%85%D0%B5%D0%BC%D0%B0_%D0%AD%D0%BB%D1%8C-%D0%93%D0%B0%D0%BC%D0%B0%D0%BB%D1%8F">Эль-Гамаля</a>.</p>
<ol>
<li>Каждый кандидат генерирует и публикует следующую информацию:
<ul>
<li>Большое <a href="http://ru.wikipedia.org/wiki/%D0%9F%D1%80%D0%BE%D1%81%D1%82%D0%BE%D0%B5_%D1%87%D0%B8%D1%81%D0%BB%D0%BE">простое</a> число <strong>p</strong></li>
<li>Число <strong>a<sub>b</sub></strong> (по <a href="http://ru.wikipedia.org/wiki/%D0%A1%D1%80%D0%B0%D0%B2%D0%BD%D0%B5%D0%BD%D0%B8%D0%B5_%D0%BF%D0%BE_%D0%BC%D0%BE%D0%B4%D1%83%D0%BB%D1%8E_%D0%BD%D0%B0%D1%82%D1%83%D1%80%D0%B0%D0%BB%D1%8C%D0%BD%D0%BE%D0%B3%D0%BE_%D1%87%D0%B8%D1%81%D0%BB%D0%B0">модулю</a> p)</li>
<li>Публичный ключ <strong>y<sub>b</sub></strong> (y<sub>b</sub> = a<sup>x<sub>b</sub></sup> mod p)
<ul>
<li>Частный ключ x<sub>b</sub> (случайное число от 1 до p-1; <span style="text-decoration: underline;">не публикуется!</span>)</li>
</ul>
</li>
</ul>
</li>
<li>Голосующий должен зашифровать свой голос — некое сообщение m (-1&lt;m&lt;p). Каждый голосующий имеет свои публичный и частный ключи —<strong> y<sub>a</sub></strong> и <strong>x<sub>a</sub></strong>, соответственно.
<ul>
<li>Формируется общий ключ SK (shared key): <strong>SK</strong> = (y<sub>b</sub>)<sup>x<sub>a</sub></sup> = (y<sub>a</sub>)<sup>x<sub>b</sub></sup></li>
<li>Голос это пара (c1, c2) = (ya, m*SK) mod p</li>
</ul>
</li>
<li>Только тот кандидат, за которого был отдан голос, сможет его расшифровать:
<ul>
<li>(m * SK * SK<sup>-1</sup>) mod p = (m * a<sup>x<sub>a</sub>x<sub>b </sub></sup>* a<sup>-x<sub>a</sub>x<sub>b</sub></sup>) mod p = m</li>
</ul>
</li>
</ol>
<p>Вот простой пример:</p>
<p>1. p = 13, a = 2, y<sub>b</sub> = 7, x<sub>b</sub> = 11 (7 = 2<sup>11</sup> mod p).<br />
2. m = 7, (c1, c2) = (2<sup>6</sup>, 7*(2<sup>11</sup>)<sup>6</sup>) mod 13 = (12, 6)<br />
3. (7*2<sup>66</sup> * 2<sup>-66</sup>) mod 13 = 7 = m.</p>
<p>Теперь немного о последнем пункте списка требований: <a href="http://ru.wikipedia.org/wiki/%D0%93%D0%BE%D0%BC%D0%BE%D0%BC%D0%BE%D1%80%D1%84%D0%B8%D0%B7%D0%BC">гомоморфизм</a> (в нашем случае — гомоморфизм групп). Если вы знакомы с теорией групп из математики, то должны вспомнить это свойство. Если коротко: группа это математический объект, «замкнутый» относительно некоторой операции. Например, целые числа относительно сложения — группа, так как взяв два любые элемента из этой группы (два целых числа) и применив операцию сложения (сложив эти числа) мы получим другое целое число — другой элемент той же группы. Это и есть «замкнутость». Такую группу обозначили бы как (Z, +).</p>
<p>Пусть у нас есть две такие группы: (G, *) и (H, ·). Гомоморфизмом будет являться функция h: G → H, если h (u*v) = h (u) · h (v). В нашем случае функцией является зашифровка:</p>
<p>enc (u·v) = enc (u) ·enc (v).</p>
<p>Это свойство системы необходимо для обеспечения возможности подсчета голосов публикой без нарушения анонимности голосования. В нашем случае гомоморфизм таков:</p>
<p>enc (m1) · enc (m2) = (y<sub>x<sub>1</sub></sub>, m1 · SK1) · (y<sub>x<sub>2</sub></sub>, m · SK2) mod p = (y<sub>x<sub>1</sub></sub>, · (m1 · m2)(SK1 · SK2)) mod p = enc (m1 · m2).</p>
<p><strong>Как происходит голосование?</strong></p>
<ol>
<li>Избиратель проверяет бюллетень. Используется принцип <a href="http://ru.wikipedia.org/wiki/%D0%94%D0%BE%D0%BA%D0%B0%D0%B7%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D1%81%D1%82%D0%B2%D0%BE_%D1%81_%D0%BD%D1%83%D0%BB%D0%B5%D0%B2%D1%8B%D0%BC_%D1%80%D0%B0%D0%B7%D0%B3%D0%BB%D0%B0%D1%88%D0%B5%D0%BD%D0%B8%D0%B5%D0%BC">доказательства с нулевым разглашением</a>. Голосующий выбирает два любых бюллетеня, соскребает случайные числа (публичный ключ) с одного из них (как в лотерее) и сканирует двумерный штрих-код чтобы удостовериться, что указанный там порядок кандидатов соответствует зашифрованной информации. Этот бюллетень перестает быть действительным, а избиратель использует второй.</li>
<li>Избиратель делает выбор.</li>
<li>Отрывает левую часть.</li>
<li>Уничтожает публичный ключ.</li>
<li>Сканирует бюллетень, уходит домой.</li>
</ol>
<p>Отсканированные бюллетени публикуются на вебсайте. Проголосовавший может проверить, был ли его голос учтен, и если был — все ли прошло без ошибок.</p>
<p><strong>Испытания</strong></p>
<p>Данная система была опробована на выборах в локальные органы самоуправления в университетах MIT, Harvard, Unversite Catholique de Louvain (25000 избирателей), University of Ottawa. 3 ноября 2009 года эта система применялась на выборах в Takoma Park, Maryland, USA.</p>
<p><strong>К прочтению</strong></p>
<p>[1] Ben Adida. <a href="http://groups.csail.mit.edu/cis/theses/adida-phd.pdf">Advances in Cryptographic Voting Systems</a>. MIT. (2006).<br />
[2] Avi Rubin. <a href="http://avirubin.com/vote/op-ed.html">An Election Day clouded by doubt</a>, October 2004.<br />
[3] Blakley, G. R. Safeguarding cryptographic keys. Proceedings of the National Computer Conference 48: 313-317, (1979).<br />
[4] Josh D. Cohen and Michael J. Fischer. A robust and verifiable cryptographically secure election scheme. In FOCS, pages 372–382. IEEE Computer Society, 1985.<br />
[5] S. Poblig and M. Hellman, An improved algorithm for computing logarithms over GF (p) and its cryptographic significance, IEEE, Transaction on Information Theory It-24:106-110, (1978).<br />
[6] T. El Gamal. A Public Key Cryptosystem and a Signature Scheme Based on Discrete Logarithms. IEEE Transactions on Information Theory, 31, pg. 469-472. (1985)<br />
[7] Презентация Jimin Park, Applied Cryptography class, Carleton University, Feb. 2011</p>
<p> <img src="http://freetonik.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=2073" width="1" height="1" style="display: none;" /></p>
<p>Наши роботы искали похожие записи, но не нашли :(</p><img src="http://feeds.feedburner.com/~r/ComputerScienceStudent/~4/hl5UX5ky69U" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://freetonik.com/video/translations/e-vote/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://freetonik.com/video/translations/e-vote/</feedburner:origLink></item>
		<item>
		<title>Затраты и сложность распределенных вычислений</title>
		<link>http://feedproxy.google.com/~r/ComputerScienceStudent/~3/uyAyT3d5jM4/</link>
		<comments>http://freetonik.com/text/distributed_computing_complexity/#comments</comments>
		<pubDate>Wed, 26 Jan 2011 03:30:21 +0000</pubDate>
		<dc:creator>freetonik</dc:creator>
				<category><![CDATA[Информатика]]></category>
		<category><![CDATA[Текст]]></category>

		<guid isPermaLink="false">http://freetonik.com/?p=1887</guid>
		<description><![CDATA[Среда, которую мы описали, является достаточно абстрактной. Это общая модель для многих типов систем, производительность которых зависит от множества факторов. 

Эффективность протокола должна отражать реальные затраты, которые требуются системе. То есть нам нужна абстрактная мера вычислительных и прочих затрат, которая будет иметь смысл в реальном мире. 
Наши роботы считают, что вас заинтересует это:<ul>
<li><a href='http://freetonik.com/text/uskoreniya-parallelnyx-vychislenij/' rel='bookmark' title='Ускорения параллельных вычислений'>Ускорения параллельных вычислений</a> <small>Главной целью создания и разроботки многочисленных типов параллельных машин, о...</small></li>
<li><a href='http://freetonik.com/text/distributed_computing_intro/' rel='bookmark' title='Введение в распределенные вычисления'>Введение в распределенные вычисления</a> <small>Современные системы давно перестали быть похожими на фантазии ученых и...</small></li>
<li><a href='http://freetonik.com/text/uslovie-i-budushhee-vremya/' rel='bookmark' title='Условие и будущее время'>Условие и будущее время</a> <small>В русском языке можно поставить условие в будущем времени: Если...</small></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>Среда, которую мы описали, является достаточно абстрактной. Это общая модель для многих типов систем, производительность которых зависит от множества факторов.</p>
<p>Эффективность протокола должна отражать реальные затраты, которые требуются системе. То есть нам нужна абстрактная мера вычислительных и прочих затрат, которая будет иметь смысл в реальном мире.<br />
<span id="more-1887"></span>Мы будем использовать две меры: <strong>затраты коммуникации</strong> и <strong>время</strong>, необходимое для завершения вычисления. Это позволит смотреть на систему с точки зрения самой системы (сколько трафика будет сгенерировано для решения задачи? насколько занята будет система?) и с точки зрения пользователя (сколько придется ждать окончания вычисления?).</p>
<p><strong>4.1 Количество сетевой деятельности</strong></p>
<p>Передача сообщения через исходящий порт (то есть исходящему соседу) это самая простая сетевая деятельность в системе. Стоит заметить, что отправка сообщения, которое не достигнет пункта назначения из-за ошибки, все еще считается сетевой деятельностью. Получается, мерой сетевой деятельности может выступать количество сообщений M, так же называемое <strong>затратой на сообщения</strong> (message cost).</p>
<p>Другое важное значение это <strong>нагрузка на узел</strong> L<sub>node</sub> = M / |V|, или количество сообщений на каждый узел, и нагрузка на соединение L<sub>link</sub> = M / |E|, или количество сообщений на каждое соединение (ребро графа).</p>
<p>Сообщение это набор битов; некоторые протоколы используют очень короткие сообщения (например, сигнальные биты), некоторые – очень длинные (например, графические файлы). Значит, для более точного подсчета эффективности системы нужно брать в расчет количество битов. Это значение назыавют <strong>битовой сложностью</strong> (bit complexity) протокола.</p>
<p><strong>4.2 Время</strong></p>
<p>Важным фактором оценки протокола является время, требуемое ему для корректного завершения. В нашей абстрактной модели время считается не в секундах или минутах, а в формальных отрезках (юнитах).<br />
В общей модели нет предположений касательно времени, кроме аксиомы 3.1.1: “При отсутствии повреждений и ошибок, задержки коммуникации конечны.” В целом, длина задержки непредсказуема и мы не может с точностью вычислить требуемое протоколу время.</p>
<p>Однако, мы можем найти значение времени, если сделаем еще несколько предположений. Время, найденное таким способом, называют <strong>идеальным</strong> или идеальной временной сложностью <strong>T</strong>. При “еденичных коммуникационных задержках” и “синхронизированных часах” любое сообщение передается и обрабатывается за один промежуток времени. В таком случае, общее время можно подсчитать зная битовую сложность.</p>
<p>Другой показатель времени называют <strong>казуальным</strong>, T<sub>causal</sub>: это промежуток времени, требуемый для передачи самой длинной цепи связанных сообщений. Казуальное время очень редко используется для анализа протоколов.</p>
<p>Пример: вещание</p>
<p>Представьте себе распределенную систему, в которой одна сущность обладает информацией, неизвестной другим, и задачей является передача (вещание) этой информации всем сущностям.</p>
<p>Это проблема называется <strong>вещанием</strong> (broadcasting) и является частью класса проблем, связанных с распространением информации. Чтобы решить эту проблему, нужно разработать набор правил, следуя которым все сущности спустя конечный отрезок времени будут обладать информацией. Решение должно работать вне зависимости от того, какой из узлов обладает информацией в начале.</p>
<p>Пусть E будет набор сущностей, а G коммуникационной топологией системы. Для упрощения, примем несколько дополнительных допущений:</p>
<p>1. Двусторонние соединения. (используем ненаправленный граф; см. рис. 3.2.1).<br />
2. Полная надежность</p>
<p>Стоит заметить, что если граф G не соединен, то существуют узлы, до которых невозможно “достучаться”, в случае чего проблема становится нерешаемой. Поэтому, нужно принять следующее допущение:</p>
<p>3. Соединение (<em>connectivity</em>). Коммуникационная топология G является соединенной.</p>
<p>Из определения самой задачи вещания следует, что только один узел обладает информацией в начале, значит:</p>
<p>4. Уникальный инициатор</p>
<p>Простая стратегия, которой мы будем следовать, звучит следующим образом:</p>
<p><em>“если сущность обладает информацией, то она делится ею с соседями”</em></p>
<p>Чтобы создать набор правил, реализующий эту стратегию, необходимо определить набор статусных значений S. Из определения понятно, что нужно отличать узел-инициатор от всех остальных узлов. Поэтому, {initiator, idle} ⊆ S. Процесс может быть начат только инициатором (узлом, статус которого является “initiator”). Обозначим информацию, которую нужно передать, за I. Так выглядит набор правил B (x) (однинаков для всех сущностей):</p>
<p>1. initiator × ι → {<strong>send</strong>(I) to N (x)}<br />
2. idle × Receiving (I) → {<strong>Process</strong>(I); <strong>send</strong>(I) to N (x)}<br />
3. initiator × Receiving (I) → <strong>nil</strong><br />
4. idle × ι → <strong>nil</strong></p>
<p>где ι означает спонтанный импульс, а nil означает бездействие. В рамках принятых допущений, каждый узел в конечном итоге получит информацию. Не смотря на это, протокол обладает существенной проблемой:</p>
<p><em>активность, сгенерированная протоколом, никогда не закончится</em></p>
<p>Представьте себе простую систему, состояющую из трех узлов, соединенных между собой (см. рис. 4.2.1). Пусть x будет инициатором, y и z будут idle, и все сообщения передаются с одинаковой скоростью; тогда y и z будут посылать сообщения друг другу до бесконечности.</p>
<p><img src="http://hexlet.ru/uploads/images/00/00/01/2011/01/25/1328fb.png" alt="" /><br />
Рис 4.2.1.</p>
<p>Для обхода этой проблемы каждая сущность должна отправлять сообщение соседям только один раз: когда она сама получает информацию. Этого можно добиться добавлением нового статуса “done”, который будет означать, что узел выполнил свою работу. Тогда S={initiator, idle, done}.</p>
<p>1. initiator × ι → {<strong>send</strong>(I)  <strong>to</strong> N (x); <strong>become</strong> done}<br />
2. idle × Receiving (I) → {<strong>Process</strong>(I); <strong>become</strong> done; <strong>send</strong>(I) to N (x)}<br />
3. initiator × Receiving (I) → <strong>nil</strong><br />
4. idle × ι →<strong>nil</strong><br />
5. done × Receiving (I) → <strong>nil</strong><br />
6. done × ι→<strong>nil</strong></p>
<p>В этом случае сетевая деятельность протокола прекращается после конечного промежутка времени, или, другими словами, за конечное время каждый узел получает статус “done”.</p>
<p>Имейте ввиду, что это не означает одновременность завершения всеми узлами. На самом деле, узел может завершить свою деятельность до того, как другой начал. Есть разница между локальным завершением и глобальным завершением.</p>
<p>Также заметьте. что в этом протоколе никто никогда не знает, случилось ли глобальное завершение.</p>
<p>Протокол является корректным, поэтому теперь давайте подсчитаем затраты и сложность.</p>
<p>Первое: подсчитаем количество переданных сообщений. Каждая сущность (хоть инициатор, хоть нет) отправляет сообщение каждому соседу. Следовательно, сумма переданных сообщений:</p>
<p><img src="http://hexlet.ru/uploads/images/00/00/01/2011/01/25/8409bd.png" alt="" /></p>
<p>На самом деле мы может уменьшить затраты. В текущей версии протокола, когда idle-узел получает сообщение, он пересылает информацию всем соседям, включая того, от которого информация была получена. Естественно, это лишнее сообщение. Вторая аксиома (о локальной ориентации узлов) позволяет сущностям отличать своих соседей, то есть сущность знает, от кого из соседей поступило сообщение, и не будет посылать информацию по этому порту. Финальная версия протокола с небольшими изменениями выглядит так:</p>
<p><strong>Protocol Flooding</strong><br />
1. initiator × ι → {<strong>send</strong>(I) to N (x); <strong>become</strong> done}<br />
2. idle × Receiving (I) → {<strong>Process</strong>(I); <strong>become</strong> done; <strong>send</strong>(I) to N (x) -sender}<br />
3. initiator × Receiving (I) → <strong>nil</strong><br />
4. idle × ι → <strong>nil</strong><br />
5. done × Receiving (I) → <strong>nil</strong><br />
6. done × ι → <strong>nil</strong></p>
<p>Этот алгоритм называется Flooding (затопление), потому что система “затапливается” сообщениями в процессе. Это базовый алгоритмический инструмент для распределенных вычислений.</p>
<p>Теперь мы знаем, что количество сообщений меньше 2m:</p>
<p>M[flooding] = 2m — n + 1.</p>
<p>Теперь посмотрим на затраты времени. Пусть d (x,y) будет обозначать дистанцию (длину кратчайшего пути) между узлами x и y в графе G. Естественно, что сообщение, переданное инициатором, должно достичь всех узлов, включая самый отдаленный. Итак, если x это инициатор, то идеальное время будет r (x) = Max {d (x, y): y ∈ E}; это значение также называют радиусом узла x. Другими словами, общее время зависит от топологии сети и его невозможно определить заранее. Однако, мы можем определить идеальное время в худшем из возможных случаев.</p>
<p>Так как любая сущность может быть инициатором, идеальное время выполнения в худшем случае будет d (G) = Max (r (x): x ∈ E}, что является диаметром графа G. Получается, идеальное время выполнения будет как максимум диаметром G:</p>
<p>T[flooding] ≤ d (G).</p>
<p> <img src="http://freetonik.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1887" width="1" height="1" style="display: none;" /></p>
<p>Наши роботы считают, что вас заинтересует это:</p><ul>
<li><a href='http://freetonik.com/text/uskoreniya-parallelnyx-vychislenij/' rel='bookmark' title='Ускорения параллельных вычислений'>Ускорения параллельных вычислений</a> <small>Главной целью создания и разроботки многочисленных типов параллельных машин, о...</small></li>
<li><a href='http://freetonik.com/text/distributed_computing_intro/' rel='bookmark' title='Введение в распределенные вычисления'>Введение в распределенные вычисления</a> <small>Современные системы давно перестали быть похожими на фантазии ученых и...</small></li>
<li><a href='http://freetonik.com/text/uslovie-i-budushhee-vremya/' rel='bookmark' title='Условие и будущее время'>Условие и будущее время</a> <small>В русском языке можно поставить условие в будущем времени: Если...</small></li>
</ul><img src="http://feeds.feedburner.com/~r/ComputerScienceStudent/~4/uyAyT3d5jM4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://freetonik.com/text/distributed_computing_complexity/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://freetonik.com/text/distributed_computing_complexity/</feedburner:origLink></item>
		<item>
		<title>Введение в распределенные вычисления</title>
		<link>http://feedproxy.google.com/~r/ComputerScienceStudent/~3/UyG0rfm8rmU/</link>
		<comments>http://freetonik.com/text/distributed_computing_intro/#comments</comments>
		<pubDate>Thu, 06 Jan 2011 02:47:48 +0000</pubDate>
		<dc:creator>freetonik</dc:creator>
				<category><![CDATA[Информатика]]></category>
		<category><![CDATA[Текст]]></category>

		<guid isPermaLink="false">http://freetonik.com/?p=1874</guid>
		<description><![CDATA[Современные системы давно перестали быть похожими на фантазии ученых и писателей прошлых столетий. Многие из них были правы относительно общих принципов и возможностей, но мало кто мог представить возможности современных суперкомпьютеров и распределенных систем, и еще меньше кто мог представить массивы данных, с которыми такие системы работают. 
Наши роботы считают, что вас заинтересует это:<ul>
<li><a href='http://freetonik.com/text/parallel_computing_intro/' rel='bookmark' title='Введение в параллельные вычисления'>Введение в параллельные вычисления</a> <small>Параллельной машиной называют, грубо говоря, набор процессоров, памяти и некоторые...</small></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>Современные системы давно перестали быть похожими на фантазии ученых и писателей прошлых столетий. Многие из них были правы относительно общих принципов и возможностей, но мало кто мог представить возможности современных суперкомпьютеров и распределенных систем, и еще меньше кто мог представить массивы данных, с которыми такие системы работают.</p>
<p>На сегодняшний день самыми перспективными считаются две основные технологии, которые имеют много общего: параллельные и распределенные вычисления. Про параллельные вычисления на нашем сайте есть отдельный <a rel="nofollow" href="http://hexlet.ru/blog/parallel/">блог</a>, из которого я возьму одну цитату:<span id="more-1874"></span></p>
<blockquote>
<p>В параллельных вычислениях участвует оборудование, находящееся, как правило, в одном физическом месте, они тесно соединены между собой и все параметры их работы известны программисту. В распределенных вычислениях нет тесной постоянной связи между узлами, соответственно названию, они распределены по некоторой территории и параметры работы этой системы динамичны и не всегда известны.</p>
</blockquote>
<p>Сегодня мы познакомимся с общими определениями и понятиями распределенных сетей.</p>
<blockquote>
<p>Это выдержки из моих конспектов, основанные на курсе Distributed Computing профессора <a rel="nofollow" href="http://people.scs.carleton.ca/~santoro/">Никола Санторо</a>, а также его книги <a rel="nofollow" href="http://people.scs.carleton.ca/~santoro/DADA.html">Design and Analysis of Distributed Algorithms</a>.</p>
</blockquote>
<p><strong>Глава 1. Вселенная.</strong></p>
<p>Мир или вселенная, в рамках которой мы будем работать, называется средой распределенных вычислений. Она состоит из конечного числа сущностей E (или узлов), которые обмениваются сообщениями между собой для достижения общей цели, например, найти решение проблемы, ответить на запрос пользователя (извне) или другой сущности (изнутри). В этой главе мы рассмотрим свойства различных объектов и процессов нашей вселенной.</p>
<p><strong>1.1 Сущности (узлы)</strong></p>
<p>Сущностью может выступать любой процесс, процессор, компьютер, сетевой свитч, агент какого-либо рода и т.д. Каждая сущность (узел) обладает собственной локальной памятью, всключающий набор регистров, значения которых устанавливаются заранее. Примером регистра может быть status (x) — текущий статус узла x. Следующий набор стандартных допущений применим к любой сущности x ∈ E:</p>
<p>хранение и обработка данных в локальной памяти<br />
передача сообщений<br />
изменение значения локальных часов<br />
сброс локальных часов<br />
изменение значения статусного регистра</p>
<p><strong>1.2 Внешние события</strong></p>
<p>Поведение узла x ∈ E зависит от внешних событий или просто событий (event). При отсутствии события сущность ничего не делает. Возможны три типа внешних событий:</p>
<p>прибытие сообщения<br />
срабатывание “будильника” локальных часов<br />
спонтанный импульс</p>
<p>Первые два типа являются локальными в рамках вселенной, но третье событие является сигналом извне. Простой пример, объясняющий внешнее спонтанное событие, это сеть банкоматов. В такой сети каждый банкомат является узлом, а клиент, решивший снять деньги с карточки, является источником спонтанного импульса. Замкнутая сеть банкоматов (вселенная) не могла знать, когда произойдет такое событие, но должна быть готова среагировать на него. Люди в шутку называют такие импульсы “рукой бога”, так как с точки зрения среды распределенных вычислений неизвестно, кто и когда сделает импульс и родится ли у него в последствии сын-плотник.</p>
<p><strong>1.3 Действия</strong></p>
<p>При возникновении внешнего события e, сущность x ∈ E среагирует на это конечным набором конечных (завершаемых за конечных промежуток времени) операций, который называют действием (action).</p>
<p>Действие должно быть неделимым, то есть если оно начнется, то не остановится, пока не завершится.</p>
<p><strong>1.4 Поведение</strong></p>
<p>Простая формула, описывающая механизм поведения сущностей выглядит так:</p>
<p>Status × Event → Action</p>
<p>и называется правилом. Правило описывает какое действие должен произвести узел при событии в зависимости от текущего состояния. В примере с банкоматом можно придумать правило: если текущий статус счета является “заморожен”, то при событии “снять денег” нужно уведомить клиента о статусе и не выдать никаких денег.</p>
<p>Поведение сущности x выражается набором правил B (x). Этот набор должен быть полным и однозначным, то есть для каждого возможного события e и статуса s должно существовать одно и только одно правило в B (x) для (s, e). Этот набор правил также называют протоколом или распределенным алгоритмом сущности x.</p>
<p>Поведение всей среды определяется поведением каждого узла и называется коллективным поведением B (E) набора сущностей E.</p>
<p>B (E) = {B (x): x ∈ E}.</p>
<p><strong>1.5 Однородное поведение</strong></p>
<p>Коллективное поведение является однородным (гомогенным), если каждая сущность обладает одним и тем же поведением. То есть, ∀x, y ∈ E, B (x) = B (y). Интересный и очень важный факт:</p>
<p><em>Свойство 1.5.1 Каждое коллективное поведение можно превратить в однородное.</em></p>
<p>Иными словами, в системе, где каждый узел обладает собственным набором правил (поведением), можно создать новый единый набор правил для всех сущностей, и поведение всей системы не изменится. Любой знакомый с программированием человек уже догадался, что такое достигается с помощью набора конструкций if...then.</p>
<p>Пример. Представьте себе сеть, сотоящую из одного сервера и нескольких рабочих станций. Конечно, они (сервер и станция) обладают разным поведением, но объединить их в одно правило можно с помощью логической конструкции:</p>
<p>s × e → { if my role = workstation then Aworkstation else Aserver endif }.</p>
<p><strong>Глава 2. Связь</strong></p>
<p>В распределенной среде сущности общаются между собой отправкой и принятием сообщений. Сообщением называют любой конечный набор битов. Обмен сообщениями не обязательно проходит напрямую; возможно, сообщение проходит через другие сущности. Обозначим набор сущностей, которым узел x может отправить сообщение напрямую, как Nout (x) ⊆ E, а называть их будем для простоты “исходящими соседями”. Также, обозначим Nin (x) ⊆ E как набор всех узлов, которые могут отправить сообщение узлу x напрямую, и назовем их “входящими соседями”.</p>
<p>Соседство описывается графом G=(V, E), где V это набор узлов, а E ⊆ V × V это набор рёбер. Направленный граф G описывает коммуникационную топологию среды. Мы будем обозначать количество узлов, рёбер и диаметр графа n (G), m (G) и d (G), соответственно. При отсутствии неоднозначности, мы будем использовать только символы n, m и d.</p>
<p><strong>Глава 3. Аксиомы и ограничения</strong></p>
<p>Определение среды распределенных вычислений имеет две базовые аксиомы в своем фундаменте: одна связана с задержками связи, другая с локальной ориентацией сущностей. Любые другие предположения (например, свойства сети, или общее знание, которым обладает каждый узел) называют ограничениями.</p>
<p><strong>3.1 Аксиомы</strong></p>
<p>Передача сообщений состоит из нескольких этапов: подготовка, пересылка, получение, обработка. В реальном мире время, которое требуется для каждого этапа, невозможно предсказать с абсолютной точностью. Например, время передачи зависит от текущей нагрузки на сеть. Сумма всех задержек передачи сообщений называется задержкой коммуникации.</p>
<p><em>Аксиома 3.1.1 При отсутствии повреждений и ошибок, задержки коммуникации конечны.</em></p>
<p>Другими словами, если система не сломалась, то сообщение, отправленное исходящему соседу узла будет доставлено в целостности и обработано за конечный промежуток времени.</p>
<p>Вторая аксиома гласит, что каждый узел имеет возможность различать своих соседей.</p>
<p><em>Аксиома 3.1.2. Каждая сущность может различать своих входящих соседей. Каждая сущность может различать своих исходящих соседей.</em></p>
<p>Иными словами, каждая сущность может определить, кому именно из своих исходящих соседей отправить сообщение, и от какого именно входящего соседа сообщение пришло.</p>
<p>Нужно помнить, что это знание локально для узла.</p>
<p><strong>3.2 Ограничения</strong></p>
<p><strong> </strong></p>
<p><strong>3.2.1 Коммуникационные ограничения</strong></p>
<p>Очередь (queuing). Соединение (x, y) может быть представлено как канал связи между узлами x и y. Различные ограничение описывают механизм работы такого канала, например, очереди FIFO (first-in-first-out) описываются следующим ограничением:</p>
<p>Последовательность сообщений (message ordering): при отсутствии повреждений и ошибок, сообщения, посланные одному и тому же исходящему соседу будут доставлены в таком же порядке, в котором они были посланы.</p>
<p>Двухсторонняя коммуникация. ∀x ∈ E, Nin (x) = Nout (x). Иными словами, если (x, y) ∈ E, то (y, x) ∈ E.</p>
<p>Нужно помнить, что (x, y) не обязательно то же самое соединение, что (y, x). Если мы имеем дело с двусторонними соединениями (рёбрами), то (x, y)=(y, x).</p>
<p><img src="http://hexlet.ru/uploads/images/00/00/01/2011/01/05/7c4c73.png" alt="" /><br />
<strong>Рис. 3.2.1.</strong> В случае двусторонних соединений используется ненаправленный граф.</p>
<p><strong>Ошибки. </strong>Несколько ограничений касаются ошибок или повреждений системы. Вот некоторые примеры:</p>
<p><em>Гарантированная доставка (guaranteed delivery). Любое сообщение, будучи отправленным, будет доставлено без повреждений.</em></p>
<p>С таким ограничением нам не нужно принимать во внимание возможные ошибки при передаче.</p>
<p><em>Частичная надежность (partial reliability). В будущем никаких ошибок не случится.</em></p>
<p>С таким ограничением нам не нужно заботиться о том, как система может повредиться. Заметьте, что ограничение говорит лишь о будущем, то есть ошибки или повреждения могли произойти в прошлом.</p>
<p><em>Полная надежность (total reliability). Ошибок не было и не будет.</em></p>
<p>Естественно, протоколы, разработанные в учетом этих ограничений, не могут гарантированно выполняться при появлении ошибок.</p>
<p><strong>Топологические ограничения.</strong> В общих случаях, если узел не соединен со всеми другими узлами напрямую, он все еще имеет возможность связываться с ними, используя другие узлы как ретрансляторы. Одно простое топологическое ограничение говорит, что любой узел может отправить сообщение любому другому узлу.</p>
<p><em>Соединение (connectivity). Коммуникационная топология G является соединенной.</em></p>
<p><strong>Временные ограничения.</strong> Общая модель не имеет никаких предположений касательно времени, кроме того, что все задержки конечны.</p>
<p><em>Ограниченные коммуникационные задержки.</em> Существует такая константа Δ, что при отсутствии ошибок или повреждений, задержка в передаче сообщения на любом соединении не превышает Δ.</p>
<p><em>Единичные коммуникационные задержки.</em> При отсутствии ошибок или повреждений задержка в передаче сообщения на любом соединении равняется одной еденице времени.</p>
<p><em>Синхронизированные часы.</em> Все локальные часы увеличивают свое значение на еденицу времени одновременно, и интервал времени между удачными увеличениями значения является константой.</p>
<p> <img src="http://freetonik.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1874" width="1" height="1" style="display: none;" /></p>
<p>Наши роботы считают, что вас заинтересует это:</p><ul>
<li><a href='http://freetonik.com/text/parallel_computing_intro/' rel='bookmark' title='Введение в параллельные вычисления'>Введение в параллельные вычисления</a> <small>Параллельной машиной называют, грубо говоря, набор процессоров, памяти и некоторые...</small></li>
</ul><img src="http://feeds.feedburner.com/~r/ComputerScienceStudent/~4/UyG0rfm8rmU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://freetonik.com/text/distributed_computing_intro/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://freetonik.com/text/distributed_computing_intro/</feedburner:origLink></item>
		<item>
		<title>Software Engineering Notes</title>
		<link>http://feedproxy.google.com/~r/ComputerScienceStudent/~3/d_ioepvq8d4/</link>
		<comments>http://freetonik.com/text/software-engineering-notes/#comments</comments>
		<pubDate>Tue, 07 Dec 2010 00:12:35 +0000</pubDate>
		<dc:creator>freetonik</dc:creator>
				<category><![CDATA[Информатика]]></category>
		<category><![CDATA[Текст]]></category>
		<category><![CDATA[book review]]></category>
		<category><![CDATA[computer science]]></category>
		<category><![CDATA[software engineering]]></category>

		<guid isPermaLink="false">http://freetonik.com/?p=44</guid>
		<description><![CDATA[Это набор конспектов по курсу Software Engineering, основанный на книге Software Engineering, 8th edition, Ian Sommerville, Pearson Education, 2006.
Наши роботы искали похожие записи, но не нашли :(]]></description>
			<content:encoded><![CDATA[<blockquote>
<p><em>Это набор конспектов по курсу Software Engineering, основанный на книге Software Engineering, 8th edition, Ian Sommerville, Pearson Education, 2006.</em></p>
</blockquote>
<p><strong>Chapter 1</strong></p>
<p>What is software? Computer program with a set of documentation (system design and structure and user documentation), configuration data and all additional sources of information directly related to the program</p>
<p>There are 2 types of software product:</p>
<ol>
<li><strong>Generic product</strong>.      Stand-alone systems, sold on open market to everyone. Examples – desktop      operating system, office packs or graphical editors.</li>
<li><strong>Customized</strong> (bespoke)      products. Developed for particular customers with special features.      Examples – special systems for traffic control or airbus flight      operations.</li>
</ol>
<p><span id="more-44"></span></p>
<p>From developers’ stand of view, one of the main differences of those types is that for customized case the specifications for a software product is done mostly by the organization which buying it. For generic product development, specifications are created by the same development organization.</p>
<p>Nowadays, there is no straight line between those types as there was several years ago.</p>
<p>Software engineers, as any other engineers, make things work by applying theories, methods and tools (created, mostly, by computer scientists, but when it comes to practical problems, there’s often need to change the solution and develop your own way, still, based on some theory). Software engineering is not all about coding programs, there are much more problems to solve during the work on project, for example project management, scheduling of work, testing and choosing the right way to go.</p>
<p>Software engineering is concerned with all aspects of the development and evolution of complex systems. System engineering is concerned with hardware development, policy and process design.</p>
<p>Software process consists of four fundamental activities:</p>
<p>1.      Software specification where engineers or/and customers define what the product should do and how should it operate.</p>
<p>2.      Software development is designing and actual coding.</p>
<p>3.      Software validation is generally testing. It is important to check if the system is designed and implemented correctly.</p>
<p>4.      Software evolution is modifying the system according to new needs of customer (s).</p>
<p>Different types of software need different development process.</p>
<p>Software process model is a simplified description of a software process that presents one view of a process. And again, choice of a view depends on the system developing, sometimes it is useful to apply a workflow model, sometimes, for example – a role/action model.</p>
<p>Most software process models are based on one of three general models or paradigms of software development.</p>
<p>1.      The waterfall approach. In this case the development process and all activities are divided into phases such as requirement specification, software design, implementation, testing etc. Development goes phase-by-phase.</p>
<p>2.      Iterative development. An initial system is rapidly developed from very abstract specifications. Of course, it can be reimplemented according to new, probably more detailed specifications.</p>
<p>3.      Component-based software engineering (CBSE). The development process is done assuming some parts of the system is already exist, so the process focuses on integrating parts together rather than developing everything from scratch.</p>
<p>A software engineering method is a structured approach to software development whose aim is to facilitate the production of high-quality software in a cost-effective way. If not talking about history, today most common method is based on UML (Unified Modeling Language), which was created from different approaches from the past.</p>
<p>As any other thing related to software engineering, methods may vary depending on different situations.</p>
<p>For a software engineer it is always important to make sure the product is good, and there are different tools to analyze that. Overall, good piece of software should meet these attributes:</p>
<p>1.      Maintainability. Software should be developed in such way that it can be changed according to new specifications and needs of customers. This aspect is directly related to software evolution.</p>
<p>2.      Dependability. It includes reliability, security and safety. Good dependable system should make minimum (or no) economic damage in case of failure.</p>
<p>3.      Efficiency. Software should be efficient and should not waste system resources.</p>
<p>4.      Usability. With all hidden for an end-user requirements, first thing customer think of when they start using the program is how easy to do it and how good the documentation is. Software should be usable without too much effort from user. Therefore, developers should always keep in mind the type of an user system building for.</p>
<p><em>My thoughts</em></p>
<p><em> </em></p>
<p><em>First chapter is introduction and most of things look familiar for me, especially after attending COMP3104 lectures. I think about software development as very complex process, which technically never ends because always has something to make better or add more features. While facing big problems and developing large systems, the necessity of every point of development become stronger. As such, I understand why maintainability is so important for both developers and customers. </em></p>
<p><em> Software engineering is a lot of responsibility: to other engineers, to customers and society around the product. It is a big challenge – applying theoretical methods on practice. </em></p>
<p><em> </em></p>
<p><strong> </strong></p>
<p><strong> </strong></p>
<p><strong>Chapter 2</strong></p>
<p>The word ‘system’ is widely used, but the useful working definition of a system when we talk about particular parts and particular goals sounds like:</p>
<p>A system is a purposeful collection of interrelated components that work together to achieve some objective.</p>
<p>No matter how complicated and large any system might be, we can still apply this definition. Now if we talk about software systems, there are two categories:</p>
<p>1. <strong>Technical computer-based</strong>. This type of system includes hardware and software but not procedures and processes. Most of simple desktop software, OS etc. are examples of technical computer-based systems. Main point is: using this software has a purpose, but software itself does not know it, knowledge of this purpose is not part of a system.</p>
<p>2. <strong>Socio-technical systems</strong> includes hardware or/and software (actually, we can say it includes technical systems), but most important part it includes knowledge of how the system should be used and operated in order to achieve final objective. This kind of system includes predefined operational processes, people (to operate a system). Carleton University is a socio-technical system, because all of resources (library, buildings, computer labs, all physical things as well as general “knowledge”) are operated and used by certain people (profs, staff and students).</p>
<p>Socio-technical system is different from technical not only because of people. The book outlines three main distinctions:</p>
<p>&mdash; Parts of socio-technical system have properties that are properties of the system as a whole rather than associated with those parts particularly.</p>
<p>&mdash; Such system may be nondeterministic, which means that the same input don’t always produce the same output. System works and operated by human, who doesn’t always react the same way as some software.</p>
<p>&mdash; The way system works and achieves its objectives does not just depend on the system itself. It also depends on the stability of these objectives.</p>
<p>We should always keep in mind that the main principle of system is one of the main problems – system cannot be fully functional if even one part of it does not work. Interdependency causes this statement. This statement must be applied not only when we look at system and its parts, but also when we look broader – at different systems within another system. For example, we have a software program which is a system itself and consists of different components. They all work properly and system designed correctly, but if we actually plug this program into operating system (which is another system), and that OS operates all the hardware (which is also a system), we cannot be sure that the program will work as it suppose to. As a software engineer, person should always think wide.</p>
<p>One another source of possible problems is the ability of the system to involve and to be changed to accommodate modified system engineering requirements. It is very common when during such change software failure happens, even though software was working properly before an attempt to change it. Therefore, this kind of software failure is actually not software failure, but rather some mistake or series of mistakes during designing the system, so that modifying gone wrong.</p>
<p>There is a complex relationship between system components and this very fact says that the system is more than just a box with some functional stuff in it. Parts and relationships have different emergent properties and those properties are properties of the whole system. Often those properties can only be derived from sub-system interrelationships and are “invisible” when we look at particular system component. There are two types of emergent properties:</p>
<p>1. <strong>Functional</strong>. Everything related to how the system works. For example, functional requirement of a phone is to be able to make and receive calls.</p>
<p>2. <strong>Non-functional</strong>. Everything related to behaviour and operating environment. For that same phone non-functional emergent requirement may be “to be easy to use”.</p>
<p>Emergent properties are often very complex and it is hard to describe them. It is even harder to analyze some properties. For example, reliability. First of all, we should know that reliability is such a property which cannot be seen and analyzed without detailed analyze of every part of a system. Even if 99 of 100 parts of a system are super reliable and solid-stone-never-fail-parts, one little piece may cause failure of a whole system.</p>
<p>There are three related influences on the overall reliability of a system:</p>
<p>1. Hardware reliability</p>
<p>2. Software reliability</p>
<p>3. Operator reliability</p>
<p>This is very obvious, because any problem may come from one of three main parts of a socio-technical system.</p>
<p>System engineers are not just concerned with software but also with hardware and human interaction. They must think of services that system provides and how useful and easy to use different parts may be.</p>
<p>System requirements specify what the system must do and its properties. An important part of the requirements definition is to establish a set of overall objectives that the system should meet. A fundamental difficulty in establishing system requirements is that the problems are so complex, that there are so many related entities and there is no definitive problem specification. The true nature of a problem emerges only when a solution is created.</p>
<p>System design is concerned with how the system functionality is to be provided by the components of the system. Process of designing a system is fairy complicated and consists of different steps or phases. It starts with organizing requirements into related groups, then – identifying sub-systems that can (alone or interacting with each other) meet those requirements and cover all the groups of them. Then developers should actually assign requirements to sub-systems. Then, every sub-system’s functionality should be specified. It is also useful to specify relationships between sub-systems. When this step is done and all sub-systems are at least in some close to working state, software engineer should define sub-system interfaces. When this is done, it is possible to continue to develop these sub-systems in parallel.</p>
<p>Designing is one of the first and most important steps of product development. For almost all systems, there are many possible design decisions that meet the requirements. In perfect situation, developers choose design as they thing is the best for given requirements, but pretty often another facts affect this choice – customer’s desire, federal laws etc.</p>
<p>Next big step in developing is system modelling. Model of a system is an abstract representation of all parts and mechanisms of system. Usually model of a system is developed and shown as graphical image. There might be different scales of a model so it is possible to look at the system from different points of view and different scale.</p>
<p>Sub-system development is basically process of creating building blocks for a project. In fact, those sub-systems are not always developed from scratch for purposes of this particular project. Quite often developers can use sub-systems of different projects or even integrate some side-developed components. Sub-systems are usually developed in parallel. If the system developing process goes step-by-step, one component after another, it becomes very hard and expensive to make modifications. And there is (almost) always modifications to be done during development.</p>
<p>Systems integration is a process of putting all independently developed sub-systems into one. Integrating all the components at a time sounds like good way, but on practice it is not always possible, because development of different sub-systems takes different time. Also, adding sub-systems one-by-one or at least by blocks or sections reduces number of errors.</p>
<p>At finally, software evolution. This process is more abstract and doesn’t not directly related to first development, but still is very important. While developing software systems, changes can come even during designing and implementation, and of course more changes will come after some period of use. There may be just bug-fixing changes or adding new requirements. Changes should not be just technically motivated, different points of view should be taken to analyze process, such as business and technical prospective.</p>
<p>System decommissioning means taking the system out of service after the end of its useful operation lifetime. Hardware can be recycled, software can be reused for some different purposes or just be ‘forgotten’. Anyway, for a software, decommissioning is not such a big problem.</p>
<p>Software development might be such a complex process, so it is impossible to create a product alone or create it within small group of developers. In a complex projects organisational processes are important.</p>
<p><em>My thoughts:</em></p>
<p><em> After this chapter I can see the difference between two general types of systems when it comes to software or hardware, also now I understand why different objectives demand different sort of system. Any technical operation (mostly cyclic, or with no need to analyze situation in real-time, especially when it comes to something moral-related) can be done easily by technical systems, but there’s no such machine that can do anything without human. Socio-technical systems come along when there’s an objective and work on something to achieve that objective needs several decisions to make, and quite often those decisions can be made only by human. </em></p>
<p><em> Socio-technical systems seems more flexible and useful in many cases, still, there are a lot of disadvantages of this system. Human resource is not the best when it comes to errors (mistakes) and supporting socio-technical system in general is much more expensive. </em></p>
<p><em> Steps of developing model are familiar to me in general, but there are some new details we didn’t face while developing model for our Monopoly game, because even though we work almost as people work during large project, we didn’t face the same problems as, for example, Mac OS developers do. That’s why I found this chapter useful.</em></p>
<p><strong>Chapter 3</strong></p>
<p>Errors, mistakes and fails in software are common, usually a fail cause inconvenience but no serious long-term damages or something as serious as huge money loss or even health damage. However, in some systems failure can have very big and serious consequences. This type of system is called <strong>critical system</strong>. There are three main types of critical systems:</p>
<ol>
<li>Safety-critical systems. Fails in this system may result      in injury, death or environmental damage. For example, space shuttle with      astronauts on board. If something goes wrong with navigation system,      people may die.</li>
<li>Mission-critical systems. Fails in this system may result      in failure of some goal-directed activity and main objective of the system      may not be reached. The same space-shuttle is an example of mission-critical      system, because even without astronauts taken in count, the whole mission      might be failed.</li>
<li>Business-critical systems. Fails may cause loss of money      for customers using this system. Bank money management system is an      example.</li>
</ol>
<p>The most important emergent property of a critical system is dependability. Systems that are unreliable and unsafe are often rejected by users. Possible failure cost may be so big users refuse to use the system. A system that may easily loose the information is very unsafe too, because data is often the most expensive part of organization.</p>
<p>As a summary of all seriousness of critical systems and software fails we can say that only trusted methods and techniques must be used for development.</p>
<p>Dependability of a system is the main component in “calculating” trustworthiness. Trustworthiness is a degree of user confidence that the system will operate exactly as it suppose to. Of course, calculating is not the right word, because such a value cannot be expressed numerically, but some abstract terms like “not dependable”, “very dependable” are used.</p>
<p>Trustworthiness and usefulness are not the same and not even directly related. Program may be very useful and easy to work with in many areas, but it may crash every time user hits more than three buttons at a time. Or vice versa, system may work as a solid stone, but all it does is printing random numbers.</p>
<p>Four principal dimensions to system dependability are: Availability, Reliability, Safety and Security.</p>
<p>All of these may be decomposed into another, for example security includes integrity (ensuring that data is not damaged) and confidentiality. Reliability includes correctness, precision and timeliness. All of them are interrelated.</p>
<p>Some other system properties may be considered under the heading of dependability:</p>
<p>1.      Repairability. How easy and fast system can be restored after fail. Unfortunately, most of today’s software systems use a lot of third-party components and therefore system’s repairabilty does not depend on system only</p>
<p>2.      Maintainability. How east and fast system can be changed to adopt new requirements and rules.</p>
<p>3.      Survivability. Ability of a system to continue work and deliver services after fail or attack.</p>
<p>4.      Error tolerance. Ability of a system to avoid input errors</p>
<p>System availability and reliability are closely related to each other. Both of them can be expressed as numerical probabilities – availability is the probability that system will be up and running to deliver services; reliability is the probability that the system will work correctly.</p>
<p>More precise definitions are:</p>
<p>&mdash;           Reliability – the probability of failure-free operation over a specified time in a given environment for a specific purpose.</p>
<p>&mdash;           Availability – the probability that a system, at a point in time, will be operational and able to deliver the requested services.</p>
<p>By definition, the environment for a system is quite important and has to be taken into account. Measuring the system in one environment doesn’t mean it will work with same results in different environment.</p>
<p>Three complementary approaches that are used to improve the reliability of a system are:</p>
<p>1.      Fault avoidance. Development techniques used to minimise the possibility of mistakes before they result in system faults.</p>
<p>2.      Fault detection and removal. Identifying and solving system problems before the system is used.</p>
<p>3.      Fault tolerance. Techniques used to ensure that some system errors doesn’t not result in failure.</p>
<p>Safety-critical systems are systems where it is essential that system operation is always safe. The system should never damage people or system’s environment even in case of failure. There are two classes of safety-critical systems:</p>
<ol>
<li>Primary safety-critical software. This is software which      is used as a controller in a system.</li>
<li>Secondary safety-critical software. This is software that      can be indirectly result in injury.</li>
</ol>
<p>There is no 100% safe and reliable system, so various methods are used to assure safety. What we can do is to ensure that accidents do not occur or the consequences of an accident are minimal. Three complementary ways of doing that are:</p>
<ol>
<li>Hazard avoidance. System is designed in such way so that      hazards are avoided, for example cutting machine can be ran only by      pressing two buttons at the same time, so operator’s both hands are busy      (still, he has plenty of other stuff that can be cut )))</li>
<li>Hazard detection and removal. System should have some      components responsible for analyzing possible hazards and removing them,      for example speed limiter for cars.</li>
<li>Damage limitation. If damage happened, system should      make the result minimum. Cars always have airbags.</li>
</ol>
<p>Security is a system attribute that reflects the ability of the system to protect itself from external attacks that may be accidental or deliberate. Nowadays, security is very serious issue, especially for Internet or network-related systems. Mistakes in designing security system can cause system faults because of possible attacks. Three types of damage that may be caused through external attack are:</p>
<p>1.      Denial of service. The system may be forced into a state when it doesn’t deliver services anymore and (from user’s point of view) doesn’t work at all.</p>
<p>2.      Corruption of programs or data. The system itself may be corrupted under attack, but also the data system operates and has access to.</p>
<p>3.      Disclosure of confidential information. The information system operates and has access to may be exposed to unauthorised people.</p>
<p><em>My thoughts:</em></p>
<p><em>We all got used to software failures and it became so common for us that programs are unstable and you can never be sure. I think this is bad thing, really bad, that’s why working on this chapter I was thinking of some “perfect future” where all software-based systems somehow managed to work perfectly fine, but actually, I don’t think this will ever happen. As you were saying on one lecture about mission-critical systems, the same software bug as there was 20 years ago came out and caused big damage. Even though computers are machines, they do mistakes, because they were created by human, and human indeed do mistakes.</em></p>
<p><strong>Chapter 4</strong></p>
<p>Software process is a set of activities that leads to the production of a software product. There’s no, of course, ideal software process and every project needs different. Software processes are complex and, like all other intellectual and creative processes, rely on people making decisions and judgements.</p>
<p>Still, there are some common parts for almost any software process:</p>
<ol>
<li>Software specification. Defining the functionality of      the software and constraints on its operation.</li>
<li>Software design and implementation.</li>
<li>Software validation. Testing the product to ensure it      meets all requirements.</li>
<li>Software evolution.</li>
</ol>
<p>Software processes can be improved by process standardisation where diversity in software processes across an organisation is reduced.</p>
<p>Three process models covered in this chapter are:</p>
<p>1.      Waterfall model. Dividing fundamental processes (specification, implementation etc) into phases.</p>
<p>2.      Evolutionary development. An initial system is rapidly developed from abstract specifications.</p>
<p>3.      Component-based software engineering. Development process is focused on integrating reusable components into a system rather than developing them from scratch.</p>
<p>In practice, of course, it is often impossible to work all the way trough within only one model. For example, sub-systems may be developed using different model than main system. Often, models are combined.</p>
<p>Principal stages of the waterfall model are:</p>
<p>1.      Requirements analysis and definition.</p>
<p>2.      System and software design</p>
<p>3.      Implementation and unit testing</p>
<p>4.      Integration and system testing</p>
<p>5.      Operation and maintenance.</p>
<p>The main principle is that the next phase cannot begin before previous is done. In practice, these stages may overlap and feed information to each other. During design, problems with requirements are identified. During coding design problems are found and so on.</p>
<p>During the final life cycle phase (operation and maintenance) the software put into use. Errors and omissions in the original software requirements are discovered. The system must evolve to be useful.</p>
<p>The advantages of waterfall model are that documentation is produced at each phase and that it fits with other engineering process models. Its major problem is its flexible partitioning of the project into distinct stages. Commitments must be made at early stage in the process, which makes it difficult to respond to changing customer requirements.</p>
<p>There are two fundamental types of evolutionary development:</p>
<ol>
<li>Exploratory development where the objective of the      process is to work with the customer to explore their requirements and      deliver a final system. The development starts with the parts of the      system that are understood. The system evolves by adding new features      proposed by the customer.</li>
<li>Throwaway prototyping where the objective of the evolutionary      development process is to understand the customer’s requirements and hence      develop a better requirements definition for the system.</li>
</ol>
<p>This approach is often more effective than the waterfall approach in producing systems that meet the immediate needs of customers. However, there are two major problems with this model:</p>
<ul>
<li>The process is not visible. Managers need regular      deliverables to measure progress. If systems are developed quickly, it is      not cost-effective to produce documents that reflect every version of the      system.</li>
<li>Systems are often poorly structured.</li>
</ul>
<p>These problems are acute when the project is large, for the small systems (up to 500,000 lines of code) the author of the book thinks that the evolutionary process it the best choice.</p>
<p>In the majority of systems there is some software reuse. Pretty often this happens informally, when people working on the project know of designs or code which is similar to that required. The look at these, modify them and reuse in current project. It is often essential for rapid system development.</p>
<p>Stages for software process using component-based model are:</p>
<ol>
<li>Component analysis</li>
<li>Requirements modification</li>
<li>System design with reuse</li>
<li>Development and integration.</li>
</ol>
<p>Change is inevitable in all large software projects. The system requirements change as the business procuring the system responds to external pressures. Management priorities change; new technologies become available, design and implementation change. This means that the software process is not a one-off process; rather, the process activities are regularly repeated as the system is reworked in response to change requests. There are two process models that have been designed to support process iteration:</p>
<p>1.      Incremental delivery. The whole process of software development are broken down into a series of increments that are each developed in a turn. This process is something between the waterfall model and evolutionary model. Customers identify the services to be provided by the system. They also identify which of the services are most important for them and which are less. After basic development, customers take early delivery of part of the system and then they can experiment with the system. This helps them clarify their requirements for later increments. New increments are developed and combined with the existing parts, so the system is getting better and more functional after each increment.</p>
<p>2.      Spiral development. The development of the system spirals outwards from an initial outline through to the final developed system. This process may be represented as a spiral. Each loop represents a phase of the software process. Thus, the innermost loop might be concerned with system feasibility. Next loop – with requirement definition, etc.</p>
<p><em> </em></p>
<p><em>My thoughts:</em></p>
<p><em>I really think mixing different software process models can give better results than using just one model. Even for such a small project as our Monopoly game, we started as a waterfall model: defining requirements and use-cases first, then – designing the system, components and signals. When coding takes place, I think it might be better to switch the process to something between waterfall model and evolutionary development. This sounds like incremental delivery, where customers are us, developers </em><em>JWe develop some part of a system, make it executable and testable and test this part as if we were end-customers. This kind of work will reduce some errors, which can be seen only while executing and testing. </em></p>
<p><strong>Chapter 5</strong></p>
<p>Software project management is an essential part of software engineering. Good management cannot guarantee project success, however, bad management usually result in project failure. Software managers do the same kind of job as other engineering project managers. However, software engineering is different from other types of engineering. Some differences are:</p>
<ol>
<li>The product is intangible. The software cannot be seen or      touched; it is not physical at all.</li>
<li>There are no standard software processes. There is no      specified process for particular task and quite often it is hard and takes      time to manage which software development process is more suitable for the      project.</li>
<li>Large software projects are often “one-off” projects.      Large software projects are often very different in some ways from      previous project. Therefore, even managers with large experience may find      it difficult to anticipate problems.</li>
</ol>
<p>Main activities of a software manager are:</p>
<ul>
<li>Proposal writing</li>
<li>Project planning and scheduling</li>
<li>Project cost</li>
<li>Project monitoring and reviews</li>
<li>Personnel selection and evaluation</li>
<li>Report writing and presentations</li>
</ul>
<p>Writing proposal to win a contract to carry out the work is important possible stage. It usually includes cost and schedule estimates and justifies why the project contract should be awarded to a particular organisation or team.</p>
<p>Project planning is concerned with identifying the activities, milestones and deliverables produced by a project.</p>
<p>The manager should keep track of the progress of the project and compare actual and planned progress and costs. Informal monitoring can often predict potential problems by revealing difficulties as they occur.</p>
<p>During a project, it is normal to have several reviews.</p>
<p>Project managers usually have to select people to work on their project. Ideally, skilled staff with appropriate experience will be available to work on the project, by in reality managers (in most cases) have to settle for a less-than-ideal project team. The reasons for this are:</p>
<ol>
<li>The project budget may not cover the use of highly paid      staff.</li>
<li>Staff with the appropriate experience may not be      available either within an organisation or externally.</li>
<li>The organisation may wish to develop the skills of its      employees, so inexperienced staff may be assigned to the project to learn      and to gain experience.</li>
</ol>
<p><strong>Chapter 6</strong></p>
<p>Requirements for the system are the descriptions of the services provided by the system and its operational constraints. The process of analyzing, documenting and checking services needed is called Requirements Engineering.</p>
<p>Requirement is quite important and widely used word in software engineering, but still it not used in industry in consistent way. In some cases requirement is some high-level, abstract statement of a service that system must provide. In some other cases – it is detailed definition of a system function.</p>
<p>There exist two general types of requirements while developing a system:</p>
<p>1.      <strong>User requirements</strong> are statements in natural language, of what services the system is expected to provide and the constraints under which it must operate. They should be concerned on functional and non-functional requirements from user’s point of view, describing in detail aspect of a system that are important for customer. While working on user requirements, it’s important to avoid everything related to system design.</p>
<p>2.      <strong>System requirements</strong> is a set of system functions descriptions in detail. Also, requirement document should be precise and define exactly what it is to be implemented. System requirements for software engineers are starting point for developing system, because they describe the way system should be designed and implemented. How user requirements should be provided.</p>
<p>Software system requirements are often classified as functional, non-functional or domain requirements.</p>
<p><strong>Functional requirements</strong> describe what system should do, how it should react to different inputs and systems behavior at different situations. Statements of functional requirement should tell exactly what should happen in which cases, still, these requirements keep pretty abstract.</p>
<p><strong>Non-functional requirements</strong> are constraints on the services of functions offered by the system. They include such aspects of development as timing, development process and standards. Non-functional requirements can be related to emergent properties such as reliability, response time etc. They are rarely associated with particular system features and more often used to describe more general aspects of a system, for example “user friendly graphical user interface”.</p>
<p><strong>Domain requirements</strong> come from the application domain of the system and that reflect characteristics of that domain. They come more from the system itself rather than from specific need of system users. Domain requirements are important because they often reflect fundamentals of the application domain.</p>
<p><strong>Chapter 7</strong></p>
<p>The goal of the requirement engineering is to create and maintain a system requirement document. The overall process includes four high-level sub-processes. These are concerned with assessing whether the system is useful to the business (feasibility study); discovering requirements (elicitation and analysis); converting these requirements into some standard form (specification); and checking that the requirements actually define the system that the customer wants (validation).</p>
<p>Feasibility study produces feasibility report and leads to next process – requirements elicitation and analysis. Then, system models and requirements specification produced, next – user and system requirements and requirements validation processes come, and as result of all these sub-processes (they also rely on each other during requirement engineering process) the requirement document developed.</p>
<p>Feasibility studies answers number of questions:</p>
<p>1.      Does the system contribute to the overall objectives of the organisation?</p>
<p>2.      Can the system be implemented using current technology and within given cost and schedule constraints?</p>
<p>3.      Can the system be integrated with other systems which are already in place?</p>
<p>In a feasibility study in it often that you consult information sources such as the managers of the departments where the system will be used, software engineers who are familiar with the type of system that is proposed, technology experts and end-users of the system.</p>
<p>In the next stage, the requirements elicitation and analysis, software engineers work with customers and end-users of a system to find out about application domain, what services the system should provide, the general performance of the system. When these general requirements are ready, developers should check if the requirements actually define the system that the customer wants. These checks include:</p>
<ul>
<li>Validity checks. Further thought and analysis may identify additional or different functions that are required.</li>
<li>Consistency checks. Requirements should not conflict.</li>
<li>Completeness checks. Requirement document should include requirements, which define al functions and constraints intended by the system user.</li>
<li>Realism checks. Using knowledge of existing technology, the requirements should be checked to ensure that they could actually be implemented.</li>
<li>Verifiability. To reduce the potential for dispute between customer and contractor, system requirements should always be written so that they are verifiable.</li>
</ul>
<p>The requirements for large project are always changing. Often, because the problem cannot be fully defined, the software requirements are bound to be incomplete. Requirement management is the process of understanding and controlling changes to system requirements. This includes keeping track of individual requirements and maintaining links between dependent requirements, establishing a formal process for making change proposals and linking these to system requirements.</p>
<p><em>My thoughts:</em></p>
<p><em>Requirements are, I believe, the most known part of this book to me. We discussed requirements quite a lot, and I see why they are important. During requirement engineering process (if I can call it that fancy way :) ) for our Monopoly game, we faced problems, discussed in this chapter. For example, some sort of consistency checks were done after Iteration 1 and we found some requirements conflicts and overlap one another. Completeness check showed that we still missing two requirements, not really important and basic ones, but still, if we were starting implementation, at some point we would come back and think again. </em></p>
<p><em>We didn’t do any feasibility studies, except for maybe one question – “Can the system be implemented using current technology and within given cost and schedule constraints?”. Given cost is a term mark and schedule was set, so we didn’t really deep thinking and analysing. For large and real project, this is much more serious questions. </em></p>
<p><strong>Chapter 8</strong></p>
<p>User requirement should be written in natural language to be understandable by non-technical people, but during developing process requirements may be expressed in more technical way. One widely used technique is to document the system specification as a set of system models. Models are graphical representation of what system should do and how it should operate, that’s why models are often more easy to understand than even detailed natural language description. Models are also an important bridge between the analysis and design process.</p>
<p>At an early stage of requirement engineering developers should define the boundaries of the system. This involves working with system stakeholders to distinguish what is the system and what is the system’s environment. These decisions should be made early to limit the cost of developing and time for analysis.</p>
<p>Once some decisions on the boundaries of the system have been made, part of the analysis activity is the definition of that context and the dependencies that a system has on its environment. Producing a simple architectural model is the first step in this activity.</p>
<p>Architectural models describe the environment of a system. However, they don’t show the relationship between the other systems in the environment and the system that is being specified. Therefore, simple architectural models are normally supplemented by other models, such as process models, that show the process activities supported by the system.</p>
<p>Behavioural models are used to describe the overall behaviour of the system. Two types of behavioural models exist:</p>
<ul>
<li>Data-flow models, which model the data processing in the system. It is an intuitive way of showing how data is processed by a system. Data-flow models are valuable because tracking and documenting how the data associated with a particular process moves through the system helps analysts understand what is going on. This type of models show a functional perspective where each transformation represents a single function or process. They show the entire sequence of action that take place from an input being processed to the corresponding output that is the system’s response.</li>
<li>State machine models, which model how the system reacts to events. It showssystem states and events that cause transition from one state to another. It does not show the flow of data within the system. A state machine model of a system assumes that, at any time, the system is in one of a number of possible states. When a signal is received, trigger may switch a transition to a different state.</li>
</ul>
<p>These types of models can be combined.</p>
<p>Most large software systems make use of a large database of information. In some cases, this database is independent of the software system. In others, it is created for the system being developed. An important part of systems modelling is defining the logical form of the data processed by the system.</p>
<p>The most widely used data modelling technique is Entity-Relation-Attribute modelling (ERA modelling), which shows the data entities, their associated attributes and the relations between these entities. These models have been widely used in database design.</p>
<p>Like all graphical models, data models lack detail, and you should maintain more detailed descriptions of the entities, relationships and attributes that are included in the model. More detailed descriptions are often stored in a repository or data dictionary. A data dictionary is an alphabetic list of the names included in the system models. As well as the name, the dictionary should include an associated description of the named entity and, if the name represents a composite object, a description of the composition.</p>
<p>An object-oriented approach to the whole software development process is now commonly used. This means expressing the system requirements using an object model, designing using objects and developing the system in an object-oriented programming language.</p>
<p>Developing object models during requirements analysis usually simplifies the transition to object-oriented design and programming. However, as author notices, end-users often find object models unnatural and difficult to understand.</p>
<p>Object-oriented modelling involves identifying the classes of object that are important in the domain being studied. These are often organised into taxonomy. A taxonomy is a classification scheme that shows how an object class is related to other classes through common attributes and services. To display this taxonomy, the classes are organised into an inheritance hierarchy with the most general object classes at the top.</p>
<p>The design of class hierarchies is not easy, so the analyst need to understand, in detail, the domain in which the system is to be installed.</p>
<p>As well as acquiring attributes and services through an inheritance relationship with other objects, some objects are groupings of other objects. The classes representing these objects may be modelled using an object aggregation model.</p>
<p>A structured method is a systematic way of producing models of an existing system or a system that is to be built. Structured methods provide a framework for detailed system modelling as part of requirements elicitation and analysis.</p>
<p><em>My thoughts:</em></p>
<p><em>As everything big and important today, such process as software engineering is based on some abstract things. System models are abstract and detailed at the same time. Different types are used, but again, as I said before, my opinion is “mixing is better”, or in this case using different types of models to describe different sides of development have to be done. </em></p>
<p><em>Modelling the system is important, because this is the base, most fundamental part of actual work after requirements are defined, or at least part of them. Even for such a small project as our Monopoly game, I cannot imagine starting coding from scratch with no requirements defined and model developed, especially when there are four people in the team. Models are also useful to divide work between developers I guess: when signals are defined and model is created, different components may be implemented by different people, sometimes – in the different parts of Earth (like most of Open Source developers work). </em></p>
<p><strong>Chapter 9</strong></p>
<p>Specification for critical systems is important. Because of the high potential costs of system failure, it is important to ensure that the specification for critical systems accurately reflects the real needs of users of the system.</p>
<p>System functional requirements may be generated to define error checking and recovery facilities and features that provide protection against system failures. Non-functional requirements may be generated to define the required reliability and availability of the system.</p>
<p>Critical systems specifications’ objective is to understand the risks faced by the system and generate dependability requirements to cope with them. The process of risk analysis consists of four steps:</p>
<p>1.      <strong>Risk identification</strong>. Potential risks that might arise are identified. These are dependent on the environment in which the system is to be used. In safety-critical systems, the principal risks are hazards that can lead to an accident. Experienced engineers, working with domain experts and professional safety advisors, should identify system risks. Group working techniques such as brainstorming may be used to identify risks.</p>
<p>2.      <strong>Risk analysis and classification</strong>. The risks are considered separately. Those that are potentially serious and not implausible are selected for further analysis. Risks can be categorised in three ways:</p>
<p>a.       <strong>Intolerable</strong>. The system must be designed in such a way so that either the risk cannot arise or, if it does arise, it will not result in an accident. Intolerable risks are those that threaten human life or the financial stability of a business and which have a significant probability of occurrence.</p>
<p>b.      As low as reasonably practical (<strong>ALARP</strong>). The system must be designed so that the probability of an accident arising because of the hazard is minimised, subject to other considerations such as cost and delivery. ALARP risks are those which have less serious consequences or which have a low probability of occurrence.</p>
<p>c.       <strong>Acceptable</strong>. While the system designers should take all possible steps to reduce the probability of an ‘acceptable’ hazard arising, these should not increase costs, delivery time or other non-functional system attributes.</p>
<p>3.      <strong>Risk decomposition</strong>. Each risk is analysed individually to discover potential root causes of that risk. Different techniques for risk decomposition exist. The one discussed in the book is Fault-tree analysis, where analyst puts hazard at the top and place different states which can lead to that hazard above. States can be linked with ‘or’ and ‘and’ symbols. Risks that require a combination of root causes are usually less probable than risks that can result from a single root cause.</p>
<p>4.      <strong>Risk reduction assessment</strong>. Proposals for ways in which the identified risks may be reduced or eliminated are made. Three possible strategies of risk deduction that can be used are:</p>
<p>a.       <strong>Risk avoidance</strong>. Designing the system in such a way that risk or hazard cannot arise.</p>
<p>b.      <strong>Risk detection and removal</strong>. Designing the system in such a way that risks are detected and neutralised before they result in an accident.</p>
<p>c.       <strong>Damage limitation</strong>. Designing the system in such a way that the consequences of an accident are minimised.</p>
<p>In the 1980s and 1990s, as computer control become widespread, the safety engineering community developed standards for safety critical systems specification and development. The process of safety specification and assurance is part of an overall safety life cycle that is defined in an international standard for safety management IEC 61508 (IEC, 1998).</p>
<p>Security and safety requirements have something in common; however, there are some differences between these types of requirements.</p>
<p>The conventional (non-computerised) approach to securityanalysis is based around the assets to be protected and their value to an organisation. The stages in this process are:</p>
<p>1.      Asset identification and evaluation</p>
<p>2.      Threat analysis and risk assessment</p>
<p>3.      Threat assignment</p>
<p>4.      Technology analysis</p>
<p>5.      Security requirements specification</p>
<p>Reliability is a complex concept that should always be considered at the system rather than the individual component level. Component in the system are interdependent, so a failure in one component can be propagated through the system and affect the operation of other components. Three types of reliability should be taken in consideration – hardware reliability, software reliability and operator reliability.</p>
<p><em>My thoughts:</em></p>
<p><em>I think almost every system can be dangerous somehow, it’s a nature of things that if something does something, this something can be done in other, more insecure or unsafe way. Especially, in such a complex structures as software systems. Engineers do their best to develop better, more secure and safe systems, but while increasing the size of system all the problems and risks increase, so all techniques of risk avoidance or reduction are in this infinite race between system size and safety. Previous chapters were all about important thing about functional part of a system, how system should be developed etc. This chapter is also about developing and designing the system, but it shows the importance of other side. </em></p>
<p><strong>Chapter 10</strong></p>
<p>The term <em>formal methods</em> is used to refer to any activities that rely on mathematical representations of software including formal system specification, specification analysis and proof, transformational development, and program verification. In the 1980s many software engineering researchers proposed that using formal development methods was the best way to improve software quality. They also predicted that by 21<sup>st</sup> century a large proportion of software would be developed using formal methods. However, this prediction has not come true.</p>
<p>Critical systems development usually involves a plan-based software process that is based on the waterfall model of development. Both the system requirements and the system design are expressed in detail and carefully analysed and checked before implementation begins. The involvement of the client decreases and the involvement of the contractor increases as more detail is added to the system specification. In the early stages of the process the specification should be ‘customer-oriented’. Stages of software specification and its interface with the design process are (in order):</p>
<p>User Requirements Definitions -&gt; System requirements specification -&gt; Architectural design -&gt; Formal specification -&gt; High-level design.</p>
<p>Depending on the process used, specification problems discovered during formal analysis might influence changes to the requirements specification if this has not already been agreed.</p>
<p>Two fundamental approaches to formal specification have been used to write detailed specifications for industrial software systems:</p>
<ol>
<li>An algebraic approach where the system is described in      terms of operations and their relationships.</li>
<li>A model-based approach where a model of the system is      built using mathematical constructs such as sets and sequences, and the      system operations are defined by how they modify the system state.</li>
</ol>
<p>Large systems are usually decomposed into sub-systems that are developed independently. Sub-systems make use of other sub-systems, so an essential part of the specification process is to define sub-system interfaces.</p>
<p>The algebraic approach was originally designed for the definition of abstract data type interfaces. In an abstract data type, the type is defined by specifying the type operations rather than the type representation, so it is similar to an object class.</p>
<p>The process of developing a formal specification of a sub-system interface includes the following activities:</p>
<ol>
<li>Specification structuring. Organise the informal      interface specification into a set of abstract data types or object      classes.</li>
<li>Specification naming. Establish a name for each abstract      type specification.</li>
<li>Operation selection. Choose a set of operations for each      specification based on the identified interface functionality.</li>
<li>Informal operation specification. Write an informal      specification of each operation.</li>
<li>Syntax definition. Define the syntax of the operations      and the parameters to each.</li>
<li>Axiom definition. Define the semantics of the operations      by describing what conditions are always true for different operation      combinations.</li>
</ol>
<p>The simple algebraic techniques can be used to describe interfaces where the object operations are independent of the object state. Therefore, the result of applying an operation should not depend on the results of previous operations. As structure increases in size, algebraic descriptions become increasingly difficult to understand.</p>
<p>Model-based specification is an approach to formal specification where the system specification is expressed as a system state model. System operations are defined by how they affect the state of the system model.</p>
<p>While developing a model-based specification, state variables and predicates should be defined.</p>
<p><em>My thoughts:</em></p>
<p><em> </em></p>
<p><em>Maybe I just don’t have any good experience, but for me a model-based approach seems like too complicated case, and algebraic approach sound more natural. </em></p>
<p><strong>Chapter 11</strong></p>
<p>Architectural design is the initial design process of identifying sub-systems and establishing a framework for sub-system control and communication. Using large-grain components improves performance, and using fine-grain components improves maintainability, so if both of these are important system requirements developers should find some compromise solution. There is an overlap between the process of requirements engineering and architectural design.</p>
<p>Sub-system design is an abstract decomposition of a system into large-grain components, each of which may be a substantial system in its own right. Block diagrams are often used to describe sub-system designs where each box in the diagram represents sub-system. Sub-systems can have their own sub-systems, in that case boxes are placed into boxes. Arrows mean that data and or control signals are passed from sub-system to sub-system in the direction of the arrows.</p>
<p>Architectural design is a creative process so many decisions are being made depending on requirements, specific rules for particular project and experience of an architect. Architectural models that may be developed may include:</p>
<ul>
<li>A static structural model that shows the sub-systems or components that are to be developed as separate units.</li>
<li>A dynamic process model that shows how the system is organised into processes at run-time.</li>
<li>An interface model that defines the services offered by each sub-system through its public interface.</li>
<li>Relationship model that shows relationships, such as data flow, between the sub-systems.</li>
<li>A distributed model that shows how sub-systems may be distributed across computers.</li>
</ul>
<p>Different models may be used. Sub-systems making up a system exchange information so that they can work together effectively. There are two fundamental ways in which this can be done.</p>
<ol>
<li>All shared data is held in a central database that can      be accessed by all sub-systems. A system model based on a shared database      is sometimes called a repository model.</li>
<li>Each sub-system maintains its own database. Data is      interchanged with other sub-systems by passing messages to them.</li>
</ol>
<p>The majority of systems that use large amount of data are organised around a shared database or repository. This model is suited to applications where data is generated by one sub-system and used by another.</p>
<p>The client-server architectural model is a system model where the system is organised as a set of services and associated servers and clients that access and use the services. Clients may have to know the names of the available servers and the services that they provide.</p>
<p>The layered model of an architecture (sometimes called an abstract machine model) organises a system into layers, each of which provide a set of services. Each layer can be thought of as an abstract machine whose machine language is defined by the services provided by the layer. This ‘language’ is used to implement the next level. This approach supports the incremental development of systems.</p>
<p>After an overall system organisation has been chosen, different approaches may be used to decompose sub-systems into modules. Two main strategies of doing this are:</p>
<ol>
<li>Object-oriented decomposition where a system is      decomposed into a set of communicating objects. Object call on the      services offered by other objects. The object-oriented approach is      well-known and convenient, but still has some disadvantages, for example, to      use services, objects must explicitly reference the name and the interface      of other objects. If an interface change is required to satisfy proposed      system changes, the effect of that change on all users of the changed      object must be evaluated.</li>
<li>Function-oriented pipelining where the system is      decomposed into functional modules that accept input data and transformed      into output data. Each processing step is implemented as a transform.</li>
</ol>
<p>The models for structuring a system are concerned with how a system is decomposed into sub-systems. To work as a system, sub-systems must be controlled so that their services are delivered to the right place at the right time. There are two generic control styles that are used in software systems:</p>
<ul>
<li>Centralised control. One sub-system has overall      responsibility for control and starts and stops other sub-systems. It may      also devolve control to another sub-system bit will expect to have this      control responsibly returned to it.</li>
<li>Even-based control. Rather than control information being      embedded in a sub-system, each sub-system can respond to externally      generated events. These events might come from other sub-systems or from      the environment of the system.</li>
</ul>
<p><strong>Chapter 12</strong></p>
<p>A distributed system is a system where the information processing is distributed over several computers rather than confined to a single machine. Advantages of distributed system are coming from several important characteristics of distributed systems. These advantages are:</p>
<ol>
<li>Resource sharing</li>
<li>Openness</li>
<li>Concurrency</li>
<li>Scalability</li>
<li>Fault tolerance</li>
</ol>
<p>However, there are (as usual) some disadvantages:</p>
<ol>
<li>Complexity</li>
<li>Security</li>
<li>Manageability</li>
<li>Unpredictability</li>
</ol>
<p>The design challenge is to create the software and hardware to provide desirable distributed system characteristics and, at the same time, minimise the problems that are inherent in these systems.</p>
<p>Two generic types of distributed systems are:</p>
<ul>
<li><strong>Client-server      architectures</strong>. The system may be thought of as a set of services that      are provided to clients that make use of these services. Servers and      clients are treated differently. The simplest client-server architecture      is called a two-tier client-server architecture, where an application is      organised as a server (or multiple servers) and a set of clients. The      client might be <strong>thin</strong> (when all      of the application processing and data management is carried out on the      server, and the client is just presenting data) or <strong>fat</strong> (where client implements the application logic and      interactions with user, and server is responsible for data management)</li>
<li><strong>Distributed      object architectures</strong>. There is no distinction between servers and      clients, and the system may be thought of as a set of interacting objects      whose location is irrelevant. There is no distinction between a service      provider and a user of these services. A more general approach to      distributed system design is to remove the distinction between client and      server and to design the system architecture as a distributed object      architecture. Objects may be distributed across a number of computers on a      network and communicate through middleware. This middleware is called an      object request broker.</li>
</ul>
<p>The simplest model of a distributed system is a multiprocessor system where the software system consists of a number of processes that may (but need not) execute on separate processors. This approach is widely used in large real-time systems.</p>
<p>Peer-to-peer (p2p) systems are decentralised systems where computations may be carried out by any node on the network and, in principle at least, no distinctions are made between clients and servers. The overall system is designed to take advantages of the computational power and storage available across a potentially big network of computers.</p>
<p><em>My thoughts:</em></p>
<p><em>Our Monopoly game is an example of client-server architecture with a thin client. We have one server which is responsible for all computations and data management, and client is only a GUI. This is the easiest way for us, because technically one program will do everything and another will only show that. It is also better in terms of security: </em></p>
<p><strong>Chapter 13</strong></p>
<p>There are many types of application system and, on the surface, they may seem to be very different. However, after examining the architectural organisation of applications many of these superficially dissimilar applications have much in common. There are four broad types of architectures discussed in the book:</p>
<ol>
<li><strong>Data-processing      applications</strong>. These are data-driven applications, they process data in      batches without explicit user interventions during the processing. The      specific action taken by the application depend on the data that it is      processing. Applications of this type are commonly used in business, where      similar operations are carried out on a large amount of data. The nature      of data-processing systems where records or transactions are processed      serially with no need to maintain state across transactions means that      these systems are naturally function-oriented. Functions are components      that do not maintain internal state information from one invocation to      another.</li>
<li><strong>Transaction-processing      applications</strong>. These are database-centred applications that process      user requests for information and that update the information in database.      These are most common type of interactive business systems. They are      organised in such a way that user actions can’t interfere with each other      and the integrity of the database is maintained. To simplify the      management of different terminal communication protocols, large-scale      transaction-processing systems may include middleware that communicates      with all types of terminal, organises and serialises the data from      terminals, and sends that data for processing. Implementations of      information and resource management systems based on Internet protocols      are now the norm.</li>
<li><strong>Event-processing      systems</strong>. This is a very large class of application where the actions      of the system depend on interpreting events in the system’s environment.      These events might be the input of a command by a system user or a change      in variables that are monitored by the system. Real-time systems also fall      into this category. However, for real-time systems, events are not usually      user interface events but events associated with sensors or actuators in      the system.</li>
<li><strong>Language-processing      systems</strong>. These are systems where the user’s intensions are expressed      in a formal language (such as Java). The language-processing system      processes this language into some internal format and then interprets this      internal representation. The best known language-processing systems are      compilers, which translate high-level language programs to machine code.      In the very abstract way the language-processing system’s process can be      described as: instructions go to the translator, which checks syntax and      semantics and then generate some abstract instructions for interpreter.      Interpreter takes those instructions along with data, executes the program      and gives the output. Other components       might also be included that transform the syntax tree to improve      efficiency and remove redundancy from the generated machine code.</li>
</ol>
<p><strong>Chapter 14</strong></p>
<p>An object-oriented system is made up of interacting objects that maintain their own local state and provide operations on that state. The representation of the state is private and cannot be accessed directly from outside the object. Object-oriented design processes involve designing object classes and the relationships between them.</p>
<p>Object-oriented design is one phase of the development process:</p>
<ul>
<li>Object-oriented analysis is concerned with developing an      object-oriented model of the application domain. The objects in that model      reflect the entities and operations associated with the problem to be      solved.</li>
<li>Object-oriented design with developing an object-oriented      model of a software system to implement the identified requirements.</li>
<li>Object-oriented programming is concerned with realising a      software design using an object-oriented programming language, such as      Java.</li>
</ul>
<p>An object is an entry that has a state and a defined set of operations that operate on that state. The state is represented as a set of object attributes. Objects created according to an object class definition.</p>
<p>In such a language as Java it is easy to take an object-oriented design and produce an implementation where the objects are concurrent processes. There are two kinds of concurrent object implementation:</p>
<ol>
<li>Servers where the object is realised as a parallel      process with methods corresponding to the defined object operations.</li>
<li>Active objects where the state of the object may be      changed by internal operations executing within the object itself.</li>
</ol>
<p>The general process that is described in the book has a number of stages:</p>
<ol>
<li>Understand and define the context and the modes of use      of the system.</li>
<li>Design the system architecture</li>
<li>Identify the principal objects in the system.</li>
<li>Develop design models</li>
<li>Specify object interfaces.</li>
</ol>
<p>My thoughts:</p>
<p>The concept of object-oriented design seemed really unnatural for me five or six years ago when I used to code with Visual Basic and Delphi. I’ve seen no sense in making things so complicated and abstract rather than just write the program you need using procedures, jumps etc. Today it’s the other way around – I don’t see any other way of programming something bigger that bash script.</p>
<p><strong>Chapter 15</strong></p>
<p>Computers are used to control a wide range of systems from simple domestic machines to entire manufacturing plants. These computers interact directly with hardware devices. The software in these systems is embedded real-time software that must react to events generated by the hardware and issue control signals in response to these events. A good definition from author of the book is the following:</p>
<p><em>A real time system is a software system where the correct functioning of the system depends on the results produced by the system and the time at which these results are produced. A soft real-time system is a system whose operation is degraded is results are not produced according to the specific timing requirements. A hard real-time system is a system whose operation is incorrect if results are not produced according to the timing specification.</em></p>
<p>One way of looking at a real-time system is as a input/response system. For a specific input system responds in a particular way. These inputs (or stimuli) fall into two classes:</p>
<ol>
<li><strong>Periodic stimuli</strong>.      These occur at predictable time intervals.</li>
<li><strong>Aperiodic stimuli</strong>.      These occur irregularly.</li>
</ol>
<p>Because real-time systems must meet their timing constraints, sometimes it is impossible to use object-oriented development for hard real-time systems. Object-oriented development involves hiding data and accessing attributes values through operations defined with the object, which means there is a significant performance overhead in object-oriented systems because extra code is required to mediate access to attributes and handle calls to operations.</p>
<p>A state model of a system assumes that, at any time, the system is in one of a number of possible states. When a stimulus is received, this may cause a transition to a different state.</p>
<p>A real-time operating system manages processes and resource allocation in a real-time. There are many RTOS products available, from very small, simple systems for consumer devices to complex systems for cell phones and mobile devices and operating systems specially designed for process control and telecommunications. RTOS usually inclides:</p>
<ul>
<li><strong>A real-time clock</strong>.      Provides information to schedule processes periodically.</li>
<li><strong>An interrupt      handler</strong>. Manages aperiodic requests for service.</li>
<li><strong>A scheduler</strong>.      Responsible for examining the processes that can be executed and choosing      one of these for execution.</li>
<li><strong>A resource      manager</strong>. Allocates appropriate memory and processor resources for      ascheduled process.</li>
<li><strong>A despatcher</strong>.      This component is responsible for starting the execution of a process.</li>
</ul>
<p>Real time operating system’s actions required to start a process looks like this: Scheduler chooses process for execution based on process priority, the expected execution time and the deadlines of the ready processes; resource manager allocates memory and processor; despatcher starts execution on available processor.</p>
<p><strong>Chapter 16</strong></p>
<p>User interface of a software product is the “face” of it. Many “user errors” are caused by the fact that user interfaces do not consider the capabilities of real users and their working environment. A poorly designed interface means that users will probably be unable to access some of the system features, will make mistakes and will fell that the system hinders rather than helps them in achieving whatever they are using system for.</p>
<p>While designing user interface, some physical and mental capabilities of the people who will use the software should be taken into account. Some of them are:</p>
<ol>
<li>People have a limited short-term memory.</li>
<li>We all make mistakes, especially when we have to handle      too much information or are under stress. Too much system warnings, alarms      etc. can annoy stressed people thus increase the chances that they will      make more operational mistakes.</li>
<li>We have a diverse range of physical capabilities. Some      people see and hear better than other, some people are color-blind, etc.</li>
<li>We have different interaction preferences. Some people      like to work with pictures, others with text.</li>
</ol>
<p>These human factors are the basic for the design principles.</p>
<p>The principle of <strong>user familiarity</strong> suggests that users should not be forced to adapt to an interface because it is convenient to implement.</p>
<p>The principle of <strong>user interface consistency</strong> means that system commands and menus should have the same format, parameters should be passed to all commands in the same way, and command punctuation should be the similar. However, full consistency is neither possible nor desirable.</p>
<p>The principle of <strong>minimal surprise</strong>is appropriate because people get very irritated when a system behaves in an unexpected way.</p>
<p>The principle of <strong>recoverability</strong> is important because users inevitably make mistakes when using a system. The interface design can minimise these mistakes, but mistakes can never be completely eliminated. Consequently, system should include some tools allowing users recover from their mistakes. These can be of three kinds:</p>
<ul>
<li>Confirmation of destructive actions. To avoid accidental      destructions or to explain consequences for user.</li>
<li>The provision of an undo facility. Undo restores the      system to a state before the action occurred. Multiple levels of undo are      useful because users don’t always recognise that a mistake has been made. <em>(Why mspaint has only three levels of      undo, or do they think that people who use mspaint are only pros and don’t      do too much mistakes??!)</em></li>
<li>Checkpointing. It involves saving the state of a system      at periodic intervals and allowing the system to restart from the last      checkpoint. Similar to simple backup system for data.</li>
</ul>
<p>A related principle is the principle of <strong>user assistance</strong>. Interfaces should have built-in user assistance or help facilities.</p>
<p>The overall user interface design process in general concerned with two main questions: <strong>how should the user interact with the system</strong> and <strong>how should information from the system be presented to the user?</strong></p>
<p>User can interact with computer system in a number of ways, most common of them are:</p>
<p>1.      Direct manipulation. The user interacts directly with objects on the screen. It usually involves a pointing device, e.g. a mouse or a finger on a touch screen (like on your white 16 gig iPhone).</p>
<p>2.      Menu selection. The user selects a command from a list of possibilities (a menu).</p>
<p>3.      Form fill-in. The user fills in the fields of a form. Some fields may have associated menus, and the form may have action to be initiated.</p>
<p>4.      Command language. User enters a special command and associated parameters to instruct the system what to do (bash!)</p>
<p>5.      Natural language. The user issues a command in natural language. This is usually a front-end to a command language. <em>(I also think that this includes voice commands)</em></p>
<p><em> </em></p>
<p>Presentation of information by a computer system depends on user of the system. Also, the issue of colour in presentation is important. The most important key guidelines for the effective use of colour are:</p>
<ol>
<li>Limit the number of colours employed and be conservative      how these are used.</li>
<li>Use colour change to show a change in system status.</li>
<li>Use colour coding to support the task users are trying      to perform.</li>
<li>Use colour coding in a thoughtful and consistent way.</li>
<li>Be careful about color pairings.</li>
</ol>
<p>The user interface design process includes sub-processes concerned with user analysis, interface prototyping and interface evaluation. The aim of user analysis is to sensitise designers to the ways in which users actually work. Different techniques (task analysis, interviewing, observation) are used during user analysis.</p>
<p>User interface prototype development should be a staged process with early prototypes based on paper versions of the interface that, after initial evaluation and feedback, are used as a basis for automated prototypes. The goals of user interface evaluation are to obtain feedback on how a UI design can be improved to assess whether an interface meets its usability requirements.</p>
<p><em>My thoughts:</em></p>
<p><em>As I was reading this chapter, I was thinking about how serious and professional Apple’s user interface designers are. Every point of the stuff discussed in this chapter was a serious for them. Like the principle of user consistency: in Mac OS user can always be sure, that the program he never used before will have a menu line at the top of the screen. ALWAYS!</em></p>
<p><em>Actually, the iPhone is one of the few products where I don’t even want to customize user interface, because it feels like someone <strong>did think</strong>.</em></p>
<p><em>In general, I think of user interface as a very important and really interesting field in software engineering. Right now I’m working on GUI for our project, so this chapter was pretty useful for me.</em></p>
<p><strong>Chapter 17</strong></p>
<p>Rapid software development processes are designed to produce useful software quickly. Generally, they are iterative processes where specification, design, development and testing are interleaved. The software is not developed and deployed in its entirety, but in a series of increments, with each increment including new system functionality. The two main advantages to adopting an incremental approach to software development are:</p>
<p>1.      Accelerated delivery of customer services. Early increments of the system can deliver high-priority functionality.</p>
<p>2.      User engagement with the system. Users of the system have to be involved in the incremental development process because they have to provide feedback to the development team on delivery increments.</p>
<p>However, as usual, there are some major difficulties with iterative development and incremental delivery are:</p>
<p>1.      Management problems. Incrementally developed systems change so quickly that it is not cost-effective to produce lots of system documentation.</p>
<p>2.      Contractual problems. When there is no system specification, it may be difficult to design a contract for the system development.</p>
<p>3.      Validation problems. In a specification-based process, verification and validation are geared towards demonstrating that the system meets its specifications.</p>
<p>4.      Maintenance problems. Continual change tends to corrupt the structure of any software system. This means that anyone apart from the original developers may find the software difficult to understand.</p>
<p>Agile methods are iterative development methods that focus on incremental specification, design and system implementation. They involve the customer directly in the development process. Reducing development overhead can make faster software development possible. Extreme programming (XP) is a well-known agile method that integrates a range of good programming practices such as systematic testing, continuous software improvement and customer participation in the development team.</p>
<p>In an XP process, customers are intimately involved in specifying and prioritizing system requirements. The requirements are not specified as lists of required system functions. Rather, the system customer is part of the development team and discusses scenarios with other team members.</p>
<p>Rapid application development involves using development environments that include powerful tools to support system production. These includes database programming languages, form and report generators, and links to office applications.</p>
<p>Throw away prototyping is an iterative development process where a prototype system is used to explore the requirements and design options. This prototype is not intended for deployment by the system customer.</p>
<p><em>My thoughts:</em></p>
<p><em> </em></p>
<p><em>Rapid software development seems interesting for me, because it somehow related to our project. Even though we had quite a lot of time and a case study (which almost means we had a set of requirements ready to be organized and used), extreme programming sounds like a good description of last two weeks before iteration 2 </em><em>J</em><em> </em></p>
<p><em>Anyway, this type of software development is interesting, but I’d prefer a regular, no-rush and planned process, it is much less stress and more creativity (at least for the type of person I am).</em></p>
<p><strong>Chapter 18</strong></p>
<p>Reuse-based software engineering is an approach to development that tries to maximize the reuse of existing software. The software units that are reused may be of radically different sizes. There may be an application system reuse, different particular component reuse or object and function reuse. A complementary form of reuse is concept reuse, where rather than reuse a component, the reused entity is more abstract and is designed to be configured and adapted for a range of situations.</p>
<p>An obvious advantage of software reuse is that overall development costs should be reduced. Fewer software components need be specified, designed, implemented and validated. However, there are also costs and problems associated with software reuse. There is a significant cost associated with understanding whether a component is suitable for reuse in a particular situation and in testing that component to ensure compatibility.</p>
<p>Design patterns are high-level abstractions that document successful design solutions. They are fundamental to design reuse in object-oriented development. A pattern description should include a pattern name, a problem and solution description, and a statement of the results and trade-offs of using the pattern. A huge number of published patterns are now available covering a range of application domains and languages. The use of patterns is an effective form of reuse.</p>
<p>Program generators are an alternative approach to concept reuse where the reusable concepts are embedded in a generator system. The designer specifies the abstractions required using a domain-specific language, and an executable program is generated.</p>
<p>Application frameworks are collections of concrete and abstract objects that are designed to be reused through specialization and addition of new objects. Three classes of framework are:</p>
<ul>
<li>System infrastructure frameworks. These frameworks support the development of system infrastructures such as communications, user interfaces and compilers.</li>
<li>Middleware integration frameworks. These consist of a set of standards and associated object classes that support component communication and information exchange.</li>
<li>Enterprise application frameworks. These are concerned with specific application domains such as telecommunications or financial systems.</li>
</ul>
<p>A commercial-off-the-shelf product is a software system that can be used without change by its buyer. COTS product reuse is concerned with the reuse of large-scale systems. These provide a lot of functionality, and their reuse can radically reduce costs and development time. Potential problem with COTS-based reuse include lack of control over functionality and performance, lack of control over system evolution, the need for support from external vendors and difficulties in ensuring that systems can interoperate.</p>
<p>One of the most effective approaches to reuse is creating software product lines or application families. A product line is a set of applications with a common application-specific architecture. Various types of specialization of a software product line may be developed:</p>
<p>1.      Platform specialization.</p>
<p>2.      Environment specialization</p>
<p>3.      Functional specialization</p>
<p>4.      Process specialization</p>
<p><em>My thoughts:</em></p>
<p><em> </em></p>
<p><em>While working on our project we touched only one aspect of software reuse – program generators. Rose Real Time is a good example of program generator. </em></p>
<p><em>When we just started I was thinking about Rose RT as a weird way to develop a system, it was hard to understand how learning a new environment and using it may be useful or may lead to faster development, but today I see all advantages of this approach. We don’t have to think about building a server, about network routines, about designing a system in a good way with straight C and Java, we don’t even have to think about choosing the way of connecting java and c code. </em></p>
<p><em>So now I think of software reuse as actually useful thing that helps us reduce the development time. </em></p>
<p><strong>Chapter 19</strong></p>
<p>Reuse-based software engineering is becoming the main development approach for business and commercial systems. Component-based software engineering (CBSE) emerged in the late 1990s as a reuse-based approach to software systems development. Single object classes were too detailed and specific, and often had to be bound with an application at compile-time. CBSE is the process of defining, implementing and integrating or composing loosely coupled independent components into systems. The essentials of component-based software engineering are:</p>
<ol>
<li>Independent components that are      completely specified by their interfaces. There should be a clear      separation between the component interface and its implementation so that      one implementation of a component can be replaced by another without      changing the system.</li>
<li>Component standards that      facilitate the integration of components. These standards are embodied in      a component model and define, at very minimum, how component interfaces      should be specific and how components communicate.</li>
<li>Middleware that provides      software support for component integration. Middleware such as CORBA      handles low-level issues efficiently and allows developers to focus on      application-related problems.</li>
<li>A development process that is      geared to component-based software engineering.</li>
</ol>
<p>As always, some problems with using this approach remain:</p>
<ol>
<li>Component trustworthiness.      Components are black-box program units, and the source code of the      component may not be available to component users.</li>
<li>Component certification. This      issue is closely related to trustworthiness, it is the issue of      certification.</li>
<li>Emergent property prediction.      Because components are opaque, predicting their emergent properties is      particularly difficult.</li>
<li>Requirements trade-offs.      Developers usually have to make trade-offs between ideal requirements and      available components in the system specification and design process.</li>
</ol>
<p>A component model defines a set of standards for components, including interface standards, usage standards and deployment standards. The implementation of the component model provides a set of horizontal services that may be used by all components.</p>
<p>Component composition is the process of writing components together to create a system.</p>
<p> <img src="http://freetonik.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=44" width="1" height="1" style="display: none;" /></p>
<p>Наши роботы искали похожие записи, но не нашли :(</p><img src="http://feeds.feedburner.com/~r/ComputerScienceStudent/~4/d_ioepvq8d4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://freetonik.com/text/software-engineering-notes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://freetonik.com/text/software-engineering-notes/</feedburner:origLink></item>
		<item>
		<title>Ускорения параллельных вычислений</title>
		<link>http://feedproxy.google.com/~r/ComputerScienceStudent/~3/aPhUzN6Be6k/</link>
		<comments>http://freetonik.com/text/uskoreniya-parallelnyx-vychislenij/#comments</comments>
		<pubDate>Tue, 19 Oct 2010 01:12:04 +0000</pubDate>
		<dc:creator>freetonik</dc:creator>
				<category><![CDATA[Информатика]]></category>
		<category><![CDATA[Текст]]></category>

		<guid isPermaLink="false">http://freetonik.com/?p=1869</guid>
		<description><![CDATA[Главной целью создания и разроботки многочисленных типов параллельных машин, о которых мы говорили в прошлой статье, это скорость. Суперкомпьютеры и многопроцессорные системы могут и должны делать все быстрее! Давайте постараемся расчитать, насколько быстрее.

Логично подумать, что если один процессор выполняет работу на n секунд, то четыре процессора потратят n/4 секунд. 
Наши роботы искали похожие записи, но не нашли :(]]></description>
			<content:encoded><![CDATA[<p>Главной целью создания и разроботки многочисленных типов параллельных машин, о которых мы говорили в <a rel="nofollow" href="http://hexlet.ru/blog/parallel/82.html">прошлой</a> статье, это скорость. Суперкомпьютеры и многопроцессорные системы могут и должны делать все быстрее! Давайте постараемся расчитать, насколько быстрее.</p>
<p>Логично подумать, что если один процессор выполняет работу на n секунд, то четыре процессора потратят n/4 секунд. Понятие “фактор ускорения” (“speedup factor”) это отношение времени, которое тратит на выполнение работы один процессор к времени, которое тратит на эту же работу многопроцессорная система.</p>
<p>S (p) = T<sub>s</sub> / T<sub>p</sub></p>
<p>Для расчета важно использовать самый оптимальный T<sub>s</sub>, то есть лучший из возможных не-параллельных алгоритмов.<br />
<span id="more-1869"></span>Теперь плохие новости: у этого ускорения есть лимит. Называется он Amdahl’s Law (Закон Амдала) и вот его суть: так выглядит какая-либо задача на обычной однопроцессорной системе:</p>
<p><img src="http://hexlet.ru/uploads/images/00/00/01/2010/10/18/484f28.png" alt="" /><br />
Все время выполнения — знакомое уже нам T<sub>s</sub>, состоит из той части, которую можно распределить на несколько процессоров (распараллелить) — (1-f) T<sub>s</sub>, и той части, что распараллелить нельзя (серийная) — fT<sub>s</sub>.</p>
<p>Как будет выглядеть схема той же задачи для нескольких процессоров?</p>
<p><img src="http://hexlet.ru/uploads/images/00/00/01/2010/10/18/b2055b.png" alt="" /></p>
<p>Теперь общее время выполнения Tp состоит из серийного времени и максимального из тех, что мы распределили на несколько процессоров (выполняются они все одновременно, но ждать нужно самого медленного). Для простоты допустим, что все они занимают одинаковое время.</p>
<p>Фактор ускорения расчитывается по формуле:</p>
<p><img src="http://hexlet.ru/uploads/images/00/00/01/2010/10/18/62cca9.png" alt="" /></p>
<p>То есть все зависит от того, какой кусок программы мы сможем распараллелить (f в процентах означает количество серийного кода). Если f=0%, то есть абсолютно весь код распараллелен (чего практически не может быть), то чем больше процессоров мы задействуем, тем быстрее будет выполнена задача, и соотношение будет линейное: хотим в 10 раз быстрее — используем десять процессоров, хотим в миллион раз быстрее — закупаем миллион процессоров. Но вот стоит оставить 5% серийного кода, а 95% распараллелить, то фактор ускорения будет равен 20 и выше никак не прыгнуть. Даже если закупим к тому миллиону еще миллион процессоров, то программа все равно будет выполняться в 20 раз быстрее. Вот как этот грустный факт выглядит на графике с примерами разных процентов f:</p>
<p><img src="http://hexlet.ru/uploads/images/00/00/01/2010/10/18/b8b8bc.png" alt="" /></p>
<p>Получается, что самое важное в вопросе эффективности параллельного кода — это хороший дизайн самого алгоритма. Каждая деталь может сильно повлиять на расширяемость: если сейчас алгоритм нормально использует ресурсы четырехядерного процессора, то возможно больше 8 ядер он нормально использовать не сможет, и тогда через год программу нужно будет писать заново — ведь вместо количества транзисторов теперь каждые полгода увеличивается количество ядер!</p>
<p>Чтобы написать хороший параллельный алгоритм, нужно вникнуть в суть проблемы и подумать, как его можно разделить на отдельные независимые (в идеале) части, чтобы все они выполнялись параллельно на разных процессорах. Посмотрим на примере довольно ёмкой задачи умножения матрицы А на вектор b. Результат будет записан в вектор y, который по размеру идентичен вектору b. Чтобы получить первое значение вектора y, нужно умножить первую строку матрицы на вектор b, чтобы получить второе значение y — вторую строку на b, и так далее. Получается, каждый элемент вектора y можно считать независимо от других, то есть параллельно.</p>
<p><img src="http://hexlet.ru/uploads/images/00/00/01/2010/10/18/61cf3b.png" alt="" /></p>
<p>Размер каждой такой задачи один и тот же — все строки A имеют одинаковый размер (пока не касаемся таких деталей, как плотность матрицы — возможно, в ней много нулей, но предположим, что это не сильно влияет на время выполнения). Нет никаких зависимостей между задачами, и все задачи используют один и тот же b.</p>
<p>Вот другой пример — запрос в базу данных:</p>
<p><strong>MODEL = “CIVIC” AND YEAR=2001 AND (COLOR=”GREEN” OR COLOR=”WHITE”);</strong></p>
<p>Запрос пытается получить все зеленые или белые Цивики 2001 года из такой базы:</p>
<p><img src="http://hexlet.ru/uploads/images/00/00/01/2010/10/18/9ee3c4.png" alt="" /></p>
<p>Такую задачу можно разложить на три части: один процессор будет формировать таблицу все Цивиков 2001 года, другой процессор будет формировать таблицу всех белых и зеленых машин (эти два запроса могут идти параллельно), после чего результат join’а этих двух таблиц и будет ответом.</p>
<p><img src="http://hexlet.ru/uploads/images/00/00/01/2010/10/18/0acbd6.png" alt="" /></p>
<p>Можно изменить структуру запроса, что может повлиять на параллелизацию</p>
<p><img src="http://hexlet.ru/uploads/images/00/00/01/2010/10/18/ac597a.png" alt="" /></p>
<p>Разделение задачи на части для последующего распределения этих частей на разные процессоры называется декомпозицией. Умножение матрицы на вектор это пример декомпозиции результата задачи: результат (вектор y) был разделен на несколько независимых частей и каждая расчитывалась отдельно от другой. То же самое можно сделать и с перемножением матриц:</p>
<p><img src="http://hexlet.ru/uploads/images/00/00/01/2010/10/18/4990a7.png" alt="" /></p>
<h4>Наша первая параллельная программа</h4>
<p>Для написания нашей первой параллельной программы мы будем использовать Cilk. Это язык программирования, который по сути является С с удобными инструментами для параллелизации и синхронизации задач. Cilk был разработан в MIT в 1994 году, был бесплатным и свободным, но к 2006 году стал коммерциализироваться, стал поддерживать С++, а год назад был куплен с потрохами компанией Intel, которой, конечно же, выгодно иметь хороший язык программирования для многоядерных систем: они ведь саим такие системы и производят. Я не уверен, как можно получить компилятор бесплатно, в нашем университете есть академическая версия для студентов (разработчик Cilk хороший друг профессора), поэтому прошу меня извинить, если вы не сможете найти его. Но поискать, я считаю, стоит, потому что Cilk жутко прост и удобен! Не сравнить с Pthreads. Все, что нам нужно знать, чтобы начать программировать, это три ключевых слова: <strong>cilk</strong>,<strong>spawn</strong> и <strong>sync</strong>.</p>
<p>Лучше всего начать с примера, поэтому вот вам любимая всеми рекурсивная задача — числа Фибоначи — на Си:</p>
<pre><code>int fib (int n){
if (n&lt;2) return n;
	else {
		int x, y;
		x = fib (n-1);
		y = fib (n-2);
		return (x+y);
}
}</code></pre>
<p>А вот та же программа на Cilk:</p>
<pre><code>cilk int fib (int n){
if (n&lt;2) return n;
	else {
		int x, y;
		x = spawn fib (n-1);
		y = spawn fib (n-2);
		sync;
		return (x+y);
}
}</code></pre>
<p>Заметили разницу? ,)<br />
Ключевое слово <strong>cilk</strong> используется для указания функции. Самыми главными являются слова spawn и sync. <strong>Spawn</strong> ставится перед вызовом функции, которую мы хотим запустить на другом ядре, а <strong>sync</strong> ждет окончания выполнения всех вызванных ранее spawn’ами функций. То есть строчка</p>
<p><strong>x=spawn fib (n-1);</strong></p>
<p>запускается на другом ядре, и сразу выполняется строчка <strong>y=spawn fib (n-2)</strong>. Перед тем, как вернуть результат (<strong>return (x+y)</strong>) нужно дождаться окончания выполнения, иначе в переменных x и y не будет правильных значений. Это делает команда sync — как и понятно из названия.</p>
<p>Правда, легко?</p>
<p>Такая программа хоршенько загрузит множество ядер! Вот как выглядит схема работы этого алгоритма для n=4:</p>
<p><img src="http://hexlet.ru/uploads/images/00/00/01/2010/10/18/0a520c.png" alt="" /></p>
<p>Цвета подсветки кода соответствуют цветам узлов графа. Каждый уровень графа выполняется одновременно, то есть первый вызов для n=4 вызывает две функции — для 3 и 2, они в свою очередь — для 2 и 1 и для 1 и 0 соответственно.</p>
<p><img src="http://hexlet.ru/uploads/images/00/00/01/2010/10/18/555a59.png" alt="" /></p>
<p>Вот <a rel="nofollow" href="http://dl.dropbox.com/u/72746/css/comp%204009/fib.cilk">исходный код</a> этой программы:</p>
<p>В следующей статье мы поговорим о том, как расчитывается масштабируемость параллельных алгоритмов, какие виды шедулинга бывают и какой используется в cilk, а также коснемся сортировки и параллельного динамического программирования.</p>
<p> <img src="http://freetonik.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1869" width="1" height="1" style="display: none;" /></p>
<p>Наши роботы искали похожие записи, но не нашли :(</p><img src="http://feeds.feedburner.com/~r/ComputerScienceStudent/~4/aPhUzN6Be6k" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://freetonik.com/text/uskoreniya-parallelnyx-vychislenij/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://freetonik.com/text/uskoreniya-parallelnyx-vychislenij/</feedburner:origLink></item>
	</channel>
</rss>

