Архив рубрики: all

update iptables

iptables -L -n --line-numbers

удалить по названию группы и номеру строки:

iptables -D NAME_OF_CHAIN NUMBER_LINE

удалить группу:

iptables -X NAME_OF_CHAIN
service iptables save
service iptables restart

backup:

iptables-save > /etc/iptables.rules

vim /etc/init.d/iptables

    echo -n $"${IPTABLES}: Setting chains to policy $policy: "
    ret=0
    for i in $tables; do
        echo -n "$i "
        case "$i" in
+           security)
+               $IPTABLES -t filter -P INPUT $policy \
+                   && $IPTABLES -t filter -P OUTPUT $policy \
+                   && $IPTABLES -t filter -P FORWARD $policy \
+                   || let ret+=1
+               ;;
            raw)
                $IPTABLES -t raw -P PREROUTING $policy \
                    && $IPTABLES -t raw -P OUTPUT $policy \
                    || let ret+=1
                ;;

link_to with params

The simplest form

The most common and straightforward way of using link_to is to create a barebones (no magic) link. So, assuming your root route points to ‘/’, the way you would use the helper is:

<%= link_to "Home", root_path %>
# => <a href="/">Home</a>

Another common variant is linking to a resource (a user’s profile for example). Let’s say the user’s model is called User and that a@user ivar points to the user record who’s id is 1. Creating a link to the user’s profile will look like the following:

<%= link_to "Profile", user_path(@user) %>
# => <a href="/users/1">Profile</a>

There’s also a shorter version that will do the same thing. It’s got some magic to it (like most things in Rails) but it also looks prettier and there’s less to type (two stones with one bird).

<%= link_to "Profile", @user %>
# => <a href="/users/1">Profile</a>

Using link_to with a block

This is somewhat of a lesser known/used option of link_to but it’s useful nonetheless and it also makes the code more readable. So in those cases where the link text is long and/or ugly, or it doesn’t really fit on a 80 chars line, you can pass the link text inside a block.

To make the example more obvious, I’m gonna do a before and after kind of thing.

Before: ruby <%= link_to "<span class='home-link'>Home</span>".html_safe, root_path %> # => <a href="/"><span class="home-link">Home</span></a>

After: ruby <%= link_to root_path do %> <%= content_tag :span, "Home", :class => "home-link" %> <% end %> # => <a href="/"><span class="home-link">Home</span></a>

link

In this case I’ve purposely chosen a less uglier link text, but usually the link text will be something like an image tag or a span with an icon inside it (or any other ugly html code you can think of).

Another very common task you’ll use is to add a html class or id to your links.

<%= link_to "Section", root_path, :class => "my-class", :id => "my-id" %>
# => <a href="/" class="my-class" id="my-id">Section</a>

How to delete a record with link_to

Calling the destroy action of a REST-ful controller requires aDELETE request and that can be easily achieved by passing the:method => :delete hash as an option to the link_to helper.

<%= link_to "Remove", @user, :method => :delete %>
# => <a rel="nofollow" data-method="delete" href="/users/1">Remove</a>

Note that the rel="nofollow" is auto-magically added by Rails as an SEO bonus.

Require confirmation for deleting a record

You will probably want some sort of confirmation when removing objects to prevent accidental deletes. The easiest way to add that is with a simple javascript alert box that will ask the user to confirm his delete request.

<%= link_to "Remove", @user, :method => :delete, :data => {:confirm => "You Sure?"} %>
# => <a data-confirm="You Sure?" rel="nofollow" data-method="delete" href="/users/1">Remove</a>

It might be that you want to make your links prettier or that you want to have some nice buttons, or even a logo click-able or whatever the reason for using click-able images is, you’ll want to add your image inside the link. Making an image link-able is pretty straight forward. Just add the image_tag where the link text would go and you’re done.

<%= link_to image_tag('logo.png'), root_path %>
# => <a href="/"><img src="/assets/logo-c88948e05e11587af2c23747862ca433.png" alt="Logo"></a>

You can also pass the image in a block if you like that style better.

<%= link_to root_path do %>
  <%= image_tag('logo.png') %>
<% end %>
# => <a href="/"><img src="/assets/logo-c88948e05e11587af2c23747862ca433.png" alt="Logo"></a>

A nice side-effect of using the image_tag helper is that it will add the asset digest to your image.

Adding an alt attribute to the image

As you’ve seen in the previous example, I didn’t specify an alt attribute but the link_to helper generated one. The generated alt tag is just the name of the image file, capitalized. In case you want (and you should want) to override the alt attribute, it’s very easy to do; just add your own alt attribute like so:

<%= link_to image_tag('logo.png'), root_path, :alt => "MyLogo" %>
# => <a href="/"><img src="/assets/logo-c88948e05e11587af2c23747862ca433.png" alt="MyLogo"></a>

Alt attributes are beneficial for SEO purposes and they also aid those visitors who use text readers or non graphical browsers.

There are times when you might want to link to an image (not necessarily with an image). This can be confusing because you need your image to contain the image digest generated by the asset pipeline. There’s a helper that provides just that and it’s called image_path.

<%= link_to "Logo", image_path('logo.png') %>
# => <a href="/assets/logo-c88948e05e11587af2c23747862ca433.png">Logo</a>

Anchors with link_to

You might need to point to a specific section (anchor) in the page which you can identify by it’s dom ID. So let’s say on the target page we have a section that has the id="interesting-section". In order to point our link to that section, we’ll need to add the anchor to the generated link.

<%= link_to "Section", root_path(:anchor => "interesting-section") %>
# => <a href="/#interesting-section">Section</a>

You can add the :remote => true option to the link to tell Rails that you want to handle the link via javascript. This option will automatically send an ajax request (handled via the jQuery UJS adapter).

<%= link_to "Ajax", root_path, :remote => true %>
# => <a data-remote="true" href="/">Ajax</a>

For a good user experience and because you’ll want your user not to leave your website if possible, you should make all your external links open in a separate tab or window. You can achieve this by using the target="_blank" html attribute which in Rails speak will look like this:

<%= link_to "Google", "http://google.com", :target => "_blank" %>
# => <a target="_blank" href="http://google.com">Google</a>

POST-ing using link_to

Sending a post request via a link is something that the html <a href> cannot do. You can only use it to make GET requests, notPOST. That being said, Rails has some magic tricks for you.

By providing the :method => :post option, Rails will create a form and submit it via javascript. Note that you need the jquery-railsgem for this to work, if you don’t have it, there won’t be any magic happening and your links will default to a GET request.

<%= link_to "Post", root_path, :method => :post %>
# => <a rel="nofollow" data-method="post" href="/">Post</a>

Adding more params to the POST request

<%= link_to "Create User", users_path(:email => "jdoe@email.com", :password => "secret"), :method => :post %>
# => <a rel="nofollow" data-method="post" href="/users?email=jdoe%40email.com&amp;password=secret">Create User</a>

Conclusion

These are some of the more common ways I’ve used link_to but I’m sure there are many others. So if you have any other examples I could add to the article please let me know in the comments section below.

SSD vs SAS

link

Имеем два подопытных кролика: 2x SAS, hw raid1 и 2x SSD, hw raid1. Машины идентичны:
CPU 2x AMD Opteron 6164 HE 12-Core
RAM 16x Gigabyte RAM
RAID-Controller HP SmartArrayP410
Barebone Hewlett Packard DL165 G7

SAS
Vendor: SEAGATE 
Product: ST3300657SS
User Capacity: 300 GB
Logical block size: 512 bytes

SSD
Product: Samsung 840 Pro
User Capacity: 128 GB
Logical block size: 512 bytes

Тест 1: линейная запись

Код:
dd if=/dev/zero of=/tmp/testfile.bin bs=256k count=2048

SAS: 717 MB/s
SSD: 682 MB/s

Тест 2: линейное чтение

Код:
dd of=/dev/null if=/tmp/testfile.bin bs=512k count=1024

SAS: 1.7 GB/s
SSD: 2.1 GB/s

Тест 3:

Код:
hdparm -tT /dev/sda

Timing cached reads:*SAS 2438.26 MB/s; SSD 2484.01 MB/s
Timing buffered disk reads: SAS 2293.67 MB/s; SSD 219.26 MB/s

Тест 4: fio

Код:
[global]
bs=4k
size=256M
filename=test.file
direct=1
buffered=0
ioengine=libaio
iodepth=16

[seq-read]
rw=read
stonewall
name=Sequential reads

[rand-read]
rw=randread
stonewall
name=Random reads

[seq-write]
rw=write
stonewall
name=Sequential writes

[rand-write]
rw=randwrite
stonewall
name=Random writes

Sequential reads: SAS 161.82 MB/s 41426 iops; SSD 120.3 MB/s 30796 iops
Random reads: SAS 245.68 MB/s 62894 iops; SSD 125.8 MB/s 32204 iops
Sequential writes: SAS 225.75 MB/s 57791 iops; SSD 202.85 MB/s 51930 iops
Random writes: SAS 218.43 MB/s 55918 iops; SSD 187.82 MB/s 48082 iops

Тест 5: линейная запись (с другими параметрами)

Код:
dd if=/dev/zero of=testfile bs=64k count=16k conv=fdatasync

SAS: 205 MB/s
SSD: 61.8 MB/s

Тест 6: линейное чтение после очистки кэша

Код:
echo 3 > /proc/sys/vm/drop_caches
dd if=testfile of=/dev/null bs=64k

SAS: 389 MB/s
SSD: 192 MB/s

Тест 7: Unixbench
File Copy 1024 bufsize 20000 maxblocks: SAS 452 MB/s; SSD 477.71 MB/s
File Copy 256 bufsize 500 maxblocks: SAS 130.52 MB/s; SSD 136.72 MB/s
File Copy 4096 bufsize 8000 maxblocks: SAS 804.79 MB/s; SSD 686.22 MB/s
System Banchmarks Index Score: SAS 645.7; SSD 637.3

Тест 8: мои наработки
SAS: 628.14 MB/s, 40200.95 request/s
SSD: 552.33 MB/s, 35348.85 requests/s

Последние два теста привел только для сравнения. Приветствуются ваши варианты тестов дисковых систем но только понятными, открытыми тестами, а не с «птичками».

Искренне прошу поделится вашими тестами — самими командами. Теория не интересует вовсе, только практические понятные тесты. Ну и разумеется ваше мнение на этот счет. Если считаете что указанные выше тесты некорректны — укажите почему и ваш вариант тестов.

Очень прошу не гадить в теме постами: «ssd лучше», «а птички битрикса показывают другое».

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

Далее продолжу тесты с разными параметрами утилиты fio.

Однопоточный тест fio для SAS
Sequential reads: bw=7196.3KB/s, iops=14392
Random reads: bw=7009.4KB/s, iops=14018
Sequential writes: bw=6800.2KB/s, iops=13601
Random writes: bw=6209.0KB/s, iops=12418

Однопоточный тест fio для SSD
Sequential reads: bw=3045.1KB/s, iops=6091
Random reads: bw=1604.2KB/s, iops=3209
Sequential writes: bw=3059.5KB/s, iops=6118
Random writes: bw=3067.2KB/s, iops=6134

SAS опережает SSD в два раза.

===============================

Тест fio в 24 потока для SAS
Sequential reads: bw=31256KB/s, iops=62511
Random reads: bw=29228KB/s, iops=58455
Sequential writes: bw=28823KB/s, iops=57645
Random writes: bw=27450KB/s, iops=54899

Тест fio в 24 потока для SSD
Sequential reads: bw=25881KB/s, iops=51761
Random reads: bw=23734KB/s, iops=47468
Sequential writes: bw=26600KB/s, iops=53200
Random writes: bw=25136KB/s, iops=50272

Получается что с ростом числа потоков SAS и SSD почти сравнились.

Однопоточный тест fio для SAS, 10 тыс. файлов общим весом 255MB
Sequential reads: bw=1901.4KB/s, iops=3802
Random reads: bw=3915.8KB/s, iops=7830
Sequential writes: bw=4358.4KB/s, iops=8716
Random writes: bw=575671B/s, iops=1124

Однопоточный тест fio для SSD, 10 тыс. файлов общим весом 255MB
Sequential reads: bw=1189.9KB/s, iops=2379
Random reads: bw=2080.8KB/s, iops=4160
Sequential writes: bw=2494.1KB/s, iops=4988
Random writes: bw=1893.8KB/s, iops=3787

======================================================

Тест fio в 24 потока для SAS, 10 тыс. файлов общим весом 255MB
Sequential reads: bw=2466.5KB/s, iops=4932
Random reads: bw=5280.9KB/s, iops=10560
Sequential writes: bw=18156KB/s, iops=36311
Random writes: bw=768665B/s, iops=1501

Тест fio в 24 потока для SSD, 10 тыс. файлов общим весом 255MB
Sequential reads: bw=15546KB/s, iops=31092
Random reads: bw=18836KB/s, iops=37672
Sequential writes: bw=17351KB/s, iops=34702
Random writes: bw=11904KB/s, iops=23807

Вот тут у SAS’а начались проблемы.

Однопоточный тест fio разными блоками (от 512б до 16Кб) для SAS
Sequential reads: bw=7196.3KB/s, iops=14392
Random reads: bw=7009.4KB/s, iops=14018
Sequential writes: bw=6800.2KB/s, iops=13601
Random writes: bw=6209.0KB/s, iops=12418

Однопоточный тест fio разными блоками (от 512б до 16Кб) для SSD
Sequential reads: bw=43603KB/s, iops=5298
Random reads: bw=15858KB/s, iops=2690
Sequential writes: bw=42736KB/s, iops=5193
Random writes: bw=31301KB/s, iops=5293

SSD не любит разброс размера блоков? Какова вероятность этого?

=================================================

Тест fio в 24 потока разными блоками (от 512б до 16Кб) для SAS
Sequential reads: bw=458294KB/s, iops=55692
Random reads: bw=322044KB/s, iops=54643
Sequential writes: bw=410884KB/s, iops=49931
Random writes: bw=286496KB/s, iops=48451

Тест fio в 24 потока разными блоками (от 512б до 16Кб) для SSD
Sequential reads: bw=395391KB/s, iops=48048
Random reads: bw=268590KB/s, iops=45573
Sequential writes: bw=408324KB/s, iops=49619
Random writes: bw=241830KB/s, iops=40897

=================================================

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

———- Добавлено 05.10.2013 в 09:46 ———-

Беремся потихоньку за MySQL

Подготовим innoDB таблицу на 500 тыс. записей и выполним тест в 128 поток выполнил 100 тыс. запросов.

Код:
sysbench --test=oltp --mysql-table-engine=innodb --oltp-table-size=500000 --db-driver=mysql prepare
sysbench --test=oltp --num-threads=128 --max-requests=100000 --oltp-table-size=500000 --db-driver=mysql run

SAS

Цитата:
transactions: 100046 (3718.79 per sec.)
deadlocks: 1 (0.04 per sec.)
read/write requests: 1900890 (70657.54 per sec.)
other operations: 200093 (7437.61 per sec.)
total time: 26.9029s

SSD

Цитата:
transactions: 100032 (2709.75 per sec.)
deadlocks: 0 (0.00 per sec.)
read/write requests: 1900608 (51485.16 per sec.)
other operations: 200064 (5419.49 per sec.)
total time: 36.9156s

SSD пасет задних.

==============================================
Аналогичный тест для MyISAM но с параметрами таблиц попроще:
SAS

Цитата:
transactions: 1000 (126.60 per sec.)
read/write requests: 19000 (2405.31 per sec.)
other operations: 2000 (253.19 per sec.)
total time: 7.8992s

SSD

Цитата:
transactions: 1000 (123.59 per sec.)
read/write requests: 19000 (2348.17 per sec.)
other operations: 2000 (247.18 per sec.)
total time: 8.0914s

Ну попробуйте убедить меня что теория права. Пока только один тест это подтвердил и то это должен быть какой то файловый хостинг или в этом роде.

from Ucoz

1) Переходим на сайт http://www.ucoz.ru/   и входим в систему под своим логином и паролем.
2) В панели «Мои сайты». Находим сайт, с которого Вы хотите сделать перенаправление. Например, у меня сайт «AndHacker.narod.ru» (мой сайт купил uCoz у Яндекса в 2013)
3)Далее откроется сайт, вида «ВАШ_САЙТ/admin/’.
   Там нужно будет ещё раз ввести Ваш пароль и выполнить вход в панель управления сайта.
4) Открылась панель управления сайтом.
    В меню «Дизайн» открываем пункт «Управление шаблоном (шаблон)»
5)В разделе «Глобальные блоки» щёлкнуть на  «верхняя часть сайта».
6)Далее в любом месте (лучше в начале) копируете и вставляете следующую строчку.
<script> document.location = «http://newsite.ru/»; content=0; target=»_blank»; </script>

Sublime text plugings and hot keys

http://proft.me/2013/02/2/oda-o-sublime-text/

Sublime Text удобный текстовый редактор, который занял нишу между большими IDE со всем готовым и текстовыми редакторами «собери сам» (vimemacs, etc). Для меня vim основной текстовый редактор с уже устоявщимся конфигом, набором плагинов и привычек, а вот Sublime‘ом пользуюсь для параллельных работ.

Как большинство в этом блоге, хочу собрать в одной заметке все свои предпочтения касательноSublime, что бы со временем быстро развернуть в новых средах.

Начнем с установки. Я пользуюсь dev-билдом который можно установить вручную отсюдова или с помощью пакетных менеджеров.

Под Ubuntu

sudo add-apt-repository ppa:webupd8team/sublime-text-3
sudo apt-get update
sudo apt-get install sublime-text-installer

Под Arch Linux

yaourt -S sublime-text-dev

Настройки

Все настройки хранятся в JSON. Мои настройки такие (Preferences — Settings — User):

{
    "auto_complete": true,
    "color_scheme": "Packages/Color Scheme - Default/Solarized (Light).tmTheme",
    "detect_slow_plugins": false,
    "ensure_newline_at_eof_on_save": true,
    "file_exclude_patterns":
    [
        "hgignore",
        ".gitignore"
    ],
    "folder_exclude_patterns":
    [
        ".hg",
        ".git"
    ],
    "font_face": "Courier New",
    "font_size": 13.0,
    "highlight_line": true,
    "highlight_modified_tabs": true,
    "ignored_packages":
    [
    ],
    "indent_guide_options":
    [
        "draw_active",
        "draw_normal"
    ],
    "indent_to_bracket": true,
    "soda_folder_icons": true,
    "sublimelinter": false,
    "tab_size": 4,
    "theme": "Soda Light.sublime-theme",
    "translate_tabs_to_spaces": true,
    "trim_trailing_white_space_on_save": true,
    "overlay_scroll_bars": "enabled",
    "line_padding_bottom": 1,
    "line_padding_top": 1,
}

Список всех настроек можно посмотреть тут.

И сочетания клавиш (Preferences — Key Bindings — User)

[
    { "keys": ["f4"], "command": "toggle_bookmark" },
    { "keys": ["f5"], "command": "next_bookmark" },
    { "keys": ["f6"], "command": "prev_bookmark" },
    { "keys": ["f7"], "command": "open_model_view" },
    { "keys": ["f8"], "command": "open_template" },
    { "keys": ["f9"], "command": "jump_back" },
    { "keys": ["f10"], "command": "jump_forward" },
    { "keys": ["alt+shift+z"], "command": "insert_snippet", "args": {"contents": "{% ${0:$SELECTION} %}"} },
    { "keys": ["alt+shift+x"], "command": "insert_snippet", "args": {"contents": "{{ ${0:$SELECTION} }}"} },
    { "keys": ["ctrl+l"], "command": "python_goto_definition" },
    { "keys": ["ctrl+j"], "command": "join_lines" },
    { "keys": ["ctrl+d"], "command": "duplicate_line" },
    { "keys": ["ctrl+y"], "command": "run_macro_file", "args": {"file": "res://Packages/Default/Delete Line.sublime-macro"} },
    { "keys": ["ctrl+alt+n"], "command": "advanced_new_file"},
    {
        "keys": ["ctrl+'"],
        "command": "bh_key",
        "args":
        {
            "lines" : true,
            "plugin":
            {
                "type": ["__all__"],
                "command": "bh_modules.bracketselect"
            }
        }
    }
]

Горячие клавиши

Наиболее часто используемые сочетания клавиш

  • ctrl + p - поиск файлов;
  • ctrl + r - поиск по именам функций, структур;
  • ctrl + ; - поиск по переменным;
  • ctrl + shift + p - меню с набором всех команд Sublime Text с возможностью поиска;
  • ctrl + shift + [ - свернуть (fold) текущий блок;
  • ctrl + shift + ] - развернуть (unfold) текущий блок;
  • shift + правая кнопки мыши — вертикальное выделение;
  • ctrl + левая клавиша — множественное выделение и правка;
  • ctrl + x - удалить линию;
  • ctrl + l - выделить линию;
  • ctrl + d - выделить слово;
  • ctrl + m - перемещение между скобками;
  • ctrl + shift + m - выделение текста внутри скобок;
  • alt + shift + 2 - разбить окно на две части;
  • alt + shift + 1 - вернуть вид к одному окну;
  • ctrl + [NUM] - переключиться на окно с номером NUM (1-4);
  • ctrl + shift + [NUM] - переместить файл в окно NUM (1-4);
  • alt + shift + w – обернуть выбранный текст в тег;
Sublime Text

Плагины

Посмотреть список доступных плагинов можно на wbond.net.

Для управления плагинами из под редактора понадобиться Package Control. Для этого нажимаем Ctrl + ` и в открывшуюся консоль вводим:

import urllib.request,os; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); open(os.path.join(ipp, pf), 'wb').write(urllib.request.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ','%20')).read())

Нажимаем ctrl + shift + p, набираем install и получаем список плагинов из внутреннего репозитарияSublime Text. Используемые плагины:

  • AngularJS - разные расширения для работы с AngularJS
  • HTML5 - подборка нововведений в HTML 5 для Sublime Text;
  • jQuery - подборка снипетов jQuery для Sublime Text;
  • Tag - удобные дополнения для работы с XML;
  • Placeholder - шаблоны HTML и контента (lorem ipsum);
  • Emmet - обновленный Zen Coding, документациясписок командпример использования;
  • SideBarEnhancements - пачка дополнительных операций над файлами в sidebar;
  • AllAutocomplete - автодополнение слов из всех вкладок в текущем окне;
  • AdvancedNewFile - быстрое создание файлов, вызов по Super+Alt+N;
  • BracketHighlighter - монстр по работе с скобками и тегами;
  • Anaconda - годный lint-чекер и автодополнение для Python
  • Djaneiro - плагин добавляет подсветку для шаблонов Django и пачку снипетов;
  • PdbSublimeTextSupport - интеграция pdb и Sublime Text;
  • SublimeREPL - запуск интерпретатора python и других языков в окне редактора;
  • Soda - светлая и темная тема оформления Soda;
  • Tomorrow Night - тема оформления Tomorrow Night;
  • Solarized - светлая и темная тема оформления Solarized;

Настройки отдельно для проекта

Мы можем установить настройки отдельно для проекта, для этого откройте Project — Edit Project и введите настройки под проект, например

{
    "folders": [
        {
           "path": "/path/to/folder1"
        },
        {
            "path": "/path/to/folder2"
        }
    ],
    "settings": {
        "python_interpreter": "/path/to/some/virtualenv/bin/python"
    }
}

ssh generate

ssh-keygen -t rsa -C "your_email@example.com"

git config --global user.name "Your Name"
git config --global user.email you@example.com

cat ~/.ssh/id_rsa.pub | (ssh root@host "cat >> ~/.ssh/authorized_keys")

# если проблемы

eval $(ssh-agent)
ssh-add