text
stringlengths
10
2.61M
class ProductsController < ApplicationController protect_from_forgery prepend: true def purchase if request.get? @product = Product.find_by(pk: params[:id]) @client_token = Gateway.new.client_token render 'purchase' elsif request.post? logger.info "Issuing sale for #{params[:product_name]}" result = Gateway.new.sale(params[:product_price], params[:payment_method_nonce]) logger.info "Sale result: #{result}" redirect_to merchant_root_url and return end end end
require 'spec_helper' describe Immutable::Set do describe '#to_list' do [ [], ['A'], %w[A B C], ].each do |values| context "on #{values.inspect}" do let(:set) { S[*values] } let(:list) { set.to_list } it 'returns a list' do list.is_a?(Immutable::List).should == true end it "doesn't change the original Set" do list set.should eql(S.new(values)) end describe 'the returned list' do it 'has the correct length' do list.size.should == values.size end it 'contains all values' do list.to_a.sort.should == values.sort end end end end end end
require 'rails_helper' RSpec.describe User, type: :model do before do @user = FactoryBot.build(:user) end describe 'ユーザー新規登録' do context '新規登録できる場合' do it '入力が必要なカラムへ正しい値が入力できれば登録できる' do expect(@user).to be_valid end end context '新規登録できない場合' do it 'nicknameが空では登録できない' do @user.nickname = '' @user.valid? expect(@user.errors.full_messages).to include "Nickname can't be blank" end it 'emailが空では登録できない' do @user.email = '' @user.valid? expect(@user.errors.full_messages).to include "Email can't be blank" end it '重複したemailが存在する場合登録できない' do @user.save another_user = FactoryBot.build(:user) another_user.email = @user.email another_user.valid? expect(another_user.errors.full_messages).to include 'Email has already been taken' end it '@が含まれないemailでは登録できない' do @user.email = 'test' @user.valid? expect(@user.errors.full_messages).to include 'Email is invalid' end it 'passwordが空では登録できない' do @user.password = '' @user.valid? expect(@user.errors.full_messages).to include "Password can't be blank" end it 'passwordが5文字以下では登録できない' do @user.password = '5moji' @user.password_confirmation = '5moji' @user.valid? expect(@user.errors.full_messages).to include 'Password is too short (minimum is 6 characters)' end it '平仮名が含まれるpasswordでは登録できない' do @user.password = 'ひらがなtest1' @user.password_confirmation = 'ひらがなtest1' @user.valid? expect(@user.errors.full_messages).to include 'Password is invalid' end it '全角カタカナが含まれるpasswordでは登録できない' do @user.password = 'カタカナtest1' @user.password_confirmation = 'カタカナtest1' @user.valid? expect(@user.errors.full_messages).to include 'Password is invalid' end it '漢字が含まれるpasswordでは登録できない' do @user.password = '漢字test1' @user.password_confirmation = '漢字test1' @user.valid? expect(@user.errors.full_messages).to include 'Password is invalid' end it '記号が含まれるpasswordでは登録できない' do @user.password = '~test1' @user.password_confirmation = '~test1' @user.valid? expect(@user.errors.full_messages).to include 'Password is invalid' end it '全角英字が含まれるpasswordでは登録できない' do @user.password = 'atest1' @user.password_confirmation = 'atest1' @user.valid? expect(@user.errors.full_messages).to include 'Password is invalid' end it '全角数字が含まれるpasswordでは登録できない' do @user.password = '1test1' @user.password_confirmation = '1test1' @user.valid? expect(@user.errors.full_messages).to include 'Password is invalid' end it '半角英字のみのpasswordでは登録できない' do @user.password = 'testtest' @user.password_confirmation = 'testtest' @user.valid? expect(@user.errors.full_messages).to include 'Password is invalid' end it '半角数字のみのpasswordでは登録できない' do @user.password = '123456' @user.password_confirmation = '123456' @user.valid? expect(@user.errors.full_messages).to include 'Password is invalid' end it '半角カタカナが含まれるpasswordでは登録できない' do @user.password = 'カタカナtest1' @user.password_confirmation = 'カタカナtest1' @user.valid? expect(@user.errors.full_messages).to include 'Password is invalid' end it 'password_confirmationが空では登録できない' do @user.password_confirmation = '' @user.valid? expect(@user.errors.full_messages).to include "Password confirmation doesn't match Password" end it 'passwordとpassword_confirmationが不一致では登録できない' do @user.password_confirmation = '1234password' @user.valid? expect(@user.errors.full_messages).to include "Password confirmation doesn't match Password" end it 'last_nameが空では登録できない' do @user.last_name = '' @user.valid? expect(@user.errors.full_messages).to include "Last name can't be blank" end it 'ー以外の記号が含まれるlast_nameでは登録できない' do @user.last_name = '~苗字' @user.valid? expect(@user.errors.full_messages).to include 'Last name is invalid' end it '全角英字が含まれるlast_nameでは登録できない' do @user.last_name = 'a苗字' @user.valid? expect(@user.errors.full_messages).to include 'Last name is invalid' end it '全角数字が含まれるlast_nameでは登録できない' do @user.last_name = '1苗字' @user.valid? expect(@user.errors.full_messages).to include 'Last name is invalid' end it '半角英字が含まれるlast_nameでは登録できない' do @user.last_name = 'a苗字' @user.valid? expect(@user.errors.full_messages).to include 'Last name is invalid' end it '半角数字が含まれるlast_nameでは登録できない' do @user.last_name = '1苗字' @user.valid? expect(@user.errors.full_messages).to include 'Last name is invalid' end it '半角カタカナが含まれるlast_nameでは登録できない' do @user.last_name = 'ミョウ字' @user.valid? expect(@user.errors.full_messages).to include 'Last name is invalid' end it 'first_nameが空では登録できない' do @user.first_name = '' @user.valid? expect(@user.errors.full_messages).to include "First name can't be blank" end it 'ー以外の記号が含まれるfirst_nameでは登録できない' do @user.first_name = '~名前' @user.valid? expect(@user.errors.full_messages).to include 'First name is invalid' end it '全角英字が含まれるfirst_nameでは登録できない' do @user.first_name = 'a名前' @user.valid? expect(@user.errors.full_messages).to include 'First name is invalid' end it '全角数字が含まれるfirst_nameでは登録できない' do @user.first_name = '1名前' @user.valid? expect(@user.errors.full_messages).to include 'First name is invalid' end it '半角英字が含まれるfirst_nameでは登録できない' do @user.first_name = 'a名前' @user.valid? expect(@user.errors.full_messages).to include 'First name is invalid' end it '半角数字が含まれるfirst_nameでは登録できない' do @user.first_name = '1名前' @user.valid? expect(@user.errors.full_messages).to include 'First name is invalid' end it '半角カタカナが含まれるfirst_nameでは登録できない' do @user.first_name = 'ナ前' @user.valid? expect(@user.errors.full_messages).to include 'First name is invalid' end it 'last_name_furiganaが空では登録できない' do @user.last_name_furigana = '' @user.valid? expect(@user.errors.full_messages).to include "Last name furigana can't be blank" end it '平仮名が含まれるlast_name_furiganaでは登録できない' do @user.last_name_furigana = 'みョウジ' @user.valid? expect(@user.errors.full_messages).to include 'Last name furigana is invalid' end it '漢字が含まれるlast_name_furiganaでは登録できない' do @user.last_name_furigana = '苗ジ' @user.valid? expect(@user.errors.full_messages).to include 'Last name furigana is invalid' end it 'ー以外の記号が含まれるlast_name_furiganaでは登録できない' do @user.last_name_furigana = '~ミョウジ' @user.valid? expect(@user.errors.full_messages).to include 'Last name furigana is invalid' end it '全角英字が含まれるlast_name_furiganaでは登録できない' do @user.last_name_furigana = 'aミョウジ' @user.valid? expect(@user.errors.full_messages).to include 'Last name furigana is invalid' end it '全角数字が含まれるlast_name_furiganaでは登録できない' do @user.last_name_furigana = '1ミョウジ' @user.valid? expect(@user.errors.full_messages).to include 'Last name furigana is invalid' end it '半角英字が含まれるlast_name_furiganaでは登録できない' do @user.last_name_furigana = 'aミョウジ' @user.valid? expect(@user.errors.full_messages).to include 'Last name furigana is invalid' end it '半角数字が含まれるlast_name_furiganaでは登録できない' do @user.last_name_furigana = '1ミョウジ' @user.valid? expect(@user.errors.full_messages).to include 'Last name furigana is invalid' end it '半角カタカナが含まれるlast_name_furiganaでは登録できない' do @user.last_name_furigana = 'ミョウジ' @user.valid? expect(@user.errors.full_messages).to include 'Last name furigana is invalid' end it 'first_name_furiganaが空では登録できない' do @user.first_name_furigana = '' @user.valid? expect(@user.errors.full_messages).to include "First name furigana can't be blank" end it '平仮名が含まれるfirst_name_furiganaでは登録できない' do @user.first_name_furigana = 'なマエ' @user.valid? expect(@user.errors.full_messages).to include 'First name furigana is invalid' end it '漢字が含まれるfirst_name_furiganaでは登録できない' do @user.first_name_furigana = '名マエ' @user.valid? expect(@user.errors.full_messages).to include 'First name furigana is invalid' end it 'ー以外の記号が含まれるfirst_name_furiganaでは登録できない' do @user.first_name_furigana = '〜ナマエ' @user.valid? expect(@user.errors.full_messages).to include 'First name furigana is invalid' end it '全角英字が含まれるfirst_name_furiganaでは登録できない' do @user.first_name_furigana = 'naマエ' @user.valid? expect(@user.errors.full_messages).to include 'First name furigana is invalid' end it '全角数字が含まれるfirst_name_furiganaでは登録できない' do @user.first_name_furigana = '1ナマエ' @user.valid? expect(@user.errors.full_messages).to include 'First name furigana is invalid' end it '半角英字が含まれるfirst_name_furiganaでは登録できない' do @user.first_name_furigana = 'naマエ' @user.valid? expect(@user.errors.full_messages).to include 'First name furigana is invalid' end it '半角数字が含まれるfirst_name_furiganaでは登録できない' do @user.first_name_furigana = '1ナマエ' @user.valid? expect(@user.errors.full_messages).to include 'First name furigana is invalid' end it '半角カタカナが含まれるfirst_name_furiganaでは登録できない' do @user.first_name_furigana = 'ナマエ' @user.valid? expect(@user.errors.full_messages).to include 'First name furigana is invalid' end it 'birthdayが空では登録できない' do @user.birthday = '' @user.valid? expect(@user.errors.full_messages).to include "Birthday can't be blank" end end end end
class Reunion attr_reader :name, :activities def initialize(name) @name = name @activities = [] end def add_activity(activity) @activities << activity end def total_cost @activities.sum {|activity| activity.total_cost} end def breakout @activities.each_with_object(Hash.new(0)) do |activity, hash| activity.owed.each do |participant| hash[participant[0]] += participant[1] end end end def summary breakout.each_with_object("") do |ower, str| str << "#{ower[0]}: #{ower[1]}\n" end.chop end def detailed_breakout @activities.each_with_object({}) do |activity, hash| owers = activity.owed activity.participants.each do |participant| amount = owers[participant[0]] payees = activity.participants.keys.find_all {|participant| amount * owers[participant] < 0} hash[participant[0]] ||= [] hash[participant[0]] << {activity: activity.name, payees: payees, amount: amount/payees.length} end end end end
require 'test/unit' def solution(s) return -1 if s.length.odd? r = 0 p1 = s[0..(s.length / 2 - 1)] p2 = s[(s.length / 2)..-1] ('a'..'z').to_a.each do |c| r += (p1.count(c) - p2.count(c)).abs end r / 2 end class Tests < Test::Unit::TestCase # def test_1 # assert_equal(solution('aaabbb'), 3) # end # # def test_2 # assert_equal(solution('ab'), 1) # end # # def test_3 # assert_equal(solution('abc'), -1) # end # # def test_4 # assert_equal(solution('mnop'), 2) # end # # def test_5 # assert_equal(solution('xyyx'), 0) # end # # def test_6 # assert_equal(solution('xaxbbbxx'), 1) # end # hhpddlnnsjfoyxpci (17) ioigvjqzfbpllssuj (17) def test_7 assert_equal(solution('hhpddlnnsjfoyxpciioigvjqzfbpllssuj'), 10) end end
class AadgController < ActionController::Base protect_from_forgery before_filter :find_holders_url layout 'aadg' def find_gallery if params[:gallery_id] @gallery = Gallery.find(params[:gallery_id]) end end def render_404(exception = nil) if exception logger.info "Rendering 404 with exception: #{exception.message}" end respond_to do |format| format.html { render :file => "#{Rails.root}/public/404.html", :status => :not_found } format.xml { head :not_found } format.any { head :not_found } end end def find_holders_url strs = request.path.split('/') if (strs.include? 'aadgadmin') || (strs.include? 'galleries') if strs.include? 'aadgadmin' index = strs.index('aadgadmin') - 1 else index = strs.index('galleries') - 1 end @holders_url = Array.new index.downto(0) do |i| sym = (strs[i].singularize + "_id").to_sym if params[sym] klass = strs[i].singularize.capitalize.constantize @holders_url << klass.find(params[sym]) end @holder_url = @holders_url.first end end end end
ActiveAdmin.register Payout do menu priority: 6 actions :index index do selectable_column column :id column '用户', sortable: false do |ph| ph.user.try(:nickname) || ph.user.try(:mobile) end column :card_name, sortable: false column :card_no, sortable: false column :money column '是否支付', sortable: false do |payout| payout.payed_at.blank? ? '否' : '是' end column('确认支付时间', :payed_at) column('申请时间', :created_at) actions defaults: false do |payout| if payout.payed_at.blank? item '确认支付', pay_admin_payout_path(payout), method: :put end end end member_action :pay, method: :put do resource.pay! redirect_to admin_payouts_path, notice: "已经确认支付" end end
class AddPetitionToMicroposts < ActiveRecord::Migration[5.0] def change add_column :microposts, :petition, :boolean end end
# config valid only for Capistrano 3.1 # lock '3.2.1' # # set :application, 'my_app_name' # set :repo_url, 'git@example.com:me/my_repo.git' # Default branch is :master # ask :branch, proc { `git rev-parse --abbrev-ref HEAD`.chomp }.call # Default deploy_to directory is /var/www/my_app # set :deploy_to, '/var/www/my_app' # Default value for :scm is :git # set :scm, :git # Default value for :format is :pretty # set :format, :pretty # Default value for :log_level is :debug # set :log_level, :debug # Default value for :pty is false # set :pty, true # Default value for :linked_files is [] # set :linked_files, %w{config/database.yml} # Default value for linked_dirs is [] # set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system} # Default value for default_env is {} # set :default_env, { path: "/opt/ruby/bin:$PATH" } # Default value for keep_releases is 5 # set :keep_releases, 5 # namespace :deploy do # # desc 'Restart application' # task :restart do # on roles(:app), in: :sequence, wait: 5 do # # Your restart mechanism here, for example: # # execute :touch, release_path.join('tmp/restart.txt') # end # end # # after :publishing, :restart # # after :restart, :clear_cache do # on roles(:web), in: :groups, limit: 3, wait: 10 do # # Here we can do anything such as: # # within release_path do # # execute :rake, 'cache:clear' # # end # end # end # # end # config valid only for current version of Capistrano lock "3.10.1" set :application, "cc_auto" set :repo_url, "git@github.com:SugiKent/cc_auto.git" set :branch, 'master' set :deploy_to, '/var/www/cc_auto' set :scm, :git set :log_level, :debug set :pty, true set :linked_files, %w{ config/secrets.yml config/database.yml .env} set :linked_dirs, %w{log tmp/pids tmp/cache tmp/sockets bundle public/system public/assets} set :default_env, { path: "/usr/local/rbenv/shims:/usr/local/rbenv/bin:$PATH" } set :keep_releases, 5 # wheneverのため set :whenever_environment, "#{fetch(:stage)}" set :whenever_identifier, ->{ "#{fetch(:application)}_#{fetch(:stage)}" } SSHKit.config.command_map[:whenever] = "bundle exec whenever" after 'deploy:publishing', 'deploy:restart' after 'deploy:publishing', 'deploy:symlink:linked_dirs' namespace :deploy do desc 'Restart application' task :restart do invoke 'unicorn:stop' invoke 'unicorn:start' end end after "deploy", "deploy:cleanup"
def most_frequent_element(arr,k) return nil if arr == nil || arr.empty? elem_hash = {} arr.each do |elem| if elem_hash.has_key? elem elem_hash[elem] += 1 else elem_hash[elem] = 1 end end #sort the hash by frequency elem_hash.keys.sort_by{|key,val| elem_hash[key]}.reverse[k] end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery before_filter :authenticate_student, :only => [:edit, :update] def get_current if(session[:student_id] == nil) return nil else return Student.find(session[:student_id]) end end def authenticate_student if session[:student_id] @current_student = Student.find(session[:student_id]) return true else flash[:notice] = "Log in!" redirect_to(:controller => 'sessions', :action => 'new') return false end end def save_login_state if session[:student_id] redirect_to(:controller => 'sessions', action => 'home') return false else return true end end end
class User < ActiveRecord::Base acts_as_authentic belongs_to :role def role_symbols # roles.map do |role| # role.name.underscore.to_sym # end [role.name.underscore.to_sym] end end
class RssProvider < ActiveRecord::Base belongs_to :user has_many :rss_items has_many :rss_twitts has_many :rt_twitts, :dependent => :delete_all belongs_to :user_twitter attr_accessible :frequence, :last_run, :name, :run_count, :twitt_prefix, :twitt_suffix, :lastdownload, :failcount, :url, :guid, :is_rss, :priority, :user_twitter_id, :user_twitter validates :url, :presence => true, :uniqueness => {:scope => :user_id}, :format => URI::regexp(%w(http https)) validates :name, :presence => true, :uniqueness => {:scope => :user_id} validates :frequence, :numericality => { :only_integer => true } validates :user_twitter_id, :presence => true validate :flux_exist? before_save :unset_failcount def unset_failcount self.failcount = 0 end #check si le flux existe, dans le cas contraire ajouter une erreur au modele. Cette methode est appellé avant de sauvegarder le modele def flux_exist? begin raw_content = open URI.escape(self.url) return true rescue errors.add(:url, "Le fichier n'existe pas") return false end end # Lorsque le cron s'execute, cette methode check si le flux existe, et si l'entente retourner est correcte def self.remote_file_exists?(url) puts "Checking if file exist : #{URI.escape(url)}" require 'open-uri' require 'net/http' url = URI.parse(URI.escape(url)) Net::HTTP.start(url.host, 80) do |http| puts "file exist : #{http.head(url.request_uri).code == "200"} (#{http.head(url.request_uri).code})" return (http.head(url.request_uri).code == "200" or http.head(url.request_uri).code == "301") end end #Si le flux a eté checker il y a plus que 30 minutes, le recharge et analyse si nous avons à faire a un flux XML ou un RSS. En fonction de l'un ou de l'autre ajoute les infos dans la DB def load_and_update # pas de refresh moins de 30 minutes return if self.lastdownload and self.lastdownload > Time.now.advance(:minutes => -30) if !self.valid? or !RssProvider.remote_file_exists? self.url self.update_attribute('failcount', self.failcount + 1) return false end self.run_count += 1 require 'rubygems' #require 'simple-rss' require 'open-uri' require 'hpricot' require 'rss_reader' begin rss = RssReader::Reader.new(self.url) rescue end if rss.is_rss self.title = rss.title self.last_build_date = Time.now self.is_rss = true rss.entries.each do |item| self.rss_items.where(:title => item.title).first_or_create do |rss_item| puts "*****" puts YAML::dump(rss_item) rss_item.link = item.link rss_item.description = ApplicationController.helpers.strip_tags(item.description) rss_item.pubdate = item.pubDate rss_item.guid = item.guid rss_item.image = item.image end end else content = open(URI.escape(self.url)) self.is_rss = false self.last_build_date = Time.now self.title = 'SITEMAP' doc = Hpricot(content) doc.search("//url").each do |item| loc = item.search("//loc").first.inner_html pub_date = item.search("//lastmod").first.inner_html if item.search("//lastmod").first priority = item.search("//priority").first.inner_html if item.search("//priority").first self.rss_items.where(:link => loc).first_or_create do |rss_item| rss_item.link = loc rss_item.pubdate = pub_date rss_item.guid = Digest::SHA1.hexdigest(loc) rss_item.priority = priority end end end self.save end #Declenche le tweet, si la page utilise un micro-format, il tweet le title de la page, avec l'image en doc attaché def tweet_me puts self.user_twitter.username to_tweet = self.rss_items.order('twitt_count ASC, pubdate ASC').first if to_tweet and !self.is_rss and to_tweet.link and RssProvider.remote_file_exists?(to_tweet.link) puts "trying to download from : #{URI.escape(to_tweet.link)}" require 'rubygems' require 'simple-rss' require 'open-uri' require 'hpricot' doc = Hpricot(open(URI.escape(to_tweet.link))) to_tweet.title = doc.at("title").inner_html.strip to_tweet.image = doc.at('/html/head/meta[@property="og:image"]')['content'] if doc.at('/html/head/meta[@property="og:image"]') to_tweet.save puts YAML::dump(to_tweet.errors) end if to_tweet and to_tweet.link @client = Twitter::Client.new( :oauth_token => self.user_twitter.twitter_token, :oauth_token_secret => self.user_twitter.twitter_secret_token ) to_tweet.twitt_count += 1 to_tweet.save self.last_run = Time.now.to_i self.run_count += 1 self.save short_url = Googl.shorten(to_tweet.link).short_url max_length = 136-self.twitt_prefix.length-self.twitt_suffix.length-short_url.length message = "#{self.twitt_prefix} #{ApplicationController.helpers.truncate(to_tweet.title, :length => max_length)} #{short_url} #{self.twitt_suffix}" begin if to_tweet.image @client.update_with_media(message, open(URI.escape(to_tweet.image)) ) else @client.update(message) end rescue end [message, to_tweet.id] end end #Due au limitation commercial du produit, une fois par jour, cette methode créer les tweet a lancer (data vide just l'horaire), il randomize l'heure du lancement def self.daily_prepare RssProvider.all.each do |rss_provider| hour = 23 sum_rand = 0 rss_provider.frequence.times do |t| my_limit = hour / (rss_provider.frequence-t+1) rand = rand(my_limit)+1 sum_rand += rand #puts "*****limit: #{my_limit} / rand :#{rand} / sum_rand#{sum_rand}" hour -= rand rss_provider.rss_twitts.build(:to_send_at => DateTime.tomorrow.at_beginning_of_day.advance(:hours => sum_rand, :minutes => rand(60))) end rss_provider.save end end # cherche si il est temps de lancer un twitt, si oui... il le lance def self.find_to_send RssTwitt.where("to_send_at<? and ISNULL(send_at)", Time.now).each do |rss_twitt| rss_twitt.rss_provider.load_and_update rss_twitt.twitt, rss_twitt.rss_item_id = rss_twitt.rss_provider.tweet_me rss_twitt.send_at = Time.now rss_twitt.save end RtTwittHistory.where("to_send_at<? and ISNULL(send_at)", Time.now).each do |rt_twitt_history| to_twitt = rt_twitt_history.rt_twitt.rss_provider.rss_twitts.where('NOT ISNULL(send_at)').order('rt_count asc').first if to_twitt prefix = "RT #{to_twitt.rss_provider.user_twitter.username} : " message = "#{prefix} #{ApplicationController.helpers.truncate(to_twitt.twitt, :length => 140-prefix.length)}" begin @client = Twitter::Client.new( :oauth_token => rt_twitt_history.rt_twitt.user_twitter.twitter_token, :oauth_token_secret => rt_twitt_history.rt_twitt.user_twitter.twitter_secret_token ) @client.update(message) to_twitt.rt_count +=1 rescue end rt_twitt_history.twitt = message rt_twitt_history.send_at = Time.now rt_twitt_history.save to_twitt.save end end end end
require_relative 'spec_helper' require 'stringio' require 'awesome_print' basedir = File.absolute_path File.join(File.dirname(__FILE__)) dirname = File.join(basedir, 'items') def check_output(logoutput, sample_out) sample_out = sample_out.lines.to_a.map {|x| x.strip} output = logoutput.string.lines.to_a.map {|x| x[/(?<=\] ).*/].strip} # puts 'output:' # ap output expect(output.size).to eq sample_out.size output.each_with_index do |o, i| expect(o).to eq sample_out[i] end end def check_status_log(status_log, sample_status_log) # puts 'status_log:' # status_log.each { |e| ap e } expect(status_log.size).to eq sample_status_log.size sample_status_log.each_with_index do |h, i| h.keys.each {|key| expect(status_log[i][key.to_s]).to eq h[key]} end end context 'TestWorkflow' do before :each do # noinspection RubyResolve ::Libis::Workflow.configure do |cfg| cfg.itemdir = dirname cfg.taskdir = File.join(basedir, 'tasks') cfg.workdir = File.join(basedir, 'work') cfg.logger.appenders = ::Logging::Appenders.string_io('StringIO', layout: ::Libis::Tools::Config.get_log_formatter) end end let(:logoutput) {::Libis::Workflow::Config.logger.appenders.first.sio} let(:workflow) { workflow = ::Libis::Workflow::Workflow.new workflow.configure( name: 'TestWorkflow', description: 'Workflow for testing', tasks: [ {class: 'CollectFiles', recursive: true}, { name: 'ProcessFiles', recursive: false, tasks: [ {class: 'ChecksumTester', recursive: true}, {class: 'CamelizeName', :recursive => true} ] } ], input: { dirname: {default: '.', propagate_to: 'CollectFiles#location'}, checksum_type: {default: 'SHA1', propagate_to: 'ChecksumTester'} } ) workflow } let(:job) { job = ::Libis::Workflow::Job.new job.configure( name: 'TestJob', description: 'Job for testing', workflow: workflow, run_object: 'TestRun', input: {dirname: dirname, checksum_type: 'SHA256'}, ) job } it 'should contain three tasks' do expect(workflow.config['tasks'].size).to eq 2 expect(workflow.config['tasks'].first['class']).to eq 'CollectFiles' expect(workflow.config['tasks'].last['name']).to eq 'ProcessFiles' end # noinspection RubyResolve it 'should camelize the workitem name' do run = job.execute expect(run.options['CollectFiles']['location']).to eq dirname expect(run.size).to eq 1 expect(run.items.size).to eq 1 expect(run.items.first.class).to eq TestDirItem expect(run.items.first.size).to eq 3 expect(run.items.first.items.size).to eq 3 expect(run.items.first.first.class).to eq TestFileItem expect(run.items.first.name).to eq 'Items' run.items.first.each_with_index do |x, i| expect(x.name).to eq %w'TestDirItem.rb TestFileItem.rb TestRun.rb'[i] end end it 'should return expected debug output' do run = job.execute check_output logoutput, <<STR INFO -- Run - TestRun : Ingest run started. INFO -- Run - TestRun : Running subtask (1/2): CollectFiles DEBUG -- CollectFiles - TestRun : Processing subitem (1/1): items DEBUG -- CollectFiles - items : Processing subitem (1/3): test_dir_item.rb DEBUG -- CollectFiles - items : Processing subitem (2/3): test_file_item.rb DEBUG -- CollectFiles - items : Processing subitem (3/3): test_run.rb DEBUG -- CollectFiles - items : 3 of 3 subitems passed DEBUG -- CollectFiles - TestRun : 1 of 1 subitems passed INFO -- Run - TestRun : Running subtask (2/2): ProcessFiles INFO -- ProcessFiles - TestRun : Running subtask (1/2): ChecksumTester DEBUG -- ProcessFiles/ChecksumTester - TestRun : Processing subitem (1/1): items DEBUG -- ProcessFiles/ChecksumTester - items : Processing subitem (1/3): test_dir_item.rb DEBUG -- ProcessFiles/ChecksumTester - items : Processing subitem (2/3): test_file_item.rb DEBUG -- ProcessFiles/ChecksumTester - items : Processing subitem (3/3): test_run.rb DEBUG -- ProcessFiles/ChecksumTester - items : 3 of 3 subitems passed DEBUG -- ProcessFiles/ChecksumTester - TestRun : 1 of 1 subitems passed INFO -- ProcessFiles - TestRun : Running subtask (2/2): CamelizeName DEBUG -- ProcessFiles/CamelizeName - TestRun : Processing subitem (1/1): items DEBUG -- ProcessFiles/CamelizeName - Items : Processing subitem (1/3): test_dir_item.rb DEBUG -- ProcessFiles/CamelizeName - Items : Processing subitem (2/3): test_file_item.rb DEBUG -- ProcessFiles/CamelizeName - Items : Processing subitem (3/3): test_run.rb DEBUG -- ProcessFiles/CamelizeName - Items : 3 of 3 subitems passed DEBUG -- ProcessFiles/CamelizeName - TestRun : 1 of 1 subitems passed INFO -- ProcessFiles - TestRun : Done INFO -- Run - TestRun : Done STR check_status_log run.status_log, [ {task: 'Run', status: :DONE, progress: 2, max: 2}, {task: 'CollectFiles', status: :DONE, progress: 1, max: 1}, {task: 'ProcessFiles', status: :DONE, progress: 2, max: 2}, {task: 'ProcessFiles/ChecksumTester', status: :DONE, progress: 1, max: 1}, {task: 'ProcessFiles/CamelizeName', status: :DONE, progress: 1, max: 1}, ] check_status_log run.items.first.status_log, [ {task: 'CollectFiles', status: :DONE, progress: 3, max: 3}, {task: 'ProcessFiles/ChecksumTester', status: :DONE, progress: 3, max: 3}, {task: 'ProcessFiles/CamelizeName', status: :DONE, progress: 3, max: 3}, ] check_status_log run.items.first.items.first.status_log, [ {task: 'CollectFiles', status: :DONE, progress: nil, max: nil}, {task: 'ProcessFiles/ChecksumTester', status: :DONE, progress: nil, max: nil}, {task: 'ProcessFiles/CamelizeName', status: :DONE, progress: nil, max: nil}, ] end end context 'Test run_always' do before :each do # noinspection RubyResolve ::Libis::Workflow.configure do |cfg| cfg.itemdir = dirname cfg.taskdir = File.join(basedir, 'tasks') cfg.workdir = File.join(basedir, 'work') cfg.logger.appenders = ::Logging::Appenders.string_io('StringIO', layout: ::Libis::Tools::Config.get_log_formatter) cfg.logger.level = :INFO end end let(:logoutput) {::Libis::Workflow::Config.logger.appenders.first.sio} let(:workflow) { workflow = ::Libis::Workflow::Workflow.new workflow.configure( name: 'TestRunAlways', description: 'Workflow for testing run_always options', tasks: [ {class: 'CollectFiles', recursive: true}, {class: 'ProcessingTask', recursive: true}, {class: 'FinalTask', recursive: true} ], input: { dirname: {default: '.', propagate_to: 'CollectFiles#location'}, processing: {default: 'success', propagate_to: 'ProcessingTask#config'}, force_run: {default: false, propagate_to: 'FinalTask#run_always'} } ) workflow } let(:processing) {'success'} let(:force_run) {false} let(:job) { job = ::Libis::Workflow::Job.new job.configure( name: 'TestJob', description: 'Job for testing run_always', workflow: workflow, run_object: 'TestRun', input: {dirname: dirname, processing: processing, force_run: force_run}, ) job } let(:run) {job.execute} context 'without forcing final task' do let(:force_run) {false} context 'when processing successfully' do let(:processing) {'success'} it 'should run final task' do run check_output logoutput, <<STR INFO -- Run - TestRun : Ingest run started. INFO -- Run - TestRun : Running subtask (1/3): CollectFiles INFO -- Run - TestRun : Running subtask (2/3): ProcessingTask INFO -- ProcessingTask - TestRun : Task success INFO -- ProcessingTask - TestRun : Task success INFO -- ProcessingTask - TestRun : Task success INFO -- Run - TestRun : Running subtask (3/3): FinalTask INFO -- FinalTask - TestRun : Final processing of test_dir_item.rb INFO -- FinalTask - TestRun : Final processing of test_file_item.rb INFO -- FinalTask - TestRun : Final processing of test_run.rb INFO -- Run - TestRun : Done STR check_status_log run.status_log, [ {task: 'Run', status: :DONE, progress: 3, max: 3}, {task: 'CollectFiles', status: :DONE, progress: 1, max: 1}, {task: 'ProcessingTask', status: :DONE, progress: 1, max: 1}, {task: 'FinalTask', status: :DONE, progress: 1, max: 1}, ] check_status_log run.items.first.status_log, [ {task: 'CollectFiles', status: :DONE, progress: 3, max: 3}, {task: 'ProcessingTask', status: :DONE, progress: 3, max: 3}, {task: 'FinalTask', status: :DONE, progress: 3, max: 3}, ] check_status_log run.items.first.items.first.status_log, [ {task: 'CollectFiles', status: :DONE}, {task: 'ProcessingTask', status: :DONE}, {task: 'FinalTask', status: :DONE}, ] end end context 'when stopped with async_halt' do let(:processing) {'async_halt'} it 'should not run final task' do run check_output logoutput, <<STR INFO -- Run - TestRun : Ingest run started. INFO -- Run - TestRun : Running subtask (1/3): CollectFiles INFO -- Run - TestRun : Running subtask (2/3): ProcessingTask ERROR -- ProcessingTask - TestRun : Task failed with async_halt status ERROR -- ProcessingTask - TestRun : Task failed with async_halt status ERROR -- ProcessingTask - TestRun : Task failed with async_halt status WARN -- ProcessingTask - items : 3 subitem(s) halted in async process WARN -- ProcessingTask - TestRun : 1 subitem(s) halted in async process WARN -- Run - TestRun : 1 subtask(s) halted in async process INFO -- Run - TestRun : Waiting for halted async process STR check_status_log run.status_log ,[ {task: 'Run', status: :ASYNC_HALT, progress: 2, max: 3}, {task: 'CollectFiles', status: :DONE, progress: 1, max: 1}, {task: 'ProcessingTask', status: :ASYNC_HALT, progress: 1, max: 1}, ] check_status_log run.items.first.status_log, [ {task: 'CollectFiles', status: :DONE, progress: 3, max: 3}, {task: 'ProcessingTask', status: :ASYNC_HALT, progress: 3, max: 3}, ] check_status_log run.items.first.items.first.status_log, [ {task: 'CollectFiles', status: :DONE}, {task: 'ProcessingTask', status: :ASYNC_HALT}, ] end end context 'when stopped with fail' do let(:processing) {'fail'} it 'should not run final task' do run check_output logoutput, <<STR INFO -- Run - TestRun : Ingest run started. INFO -- Run - TestRun : Running subtask (1/3): CollectFiles INFO -- Run - TestRun : Running subtask (2/3): ProcessingTask ERROR -- ProcessingTask - TestRun : Task failed with failed status ERROR -- ProcessingTask - TestRun : Task failed with failed status ERROR -- ProcessingTask - TestRun : Task failed with failed status ERROR -- ProcessingTask - items : 3 subitem(s) failed ERROR -- ProcessingTask - TestRun : 1 subitem(s) failed ERROR -- Run - TestRun : 1 subtask(s) failed INFO -- Run - TestRun : Failed STR check_status_log run.status_log, [ {task: 'Run', status: :FAILED, progress: 2, max: 3}, {task: 'CollectFiles', status: :DONE, progress: 1, max: 1}, {task: 'ProcessingTask', status: :FAILED, progress: 1, max: 1}, ] check_status_log run.items.first.status_log, [ {task: 'CollectFiles', status: :DONE, progress: 3, max: 3}, {task: 'ProcessingTask', status: :FAILED, progress: 3, max: 3}, ] check_status_log run.items.first.items.first.status_log, [ {task: 'CollectFiles', status: :DONE}, {task: 'ProcessingTask', status: :FAILED}, ] end end context 'when stopped with error' do let(:processing) {'error'} it 'should not run final task' do run check_output logoutput, <<STR INFO -- Run - TestRun : Ingest run started. INFO -- Run - TestRun : Running subtask (1/3): CollectFiles INFO -- Run - TestRun : Running subtask (2/3): ProcessingTask ERROR -- ProcessingTask - items/test_dir_item.rb : Error processing subitem (1/3): Task failed with WorkflowError exception ERROR -- ProcessingTask - items/test_file_item.rb : Error processing subitem (2/3): Task failed with WorkflowError exception ERROR -- ProcessingTask - items/test_run.rb : Error processing subitem (3/3): Task failed with WorkflowError exception ERROR -- ProcessingTask - items : 3 subitem(s) failed ERROR -- ProcessingTask - TestRun : 1 subitem(s) failed ERROR -- Run - TestRun : 1 subtask(s) failed INFO -- Run - TestRun : Failed STR check_status_log run.status_log, [ {task: 'Run', status: :FAILED, progress: 2, max: 3}, {task: 'CollectFiles', status: :DONE, progress: 1, max: 1}, {task: 'ProcessingTask', status: :FAILED, progress: 1, max: 1}, ] check_status_log run.items.first.status_log, [ {task: 'CollectFiles', status: :DONE, progress: 3, max: 3}, {task: 'ProcessingTask', status: :FAILED, progress: 0, max: 3}, ] check_status_log run.items.first.items.first.status_log, [ {task: 'CollectFiles', status: :DONE}, {task: 'ProcessingTask', status: :FAILED}, ] end end context 'when stopped with abort' do let(:processing) {'abort'} it 'should not run final task' do run check_output logoutput, <<STR INFO -- Run - TestRun : Ingest run started. INFO -- Run - TestRun : Running subtask (1/3): CollectFiles INFO -- Run - TestRun : Running subtask (2/3): ProcessingTask FATAL -- ProcessingTask - items/test_dir_item.rb : Fatal error processing subitem (1/3): Task failed with WorkflowAbort exception ERROR -- ProcessingTask - items : 1 subitem(s) failed ERROR -- ProcessingTask - TestRun : 1 subitem(s) failed ERROR -- Run - TestRun : 1 subtask(s) failed INFO -- Run - TestRun : Failed STR check_status_log run.status_log, [ {task: 'Run', status: :FAILED, progress: 2, max: 3}, {task: 'CollectFiles', status: :DONE, progress: 1, max: 1}, {task: 'ProcessingTask', status: :FAILED, progress: 1, max: 1}, ] check_status_log run.items.first.status_log, [ {task: 'CollectFiles', status: :DONE, progress: 3, max: 3}, {task: 'ProcessingTask', status: :FAILED, progress: 0, max: 3}, ] check_status_log run.items.first.items.first.status_log, [ {task: 'CollectFiles', status: :DONE}, {task: 'ProcessingTask', status: :FAILED}, ] end end end context 'with forcing final task' do let(:force_run) {true} context 'when processing successfully' do let(:processing) {'success'} it 'should run final task' do run check_output logoutput, <<STR INFO -- Run - TestRun : Ingest run started. INFO -- Run - TestRun : Running subtask (1/3): CollectFiles INFO -- Run - TestRun : Running subtask (2/3): ProcessingTask INFO -- ProcessingTask - TestRun : Task success INFO -- ProcessingTask - TestRun : Task success INFO -- ProcessingTask - TestRun : Task success INFO -- Run - TestRun : Running subtask (3/3): FinalTask INFO -- FinalTask - TestRun : Final processing of test_dir_item.rb INFO -- FinalTask - TestRun : Final processing of test_file_item.rb INFO -- FinalTask - TestRun : Final processing of test_run.rb INFO -- Run - TestRun : Done STR check_status_log run.status_log, [ {task: 'Run', status: :DONE, progress: 3, max: 3}, {task: 'CollectFiles', status: :DONE, progress: 1, max: 1}, {task: 'ProcessingTask', status: :DONE, progress: 1, max: 1}, {task: 'FinalTask', status: :DONE, progress: 1, max: 1}, ] check_status_log run.items.first.status_log, [ {task: 'CollectFiles', status: :DONE, progress: 3, max: 3}, {task: 'ProcessingTask', status: :DONE, progress: 3, max: 3}, {task: 'FinalTask', status: :DONE, progress: 3, max: 3}, ] check_status_log run.items.first.items.first.status_log, [ {task: 'CollectFiles', status: :DONE}, {task: 'ProcessingTask', status: :DONE}, {task: 'FinalTask', status: :DONE}, ] end end context 'when stopped with async_halt' do let(:processing) {'async_halt'} it 'should run final task' do run check_output logoutput, <<STR INFO -- Run - TestRun : Ingest run started. INFO -- Run - TestRun : Running subtask (1/3): CollectFiles INFO -- Run - TestRun : Running subtask (2/3): ProcessingTask ERROR -- ProcessingTask - TestRun : Task failed with async_halt status ERROR -- ProcessingTask - TestRun : Task failed with async_halt status ERROR -- ProcessingTask - TestRun : Task failed with async_halt status WARN -- ProcessingTask - items : 3 subitem(s) halted in async process WARN -- ProcessingTask - TestRun : 1 subitem(s) halted in async process INFO -- Run - TestRun : Running subtask (3/3): FinalTask INFO -- FinalTask - TestRun : Final processing of test_dir_item.rb INFO -- FinalTask - TestRun : Final processing of test_file_item.rb INFO -- FinalTask - TestRun : Final processing of test_run.rb WARN -- Run - TestRun : 1 subtask(s) halted in async process INFO -- Run - TestRun : Waiting for halted async process STR check_status_log run.status_log, [ {task: 'Run', status: :ASYNC_HALT, progress: 3, max: 3}, {task: 'CollectFiles', status: :DONE, progress: 1, max: 1}, {task: 'ProcessingTask', status: :ASYNC_HALT, progress: 1, max: 1}, {task: 'FinalTask', status: :DONE, progress: 1, max: 1}, ] check_status_log run.items.first.status_log, [ {task: 'CollectFiles', status: :DONE, progress: 3, max: 3}, {task: 'ProcessingTask', status: :ASYNC_HALT, progress: 3, max: 3}, {task: 'FinalTask', status: :DONE, progress: 3, max: 3}, ] check_status_log run.items.first.items.first.status_log, [ {task: 'CollectFiles', status: :DONE}, {task: 'ProcessingTask', status: :ASYNC_HALT}, {task: 'FinalTask', status: :DONE}, ] end end context 'when stopped with fail' do let(:processing) {'fail'} it 'should run final task' do run check_output logoutput, <<STR INFO -- Run - TestRun : Ingest run started. INFO -- Run - TestRun : Running subtask (1/3): CollectFiles INFO -- Run - TestRun : Running subtask (2/3): ProcessingTask ERROR -- ProcessingTask - TestRun : Task failed with failed status ERROR -- ProcessingTask - TestRun : Task failed with failed status ERROR -- ProcessingTask - TestRun : Task failed with failed status ERROR -- ProcessingTask - items : 3 subitem(s) failed ERROR -- ProcessingTask - TestRun : 1 subitem(s) failed INFO -- Run - TestRun : Running subtask (3/3): FinalTask INFO -- FinalTask - TestRun : Final processing of test_dir_item.rb INFO -- FinalTask - TestRun : Final processing of test_file_item.rb INFO -- FinalTask - TestRun : Final processing of test_run.rb ERROR -- Run - TestRun : 1 subtask(s) failed INFO -- Run - TestRun : Failed STR check_status_log run.status_log, [ {task: 'Run', status: :FAILED, progress: 3, max: 3}, {task: 'CollectFiles', status: :DONE, progress: 1, max: 1}, {task: 'ProcessingTask', status: :FAILED, progress: 1, max: 1}, {task: 'FinalTask', status: :DONE, progress: 1, max: 1}, ] check_status_log run.items.first.status_log, [ {task: 'CollectFiles', status: :DONE, progress: 3, max: 3}, {task: 'ProcessingTask', status: :FAILED, progress: 3, max: 3}, {task: 'FinalTask', status: :DONE, progress: 3, max: 3}, ] check_status_log run.items.first.items.first.status_log, [ {task: 'CollectFiles', status: :DONE}, {task: 'ProcessingTask', status: :FAILED}, {task: 'FinalTask', status: :DONE}, ] end it 'should run final task during retry' do run logoutput.truncate(0) run.run :retry check_output logoutput, <<STR INFO -- Run - TestRun : Ingest run started. INFO -- Run - TestRun : Running subtask (2/3): ProcessingTask ERROR -- ProcessingTask - TestRun : Task failed with failed status ERROR -- ProcessingTask - TestRun : Task failed with failed status ERROR -- ProcessingTask - TestRun : Task failed with failed status ERROR -- ProcessingTask - items : 3 subitem(s) failed ERROR -- ProcessingTask - TestRun : 1 subitem(s) failed INFO -- Run - TestRun : Running subtask (3/3): FinalTask INFO -- FinalTask - TestRun : Final processing of test_dir_item.rb INFO -- FinalTask - TestRun : Final processing of test_file_item.rb INFO -- FinalTask - TestRun : Final processing of test_run.rb ERROR -- Run - TestRun : 1 subtask(s) failed INFO -- Run - TestRun : Failed STR check_status_log run.status_log, [ {task: 'Run', status: :FAILED, progress: 3, max: 3}, {task: 'CollectFiles', status: :DONE, progress: 1, max: 1}, {task: 'ProcessingTask', status: :FAILED, progress: 1, max: 1}, {task: 'FinalTask', status: :DONE, progress: 1, max: 1}, {task: 'Run', status: :FAILED, progress: 3, max: 3}, {task: 'ProcessingTask', status: :FAILED, progress: 1, max: 1}, {task: 'FinalTask', status: :DONE, progress: 1, max: 1}, ] check_status_log run.items.first.status_log, [ {task: 'CollectFiles', status: :DONE, progress: 3, max: 3}, {task: 'ProcessingTask', status: :FAILED, progress: 3, max: 3}, {task: 'FinalTask', status: :DONE, progress: 3, max: 3}, {task: 'ProcessingTask', status: :FAILED, progress: 3, max: 3}, {task: 'FinalTask', status: :DONE, progress: 3, max: 3}, ] check_status_log run.items.first.items.first.status_log, [ {task: 'CollectFiles', status: :DONE}, {task: 'ProcessingTask', status: :FAILED}, {task: 'FinalTask', status: :DONE}, {task: 'ProcessingTask', status: :FAILED}, {task: 'FinalTask', status: :DONE}, ] end end context 'when stopped with error' do let(:processing) {'error'} it 'should run final task' do run check_output logoutput, <<STR INFO -- Run - TestRun : Ingest run started. INFO -- Run - TestRun : Running subtask (1/3): CollectFiles INFO -- Run - TestRun : Running subtask (2/3): ProcessingTask ERROR -- ProcessingTask - items/test_dir_item.rb : Error processing subitem (1/3): Task failed with WorkflowError exception ERROR -- ProcessingTask - items/test_file_item.rb : Error processing subitem (2/3): Task failed with WorkflowError exception ERROR -- ProcessingTask - items/test_run.rb : Error processing subitem (3/3): Task failed with WorkflowError exception ERROR -- ProcessingTask - items : 3 subitem(s) failed ERROR -- ProcessingTask - TestRun : 1 subitem(s) failed INFO -- Run - TestRun : Running subtask (3/3): FinalTask INFO -- FinalTask - TestRun : Final processing of test_dir_item.rb INFO -- FinalTask - TestRun : Final processing of test_file_item.rb INFO -- FinalTask - TestRun : Final processing of test_run.rb ERROR -- Run - TestRun : 1 subtask(s) failed INFO -- Run - TestRun : Failed STR check_status_log run.status_log, [ {task: 'Run', status: :FAILED, progress: 3, max: 3}, {task: 'CollectFiles', status: :DONE, progress: 1, max: 1}, {task: 'ProcessingTask', status: :FAILED, progress: 1, max: 1}, {task: 'FinalTask', status: :DONE, progress: 1, max: 1}, ] check_status_log run.items.first.status_log, [ {task: 'CollectFiles', status: :DONE, progress: 3, max: 3}, {task: 'ProcessingTask', status: :FAILED, progress: 0, max: 3}, {task: 'FinalTask', status: :DONE, progress: 3, max: 3}, ] check_status_log run.items.first.items.first.status_log, [ {task: 'CollectFiles', status: :DONE}, {task: 'ProcessingTask', status: :FAILED}, {task: 'FinalTask', status: :DONE}, ] end end context 'when stopped with abort' do let(:processing) {'abort'} it 'should run final task' do run check_output logoutput, <<STR INFO -- Run - TestRun : Ingest run started. INFO -- Run - TestRun : Running subtask (1/3): CollectFiles INFO -- Run - TestRun : Running subtask (2/3): ProcessingTask FATAL -- ProcessingTask - items/test_dir_item.rb : Fatal error processing subitem (1/3): Task failed with WorkflowAbort exception ERROR -- ProcessingTask - items : 1 subitem(s) failed ERROR -- ProcessingTask - TestRun : 1 subitem(s) failed INFO -- Run - TestRun : Running subtask (3/3): FinalTask INFO -- FinalTask - TestRun : Final processing of test_dir_item.rb INFO -- FinalTask - TestRun : Final processing of test_file_item.rb INFO -- FinalTask - TestRun : Final processing of test_run.rb ERROR -- Run - TestRun : 1 subtask(s) failed INFO -- Run - TestRun : Failed STR check_status_log run.status_log, [ {task: 'Run', status: :FAILED, progress: 3, max: 3}, {task: 'CollectFiles', status: :DONE, progress: 1, max: 1}, {task: 'ProcessingTask', status: :FAILED, progress: 1, max: 1}, {task: 'FinalTask', status: :DONE, progress: 1, max: 1}, ] check_status_log run.items.first.status_log, [ {task: 'CollectFiles', status: :DONE, progress: 3, max: 3}, {task: 'ProcessingTask', status: :FAILED, progress: 0, max: 3}, {task: 'FinalTask', status: :DONE, progress: 3, max: 3}, ] check_status_log run.items.first.items.first.status_log, [ {task: 'CollectFiles', status: :DONE}, {task: 'ProcessingTask', status: :FAILED}, {task: 'FinalTask', status: :DONE}, ] end end end end
require 'set' require_relative 'simple_dag/vertex' class DAG Edge = Struct.new(:origin, :destination, :properties) attr_reader :vertices # # Create a new Directed Acyclic Graph # # @param [Hash] options configuration options # @option options [Module] mix this module into any created +Vertex+ # def initialize(options = {}) @vertices = [] @mixin = options[:mixin] @n_of_edges = 0 end def add_vertex(payload = {}) Vertex.new(self, payload).tap do |v| v.extend(@mixin) if @mixin @vertices << v end end def add_edge(attrs) origin = attrs[:origin] || attrs[:source] || attrs[:from] || attrs[:start] destination = attrs[:destination] || attrs[:sink] || attrs[:to] || attrs[:end] properties = attrs[:properties] || {} raise ArgumentError, 'Origin must be a vertex in this DAG' unless my_vertex?(origin) raise ArgumentError, 'Destination must be a vertex in this DAG' unless my_vertex?(destination) raise ArgumentError, 'Edge already exists' if origin.successors.include? destination raise ArgumentError, 'A DAG must not have cycles' if origin == destination raise ArgumentError, 'A DAG must not have cycles' if destination.path_to?(origin) @n_of_edges += 1 origin.send :add_edge, destination, properties end # @return Enumerator over all edges in the dag def enumerated_edges Enumerator.new(@n_of_edges) do |e| @vertices.each { |v| v.outgoing_edges.each { |out| e << out } } end end def edges enumerated_edges.to_a end def subgraph(predecessors_of = [], successors_of = []) (predecessors_of + successors_of).each do |v| raise ArgumentError, 'You must supply a vertex in this DAG' unless my_vertex?(v) end result = self.class.new(mixin: @mixin) vertex_mapping = {} # Get the set of predecessors verticies and add a copy to the result predecessors_set = Set.new(predecessors_of) predecessors_of.each { |v| v.ancestors(predecessors_set) } # Get the set of successor vertices and add a copy to the result successors_set = Set.new(successors_of) successors_of.each { |v| v.descendants(successors_set) } (predecessors_set + successors_set).each do |v| vertex_mapping[v] = result.add_vertex(v.payload) end predecessor_edges = predecessors_set.flat_map(&:outgoing_edges).select do |e| predecessors_set.include? e.destination end # Add the edges to the result via the vertex mapping n_of_result_edges = 0 (predecessor_edges | successors_set.flat_map(&:outgoing_edges)).each do |e| n_of_result_edges += 1 vertex_mapping[e.origin].send :add_edge, vertex_mapping[e.destination], e.properties end result.instance_variable_set :@n_of_edges, n_of_result_edges result end # Returns an array of the vertices in the graph in a topological order, i.e. # for every path in the dag from a vertex v to a vertex u, v comes before u # in the array. # # Uses a depth first search. # # Assuming that the method include? of class Set runs in linear time, which # can be assumed in all practical cases, this method runs in O(n+m) where # m is the number of edges and n is the number of vertices. def topological_sort result_size = 0 result = Array.new(@vertices.length) visited = Set.new visit = lambda { |v| return if visited.include? v v.successors.each do |u| visit.call u end visited.add v result_size += 1 result[-result_size] = v } @vertices.each do |v| next if visited.include? v visit.call v end result end private def my_vertex?(v) v.is_a?(Vertex) && (v.dag == self) end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable attr_accessible :email, :password, :password_confirmation, :remember_me, :profile_pic, :reputation, :username, :banned, :image has_many :quips, :dependent => :destroy has_many :feedbacks, :dependent => :destroy has_many :inappropriates has_many :likes validates :username, presence: true validates :reputation, presence: true validates :banned, :inclusion => {:in => [true, false]} after_initialize :defaults end def defaults self.reputation ||= 0 self.profile_pic ||= 'none' self.banned ||= false end
require 'spec_helper' describe A2z::Requests::ItemLookup do subject do A2z::Requests::ItemLookup.new(&block) end let(:block) { proc { } } describe '#params' do specify { subject.params.should be_a Hash } it 'sets the operation' do subject.params['Operation'].should eq 'ItemLookup' end describe 'when id is specified' do describe 'as a string' do let(:block) { proc { id 'ABC123' } } it 'sets the item ID' do subject.params['ItemId'].should eq 'ABC123' end end describe 'as an array' do let(:block) { proc { id %w(ABC123 DEF456) } } it 'sets the comma-delimited item ID' do subject.params['ItemId'].should eq 'ABC123,DEF456' end end end describe 'when category is specified' do let(:block) { proc { category 'Books' } } it 'sets the search index' do subject.params['SearchIndex'].should eq 'Books' end end describe 'when response group is specified' do let(:block) { proc { response_group 'Offers' } } it 'sets the response group' do subject.params['ResponseGroup'].should eq 'Offers' end end describe 'when include reviews summary is specified' do describe 'as true' do let(:block) { proc { include_reviews_summary true } } it 'sets include reviews summary' do subject.params['IncludeReviewsSummary'].should eq 'True' end end describe 'as false' do let(:block) { proc { include_reviews_summary false } } it 'sets include reviews summary' do subject.params['IncludeReviewsSummary'].should eq 'False' end end end describe 'when condition is specified' do let(:block) { proc { condition 'New' } } it 'sets condition' do subject.params['Condition'].should eq 'New' end end describe 'when ID type is specified' do let(:block) { proc { id_type 'ASIN' } } it 'sets ID type' do subject.params['IdType'].should eq 'ASIN' end end describe 'when merchant ID is specified' do let(:block) { proc { merchant_id 'ABC123' } } it 'sets merchant ID' do subject.params['MerchantId'].should eq 'ABC123' end end describe 'when truncate reviews at is specified' do let(:block) { proc { truncate_reviews_at 10 } } it 'sets truncate reviews at' do subject.params['TruncateReviewsAt'].should eq 10 end end describe 'when variation page is specified' do let(:block) { proc { variation_page 10 } } it 'sets variation page' do subject.params['VariationPage'].should eq 10 end end describe 'when nothing is specified' do let(:block) { proc { } } it 'does not set the item ID' do subject.params.should_not have_key 'ItemId' end it 'does not set the search index' do subject.params.should_not have_key 'SearchIndex' end it 'does not set the response group' do subject.params.should_not have_key 'ResponseGroup' end it 'does not set include reviews summary' do subject.params.should_not have_key 'IncludeReviewsSummary' end it 'does not set condition' do subject.params.should_not have_key 'Condition' end it 'does not set ID type' do subject.params.should_not have_key 'IdType' end it 'does not set merchant ID' do subject.params.should_not have_key 'MerchantId' end it 'does not set truncate reviews at' do subject.params.should_not have_key 'TruncateReviewsAt' end it 'does not set variation page' do subject.params.should_not have_key 'VariationPage' end end end end
class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy] def index @users = User.all end def show @posts = Post.where(:user_id => current_user.id) @games = Game.all.sort_by &:title end def admin? admin end private def set_user @user = User.find(params[:id]) end end
# frozen_string_literal: true require 'fun/helpers' require 'fun/monad' module FUN class Just < Monad include Helpers def map(fun = identity) return Just.of(yield(value)) if block_given? Just.of(fun&.call(value)) end def flat_map(fun = identity) return yield(value) if block_given? fun&.call(value) end def fold(just: identity, nothing: nil) just&.call(value) end def inspect "Just(#{value})" end end end
require 'spec_helper' describe Castle::Position do let(:position) { Castle::Position.new } describe "#initialize" do context "when given a FEN" do let(:fen) { 'rnbqkbnr/pppppppp/8/8/8/4P3/PPPP1PPP/RNBQKBNR w KQkq - 0 1'} let(:position) { Castle::Position.new(fen) } it "sets that as its FEN" do position.fen.should eq fen end end context "when not given a FEN" do let(:position) { Castle::Position.new } it "uses the default position" do position.fen.should eq Castle::START_POSITION_FEN end end it "creates a piece for each piece on its board" do position.pieces.count.should eq 32 end end end
require 'spec_helper' describe Destiny do describe '#configuration' do let(:api_key) { 'xyz' } let(:membership_id) { '123' } before do Destiny.configure do |config| config.api_key = api_key config.membership_id = membership_id end end it 'has an api_key' do expect(Destiny.configuration.api_key).to eq api_key end it 'has a membership_id' do expect(Destiny.configuration.membership_id).to eq membership_id end end end
module Admin::CategoriesHelper def show_articles(kind, id) if kind == 1 "查看栏目文章" link_to "查看栏目文章", admin_articles_category_path(id) end end def blank(count) result = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" * count end def show_title(tree) # title = " <span class='badge'>#{tree.count+1}</span> " # title += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" * tree.count blank = 2 * tree.count title = "<p class='badge' style='margin-left:#{blank}em;' >" title += "<span>#{tree.name}</span>" if tree.kind == 0 title += " <span class='cate_fm'>[封面]</span>" end title += "</p>" title end def trees_array(trees) #trees_array = @trees.map { |tree| [sanitize("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" * tree.count)+tree.name, tree.id] } trees_array = [["頂級欄目", 0]] trees.each do |tree| title = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" * tree.count+tree.name if tree.kind == 0 title += " [封面]" end trees_array << [sanitize(title), tree.id] end trees_array end end
# # Cookbook Name:: elk-chef # Recipe:: logstash_install # # Copyright (c) 2016 The Authors, All Rights Reserved. # set package source url case node['platform_family'] when 'debian' source_url = "https://download.elastic.co/logstash/logstash/packages/debian/logstash_#{node['logstash']['version']}-1_all.deb" when 'rhel' source_url = "https://download.elastic.co/logstash/logstash/packages/centos/logstash-#{node['logstash']['version']}-1.noarch.rpm" end # download logstash remote_file 'download_logstash' do source source_url path "/usr/local/src/#{source_url.split('/')[-1]}" owner 'root' group 'root' mode '744' action :create_if_missing end # install logstash package 'install_logstash' do package_name 'logstash' source "/usr/local/src/#{source_url.split('/')[-1]}" action :install end # install logstash plugins node['logstash']['plugins'].each do |plugin| bash "install_logstash_plugin_#{plugin}" do cwd '/opt/logstash' code "./bin/logstash-plugin install #{plugin}" action :run end end unless node['logstash']['plugins'].empty? # add logstash configs node['logstash']['configs'].each do |config| template "config_logstash_#{config}" do source "#{config}.conf.erb" path "/etc/logstash/conf.d/#{config}.conf" owner 'root' group 'root' mode '0644' end end unless node['logstash']['configs'].empty? # start logstash service 'logstash' do case node['platform_family'] when 'debian' service_name 'logstash' when 'rhel' service_name 'logstash.service' end action [ :enable, :start ] end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception include SessionsHelper private def require_user_logged_in unless logged_in? redirect_to login_url, flash: { danger: t("views.flash.non_logged_in_user") } end end end
class Validation < ActiveRecord::Base belongs_to :antibody, :counter_cache => true belongs_to :species belongs_to :validator, :counter_cache => true belongs_to :target, :counter_cache => true has_many :images validates_presence_of :target_id, :antibody_id, :category #, :validator_id has_attached_file :image def result self.passed? ? "Passed" : self.passed.nil? ? "" : "Failed" end end
class KwkSale < ActiveRecord::Base # Concerns include HasSlug # Images mount_uploader :banner, BasicUploader mount_uploader :logo, BasicUploader # Relationships has_many :products, class_name: 'KwkProduct' has_many :sorted_products, -> { active.visible.sorted }, class_name: 'KwkProduct' # Validations validates :name, :slug, :deadline, presence: true # Scopes scope :by_deadline, -> { order(deadline: :desc) } scope :visible, -> { where(visible: true) } scope :active, -> { where(active: true) } scope :ongoing, -> { where(['deadline >= ?', Time.zone.now]).active.visible.by_deadline } scope :archived, -> { where(['deadline <= ?', Time.zone.now]).active.visible.by_deadline } def orders KwkOrder.joins(:line_items).where( 'kwk_line_items.kwk_variant_id' => self.products.map { |product| product.variants.map(&:id).flatten } ).uniq end def ongoing? deadline >= Time.zone.now ? true : false end def past_deadline? !ongoing? end def days_left ongoing? ? (deadline.to_date - Time.zone.now.to_date).to_i : 0 end def total_participants orders.includes(:user).paid.map(&:user).uniq.size # todo: map difference of nils for guest orders end def total_orders orders.paid.size end end
class RemoveLordAndClanIdFromUser < ActiveRecord::Migration[5.0] def change remove_column :users, :lord, :boolean remove_column :users, :clan_id, :integer end end
module RailsLogConverter class CLI module Execute def self.included(receiver) receiver.extend ClassMethods end module ClassMethods def execute parse(ARGV).execute! end def setup_logger ActiveRecord::Base.logger = Logger.new(Configuration.out_stream) ActiveRecord::Base.logger.level = Logger::WARN end def create_database(path) ActiveRecord::Base.establish_connection( :adapter => "sqlite3", :database => path ) UI.puts "Saving output file to #{path}" ActiveRecord::Base.connection ActiveRecord::Migration.verbose = Configuration.debug? ActiveRecord::Migrator.migrate(File.expand_path(File.dirname(__FILE__) + "/../db"), nil) end def close_database ActiveRecord::Base.connection.disconnect! end end def create_database CLI.setup_logger path = "#{directory_path}/#{database_name}" File.delete path if File.exists?(path) CLI.create_database(path) end def close_database CLI.close_database end def execute! create_database Parser.parse_file(file_path) close_database UI.puts "[DONE]" end end end end
require "rails_helper" feature "Home page" do it "has a top-level heading", points: 1 do visit "/" expect(page).to have_selector("h1", text: /Welcome/i) end it "has an unordered list with three items", points: 1 do visit "/" expect(page).to have_tag("ul") do with_tag("li", count: 3) end end it "has a link to Wikipedia", points: 1 do visit "/" expect(page).to have_link("Wikipedia", href: "https://en.wikipedia.org/wiki/Rock–paper–scissors") end it "has some paragraphs", points: 1 do visit "/" expect(page).to have_selector("p", minimum: 3) end it "has a table", points: 1 do visit "/" expect(page).to have_selector("table") end it "has a link to play rock" do visit "/" click_on "Play Rock" expect(page).to have_current_path(/\/rock/) end it "has a link to play paper" do visit "/" click_on "Play Paper" expect(page).to have_current_path(/\/paper/) end it "has a link to play scissors" do visit "/" click_on "Play Scissors" expect(page).to have_current_path(/\/scissors/) end end feature "Move table" do it "has five rows", points: 1 do visit "/" expect(page).to have_tag("table") do with_tag("tr", count: 5) end end it "has the correct number of cells in the first row" do visit "/" expect(page).to have_tag("table") do with_tag("tr:first-child") do with_tag("td", count: 2) end end end it "has the first row's cells sized correctly" do visit "/" expect(page).to have_tag("table") do with_tag("tr:first-child") do with_tag("td[colspan='2']") with_tag("td[colspan='3']") end end end it "has the correct number of cells in the second row" do visit "/" expect(page).to have_tag("table") do with_tag("tr:first-child") do with_tag("td[rowspan='2']") end with_tag("tr:nth-child(2)") do with_tag("td", count: 3) end end end it "has the correct number of cells in the third row" do visit "/" expect(page).to have_tag("table") do with_tag("tr:nth-child(3)") do with_tag("td", count: 5) end end end it "has the correct number of cells in the fourth row" do visit "/" expect(page).to have_tag("table") do with_tag("tr:nth-child(3)") do with_tag("td[rowspan='3']") end with_tag("tr:nth-child(4)") do with_tag("td", count: 4) end end end it "has the correct number of cells in the fifth row" do visit "/" expect(page).to have_tag("table") do with_tag("tr:nth-child(3)") do with_tag("td[rowspan='3']") end with_tag("tr:nth-child(5)") do with_tag("td", count: 4) end end end end feature "Play Rock page" do it "has the correct content" do visit "/rock" expect(page).to have_content("We played rock!") expect(page).to_not have_content("We played paper!") expect(page).to_not have_content("We played scissors!") end it "has a link to the homepage", points: 1 do visit "/rock" click_on "Rules" expect(page).to have_current_path("/").or have_current_path(/\/index/) end it "has a link to play rock" do visit "/" click_on "Play Rock" expect(page).to have_current_path(/\/rock/) end it "has a link to play paper" do visit "/" click_on "Play Paper" expect(page).to have_current_path(/\/paper/) end it "has a link to play scissors" do visit "/" click_on "Play Scissors" expect(page).to have_current_path(/\/scissors/) end end feature "Play Paper page" do it "has the correct content" do visit "/paper" expect(page).to have_content("We played paper!") expect(page).to_not have_content("We played rock!") expect(page).to_not have_content("We played scissors!") end it "has a link to the homepage", points: 1 do visit "/paper" click_on "Rules" expect(page).to have_current_path("/").or have_current_path(/\/index/) end it "has a link to play rock" do visit "/" click_on "Play Rock" expect(page).to have_current_path(/\/rock/) end it "has a link to play paper" do visit "/" click_on "Play Paper" expect(page).to have_current_path(/\/paper/) end it "has a link to play scissors" do visit "/" click_on "Play Scissors" expect(page).to have_current_path(/\/scissors/) end end feature "Play Scissors page" do it "has the correct content" do visit "/scissors" expect(page).to have_content("We played scissors!") expect(page).to_not have_content("We played rock!") expect(page).to_not have_content("We played paper!") end it "has a link to the homepage", points: 1 do visit "/scissors" click_on "Rules" expect(page).to have_current_path("/").or have_current_path(/\/index/) end it "has a link to play rock" do visit "/" click_on "Play Rock" expect(page).to have_current_path(/\/rock/) end it "has a link to play paper" do visit "/" click_on "Play Paper" expect(page).to have_current_path(/\/paper/) end it "has a link to play scissors" do visit "/" click_on "Play Scissors" expect(page).to have_current_path(/\/scissors/) end end
class OneLine desc 'scan @x,y', 'report activity in a map area' option :r, :type => :numeric, :desc => 'search radius', :default => 0 option :dx, :type => :numeric, :desc => 'x search radius' option :dy, :type => :numeric, :desc => 'y search radius' option :objects, :type => :string, :desc => 'objects 1,2,3', :default => '' def scan(coords) actors = Set.new x,y = *coords.sub('@', '').split(',').map(&:to_i) dx = (options[:dx] || options[:r]).to_i dy = (options[:dy] || options[:r]).to_i xr = (x-dx)..(x+dx) yr = (y-dy)..(y+dy) p xr, yr objects = options[:objects].split(',') matching_placements do |log| if xr.cover?(log.x) && yr.cover?(log.y) && (objects.empty? || objects.include?(log.object)) p [log.object, log.x, log.y, log.actor, log.s_time] actors << log.actor end end print_actors(actors) end end
class A1300c attr_reader :options, :name, :field_type, :node def initialize @name = "Name by which resident prefers to be addressed (A1300c)" @field_type = TEXT @node = "A1300C" @options = [] @options << FieldOption.new("") end def set_values_for_type(klass) return "JD" end end
class ChangeWaresToProjectWares < ActiveRecord::Migration[5.2] def change create_table :stock_wares do |t| t.string :name t.string :cat1 t.string :cat2 t.string :cat3 t.string :cat4 t.string :cat5 t.integer :stock_quantity end end end
class AddCitiesIdToUserDetails < ActiveRecord::Migration def self.up add_column :user_details, :cities_id, :integer, :default => 2094941 # London, UK end def self.down remove_column :user_details, :cities_id end end
require 'rails_helper' RSpec.describe User, type: :model do context '[Validations]' do it "ensures the presence of username" do user = User.create(username: "", name: "name", email: "email@email.com", password: "Password1", type: "USER") expect(user.save).to eq(false) end it "ensures the presence of name" do user = User.create(username: "username", name: "", email: "email@email.com", password: "Password1", type: "USER") expect(user.save).to eq(false) end it "ensures the presence of email" do user = User.create(username: "username", name: "name", email: "", password: "Password1", type: "USER") expect(user.save).to eq(false) end it "ensures the presence of password" do user = User.create(username: "username", name: "name", email: "email@email.com", password: "", type: "USER") expect(user.save).to eq(false) end it "ensures the presence of type" do user = User.create(username: "username", name: "name", email: "email@email.com", password: "Password1", type: "") expect(user.save).to eq(false) end it "ensures username uniqueness" do user = User.create!(username: "username", name: "name", email: "email@email.com", password: "Password1", type: "USER") user.save! user2 = User.create(username: "username", name: "name", email: "email2@email.com", password: "Password1", type: "USER") expect(user2.save).to eq(false) expect(user.delete).to eq(true) end it "ensures email uniqueness" do user = User.create!(username: "username", name: "name", email: "email@email.com", password: "Password1", type: "USER") user.save! user2 = User.create(username: "username2", name: "name", email: "email@email.com", password: "Password1", type: "USER") expect(user2.save).to eq(false) expect(user.delete).to eq(true) end it "ensures type is valid" do user = User.create(username: "username", name: "name", email: "email@email.com", password: "Password1", type: "type") bool = (user.type == "USER") or (user.type == "ADMIN") expect(user.save).to eq(bool) end it "ensures email is valid" do user = User.create(username: "username", name: "name", email: "email", password: "Password1", type: "type") bool = (user.email.include? "@" and user.email.include? ".") expect(user.save).to eq(bool) end it "ensures password is valid" do user = User.create(username: "username", name: "name", email: "email@email.com", password: "Password1", type: "type") expect(user.password =~ /[0-9]/).not_to eq(nil) expect(user.password =~ /[a-z]/).not_to eq(nil) expect(user.password =~ /[A-Z]/).not_to eq(nil) expect(user.password.length >= 8) end it "ensures username is valid" do user = User.create(username: "user name", name: "name", email: "email@email.com", password: "Password1", type: "type") bool = !( user.username.include? " ") expect(user.save).to eq(bool) end it "creates a user when validations are passed" do user = User.create(username: "username", name: "name", email: "email@email.com", password: "Password1", type: "USER") expect(user.save!).to eq(true) expect(User.find(user.username).delete).to eq(true) end end context '[Read and Delete]' do subject { @user } before(:all) do @user = User.create(username: "username", name: "name", email: "email@email.com", password: "Password1", type: "USER") @user.save! end it "reads a created user with a given username" do expect(User.find(@user.username)).to eq(@user) end it "deletes a created user with a given username" do expect(@user.delete).to eq(true) end end end
class City < ApplicationRecord has_many :departed_cargos, foreign_key: :departure_city_id, class_name: 'Cargo' has_many :delivered_cargos, foreign_key: :delivery_city_id, class_name: 'Cargo' geocoded_by :name after_validation :geocode def self.by_departure self .joins(:departed_cargos) .group('cities.id') .select('cities.id, cities.name, COUNT(cargos.id) as cargos_count') .order('cargos_count DESC') end end
require "puppet/provider/package" require "tmpdir" Puppet::Type.type(:package).provide(:dmg, :parent => :application) do desc "Package management using Disk Images from the Internet." commands :hdiutil => "hdiutil", :yes => "yes" private def dmg "image.dmg" end def download curl("-o", dmg, "-L", resource[:source]) end def extract execute("yes | hdiutil attach #{dmg} -nobrowse -mountpoint mount") end def install_application FileUtils.cp_r("mount/#{resource[:name]}.app", "/Applications") end def cleanup hdiutil(:detach, "mount") end end
require 'digest' require 'ipaddr' module WebShield class IPShield < Shield # Options # whitelist: options, defualt [], like 172.10.10.10 172.10.10.10/16 # blacklist: options, default [], like 172.10.10.10 172.10.10.10/16 allow_option_keys :whitelist, :blacklist def initialize(id, shield_path, options, config) super @options[:dictatorial] = true push_to_whitelist(options[:whitelist]) if options[:whitelist] push_to_blacklist(options[:blacklist]) if options[:blacklist] end def filter(request) req_path = request.path return unless path_matcher.match(req_path) if in_blacklist?(request.ip) user = config.user_parser.call(request) write_log(:info, "Blacklist block '#{user}' #{request.request_method} #{req_path}") :block elsif in_whitelist?(request.ip) write_log(:info, "Whitelist pass '#{user}' #{request.request_method} #{req_path}") :pass else nil end end def in_whitelist?(ip) in_ip_list?(get_store_key('whitelist'), ip) end def in_blacklist?(ip) in_ip_list?(get_store_key('blacklist'), ip) end def push_to_whitelist(ips) config.store.sadd(get_store_key('whitelist'), ips) end def push_to_blacklist(ips) config.store.sadd(get_store_key('blacklist'), ips) end private # TODO optimize it def in_ip_list?(list_key, ip) config.store.smembers(list_key).any? {|ip_range| IPAddr.new(ip_range).include?(ip) } end def get_store_key(list_name) generate_store_key(list_name) end end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'shelter show page', type: :feature do it 'can see shelter with name address city state zip' do visit "/shelters/#{@shelter1.id}" expect(page).to have_content(@shelter1.name) expect(page).to have_content('Address:') expect(page).to have_content(@shelter1.address.to_s) expect(page).to have_content('City:') expect(page).to have_content(@shelter1.city.to_s) expect(page).to have_content('State:') expect(page).to have_content(@shelter1.state.to_s) expect(page).to have_content(@shelter1.state.to_s) expect(page).to have_content('Zip:') visit "/shelters/#{@shelter2.id}" expect(page).to have_content(@shelter2.name) expect(page).to have_content('Address:') expect(page).to have_content(@shelter2.address.to_s) expect(page).to have_content('City:') expect(page).to have_content(@shelter2.city.to_s) expect(page).to have_content('State:') expect(page).to have_content(@shelter2.state.to_s) expect(page).to have_content('Zip:') expect(page).to have_content(@shelter2.zip.to_s) end end
# encoding: UTF-8 # Copyright © Emilio González Montaña # Licence: Attribution & no derivates # * Attribution to the plugin web page URL should be done if you want to use it. # https://redmine.ociotec.com/projects/advanced-roadmap # * No derivates of this plugin (or partial) are allowed. # Take a look to licence.txt file at plugin root folder for further details. require_dependency 'redmine/i18n' module AdvancedRoadmap module RedmineI18nPatch def self.included(base) base.class_eval do def l_days(days) days = days.to_f l((days == 1.0 ? :label_f_day : :label_f_day_plural), :value => ('%.2f' % days.to_f)) end def l_weeks(weeks) weeks = weeks.to_f l((weeks == 1.0 ? :label_f_week : :label_f_week_plural), :value => ('%.2f' % weeks.to_f)) end end end end end
#------------------------------------------------------------------------------- # # Thomas Thomassen # thomas[at]thomthom[dot]net # #------------------------------------------------------------------------------- require 'sketchup.rb' #------------------------------------------------------------------------------- module TT::Plugins::AxisPivot ### MENU & TOOLBARS ### -------------------------------------------------- unless file_loaded?( __FILE__ ) parent_menu = ($tt_menu) ? $tt_menu : UI.menu('Tools') parent_menu.add_item('Pivot around Axis') { self.pivot_tool } end ### MAIN SCRIPT ### ------------------------------------------------------ def self.pivot_tool model = Sketchup.active_model sel = model.selection if sel.single_object? && sel[0].is_a?(Sketchup::ComponentInstance) model.tools.push_tool( Pivot.new( sel[0] ) ) end end class Pivot APERTURE = 10 def initialize(instance) @instance = instance end def activate @mouseover = nil @selected = nil @vector = nil @p = nil @mp = nil @lp = nil end def deactivate(view) view.invalidate end def onMouseMove(flags, x, y, view) pivot,xv,yv,zv = get_axis(view) t = @instance.transformation if @selected @mp = [x, y, 0] #angle = @p.distance(@mp).to_f.degrees / 3.0 angle = ( @lp.y - @mp.y ) / 50.0 tr = Geom::Transformation.rotation(pivot, @vector, angle) #@instance.transformation = @t * tr @instance.transform!( tr ) else @mouseover = nil ph = view.pick_helper ph.do_pick(x,y) xaxis = [pivot, xv] yaxis = [pivot, yv] zaxis = [pivot, zv] if ph.pick_segment(xaxis, x, y) @mouseover = :xaxis elsif ph.pick_segment(yaxis, x, y) @mouseover = :yaxis elsif ph.pick_segment(zaxis, x, y) @mouseover = :zaxis end end @lp = [x, y, 0] view.invalidate end def onLButtonDown(flags, x, y, view) @selected = nil ph = view.pick_helper ph.do_pick(x,y) pivot,xv,yv,zv = get_axis(view) t = @instance.transformation xaxis = [pivot, xv] yaxis = [pivot, yv] zaxis = [pivot, zv] if ph.pick_segment(xaxis, x, y) @selected = :xaxis @vector = t.xaxis elsif ph.pick_segment(yaxis, x, y) @selected = :yaxis @vector = t.yaxis elsif ph.pick_segment(zaxis, x, y) @selected = :zaxis @vector = t.zaxis end if @selected Sketchup.active_model.start_operation('Pivot about Axis') @t = @instance.transformation.clone @p = [x, y, 0] end view.invalidate end def onLButtonUp(flags, x, y, view) Sketchup.active_model.commit_operation if @selected @selected = nil @mp = nil view.invalidate end def draw(view) if @selected && @mp p1 = @p.map { |n| n + 0.5 } p2 = @mp.map { |n| n + 0.5} view.line_width = 1 view.drawing_color = [64,64,64] view.line_stipple = '-' view.draw2d(GL_LINES, p1, [p1.x, p2.y, 0]) view.line_stipple = '.' view.draw2d(GL_LINES, [p1.x, p2.y, 0], p2) end # Axes info pivot,x,y,z = get_axis(view) # Vectors draw_vector(pivot, x, [255,0,0], view, @mouseover == :xaxis) # X draw_vector(pivot, y, [0,255,0], view, @mouseover == :yaxis) # Y draw_vector(pivot, z, [0,0,255], view, @mouseover == :zaxis) # Z # Points view.line_width = 2 view.line_stipple = '' view.draw_points(pivot, 10, 4, [0,0,0]) # Pivot view.draw_points(x, 5, 1, [255,0,0]) # X view.draw_points(y, 5, 1, [0,255,0]) # Y view.draw_points(z, 5, 1, [0,0,255]) # Z end def draw_vector(pt1, pt2, color, view, selected = false) view.line_width = (selected) ? 4 : 2 view.line_stipple = '' view.drawing_color = color p1 = view.screen_coords(pt1) p2 = view.screen_coords(pt2) view.draw2d(GL_LINES, p1, p2) end def get_axis(view) t = @instance.transformation pivot = t.origin size = view.pixels_to_model(80, pivot) x = pivot.offset(t.xaxis, size) y = pivot.offset(t.yaxis, size) z = pivot.offset(t.zaxis, size) [pivot, x, y, z] end end # class Pivot ### HELPER METHODS ### --------------------------------------------------- def self.start_operation(name) model = Sketchup.active_model if Sketchup.version.split('.')[0].to_i >= 7 model.start_operation(name, true) else model.start_operation(name) end end end # module #------------------------------------------------------------------------------- file_loaded( __FILE__ ) #-------------------------------------------------------------------------------
class ChangeColumnOfTweets < ActiveRecord::Migration def change change_column :tweets, :text, :string, null: false change_column :tweets, :image, :string, null: false end end
class Machine < ApplicationRecord geocoded_by :location after_validation :geocode, if: :will_save_change_to_location? has_many :bookings, dependent: :destroy belongs_to :user validates :make, inclusion: {in: ["Massey-Ferguson", "New Holland", "International", "Bobard", "McCormick", "Kobatsu", "Manitou", "John Deere", "Deutz-Fahr", "Someca"]}, presence: true validates :year, inclusion: {in: (1990..2018)}, presence: true validates :min_hours, presence: true validates :category, inclusion: {in: ["Tractor","Combine Harvester","Sower","Sprayer","Shredder","Spreader","Rolls","Sidewinder","Vineyard Tractor"]}, presence: true validates :location, presence: true validates :price_per_hour, presence:true, numericality: true mount_uploader :photo, PhotoUploader include AlgoliaSearch algoliasearch per_environment: true do attribute :location, :category, :make, :photo, :id, :price_per_hour end end
class FlightsController < ApplicationController def index # return if no params params = params_flights # get all airports for the select field @airports = Airport.all return if params == {} from_id = params[:airport][:departure_airport_id].to_i to_id = params[:airport][:arrival_airport_id].to_i departure_date = params[:departure_date] # retrieve airport codes if IDs passed as parameters @departure_airport_code = Airport.find(from_id).airport_code if from_id > 0 @arrival_airport_code = Airport.find(to_id).airport_code if to_id > 0 # search flights related to specified IDs @flights = Flight.search(from_id, to_id, departure_date) end private def params_flights params.permit({ airport: [:departure_airport_id, :arrival_airport_id] }, :departure_date) end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe HeightsController, type: :controller do before do @user = FactoryBot.create :user, email: 'joao@example.org' sign_in @user @existing_profile = FactoryBot.create :profile, email: 'joao@example.org', user: @user end after do sign_out @user end describe 'GET #index' do it 'returns a success response' do get :index, params: { profile_email: @existing_profile.email } expect(response).to be_successful end it 'returns a page with all heights registered from an user' do get :index, params: { profile_email: @existing_profile.email } expect(assigns(:heights)).to eq(@existing_profile.heights) end it 'render a index page' do get :index, params: { profile_email: @existing_profile.email } expect(response).to render_template(:index) end end describe 'GET #new' do it 'returns a success response' do get :new, params: { profile_email: @existing_profile.email } expect(response).to be_successful end it 'render a new height page' do get :new, params: { profile_email: @existing_profile.email } expect(response).to render_template(:new) end end describe 'GET #edit' do before do @existing_height = FactoryBot.create :height, profile: @existing_profile end it 'returns a success response' do get :edit, params: { profile_email: @existing_profile.email, id: @existing_height.id } expect(response).to be_successful end it 'returns an existing height' do get :edit, params: { profile_email: @existing_profile.email, id: @existing_height.id } expect(assigns(:height)).to eq(@existing_height) end it 'returns an edit view' do get :edit, params: { profile_email: @existing_profile.email, id: @existing_height.id } expect(response).to render_template(:edit) end end describe 'POST #create' do context 'with valid params' do let(:valid_attributes) do { value: '70', date: 1.day.ago } end it 'creates a new Height' do expect do post :create, params: { profile_email: @existing_profile.email, height: valid_attributes } end.to change(@existing_profile.heights, :count).by(1) end it 'redirects to the heights page' do post :create, params: { profile_email: @existing_profile.email, height: valid_attributes } expect(response).to redirect_to( profile_heights_path(profile_email: @existing_profile.email) ) end end context 'with invalid params' do let(:invalid_attributes) do { value: '' } end it "doesn't creates a new height" do expect do post :create, params: { profile_email: @existing_profile.email, height: invalid_attributes } end.to_not change(@existing_profile.heights, :count) end it 'stay in the new height' do post :create, params: { profile_email: @existing_profile.email, height: invalid_attributes } expect(response).to render_template(:new) end end end describe 'PUT #update' do before do @existing_height = FactoryBot.create :height, profile: @existing_profile @original_height_value = @existing_height.value @original_height_date = @existing_height.date end context 'with valid params' do let(:new_attributes) do { value: '1.85', date: '2018-06-25' } end it 'updates the requested profile' do put :update, params: { profile_email: @existing_profile.email, id: @existing_height.id, height: new_attributes } @existing_height.reload expect(@existing_height.value).to eq(new_attributes[:value].to_f) expect(@existing_height.date).to eq(new_attributes[:date].to_date) expect(@existing_height.profile).to eq(@existing_profile) end it 'redirects to the heights page' do put :update, params: { profile_email: @existing_profile.email, id: @existing_height.id, height: new_attributes } expect(response).to redirect_to( profile_heights_path(profile_email: @existing_profile.email) ) end end context 'with invalid params' do let(:invalid_attributes) do { value: '' } end it "doesn't change the Height" do put :update, params: { profile_email: @existing_profile.email, id: @existing_height.id, height: invalid_attributes } @existing_height.reload expect(@existing_height.value).to eq(@original_height_value) expect(@existing_height.date).to eq(@original_height_date) expect(@existing_height.profile).to eq(@existing_profile) end it 'stay in the edit height' do put :update, params: { profile_email: @existing_profile.email, id: @existing_height.id, height: invalid_attributes } expect(response).to render_template(:edit) end end end describe 'DELETE #destroy' do before do @existing_height = FactoryBot.create :height, profile: @existing_profile end it 'destroys the requested beight' do expect do delete :destroy, params: { profile_email: @existing_profile.email, id: @existing_height.to_param } end.to change(Height, :count).by(-1) end it 'redirects to the heights list' do delete :destroy, params: { profile_email: @existing_profile.email, id: @existing_height.to_param } expect(response).to redirect_to( profile_heights_path(profile_email: @existing_profile.email) ) end end end
class SubscriptionPlan < ActiveRecord::Base include UUIDRecord include ActionView::Helpers::NumberHelper attr_accessible :active, :name, :plan_description, :price_description, :recurring, :stripe_plan_id, :trial_period, :uuid validates :name, presence: true # validates :price_description, presence: true validates :stripe_plan_id, presence: true validates :recurring, inclusion: [true, false] validates :active, inclusion: [true, false] belongs_to :offer, primary_key: 'uuid', foreign_key: 'offer_uuid' after_initialize :set_defaults def set_defaults self.active = true if self.active.nil? self.recurring = true if self.recurring.nil? end def best_value? self.uuid == self.offer.best_value_plan_uuid end def stripe_plan @stripe_plan ||= Stripe::Plan.retrieve(self.stripe_plan_id) end def name read_attribute(:name) || self.stripe_plan.name end def apply_coupon(coupon) return nil unless coupon case coupon.duration when 'once' @coupon = coupon unless self.recurring when 'repeating', 'forever' @coupon = coupon if self.recurring end @coupon end def price (self.stripe_plan.amount / 100.0).round(2) end def price_per_month plan = self.stripe_plan case plan.interval when 'week' cents = plan.amount.to_f * (52 / plan.interval_count / 12) when 'month' cents = plan.amount.to_f / plan.interval_count when 'year' cents = plan.amount.to_f / (12 * plan.interval_count) end (cents / 100.0).round(2) end def discounted_price return self.price unless @coupon case when @coupon.percent_off discount = self.stripe_plan.amount * @coupon.percent_off / 100.0 when @coupon.amount_off discount = @coupon.amount_off end (stripe_plan.amount - discount) / 100.0 end def term plan = self.stripe_plan if plan.interval_count == 1 case plan.interval when 'week' 'Weekly Subscription' when 'month' 'Monthly Subscription' when 'year' 'Yearly Subscription' end else "x #{plan.interval_count} #{plan.interval.pluralize}" end end def description # read_attribute(:plan_description) case when self.recurring case stripe_plan.interval_count when 1 "a #{stripe_plan.interval}. Cancel anytime." else "every #{stripe_plan.interval_count} #{stripe_plan.interval.pluralize}." end else case stripe_plan.interval_count when 1 "for 1 #{stripe_plan.interval}." else "for #{stripe_plan.interval_count} #{stripe_plan.interval.pluralize}." end end end def price_description read_attribute(:price_description) end # Coupon discounts def discount_description return nil unless @coupon case when @coupon.percent_off discount = number_to_percentage(@coupon.percent_off, precision: 0) when @coupon.amount_off discount = number_to_currency(@coupon.amount_off / 100.0) end case @coupon.duration when 'once' "Save #{discount}." when 'repeating' "Save #{discount} a month for #{@coupon.duration_in_months} months." when 'forever' "Save #{discount}." end end # Discount relative to best plan of the default offer def discount_from_default_plan default_price = Offer.where(default:true).first.best_value_plan.price_per_month this_price = price_per_month 100 - (100.0*(this_price/default_price.to_f)).to_i end end
# Validates that a uuid has the right format class UuidValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) message = options[:message] || 'is not a well-formatted UUID' record.errors[attribute] << message unless GalleryLib.uuid?(value) end end
class Contact < ActiveRecord::Base # We need to add '_attributes' to be accessible so it can be set on the forms attr_accessible :dob, :first_name, :last_name, :emails, :emails_attributes, :addresses, :addresses_attributes, :_delete, :_destroy has_many :emails, :dependent => :destroy has_many :addresses, :dependent => :destroy accepts_nested_attributes_for :emails, :allow_destroy => true, :reject_if => proc { |attributes| attributes['address'].blank? } accepts_nested_attributes_for :addresses, :allow_destroy => true, :reject_if => proc { |attributes| attributes['street_1'].blank? } validates :last_name, :presence => true validates :first_name, :presence => true validates_associated :emails, :addresses end
class AlertWeixinReplyMessageRulesSReplyMessageLength < ActiveRecord::Migration[5.1] def change change_column :weixin_reply_message_rules, :reply_message, :text end end
# ============================================================================= # # MODULE : lib/dispatch_queue_rb/dispatch.rb # PROJECT : DispatchQueue # DESCRIPTION : # # Copyright (c) 2016, Marc-Antoine Argenton. All rights reserved. # ============================================================================= module DispatchQueue module Dispatch Result = Struct.new( :value ) class << self def ncpu() @@ncpu ||= case RUBY_PLATFORM when /darwin|freebsd/ then `sysctl -n hw.ncpu`.to_i when /linux/ then `cat /proc/cpuinfo | grep processor | wc -l`.to_i else 2 end end def default_queue @@default_queue end def main_queue @@main_queue end def synchronize() mutex, condition = ConditionVariablePool.acquire() result = nil result_handler = Proc.new { |r| result = r; mutex.synchronize { condition.signal() } } mutex.synchronize do yield result_handler condition.wait( mutex ) end ConditionVariablePool.release( mutex, condition ) result end def concurrent_map( input_array, target_queue:nil, &task ) group = DispatchGroup.new target_queue ||= default_queue output_results = input_array.map do |e| result = Result.new target_queue.dispatch_async( group:group ) do result.value = task.call( e ) end result end group.wait() output_results.map { |result| result.value } end private @@default_queue = ThreadPoolQueue.new() @@main_queue = ThreadQueue.new() end # class << self end # class Dispatch end # module DispatchQueue
class ConversationsController < ApplicationController before_action :authenticate_user! before_action :set_conversation, :check_participating!, only: [:new, :show, :update] def new redirect_to conversation_path(@conversation) and return if @conversation @message = current_user.messages.build end def index @conversations = Conversation.participating(current_user).order('updated_at DESC') @conversations = @conversations.collect { |conversation| ConversationDecorator.new(conversation, current_user).simple_decorate } @user = UserDecorator.new(current_user).simple_decorate @data = { :conversations => @conversations, :currentUser => @user } render :index end def show @conversation = ConversationDecorator.new(@conversation, current_user).decorate @user = UserDecorator.new(current_user).simple_decorate @data = { :conversation => @conversation, :currentUser => @user } render :show end def update @messages = @conversation.messages.unread @messages.each do |message| message.update_attributes(:unread => false) end @conversation = ConversationDecorator.new(@conversation, current_user).decorate render json: { :conversation => @conversation } end private def set_conversation @conversation = Conversation.find(permitted_params[:id]) end def check_participating! redirect_to '/inbox' unless @conversation.present? && @conversation.participates?(current_user) end def permitted_params params.permit(:id) end end
# frozen_string_literal: true # swagger documentation module Api::V1::AuthController::Docs include Swagger::Blocks # rubocop:disable BlockLength swagger_path "/api/v1/auth/sign_in" do operation :post do key :summary, "Sign in with email and password" key :description, "Signs user in using email and password. "\ "Returns authorization token (JWT token) which will expire in 1 month." key :consumes, ["application/json"] key :produces, ["application/json"] key :tags, ["users"] parameter do key :name, :body_params key :description, "User credentials" key :in, :body key :required, true schema do key :"$ref", :TokenParams end end response 200 do key :description, "User authenticated successfully. Token returned in response." schema do key :"$ref", :Token end end response 401 do key :description, "Invalid email or password" schema do key :"$ref", :ApiError end end response 500 do key :description, "Unexpected error" schema do key :"$ref", :ApiError end end end end swagger_schema :Token do key :required, [:token] property :token do key :description, "JWT token" key :type, :string end end swagger_schema :TokenParams do property :email do key :description, "User email" key :type, :string end property :password do key :description, "User password" key :type, :string end property :unlimited_expiry_time do key :description, "true if you need token without expiration" key :type, :boolean end end end
class Api::V1::LogsController < ApplicationController before_action :authorized, only: [:create, :update] def create log = Log.new(log_params) if log.save render json: log else render json: {errors: log.errors.full_messages} end end def update log = Log.find(params[:id]) log.assign_attributes(log_params) if log.save render json: log else render json: {errors: log.errors.full_messages} end end private def log_params params.permit(:plant_id, :action_id, :amount) end end
#!/usr/bin/env ruby #encoding:UTF-8 require 'getoptlong' # specify the options we accept and initialize # the option parser opts = GetoptLong.new( [ "--iban", "-i", GetoptLong::REQUIRED_ARGUMENT ] ) puts 'ACHTUNG: Eine gültige IBAN bedeutet nicht, dass das Konto existert' # process the parsed options iban = '' opts.each do |opt, arg| case opt when '--iban' iban = arg end end iban.strip! if iban == '' puts 'Usage: ibanValidator --iban IBAN' exit 1 end if !/[0-9A-Za-z]{4,34}/.match(iban) puts 'Die IBAN muss 4 bis 34 Stellen haben und aus Buchstaben und Zahlen bestehen.' exit 3 end # Prüfziffer validieren testiban = iban[4,iban.length] << iban[0,4] testiban.gsub!(/[ABCDEFGHIJKLMNOPQRSTUVWXYZ]/, 'A' => 10, 'B' => 11, 'C' => 12, 'D' => 13, 'E' => 14, 'F'=>15,'G'=>16,'H'=>17,'I'=>18,'J'=>19,'K'=>20,'L'=>21,'M'=>22,'N'=>23,'O'=>24,'P'=>25,'Q'=>26,'R'=>27,'S'=>28,'T'=>29,'U'=>30,'V'=>31,'W'=>32,'X'=>33,'Y'=>34,'Z'=>35) pruef = (testiban.to_i % 97) valid = pruef == 1 ? 'gültig' : 'ungültig' puts "Die angegebene IBAN ist #{valid}!"
require 'test/test_helper' class SitemapsControllerTest < ActionController::TestCase # events should_route :get, '/sitemap.events.xml', :controller => 'sitemaps', :action => 'events' # tags should_route :get, '/sitemap.tags.il.chicago.xml', :controller => 'sitemaps', :action => 'tags', :city => 'chicago', :state => 'il' # locations should_route :get, '/sitemap.locations.il.chicago.1.xml', :controller => 'sitemaps', :action => 'locations', :state => 'il', :city => 'chicago', :index => '1' should_route :get, '/sitemap.locations.il.chicago.10.xml', :controller => 'sitemaps', :action => 'locations', :state => 'il', :city => 'chicago', :index => '10' should_route :get, '/sitemap.locations.cities.medium.1.xml', :controller => 'sitemaps', :action => 'locations', :city_size => 'medium', :index => '1' should_route :get, '/sitemap.locations.cities.small.1.xml', :controller => 'sitemaps', :action => 'locations', :city_size => 'small', :index => '1' should_route :get, '/sitemap.locations.cities.tiny.1.xml', :controller => 'sitemaps', :action => 'locations', :city_size => 'tiny', :index => '1' should_route :get, '/sitemap.index.locations.il.chicago.xml', :controller => 'sitemaps', :action => 'index_locations', :state => 'il', :city => 'chicago' should_route :get, '/sitemap.index.locations.cities.medium.xml', :controller => 'sitemaps', :action => 'index_locations', :city_size => 'medium' # chains should_route :get, '/sitemap.chains.1.xml', :controller => 'sitemaps', :action => 'chains', :id => '1' should_route :get, '/sitemap.index.chains.xml', :controller => 'sitemaps', :action => 'index_chains' # zips should_route :get, '/sitemap.index.zips.xml', :controller => 'sitemaps', :action => 'index_zips' should_route :get, '/sitemap.zips.il.xml', :controller => 'sitemaps', :action => 'zips', :state => 'il' end
class Role < ActiveRecord::Base belongs_to :project belongs_to :parent, :class_name => 'Role' has_many :children, :class_name => 'Role', :foreign_key => 'parent_id' accepts_nested_attributes_for :parent validates :name, :project, true end
require 'eventmachine' module Rack class EMStream include EventMachine::Deferrable def initialize(app, &block) @app, @block = app, block end def each(&b) @callback = b end def call(env) dup._call(env) end def _call(env) result = @app.call(env) result[2].close if result[2].respond_to?(:close) if env['async.callback'] EM.next_tick { env['async.callback'].call [ result[0], result[1], self ] begin result[2].each { |data| EM.next_tick { begin @callback.call(data) rescue => e @callback.call(@block.call(e, env)) if @block end } } rescue => e @callback.call(@block.call(e, env)) if @block end EM.next_tick { succeed } } throw :async else result end end end end
class Work < ApplicationRecord has_many :votes validates :category, :title, :creator, presence: true def self.all_works (type) @all_works = Work.where(category: type) end def self.top_works (type) @all_works = Work.where(category: type).limit(10) end end
# Hash é bem similar aos Array é quase como um dicionario como em Python # Criando o hash capitais = Hash.new # OU # capitais = {} capitais = {acre: 'Rio Branco', sao_paulo: 'São Paulo'} print capitais puts "\n" #Adicionando valores capitais[:minas_gerais] = "Belo Horizonte" print capitais puts "\n" # Vendo as chaves print capitais.keys puts "\n" # Ver so os valores print capitais.values puts "\n" # Para excluir capitais.delete(:acre) print capitais puts "\n" print capitais.values puts "\n" # Selecionar um valor capitais[:sao_paulo] puts "\n" # Descobrir quantidade de elementos dentro do hash print capitais.size puts "\n" # Se ta vazio print capitais.empty?
class AddImagesToProduct < ActiveRecord::Migration[5.2] def change add_column :products, :second_image, :string add_column :products, :third_image, :string end end
# frozen_string_literal: true require 'singleton' module Algorithms module HoltWintersForecasting module Services ## # Methods for validation, used by different components of {Algorithms::HoltWintersForecasting}. class Validation include Singleton def defaults @min_exp_value = 0 @max_exp_value = 1 @teta_min = 2 @teta_max = 3 end def exponential_smoothing_const?(const) return if (@min_exp_value..@max_exp_value).cover?(const) throw StandardError.new("#{self.class.name} - #{__method__} - #{const} must belong\ to [#{@min_exp_value},#{@max_exp_value}].") end def teta_const?(const) return if (@teta_min..@teta_max).cover?(const) error_message = "#{self.class.name} - #{__method__} - #{const} must belong to [#{@teta_min},#{@teta_max}]." throw StandardError.new(error_message) end def actual_value?(value) return if value.class == Integer && value.positive? throw StandardError.new("#{self.class.name} - #{__method__} - #{value} must be\ a non negative #{Integer.name}.") end def confidence_band_upper_value?(value) nil_or_non_negative_float(value) end def baseline?(value) nil_or_non_negative_float(value) end def linear_trend?(value) nil_or_non_negative_float(value) end def seasonal_trend?(value) nil_or_non_negative_float(value) end def estimated_value?(value) nil_or_non_negative_float(value) end def weighted_avg_abs_deviation_value?(value) nil_or_non_negative_float(value) end def seconds?(value) positive_integer?(value) end def weights_percentage?(value) if value.class == Float return if value >= 0.0 && value <= 1.0 end error_message = "#{self.class.name} - #{__method__} - #{value}" error_message += " must be a #{Float.name} in the range [0.0, 1.0]." throw StandardError.new(error_message) end def collections_count?(value) positive_integer?(value) end private def non_negative_float?(value) return if (value.class == Float || value.class == Integer) && value.positive? throw StandardError.new("#{self.class.name} - #{__method__} - #{value} must be\ a non negative #{Float.name} or #{Integer.name}.") end def nil_or_non_negative_float(value) return if value.class == NilClass begin non_negative_float?(value) rescue StandardError => e throw StandardError.new("#{e.message} Or #{NilClass.name}.") end end def positive_integer?(value) return if value.class == Integer && value.positive? error_message = "#{self.class.name} - #{__method__} - #{value} is not a positive #{Integer.name}." throw StandardError.new(error_message) end end end end end
class Location < ApplicationRecord acts_as_mappable default_units: :kms, lat_column_name: :latitude, lng_column_name: :longitude has_many :locations_tags, dependent: :destroy has_many :tags, through: :locations_tags has_many :visited_location, dependent: :destroy has_many :users, through: :visited_location def visit_by(user, recommended = false) user.visited_locations.create!(location_id: id, recommended: recommended) end end
class Employee attr_accessor :name, :salary, :manager @@all = [] def initialize(name, salary) @name = name @salary = salary @@all << self end def manager_name manager.name end def tax_bracket min = @salary - 1000 max = @salary + 1000 @@all.select {|employee| employee.salary.between?(min, max)} end def self.paid_over(salary_amt) self.all.select {|employee| employee.salary > salary_amt} end def self.find_by_department(department) self.all.find {|employee| employee.manager.department == department} end def self.all @@all end end
class AddEInvoiceFieldsToAccount < ActiveRecord::Migration def change add_column :accounts, :e_invoice_resolution_date, :date add_column :accounts, :e_invoice_regional_address, :string end end
require 'mandrill' class MailWorker include Sidekiq::Worker def template mandrill.templates.render @template_name, [{:name => @template_slug}] end def perform(*params) raise 'not implemented' end def mandrill @mandrill ||= Mandrill::API.new end end
class Chapter < ActiveRecord::Base #it will raise exception for question when chapter is deleted right? has_many :questions has_many :batch_set_chapter_topics #, dependent: :destroy has_many :chapter_topics #, dependent: :destroy has_many :topics, through: :chapter_topics validates_presence_of :name end
class ProjectsController < ApplicationController before_filter :find_project, only: [:show,:edit,:update,:destroy] before_filter :authenticate_admin!, except: :index def index @projects=Project.all respond_to do |format| format.js format.html end end def create @project=Project.create(params[:project]) redirect_to root_path end def new @project = Project.new respond_to do |format| format.js end end def show @projects=Project.all end def edit respond_to do |format| format.js end end def update @project.update_attributes(params[:project]) redirect_to root_path end def destroy @project.destroy redirect_to root_path end private def find_project @project =Project.find(params[:id]) end end
class AddDesignatedEndtimeToUsers < ActiveRecord::Migration[5.1] def change add_column :users, :designated_endtime, :datetime, default: Time.current.change(hour: 18, min: 0, sec: 0) end end
require 'spec_helper' describe Game do subject(:game) {FactoryGirl.create(:game)} subject(:second_game) {FactoryGirl.create(:second_game)} subject(:invalid_num_game) {FactoryGirl.build(:invalid_game_max)} subject(:invalid_name_game) {FactoryGirl.build(:invalid_game_names)} subject(:no_name) {FactoryGirl.build(:no_name)} subject(:short_description) {FactoryGirl.build(:short_description)} subject(:long_description) {FactoryGirl.build(:long_description)} subject(:no_age_group) {FactoryGirl.build(:no_age_group)} subject(:zero_pop_value) {FactoryGirl.build(:zero_pop_value)} its "valid with a two names, instructions, example script, max, min, and age group booleans" do expect(game).to be_valid end its "invalid when the max num of players exceeds the min" do expect(invalid_num_game).to_not be_valid end its "invalid without at least one name" do expect(no_name).to_not be_valid end its "invalid with a description less than 10 characters" do expect(short_description).to_not be_valid end its "invalid with a description more than 1000 characters" do expect(long_description).to_not be_valid end its "invalid without an age group selected" do expect(no_age_group).to_not be_valid end its "invalid with two names but one doesn't have a popularity value" do expect(zero_pop_value).to_not be_valid end its "method to see if a game has more than one name works" do expect(game.multiple_names?).to be(true) end its "method to find the most popular name results in the most popular name" do expect(game.most_popular_name.content).to eq("More Popular") end its "method to find the less popular name results in the less name" do expect(game.less_popular_names.first.content).to eq("Middle-ish Popularity") end its "method to see if the exercise/game is appropriate for all ages results in true" do expect(game.all_ages?).to be(true) end its "method to see if the exercise/game is appropriate for all ages results in false" do expect(second_game.all_ages?).to be(false) end end
require 'spec_helper' describe MoneyMover::Dwolla::CustomerBeneficialOwner do let(:firstName) { double 'FirstName' } let(:lastName) { double 'LastName' } let(:dateOfBirth) { double 'DateOfBirth' } let(:ssn) { double 'Ssn' } # required if no passport info let(:owner_passport_params) { double 'controller passport params' } # require if no ssn let(:owner_address_params) { double 'owner address params' } let(:passport_valid?) { true } let(:passport_to_params) { double 'controller passport to_params' } let(:owner_passport) { double 'controller passport', valid?: passport_valid?, to_params: passport_to_params } let(:address_valid?) { true } let(:address_errors) { double 'address errors', full_messages: ["address error msg", "address error msg2"] } let(:address_to_params) { double 'controller passport to_params' } let(:owner_address) { double 'controller address', valid?: address_valid?, errors: address_errors, to_params: address_to_params } let(:required_owner_attrs) do { firstName: firstName, lastName: lastName, dateOfBirth: dateOfBirth, address: owner_address_params, ssn: ssn } end let(:required_owner_attrs_with_passport) do { firstName: firstName, lastName: lastName, dateOfBirth: dateOfBirth, address: owner_address_params, passport: owner_passport_params } end before do allow(MoneyMover::Dwolla::Passport).to receive(:new).with(owner_passport_params) { owner_passport } allow(MoneyMover::Dwolla::ExtendedAddress).to receive(:new).with(owner_address_params) { owner_address } end subject { described_class.new(attrs) } describe '#valid?' do context 'valid - with ssn' do let(:attrs) { required_owner_attrs } it 'returns true' do expect(MoneyMover::Dwolla::ExtendedAddress).to receive(:new).with(owner_address_params) expect(MoneyMover::Dwolla::Passport).to_not receive(:new) expect(owner_address).to receive(:valid?) expect(subject.valid?) #.to eq(true) expect(subject.errors).to be_empty end end context 'valid - with passport' do let(:attrs) { required_owner_attrs_with_passport } it 'returns true' do expect(owner_passport).to receive(:valid?) expect(owner_address).to receive(:valid?) expect(subject.valid?).to eq(true) expect(subject.errors).to be_empty end end context 'invalid - empty params' do let(:attrs) { {} } it 'returns false' do expect(MoneyMover::Dwolla::ExtendedAddress).to_not receive(:new) expect(MoneyMover::Dwolla::Passport).to_not receive(:new) expect(subject.valid?).to eq(false) expect(subject.errors.full_messages).to eq([ "Firstname can't be blank", "Lastname can't be blank", "Dateofbirth can't be blank", "Address can't be blank", "SSN or Passport information must be provided" ]) end end context 'invalid - with invalid address' do let(:attrs) { required_owner_attrs } let(:address_valid?) { false } it 'returns false' do expect(MoneyMover::Dwolla::Passport).to_not receive(:new) expect(owner_address).to receive(:valid?) expect(subject.valid?).to eq(false) expect(subject.errors.full_messages).to eq([ 'Address address error msg', "Address address error msg2" ]) end end context 'invalid - with invalid passport' do let(:attrs) { required_owner_attrs_with_passport } let(:passport_valid?) { false } it 'returns false' do expect(subject.valid?).to eq(false) expect(subject.errors.full_messages).to eq(["SSN or Passport information must be provided"]) end end end describe '#to_params' do context 'all params set' do let(:attrs) do attrs = required_owner_attrs_with_passport attrs[:ssn] = ssn attrs end it 'returns expected values' do expect(subject.to_params).to eq({ firstName: firstName, lastName: lastName, dateOfBirth: dateOfBirth, ssn: ssn, passport: passport_to_params, address: address_to_params }) end end context 'address and passport NOT set' do let(:attrs) do attrs = required_owner_attrs attrs.delete(:address) attrs end it 'returns expected values' do expect(subject.to_params).to eq({ firstName: firstName, lastName: lastName, dateOfBirth: dateOfBirth, ssn: ssn }) end end end end
require "minitest/autorun" require_relative "Lottery.rb" class Lottery_test < Minitest::Test def test_return_empty_when_no_winning my_number = "1234" bash_number = [] assert_equal([], grand_bash(my_number, bash_number)) end def test_no_matches my_number = "1234" bash_number = ["6666", "5764", "3436"] assert_equal([], grand_bash(my_number, bash_number)) end def test_return_match my_number = "1234" bash_number = ["3234", "5646", "1234"] assert_equal(["1234"], grand_bash(my_number, bash_number)) end def test_to_see_if_false_works my_number = "1234567" bash_number = "1234567" assert_equal(false, close_num(my_number, bash_number)) end def test_to_see_if_one_off my_number = "1234567" bash_number = "1234560" assert_equal(true, close_num(my_number, bash_number)) end def test_close_but_no_cigar my_number = "1234" bash_number = ["1239", "2353", "3521"] assert_equal(["1239"], winning_array(my_number, bash_number)) end def test_again my_number = "1234" bash_number = ["1239", "2353", "3521", "1323", "1233","6666"] assert_equal(["1239", "1233"], winning_array(my_number, bash_number)) end def test_for_larger_number my_number = "123456789" bash_number = ["123456783", "123456789", "123456788"] assert_equal(["123456783", "123456788"], winning_array(my_number, bash_number)) end def test_for_larger_number_2 my_number = "123456789" bash_number = ["123456788", "123", "234590", "bob", "2398", "123456787"] assert_equal(["123456788", "123456787"], winning_array(my_number, bash_number)) end def test_for_five my_number = "123457897" bash_number = ["123457891", "888888888", "5678", "37737"] assert_equal(["123457891"], winning_array(my_number, bash_number)) end end
require 'formula' class GoogleAuthenticator < Formula url 'https://github.com/google/google-authenticator/archive/9d858ecaad46b40b004fbc1413daa4143c3f10b8.zip' sha256 'a54bd7e1d1f68f0d134f2cfefbe5b8daf86e0eaf9717dc3fda0cf42cd194d479' head 'https://github.com/google/google-authenticator/', :using => :git homepage 'https://github.com/google/google-authenticator/' def install if ARGV.build_head? libpam_path = "libpam" else libpam_path = "." end system "cd #{libpam_path} && make" bin.install "#{libpam_path}/google-authenticator" (lib+"pam").install "#{libpam_path}/pam_google_authenticator.so" end def caveats; <<-EOS.undent google-authenticator PAM installed to: #{prefix}/lib/pam To actually plug this module into your system you must run: sudo ln -sf #{HOMEBREW_PREFIX}/lib/pam/pam_google_authenticator.so /usr/lib/pam/ Then, add following line to desired PAM configurations under /etc/pam.d/: auth required pam_google_authenticator.so nullok For remote logins (e.g., ssh), /etc/pam.d/sshd is the file you would want to modify. You can safely add it after all the "auth" lines. WARNING: After this point, each user should run google-authenticator command to generate their own secret for two-factor authentication. Otherwise, they may not be able to login with their password alone. For other possible setups, read the long instruction: #{prefix}/README EOS end end
# $Id$ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe WysiwygPreview do def wysiwyg_source_with_images <<-WIZ <p><img src="..." id="artifact_photo_1" /></p> WIZ end describe "previewing with images" do before(:each) do Photo.expects(:find).with(1).returns(@photo = create_content(:type => :photo)) @wys = WysiwygPreview.new(wysiwyg_source_with_images) end it "filter method should add lightview links to all photo thumbnails" do @wys.filter.should match(/lightview/) end end end
# frozen_string_literal: true class ChangeNullTeamsOnParticipations < ActiveRecord::Migration[5.1] def change change_column_null :participations, :team_id, true end end
class CreateWorkOrders < ActiveRecord::Migration def change create_table :work_orders do |t| t.string :name, limit: 255 t.text :description t.date :due_date t.references :responsible, index: true, references: :users #-> responsible_id t.references :work_order_status, index: true, foreign_key: true t.references :organisation, index: true, foreign_key: true t.timestamps null: false end add_foreign_key :work_orders, :users, column: :responsible_id end end
module Fog module DNS class Google class Changes < Fog::Collection model Fog::DNS::Google::Change attribute :zone ## # Enumerates the list of Changes # # @return [Array<Fog::DNS::Google::Change>] List of Changes resources def all requires :zone data = service.list_changes(zone.identity).to_h[:changes] || [] load(data) rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 [] end ## # Fetches the representation of an existing Change # # @param [String] identity Change identity # @return [Fog::DNS::Google::Change] Change resource def get(identity) requires :zone if change = service.get_change(zone.identity, identity).to_h new(change) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end ## # Creates a new instance of a Change # # @return [Fog::DNS::Google::Change] Change resource def new(attributes = {}) requires :zone super({ :zone => zone }.merge!(attributes)) end end end end end
class RemoveAvatorFromPictures < ActiveRecord::Migration def change remove_column :pictures, :avator, :string end end
class RemovePhase3DiscardedCols < ActiveRecord::Migration def change remove_column :phase3s, :externalAudit end end
class TrademarksController < ApplicationController before_action :set_trademark, only:[:show, :destroy] before_action :logged_in_user, only:[:index] before_action :your_page_as_a_user, only:[:new] before_action :your_page, only:[:edit, :show, :destroy] def index @trademarks = current_user.trademarks.all end def new @trademark = Trademark.new end def create @trademark = current_user.trademarks.new(trademark_params) if @trademark.save redirect_to trademarks_path, notice: "商標作成" else render 'new' end end def show end def edit @trademark = Trademark.find(params[:id]) end def update @trademark = Trademark.find(params[:id]) if @trademark.update(trademark_params) redirect_to trademark_path(@trademark.id) else render "edit" end end def destroy @trademark.destroy redirect_to trademarks_path, notice: "商標削除" end private def trademark_params params.require(:trademark).permit(:tm_name, :description, :investigation_result, :investigation_date, :apply_number, :apply_date, :judge_status, :registration_number, :registration_date, :maintenance_period) end def set_trademark @trademark = Trademark.find(params[:id]) end def logged_in_user unless logged_in? redirect_to new_session_path end end def your_page @trademark = Trademark.find(params[:id]) unless logged_in? && session[:user_id].present? && @trademark.user_id == current_user.id || session[:admin_user_id].present? redirect_to new_session_path end end def your_page_as_a_user unless logged_in_as_a_user? redirect_to new_session_path end end end
def encrypt (string, offset) raise ArgumentError, "String must not be empty" if string.empty? raise ArgumentError, "Offset must not be zero" if offset == 0 alphabet = %w(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) encrypted = "" string.each_char do |character| if character != " " #skips if the object is empty space character = character.upcase if (alphabet.index(character) + offset) <= 25 character = alphabet[alphabet.index(character) + offset] #replace each letter in the list with a number, determined by the hash and offset elsif (alphabet.index(character) + offset) > 25 character = alphabet[(alphabet.index(character) + offset) - 26] end end encrypted += character end return encrypted end def decrypt (string, offset) return encrypt(string, offset * -1).downcase end
# == Schema Information # # Table name: contacts # # id :integer(4) not null, primary key # first_name :string(255) # last_name :string(255) # created_at :datetime # updated_at :datetime # email :string(255) # device_id :integer(4) # image_file_name :string(255) # image_content_type :string(255) # image_file_size :integer(4) # image_updated_at :datetime # cloudapp_login :string(255) # cloudapp_password :string(255) # cloudapp_last_file_id :integer(4) default(0) # read_at :datetime # class Contact < ActiveRecord::Base has_many :messages belongs_to :device validates_presence_of :first_name, :last_name, :email, :device default_scope :order => 'last_name' boolean_datetime_attribute :read_at def name "#{first_name} #{last_name}" end def to_s name end def notification? if self.messages.empty? false else if self.read_at && self.messages.last.created_at if self.read_at < self.messages.last.created_at true else false end elsif self.messages.last.created_at true else false end end end def image_path(size = 'normal') image.url(size) end def cloudapp return nil if cloudapp_login.blank? @cloudapp ||= CloudApp.find_by_contact(self) end has_attached_file :image, :styles => { :original => ['300x300>'], :normal => ['100x100#'], :small => ['70x70#'] }, :default_style => :normal, :storage => :s3, :s3_credentials => "#{RAILS_ROOT}/config/aws.yml", :path => "profile_images/:id/:style/:filename" # http://stackoverflow.com/questions/2465035/how-to-pass-additional-convert-options-to-paperclip-on-heroku #, :convert_options => { :all => '-auto-orient' } end
require 'digest/md5' require 'base64' module Oplop class V1 attr_reader :master, :label, :length LEGACY_LENGTH = 8 DEFAULT_LENGTH = 16 def self.password(args={}) self.new(args).password end def initialize(args={}) @master = args[:master] @label = args[:label] @length = args[:length] || DEFAULT_LENGTH if @label =~ /^([0-9]*)?\*/ (@length, @label) = @label.split('*') @length = length.to_i @length = LEGACY_LENGTH if length <= 0 end end def master_label @master_label ||= '%s%s' % [ master, label ] end def password password = Base64.urlsafe_encode64(Digest::MD5.digest(master_label)) if password.respond_to?(:encode) password = password.encode('UTF-8') end if m = password.match(/\d+/) password = '%s%s' % [ m[0], password ] if (m.begin(0) >= length) else password = '1%s' % password end password[0,length] end end end
class CreateAdHocOptionTypes < ActiveRecord::Migration[4.2] def self.up create_table :ad_hoc_option_types do |t| t.integer :product_id t.integer :option_type_id t.string :price_modifier_type, null: true, default: nil t.boolean :is_required, default: false t.timestamps null: false end end def self.down drop_table :ad_hoc_option_types end end
# frozen_string_literal: true class RemoveTimeZoneFromRecordBooks < ActiveRecord::Migration[5.1] def change remove_column :record_books, :time_zone, :string, default: 'UTC', null: false end end
module SwellBot class JokeResponder < TextResponder self.help name: 'Jokes', syntax: 'Tell me a joke', description: 'I can tell funny jokes' self.draw do respond /^tell me a joke/i, :tell_me_a_joke scope :joke_knock_knock do respond /^who's there|whos there/i, :who_is_there respond :all, :say, text: 'You are suppose to say "Who\'s there?"', scope: 'joke_knock_knock' end scope :joke_something_who do respond :all, :something_who end end JOKES = { 'canoe' => { who_is_there: "Canoe", something_who: "Canoe help me with my homework?" }, 'orange' => { who_is_there: "Orange", something_who: "Orange you going to let me in?" }, 'needle' => { who_is_there: "Needle", something_who: "Needle little money for the movies." } } def tell_me_a_joke respond_with text: "Knock knock", scope: :joke_knock_knock, emoticon: :smile end def who_is_there joke_key = JOKES.keys.sample joke = JOKES[joke_key] respond_with text: "#{joke[:who_is_there]}.", scope: :joke_something_who, emoticon: :smile, params: { joke_key: joke_key } end def something_who joke = JOKES[request.params['joke_key']] if (request.input =~ /^#{joke[:who_is_there]} who/i).present? respond_with text: joke[:something_who], emoticon: :laughing respond_with text: 'LMFAO!', emoticon: :laughing else respond_with text: "You are suppose to say \"#{joke[:who_is_there]} who?\"", scope: request.scope, params: { joke_key: request.params['joke_key'] } end end end end
class Api::V1::SusuMembershipsController < Api::V1::BaseController before_action :set_susu_membership, only: [:show, :update, :destroy] def_param_group :susu_membership do param :susu_membership, Hash, required: true, action_aware: true do param :admin, [true, false], required: true, allow_nil: false param :collected, [true, false], required: true, allow_nil: false param :last_payin_round, Integer, required: true, allow_nil: false param :payout_round, Integer, required: true, allow_nil: false param :user_id, Integer, required: true, allow_nil: false param :susu_id, Integer, required: true, allow_nil: false end end #api :GET, '/susu_memberships', 'List Susu Memberships' def index @susu_memberships = SusuMembership.page(params[:page]).per(params[:per]) render json: @susu_memberships end #api :GET, '/susu_memberships/:id', 'Show Susu Membership' def show render json: @susu_membership end #api :POST, '/susu_memberships', 'Create Susu Membership' param_group :susu_membership def create @susu_membership = SusuMembership.new(susu_membership_params) if @susu_membership.save render json: @susu_membership, status: :created, location: @susu_membership else render json: @susu_membership.errors, status: :unprocessable_entity end end #api :PUT, '/susu_memberships/:id', 'Update Susu Membership' param_group :susu_membership def update if @susu_membership.update(susu_membership_params) render json: @susu_membership else render json: @susu_membership.errors, status: :unprocessable_entity end end #api :DELETE, '/susu_memberships/:id', 'Destroy Susu Membership' def destroy @susu_membership.destroy end private # Use callbacks to share common setup or constraints between actions. def set_susu_membership @susu_membership = SusuMembership.find(params[:id]) end # Only allow a trusted parameter "white list" through. def susu_membership_params params.require(:susu_membership).permit(:admin, :collected, :last_payin_round, :payout_round, :user_id, :susu_id) end end
require_relative 'invoice_item_parser' class InvoiceItemRepository attr_reader :file, :all, :sales_engine def initialize(file, sales_engine) @file = file @invoice_item_parser = InvoiceItemParser.new @all = @invoice_item_parser.make_invoice_item(file, sales_engine) @sales_engine = sales_engine end def random all.sample end def find_by_id(id) match = all.detect { |e| e.id == id } match.nil? ? "No match, try again." : match end def find_by_item_id(item_id) match = all.detect { |e| e.item_id == item_id } match.nil? ? "No match, try again." : match end def find_by_invoice_id(invoice_id) match = all.detect { |e| e.invoice_id == invoice_id } match.nil? ? "No match, try again." : match end def find_by_quantity(quantity) match = all.detect { |e| e.quantity == quantity } match.nil? ? "No match, try again." : match end def find_by_unit_price(unit_price) match = all.detect { |e| e.unit_price == unit_price } match.nil? ? "No match, try again." : match end def find_all_by_item_id(item_id) matches = all.select { |e| e.item_id == item_id } matches.nil? ? [] : matches end def find_all_by_invoice_id(invoice_id) matches = all.select { |e| e.invoice_id == invoice_id } matches.nil? ? [] : matches end def find_all_by_quantity(quantity) matches = all.select { |e| e.quantity == quantity } matches.nil? ? [] : matches end def find_all_by_unit_price(unit_price) matches = all.select { |e| e.unit_price == unit_price } matches.nil? ? [] : matches end end
require 'active_record' require 'active_support/inflector' require 'active_support/core_ext/module/delegation' module Kantox module Refactory module MonkeyPatches class ::String # tries the following: # self.constantize # self.camelize.constantize # self.singularize.constantize def clever_constantize self.safe_constantize || self.camelize.safe_constantize || self.singularize.camelize.safe_constantize end end class ::Symbol def clever_constantize self.to_s.clever_constantize end end class ::Object def exposed_to_s nil end alias_method :original_to_s, :to_s def to_s exposed_to_s ? "#<#{self.class}:#{'0x%16x' % (self.__id__ << 1)} #{exposed_to_s}>" : original_to_s end end class ::ActiveRecord::Reflection::ThroughReflection def model_class src = source_reflection || through_reflection while src.options[:through] do src = src.source_reflection || src.through_reflection end (src.options[:class_name] || src.name).clever_constantize || active_record end end class ::ActiveRecord::Reflection::MacroReflection def model_class (options[:class_name] || name).clever_constantize || active_record end end end end end
class MobileUsersController < ApplicationController before_action :set_mobile_user, only: [:show, :edit, :update, :destroy] # GET /mobile_users # GET /mobile_users.json def index @mobile_users = MobileUser.all $content = @mobile_users end # GET /mobile_users/1 # GET /mobile_users/1.json def show @mobile_user = MobileUser.find(params[:id]) if @mobile_user.group @profile = @mobile_user.group.profile @wallpaper = nil if !@profile.wallpaper.nil? @wallpaper = "#{Rails.root.join('public')}" + @profile.wallpaper.avatar.url end @ringtone = nil if !@profile.ringtone.nil? @ringtone = "#{Rails.root.join('public')}" + @profile.ringtone.source.url end end build_json_for_android(@profile) end # GET /mobile_users/new def new @mobile_user = MobileUser.new end # GET /mobile_users/1/edit def edit end # POST /mobile_users # POST /mobile_users.json def create @mobile_user = MobileUser.new(mobile_user_params) respond_to do |format| if @mobile_user.save format.html { redirect_to @mobile_user, notice: 'Mobile user was successfully created.' } format.json { render :show, status: :created, location: @mobile_user } else format.html { render :new } format.json { render json: @mobile_user.errors, status: :unprocessable_entity } end end end # PATCH/PUT /mobile_users/1 # PATCH/PUT /mobile_users/1.json def update respond_to do |format| if @mobile_user.update(mobile_user_params) format.html { redirect_to @mobile_user, notice: 'Mobile user was successfully updated.' } format.json { render :show, status: :ok, location: @mobile_user } else format.html { render :edit } format.json { render json: @mobile_user.errors, status: :unprocessable_entity } end end end # DELETE /mobile_users/1 # DELETE /mobile_users/1.json def destroy @mobile_user.destroy respond_to do |format| format.html { redirect_to mobile_users_url, notice: 'Mobile user was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_mobile_user @mobile_user = MobileUser.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def mobile_user_params params.require(:mobile_user).permit(:user_name, :password, :first_name, :last_name, :dob, :gender, :employee_id, :mobile, :group_id) end end
class PolyTreeNode attr_accessor :children attr_reader :parent def initialize(value) @value = value @parent = nil @children = [] end def parent @parent end def children @children end # Write add_child(child_node) and remove_child(child_node) methods. # These methods should be one- or two-liners that call #parent=. def add_child(node) @children << node unless @children.include?(node) node.parent = self end def remove_child(node) raise "not a child" unless @children.include?(node) return unless @children.include?(node) @children -= [node] node.parent = nil end def value @value end require 'byebug' def parent=(node) if node.nil? @parent.children -= [self] unless @parent == nil @parent = nil elsif @parent.nil? && !node.nil? @parent = node node.children << self unless node.children.include?(self) else @parent.children -= [self] @parent = node node.children << self unless node.children.include?(self) end end # Write a #dfs(target_value) method which takes a value to # search for and performs the search. Write this recursively. # First, check the value at this node. If a node's value # matches the target value, return the node. # If not, iterate through the #children and repeat. def dfs(target) return self if @value == target @children.each do |child| result = child.dfs(target) return result unless result.nil? end nil end def bfs(target) queue = [self] until queue.empty? node = queue.shift result = node.value return node if result == target queue += node.children end nil end end # Write a #bfs(target_value) method to implement breadth first search. # You will use a local Array variable as a queue to implement this. # First, insert the current node (self) into the queue. # Then, in a loop that runs until the array is empty: # Remove the first node from the queue, # Check its value, # Push the node's children to the end of the array. # # Write a class with four methods: # # An #initialize(value) method that sets the value, and starts parent as nil, # # and children to an empty array. # # A #parent method that returns the node's parent. # A #children method that returns an array of children of a node. # A #value method that returns the value stored at the node. # Write a #parent= method which (1) sets the parent property and (2) adds the # node to their parent's array of children (unless we're setting parent to nil).
class CreatePermitSubmissions < ActiveRecord::Migration[6.0] def change create_table :permit_submissions, id: :uuid do |t| t.string :name t.string :agency t.date :deadline t.string :status t.belongs_to :user, type: :uuid, index: true, null: false t.timestamps end end end
class MonetizeArticle < ActiveRecord::Migration def change add_money :articles, :price end end
require File.dirname(__FILE__) + '/../test_helper.rb' module ActsAsResourceAuthenticTest class EmailTest < ActiveSupport::TestCase context "email configurations" do should "have defined email fields" do assert_equal :email, User.email_field User.email_field = :nope assert_equal :nope, User.email_field User.email_field :email assert_equal :email, User.email_field end should "have defined validation for email fields" do assert User.validate_email_field User.validate_email_field = false assert !User.validate_email_field User.validate_email_field = true assert User.validate_email_field end should "have defined validation for email length" do assert_equal({:within => 6..100}, User.validates_length_of_email_field_options) User.validates_length_of_email_field_options = {:yes => "no"} assert_equal({:yes => "no"}, User.validates_length_of_email_field_options) User.validates_length_of_email_field_options({:within => 6..100}) assert_equal({:within => 6..100}, User.validates_length_of_email_field_options) end should "have defined validation for email format" do default = {:with => User.send(:email_regex), :message => I18n.t('error_messages.email_invalid', :default => "should look like an email address.")} assert_equal default, User.validates_format_of_email_field_options User.validates_format_of_email_field_options = {:yes => "no"} assert_equal({:yes => "no"}, User.validates_format_of_email_field_options) User.validates_format_of_email_field_options default assert_equal default, User.validates_format_of_email_field_options end context "validating email" do setup do @user = User.new @user.password = 'somepassword' @user.password_confirmation = 'somepassword' end should "validate length of email field" do @user.email = "a@a.a" assert !@user.valid? assert @user.errors.on(:email) @user.email = "skhchiu@gmail.com" assert @user.valid? assert !@user.errors.on(:email) end should "validate format of email field" do @user.email = "aaaaaaaaaaaaa" assert !@user.valid? assert @user.errors.on(:email) @user.email = "skhchiu@gmail.com" assert @user.valid? assert !@user.errors.on(:email) end end end end end
require 'rails_helper' RSpec.feature "Logins", type: :feature do before(:each) do @user = User.create(email: "example@gmail.com", password: "123456", password_confirmation: "123456") end scenario "Login with valid user without active mail" do visit "/login" fill_in "Email", with: @user.email fill_in "Password",with: "123456" click_button "Log in" expect(page).to have_content "You have to confirm your email address before continuing." end scenario "Login with invalid user" do visit "/login" fill_in "Email", with: "" fill_in "Password",with: "123456" click_button "Log in" expect(page).to have_content "Invalid Email or password" end end
class AddRentalDateToCarRentals < ActiveRecord::Migration[6.0] def change add_column :car_rentals, :rental_date, :datetime end end
RecipeWebsite::Application.routes.draw do resources :recipes do resources :comments end root :to => 'recipes#index' end
require 'bel' require_relative 'base' module OpenBEL module Resource module MatchResults class MatchResultSerializer < BaseSerializer adapter Oat::Adapters::HAL schema do type :match_result properties do |p| p.match_text item.snippet p.rdf_uri item.uri p.rdf_scheme_uri item.scheme_uri p.identifier item.identifier p.name item.pref_label # Do not have alt_labels property from FTS index. # p.synonyms item.alt_labels end end end class MatchResultResourceSerializer < BaseSerializer adapter Oat::Adapters::HAL schema do type :'match_result' properties do |p| collection :match_results, item, MatchResultSerializer end # link :self, link_self(item.first[:short_form]) end # private # # def link_self(id) # { # :type => :function, # :href => "#{base_url}/api/functions/#{id}" # } # end end class MatchResultCollectionSerializer < BaseSerializer adapter Oat::Adapters::HAL schema do type :'match_result_collection' properties do |p| collection :match_results, item, MatchResultSerializer end # link :self, link_self # link :start, link_start(item[0][:short_form]) end # private # # def link_self # { # :type => :'function_collection', # :href => "#{base_url}/api/functions" # } # end # # def link_start(first_function) # { # :type => :function, # :href => "#{base_url}/api/functions/#{first_function}" # } # end end end end end
class UrlsController < ApplicationController include UrlsHelper def index @urls = Url.all @url = Url.new end def show @url = Url.find_by(short_url: params[:short_url]) redirect_to @url.original_url end def create @urls = Url.all @url = Url.new(url_params) generate_sanitized_url(@url) respond_to do |format| if@url.save format.html { redirect_to @url, notice: 'Url was successfully created.' } format.json { render :show, status: :created, location: @url } format.js else format.html { render :new } format.json { render json: @url.errors, status: :unprocessable_entity } format.js end end end private def url_params params.require(:url).permit(:original_url) end end
require 'rails_helper' feature 'List available products' do let!(:products){ FactoryGirl.create_list(:product, 3) } scenario 'see a list of products' do visit root_path products.each do |product| expect(page).to have_content(product.name) end end end
class AddGroupsToProducts < ActiveRecord::Migration def change add_column :products, :group_id, :integer add_column :products, :subgroup_id, :integer add_index :products, [:group_id, :subgroup_id, :created_at] end end
# # Cookbook Name:: cracker # Recipe:: default # # enable EPEL template '/etc/yum.repos.d/epel.repo' do source 'epel.repo' owner 'root' group 'root' mode '0755' backup 5 end # install packages package 'bash-completion' package 'p7zip' #package 'Development tools' # install Nvidia driver remote_file '/root/NVIDIA-Linux-x86_64-352.55.run' do source 'http://us.download.nvidia.com/XFree86/Linux-x86_64/352.55/NVIDIA-Linux-x86_64-352.55.run' owner 'root' group 'root' mode '0700' action :create end execute 'nvidia_installer' do command '/root/NVIDIA-Linux-x86_64-352.55.run -s' ignore_failure true end # install cudaHashcat remote_file '/root/cudaHashcat-1.37.7z' do source 'http://hashcat.net/files/cudaHashcat-1.37.7z' owner 'root' group 'root' mode '0700' action :create end execute 'hashcat_unpack' do command '/usr/bin/7za x -o/root /root/cudaHashcat-1.37.7z' end template '/root/cudaHashcat-1.37/eula.accepted' do source 'eula.accepted' owner 'root' group 'root' mode '0755' end