Публикации с меткой «tools»

Блог python на хабрахабре

Язык программирования Python / Автоматическая активация/деактивация при входе/выходе из папки

Активация virtualenv персонально для меня несколько геморная штука. И даже дело не в том, что активировать сложно — это неудобно. Так что ниже небольшой скрипт, который поможет активировать virtualenv прямо при заходе в папку с проектом.

Vurtseed

Система автоматизации продвижения сайтов

По адресу http://seoautomator.mediavirus.ru/ появился первая работающая утилита. Сервис по очистке HTML'а от вредного дерьма которое генерит Word и прочее. Пока еще думаю в каком виде оформить результат, может быть выводить расцвеченный diff? В общем если кому-то интересно взглянуть на зачаток проекта который работает на Google App Engine, то велком.

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

Даёшь Django в народные массы!

Дебажим джангу

Вроде начал толком писать приложение на Django и, естественно, понадобилось как-то отлаживать приложения. Довольно приятно был удивлён наличием удобных вещей по сравнению с PHP (или может я просто так плохо умею с ним обращаться?):
  1. bdp/ipdb позволяет ставить брейкпойнты в коде и делать пошаговую отладку, конечно, не Eclipse/Visual Studio, но вполне годно к использованию;
  2. django-debug-toolbar, о ней я уже писал, с тех пор там появилась ещё рубрика "сигналы";
  3. django-extensions в связке с werkzeug, про использование extensions для рисования диаграмм моделей я уже упоминал, но вот расширение страницы ошибки до того, что там становится доступна коммандная строка, меня сильно впечатлило.
Сухими словам или картинками объяснять получится не очень демоснтративно, поэтому рекомендую посмотреть неплохие касты от Eric Holscher тут и тут.
Оттуда же я узнал, что даже стандартная страница об ошибке Django информативнее, чем мне казалось (к примеру можно посмотреть участки кода и отправить стэктрейс на dpaste.com).
И ещё складывается такое впечатление, что на Django как-то больше думаешь о строении приложения с архитектурной точки зрения, т.е. как отдельные части взаимосвязаны и, возможно ли какое-нибудь переиспользование кода, а не с точки зрения "вот тут параметр А, надо отобразить табличку в Н строк". Хотя задачка не очень показательная, т.к. не из типовых для джанго, по-моему.

Lazy Crazy Coder's blog

Interesting extension for zc.buildout

This buildout extension will be helpful for those developers, who actively uses different VCS/DVCS in their everyday life and deployment.

Lazy Crazy Coder's blog

Database migration from SQLite to MySQL or Postgres

Script to migrate from SQLite to MySQL or PostgreSQL. Uses SQLAlchemy as middleware.

Lazy Crazy Coder's blog

Yet another GTD tool

I was very busy last month because of a deadline of my current project. And getting things done method was especially useful for me these days.

During last two or three weeks, I tried almost all time management programs for Mac OS X, but have not found any convinient. All of them are overloaded with uneeded features, their interfaces are cluttered with tags, projects, areas and etc..

So, I decided to write my own GTD tool, simple, flexible and convinient. I wrote it in one holiday using python and sqlalchemy. It's name is GTDZen.

GTDZen operates with two item types: Task and Tag. Any Task have title, priority and tags. You can get Tasks by tags, using simple AND-NOT logic. For example, you can show all tasks, related to "work" but not to "today".

Now GTDzen exists as a python module, which is the middleware between user interface and database. Also, it includes a command line interface. I think that this is enough, but you easily could write you own GUI interface for Windows or Mac OS X.

You can find a short tutorial in the README file, on the project's page at GitHub.

Code is licensed under the New BSD License, so feel free to fork it and use it. But I would be very appreciated if you send me some patches.

Lazy Crazy Coder's blog

Yet another GTD tool

I was very busy last month because of a deadline of my current project. And getting things done method was especially useful for me these days.

During last two or three weeks, I tried almost all time management programs for Mac OS X, but have not found any convinient. All of them are overloaded with uneeded features, their interfaces are cluttered with tags, projects, areas and etc..

So, I decided to write my own GTD tool, simple, flexible and convinient. I wrote it in one holiday using python and sqlalchemy. It's name is GTDZen.

GTDZen operates with two item types: Task and Tag. Any Task have title, priority and tags. You can get Tasks by tags, using simple AND-NOT logic. For example, you can show all tasks, related to "work" but not to "today".

Now GTDzen exists as a python module, which is the middleware between user interface and database. Also, it includes a command line interface. I think that this is enough, but you easily could write you own GUI interface for Windows or Mac OS X.

You can find a short tutorial in the README file, on the project's page at GitHub.

Code is licensed under the New BSD License, so feel free to fork it and use it. But I would be very appreciated if you send me some patches.

Lazy Crazy Coder's blog

RopeVim — refactoring tool for Python and Vim

Today I found an interesting project "rope". It is a python library for refactoring python code. Also, it has frontends for vim and emacs. As I am active user of the vim, I wrote a simple script, to simplify installation and update of the ropevim. To try ropevim, you need a Vim with support for python plugins and mercurial, to fetch sources of the rope from repository. If you work under Linux Ubuntu, like me, then you need to do few simple commands, to install the ropevim:

  • First, install the mercurial and vim-python: sudo apt-get install mercurial vim-python.
  • Next, create a directory anywhere in your home directory and download my installation script into that directory.
  • Make script executable and run it.
  • Add one line into your .vimrc to source autogenerated configuration file.

That's it! Enjoy python refactoring with vim and rope. And don't forget to read a ropevim manual with default keybindings.

Lazy Crazy Coder's blog

Using __slots__ for optimisation in python

Do you know anything about python's slots construction? I did't before this day.

But slots in the python exists from version 2.2. It's main purpose is memory optimisation because it allow to get rid of dict object, which created by interpreter for each instance of class.

If you create many small objects, with predefined structure, and meet a memory limit, than slots can help you to overcome that limitation.

But remember, that early optimisation is the root of all evil. Furthermore, slots has many limitations that you need to be aware. For example, you can't use multiple inheritance and must be very careful if usual inheritance too.

As I am very interested in the different optimisation technics, I desided to make a small test.

I have found an interesting python library, that helps to measure memory usage. It's name is Guppy.

So, I write this simple test, which create tuples of one million instances of simple class. Every object hold two attibute 'a' and 'b'. First class is standart, second uses slots to optimise memory footprint.


import sys
import guppy
import time

class Test1(object):
    def __init__(self):
        self.a = 1
        self.b = 2

class Test2(object):
    __slots__ = ('a', 'b')
    def __init__(self):
        self.a = 1
        self.b = 2

if __name__ == '__main__':
    num = 1000000
    cls = Test1

    if len(sys.argv) == 2:
        if sys.argv[1] == '2':
            cls = Test2

    l = tuple(cls() for i in xrange(num))

    h = guppy.hpy()
    print h.heap()

If you run this program without params, it would create a 1000000 usual instances and output something like that:

Partition of a set of 2020446 objects. Total size = 169426216 bytes.
 Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
     0 1000000  49 136000000  80 136000000  80 dict of __main__.Test1
     1 1000000  49 28000000  17 164000000  97 __main__.Test1
     2   4901   0  4178264   2 168178264  99 tuple
     3   9527   0   611920   0 168790184 100 str
     4   1416   0    96288   0 168886472 100 types.CodeType
     5     61   0    89704   0 168976176 100 dict of module
     6    155   0    85784   0 169061960 100 dict of type
     7   1342   0    75152   0 169137112 100 function
     8    170   0    73360   0 169210472 100 type
     9    119   0    68408   0 169278880 100 dict of class

Now run program with one argument '2'. In this case, output will look like that:

Partition of a set of 1020446 objects. Total size = 33426216 bytes.
 Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
     0 1000000  98 28000000  84  28000000  84 __main__.Test2
     1   4901   0  4178264  12  32178264  96 tuple
     2   9527   1   611920   2  32790184  98 str
     3   1416   0    96288   0  32886472  98 types.CodeType
     4     61   0    89704   0  32976176  99 dict of module
     5    155   0    85784   0  33061960  99 dict of type
     6   1342   0    75152   0  33137112  99 function
     7    170   0    73360   0  33210472  99 type
     8    119   0    68408   0  33278880 100 dict of class
     9     65   0    49928   0  33328808 100 dict (no owner)

Pay attention at the top line in the first stats. It states, that 136000000 was reserved to the "dict of main.Test1". Seconds stats does not countain such line because of slots was used for optimisation.

Now we can calculate a profit of the slots in that particular case. It is (136000000 + 28000000) / 28000000 or 5 times! Second run reqire a 5 times less memory than first! It's amazing! But remember about warning you was given to.

Also see these links:

Kinght who said PY!

jython: уже 2.2

Между тем Jython достиг реализации спецификации Python2.2 [>>>]. Пока что только бета, но we call it 'beta' cause it's much betta than nothing.

Собственно Jython это реализация языка Python для JVM. Идея кажется мне странной, но вот Microsoft поддерживает проект IronPython - реализацию питона для .NET.

Kinght who said PY!

pylint: 0.13

Для тех, кому еще понятно слово lint и -Wall. Lint для python. Не сказать чтобы очень хороший, но неплохой. Рикамендед [>>>]

Kinght who said PY!

Shed Skin: компилятор Python в C++

Да, вам не показалось. Это оптимизирующий компилятор Python -> C++ -> Бинарный код. Результаты работают очень быстро, но за все приходится платить - ShedSkin понимает только очень небольшой сабсет языка Python. Изменения в версии 0.0.20:
  • улучшена работа со списками и словарями
  • поправлена работа операций целочисленного деления (/, //, divmod, floordiv), так чтобы они работали по схеме CPython2.5
  • преобразование float в str аналогичное CPython
  • масса исправлений в коде самого компилятора
  • починена наконец то работа с self в статических методах.


Таким образом как вы понимаете работы еще вагон и маленькая тележка, но уже сейчас это очень полезный инструмент. [>>>]

Kinght who said PY!

PyPy: это не то о чем вы подумали.

Не смотря на идиотское с точки зрения русского человека название (впрочем zope это еще круче) PyPy это просто реализация языка Python на самом языке Python. Не спрашивайте зачем - лучше почитайте обзор изменений в версии 0.99.0 [>>>].

Kinght who said PY!

Java2Python

Ну вот. Началось. Java to Python - простой и эффективный способ трансляции кода из Java в Python. [>>>]

Помяните мое слово - скоро появятся человекоподобные роботы, которые пишут на Java и транслируют это дело в Python.

Метки

.net .NET C# .sort 1.2 2009 2010 404 error admin ajax amazon analytics and apache api archlinux asp.net async asynchronous autocomplete bash blender blog blogengine blogs book bootstrap bot bpython buildout byteflow bzr C c plus plus C++ cache cbv Chaco checkio chrome ci ckeditor class based views clojure closure cms cms с удобной админкой code coding style collectd COM comet competition conference ConfigParser contest Context continuous integration CouchDB coverage CppCMS cpyext cpython crud csrf CSS ctypes curl custom model fields cx_freeze cython database db dbm dbqueries debian debug debugging decorator decorators deploy deployment descriptor design dev devconf developers development diveintopython Django django 1.2 django 1.3 django advent django framework django template django trunk django weblog django-admin-tools django-cms django-compressor django-hosts django-piston django-registration django-sphinx django.admin djangoadvent djangocms djangodash doc documentation drupal e-legion eclipse EGit emacs encoding Enthought epoll erlang event exception ExtJS fabric facebook fastcgi finaloption fixtures fonts forms formset fp framework freebsd freeswitch fs2web ftp fun funcparserlib functional gae gamin gandi generic views gettext gevent gil git github gitosis Google Google App Engine google picasa Google Translate google wave Google Web Toolkit grab grablab greenlet gtd gui haskell hg hgshelve highlighter host hosting how-to howto html html5lib Hudson humor i18n icfpc ide idiomatic image-scripting improvements Internet interpreter ipython ironpython izmenimsya.ru jabber java javascript jenkins jetbrains JIT job jquery json jstree jython kde kiev kiyv kyivpy l10n ldap library libs Life Links linux Linux & Unix LLVM logging logs lxml Mac OS X magic mail markdown Matplotlib Mayavi maybe mediavirus meetup memcache Memcached memory messages metaclass middleware migration mikrotik mkd model models mod_python mod_wsgi mongodb monitoring mptt musicmans.ru musicx mvc my-projects mysql netCDF networkx newforms newforms-admin news nginx Nhibernate nix nose NoSQL numpy oop open source OpenID openoffice opster optimization oracle orm os pagination parsing path patterns pdf PDF-принтер PEP PEP8 performance performance optimization perl personality photo php picture-driven computing PIL pinax pingback pip plasma plone plugin plugins postgresql programming progress bar psycopg2 py2exe pybb pybbm pycamp pycharm pycon pycow pycurl pydev pygtk pylons PyNGL pypy pyqt PyQt4 pyrad pyramid PySide Python Python 2.5 python 2.7 python 3 python c api python speed python-mssql python3 pywinauto Qt Qt4 queue rabbitmq radius raw sql re redis redsolution redsolution cms regexp regular expressions release repoze.bfg RequestContext reusable apps robokassa rss ru ruby ruby-on-rails sample satchmo scalability SciPy scraping screencast search selenium self.error seo server setattr settings setuptools shell sikuli sms snippet socket.io software sorting south sphinx spider sql sqlalchemy sqlite ssh startup step-by-step subdomain subversion svn SyntaxHighlighter system tags tdd tddspry teh drama template templates templatetags test testing thinkpad threading threads tips tips and tricks tools tornadio tornado tornado server tricks tutorial tweepy twisted twitter typography uapycon Ubuntu ucsvlog uml Uncategorized unicode unit test unit testing UnitTest Unladen Swallow upload urllib urls utf-8 uwsgi validation vcs versioning video vim virtualenv Visual Studio vkontakte voip wave web web-devel web-services web-разработка webdev webfaction webkit webpy websockets webtest widget widgets Win API windows Wirbel work wrapper wsgi wxPython wxWidgets wysiwyg xapian xml xmonad xmpp xpath yandex youtube zip zomg zope [cdata[cbv]] [cdata[ci]] [cdata[class based views]] [cdata[continuous integration]] [cdata[django framework]] [cdata[django-sphinx]] [cdata[django]] [cdata[nginx]] [cdata[python]] [cdata[virtualenv]] [cdata[программирование]] автоматизация администрирование администрирование django админка алгоритмы архитектура атрибуты базы данных Без рубрики безопасность библиотеки блоге бот веб-разработка видео Визуализация данных вконтакте Все записи гвидо ван россум граббер графика графы декоратор декораторы дескриптор дескрипторы документация заметки игра жизнь идея интересное киев Клиентам книги конференция личное математика метаклассы модели модули монады морфология мысли невозможное новости о облачные вычисления обо мне Обработка данных оптимизация оптимизация кода Основная лента основы парсинг парсинг сайтов перевод песочница Питон поебень поиск правила кодирования программирование Проектирование производительность работа рабочее размышлизмы Разное разработка разработка приложений разработки регулярные выражения сайт событие события ссылки статьи тестирование тесты Тюмень убунтариум фигня философия формы форум Хабрахабр хакинг хостинг шаблоны шаблоны проектирования эксперимент Эксперименты юмор я пиарюсь Яндекс