friends [entries|archive|friends|userinfo]
Valery V. Vorotyntsev

[ userinfo | livejournal userinfo ]
[ archive | journal archive ]

Links
[Links:| wikipedia yubnub reader del.icio.us last.fm ]

путь кенгурёнка | reprise [May. 18th, 2008|04:03 pm]

jtootf
[Tags|]
[Current Music |Metallica - Master Of Puppets]

"...теперь нам лень изощряться, оптимизировать код
и интерфейс с дураками мы пишем из году в год
свыклись с мощной машиной, отвыкли от всякого риска

забыли коды комманд, и старых трюков запас
и только ненависть к Windows порою у нас
зажигает огонь в глазах как индикатор хард-диска..."



подумалось...

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

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

в результате та технология, на которой я остановился в данный момент - совмещение высокоуровневого программирования на Haskell с кодогенерацией в более низкоуровневые Тьюринг-языки. построение дополнительного барьера в разработке, использование Haskell в том качестве, в котором обычно программисты используют IDE. тем более что в качестве IDE мне всегда хватало пары-тройки Emacs'ов. генерируемый язык - C, уже хотя бы потому, что я до отвратительного плохо знаю ассемблеры. возможно в дальнейшем смогу перейти на что-то вроде BitC/nesC - там видно будет. во всяком случае хочется верить, что такой подход сработает

да, я понимаю, что подобные сложности нерентабельны в 99% процессов разработки ПО - что ж, буду искать свой 1%. пока же есть время учиться, время совершать ошибки и время их исправлять. ну и зарабатывать на жизнь в оставшееся время

я продал душу за третью заповедь IBM
Link6 comments|Leave a comment

radio astronomy [May. 18th, 2008|12:41 am]

nibot_lab
[Tags|, ]

What is the simplest possible radio astronomy experiment that would be interesting?
Link1 comment|Leave a comment

Imitating greatness. [May. 17th, 2008|08:03 pm]

zestyping

Consider this a sincere form of flattery, then.


Conversations These Days

Link4 comments|Leave a comment

[May. 18th, 2008|12:29 am]

jtootf
[Tags|]
[Current Music |Д'ркин - Мечта]

фраза одного PM'а о нашем отделе : сидит пятёрочка человек и чего-то там колопуцают...

P.S. за душою моей безденежье, да постылое багоборчество...
LinkLeave a comment

[May. 18th, 2008|12:22 am]

jtootf
[Tags|]
[Current Music |Д'ркин - Одиноким]


"...папироску, забитую ветром,
покурю, улечу восвояси
все, что не было — исковеркаю
все, что может быть — приукрасил

я спрошу — не спеши с ответом
походи, погуляй по крыше
если вспомнишь — расскажешь ветру,
я тебя далеко услышу..."





Link6 comments|Leave a comment

Something I should do more often [May. 17th, 2008|06:42 am]

stereotype441
Last night it was too hot to sleep in my bed upstairs so I slept on my front porch.

Also, at one point I dreamt I was wearing white tennis shoes. I looked down at my feet and thought, "what the hell are those doing there?" Weird.
Link2 comments|Leave a comment

Верной дорогой идете, товарищи! [May. 16th, 2008|11:21 pm]

shmyg
[Tags|]

Як заявив біс його знати - паном його не назвати - скажімо так - непан Лавров, Україна, виявляється, сама винна в Севастопольському скандалі. І заборона в'їзду в Україну кепкомордого виродка - недоброзичливість по відношенню до братерського народу. Що ж, непан Лавров є гідним учнем і наступником свого дідуся Геббельса, який казав, що євреї самі винні в тому, що німці їх ненавидять, бо, коли німці працюють, ті накопичують гроші. Так тримати, непан Лавров-Геббельс!
LinkLeave a comment

Мушля та намул/про язык и мову [May. 16th, 2008|01:30 pm]

limetta
[Tags|]

Помните ли ли вы то нелепое время, когда телевизор надо было включать/выключать не пультом, а путем нажатия длинной выпуклой кнопки, и переключать каналы в непосредственной близости к телу?
Помните ли ли вы то странное время, когда по телевизору было к счастью всего три канала?
много букв )
Link60 comments|Leave a comment

Hey Portlanders [May. 15th, 2008|10:46 pm]

stereotype441
...and out-of-town visitors who will be in town on Sunday.

Sunday is the last Sinfonietta concert of the season. You want to come. Yes, you do.

Mozart, piano concerto No.24 in c minor, k.491, with Adria Ye.

Dvořák, Symphony No.6 in D major, Op.60.

3:00pm at Sunnyside Adventist Church, 10501 SE Market St, Portland.

If you need a ride let me know you're on your own. My car is full with my parents.
Link5 comments|Leave a comment

SBCL in Debian testing (lenny): good news [May. 15th, 2008|09:35 pm]
lhealy
[Tags|, ]

Thanks to lots of work and attention from various people:

http://release.debian.org/migration/testing.pl?package=sbcl
Checking sbcl

* trying to update sbcl from 1:0.9.16.0-1 to 1:1.0.16.0-2 (candidate is 12 days old)
* sbcl is going in today
LinkLeave a comment

aut nihil [May. 16th, 2008|02:52 am]

jtootf
[Current Music |Buckethead - Cyborg Slunks]

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



если когда-нибудь я напишу книгу, то называться она будет именно так : aut nihil
это самый сложный выбор - выбор из одного варианта
но как правило их всё же больше

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

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

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

P.S. и, между прочим, ко мне можно прийти в гости на партию в Го ;)
Link61 comments|Leave a comment

The causal structure of black holes, part two [May. 15th, 2008|11:09 pm]

sharp_blue

In the previous part of what has now become an ongoing series on the causal structure of various general relativistic spacetimes, I discussed the causal structure of the flat, Minkowski spacetime of special relativity, and of the Schwarzschild vacuum outside a spherical, uncharged, non-rotating star which collapses to form a black hole. In this part, I'd like to discuss the so-called Kruskal extension of the Schwarzschild vacuum. This is the general solution for a static, asymptotically flat vacuum (that is, a matter-free spacetime that looks like Minkowski spacetime when one is far away from the event horizon) containing a black hole. In other words, this time we'll consider a black hole that exists for all time, rather than one which forms from the collapse of a star.

As commenters have noted, the astrophysical black hole in the last article is not a time-symmetric solution as there's a star early in time and a black hole late in time. The time reverse of this solution is a "white hole", from which matter can emerge into the outside universe but into which no matter can fall. The Kruskal extension of the Schwarzschild metric is time symmetric and it contains both a black hole region and a white hole region (and is thus occasionally called a "grey hole"). The former contains a singularity that is in the future of some lightlike and timelike paths - those that enter the black hole - but in the past of none. Similarly, the latter contains a singularity that is in the past of some lightlike and timelike paths but in the future of none. More surprisingly, the full solution contains two asymptotically flat external regions, each of which is causally isolated from the other!

Causal structure of maximally extended Schwarzschild spacetime
Figure 1 The causal structure of a maximally extended Schwarzschild spacetime

Even though these posts are about the causal structure of the spacetimes in question rather than their geometries, I feel that at this point I ought to say something more about coordinates I've used in this diagram. For observers at rest with respect to the hole and far away from it in one of the asymptotically flat regions, the t coordinate is just proper time as measured on a standard clock. Suppose this distant clock emits a regular "time signal": a flash of light to mark every second of its proper time. An observer elsewhere in the external vacuum who is at rest with respect to the distant clock will not in general receive one time signal flash per second of her proper time. If she's closer to the hole then she'll receive more than one flash per second as measured on her clock. (If she emits her own time signal flash once per second of her proper time, the distant clock will receive them less often than once per second of its proper time. This is the famous phenomenon of gravitational time dilation, which leads immediately to gravitational redshifts and blueshifts. Unlike the time dilation of special relativity its not symmetric with respect to the two clocks.) However, by adjusting the mechanism of her clock so it runs more slowly she can make it tick in synchrony with the time signals arriving from the asymptotically flat region. In this way - provided a timelike hypersurface is chosen as a "zero" of coordinate time - the t coordinate can be extended across the external region.

The r coordinate is much easier to grasp. It's a radial coordinate with respect to the hole that's chosen such that a sphere of constant r coordinate has an area of 4 pi r^2. (Every point in the Penrose diagram is such a sphere at a certain time.) Note, though, that this means that r is not a proper distance (that is, a distance measured by using measuring rods). As the spacetime is spherically symmetric it's easy enough to finish off our coordinate system by picking two angular coordinates, but these won't concern us here.

The event horizon of the hole is at an r coordinate of 2m (where m is the mass of the hole and I'm using coordinates in which the gravitational constant and the speed of light are both equal to 1). (This distance is called the Schwarzschild radius, but it's not, of course, a proper radius.) As I described in the last part, a distant observer watching an object fall into the black hole sees it fall ever more slowly towards the horizon (and at the same time it appears to get ever more redshifted and ever dimmer). The black hole's event horizon is thus at a t coordinate of +infinity. (Remember, though, that the falling object crosses the event horizon in a finite amount of its proper time.) In a similar way, the distant observer sees any objects that emerge from the white hole as having done so infinitely long ago in coordinate time. The white hole's event horizon is thus at a t coordinate of -infinity.

At some future time, I'd like to say something about the causal structure of rotating and/or electrically charged black holes, but in the next part of the series I'm going to focus on the causal structure of open and closed universes.

LinkLeave a comment

жара-жара [May. 15th, 2008|12:42 pm]
lionet
Обещают 41 градус сегодня. Не знаю что там про градусы, но в девять утра весь теннисный корт был полностью засыпан дохлыми мухами!



Вот удивительно — сколько раз слышал про то что "мухи в полёте дохли от жары" и только первый раз в реальной жизни увидел этот феномен. Офигеть. Поиграли сорок минут, хватило.
Link5 comments|Leave a comment

[May. 14th, 2008|11:25 pm]

stereotype441
When I posted two weeks ago about feeling that my life was too busy, I think a large part of the problem was that I wasn't giving myself permission to deviate from my plans to suit circumstances.

Tonight I was planning on going tango dancing. But instead I went to the Cubespace open house, had a nice dinner with [info]stacy_bird, and had dessert at Rimsky's with [info]freyley and [info]linettasky.

I'm sorry I didn't go dancing. I'm especially sorry I didn't get to see [info]akatchoom tonight. But it was great to change plans on the spur of the moment and just follow what was enjoyable. I need to do that more.
Link4 comments|Leave a comment

what you need to do in response to the openssl fiasco [May. 14th, 2008|02:59 pm]

evan_tech

[evan]
If you have used a Debian-based system to generate SSH keys in the past two years, your keys are likely no good. This document has instructions. In brief:

1) Delete your bad keys: .ssh/id_*. Fix all systems where you're trusting those keys (think .ssh/authorized_keys); someone has already published a table of all private keys, so it's just a matter of time before your system is brute-forced.

2) Update your systems. I see an "openssl-blacklist" package show up on both my Debian stable and my Ubuntu whateverletterthey'reon one. You'll get some debconf prompts about it clobbering stuff, including potentially your host keys, which means the next time you connect to the machine you'll get the "host keys have changed" message.

3) To make yourself feel less anxious, try running ssh-vulnkey to print an analysis of keys in standard paths on your system. (Run it as sudo ssh-vulnkey -a to check all users on your system.)
Link8 comments|Leave a comment

Вопрос о реализации эта-редукции [May. 14th, 2008|07:26 pm]

ru_lambda

[codedot]
После довольно продолжительного поиска и изучения литературы по "Explicit Substitions" и "Term Rewriting Systems" первой из найденных статей по эта-редукции к контексте "Explicit Substitutions" стала "Eta-Conversion for the Languages of Explicit Substitutions" (Therese Hardin). К сожалению, в ней не предлагается система, четко описывающая процесс вычисления. Поэтому дальнейший поиск был сосредоточен именно на TRS с эта-редукцией.

Позже была найдена статья "An explicit Eta rewrite rule" (Daniel Briaud), дополняющая вариант лямбда-ипсилон теории "Explicit Substitutions" правилом Eta, описываемым с помощью нескольких "Rewrite rules". Получаемая в результате теория лямбда-ипсилон-эта является TRS с конечным набором правил. Однако, для реализации в виде абстрактной машины эта теория не готова из-за того, что нормальная форма в ней не совпадает с бета-эта-нормальной и не сводится к таковой. Например, следующее выражение, уже находившееся в нормальной форме, редуцируется с помощью правил системы к выражению, по которому восстановить бета-эта-нормальную форму терма уже не представляется возможным ("T-перевернутая" здесь обозначается просто "T"):

x: ((x @ x) @ x) = \((1 1) 1) -Eta-> (1 1)[T/] ->
-> 1[T/] 1[T/] -> T T = (T @ T).

К сожалению, в комбинаторной логике сильная редукция требует бесконечного набора аксиом, поэтому создание машины для сильной редукции на основе комбинаторной логики теряет смысл - гораздо легче при решении этой задачи обратиться к обычному лямбда-исчислению. С другой стороны, прямое примененение эта-конверсии в машинах для редукции графов является крайне неэффективным, так как требует прохода по дереву для проверки на свободное вхождение переменной в подвыражение. В свою очередь, попытки применить подход "Micro Lambda Calculus" (который, кстати, показал себя особенно неэффективным, по крайней мере, при выборе стратегии Gyorgy Revesz) к эта-редукции пока не увенчались успехом.

Вопрос: какие существуют еще варианты реализации эта-редукции, подходящие для создания машины для сильной редукции термов бестипового лямбда-исчисления?
LinkLeave a comment

Печать из emacs [May. 14th, 2008|09:36 am]

ru_emacs

[nikonor]
Есть Ubuntu 8.04. Локаль UTF-8. emacs - 22.1.1.

Помогите понять, что надо сделать, чтобы работала печать текстовая и postscript?
Link1 comment|Leave a comment

type-safe printf [May. 13th, 2008|10:05 pm]

evan_tech

[evan]
[Tags|, ]

printf is a function with a complicated type. In C we used to just give up and tell the compiler "this function takes some other stuff that you shouldn't worry about" with the amusing "..." builtin. These days compilers have special support for annotating printf-like functions to provide type-checking. The other side of this is that an implementation of printf necessarily has a little tokenizer/parser for run-time processing of the format string, along with the associated performance penalty*.

Yet pretty much all programs that involve format strings ought to have the format strings known statically. Even a mini-language like printf turns out to have enough power to not be able to safely process untrusted input, as the "poke" instruction (named %n) demonstrated by creating a completely new class of security vulnerabilities. And without the compiler to help with type coercions, it's easy to write something invalid, especially when you're playing fast and loose with integer and pointer sizes across platforms.

Perl and Ruby neatly sidestep this problem by using string interpolation: at parse/compile time, the compiler scans the strings for bits to be expanded and just rewrites the "format" string to the equivalent concatenation of literal strings and variable values, which then uses the normal language's support for pasting strings together. (Prove it to yourself: perl -e 'use strict; print "$x";' aborts with a "compilation error".) But sometimes you really just want something like printf, and both those languages fall back on "figure it out at runtime" for that.


Supporting printf at all proves to be pretty difficult in more strict languages which generally require all types to be known. OCaml's compiler does some crazy hacks where sometimes a quoted string is interpreted as a format, a six-parameter type that, for example, needs its own concatenation operator. Haskell at least encodes it in the user-available language with some typeclass magic that gets you to more or less to feature parity with dynamic languages -- failure at runtime if the parameters don't properly line up.

But it turns out there's a nice paper that provides a type-safe encoding of printf that doesn't rely on any fancy language features. The paper is structured like this: (1) "wouldn't it be nice if printf worked like this?" (2) "oh wow check it out, here are the functions!" I've been staring at it for a week and though I can sorta see how it works, it's unclear to me how anyone would come up with it. Here's an overview from a person who lacks sufficient brain to say much smarter (me).


To start with, you don't use a string for the format string. This sorta seems like you've already given up, but you could imagine a macro expanding a format string into the proper expression here, much like how Perl/Ruby's interpolation works. Since this is functional code we're talking about, it ends up being an expression involving some functions. Format string concatenation ends up being encodable as composition, which means you end up with the same operator as Perl (.) for pasting them together.

The basic task then is that you need print (some magic here) to be able to give you a function of varying types, depending on what the magic is, so that print format1 3 "foo" can be type-checked that format expects an int and a string. So the type of printf must be (some magic type involving an a) -> a, where the polymorphic a is a function produced by the magic. And here's where the magic drops, painful in its simplicity:

lit :: String -> (String -> a) -> String -> a
lit text k s = k (s ++ text)

int :: (String -> a) -> String -> Int -> a
int k s val = k (s ++ show val)

printf :: ((String -> String) -> String -> a) -> a
printf fmt = fmt id ""


And that's it. lit is what converts a literal string into a format, while int is the placeholder for an int. So "my int is %d\n" would be expressed as lit "my int is " . int . lit "\n". If you drop this in to GHC you'll see that the type of printf (lit "my int is " . int . lit "\n") really is, as you'd expect, Int -> String -- it's waiting for you to give it an int so it can dump out the formatted string. The result of printf is just a plain function, so you do all the normal sorts of things you'd want, like partially apply it or pass it to map. The formatters are plain functions, too, so you can add your own formatter that, for example, can accept a list (as he does in the paper).


So how's it work?

Look at the two formatters, int and lit. The k parameter to the formatters is a continuation: it's where each formatter should pass the string constructed so far when the formatter is done. Then the s input parameter is the string as constructed so far. You can mentally expand printf (lit "foo" . int) as (lit "foo" (int (id))) "", where that empty string is your starting string and id is the innermost continuation which just gives you back the string that's been constructed.

You can also look at int like this, just with some added parens for clarity: (String -> a) -> (String -> (Int -> a)). It takes the continuation as a parameter, and the function it returns is sorta the same shape as the continuation but with Int -> a in place of a -- that's how it tacks on its need for an int to the greater formatting requirement.

But from there... uh, the types just work out. I don't know. It's pretty much magic.


[Edit: a commenter on reddit linked to this discussion of the general technique, which I haven't read yet but looks promising.]


* Though I'd argue you're in a pretty bad place if printf performance is your bottleneck.
Link16 comments|Leave a comment

[May. 13th, 2008|08:26 pm]

stereotype441
Just saw this on a church billboard:

A newborn chick doesn't know it's alive until its world begins to crumble.


Huh.
Link12 comments|Leave a comment

"Войной надо увлекаться!" [May. 14th, 2008|12:49 am]

evgenkriks
128,36 КБ

Киев. Оболонь. Во дворе на скамейке мальчик аккуратно заворачивает снайперскую винтовку в маскировочную сеть. Мальчик одет в полную форму SAS, с погонами и шапкой.
На вид лет 12. Упитанный, домашний, розовощекий.

Read more... )
Link11 comments|Leave a comment

navigation
[ viewing | most recent entries ]
[ go | earlier ]