Категория: Компьютеры

Заметки о программировании и на околокомпьютерные темы

Вложенные категории: Delphi, Игры

О закладках

Идею закладок (bookmarks) давно надо расширить, глядя на то, как люди их используют (точнее, не используют):

  1. Закладка должна по возможности сохранять кешированную копию страницы.
    Часто сохраняешь ссылку не на ресурс, а на какой-то полезный материал, и неудобно, что он может исчезнуть. Фактически, это убивает смысл таких закладок. Приходится вести какие-то сторонние хранилища заметок, копировать нужные тексты. Гораздо лучше, чтобы в закладке сохранялась текущая копия страницы, ну и её можно было обновить по желанию.
  2. Табы должны быть закладками.
    Держать открытыми больше 20 табов – это глупо, т.к. уничтожает все преимущества табов. И тем не менее, люди так делают. Почему? Потому, что люди бестолковые. Похоже, по двум причинам: табы привычны и на виду, и табы помнят, где ты остановил чтение. Значит, надо добавить эти же функции закладкам, и сделать табы особым их видом: таким, который показывается как открытые страницы, а не в меню. Хотите хранить свои закладки кучей и на виду – пожалуйста.
    Технически это очень хорошо, т.к. табы невозможно будет потерять случайно при закрытии, они будут синхронизироваться между компами, не обязательно загружать все 200 табов при старте браузера и памяти они до первого обращения тратить не будут. Единственный минус – загромождение табов по-прежнему неудобно, но это уже проблемы того, кто так делает. Сам себе злобный буратино.
    Ах да: и легко будет сделать папки табов, о которых многие мечтают
  3. Стеш должен быть встроен в браузер.
    Стеш – это такое место, куда кидаешь найденное в интернете, чтобы прочесть как-нибудь позже. У многих это место – открытые табы, увы. У других это корень букмарков. Где бы это ни было, там образуется бардак. Надо, чтобы в браузере для него было отведено специальное место, с которым удобно было бы работать.
    Вообще-то, никто не мешает сделать отдельную папочку в закладках, назвать её “Стеш”, вытащить на панель инструментов и пользоваться. Но никто так не делает – то ли в голову не приходит, то ли неудобно. Так что браузер должен делать это сам. Для тех, кто предпочитает хранить всё табами, можно сделать галочку “Отображать стеш как табы”.
    Что-то такое пытается сделать новая Опера.
  4. Speed Dial, панель быстрого запуска, боковые панели, быстрый поиск – это всё должны быть подвиды закладок.
    Потому, что незачем плодить сущности. Плохо, когда нужно вспоминать – “вот этот сайт с панели быстрого запуска есть у меня в закладках или нет”. Ну как же его может не быть, когда вот он на главном экране.
    Это у многих браузеров сделано, особенно у Файрфокса – во всём. У Оперы в части панелей.

Если какой-нибудь браузер всё это сделает, цены ему не будет!

pyoperalink: certificate verify failed

If you're trying to use pyoperalink and you're getting certificate verification errors:

httplib2.SSLHandshakeError: [Errno 1] _ssl.c:507: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

That might be because libhttpd2's root certificate list is too short (I don't know why).

Quick solution: Download this cacert.pem and save as Python\Lib\libhttpd2\cacerts.txt or Python\Lib\site-packages\libhttp2\cacerts.txt. You'll need administrator privileges and make a backup of cacerts.txt beforehand.

Ostensible explanation: Certificates are chained: there's a handful of root certificates which are used to sign site certificates or second-layer certificates and so on. Open auth.opera.com and study the certificate (in Opera you have to click the green placard in the address bar). At the time of writing the topmost certificate in its chain is "DigiCert High Assurance EV CA-1".

Open cacerts.txt. This is the root certificates libhttpd2 understands. Search for "DigiCert" or "Digi": no matches. Thus, libhttpd2 does not trust the "DigiCert High Assurance". It has to be added to this list. "Quick solution" does this by replacing the file with a longer list of trusted certificates extracted from the list at mozilla.org. You can use any other list in compatible format which contains root certificates you need. (You should study the source before copying it because I may be malevolent or mistaken myself).

Restore deleted notes in Anki

Sometimes you accidentally delete notes/cards in Anki. Ctrl-Z can revert one deletion, but several notes cannot be restored. If you use Anki Sync and haven't done any important edits locally, you should simply delete the collection and redownload it. But what if you don't want to lose local edits/reviews?

Note: If you have Sync enabled, do not sync at any point throughout this instruction. Pull out the network cable, disable Wi-Fi etc, to stop Anki from accidentally uploading your collection midway.

  1. Close Anki.
  2. Go to My Documents and zip the whole Anki folder. Put the archive in the safe place.
  3. Revert the collection to an older date:
    • Go to My Documents\Anki\YourProfile\Backups and choose a backup from when you have not yet deleted the cards.
    • Start Anki, wait until it loads, then double-click the chosen .apkg file.
    • Anki will say this will replace your collection, confirm it.
    • You have now reverted the collection to the older date.
  4. Export the broken deck:
    • Go to File->Export.
    • Choose "Export format: Anki deck package".
    • "Include": the deck where the deleted cards were.
    • Include sheduling information and media.
    • Press "Export" and save the file somewhere outside of Anki folder.
  5. Restore the current deck state
    • Close Anki.
    • Delete the My Documents\Anki folder
    • Unpack the zip file you have prepared before
    • Make sure the contents of My Documents\Anki folder is as before (no double Anki\Anki folders etc)
  6. Start Anki
  7. Double-click the saved deck .apkg file and let Anki import it
  8. Missing cards are imported with all their history.

Не печатайте домен

Многие забывают, что тэг a href можно использовать без домена:
<a href="/path/">
Поддерживается всеми браузерами с незапамятных времён. Выгода двойная: меньше печатать, и если когда-нибудь перенесёте сайт – не придётся менять адреса.

В сочетании с умением вордпресса находить пост или страницу только по их ярлычку (slug), это позволяет писать вот такие замечательные ссылки:
<a href=opera>Полезные заметки по браузеру Opera</a>
Также можно указывать путь относительно текущей папки <a href="./path/">

Apache cannot serve files with unicode filenames

I've had a problem with my Apache setup where it couldn't serve images with unicode characters in file names:

 <a href="http://www.boku.ru/img/проверка.jpg">http://www.boku.ru/img/проверка.jpg</a> (really missing right now; just an example)

SCP client (WinSCP) clearly showed files were present, other files from the same folder could be accessed but those with cyrillic characters were returning 404.

Using Wireshark, I determined my browser sends urlencoded text (B0%D0…) instead of bare unicode, but that was, apparently, like it should be.

Studying Apache logs, I've found it complain about missing files, re-encoded in \x notation (\xb0\xd0…). For a while I thought this suggested a problem, but in the end it was unrelated and probably correct behavior.

Turns out, WinSCP does not use UTF-8 by default. Instead it sends file names to server in the local PC encoding, Win-1251 in my case. Looking through WinSCP everything seemed alright because it reads filenames back in the same encoding. But from the server point of view (as seen through SSH for example) those were not Russian characters but some Krakozyabry.

In other words, there really was no проверка.jpg.

To recongifure WinSCP, open Site manager, press Edit, Advanced, "UTF-8 encoding for file names: On", then reconnect. You'll have to rename all affected files.

WordPress not remembering name or email for anonymous commenters

Someone reported that WordPress at boku.ru hasn’t been remembering the name and email which you enter in comments. I vaguely remembered this working before. After some investigation, turns out it was W3 Total Cache plugin which uses comment_cookie_lifetime filter to drop standard WordPress cookie lifetime from half a year to 30 minutes. And since my site runs as GMT, this was eaten by the 4-hour time difference.

W3 Total Cache did that because for cookie-less visitors it serves fast static version of the page (which can not be tailored for each visitor and have their name pre-entered, the way names are handled now). As long as you have posted a comment, you receive a cookie and WordPress serves you slower, dynamic version of the page. So the longer the cookie lifetime is, the longer you’re going to be served dynamic pages (but the longer your settings are going to be preserved).

This setting can be changed at “Performance > Page Cache > Advanced > Comment cookie lifetime”.

If you’ve stumbled upon this post while solving a related problem, here’s some additional pointers:
1. WordPress stores commenter name/email/url in cookies:
comment_author_*
comment_author_email_*
comment_author_url_*

An example of how querying for these values should look like is in /wp-includes/comment-template.php/comments_template()

2. Your comment form is generated either by this, or by customization hook in your theme’s comments.php.

3. To debug cookies, add print_r($_COOKIES); to your theme’s header.php, don’t forget to remove it later. Use Wireshark or your browser’s request sniffer to track what’s being sent.

Всегда занят

Invisible – бесполезный режим в мессенджерах, поскольку всё, что он делает – это пытается забанить человека под благовидным предлогом, не портя с ним отношения, и длится это ровно до первого раза, когда вы спалитесь, ответив из инвиза.
Ну, конечно, есть умельцы, которые из принципа постоянно в инвизе, и это правильно, поскольку создаёт основания для plausible deniality, но тогда они вообще не пользуются статусом, получается.
Гораздо убедительней было бы “‘Занят/нет на месте’ для этого человека”. Во-первых, даже если вы заняты, вы можете отвлечься и ответить, когда захотите. Во-вторых, существует тысяча причин иметь такой статус постоянно (например, вы выставили его на мобильнике, т.к. оттуда общаться неудобно).

Чтобы действительно познакомиться с товаром перед покупкой, нужно искать в гугле “[товар] отстой”, “[товар] глючит”, “[товар] не покупайте”. А чтобы проверить, нельзя ли в программе случайно спалить свои личные данные, нужно погуглить “[программа] расшарить данные”. У вас и у этих людей дополняющие друг друга цели: вы хотите исключить любую лазейку, а они – какую-нибудь найти.

Can you repeat that?

Reading personal experiences on trimming the sizes of Delphi executables, I often encounter stories like this one:

I’ve moved from Delphi 2007 to Delphi XE3 and my executable went from 3Mb to 18Mb! I did this thing and that thing and disabled RTTI and set these flags and got the executable down to 16Mb. Nice, but not enough.
Then I discovered UPX and it reduced the size to 3.5Mb! UPX is magic!!

This is obviously wrong, it should make anyone with half a pint of a sense cringe – but why is it wrong? They got their size down. That’s what they wanted.

And then I figured:
Well, you got it down to 3Mb. Can you repeat that?

If Delphi XE8 comes out and your executable is suddenly 17Mb again, what are you going to do to trim it back? If you had spent several hours more and actually understood what happened and how to unhappen that, then you’d still be on a fair footing with the circumstances. Your trump card of using UPX and being excited would still be with you. And now it isn’t.

Right-click to copy web path for the file

Everybody who uses Dropbox have probably seen that you can right-click the file and “Copy shared path”, under which it is accessible in the internet.

I thought it would be nice to have similar functionality for BTSync and wrote the following sсript.

Code on pastebin.

Usage: put the code into “Copy links.cmd”, drop the shorcut to it into “C:\Users\[your username]\AppData\Roaming\Microsoft\Windows\SendTo” or wherever Sent To folder is in your versions of Windows.

Now suppose you have a folder C:\Download\images which is BTSync-ed to your server as http://example.org/lib/img. Create a file C:\Download\images\path.txt and write the above web base path to it.

Now select some files, right-click them and press “Send To -> Copy Links”. Web links for all the selected images are copied into your clipboard:

C:\Download\images\test\file.png --> http://example.org/lib/img/test/file.png

The sсript can also be used if you have a web server running at home which presents some of the files on your PC to the outside world, or even if you share some files and want to copy those as “\\mypc\share\path”. Since the sсript looks for the first available path.txt in the parent directories, you can link different folders to different addresses, or even copy and modify the sсript so that the same folder is linked to several base paths (“Copy as web address”, “Copy as local \\share”).