Archive for the ‘software’ Category

Code review

Tuesday, February 5th, 2008

Жизненное via boris:

Code Review

Техника безопасности при стрельбе

Thursday, October 18th, 2007

Wired пишет про трагически закончившиеся испытания ПВО-шного Эрликона в Южной Африке: 35мм спаренная турель вышла из под контроля при испытании боевыми снарядами и выложила весь боевой запас в 250 снарядов вокруг себя, убив 9 человек и ранив еще 14.

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

Mangope told The Star that it “is assumed that there was a mechanical problem, which led to the accident. The gun, which was fully loaded, did not fire as it normally should have,” he said. “It appears as though the gun, which is computerised, jammed before there was some sort of explosion, and then it opened fire uncontrollably, killing and injuring the soldiers.”

Other reports have suggested a computer error might have been to blame. Defence pundit Helmoed-Römer Heitman told the Weekend Argus that if “the cause lay in computer error, the reason for the tragedy might never be found.”

Гусли-самогуды, сапоги-самоплясы

Thursday, October 4th, 2007

Гибсон подписал контракт с немецкой фирмой Tronical на выпуск самонастраивающихся гитар. Уж теперь-то я точно стану рок-звездой! Самое главное ведь что? Чтобы гитара была правильно настроена! :) А что там бренькать на ней - уже не важно (взять хотя бы весь русский рочок).

Система состоит из моторчиков на грифе, которые вращают колки и натягивают струны, а также из датчика и ручки настройки на корпусе гитары. Ручкой устанавливаем нужный строй (A, B, C…) и бренькаем по струнам, чтобы звучали. Моторчики сами подтягивают и отпускают струны, пока все не войдут в лад.

Выглядит все это примерно вот так:

Tuning knobGuitar neck

Почитать подробнее можно на сайте у производителя и у Гибсона

Настройка гитары

Thursday, October 4th, 2007

Гибсон подписал контракт с немецкой фирмой Tronical на выпуск самонастраивающихся гитар. Уж теперь-то я точно стану рок-звездой! Самое главное ведь что? Чтобы гитара была правильно настроена! :) А что там бренькать на ней - уже не важно (взять хотя бы весь русский рочок).

Система состоит из моторчиков на грифе, которые вращают колки и натягивают струны, а также из датчика и ручки настройки на корпусе гитары. Ручкой устанавливаем нужный строй (A, B, C…) и бренькаем по струнам, чтобы звучали. Моторчики сами подтягивают и отпускают струны, пока все не войдут в лад.

Выглядит все это примерно вот так:

Tuning knobGuitar neck/>

Почитать подробнее можно на сайте у производителя

Хакерство

Wednesday, October 3rd, 2007

Вчера мне нужно было заглянуть в “настольную книжечку нотариуса”, чтобы освежить память по паре вопросов. Обычно она лежит в pdf формате на сайте Secretary of State, и я себе этот пдф забыл скачать. Иду на сайт, а сайт лежит! И вообще не отвечает.

Поудивлялся и забыл. А вот, оказывается, почему сайт лежал (линк будет жить не вечно, поэтому скопирую сюда часть текста):

SACRAMENTO — A hacker who directed people from a county website to pornography triggered a federal shutdown of state government Internet and e-mail service late Tuesday afternoon, according to a spokesman for Gov. Arnold Schwarzenegger.

The state system, which uses the domain name “ca.gov,” was never hacked and all of its websites and e-mail should be functioning within a few hours, spokesman Aaron McLear said.

He said the federal government moved to suspend the state’s Internet and e-mail service after someone hacked into a county website that contained the domain name ca.gov and redirected people to a pornography site. McLear said he did not know which county website was hacked.

Короче, какую-то страничку округа задефэйсили и перенаправляли всех на порнуху. А федералы это дело просекли и не мудрствуя лукаво просто закрыли весь .ca.gov домен вместе с почтой и всем остальным. Ловко.

Переезд

Wednesday, September 19th, 2007

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

А вот отличная штука для антрепренеров: Sandbox Suites. Вместо того, чтобы брать в лиз офис, подключать туда всю инфраструктуру (электричество, интернет, телефон и т.п.) можно просто подписаться на “горячий стол” в разных планах: от одного дня в неделю до полной недели. Без лизов, без всего. Надо встретиться с клиентами - пришел, сел за стол и встретился. Стол полностью подключен - поставил лэптоп и работай себе. Кого в офисе почти не бывает, а офисное место нужно - идеальное решение.

Надеюсь, у них дело пойдет, и они до Сан Хосе тоже доберутся.

Google Checkout Experience

Friday, July 27th, 2007

Пару дней назад первый раз воспользовался Google Checkout. В качестве рекламной кампании, там пока что никаких поборов с продавцов не берут - в отличие от business account на PayPal.

Ну что сказать - с пэйпалом и рядом пока что не лежало в плане удобства и сервисов. Юзабилити не то что плохой - он еще и опасный довольно. Сделавно все на Ajax, в результате вместо привычного “нажми на кнопку - получишь результат” получается примерно такое:

- сделал инвоис
- нажал на кнопку “отправить”
- нарисовалась маленькая хрень горчичного цвета “отправляю инвоис”.
- маленькая хрень исчезла, а я остался на той же странице в недоумении. Может не сработало чего? Нажал на кнопку еще раз. На третий раз Штирлиц догадался, что так и задумано - когда в инбокс повалились идентичные копии инвоисов.

Ну ладно, лиха беда начало: отправил два инвоиса вместо одного - клиент разберется. Так там еще и карточку можно по одному инвоису биллить до бесконечности: нету перехода между страничками “нажал - сделано” и кнопка “charge” даже не дисэйблится.

Превед.

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

В ообщем, года через два, может быть, догонят Пэйпал. Я, правда, не знаю, как там с customer service - в фин. системах это ведь практически самое главное.

Photoshop script

Tuesday, June 12th, 2007

Написал скрипт для Photoshop CS3, который делает рамку вокруг фотки, ставит лого в правом нижнем углу и подводит guide к этому лого, чтобы в левом углу можно было название прописать на том же уровне.

Результат выглядит вот так

Скрипт брать вот здесь:
http://www.pneyman.com/downloads/

Почему не action? А потому что action ваши действия запоминает в абсолютных координатах, и если фото будет отличаться по размеру, то лого уедет бог знает куда. А скрипт работает в относительных координатах :)

Чтобы поменять текст лого и фонт - поменяйте первые две строчки скрипта (logoText и fontFace)

Flex 2, Adobe. Teh Suck.

Saturday, February 3rd, 2007

Recently I had a project at work where we wanted to integrate Adobe Flex 2 technology with our product. For those, who don’t know what Flex 2 is, it’s a glorified JavaScript with elements of Flash in it. A nice web2.0 tool if, and I stress it, if they had implemented it properly. Unfortunately, as of now, their third iteration (Action Script 3.0) is still pretty buggy, and lacks in documentation.

So, here are a couple of gotchas I ran into. Chances of Google indexing it, and people looking up this post when they are scratching their heads trying to figure out why the stuff doesn’t work, is pretty slim. But still. I ran into a post like this on some random blog while googling around for an answer, so maybe this post would be useful to someone else.

1. Always use unique loop counter names.

Variables you declare in for() loop do not get garbage collected as soon as you exit the loop. In fact, they live even after you exit the function call. I had a situation where I had a counter ‘i’ declared in a loop in a callee, and another ‘i’ used in a loop in a caller. My generated ’swf’ was behaving extremely erratically: debugger was showing that each loop was executing properly, however, the browser was crashing and hanging reliably with every launch. I suspect the garbage collector was either sweeping up the wrong counter or doing some other wacky stuff. Nothing worked until I renamed one of the loop counters. To avoid situations like this in the future, I made a rule: always use unique loop counter names. Cumbersome? Yes. But it could save you a day of debugging.

2. Event model is weak and poorly documented

I used a DataGrid component to display data coming over. DataGrid can figure out columns by default, based on the data provider, or you can specify the columns manually, thus enforcing their displayed order. In our case, we do not know the number of columns in the data coming over, so we can’t hardcode it in the mxml layout code.

I tried to dynamically bind not only the data provider, but the columns Array as well: as soon as I figure out the columns myself in the first batch of data - update the Array, and you are done. Right? Wrong. Much to my dismay I discovered that no matter what I stuffed in the Array with push() call, the DataGrid always displayed the columns how it wanted (alphabetically sorted). After several hours I gave up and asked for help on the newsgroup.

The answer? Push() call does not generate an event. And since it does not generate an event, DataGrid will never detect that array changed, and will never take it into consideration. Awesomeness. Pure awesomeness. You have to do something on the order of myArray = myArray.concat(newArray) to force it to update itself. I challenge and Adobe engineer to show me a place where this is documented, and explain me why it is so in the first place.

Btw, the DataGrid still doesn’t work. I think establishing columns dynamically is just impossible with ActionScript 3.0: while the array gets updated in the callee, it remains unchanged in the caller (which is DataGrid in this case). A serious bug? I bet.

3. Security model is even worse

Now, this is my pet peeve in Flex 2: their security model. I don’t know what kind of crack they smoked when they came up with this, but we have to deal with it now. They took the security model from JavaScript and botched it even more.

In Flex 2, you protect the server side. That is, your client application running on server A is not allowed to make a crossdomain call to server B, unless server B places a special crossdomain.xml file in the root of its webserver.

Now seriously, did anyone at Adobe think for a minute that this is not going to fly in the real world? Let’s say I want to obtain some data from a public server via an Http request. Do I have to write to their admin guy and ask them to place some stupid xml file and add all the possible domains in it, so that I could query it? No shit, Sherlock.

People have expressed their dissatisfaction about this security model all over the web. Adobe’s response? Run a proxy! Or, better yet, buy a Flex Proxy from us, which, by the way, is sold as a separate product, and requires separate license. Awesome.

To add insult to injury, the cross-domain check inside Flex 2 is fubared. The spec clearly says: in order for the client to talk to the server and not violate the sandbox security, they have to be in the same domain. Unless something has changed and Jesus came again, this means that the domain name (and maybe port) for the client and server have to match. That’s all.

Not so in Flex 2. By trial and error we discovered that they match the path as well. That is, a client running on http://mydomain.com:111/pathA cannot talk to http://mydomain.com:111/pathB without violating the sandbox security. Great. Again, either update the goddamn spec or fix the check call (I suggest the latter).

Oh, and one more thing: we decided to trace what exactly goes over the wire when Flex 2 performs the check, and it’s not even a valid HTTP request. It sends and XML snippet! Why? I don’t know. Perhaps because Adobe is heavily pedaling their Flex Data Services platform which is supposed to run on a webserver and enable runtime compilation of MXML. Maybe it intercepts this XML snippet and responds to it. Who knows. All we know is that this is not even a valid call. Good job.

4. Careful with SharedObject names

You save and load SharedObject by name. As it turns out, not all names are created equal. My test flash was running with a name like ‘foo’, and it was behaving properly. We loaded it into staging environment - and … nothing happened. Time to debug. Debugging in Flex 2 sucks as well, but that’s another story. So, our staging environment does not have a debug version of Flash player, so I connect from my desktop. Boom - I get an exception “Could not create a SharedObject”. Thank you, Adobe, for such a helpful error message. Really, why would anybody be interested about the reasons SharedObject could not be created?

The magnificent Adobe Flex 2 documentation has this to say: “an exception will be thrown if SharedObject could not be created for whatever reason”. That seriously helps! Where would I be without documentation like that? After about 30 minutes of checking and double checking storage and security settings, I realized, they had nothing to do with the creation failure. A Google search yielded about a dozen links with the same unhelpful Adobe documentation, and one random blog link which gave me a clue.

That blog described exactly how Flash player stores SharedObjects on the client’s machine. They usually go in “C:/Documents and Settings/username/Application Data/Macromedia/Flash Player/domain_name/shared_object_name”. What if the name we supplied could not be accepted by Windows and throw an exception? I checked the page source on the staging environment, and sure enough: we had a name like ‘_foo_’ being passed in.

As soon as we got rid of front underscore, the app started working. Poor name choice? Perhaps. But was there anything in the documentation about limitations on SharedObject names? Nope. Was there any hint or indication in the exception about the reason it occurred? Zip. Nothing.

*sigh*

5. Debugging

I could write another paragraph about how debugging in Flex 2 sucks, and their integration with Eclipse 3.2 doesn’t fully work, but I’m too tired. I think Adobe has to do a couple more iterations of their technology before I will touch it again.

Проводка телефона

Thursday, October 20th, 2005

Программист и цветные проводки.

Нужно в доме поставить вторую линию. Заказали у SBC - пришел мужик и включил тон на коммутаторе. За внутреннюю проводку они берут сумашедшие бабки, а делов там на самом деле немного (важно подумал я).

Пришел вечером с работы с новенькой телефонной розеткой на два джека и полез подключать.
Открываю коммутатор. Тэкс, что у нас тут. Зеленый-красный, желтый-черный на две линии. Все тривиально. Эх! Решительным жестом втыкаю свободную черно-желтую пару первой линии на черно-желтые клеммы второй линии. Ага. Логик хренов.

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

Включаю телефон. А там: ….
Так.

Беру вольтметр, иду к коммутатору. На улице темень. Зажав фонарик между ухом и плечом, мерю клеммы. Ой, а что это на черно-желтых ничего нет? Ой, а вот они 50 вольт, на зелено-красных. Решительно перетыкаю провода и включаю трубку радиотелефона. А там: ….

Так. В доме розеток не то что много, а… по одной в каждой комнате, и все подключены друг через друга. Беру отвертку и вольтметр и начинаю проверять. Розетка в гараже. Напруга есть. Розетка в кухне. Напруга есть. Розетка в спальне (пыхтя отодвигая кровать). Есть. Розетка в офисе (пыхтя отодвигая диван). Напряжение - есть! А тона - нет! Меня черно-желтые местами (типа crossover сделал!) - результатов ноль. Странно. Логика подсказывает, что напряжение -50В - неправильно. Меняю назад. Тона нет.

Долго чешу в затылке.
Иду в интернет. Читаю инструкции по разводке. А че это они, дураки, черно-желтую пару на зелено-красные включают? Делать что ли нечего? Ой, подождите! Подождите!

….

В общем, заработало в конце концов :)