Skip to content

Instantly share code, notes, and snippets.

View sadfuzzy's full-sized avatar
🎯
Focusing

Denis Savitskiy sadfuzzy

🎯
Focusing
View GitHub Profile
@sadfuzzy
sadfuzzy / cookie_value_generator.rb
Created December 4, 2014 15:42
Rails 4 cookie value generator
-- View Current Lock
SELECT c.relname, l.mode, l.granted, l.pid FROM pg_locks as l JOIN pg_class as c on c.oid = l.relation;
-- UTF-8 text search by index
create index on <table> (<column> text_pattern_ops);
-- Generate nodes path
create table <table> as select i, format('/%s/%s/', (random() * 10), (random() * 10)) from generate_series(1,100000);
-- Create extension
@sadfuzzy
sadfuzzy / setup.txt
Last active November 2, 2018 20:50
Ubuntu setup
System:
sudo apt-get install software-properties-common ncdu
Git:
sudo apt-get install git git-core
git config --global user.email "sadfuzzy@yandex.ru"
git config --global user.name "Denis Savitskiy"
git config --global push.default simple
https://github.com/settings/ssh
@sadfuzzy
sadfuzzy / hashquiz.rb
Last active August 29, 2015 14:26 — forked from potatosalad/hashquiz.rb
Ruby quiz for convert hash "dot paths" into actual hash hierarchy.
#require 'rubygems'
require 'pp'
#require 'ap' # Awesome Print
class Object
# expects [ [ symbol, *args ], ... ]
def recursive_send(*args)
args.inject(self) { |obj, m| obj.send(m.shift, *m) }
end
end
@sadfuzzy
sadfuzzy / active_admin_customizations.rb
Created February 19, 2016 11:07
active_admin_customizations
ActiveAdmin.register Event do
#Menu display index
menu :priority => 1
#Scopes
scope :all
scope :pending
scope :approved
scope :rejected
scope :cancelled
class RecountMediamapService
def initialize(task)
@task = task
@comparisons_ids = Film.where.not(kinopoisk_rate: nil).where.not(kinopoisk_rate: 0).where('kinopoisk_num > 10').order(year: :desc, kinopoisk_rate: :desc, kinopoisk_num: :desc).limit(20000).pluck(:id)
@film = Film.includes(:genres, :subgenres, :countries, :tags, :people).find(@task.task.to_i)
end
def recount
begin
kbs = {}
@sadfuzzy
sadfuzzy / routes.rb
Created April 12, 2016 07:30 — forked from kryzhovnik/routes.rb
Интеграция Яндекс.Кассы с Rails
# config/routes.rb
YandexKassaIntegration::Application.routes.draw do
# ...
scope '/yandex_kassa' do
controller 'yandex_kassa', constraints: { subdomain: 'ssl' } do
post :check
post :aviso
get :success
get :fail
@sadfuzzy
sadfuzzy / test_task.md
Last active February 14, 2019 10:55
Check credit cards

Checking Credit Cards

Write a program that accepts a credit card number as a command-line argument. The program should print the card's type (or Unknown) as well a Valid/Invalid indication of whether or not the card passes the Luhn algorithm. Hint: use git, cover with specs, make some user friendly interface (can be a command line), make it modular.

Before a credit card is submitted to a financial institution, it generally makes sense to run some simple reality checks on the number. The numbers are a good length and it's common to make minor transcription errors when the card is not scanned directly. The first check people often do is to validate that the card matches a known pattern from one of the accepted card providers. Some of these patterns are:

+============+=============+===============+
| Card Type  | Begins With | Number Length |

Day one, part II

Ruby in 60 seconds

  • Everything is an Object
  • Variables can refer to Objects
  • Objects can receive Method calls
  • Methods can change variables and send Method calls

(everything else is a KEYWORD of OPERATOR or LITERAL)

@sadfuzzy
sadfuzzy / gist:703d751eba8982485d1e8bedbe11272f
Last active February 9, 2017 08:03
Linux Security tips
Ряд моментов Вы уже сделали, но я все равно их опишу для полноты списка.
1. Создать отдельного пользователя и хороший пароль на sudo. Не использовать больше root напрямую. Совсем.
2. SSH. Отключаем метод аутентификации по паролю. Если Вам не нужны другие методы, то их тоже можно отключить, оставив только publickey. Отключаем возможность аутентификации root'ом. Включаем использование только 2й версии SSH протокола.
3. Устанавливаем Fail2Ban и настраиваем чтобы после нескольких неуспешных попыток подключения по SSH банило по IP на длительное время. Кол-во попыток и время бана можно тюнить в меру своей паранойи. У меня, например, банит на час после 2х неуспешных попыток.
4. Iptables. Действуем по принципу "запрещено все, что не разрешено". Запрещаем по умолчанию весь INPUT и FORWARD трафик снаружи. Открываем на INPUT'е 22 порт. В дальнейшем открываем порты/forwarding по мере необходимости. Если у нас предполагаются сервисы на соседних серверах нужные только для внутренней коммуникации (Memcached, Redis, и т.