вторник, 9 апреля 2013 г.

[PUPPET] Ставим пакеты из backports

Возникла необходимость поставить пакет из бекпортов через apt-get с помощью паппета.
Для этого необходимо проделать примерно следующее (кусок манифеста из рабочего проекта)

class collectd {
# directories and filenames setup
    $apt_sources_dir = '/etc/apt/sources.list.d'
    $apt_sources_file = 'backports.list'

    file { "{$apt_sources_dir}/{$apt_sources_file}":
        ensure    => file,
        content    => 'deb http://backports.debian.org/debian-backports squeeze-backports main',
    }
#
    exec { "apt-get update":
        command => "/usr/bin/apt-get update",
        onlyif => "/bin/sh -c '[ ! -f /var/cache/apt/pkgcache.bin ] || /usr/bin/find /etc/apt/* -cnewer /var/cache/apt/pkgcache.bin | /bin/grep . > /dev/null'",
    }
# installing package
    package { "collectd-core/squeeze-backports":
        ensure => "latest",
        require => Exec['apt-get update'],
    }
}

понедельник, 1 апреля 2013 г.

[ANDROID] "Переносим" данные из внутренней памяти телефона на флеш-карту

1. Определитесь где у вас на (флешке) будут храниться перенесенные данные и создайте для них папку. Например Bind
2. Создайте в только что созданной папке еще одну папку с именем gameloft
3. Перенесите в нее содержимое папки /mnt/sdcard/gameloft/games
4. Скачайте с маркета бесплатное приложение Script Manager
5. Решите где у вас будет лежать скрипт ==> Создайте папку Scripts.
6. Запустите Script Manager и перейдите в эту папку.
7. Создайте новый скрипт (меню-(+)) и назовите его bind.sh
8. Щелкните по свежесозданному файлу и в появившемся меню нажмите:
Звездочку - это добавит наш скрипт в избранное.
Черепок - запуск скрипта с root привилегиями.
Шестеренку - добавит скрипт в автозагрузку.
Далее жмем кнопку Edit и открываем скрипт любимым текстовым редактором.
9. Настало время для самого сложного
Структура команды:
mount -o bind </что/хотите/смонтировать> </куда/хотите/смонтировать>
Исходя из этого у нас получается:
mount -o bind /mnt/sdcard2/bind/gameloft /mnt/sdcard/gameloft/games
иными словами мы говорим системе что содержимое папки /sdcard/gameloft/games находится в папке /sdcard2/bind/gameloft

10. В открытом файле  пишем:
#!/system/bin/sh
mount -o bind /mnt/sdcard2/bind/gameloft /mnt/sdcard/gameloft/games

exit 0


#!/system/bin/sh
##Cashe gameloft
mount -o bind /mnt/sdcard2/bind/gameloft /mnt/sdcard/gameloft/games
##Cashe Spectral Souls
mount -o bind /mnt/sdcard2/bind/hyperdevbox /mnt/sdcard/hyperdevbox
##Maps 2GIS
mount -o bind /mnt/sdcard2/bind/2gisMobile /mnt/sdcard/2gisMobile
exit 0

11. Сохраняем файл и закрываем текстовый редактор.
12. Жмем кнопку Run и идем в папку /gameloft/games
Если кэши в ней видны, значит вы все сделали правильно, можно запустить и проверить игру.
При следующей перезагрузке скрипт выполнится автоматически.

По аналогии переносим другие данные просто дописывая в этот скрипт.

вторник, 26 марта 2013 г.

[PHP] Useful code snippets

Email PHP errors instead of displaying it

By default, most servers are set to display an error message when an error occured in one of your script. For security reasons, you may want to get an email with the error, instead of displaying it to the public.
// Our custom error handler
function nettuts_error_handler($number, $message, $file, $line, $vars){
 $email = "
  An error ($number) occurred on line
  $line and in the file: $file.
  

$message 

";

 $email .= "
" . print_r($vars, 1) . "
"; $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Email the error to someone... error_log($email, 1, 'you@youremail.com', $headers); // Make sure that you decide how to respond to errors (on the user's side) // Either echo an error message, or kill the entire project. Up to you... // The code below ensures that we only "die" if the error was more than // just a NOTICE. if ( ($number !== E_NOTICE) && ($number < 2048) ) { die("There was an error. Please try again later."); } } // We should use our custom function to handle errors. set_error_handler('nettuts_error_handler'); // Trigger an error... (var doesn't exist) echo $somevarthatdoesnotexist; 

Detect location by IP

Here is an useful code snippet to detect the location of a specific IP. The function below takes one IP as a parameter, and returns the location of the IP. If no location is found, UNKNOWN is returned.
function detect_city($ip) {
        
        $default = 'UNKNOWN';

        if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost')
            $ip = '8.8.8.8';

        $curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';
        
        $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
        $ch = curl_init();
        
        $curl_opt = array(
            CURLOPT_FOLLOWLOCATION  => 1,
            CURLOPT_HEADER      => 0,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_USERAGENT   => $curlopt_useragent,
            CURLOPT_URL       => $url,
            CURLOPT_TIMEOUT         => 1,
            CURLOPT_REFERER         => 'http://' . $_SERVER['HTTP_HOST'],
        );
        
        curl_setopt_array($ch, $curl_opt);
        
        $content = curl_exec($ch);
        
        if (!is_null($curl_info)) {
            $curl_info = curl_getinfo($ch);
        }
        
        curl_close($ch);
        
        if ( preg_match('{
  • City : ([^<]*)
  • }i', $content, $regs) ) { $city = $regs[1]; } if ( preg_match('{
  • State/Province : ([^<]*)
  • }i', $content, $regs) ) { $state = $regs[1]; } if( $city!='' && $state!='' ){ $location = $city . ', ' . $state; return $location; }else{ return $default; } }

    Display Facebook fans count in full text

    Want to display how many Facebook fans do you have, in full text, on your blog? It’s very easy using the following snippet:
    function fb_fan_count($facebook_name){
        // Example: https://graph.facebook.com/digimantra
        $data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));
        echo $data->likes;
    }

    Get info about your memory usage

    In order to optimize your scripts, you may definitely want to know how many amount of RAM they use on your server. This snippet will check memory and then print initial, final and peak usages.
    echo "Initial: ".memory_get_usage()." bytes \n";
    /* prints
    Initial: 361400 bytes
    */
    
    // let's use up some memory
    for ($i = 0; $i < 100000; $i++) {
     $array []= md5($i);
    }
    
    // let's remove half of the array
    for ($i = 0; $i < 100000; $i++) {
     unset($array[$i]);
    }
    
    echo "Final: ".memory_get_usage()." bytes \n";
    /* prints
    Final: 885912 bytes
    */
    
    echo "Peak: ".memory_get_peak_usage()." bytes \n";
    /* prints
    Peak: 13687072 bytes
    */

    
    

    четверг, 14 февраля 2013 г.

    [PHP] Заменить 2+ пробелов на "пусто"

    Просто записка:
    $string=preg_replace('/ {2,}/','',$string);
            /*  |          | ||     |   |_в $string
                |          | ||     |_на пустую строку
                |          | ||_и более раз
                |          | |_встреченный 2 
                |          |_пробел (только пробел, для табов и пр символов - \s
                |_заменить 
            */
    

    понедельник, 11 февраля 2013 г.

    Installing LessCSS on Gentoo Linux

    Here’s a short HOWTO on installing lesscss on Gentoo. As root, execute:
    emerge --sync (or skip this if you know you are relatively up-to-date)
    emerge rubygems
    gem install less
    gem install therubyracer 
    That’s all.

    понедельник, 10 декабря 2012 г.

    [STAT] Collectd - Установка, настройка, использование.

    Что это такое?

    Collectd - это небольшой демон, который каждые 10 секунд собирает статистку об использовании ресурсов системы. Есть возможность сбора статистики для нескольких хостов и отсылка её на сервер, который занимается отрисовкой красивых графиков.
    Основное отличие этого сборщика в том, что он работает по принципу push, а не poll/pull. Т.е. он "висит" и слушает, а сервера ему сами статистику присылают. :)

    Что мы будем делать?

    Что я хочу описать в этом посте:
    • Установка.
    • Настройка общая.
    • Настройка отдельных плагинов.
    • Настройка slave серверов, которые будут слать нам на главный сервер свою статистику работы.
    • Настройка нотификаций по email.
    По поводу последнего пункта -- это будет только то, что мне подходит и интересно, все представленные интерфейсы я рассматривать не буду.

    вторник, 27 ноября 2012 г.

    [apache] Изменяем маску созаваемых файлов и директорий под апачем

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


    emerge www-apache/mod_umask
    

    Ну и потом в /etc/apache2/modules.d/mod_umask.conf раскомментируем нужную строчку. И конечно же перезапустим апач.

    Вот и все.