text
stringlengths
10
2.61M
module IncludesIIDX class DependenceSet attr_accessor :deps def initialize(combined) @deps = {} if combined.class.name != 'Array' combined = [combined] end combined.each do |a| case a.class.name when 'Symbol' @deps[a] = IncludesIIDX::DependenceSet.empty when 'Hash' a.each do |k, v| # Deep recursive initialization, all subsets are converted to DependenceSets @deps[k] = IncludesIIDX::DependenceSet.new(v) end else raise "Dependence type not handled: #{a.class.name} (valid types are Symbol, Hash)" end end end # @abstract Convert the DependenceSet to an array, possibly terminated by an hash # @note The output format is the one used by ActiveRecord `includes` scope # @return [Array] def to_a direct = [] associated = {} @deps.each do |k, v| if v.empty? direct << k else associated[k] = v.to_a end end direct + (associated.any? ? [associated] : []) end # @abstract Merge two DependenceSets def merge!(other) @deps.deep_merge!(other.deps) end # @abstract Get the association of a class from its name # @return [ActiveRecord::Reflection] def self.association_for(klass, name) klass.reflect_on_all_associations.each do |a| return a if a.name == name end nil end # @abstract Get the klass pointed by an expection from its name # @return [<T>] def self.associated_klass_for(klass, name) if asso = association_for(klass, name) if asso.polymorphic? :polymorphic else asso.klass end end end # @abstract Resolve an DependenceSet in the context of a klass by replacing # abstract elements (user-defined dependencies) by associations # @return [DependenceSet] def resolve_for(klass) res = IncludesIIDX::DependenceSet.empty @deps.each do |k, v| if (sub = IncludesIIDX::DependenceSet.associated_klass_for(klass, k)) res.deps[k] = sub == :polymorphic ? {} : v.resolve_for(sub) end if (attr_deps = klass.iidx_dependencies[k]) res.merge!(attr_deps.resolve_for(klass)) end if klass.respond_to?(:translated_attribute_names) && k.in?(klass.translated_attribute_names) res.merge!(IncludesIIDX::DependenceSet.new([:translations])) end end res end def empty? deps.empty? end # @abstract Return an empty DependenceSet def self.empty new([]) end end end
# # Cookbook Name:: composer # Attributes:: default # # Copyright (c) 2016, David Joos # include_attribute 'php' if node['platform'] == 'windows' default['composer']['url'] = 'https://getcomposer.org/Composer-Setup.exe' default['composer']['install_dir'] = 'C:\\ProgramData\\ComposerSetup' default['composer']['bin'] = "#{node['composer']['install_dir']}\\composer.bat" default['composer']['global_install']['install_dir'] = 'C:\\Program\ Files\\Composer' default['composer']['global_install']['bin_dir'] = 'C:\\ProgramData\\Composer' else default['composer']['url'] = 'http://getcomposer.org/composer-stable.phar' default['composer']['install_dir'] = '/usr/local/bin' default['composer']['bin'] = "#{node['composer']['install_dir']}/composer" default['composer']['install_globally'] = true default['composer']['mask'] = '0755' default['composer']['link_type'] = :symbolic default['composer']['global_install']['install_dir'] = '/usr/local/composer' default['composer']['global_install']['bin_dir'] = '/usr/local/bin' end default['composer']['global_configs'] = {} default['composer']['home_dir'] = nil default['composer']['php_recipe'] = 'php::default' default['composer']['self_update_channel'] = nil
class AddFieldsToSocialMediaPosts < ActiveRecord::Migration[5.2] def change add_column :social_media_posts, :posted_at, :date add_column :social_media_posts, :uri, :string end end
require 'journey' require 'station' describe Journey do context 'journey returns entry station ' do it 'returns Baker Street when asked for entry station' do subject.touch_in("Baker Street") expect(subject.entry_station).to eq("Baker Street") end it 'returns Finsbury Park when asked for entry station' do subject.touch_out("Finsbury Park") expect(subject.exit_station).to eq("Finsbury Park") end end context 'determine if journey is complete' do it 'views a journey as complete' do subject.touch_in("Waterloo") subject.touch_out("Embankment") expect(subject.journey_complete?).to eq(true) end it 'views a journey as incomplete if no touch out' do subject.touch_in("Waterloo") expect(subject.journey_complete?).to eq(false) end it 'views a journey as incomplete if no touch_in' do subject.touch_out("Embankment") expect(subject.journey_complete?).to eq(false) end end context 'it assigns a fare to a journey' do it 'assigns a fare of 1 by default' do expect(subject.fare).to eq(1) end it 'assigns a penalty fare to a journey' do subject.assign_penalty_fare expect(subject.fare).to eq(6) end end end
# range literal letters = ('a'..'c') # converting range to an array puts(['a', 'b', 'c'] == letters.to_a) # iterating over a range ('A'..'Z').each do |letter| print letter end puts god_bless_the_70s = 1970..1979 puts god_bless_the_70s.min puts god_bless_the_70s.max puts god_bless_the_70s.include?(1979) puts god_bless_the_70s.include?(1980) puts god_bless_the_70s.include?(1974.5) prof = "We tore the universe a new space-hole, alright!" puts prof[12, 8] puts prof[12..19] puts def is_avi filename filename.downcase[-4..-1] == ".avi" end puts is_avi("DANCEMONKEYBOY.AVI") puts is_avi("toilet_paper_fiasco.jpg")
class User < ActiveRecord::Base has_and_belongs_to_many :events validates_presence_of :username validates_uniqueness_of :username validate :password_non_blank def password @password end def password=(pwd) @password = pwd return if pwd.blank? create_new_salt self.hashed_password = User.encrypted_password(self.password, self.salt) end def self.authenticate(name, password) user = self.find_by_username(name) if user expected_password = encrypted_password(password, user.salt) if user.hashed_password != expected_password user = nil end end user end def User.can_edit_event?(event, twitter_name) return false if twitter_name.blank? user = User.find_by_twitter_name(twitter_name) return false if user.nil? user.events.select do |g| g.id == event.id end.length > 0 end def twitter_profile if @twitter_profile.nil? ha = Twitter::HTTPAuth.new('asktwoups', '1rumbleapp!') base = Twitter::Base.new(ha) @twitter_profile = base.user(self.twitter_name) end @twitter_profile rescue return nil end def User.filter_at(user_name) user_name.slice!(0) if user_name[0,1] == '@' user_name end private def password_non_blank errors.add(:password, "Missing password") if hashed_password.blank? end def create_new_salt self.salt = self.object_id.to_s + rand.to_s end def self.encrypted_password(password, salt) string_to_hash = password + "eventcasts" + salt Digest::SHA1.hexdigest(string_to_hash) end end
class MembershipsController < ApplicationController def create @membership = current_user.memberships.build(:member_id => params[:member_id]) if @membership.save flash[:notice] = "Successfully created membership." redirect_to root_url else render :action => 'new' end end def destroy @membership = current_user.memberships.find(params[:id]) @membership.destroy flash[:notice] = "Successfully destroyed membership." redirect_to root_url end end
def oxford_comma(array) result = "" case array.size when 0 result = "" when 1 result = array.first when 2 result = "#{array.first} and #{array.last}" when 3 result = "#{array.first}, #{array[1]}, and #{array.last}" else arr_string = array.slice(0,array.size-1).join(", ") result = "#{arr_string}, and #{array.last}" end return result end
class RemoveUnusedAttributesFromDiscounts < ActiveRecord::Migration[5.0] def change add_reference :discounts, :discount_type_period, index: true, null: false add_foreign_key :discounts, :discount_type_periods remove_column :discounts, :start_date, :datetime remove_column :discounts, :end_date, :datetime remove_column :discounts, :shop_name, :string remove_column :discounts, :discount_type, :string end end
class RemoveCrossingFromAverage < ActiveRecord::Migration def up remove_column :averages, :location remove_column :averages, :title end def down add_column :averages, :title, :string add_column :averages, :location, :string end end
require 'spec_helper' describe 'iis::website' do let :title do 'puppet.puppet.vm' end let :pre_condition do 'class { "iis": }' end context 'all defaults' do let :facts do { kernel: 'windows', os: { 'family' => 'windows' }, } end it do is_expected.to contain_file('C:\inetpub\puppet.puppet.vm').with( 'ensure' => 'directory', 'before' => 'Dsc_xwebapppool[puppet.puppet.vm]', ) end it do is_expected.to contain_acl('C:\inetpub\puppet.puppet.vm').with( 'purge' => false, 'permissions' => [ { 'identity' => 'S-1-5-17', 'rights' => %w[read execute], 'perm_type' => 'allow', 'child_types' => 'all', 'affects' => 'all', }, { 'identity' => 'IIS APPPOOL\puppet.puppet.vm', 'rights' => %w[read execute], 'perm_type' => 'allow', 'child_types' => 'all', 'affects' => 'all', }, { 'identity' => 'BUILTIN\Users', 'rights' => ['read'], 'perm_type' => 'allow', 'child_types' => 'all', 'affects' => 'all', }, ], 'inherit_parent_permissions' => false, ) end it do is_expected.to contain_dsc_xwebapppool('puppet.puppet.vm').with( 'dsc_ensure' => 'Present', 'dsc_name' => 'puppet.puppet.vm', 'dsc_managedruntimeversion' => 'v4.0', 'dsc_logeventonrecycle' => 'Memory', 'dsc_restartmemorylimit' => 1000, 'dsc_restartprivatememorylimit' => 1000, 'dsc_identitytype' => 'ApplicationPoolIdentity', 'dsc_state' => 'Started', 'before' => 'Dsc_xwebsite[puppet.puppet.vm]', ) end it do is_expected.to contain_dsc_xwebsite('puppet.puppet.vm').with( 'dsc_ensure' => 'Present', 'dsc_name' => 'puppet.puppet.vm', 'dsc_state' => 'Started', 'dsc_physicalpath' => 'C:\inetpub\puppet.puppet.vm', 'dsc_bindinginfo' => [ { 'protocol' => 'HTTP', 'port' => 80, 'hostname' => 'puppet.puppet.vm', }, ], ) end end context 'with app' do let :params do { app_name: 'myapp', app_path: 'C:\\sites\\puppet\\app', } end let :facts do { kernel: 'windows', os: { 'family' => 'windows' }, } end it do is_expected.to contain_dsc_xwebapplication('myapp').with( 'dsc_ensure' => 'Present', 'dsc_name' => 'myapp', 'dsc_physicalpath' => 'C:\sites\puppet\app', 'dsc_webapppool' => 'puppet.puppet.vm', 'dsc_website' => 'puppet.puppet.vm', 'require' => 'Dsc_xwebsite[puppet.puppet.vm]', ) end end context 'with different permission on website directory' do let :facts do { kernel: 'windows', os: { 'family' => 'windows' }, } end let :params do { website_directory_acl: { group: 'S-1-5-18', inherit_parent_permissions: true, owner: 'S-1-5-18', permissions: [ { 'identity' => 'NT SERVICE\TrustedInstaller', 'rights' => [ 'full' ], 'affects' => 'self_only', }, { 'identity' => 'NT SERVICE\TrustedInstaller', 'rights' => [ 'full' ], 'child_types' => 'containers', 'affects' => 'children_only', } ] }, } end it do is_expected.to contain_acl('C:\inetpub\puppet.puppet.vm').with( 'group' => 'S-1-5-18', 'inherit_parent_permissions' => true, 'owner' => 'S-1-5-18', 'permissions' => [ { 'identity' => 'NT SERVICE\TrustedInstaller', 'rights' => %w[full], 'affects' => 'self_only', }, { 'identity' => 'NT SERVICE\TrustedInstaller', 'rights' => %w[full], 'child_types' => 'containers', 'affects' => 'children_only', }, ], ) end end end
require 'helper' module CSSPool module CSS class TestSupportsRule < CSSPool::TestCase def test_basic doc = CSSPool.CSS <<-eocss @supports ( display: flexbox ) { body { display: flexbox; } } eocss assert_equal 1, doc.supports_rules.size assert_match '( display: flexbox )', doc.supports_rules[0].conditions assert_equal 1, doc.supports_rules[0].rule_sets.size end def test_not doc = CSSPool.CSS <<-eocss @supports not ( display: flexbox ) { body { display: flexbox; } } eocss assert_equal 1, doc.supports_rules.size assert_match 'not ( display: flexbox )', doc.supports_rules[0].conditions assert_equal 1, doc.supports_rules[0].rule_sets.size end def test_or doc = CSSPool.CSS <<-eocss @supports ( display: flexbox ) or ( display: block ) { body { display: flexbox; } } eocss assert_equal 1, doc.supports_rules.size assert_match '( display: flexbox ) or ( display: block )', doc.supports_rules[0].conditions assert_equal 1, doc.supports_rules[0].rule_sets.size end def test_and doc = CSSPool.CSS <<-eocss @supports ( display: flexbox ) and ( display: block ) { body { display: flexbox; } } eocss assert_equal 1, doc.supports_rules.size assert_match '( display: flexbox ) and ( display: block )', doc.supports_rules[0].conditions assert_equal 1, doc.supports_rules[0].rule_sets.size end def test_complex doc = CSSPool.CSS <<-eocss @supports ((display: inline) or (( display: flexbox ) and ( display: block ))) { body { display: flexbox; } } eocss assert_equal 1, doc.supports_rules.size assert_match '((display: inline) or (( display: flexbox ) and ( display: block ))', doc.supports_rules[0].conditions assert_equal 1, doc.supports_rules[0].rule_sets.size end def test_double_parens doc = CSSPool.CSS <<-eocss @supports ((display: flexbox)) { body { display: flexbox; } } eocss assert_equal 1, doc.supports_rules.size assert_match '((display: flexbox))', doc.supports_rules[0].conditions assert_equal 1, doc.supports_rules[0].rule_sets.size end def test_important doc = CSSPool.CSS <<-eocss @supports ( display: flexbox !important) { body { display: flexbox; } } eocss assert_equal 1, doc.supports_rules.size assert_match '( display: flexbox !important)', doc.supports_rules[0].conditions assert_equal 1, doc.supports_rules[0].rule_sets.size end def test_other_use_of_keyword doc = CSSPool.CSS <<-eocss /* and */ .and { display: flexbox; content: " and ";} and { and: and; } eocss end def test_invalid_keyword_in_place_of_and_or exception_happened = false begin doc = CSSPool.CSS <<-eocss @supports ( display: flexbox ) xor ( display: block ) { body { display: flexbox; } } eocss rescue exception_happened = true end assert exception_happened end def test_invalid_keyword_in_place_of_not exception_happened = false begin doc = CSSPool.CSS <<-eocss @supports isnt ( display: flexbox ) { body { display: flexbox; } } eocss rescue exception_happened = true end assert exception_happened end def test_with_parens doc = CSSPool.CSS <<-eocss @supports ( filter: url(http://example.com) ) { body { filter: url(http://example.com) } } eocss assert_equal 1, doc.supports_rules.size assert_match 'filter: url("http://example.com")', doc.supports_rules[0].conditions assert_equal 1, doc.supports_rules[0].rule_sets.size end end end end
module Platforms module Yammer module Api # Yammer's subscription (following) management # @author Benjamin Elias # @since 0.1.0 class Subscriptions < Base # Check if the current user is subscribed to (following) another user # @param id [#to_s] The ID of the User # @param options [Hash] Options for the request # @param headers [Hash] Additional headers to send with the request # @return [Faraday::Response] the API response # @see https://developer.yammer.com/docs/subscriptionsto_useridjson def to_user id, options={}, headers={} @connection.get "subscriptions/to_user/#{id}.json", options, headers end # Check if the current user is subscribed to (following) a topic (hashtag) # @param id [#to_s] The ID of the User # @param options [Hash] Options for the request # @param headers [Hash] Additional headers to send with the request # @return [Faraday::Response] the API response # @see https://developer.yammer.com/docs/subscriptionsto_topicidjson def to_topic id, options={}, headers={} @connection.get "subscriptions/to_topic/#{id}.json", options, headers end # Subscribe to a user or topic. # This usually involves setting target_id and target_type in the JSON body. # @param body [#to_s] Body of the request # @param headers [Hash] Additional headers to send with the request # @return [Faraday::Response] the API response # @see https://developer.yammer.com/docs/subscriptions-1 def post body=nil, headers={} @connection.post "subscriptions.json", body, headers end # Unsubscribe from a user or topic. # This usually involves setting target_id and target_type in the options hash. # @param options [Hash] Options for the request # @param headers [Hash] Additional headers to send with the request # @return [Faraday::Response] the API response # @see https://developer.yammer.com/docs/subscriptions-1 def delete options={}, headers={} @connection.delete "subscriptions.json", options, headers end end end end end
# Cached generated iCalendar entries, to speed up the feed generation class IcalEntry < ActiveRecord::Base belongs_to :task belongs_to :work_log end
# == Schema Information # # Table name: volunteers # # id :integer not null, primary key # person_id :integer not null # admission :date # area_of_operation :string(255) # created_at :datetime # updated_at :datetime # class Volunteer < ApplicationRecord AREAS = %w( Banco\ de\ Dados Comunicação Coordenação\ Geral Eventos Facilitação\ Interdimensional\ de\ Pesquisas Jurídico-Financeiro Parapedagogia Parapercepciografia Voluntariado) EVENT_ADMIN_ROLE_AREAS = %w(Eventos Jurídico-Financeiro Parapedagogia) VOLUNTEER_ADMIN_ROLE_AREAS = %w(Voluntariado) PERSON_ADMIN_ROLE_AREAS = %w(Eventos Voluntariado) ADMIN_ROLE_AREAS = %w(Coordenação\ Geral Banco\ de\ Dados) validates :person, :person_id, presence: true, uniqueness: true belongs_to :person after_update :set_roles, if: :saved_change_to_area_of_operation? after_create :set_roles after_destroy do u = User.find_by(person_id: person_id) u.remove_role :volunteer if u end def to_s "Voluntário #{person.name}" end private def set_roles u = User.find_by(person_id: person_id) return unless u # Make sure volunteer role is always set u.add_role :volunteer u.remove_role(:person_admin) if PERSON_ADMIN_ROLE_AREAS.include?(area_of_operation_before_last_save) u.remove_role(:event_admin) if EVENT_ADMIN_ROLE_AREAS.include?(area_of_operation_before_last_save) u.remove_role(:volunteer_admin) if VOLUNTEER_ADMIN_ROLE_AREAS.include?(area_of_operation_before_last_save) u.remove_role(:admin) if ADMIN_ROLE_AREAS.include?(area_of_operation_before_last_save) u.add_role(:person_admin) if PERSON_ADMIN_ROLE_AREAS.include?(area_of_operation) u.add_role(:event_admin) if EVENT_ADMIN_ROLE_AREAS.include?(area_of_operation) u.add_role(:volunteer_admin) if VOLUNTEER_ADMIN_ROLE_AREAS.include?(area_of_operation) u.add_role(:admin) if ADMIN_ROLE_AREAS.include?(area_of_operation) end end
class ItemsController < ApplicationController require 'payjp' before_action :move_to_login, only: [:new, :edit] before_action :items_list, only: [:sell_list,:buy_list] before_action :set_item, only: [:edit, :update, :show, :purchase, :pay, :destroy] before_action :set_likes_count, only: [:index, :tag, :search] before_action :set_parents, only: [:index, :show, :tag, :search, :sell_list, :buy_list, :done] before_action :set_current_user, only: [:tag, :search] before_action :correct_user, only: :edit before_action :item_look_for, only: :purchase def index @items = Item.all.last(3) ctgry_ids = Category.roots.pluck(:id) items_by_category = {} ctgry_ids.each do |ctgry_id| category_items_id = Category.find(ctgry_id).descendant_ids items_by_category[:"#{Category.find(ctgry_id).name}"] = Item.where(category_id: category_items_id).last(3) end @picked_up_category = "レディース" @picked_up_items = items_by_category[:"#{@picked_up_category}"] respond_to do |format| format.html format.json { render json: @items.concat(@picked_up_items)} end end def new @item = Item.new @item.pictures.new end def create @item = Item.new(item_params) if @item.save redirect_to item_path(@item), notice: '出品が完了しました。' else flash.now[:alert] = @item.errors.full_messages @item.pictures.new set_category if @item.category != nil render :new end end def edit set_category end def update if params[:item].keys.include?('picture') || params[:item].keys.include?('pictures_attributes') before_pictures_ids = @item.pictures.ids if @item.update(item_params) if params[:item].keys.include?('picture') update_pictures_ids = params[:item][:picture].values before_pictures_ids.each do |pict_id| Picture.find(pict_id).destroy unless update_pictures_ids.include?("#{pict_id}") end else before_pictures_ids.each do |pict_id| Picture.find(pict_id).destroy end end redirect_to item_path(@item), notice: '商品を編集しました' else flash[:alert] = @item.errors.full_messages redirect_back(fallback_location: :edit) end else flash[:alert] = '画像は1枚以上必要です' redirect_back(fallback_location: root_path) end end def get_category_children @category_children_array = set_ancestry(params[:parent_id]) end def get_category_grandchildren @category_grandchildren_array = set_ancestry(params[:child_id]) end def show @comment = Comment.new @commentAll = @item.comments @likes_count = Like.where(item_id: @item.id).count if user_signed_in? && Like.where(item_id: @item.id, user_id: current_user.id).present? @like_check = Like.where(item_id: @item.id, user_id: current_user.id).ids[0] else @like_check = 0 end respond_to do |format| format.html do @item.view_count += 1 unless user_signed_in? && current_user.id == @item.user.id @item.save render :show end format.json {render json: @item} end end def purchase @card = Card.find_by(user_id: current_user.id) if @card == nil redirect_to new_card_path flash[:alert] = "クレジットカードが登録されていませんので登録してください" else Payjp.api_key = Rails.application.credentials[:payjp][:PAYJP_PRIVATE_KEY] customer = Payjp::Customer.retrieve(@card.customer_id) @card_information = customer.cards.retrieve(@card.card_id) # 《+α》 登録しているカード会社のブランドアイコンを表示するためのコードです。--------- @card_brand = @card_information.brand case @card_brand when "Visa" @card_src = "if-visa-2593666_86609.svg" when "JCB" @card_src = "jcbcard.png" when "MasterCard" @card_src = "mastercard.png" when "American Express" @card_src = "americancard.png" when "Diners Club" @card_src = "diners_club.png" when "Discover" @card_src = "discover.png" end # --------------------------------------------------------------- end end def pay card = Card.find_by(user_id: current_user.id) Payjp.api_key = Rails.application.credentials[:payjp][:PAYJP_PRIVATE_KEY] Payjp::Charge.create( amount: @item.price, # Payjpに載る金額 customer: card.customer_id, # 顧客ID currency: 'jpy' ) @item.update(buyer: current_user.id) require 'date' @item.update(bought_at: Time.now ) redirect_to done_item_path(@item.id) flash[:notice] = "購入が完了しました" end def done end def destroy if @item.destroy redirect_to root_path flash[:notice] = "商品の削除が完了しました。" else redirect_to item_path(item.id) flash[:notice] = "商品の削除に失敗しました。" end end def tag @tag = Tag.find_by(name: params[:name]) @items = @tag.items.reverse end def search @keyword = params[:keyword] @items = Item.search(params[:keyword]).reverse end def sell_list @items = Item.where(user_id: params[:user_id]) end def buy_list @items = Item.where(buyer: params[:user_id]) end private def item_params params.require(:item).permit(:name, :price, :condition, :explanation, :view_count, pictures_attributes: [:image, :_destroy, :id]) .merge(user_id: current_user.id, category_id: params[:item][:category], prefecture_id: params["prefecture"], postage_id: params["postage"], delivery_date_id: params["delivery-date"]) end def set_ancestry(key) return Category.find(key).children end def move_to_login redirect_to user_session_path unless user_signed_in? end def correct_user redirect_to purchase_item_path unless current_user.id == @item.user_id end def set_category @category_grandchild = @item.category @category_child = @category_grandchild.parent @category_parent = @category_child.parent @child_array = [] @child_array = set_ancestry(@category_parent.id) @grandchild_array = [] @grandchild_array = set_ancestry(@category_child.id) end def set_item @item = Item.find(params[:id]) end def item_look_for unless @item.bought_at == nil redirect_to item_path(@item.id) flash[:notice] = "この商品は売り切れです。" end end def items_list @likes_counts = Like.group(:item_id).count @user_items_count = Item.where(user_id: current_user.id).count end def set_likes_count @likes_count = Like.group(:item_id).count end def set_parents @parents = Category.where(ancestry: nil) end def set_current_user @current_user_id = current_user.id if user_signed_in? end end
module Factory class Vehicle def turn_on puts "Turn on the vehicle." end def move puts "Moving..." end def stop puts "Stopping." end end end car = Factory::Vehicle.new car.turn_on car.move car.stop
require './count_sentences' describe String, "#count_sentences" do it "should return the number of sentences in a string" do "Hello! My name is Uzo, and it\'s a pleasure to meet you. What is your and where are you from????".count_sentences.should eq(3) end it "should return zero if there are no sentences in a string" do "".count_sentences.should eq(0) end end
Rails.application.routes.draw do get 'password_reset/new' get 'password_reset/edit' get '/update_awards' => 'picks#update_awards', :as => 'update_awards' get '/help', to: 'static_pages#help' get '/about', to: 'static_pages#about' get '/contacts', to: 'contacts#new' get '/signup', to: 'users#new' get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' delete '/logout', to: 'sessions#destroy' get '/players', to: 'players#index' get '/players/test', to: 'players#test' get '/players/:id', to: 'players#show', as: "player" resources :users do member do get :outgoing_friends, :incoming_friends, :friends end end resources :relationships resources :picks resources :account_activations, only: [:edit] resources :password_resets, only: [:new, :create, :edit, :update] get '/posts/:id', to: 'posts#index', as: 'post' get '/posts/friends/:id', to: 'posts#friends', as: 'post_friends' resources :posts, only: [:create, :destroy] resources :contacts, only: [:new, :create] resources :groups do get 'join', to: :create, controller: 'memberships' get 'leave', to: :destroy, controller: 'memberships' end root 'static_pages#home' end
class Vote < ApplicationRecord validates :user_id, :voteable_id, :voteable_type, presence: true belongs_to :voteable, polymorphic: true, counter_cache: true belongs_to :user end
class Episode < ApplicationRecord belongs_to :tv_show has_many :episode_ratins, :dependent => :destroy has_many :episode_comments, :dependent => :destroy has_many :users, through: :episode_ratings end
class Api::V1::Items::SearchController < ApplicationController def show item = if params[:name] Item.find_item(params[:name]) elsif params[:min_price] Item.min_price(params[:min_price]) elsif params[:max_price] Item.max_price(params[:max_price]) elsif params[:min_price] && params[:max_price] Item.min_and_max_price(params[:min_price], params[:max_price]) end render json: ItemSerializer.new(item) end end
class Ingredient < ApplicationRecord default_scope { order(created_at: :desc) } has_many :inventories belongs_to :ingredient_type end
class ActivitySerializer < ActiveModel::Serializer attributes :id, :name, :description belongs_to :camp end
class CreateAdminService def call user = User.find_or_initialize_by(email: Rails.application.secrets.admin_email) user.password = Rails.application.secrets.admin_password user.password_confirmation = Rails.application.secrets.admin_password user.confirm unless user.confirmed? user.add_to_role("administrator") user.save! user end end
json.array!(@site_settings) do |site_setting| json.extract! site_setting, :id, :name, :value, :description json.url admin_site_setting_url(site_setting, format: :json) end
desc "Remove unconfirmed subscriptions" task :remove_unconfirmed => :environment do Subscription.where(confirmed: false).where("created_at < ?", Date.today-3.days).destroy_all end
# frozen_string_literal: true require 'fun/helpers' require 'fun/just' require 'fun/nothing' module FUN class Maybe class << self include Helpers def from_nil lambda { |value| (is_defined?.call(value) ? Just : Nothing).of(value) } end end end end
# Blocks # Blocks, like parameters, can be passed into a method just like normal variables. # The ampersand (&) in the method definition tells us that the argument is a block. You could name it anything you wanted. The block must always be the last parameter in the method definition. When we're ready to use the method, we call it like any other method: take_block. The only difference is that because this method can accept a block, we can pass in a block of code using do/end # def take_block(&block) # block.call # end # take_block do # puts "Block being called in the method!" # end # def another_block(&block) # block.call # end # another_block do # puts "This string is being called from inside of another_block method!" # end # another_block do # puts 7 ** 2 # end # Let's make this more complex. Say we wanted to pass an argument to the method as well. # def take_block(number, &block) # block.call(number) # end def take_block(username, &block) block.call(username) end username = "Anne Lister" take_block(username) do |name| puts "#{name}, Welcome to the global environment! " end # => Anne Lister, Welcome to the global environment!
require 'rails_helper' RSpec.describe 'DogWalking End Without Errors Api', type: :request do describe 'GET /dog_walking/:id/finish_walk' do context "When start walk with a valid uuid" do before do Product.create({ name: 'Caminhada de 60 min', duration: 60, first_price: 25, aditional_price: 15 }) create_list(:dog_walking, 5, schedule_date: Time.now + 1.hours, duration: 60, pets: 1) @walk = DogWalking.all.sample @walk.start! patch "/dog_walkings/#{@walk.id}/finish_walk", params: {} end it 'returns status :OK 200' do expect(response).to have_http_status(:ok) end it 'changes walk status to finished' do @walk.reload expect(@walk.status).to eql('finished') end it 'changes walk end_date' do @walk.reload expect(@walk.end_date.nil?).to be_falsey end end context "When Finish with a invalid uuid" do before do Product.create({ name: 'Caminhada de 60 min', duration: 60, first_price: 25, aditional_price: 15 }) create_list(:dog_walking, 5, schedule_date: Time.now + 1.hours, duration: 60, pets: 1, start_date: Time.now + 1.hours, end_date: (Time.now + 2.hours) + 2.minutes ) @walk = DogWalking.all.sample @walk.start! patch "/dog_walkings/nao_existe/finish_walk", params: {} end it 'returns status :not_found 404' do expect(response).to have_http_status(:not_found) end end end end
require_relative '../lib/card_deck' require_relative '../lib/playing_card' describe 'CardDeck' do it 'stores a specified array of cards' do cards = [PlayingCard.new, PlayingCard.new] deck = CardDeck.new(cards) expect(deck.cards).to match_array cards end it 'defaults to a standard 52 card deck' do deck = CardDeck.new expect(deck.cards_left).to eq 52 end it 'adds a card to the deck' do cards = [PlayingCard.new, PlayingCard.new] new_card = PlayingCard.new('8') deck = CardDeck.new(cards) deck.add_card(new_card) expect(deck.cards.count).to eq 3 expect(deck.cards.first).to eq new_card end it 'deals a card from the top of the deck' do cards = [PlayingCard.new('3'), PlayingCard.new('2'), PlayingCard.new('A')] deck = CardDeck.new(cards) dealt_card = deck.deal expect(dealt_card.rank).to eq 'A' end it 'returns the number of cards left in the deck' do cards = [PlayingCard.new, PlayingCard.new, PlayingCard.new] deck = CardDeck.new(cards) expect(deck.cards_left).to eq cards.count cards2 = [PlayingCard.new, PlayingCard.new] deck2 = CardDeck.new(cards2) expect(deck2.cards_left).to eq cards2.count end end
class Preference < ActiveRecord::Base belongs_to :user belongs_to :user_with_default_attrs, :class_name => 'User', :foreign_key => 'user_id' belongs_to :user_with_block, :class_name => 'User', :foreign_key => 'user_id' auto_create :user auto_create :user_with_default_attrs, {:username => 'defaulted'} auto_create :user_with_block, ->(instance){ instance.create_user(:username => 'blocked') } end
class AddTrendyOnToTrends < ActiveRecord::Migration def change add_column :trends, :trendy_on, :date end end
#!/usr/bin/env ruby # There is a problem here, as this is a hash it can't have the same source # character twice so you can't ask it to replace i with 1 and i with l replace_hash = { "o" => "0", "i" => "l", "m" => "rn", "aa" => "a", "bb" => "b", "cc" => "c", "dd" => "d", "ee" => "e", "ff" => "f", "gg" => "g", "hh" => "h", "ii" => "i", "jj" => "j", "kk" => "k", "ll" => "l", "mm" => "m", "mn" => "nm", "nm" => "mn", "nn" => "n", "oo" => "o", "pp" => "p", "qq" => "q", "rr" => "r", "ss" => "s", "tt" => "t", "uu" => "u", "vv" => "v", "ww" => "w", "xx" => "x", "yy" => "y", "zz" => "z", } if ARGV.length != 1 puts "type_squatter v0.1 Usage: ./typo_squatter.rb <domain name> " exit 1 end tmp_domain = ARGV.shift domain_name = "" if tmp_domain.match(/([^\.]*)\.(.*)/) domain_name = $1 tld = $2 else domain_name = tmp_domain tld = nil end new_domains = [] num_replace = domain_name.length 0.upto((2**num_replace) - 1) do |bitmap| new_domain_name = domain_name.dup (num_replace-1).downto(0) do |bit| # Doing it with 0 rather than 1 because that runs through backwards # which means a 2 char replace happens at the end of the string first # and doesn't mess up the length of the string if bitmap[bit] == 0 src_char = domain_name[bit] src_2_char = domain_name[bit, 2] # puts "bit = " + bit.to_s # puts "src = " + src_char #print domain_name[bit] + " " #print "replace " if replace_hash.has_key?(src_char) dst_char = replace_hash[src_char] # puts "dst = " + dst_char new_domain_name[bit, src_char.length] = dst_char elsif replace_hash.has_key?(src_2_char) dst_char = replace_hash[src_2_char] # puts "replacing " +bit.to_s + " with " + dst_char # puts "dst = " + dst_char new_domain_name[bit, src_2_char.length] = dst_char end else # print "leave " end end if !(new_domains.include?(new_domain_name.to_s)) and domain_name != new_domain_name new_domains << new_domain_name end end if new_domains.count == 0 puts "No suggestions of alternative domains" else puts "Some alternative domains:" new_domains.each do |dom| if tld.nil? puts dom else puts dom + "." + tld end end end
module Verify class FinanceOtherController < ApplicationController include IdvStepConcern before_action :confirm_step_needed before_action :confirm_step_allowed def new @view_model = view_model analytics.track_event(Analytics::IDV_FINANCE_OTHER_VISIT) end private def step_name :financials end def confirm_step_needed redirect_to verify_phone_url if idv_session.financials_confirmation.try(:success?) end def view_model Verify::FinancialsNew.new( remaining_attempts: remaining_step_attempts, idv_form: idv_finance_form ) end def idv_finance_form @_idv_finance_form ||= Idv::FinanceForm.new(idv_session.params) end end end
require 'pstore' require 'forwardable' module Medusa module Storage class PStore extend Forwardable def_delegators :@keys, :has_key?, :keys, :size def initialize(file) File.delete(file) if File.exists?(file) @store = ::PStore.new(file) @keys = {} end def [](key) @store.transaction { |s| s[key] } end def []=(key,value) @keys[key] = nil @store.transaction { |s| s[key] = value } end def delete(key) @keys.delete(key) @store.transaction { |s| s.delete key} end def each @keys.each_key do |key| value = nil @store.transaction { |s| value = s[key] } yield key, value end end def merge!(hash) @store.transaction do |s| hash.each { |key, value| s[key] = value; @keys[key] = nil } end self end def close; end end end end
require_relative 'deck' require 'byebug' class Hand def initialize @cards = [] end def empty? @cards.length == 0 end def full? @cards.length == 5 end def add_card(card) raise 'Argument is not a card' unless card.is_a?(Card) raise 'Hand is full' if full? @cards << card card end def discard(num) raise 'Argument does not indicate a card on hand' unless num.is_a?(Integer) raise 'No cards in hand' if empty? @cards.delete_at(num - 1) end def to_s return [] if empty? @cards.map{|card| card.to_s} end def to_n return [] if empty? @cards.map{|card| card.to_n} end def straight? hand = to_n if hand.include?(14) && !hand.include?(13) hand.delete(14) hand << 1 end hand.sort_by!{|value| value} hand.last - hand.first == 4 end def flush? @cards.map{|card| card.suit}.uniq.length == 1 end def royal_flush? hand = to_n straight? && flush? && hand.include?(13) && hand.include?(14) end def count_values counter = Hash.new(0) to_n.each {|value| counter[value] += 1} counter end def calculate #returns array [pair_type_value,high_value or kicker,low_value or kicker,other kicker values in order] hand = to_n counter = count_values values = counter.values.sort.reverse case values when [1,1,1,1,1] #high card,straight,flush,straight flush,royal flush return [10] if royal_flush? #royal flush if straight? && flush? if hand.include?(14) hand.delete(14) hand << 1 end return [9,hand.sort.last] #straight flush end return [6,*hand.sort.reverse] if flush? #flush if straight? if !hand.include?(13) && hand.include?(14) delete(14) hand << 1 end return [5,hand.sort.last] #straight end return [1,*hand.sort.reverse] #high card when [2,1,1,1] #one pair return [2,*counter.select{|k,v| counter[k] == 2}.to_h.keys, *counter.select{|k,v| counter[k] == 1}.to_h.keys.sort.reverse] when [2,2,1] #2-pairs return [3,*counter.select{|k,v| counter[k] == 2}.to_h.keys.sort.reverse, *counter.select{|k,v| counter[k] == 1}.to_h.keys] when [3,1,1]#3 of a kind return [4,*counter.select{|k,v| counter[k] == 3}.to_h.keys, *counter.select{|k,v| counter[k] == 1}.to_h.keys.sort.reverse] when [3,2] #full house return [7,*counter.select{|k,v| counter[k] == 3}.to_h.keys, *counter.select{|k,v| counter[k] == 2}.to_h.keys] when [4,1] #four of a kind return [8,*counter.select{|k,v| counter[k] == 4}.to_h.keys] end end def beats?(hand) my_hand = calculate other_hand = hand.calculate paired_results = my_hand.zip(other_hand) paired_results.each do |my_value,other_value| return :win if my_value > other_value return :loss if other_value > my_value end return :tie end def hand_type hand = to_n counter = count_values values = counter.values.sort.reverse case values when [1,1,1,1,1] #high card,straight,flush,straight flush,royal flush return 'ROYAL FLUSH!' if royal_flush? #royal flush return 'STRAIGHT FLUSH' if straight? && flush? return 'FLUSH' if flush? #flush return 'STRAIGHT' if straight? return 'HIGH CARD' when [2,1,1,1] #one pair return 'ONE PAIR' when [2,2,1] #2-pairs return 'TWO PAIRS' when [3,1,1]#3 of a kind return 'THREE OF A KIND' when [3,2] #full house return 'FULL HOUSE' when [4,1] #four of a kind return 'FOUR OF A KIND' end end end
require "openssl" module Celluloid module IO # SSLSocket with Celluloid::IO support class SSLSocket < Stream extend Forwardable def_delegators :@socket, :read_nonblock, :write_nonblock, :closed?, :cert, :cipher, :client_ca, :peeraddr, :peer_cert, :peer_cert_chain, :post_connection_check, :verify_result, :sync_close= def initialize(io, ctx = OpenSSL::SSL::SSLContext.new) super() @context = ctx @socket = OpenSSL::SSL::SSLSocket.new(::IO.try_convert(io), @context) @socket.sync_close = true if @socket.respond_to?(:sync_close=) end def connect @socket.connect_nonblock self rescue ::IO::WaitReadable wait_readable retry end def accept @socket.accept_nonblock self rescue ::IO::WaitReadable wait_readable retry rescue ::IO::WaitWritable wait_writable retry end def to_io @socket end end end end
module SocialPusher module Postable module Base def self.included(base) base.class_attribute :social_pusher_as base.class_attribute :social_pusher_to base.extend ClassMethods end module ClassMethods def postable(*args) options = args.extract_options! self.social_pusher_as = options[:as] self.social_pusher_to = options[:to] include InstanceMethods end end module InstanceMethods def get_social_data __send__("get_social_data_for_#{self.social_pusher_as.to_s}".to_sym) end def get_social_data_for_post { :name => self.name, :body => self.body } end def get_social_data_for_event { :name => self.name, :start_time => self.date.to_time } end def get_social_poster(service) provider_class = service.provider.camelize act_as_class = self.social_pusher_as.to_s.camelize service_params = { :token => service.token, :secret => service.secret, :target => service.fb_page_id } "SocialPusher::#{provider_class}::#{act_as_class}".constantize.new(service_params) end def collect_social_data(social_service, url) data = get_social_data data.merge!({:url => url}) if url if social_service["captcha"] && social_service["captcha_id"] data.merge!({ :captcha_sid => social_service["captcha_id"], :captcha_key => social_service["captcha"] }) end data end def provider_accepted?(social_service) self.social_pusher_to.include?(social_service.provider.to_sym) end def post_to_social(services, url = nil) return if !self.user || !self.user.social_services service_errors = {} services.each_value do |social_service| if social_service["id"] sid = social_service["id"].to_i ss = self.user.social_services.find(sid) if ss && provider_accepted?(ss) data = collect_social_data(social_service, url) poster = get_social_poster(ss) begin res = poster.create(data) if res.is_a?(Array) if res[0] == :captcha service_errors[sid] = { :captcha => res[1]} end end rescue => e service_errors[sid] = { :message => e.backtrace } end end end end service_errors end end end end end ::ActiveRecord::Base.send :include, SocialPusher::Postable::Base
class EditFamilyMembers < ActiveRecord::Migration[5.0] def change remove_column :family_members, :relationship, :string remove_column :family_members, :name, :string remove_column :family_members, :age, :integer remove_column :family_members, :living, :boolean remove_column :family_members, :cause_of_death, :string remove_column :family_members, :note, :string change_table :family_members do |t| t.belongs_to :seeded_relationship_type, null: false t.jsonb :future_patient_data_hash end end end
# frozen_string_literal: true set :local_repo_root, File.expand_path('../../../repos', __FILE__) set :local_repo_path, File.join(fetch(:local_repo_root), fetch(:application)) # We want to build this locally and push the built version to the server, # se we need to redefine the SCM tasks # rubocop:disable Metrics/BlockLength namespace :git do # rubocop:enable Metrics/BlockLength # Clone the repo to the local directory if it is not yet cloned. Rake::Task['git:clone'].clear_actions task :clone do run_locally do `mkdir -p #{fetch(:local_repo_root).to_s}` Dir.chdir(fetch(:local_repo_root).to_s) do unless Dir.exist?(fetch(:local_repo_path)) `git clone #{fetch(:repo_url)} #{fetch(:local_repo_path)}` end end end end # This shall fetch the remote repo to the local directory and update it to the # given branch/commit. Rake::Task['git:update'].clear_actions task :update do run_locally do Dir.chdir(fetch(:local_repo_path)) do `git remote update --prune` end end end # This shall only create the release directory, and not push the repository at # the given commit into it. Later on, the built app will be uploaded there. Rake::Task['git:create_release'].clear_actions task create_release: :'git:update' do on release_roles :all do with fetch(:git_environmental_variables) do within repo_path do execute :mkdir, '-p', release_path end end end end Rake::Task['git:set_current_revision'].clear_actions task :set_current_revision do run_locally do Dir.chdir(fetch(:local_repo_path)) do current_revision = `git rev-list --max-count=1 #{fetch(:branch)}`.strip set :current_revision, current_revision end end end end # This is needed because capistrano expects a repo directory to exist. after :'deploy:check:directories', :create_repo_directory do on roles(:all) do execute('mkdir', '-p', repo_path) end end # Find the latest tag in the local repository # (overwrite the task for the live stage) Rake::Task['set_latest_tag'].clear_actions after :'git:update', :set_latest_tag do run_locally do Dir.chdir(fetch(:local_repo_path)) do set :latest_tag, `git tag --list`.lines.last.strip end end end after :set_latest_tag, :set_deploy_tag after :'git:update', :'git:checkout' do run_locally do Dir.chdir(fetch(:local_repo_path)) do ref = fetch(:branch) # We check out a tag in a live stage - no 'origin/' required if fetch(:stage).to_s.split('_', 2).first != 'live' ref = "origin/#{ref}" unless ref.start_with?('origin/') end # Clean and reset to allow a checkout `git clean -fd .` `git reset --hard` # Actuall checkout `git checkout #{ref}` # Clean again because the .gitignore might have changed and thus, the # previous cleaning might be inclomplete. `git clean -fd .` end end end # Deploy the application desc 'deploy the application' task :publish_built_application do on roles(:all) do remote_base_dir = fetch(:release_path).to_s local_base_dir = File.join(fetch(:local_repo_path), 'build') files = Dir.glob(File.join(local_base_dir, '**/*')).reject do |file| File.directory?(file) end files.each do |local_file| remote_file = local_file.to_s.sub(local_base_dir, remote_base_dir) remote_dir = File.dirname(remote_file).sub(%r{\A~/}, '') execute :mkdir, '-p', remote_dir upload! local_file, remote_dir end end end
require 'test_helper' class DivesitesControllerTest < ActionController::TestCase setup do @divesite = divesites(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:divesites) end test "should get new" do get :new assert_response :success end test "should create divesite" do assert_difference('Divesite.count') do post :create, :divesite => @divesite.attributes end assert_redirected_to divesite_path(assigns(:divesite)) end test "should show divesite" do get :show, :id => @divesite.to_param assert_response :success end test "should get edit" do get :edit, :id => @divesite.to_param assert_response :success end test "should update divesite" do put :update, :id => @divesite.to_param, :divesite => @divesite.attributes assert_redirected_to divesite_path(assigns(:divesite)) end test "should destroy divesite" do assert_difference('Divesite.count', -1) do delete :destroy, :id => @divesite.to_param end assert_redirected_to divesites_path end end
module Packit class Field attr_accessor :name, :args def initialize( name, args ) @name = Utils.cache_key_for name @args = args end def size 0 end def call nil end end class Record def initialize @fields = [] end # TODO: test me def call yield self if block_given? # I forgot what happens here to_a.map { | field | field.call } end def add name, args = {} @fields << Field.new( name.to_sym, args ) self end def bring record @fields += Backend.find( record ).to_a self end def size @fields.inject( 0 ) { | sum, f | sum + f.size } end def to_a @fields.to_a end end class Backend class << self def new &block block.call( Record.new ) end def create name, &block key = Utils.cache_key_for name records[ key ] ||= new &block end def find record return record if record.respond_to? :bring records[ Utils.cache_key_for( record ) ] end def count records.size end def clear records.clear end private def records @@records ||= {} end end end class Utils def self.cache_key_for name return name.to_sym if name.respond_to? :to_sym name end end class << self def [] name Backend.find name end # TODO: test me def call name, &block record = Backend.find name record.call &block end end end
#!/usr/bin/env ruby require 'rubygems' require 'net/ssh' require 'yaml' begin config = YAML.load_file(File.join(File.dirname(__FILE__), 'config.yml')) Net::SSH.start(config[:host], config[:username]) do |ssh| puts ssh.exec!("cd #{config[:dir]}; git pull; git submodule update") end rescue Errno::ENOENT msg = <<-HEREDOC *** missing bin/config.yml cp bin/config_sample.yml bin/config.yml and edit ... HEREDOC raise msg rescue Net::SSH::AuthenticationFailed msg = <<-HEREDOC *** SSH authentication failed connecting to: #{config[:host]}" check the configuration: bin/config.yml HEREDOC raise msg rescue SocketError msg = <<-HEREDOC *** unable to connect to: #{config[:host]}" Are you connected to the network? HEREDOC raise msg end
# encoding: utf-8 Redmine::Plugin.register :redmine_drawio do name 'Redmine Drawio plugin' author 'Michele Tessaro' description 'Wiki macro plugin for inserting drawio diagrams into Wiki pages and Issues' version '1.4.7' url 'https://github.com/mikitex70/redmine_drawio' author_url 'https://github.com/mikitex70' requires_redmine :version_or_higher => '2.6.0' settings(partial: 'settings/drawio_settings', default: {'drawio_service_url' => '//embed.diagrams.net', 'drawio_mathjax' => false, 'drawio_mathjax_url' => '//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js', 'drawio_svg_enabled' => false }) should_be_disabled false if Redmine::Plugin.installed?(:easy_extensions) end unless Redmine::Plugin.installed?(:easy_extensions) require_relative 'after_init' end
require 'goby' module Goby # Allows a player to buy and sell Items. class Shop < Event # Message for when the shop has nothing to sell. NO_ITEMS_MESSAGE = "Sorry, we're out of stock right now!\n\n" # Message for when the player has nothing to sell. NOTHING_TO_SELL = "You have nothing to sell!\n\n" # Introductory greeting at the shop. WARES_MESSAGE = "Please take a look at my wares.\n\n" # @param [String] name the name. # @param [Integer] mode convenient way for a shop to have multiple actions. # @param [Boolean] visible whether the shop can be seen/activated. # @param [[Item]] items an array of items that the shop sells. def initialize(name: "Shop", mode: 0, visible: true, items: []) super(mode: mode, visible: visible) @name = name @command = "shop" @items = items end # The chain of events for buying an item (w/ error checking). # # @param [Player] player the player trying to buy an item. def buy(player) print_items return if @items.empty? print "What would you like (or none)?: " name = player_input index = has_item(name) # The player does not want to buy an item. return if name.casecmp("none").zero? if index.nil? # non-existent item. print "I don't have #{name}!\n\n" return end # The specified item exists in the shop's inventory. item = @items[index] print "How many do you want?: " amount_to_buy = player_input total_cost = amount_to_buy.to_i * item.price if total_cost > player.gold # not enough gold. puts "You don't have enough gold!" print "You only have #{player.gold}, but you need #{total_cost}!\n\n" return elsif amount_to_buy.to_i < 1 # non-positive amount. puts "Is this some kind of joke?" print "You need to request a positive amount!\n\n" return end # The player specifies a positive amount. player.remove_gold(total_cost) player.add_item(item, amount_to_buy.to_i) print "Thank you for your patronage!\n\n" end # Returns the index of the specified item, if it exists. # # @param [String] name the item's name. # @return [Integer] the index of an existing item. Otherwise nil. def has_item(name) @items.each_with_index do |item, index| return index if item.name.casecmp(name).zero? end return end # Displays the player's current amount of gold # and a greeting. Inquires about next action. # # @param [Player] player the player interacting with the shop. # @return [String] the player's input. def print_gold_and_greeting(player) puts "Current gold in your pouch: #{player.gold}." print "Would you like to buy, sell, or exit?: " input = player_input doublespace: false print "\n" return input end # Displays a formatted list of the Shop's items # or a message signaling there is nothing to sell. def print_items if @items.empty? print NO_ITEMS_MESSAGE else print WARES_MESSAGE @items.each { |item| puts "#{item.name} (#{item.price} gold)" } print "\n" end end # The amount for which the shop will purchase the item. # # @param [Item] item the item in question. # @return [Integer] the amount for which to purchase. def purchase_price(item) item.price / 2 end # The default shop experience. # # @param [Player] player the player interacting with the shop. def run(player) # Initial greeting. puts "Welcome to #{@name}." input = print_gold_and_greeting(player) while input.casecmp("exit").nonzero? if input.casecmp("buy").zero? buy(player) elsif input.casecmp("sell").zero? sell(player) end input = print_gold_and_greeting(player) end print "#{player.name} has left #{@name}.\n\n" end # The chain of events for selling an item (w/ error checking). # # @param [Player] player the player trying to sell an item. def sell(player) # The player has nothing to sell. if player.inventory.empty? print NOTHING_TO_SELL return end player.print_inventory print "What would you like to sell? (or none): " input = player_input index = player.has_item(input) # The player does not want to sell an item. return if input.casecmp("none").zero? if index.nil? # non-existent item. print "You can't sell what you don't have.\n\n" return end item = player.inventory[index].first item_count = player.inventory[index].second unless item.disposable # non-disposable item (cannot sell/drop). print "You cannot sell that item.\n\n" return end puts "I'll buy that for #{purchase_price(item)} gold." print "How many do you want to sell?: " amount_to_sell = player_input.to_i if amount_to_sell > item_count # more than in the inventory. print "You don't have that many to sell!\n\n" return elsif amount_to_sell < 1 # non-positive amount specified. puts "Is this some kind of joke?" print "You need to sell a positive amount!\n\n" return end player.add_gold(purchase_price(item) * amount_to_sell) player.remove_item(item, amount_to_sell) print "Thank you for your patronage!\n\n" end attr_accessor :name, :items end end
class AddTrackRefToEvents < ActiveRecord::Migration def change add_reference :events, :track, index: true add_foreign_key :events, :tracks end end
class Admin::UsersController < Admin::AdminController before_action :set_user, only: [:ban, :change_role] def index @search = User.ransack(params[:q]) @users = @search.result end def ban @user.banned = @user.banned ? false : true @user.save redirect_to admin_users_path end def change_role @user.admin = @user.admin ? false : true @user.save redirect_to admin_users_path end private def set_user @user = User.find(params[:id]) end end
class ApplicationController < ActionController::Base protect_from_forgery rescue_from ActiveRecord::RecordNotFound, :with => :render_404 def help Helper.instance end def render_404 render :file => "#{Rails.root}/public/404.html", :status => 404 end def redirect_with_delay(url, delay = 0) @redirect_url, @redirect_delay = url, delay render end class Helper include Singleton include ActionView::Helpers::TextHelper include ActionView::Helpers::SanitizeHelper 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 before_create :update_access_token! require 'securerandom' def update_access_token! return if access_token.present? self.access_token = SecureRandom.uuid.gsub(/\-/,'') end end
module API module V1 class Devices < Grape::API include API::V1::Defaults resource :devices do desc "create a device" post do Device.find_or_create_by(token: params[:token], platform: params[:platform]) end end end end end
class AddColumnToItemsController < ActiveRecord::Migration def change add_column :items, :counter, :integer, default: 0 end end
class Admin::PeriodsController < ApplicationController def index @periods = policy_scope(Period) end def show @period = Period.find(params[:id]) authorize(@period) end def new @period = Period.new authorize(@period) end def create @period = Period.new(params.require(:period).permit(:name, :start_date, :end_date)) authorize(@period) if @period.save redirect_to admin_period_path(@period), notice: 'Period successfully created' else render action: :new end end def edit @period = Period.find(params[:id]) authorize(@period) end def update @period = Period.find(params[:id]) authorize(@period) if @period.update(params.require(:period).permit(:name, :start_date, :end_date)) redirect_to admin_period_path(@period), notice: 'Period successfully updated' else render action: :edit end end def destroy @period = Period.find(params[:id]) authorize(@period) @period.destroy redirect_to admin_periods_path, notice: 'Period successfully removed' end def destroy_confirmation @period = Period.find(params[:id]) authorize(@period) end def set_current @period = Period.find(params[:id]) authorize(@period) if request.post? if Period.set_current(@period) notice = "Period set as current one" else notice = @period.errors.full_messages[0] end redirect_to admin_period_path(@period), notice: notice end end end
class UsersController < ApplicationController before_action :authenticate_user! def new_profile @user = current_user end def create_profile @user = User.find(params[:user][:id]) if @user.update_attributes(user_params) redirect_to dashboard_path, notice: 'Profile was successfully created.' else render :new_profile end end def dashboard @user = current_user redirect_to new_profile_path if @user.username.nil? @feed = @user.feed if @user.posts.empty? @new_post = @user.posts.build end @trainers = User.where(role: 1) # @hash = Gmaps4rails.build_markers(@trainers) do |trainers, marker| # marker.infowindow "<b>#{trainers.username}</b>" # marker.lat trainers.latitude # marker.lng trainers.longitude # end end private def user_params params.require(:user).permit(:username, :body_type, :age, :gender, :tag_list, locations_attributes: [:postal_code]) end end
# (日次)overwatchブログ投稿バッチ処理 # Author:: himeno # Date:: 2016/09/20 # Execute:: rails runner PostOverWatch.execute class PopularOverWatch < PopularBatchBase @@batch_description = 'OverWatchブログ 投稿' @@blog_url = 'https://omnic.wordpress.com' @@user = Rails.application.secrets.omnic_user @@password = Rails.application.secrets.omnic_password @@categories = ['OVERWATCH','人気記事ランキング'] @@keywords = ['OVERWATCH', 'オーバーウォッチ'] def self.create_description cnt = 0 description = '<table>' #24時間以内の人気記事順を取得 contents = Content.contain_tags(@@keywords).today_ranking.limit(@@article_count) contents.each do |content| cnt += 1 # 投稿用画像取得 article = ArticleConstructor.build_from_content(content) appendix = article.image('https://pbs.twimg.com/profile_images/750599382647578624/Z0DsSnik.jpg') # 投稿投稿内容の生成 description << "<tr><td><a href=\"#{content.text}\" target=\"_blank\">" description << image_description(appendix.text) description << "#{content.title}" description << "</a></td></tr>" end description << "</table>" Rails.logger.debug description return description end def self.image_description(image_path) return "<img class=\"alignnone size-full wp-image-80 aligncenter\" src=\"#{image_path}\" alt=\"gazou_0178\" align=\"left\" width=\"100\"/>" end end
require 'tb' require 'test/unit' class TestCustomCmp < Test::Unit::TestCase def test_revcmp cmp = lambda {|a, b| b <=> a } v1 = Tb::CustomCmp.new(1, &cmp) v2 = Tb::CustomCmp.new(2, &cmp) v3 = Tb::CustomCmp.new(3, &cmp) assert_equal(2 <=> 1, v1 <=> v2) assert_equal(1 <=> 2, v2 <=> v1) assert_equal(3 <=> 3, v3 <=> v3) end end
require "esv" describe ESV, ".generate and .parse" do it "works" do data = ESV.generate do |esv| esv << [ "Dogs", "Cats" ] esv << [ 1, 2 ] end output = ESV.parse(data) expect(output).to eq [ [ "Dogs", "Cats" ], [ 1, 2 ], ] end end describe ESV, ".parse" do it "raises if there's more than one worksheet" do excel_file_with_two_worksheets = generate_excel_file do |sheet, book| book.create_worksheet end expect { ESV.parse(excel_file_with_two_worksheets) }.to raise_error(/Expected 1 worksheet, found 2/) end it "ignores formatting, always returning a plain array of data" do excel_file_with_formatting = generate_excel_file do |sheet| sheet.row(0).replace([ 1, 2 ]) sheet.row(0).default_format = Spreadsheet::Format.new(color: :blue) end output = ESV.parse(excel_file_with_formatting) expect(output).to eq [ [ 1, 2 ], ] expect(output[0].class).to eq Array end it "returns the last value of a formula cell" do excel_file_with_formula = generate_excel_file do |sheet| formula = Spreadsheet::Formula.new formula.value = "two" sheet.row(0).replace([ "one", formula ]) end output = ESV.parse(excel_file_with_formula) expect(output).to eq [ [ "one", "two" ], ] expect(output[0].class).to eq Array end it "returns the URL of a link cell" do excel_file_with_link = generate_excel_file do |sheet| link = Spreadsheet::Link.new("https://example.com", "desc", "foo") sheet.row(0).replace([ "one", link ]) end output = ESV.parse(excel_file_with_link) expect(output).to eq [ [ "one", "https://example.com#foo" ], ] expect(output[0][1].class).to eq String end private def generate_excel_file(&block) book = Spreadsheet::Workbook.new sheet = book.create_worksheet block.call(sheet, book) data = "" fake_file = StringIO.new(data) book.write(fake_file) data end end describe ESV, ".generate_file and .parse_file" do before do @file = Tempfile.new("esv") end it "works" do path = @file.path ESV.generate_file(path) do |esv| esv << [ "Dogs", "Cats" ] esv << [ 1, 2 ] end output = ESV.parse_file(path) expect(output).to eq [ [ "Dogs", "Cats" ], [ 1, 2 ], ] end after do @file.close @file.unlink end end
class InvestorsDatatable delegate :params, :h, :link_to, to: :@view include Rails.application.routes.url_helpers include ActionView::Helpers::OutputSafetyHelper def initialize(view) @view = view end def as_json(options = {}) { sEcho: params[:sEcho].to_i, iTotalRecords: User.count, iTotalDisplayRecords: users.total_entries, aaData: data } end private def data users.map do |user| [ (user.full_name.present? ? user.full_name : ''), (user.email.present? ? user.email : ''), (user.legal_agent.present? ? user.legal_agent : '' ), (user.country.present? && user.country.name.present? ? user.country.name : '' ), (user.rut.present? ? user.rut : '' ), (user.address.present? ? user.address : '' ), (user.phone.present? ? user.phone : ''), (user.balance.present? ? user.balance : '' ), (user.transfers.any? ? user.transfers.size : '0' ), link_to('Delete', admin_investor_path(user), method: :delete, data: { confirm: '¿Are you sure want to delete this user ?' }, class: 'btn btn-xs btn-danger')+" "+ link_to('Show', admin_investor_path(user), class: 'btn btn-xs btn-success')+" "+ link_to('Edit', edit_admin_investor_path(user), class: 'btn btn-xs btn-warning') ] end end def users @users ||= fetch_users end def fetch_users users = (User.with_role :investor).eager_load(:country).order("#{sort_column} #{sort_direction}") users = users.page(page).per_page(per_page) if params[:sSearch].present? #users = users.where("CAST(TO_CHAR(users.created_at, 'dd/mm/YYYY') AS TEXT) LIKE :search OR users.full_name LIKE :search OR users.email LIKE :search OR users.legal_agent LIKE :search OR users.nationality LIKE :search OR users.rut LIKE :search OR users.address LIKE :search OR users.phone LIKE :search OR CAST(users.balance as text) LIKE :search ", search: "%#{params[:sSearch]}%") users = users.where("users.full_name LIKE :search OR users.email LIKE :search OR users.legal_agent LIKE :search OR countries.name LIKE :search OR users.rut LIKE :search OR users.address LIKE :search OR users.phone LIKE :search OR CONVERT(users.balance, CHAR(50)) LIKE :search", search: "%#{params[:sSearch]}%") end users end def page params[:iDisplayStart].to_i / per_page + 1 end def per_page params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10 end def sort_column columns = [ 'users.full_name', 'users.email', 'users.legal_agent', 'countries.name', 'users.rut' , 'users.address', 'users.phone', 'users.balance', '', ''] columns[params[:iSortCol_0].to_i] end def sort_direction params[:sSortDir_0] == 'desc' ? 'desc' : 'asc' end end
module Locomotive module ActionController module AgeGate extend ActiveSupport::Concern included do before_filter :verify_age end module ClassMethods def bypass_urls @bypass_urls || [] end def bypass_age_gate(*args) @bypass_urls = args end end def verify_age unless bypass? || verified? session[:original_request] = request.fullpath redirect_to LPAPath else check_verification end end protected LPAPath = "/lpa" BotAgentMatcher = /alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/ VerificationAge = 21 DaysPerYear = 365 UnderageRedirectURL = "http://www.centurycouncil.org/landing" BypassParam = :bypass_lpa ProtectedController = "locomotive/public/pages" def check_verification if !params[:lpa].nil? day, month, year, remember = params[:lpa].values_at(:day, :month, :year, :remember) redirect_to LPAPath && return if day.nil? || month.nil? || year.nil? supplied_age_in_days = Date.today - Date.parse("#{day}/#{month}/#{year}") if supplied_age_in_days >= VerificationAge * DaysPerYear session[:verified_at] = Time.now session[:age_verified] = true if remember session[:verification_duration] = 1.week else session[:verification_duration] = 1.hour end redirect_url = session[:original_request] || "/" session[:original_request] = nil redirect_to redirect_url else redirect_to UnderageRedirectURL end end end def bypass? agent_is_bot? || !controller_protected? || !params[BypassParam].nil? || ApplicationController.bypass_urls.include?(path.split("/").first) end def verified? session[:age_verified] && !verification_expired? end def verification_expired? !session[:verification_duration].nil? && !session[:verified_at].nil? && session[:verification_duration] < Time.now - session[:verified_at] end def agent_is_bot? agent.downcase =~ BotAgentMatcher end def controller_protected? params[:controller] == ProtectedController && "/#{path}" != LPAPath end def path params[:path] || '' end def agent request.env["HTTP_USER_AGENT"] || '' end end end end
module Harvest module Domain class Fisherman extend Realm::Domain::AggregateRoot def initialize(attributes) fire(:fisherman_registered, uuid: Harvest.uuid, name: attributes[:name]) end def assign_user(uuid: required(:uuid)) fire(:user_assigned_to_fisherman, user_uuid: uuid) end def set_up_in_business_in(fishing_ground) invalid_operation("Fisherman is already in business there") if @current_fishing_ground_uuid # Command calling command - this is the clue we need a long running process for the ground # (by comparison, assign_user above only takes the uuid) fishing_ground.new_fishing_business_opened(self, fishing_business_name: @name) fire(:fisherman_set_up_in_business_in, uuid: uuid, fishing_ground_uuid: fishing_ground.uuid) end private def event_factory Events end def apply_fisherman_registered(event) @uuid = event.uuid @name = event.name @current_fishing_ground_uuid = nil end def apply_user_assigned_to_fisherman(event) # Currently unused: # @user_uuid = event.user_uuid end def apply_fisherman_set_up_in_business_in(event) @current_fishing_ground_uuid = event.fishing_ground_uuid end end end end
class FieldsController < ApplicationController before_action :require_user before_action :current_user before_action :user_expiration def index @field = Field.new @fields = @current_user.fields.where(archived: false) end def create @field = Field.new(field_params) @field.user = current_user if @field.save session[:field_id] = @field.id redirect_to campo_path(@field.id) else flash[:danger] = "Ocorreu um erro. Tente novamente!" redirect_to campos_path end end def show @field = Field.find(params[:id]) if require_same_user(@field.user.id) session[:field_id] = @field.id end end def pdf @field = Field.find(params[:id]) if @field.treatments.any? @si_end = @field.treatments[0].date end fertilizations_total(@field.fertilizations) if require_same_user(@field.user.id) respond_to do |format| format.pdf do render pdf: "book", disposition: "inline", template: "fields/record.pdf.erb", orientation: "Landscape", page_size: "A4", title: @field.name + "(" + @field.date.strftime('%d/%m/%Y') + ")" end end end end def archive_index @fields = @current_user.fields.where(archived: true) render 'index' end def archive_field @field = Field.find(params[:id]) if require_same_user(@field.user.id) @field.update(archived: !@field.archived) if @field.archived redirect_to arquivo_path else redirect_to campos_path end end end private def field_params params.require(:field).permit(:name, :culture, :date) end end
Pod::Spec.new do |s| s.name = "MoipSDK" s.version = "1.0.5" s.summary = "Cliente iOS para integração com as APIs v2 Moip, possibilita a criptografia de dados sensíveis de cartão de crédito." s.description = <<-DESC Cliente iOS para integração com as APIs v2 Moip, possibilita a criptografia de dados sensíveis de cartão de crédito. DESC s.homepage = "https://github.com/moip/ios-sdk" s.license = "MIT" s.author = { "Moip" => "mobile@moip.com" } s.platform = :ios s.ios.deployment_target = "7.0" s.source = { :git => "https://github.com/moip/ios-sdk.git", :tag => s.version } s.source_files = "MoipSDK", "MoipSDK/**/*.{h,m}" s.public_header_files = "MoipSDK/**/*.h" s.requires_arc = true end
class User < ApplicationRecord has_many :favorites, dependent: :destroy has_many :reviews has_many :social_profiles, dependent: :destroy # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :trackable, :omniauthable, omniauth_providers: %i[line google] enum gender: { "male": 0, "female": 1, "other": 2 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :name, presence: true, length: { in: 1..30 } validates :email, presence: true, length: { maximum: 100 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: true validates :password, presence: true, length: { minimum: 6 } ,allow_nil: true validates :address, presence: true, length: { in: 5..60 } validates :gender, presence: true validates :nickname, length: { in: 1..30 }, allow_blank: true protected def social_profile(provider) social_profiles.select{ |sp| sp.provider == provider.to_s }.first end end
FactoryGirl.define do factory :manufacturer do name do ['Musashi Industrial and Starflight Concern', 'Drake Interplanetary', 'Roberts Space Industries', 'Anvil Aerospace'].sample end short do name.split(' ')[0] end end end
require 'rails_helper' RSpec.describe "PETS index page - A user", type: :feature do before(:each) do @shelter_1 = Shelter.create( name: "Henry Porter's Puppies", address: "1315 Monaco Parkway", city: "Denver", state: "CO", zip: "80220" ) @pet_1 = Pet.create( name: "Holly", age: 4, sex: "Male", shelter_id: @shelter_1.id, image: 'hp.jpg', description: 'Cute', adoptable_status: 'Adoptable') @pet_2 = Pet.create( name: "Liza Bear", age: 16, sex: "Female", shelter_id: @shelter_1.id, image: 'hp2.jpg', description: 'Cute', adoptable_status: 'Adoptable') end it "can see the name and info of each pet in the system" do visit "/pets" expect(page).to have_content(@pet_1.name.upcase) expect(page).to have_content(@pet_2.name.upcase) expect(page).to have_content(@pet_1.age) expect(page).to have_content(@pet_2.age) expect(page).to have_content(@pet_1.sex) expect(page).to have_content(@pet_2.sex) expect(page).to have_css("img[src='/assets/hp-606612a36d3cc16d901e74616fbd73a568030910d171797aa44123d55a9bfa70.jpg']") expect(page).to have_css("img[src='/assets/hp2-d54ec5938e641f10459be7bdba8fbb7fed849ec44ba2d1ed8568773d69bd164d.jpg']") end it "can click to edit an existing pet" do visit "/pets" within("##{@pet_1.id}") do click_link "Edit Pet" end expect(page).to have_current_path("/pets/#{@pet_1.id}/edit") visit "/pets" within("##{@pet_2.id}") do click_link "Edit Pet" end expect(page).to have_current_path("/pets/#{@pet_2.id}/edit") end it "can click to delete an existing pet" do visit "/pets" within("##{@pet_1.id}") do click_link "Delete Pet" end expect(page).to have_current_path("/pets") expect(page).not_to have_content(@pet_1.name) visit "/pets" within("##{@pet_2.id}") do click_link "Delete Pet" end expect(page).to have_current_path("/pets") expect(page).not_to have_content(@pet_2.name) end it "can click to show the shelter", type: :feature do visit "/pets" within("##{@pet_1.id}") do click_link "#{@pet_1.shelter_name}" end expect(page).to have_current_path("/shelters/#{@shelter_1.id}") visit "/pets" within("##{@pet_2.id}") do click_link "#{@pet_2.shelter_name}" end expect(page).to have_current_path("/shelters/#{@shelter_1.id}") end it "can click to show the pet" do visit "/pets" within("##{@pet_1.id}") do click_link "#{@pet_1.name.upcase}" end expect(page).to have_current_path("/pets/#{@pet_1.id}") visit "/pets" within("##{@pet_2.id}") do click_link "#{@pet_2.name.upcase}" end expect(page).to have_current_path("/pets/#{@pet_2.id}") end end
class LineItem attr_reader :quantity def initialize(quantity, item) @quantity = quantity @item = item end def item_name; item.name end def item_price; item.price end def item_indication; item.indication end def total quantity * item_price end private def item; @item end end
class CreateUserContactGroups < ActiveRecord::Migration def change create_table :user_contact_groups do |t| t.integer :user_id t.integer :contact_group_id t.integer :gg_contact_group_id t.timestamps end end end
class AddCastAndCrewToMovies < ActiveRecord::Migration[5.1] def change add_column :movies, :cast, :string add_column :movies, :crew, :string end end
#!/usr/bin/env ruby require_relative 'crypter.rb' # Hauptprogramm if (ARGV.length < 3) puts "Too few arguments!" puts "Usage: cracker HASH WORD-FILE TRANSFORM-FILE [-v]" exit end hash = ARGV[0] wordlist_file = ARGV[1] transform_file = ARGV[2] verbose = ARGV.length == 4 && ARGV[3] == "-v" # Step 1: Common words puts "Teste gegen Worliste #{wordlist_file}\n\n" starting = Time.now File.open(wordlist_file, "r:UTF-8").each do |line| word = line.chomp puts "\033[1ATeste: " + word + " " * (70 - word.length) if verbose #puts line if test_password(word, hash) puts "\nGefunden: " + word exit end end puts "Laufzeit: %.2f s" % (Time.now - starting) # Step 2: Common words - transmogrified puts "\nTeste #{wordlist_file} mit Modifikationen aus #{transform_file}\n\n" # Read transformations transformations = [] File.open(transform_file, "r:UTF-8").each do |line| elements = line.split(' ') transformations << [ Regexp.new(elements[0].gsub(/\//, "")), elements[1] ] end starting = Time.now # Test words (with transformations) File.open(wordlist_file, "r:UTF-8").each do |line| line = line.chomp transformations.each do |t| word = line.gsub(t[0], t[1]) # Test only real modifications if word == line next end puts "\033[1ATeste: " + word + " " * (70 - word.length) if verbose if test_password(word, hash) puts "\nGefunden: " + word exit end end end puts "Laufzeit: %.2f s" % (Time.now - starting) # Step 3: Brute force starting = Time.now for i in 1..8 do puts "\nBrute Force Angriff Länge #{i}\n\n" starting = Time.now "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.:-_,;!\"§$%&/()=?ß`´*+'#" .chars .repeated_permutation(i) .lazy .map(&:join) .each do |word| puts "\033[1ATeste: " + word + " " * (70 - word.length) if verbose if test_password(word, hash) puts "\nGefunden: " + word.chomp puts "Laufzeit: %.2f s" % (Time.now - starting) exit end end puts "Laufzeit: %.2f s" % (Time.now - starting) end
require 'test_helper' class TrendsControllerTest < ActionDispatch::IntegrationTest fixtures :seasons, :heroes setup do @past_season = seasons(:one) @season = seasons(:two) @future_season = create(:season, started_on: 2.months.from_now) @user = create(:user) @account = create(:account, user: @user) @hero1 = heroes(:ana) @hero2 = heroes(:genji) @friend = create(:friend, user: @user) @match1 = create(:match, account: @account, season: @season.number, result: :win, group_member_ids: [@friend.id], heroes: [@hero1]) @match2 = create(:match, account: @account, season: @season.number, prior_match: @match1, group_member_ids: [@friend.id], heroes: [@hero2]) end test 'all seasons/accounts page redirects anonymous user' do get '/trends/all-seasons-accounts' assert_response :redirect assert_redirected_to 'http://www.example.com/' end test 'all seasons page redirects anonymous user' do get "/trends/all-seasons/#{@account.to_param}" assert_response :redirect assert_redirected_to 'http://www.example.com/' end test 'all accounts page redirects anonymous user' do get '/trends/all-accounts/2' assert_response :redirect assert_redirected_to 'http://www.example.com/' end test 'all seasons/accounts page loads successfully for authenticated user with no matches' do account = create(:account) sign_in_as(account) get '/trends/all-seasons-accounts' assert_response :ok assert_select 'div.mb-4', text: /Matches logged:\s+0/ end test 'all seasons page loads successfully for authenticated user with no matches' do account = create(:account) sign_in_as(account) get "/trends/all-seasons/#{account.to_param}" assert_response :ok assert_select 'div', text: /Matches logged:\s+0/ end test 'all accounts page loads successfully for authenticated user with no matches' do account = create(:account) season = seasons(:two) sign_in_as(account) get "/trends/all-accounts/#{season}" assert_response :ok assert_select 'div', text: /Matches logged:\s+0/ end test 'all seasons/accounts page loads successfully for authenticated user with matches' do account2 = create(:account, user: @user) create(:match, account: @account, season: @past_season.number, result: :win) create(:match, account: account2, season: @past_season.number, result: :loss) sign_in_as(account2) get '/trends/all-seasons-accounts' assert_response :ok assert_select 'div.mb-4', text: /Matches logged:\s+4/ assert_select 'div.mb-4', text: /Active in seasons:\s+#{@past_season}, #{@season}/ assert_select 'div', text: /2\s+accounts with matches/ end test 'all seasons page loads successfully for authenticated user with matches' do create(:match, account: @account, season: @past_season.number, result: :win) sign_in_as(@account) get "/trends/all-seasons/#{@account.to_param}" assert_response :ok assert_select 'div.mb-4', text: /Matches logged:\s+3/ assert_select 'div', text: /Active in seasons:\s+#{@past_season}, #{@season}/ end test 'all accounts page loads successfully for authenticated user with matches' do account2 = create(:account, user: @user) create(:match, account: @account, season: @past_season.number, result: :win) create(:match, account: account2, season: @past_season.number, result: :loss) create(:match, account: @account, season: @past_season.number, result: :draw) sign_in_as(@account) get "/trends/all-accounts/#{@past_season}" assert_response :ok assert_select 'div.mb-4', text: /Matches logged:\s+3/ assert_select 'div', text: /2\s+accounts with matches/ end test "redirects to home page for another user's account" do account2 = create(:account) sign_in_as(@account) get "/trends/all-seasons/#{account2.to_param}" assert_redirected_to root_path end test 'says season has not started for future season' do sign_in_as(@account) get "/trends/#{@future_season}/#{@account.to_param}" assert_select '.blankslate', text: /Season #{@future_season} has not started yet./ end test 'says when user has not logged matches in past season' do sign_in_as(@account) get "/trends/#{@past_season}/#{@account.to_param}" assert_select '.blankslate', text: /#{@account}\s+did not log\s+any competitive matches in season #{@past_season}./ end test 'redirects to home page when season not shared for anonymous user' do get "/trends/#{@season}/#{@account.to_param}" assert_redirected_to root_path end test 'index page loads for owner' do sign_in_as(@account) get "/trends/#{@season}/#{@account.to_param}" assert_response :ok end test 'index page loads for anonymous user when season is shared' do create(:season_share, account: @account, season: @season.number) get "/trends/#{@season}/#{@account.to_param}" assert_response :ok end test 'index page loads for a user who is not the owner when season is shared' do create(:season_share, account: @account, season: @season.number) other_account = create(:account) sign_in_as(other_account) get "/trends/#{@season}/#{@account.to_param}" assert_response :ok end end
require 'csspool' module CSSPoolSanitizer private def parse_and_sanitize(raw, sanitizer, allowed_selectors) source_doc = CSSPool.CSS raw dest_doc = "" source_doc.rule_sets.each do |rs| if rs.selectors.all? { |s| allowed_selectors.include?(s.to_s) } sanitized = sanitizer.sanitize_css(rs.declarations.to_s) dest_doc << "#{rs.selectors.join(", ").to_s}\n {\n #{sanitized}\n}\n" end end dest_doc.to_s end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception helper_method :current_user def current_user if session[:user_id] @current_user = User.find(session[:user_id]) else @current_user = nil end end def logged_in? # this works !!current_user end def authorize redirect_to '/login' unless current_user end # def authorized # if logged_in? # else # redirect_to login_path # end # end end
require 'spec_helper' require 'jsonapi/schema' RSpec.describe Jsonapi::Schema do describe '#type' do it 'raises if no type is defined' do test_class = Class.new(described_class) type_call = -> { test_class.new.type } expect(type_call).to raise_error(Jsonapi::TypeMustBeDefined) end it 'sets the type of every entity of this schema' do test_class = Class.new(described_class) do type :todos end expect(test_class.new.type).to eq(:todos) end it 'works correctly with multiple inherited classes' do test_class1 = Class.new(described_class) do type :todos end test_class2 = Class.new(described_class) do type :users end expect(test_class1.new.type).to eq(:todos) expect(test_class2.new.type).to eq(:users) end end describe '#attribute' do it 'returns an empty array if no attributes were set' do test_class = Class.new(described_class) expect(test_class.new.attributes).to eq([]) end it 'adds each attribute to the attributes array' do test_class = Class.new(described_class) do attribute :name attribute :email end expect(test_class.new.attributes).to contain_exactly(:name, :email) end it 'works correctly with multiple inherited classes' do test_class1 = Class.new(described_class) do attribute :task end test_class2 = Class.new(described_class) do attribute :name attribute :email end expect(test_class1.new.attributes).to contain_exactly(:task) expect(test_class2.new.attributes).to contain_exactly(:name, :email) end end describe '#relationships' do it 'returns an empty hash if not declared' do test_class = Class.new(described_class) expect(test_class.new.relationships).to eq({}) end it 'returns the type, cardinality indexed by name of each relationship' do test_class = Class.new(described_class) do has_one :user, type: :users has_many :posts, type: :blog_posts end relationships = test_class.new.relationships expect(relationships).to match( user: a_hash_including(type: :users, cardinality: :one), posts: a_hash_including(type: :blog_posts, cardinality: :many) ) end end end
class Question < ApplicationRecord has_many :answers, dependent: :destroy validates :title, :contents, presence: true, length: { minimum: 5 } #validates :askedby, presence: true def self.search(search) where("title LIKE ?", "%#{search}%") #where("contents LIKE ?", "%#{search}%") end end
require 'rubygems' require 'rake' require 'uglifier' desc "Compile the JavaScript js/BoldFace.js into buld/BoldFace-mini.js" task :compile_js => [:compile_html] do html = File.read('build/BoldFace.html').gsub!('"', "'") new_html = 'BoldFace.html = ' + '"' + html + '";' new_bookmarklet_host = "BoldFace.bookmarklet_host = 'https://raw.github.com';" compile_js("js/BoldFace.js", "build/BoldFace-min.js") do |text| text.gsub!("BoldFace.mode = 'development';", "BoldFace.mode = 'production';") text.gsub!("BoldFace.html = '<div></div>';", new_html) text.gsub!("BoldFace.bookmarklet_host = 'http://0.0.0.0:9000';", new_bookmarklet_host) end end task :compile_js_data do compile_js("js/googleWebFonts.js", "build/googleWebFonts.js") end task :compile_js_data_small do compile_js("js/googleWebFonts_SMALL.js", "build/googleWebFonts.js") end def compile_js(in_files, out_file) File.open(out_file, 'w') do |file| text = File.read(in_files) yield text if block_given? file.write Uglifier.compile(text) end end desc "Compile the JavaScript js/BoldFace.js into buld/BoldFace-mini.js" task :compile_html do args = [ ["-jar", "tools/htmlcompressor-1.5.1.jar"], ["html/BoldFace.html"], [" > ", "build/BoldFace.html"], ] command = "java #{args.flatten.join(' ')}" puts command output = `#{command}` puts output end desc "Compile the sass/BoldFace.scss into build/BoldFace.css" task :compile_sass do args = [ ["--style", "compressed"], ["sass/BoldFace.scss"], ["build/BoldFace.css"], ] command = "sass #{args.flatten.join(' ')}" puts command output = `#{command}` puts output end desc "build the bookmarklet.txt from js/bookmarklet.js" task :build_bookmarklet do uglified_js = Uglifier.compile(File.read('js/bookmarklet.js')) bookmarklet = "javascript:#{uglified_js}" File.open('bookmarklet.txt', 'w') do |file| file.write bookmarklet end end task :build_all_small => [:compile_js, :compile_js_data_small, :compile_js] task :build_all => [:compile_js, :compile_js_data, :compile_js]
# $Id$ # $Id$ # Represents a generic mailing address. Addresses are expected to consist of the # following fields: # * +addressable+ - The record that owns the address # * +street_1+ - The first line of the street address # * +city+ - The name of the city # * +postal_code+ - A value uniquely identifying the area in the city # * +region+ - Either a known region or a custom value for countries that have no list of regions available # * +country+ - The country, which may be implied by the region # # The following fields are optional: # * +street_2+ - The second lien of the street address # # There is no attempt to validate the open-ended fields since the context in # which the addresses will be used is unknown class Address < ActiveRecord::Base belongs_to :addressable, :polymorphic => true belongs_to :region belongs_to :country with_options :if => :validatible_location? do |m| m.validates_presence_of :street_1 m.validates_presence_of :city m.validates_presence_of :country_id, :on => :create m.validates_presence_of :region_id, :if => :known_region_required? ## validates_presence_of :custom_region, ## :message => 'Custom Region!?', ## :if => :custom_region_required? m.before_save :ensure_exclusive_references end validate :ensure_min_address_fields before_save :clear_moved_out_if_current_address alias_attribute :start_at, :moved_in_on alias_attribute :end_at, :moved_out_on # Virtual attributes attr_accessor :current_address, :no_street acts_as_archivable :on => :moved_in_on include TimelineEvents include CommonDateScopes include CommonDurationScopes self.end_archivable_attribute = :moved_out_on serialize_with_options do methods :postal_address end # thinking_sphinx define_index do # fields indexes [street_1, street_2] => :street indexes city indexes country(:name), :as => :country indexes region(:name), :as => :region # attributes has user_id, created_at, moved_in_on, moved_out_on group_by 'user_id' end # For formatting postal addresses from over 60 countries. # Problem: :country must return 2-letter country code for this plugin # to do country-specific formatting. # TODO: monkey-patch plugin biggs :postal_address, :recipient => Proc.new {|address| address.addressable.try(:full_name) || ""}, :zip => :postal_code, :street => [:street_1, :street_2], :state => Proc.new {|address| address.region.try(:name) }, :country => Proc.new {|address| address.country.try(:name) } LocationTypes = { 'Home' => 'home', 'Birth' => 'birth', 'Business' => 'business', 'Billing' => 'billing', 'FB' => 'facebook' }.freeze Home = LocationTypes['Home'] Birth = LocationTypes['Birth'] Business = LocationTypes['Business'] Billing = LocationTypes['Billing'] DefaultLocationType = Home EmtpyZip = "00000" named_scope :home, :conditions => {:location_type => Home} named_scope :business, :conditions => {:location_type => Business} named_scope :billing, :conditions => {:location_type => Billing} named_scope :birth, :conditions => {:location_type => Birth} include CommonDateScopes named_scope :in_dates, lambda { |start_date, end_date| { :conditions => ["((moved_out_on IS NOT NULL) AND (? BETWEEN moved_in_on AND moved_out_on)) OR " + "(moved_out_on IS NULL AND moved_in_on <= ? AND DATE(NOW()) > ?)", start_date, end_date, start_date] } } # Returns true if address location is one that needs validation def validatible_location? !([Birth].include?(location_type) || no_street) end # Returns the country, which may be determined from the # current region def country_with_region_check region ? region.country : country_without_region_check end alias_method_chain :country, :region_check # Gets the name of the region that this address is for (whether it is a custom or # known region in the database) def region_name custom_region || region && region.name end # Gets all regions for existing country def regions ignore_nil { country.regions } end # Helper for form selects #def country_id # country.id if country #end # Gets a representation of the address on a single line. # # For example, # address = Address.new # address.single_line # => "" # # address.street_1 = "1600 Amphitheatre Parkey" # address.single_line # => "1600 Amphitheatre Parkway" # # address.street_2 = "Suite 100" # address.single_line # => "1600 Amphitheatre Parkway, Suite 100" # # address.city = "Mountain View" # address.single_line # => "1600 Amphitheatre Parkway, Suite 100, Mountain View" # # address.region = Region['US-CA'] # address.single_line # => "1600 Amphitheatre Parkway, Suite 100, Mountain View, California, United States" # # address.postal_code = '94043' # address.single_line # => "1600 Amphitheatre Parkway, Suite 100, Mountain View, California 94043, United States" def single_line multi_line.join(', ') end # Gets a representation of the address on multiple lines. # # For example, # address = Address.new # address.multi_line # => [] # # address.street_1 = "1600 Amphitheatre Parkey" # address.multi_line # => ["1600 Amphitheatre Parkey"] # # address.street_2 = "Suite 100" # address.multi_line # => ["1600 Amphitheatre Parkey", "Suite 100"] # # address.city = "Mountain View" # address.multi_line # => ["1600 Amphitheatre Parkey", "Suit 100", "Mountain View"] # # address.region = Region['US-CA'] # address.multi_line # => ["1600 Amphitheatre Parkey", "Suit 100", "Mountain View, California", "United States"] # # address.postal_code = '94043' # address.multi_line # => ["1600 Amphitheatre Parkey", "Suit 100", "Mountain View, California 94043", "United States"] def multi_line lines = [] lines << street_1 if street_1? lines << street_2 if street_2? line = '' line << city if city? if region_name line << ', ' unless line.blank? line << region_name end if postal_code line << ' ' unless line.blank? line << postal_code end lines << line unless line.blank? lines << country.name if country lines end # Virtual attribute def current_address=(val) @current_address = (val && val == '1') end protected def ensure_min_address_fields errors.add_to_base("Street, City, or Country required") unless !street_1.blank? || !street_2.blank? || !city.blank? || country_id || region_id end private # Does the current country have a list of regions to choose from? def known_region_required? validatible_location? && country && country.regions.any? end # A custom region name is required if a known region was not specified and # the country in which this address resides has no known regions in the # database def custom_region_required? !region_id && country && country.regions.empty? end # Ensures that the country id/user region combo is not set at the same time as # the region id def ensure_exclusive_references if known_region_required? self.country_id = nil self.custom_region = nil end true end def clear_moved_out_if_current_address self.moved_out_on = nil if @current_address end end
FactoryGirl.define do factory :developer do sequence(:name) { |n| "Cool Person #{n}" } bio "This is a very nice person and stuff" end end
# encoding: UTF-8 class HouseMailer < ActionMailer::Base RECIPIENT = ['hello@jerevedunemaison.com', 'tukan2can@gmail.com'] default from: "Je Rêve d’une Maison <contact@jerevedunemaison.com>" helper :application # gives access to all helpers defined within `application_helper`. def create_mail(house) @house = house attachments.inline['logo.png'] = Rails.root.join('app/assets/images/logo_full.png').read mail(to: RECIPIENT, subject: "House created") do |format| format.html end end def update_mail(house) @house = house attachments.inline['logo.png'] = Rails.root.join('app/assets/images/logo_full.png').read mail(to: RECIPIENT, subject: "House updated") do |format| format.html end end def create_dream_mail(dream) @house = dream.house @user = dream.user attachments.inline['logo.png'] = Rails.root.join('app/assets/images/logo_full.png').read mail(to: RECIPIENT, subject: "House added to dream list") do |format| format.html end end def invitation_mail(house, contact_email, user) @house = house @contact_email = contact_email @user = user attachments.inline['logo.png'] = Rails.root.join('app/assets/images/logo_full.png').read mail(to: RECIPIENT, subject: "Dream apero request") do |format| format.html end end def new_item_in_folio_mail(folio) @house = folio.house @user = folio.user mail(to: @user.email, subject: "Vous avez une nouvelle annonce dans votre dossier Jerevedunemaison.com") do |format| format.html end end end
class Trinary def initialize(trinary_str) @trinary_str = trinary_str end def to_decimal return 0 if @trinary_str.match(/[^012]/) @trinary_str.to_i.digits.map.with_index do |digit, idx| digit * 3**idx end.sum end end # Hexadecimal challenge # class Hexadecimal # DIGITS = { # '0' => 0, # '1' => 1, # '2' => 2, # '3' => 3, # '4' => 4, # '5' => 5, # '6' => 6, # '7' => 7, # '8' => 8, # '9' => 9, # 'a' => 10, # 'b' => 11, # 'c' => 12, # 'd' => 13, # 'e' => 14, # 'f' => 15 # }.freeze # # def initialize(hex_str) # @hex_str = hex_str.downcase # end # # def to_decimal # return 0 if @hex_str.match(/[^0-9a-z]/) # digits = @hex_str.chars.map { |char| DIGITS[char] } # digits.reverse.map.with_index do |digit, idx| # digit * 16**idx # end.sum # end # end # # p Hexadecimal.new('af445').to_decimal == 717893
# frozen_string_literal: true class Problem3 TITLE = 'Largest prime factor' DESCRIPTION = 'The prime factors of 13195 are 5, 7, 13 and 29.'\ 'What is the largest prime factor of the number 600851475143?' def save_prime_factors # rubocop:disable Metrics/MethodLength number = 600_851_475_143 prime_factors = [] divisor = 2 while number > 1 if (number % divisor).zero? number /= divisor prime_factors << divisor else divisor += 1 end end prime_factors.last end end
class Newsletter < ActiveRecord::Base # Fetch all published news since last newsletter sending def self.latest_news last_sent = self.where(['sent_on IS NOT NULL']).last last_sent ? start_date = last_sent.sent_on : start_date = '2010-01-01 00:00:00'.to_date Post.where(['created_at > ?', start_date]).order('created_at DESC').all end end
# frozen_string_literal: true require 'get_process_mem' module Dynflow module Watchers class MemoryConsumptionWatcher attr_reader :memory_limit, :world def initialize(world, memory_limit, options) @memory_limit = memory_limit @world = world @polling_interval = options[:polling_interval] || 60 @memory_info_provider = options[:memory_info_provider] || GetProcessMem.new @memory_checked_callback = options[:memory_checked_callback] @memory_limit_exceeded_callback = options[:memory_limit_exceeded_callback] set_timer options[:initial_wait] || @polling_interval end def check_memory_state current_memory = @memory_info_provider.bytes if current_memory > @memory_limit @memory_limit_exceeded_callback.call(current_memory, @memory_limit) if @memory_limit_exceeded_callback # terminate the world and stop polling world.terminate else @memory_checked_callback.call(current_memory, @memory_limit) if @memory_checked_callback # memory is under the limit - keep waiting set_timer end end def set_timer(interval = @polling_interval) @world.clock.ping(self, interval, nil, :check_memory_state) end end end end
require 'rails_helper' RSpec.describe "customer relationships" do before(:each) do @customer = create(:customer) @invoice = create(:invoice, customer_id: @customer.id) @invoice_1 = create(:invoice, customer_id: @customer.id) end it "can load a collection of invoices associated with a customer" do get "/api/v1/customers/#{@customer.id}/invoices" expect(response).to be_successful customer_hash = JSON.parse(response.body) expect(customer_hash['data'].count).to eq(2) end it "can load a collection of invoices associated with a customer" do transaction = create(:transaction, invoice_id: @invoice.id) transaction_1 = create(:transaction, invoice_id: @invoice.id) transaction_2 = create(:transaction, invoice_id: @invoice.id) get "/api/v1/customers/#{@customer.id}/transactions" expect(response).to be_successful customer_hash = JSON.parse(response.body) expect(customer_hash['data'].count).to eq(3) end end
class StringCalculator MAXIMUM_NUMBER = 1000 def initialize(splitter) @splitter = splitter end def add(numbers) numbers = NumberCollection.new(@splitter.split(numbers)) negatives = numbers.negatives raise Exception.new("Negatives not allowed: #{negatives.inspect}") if negatives.any? small_enough(numbers).inject(0){|sum, number| sum + number} end def small_enough(numbers) numbers.select{|number| not is_too_big? number} end def is_too_big? (number) number > MAXIMUM_NUMBER end end
class Skill < ActiveRecord::Base has_many :abilities has_many :gigs, through: :abilities end
class CreateTickets < ActiveRecord::Migration def change create_table :tickets do |t| t.string :name, null: false t.float :price, null: false t.integer :scenic_id, null: false t.string :picture t.text :description t.integer :ticket_type, null: false t.integer :status, default: 0 t.integer :sys_admin_id t.timestamps null: false end end end
require 'date' module WithingsSDK module Utils def self.normalize_date_params(options) opts = hash_with_string_date_keys(options) convert_epoch_date_params!(opts) convert_ymd_date_params!(opts) if opts.has_key? 'startdateymd' and !opts.has_key? 'startdate' opts['startdate'] = to_epoch(opts['startdateymd']) end if opts.has_key? 'enddateymd' and !opts.has_key? 'enddate' opts['enddate'] = to_epoch(opts['enddateymd']) end opts['startdateymd'] = to_ymd(opts['startdate']) if opts.has_key? 'startdate' opts['enddateymd'] = to_ymd(opts['enddate']) if opts.has_key? 'enddate' opts end private def self.hash_with_string_date_keys(params) p = params.dup date_fields = [:startdateymd, :enddateymd, :startdate, :enddate, :lastupdate] date_fields.each { |key| p[key.to_s] = p.delete(key) if p.has_key? key } p end def self.convert_ymd_date_params!(params) ymd_fields = ['startdateymd', 'enddateymd'] ymd_fields.each do |key| params[key] = to_ymd(params[key]) if params.has_key? key end end def self.convert_epoch_date_params!(params) epoch_fields = ['startdate', 'enddate', 'lastdate', 'date'] epoch_fields.each do |key| params[key] = to_epoch(params[key]) if params.has_key? key end end def self.to_epoch(d) if d.is_a? Date or d.is_a? DateTime d.strftime('%s').to_i elsif d =~ /[0-9]{4}-[0-9]{2}-[0-9]{2}/ DateTime.strptime(d, '%Y-%m-%d').strftime('%s').to_i else d end end def self.to_ymd(d) if d.is_a? Date or d.is_a? DateTime d.strftime('%Y-%m-%d') elsif (d =~ /[0-9]+/) != 0 DateTime.strptime(d.to_s, '%s').strftime('%Y-%m-%d') else d end end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) Product.create(:name => 'FooBar', :price => 100) User.create(:email => 'nadqur@gmail.com', :password => 'letmein123') PaymentOption.create( [ { amount: 10.00, amount_display: '$10', description: '<strong>Basic level: </strong>You receive a great big thankyou from us! You Rock', shipping_desc: '', delivery_desc: '', limit: -1 }, { amount: 100.00, amount_display: '$100', description: '<strong>Package 1: </strong>You receive our print edition', shipping_desc: 'add $3 to ship outside the US', delivery_desc: 'Estimated delivery: Oct 2013', limit: 2 }, { amount: 125.00, amount_display: '$125', description: '<strong>Package 2: </strong>You will receive both our print and digital edition', shipping_desc: 'add $3 to ship outside the US', delivery_desc: 'Estimated delivery: Oct 2013', limit: -1 } ])
class CreateVideos < ActiveRecord::Migration def up create_table :videos do |t| t.integer :newsitem_id t.string :video_title t.string :video_link t.string :video_type t.timestamps end end def down drop_table :videos end end
=begin Test word_count method - Text Recall that in the last exercise we only had to test one method of our Text class. One of the useful facets of the setup and teardown methods is that they are automatically run before and after each test respectively. To show this we'll be adding one more method to our Text class, word_count. class Text def initialize(text) @text = text end def swap(letter_one, letter_two) @text.gsub(letter_one, letter_two) end def word_count @text.split.count end end Write a test for this new method. Make sure to utilize the setup and teardown methods for any file related operations. =end =begin Problem - Examples Data-structures Algorithm Code =end
# -*- mode: ruby -*- # vi: set ft=ruby : # vagrant plugin install vagrant-disksize # Vagrant.configure(2) do |config| # config.vm.box = "ubuntu/xenial64" config.disksize.size = "20GB" #--------------------------------------- # config.vm.box = "deadbok/debian-stretch-xfce-amd64" # config.vm.box_version = "9.2.1" #--------------------------------------- # config.vm.box = "debian/stretch64" # config.vm.box = "ubuntu/bionic64" config.vm.box = "generic/debian9" # If you want to use this system to netboot Raspberry Pi, then uncomment this line # config.vm.network "public_network", bridge: 'ask', ip: "10.0.0.1" config.vm.provider "virtualbox" do |v| v.memory = 2048 end config.vm.provision "ansible" do |ansible| ansible.playbook = "playbook.yml" end end
# frozen_string_literal: true FactoryBot.define do factory :game do player { 'Mutuba' } after(:build) do |game| game.board ||= FactoryGirl.build(:board, game: game) end end end
# After this if you don't hate kinesis, I'd be super shocked. require 'aws-sdk' require 'slack-notifier' require 'json' # Read the configuration file. See kinesis-asg-config.json. $config = JSON.parse( File.read('./kinesis-asg-config.json') ) if $config['postToSlack'] $notifier = Slack::Notifier.new $config['slack_webhook_url'], channel: $config['slack_channel'], username: $config['slack_username'], icon_emoji: $config['slack_icon'] end # The maximum bytes a shard can process per second, # and the maximum records it can process per second. $MAX_PER_SHARD_BYTES = 2097152 $MAX_PER_SHARD_RECORDS = 2000 # Determines if an arbitrary item is in an array. def item_in_array(item, arr) !([item] & arr).first.nil? end # Determines if a shard has any children. def child_shard?(shards, shard_id) !shards.select { |s| s.parent_shard_id == shard_id }.empty? end # Determines which shard has a higher hash range # for use in determining adjacents. def determine_high_shard(shard_one, shard_two) if shard_one.hash_key_range.starting_hash_key.to_i < shard_two.hash_key_range.starting_hash_key.to_i [shard_one, shard_two] else [shard_two, shard_one] end end def get_open_shards(shards) shards.select do |shard| shard.sequence_number_range.ending_sequence_number.nil? end end def check_adjacent_key_range(shards_to_test) (shards_to_test[1].hash_key_range.starting_hash_key.to_i - shards_to_test[0].hash_key_range.ending_hash_key.to_i) == 1 end # Get a list of all the adjacent shards. def get_adjacent_shards(shards) final_values = [] # Loop through the open shards comparing to every other # open shard to check for _all_ adjacents. shards.each_with_index do |open_shard, index| next unless index != (shards.length - 1) shards[(index + 1)..shards.length].each do |possibly_adjacent_shard| shards_to_test = determine_high_shard(possibly_adjacent_shard, open_shard) next unless check_adjacent_key_range(shards_to_test) final_values << { lower_hash: shards_to_test[0], higher_hash: shards_to_test[1] } end end final_values end def calculate_new_hash_key(shard_to_split) # Grab the new starting hash key. # This math is straight out of the AWS Docs. Blame them if it breaks. starting_hash_key = shard_to_split.hash_key_range.starting_hash_key.to_i ending_hash_key = shard_to_split.hash_key_range.ending_hash_key.to_i ( (starting_hash_key + ending_hash_key) / 2 ).to_s end def split_shard(kinesis_client, shard_to_split, stream_name) new_starting_hash_key = calculate_new_hash_key(shard_to_split) kinesis_client.split_shard(stream_name: stream_name, shard_to_split: shard_to_split.shard_id, new_starting_hash_key: new_starting_hash_key) loop do described = kinesis_client.describe_stream(stream_name: stream_name) break if described.stream_description.stream_status == 'ACTIVE' sleep 1 end end def merge_shard(kinesis_client, shard_to_merge, stream_name) kinesis_client.merge_shards( stream_name: stream_name, shard_to_merge: shard_to_merge[:lower_hash].shard_id, adjacent_shard_to_merge: shard_to_merge[:higher_hash].shard_id ) loop do described = kinesis_client.describe_stream(stream_name: stream_name) break if described.stream_description.stream_status == 'ACTIVE' sleep 1 end end def perform_shard_scale(stream, use_assume_role, assume_role_creds, scale_get, scale_put, scale_puts, metrics_to_grab, metric_results, scaling_up_config, scaling_down_config) metrics_to_grab += ['IncomingBytes', 'IncomingRecords'] if scale_get metrics_to_grab += ['OutgoingBytes', 'OutgoingRecords'] if scale_put || scale_puts if metrics_to_grab.empty? $notifier.ping "Stream #{stream['name']} has no metrics configured :sadthethings:, Skipping." unless !$notifier return end kinesis_client = nil if use_assume_role kinesis_client = Aws::Kinesis::Client.new( region: stream['region'], credentials: assume_role_creds ) else kinesis_client = Aws::Kinesis::Client.new region: stream['region'] end begin stream_described = kinesis_client.describe_stream( stream_name: stream['name'] ) rescue Aws::Errors::ServiceError return end if stream_described.stream_description.stream_status != 'ACTIVE' $notifier.ping "Stream #{stream['name']} is currently in state: `#{stream_described.stream_description.stream_status}` which is not active, Skipping." unless !$notifier return end stream_shards = get_open_shards(stream_described.stream_description.shards) shards_we_can_split = stream_shards.select do |s| !child_shard?(stream_shards, s[:shard_id]) end if shards_we_can_split.empty? $notifier.ping "Stream #{stream['name']} currently has no open shards to scale up. This should never ever happen. Something is seriously wrong." unless !$notifier return end # Grab Each Metric from cloudwatch cloudwatch_client = nil if use_assume_role cloudwatch_client = Aws::CloudWatch::Client.new( region: stream['region'], credentials: assume_role_creds ) else cloudwatch_client = Aws::CloudWatch::Client.new( region: stream['region'] ) end # Only grab the metrics for the last hour current_time = Time.now.to_i # Respect Cloudwatch Data Limits last_time = current_time - 1440 stream_shards.each do |shard| metrics_to_grab.each do |metric| metric_results << { shard: shard, metric_results: cloudwatch_client.get_metric_statistics( namespace: 'AWS/Kinesis', metric_name: metric, dimensions: [{ name: 'StreamName', value: stream['name'] }, { name: 'ShardID', value: shard[:shard_id] }], start_time: last_time, end_time: current_time, period: 60, statistics: ['Sum'] ) } end end per_shard_votes = {} metric_results.each do |metric_result| metric_shard = metric_result[:shard] votes = per_shard_votes[metric_shard[:shard_id]] if votes.nil? votes = [] end frd_metric_result = metric_result[:metric_results] total = 0 is_bytes = item_in_array(frd_metric_result.label, ['IncomingBytes', 'OutgoingBytes']) frd_metric_result.datapoints.each do |datapoint| total += datapoint.sum end avg = total / 1440 utilization_percentage = 0 if is_bytes utilization_percentage = (avg / $MAX_PER_SHARD_BYTES) * 100 else utilization_percentage = (avg / $MAX_PER_SHARD_RECORDS) * 100 end if utilization_percentage >= scaling_up_config['thresholdPct'] votes << 'scale_up' elsif utilization_percentage <= scaling_down_config['thresholdPct'] votes << 'scale_down' else votes << 'scale_same' end per_shard_votes[metric_shard[:shard_id]] = votes end per_shard_results = {} per_shard_votes.each do |shard_id, votes| per_shard_results[shard_id] = votes.group_by { |i| i } .max { |x, y| x[1].length <=> y[1].length }[0] end non_busy_shards = [] per_shard_results.each do |shard_id, we_should| if we_should == 'scale_up' if shards_we_can_split.include?(shard_id) if (1 + stream_shards.length) > stream['maxShards'] $notifier.ping "We want to scale the shard: #{shard_id}, but it's at capcity!" unless !$notifier return end split_shard(kinesis_client, shard_id, stream['name']) $notifier.ping "We split the following shard for the Stream: #{stream['name']}:\n `#{shard_id}`" unless !$notifier end $notifier.ping "We merged #{shards_to_merge.length} shard(s) for the Stream: #{stream['name']}." unless !$notifier elsif we_should == 'scale_same' $notifier.ping "Shard #{shard_id} is just right. :just_right:" unless !$notifier else non_busy_shards << shard_id end end if !non_busy_shards.empty? $notifier.ping "#{non_busy_shards.length} shards are bored for: #{stream['name']}." unless !$notifier end end def perform_stream_scale(stream, use_assume_role, assume_role_creds, scale_get, scale_put, scale_puts, metrics_to_grab, metric_results, scaling_up_config, scaling_down_config) metrics_to_grab += ['GetRecords.Bytes', 'GetRecords.Records'] if scale_get metrics_to_grab += ['PutRecord.Bytes', 'IncomingRecords'] if scale_put metrics_to_grab += ['PutRecords.Bytes', 'PutRecords.Records'] if scale_puts if !metrics_to_grab.empty? # Only grab the metrics for the last hour current_time = Time.now.to_i # Respect Cloudwatch Data Limits last_time = current_time - 1440 # Grab Each Metric from cloudwatch cloudwatch_client = nil if use_assume_role cloudwatch_client = Aws::CloudWatch::Client.new( region: stream['region'], credentials: assume_role_creds ) else cloudwatch_client = Aws::CloudWatch::Client.new( region: stream['region'] ) end metrics_to_grab.each do |metric| metric_results << cloudwatch_client.get_metric_statistics( namespace: 'AWS/Kinesis', metric_name: metric, dimensions: [{ name: 'StreamName', value: stream['name'] }], start_time: last_time, end_time: current_time, period: 60, statistics: ['Sum'] ) end else $notifier.ping "Stream #{stream['name']} has no metrics configured :sadthethings:, Skipping." unless !$notifier return end kinesis_client = nil if use_assume_role kinesis_client = Aws::Kinesis::Client.new( region: stream['region'], credentials: assume_role_creds ) else kinesis_client = Aws::Kinesis::Client.new region: stream['region'] end # Describe the Kinesis Stream to get a list of shards, and their info. begin stream_described = kinesis_client.describe_stream( stream_name: stream['name'] ) rescue Aws::Errors::ServiceError return end stream_shards = get_open_shards(stream_described.stream_description.shards) shards_we_can_split = stream_shards.select do |s| !child_shard?(stream_shards, s[:shard_id]) end if stream_described.stream_description.stream_status != 'ACTIVE' $notifier.ping "Stream #{stream['name']} is currently in state: `#{stream_described.stream_description.stream_status}` which is not active, Skipping." unless !$notifier return end if shards_we_can_split.empty? # This can only happen if someone manually splits a stream, # and then messes with the parent ids. $notifier.ping "Stream #{stream['name']} currently has no open shards to scale up. This should never ever happen. Something is seriously wrong." unless !$notifier return end scale_votes = [] # Grab the maximum bytes/records our stream can handle. max_bytes = $MAX_PER_SHARD_BYTES * stream_shards.length max_records = $MAX_PER_SHARD_RECORDS * stream_shards.length # The way this works is each metric gets a vote of whether it # needs more resources, less resources, or is okay where it's at. # Whichever gets the most votes wins. metric_results.each do |result| total = 0 is_bytes = item_in_array(result.label, ['GetRecords.Bytes', 'PutRecord.Bytes', 'PutRecords.Bytes']) result.datapoints.each do |datapoint| total += datapoint.sum end avg = total / 1440 utilization_percentage = 0 # Utilization Percentage is exactly what it sounds like. # How much of this metric are we using. if is_bytes utilization_percentage = (avg / max_bytes) * 100 else utilization_percentage = (avg / max_records) * 100 end if utilization_percentage >= scaling_up_config['thresholdPct'] scale_votes << 'scale_up' elsif utilization_percentage <= scaling_down_config['thresholdPct'] scale_votes << 'scale_down' else scale_votes << 'scale_same' end end if scale_votes == [] $notifier.ping "That's weird. Stream: #{stream['name']} had no scaling votes, Skipping." unless !$notifier return end we_should = scale_votes.group_by { |i| i } .max { |x, y| x[1].length <=> y[1].length }[0] if we_should == 'scale_up' if (scaling_up_config['rate'] + stream_shards.length) > stream['maxShards'] $notifier.ping "We want to scale: #{stream['name']}, but it's at capcity!" unless !$notifier return end shards_to_split = shards_we_can_split.sample(scaling_up_config['rate']) begin shards_to_split.each do |shard_to_split| split_shard(kinesis_client, shard_to_split, stream['name']) end rescue Aws::Errors::ServiceError return end $notifier.ping "We split the following shards for the Stream: #{stream['name']}:\n ```#{shards_to_split.join(', ')}```" unless !$notifier elsif we_should == 'scale_down' return if stream_shards.length == 1 if (stream_shards.length - scaling_down_config['rate']) < stream['minShards'] $notifier.ping "We want to turndown: #{stream['name']}, but your config says not to." unless !$notifier return end adjacent_shards = get_adjacent_shards(stream_shards) # If your adjacent shards aren't yet open, or other stuff is going on it's possible that you # can't merge any shards. This sucks, but from reading it's a decently common occurence. if adjacent_shards.empty? $notifier.ping "We want to merge shards for the Stream: #{stream['name']}, but it has no adjacent shards. :tear:." unless !$notifier unless !$notifier return end shards_to_merge = adjacent_shards.sample(scaling_down_config['rate']) begin shards_to_merge.each do |to_merge| merge_shard(kinesis_client, to_merge, stream['name']) end rescue Aws::Errors::ServiceError return end $notifier.ping "We merged #{shards_to_merge.length} shard(s) for the Stream: #{stream['name']}." unless !$notifier elsif we_should == 'scale_same' $notifier.ping "Stream #{stream['name']} is just right :just_right:." unless !$notifier else $notifier.ping "Stream #{stream['name']} doesn't know how to scale: `#{we_should}`. :sadthethings:." unless !$notifier end end loop do accounts = $config['accounts'] $config['streams'].each { |stream| scaling_config = stream['scalingConfig'] scaling_up_config = scaling_config['up'] scaling_down_config = scaling_config['down'] scale_get = item_in_array(stream['scaleOn'], ['GET', 'ALL']) scale_put = item_in_array(stream['scaleOn'], ['PUT', 'BOTH_PUTS', 'ALL']) scale_puts = item_in_array(stream['scaleOn'], ['PUTS', 'BOTH_PUTS', 'ALL']) account_to_use = stream['account'] account_config = accounts[account_to_use] use_assume_role = false assume_role_creds = nil if account_config['assume_role'] use_assume_role = true assume_role_creds = Aws::AssumeRoleCredentials.new( client: Aws::STS::Client.new, role_arn: account_config['role_arn'], role_session_name: account_config['role_session_name'] ) end if stream['shardLevelScale'] perform_shard_scale(stream, use_assume_role, assume_role_creds, scale_get, scale_put, scale_puts, [], [], scaling_up_config, scaling_down_config) else perform_stream_scale(stream, use_assume_role, assume_role_creds, scale_get, scale_put, scale_puts, [], [], scaling_up_config, scaling_down_config) end } sleep $config['cloudwatchRefreshTime'] end
# frozen_string_literal: true # # Copyright (C) 2017-2918 Harald Sitter <sitter@kde.org> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) version 3, or any # later version accepted by the membership of KDE e.V. (or its # successor approved by the membership of KDE e.V.), which shall # act as a proxy defined in Section 6 of version 3 of the license. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library. If not, see <http://www.gnu.org/licenses/>. class Desktopfile attr_reader :path attr_reader :lines # NB: the data needs to be read here. we move out of the context of the # temporary file after construction!!! def initialize(path) @path = path @lines = File.read(path).split($/) end def dbus? lines.any? do |x| x.start_with?('X-DBUS-ServiceName=') || x.match?(/X-DBUS-StartupType=(Multi|Unique)/) end end def service_name return nil unless dbus? dbus_line = lines.find { |x| x.start_with?('X-DBUS-ServiceName=') } return dbus_line.split('=', 2)[-1] if dbus_line # NB: technically the name is assumed to be org.kde.binaryname. However, # due to wayland the desktop file should be named thusly anyway. # Technically wayland may also be set programatically though, so # this assumption may not always be true and we indeed need to resolve # org.kde.binaryname, which is tricky because that entails parsing Exec=. name = File.basename(path, '.desktop') raise unless name.start_with?('org.kde.') name end end
class RenamechargeidfromWorkerContract < ActiveRecord::Migration def change rename_column(:worker_contracts, :charge_id, :article_id) end end
# frozen_string_literal: true class PassangerTrain < Train attr_reader :number attr_accessor :wagons, :current_route, :current_station, :type def initialize(number) @number = number validate! @wagons = [] @current_route = [] @current_station = [] @type = 'Пассажирский' end end
class Implementation < ActiveRecord::Base self.table_name = 'RL' attr_accessible :S, :N, :DAT, :DN, :KOD, :NAIM, :SUM, :SUMM, :SUMY, :P, :AWT, :s, :n, :dat, :dn, :kod, :naim, :sum, :summ, :sumy, :p, :awt #field :KOD #field :NAIM #field :SUM #field :SUMM #field :SUMY #field :DAT after_update :sum_cor after_update :summing_sum after_update :summing_summ after_update :summing_sumy scope :year_eq, lambda{ |year| where("YEAR(DAT) = ?", year.to_i) } scope :month_eq, lambda{ |month| where("MONTH(DAT) = ?", month.to_i) } scope :day_eq, lambda{ |day| where("DAY(DAT) = ?", day.to_i) } search_methods :year_eq search_methods :month_eq search_methods :day_eq def sum_cor summ = Implementation.where("YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) <= ? AND N = ?",self.DAT.year, self.DAT.month, self.DAT.day, self.N).sum("SUM") sumy = Implementation.where("YEAR(DAT) = ? AND DAY(DAT) <= ? AND N = ?",self.DAT.year, self.DAT.day, self.N).sum("SUM") Implementation.where("YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ? AND N = ?",self.DAT.to_date.year, self.DAT.to_date.month, self.DAT.to_date.day, self.N).update_all(:SUMY => sumy, :SUMM => summ ) end def summing_sum ost_kam = Implementation.where("YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ? AND N IN (17,18)", self.DAT.to_date.year, self.DAT.to_date.month, self.DAT.to_date.day).sum("SUM") ost_kam_summ = Implementation.where("YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ? AND N IN (17,18)", self.DAT.to_date.year, self.DAT.to_date.month, self.DAT.to_date.day).sum("SUMM") ost_kam_sumy = Implementation.where("YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ? AND N IN (17,18)", self.DAT.to_date.year, self.DAT.to_date.month, self.DAT.to_date.day).sum("SUMY") Implementation.where("YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ? AND N = 16", self.DAT.to_date.year, self.DAT.to_date.month, self.DAT.to_date.day).update_all( :SUMY => ost_kam_sumy, :SUM => ost_kam, :SUMM => ost_kam_summ ) end def summing_summ rel_mokshan = Implementation.where("YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ? AND N IN (3, 4)", self.DAT.to_date.year, self.DAT.to_date.month, self.DAT.to_date.day).sum("SUM") rel_mokshan_summ = Implementation.where("YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ? AND N IN (3, 4)", self.DAT.to_date.year, self.DAT.to_date.month, self.DAT.to_date.day).sum("SUMM") rel_mokshan_sumy = Implementation.where("YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ? AND N IN (3, 4)", self.DAT.to_date.year, self.DAT.to_date.month, self.DAT.to_date.day).sum("SUMY") Implementation.where("YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ? AND N = 9", self.DAT.to_date.year, self.DAT.to_date.month, self.DAT.to_date.day).update_all( :SUMY => rel_mokshan_sumy, :SUM => rel_mokshan, :SUMM => rel_mokshan_summ) end def summing_sumy rel_all = Implementation.where("YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ? AND N IN (2, 3, 4, 5)",self.DAT.to_date.year, self.DAT.to_date.month, self.DAT.to_date.day).sum("SUM") rel_all_summ = Implementation.where("YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ? AND N IN (2, 3, 4, 5)",self.DAT.to_date.year, self.DAT.to_date.month, self.DAT.to_date.day).sum("SUMM") rel_all_sumy = Implementation.where("YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ? AND N IN (2, 3, 4, 5)",self.DAT.to_date.year, self.DAT.to_date.month, self.DAT.to_date.day).sum("SUMY") Implementation.where("YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ? AND N = 1", self.DAT.to_date.year, self.DAT.to_date.month, self.DAT.to_date.day).update_all( :SUMY => rel_all_sumy, :SUM => rel_all, :SUMM => rel_all_summ) end end
class AppointmentsController < ApplicationController # GET /appointments # GET /appointments.xml def index @search = default_search(Appointment) @appointments = @search.relation.includes(:visit, :series => [:series_metainfo, {:series_log_items => :series_scenario}]).page(params[:page]) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @appointments } end end # GET /appointments/1 # GET /appointments/1.xml def show @appointment = Appointment.find(params[:id]) # @series = @appointment.series.includes(:series_metainfo, :series_log_item => {:series_scenario => :functional_set}).order("`functional_sets`.`setname` ASC, `position` ASC") # => {:series_scenario => :functional_set})#.order("functional_sets.setname, series.position") @series = @appointment.series #.order("`series_set_id` ASC, `position` ASC")#.with_sequence_set #.with_pulses_or_tasks.includes(:series_metainfo, :series_log_items => {:series_scenario => :functional_set}).order("`pfile` ASC, `position` ASC") # => {:series_scenario => :functional_set})#.order("functional_sets.setname, series.position") # logger.info @series = @appointment.series.joins("LEFT OUTER JOIN `series_log_items` ON `series_log_items`.`series_id` = `series`.`id`") #LEFT OUTER JOIN `series_scenarios` ON `series_scenarios`.`id` = `series_log_items`.`series_scenario_id` LEFT OUTER JOIN `functional_sets` ON `functional_sets`.`id` = `series_scenarios`.`functional_set_id`").order("functional_sets.setname, series.order") # logger.info @series.to_sql # logger.info @series.count respond_to do |format| format.html # show.html.erb format.xml { render :xml => @appointment } end end # GET /appointments/new # GET /appointments/new.xml def new @appointment = Appointment.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @appointment } end end # GET /appointments/1/edit def edit @appointment = Appointment.find(params[:id]) end # POST /appointments # POST /appointments.xml def create @appointment = Appointment.new(params[:appointment]) respond_to do |format| if @appointment.save format.html { redirect_to(@appointment, :notice => 'Appointment was successfully created.') } format.xml { render :xml => @appointment, :status => :created, :location => @appointment } else format.html { render :action => "new" } format.xml { render :xml => @appointment.errors, :status => :unprocessable_entity } end end end # PUT /appointments/1 # PUT /appointments/1.xml def update @appointment = Appointment.find(params[:id]) respond_to do |format| if @appointment.update_attributes(params[:appointment]) format.html { redirect_to(@appointment, :notice => 'Appointment was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @appointment.errors, :status => :unprocessable_entity } end end end # DELETE /appointments/1 # DELETE /appointments/1.xml def destroy @appointment = Appointment.find(params[:id]) @appointment.destroy respond_to do |format| format.html { redirect_to(appointments_url) } format.xml { head :ok } end end end
require 'spec_helper' describe PagesController do render_views before(:each) do @base_title = "Ruby on Rails Tutorial Sample App" end describe "GET 'home'" do it "should have the title 'Home'" do visit '/' page.should have_selector("title", :contents => "#{@base_title} | Home") end it "should have the h1 'Hier wird scharf geritten!'" do visit '/' page.should have_selector('h1', :text => 'Hier wird scharf geritten!') end end describe "GET 'contact'" do it "returns http success" do get 'contact' response.should be_success end it "should have the right title" do visit '/contact' page.should have_selector("title", :contents => "#{@base_title} | Contact") end end describe "GET 'about'" do it "returns http success" do get 'about' response.should be_success end it "should have the right title" do visit '/about' page.should have_selector("title", :contents => "#{@base_title} | About") end end describe "GET 'help'" do it "returns http success" do get 'help' response.should be_success end it "should have the right title" do visit '/help' page.should have_selector("title", :contents => "#{@base_title} | Help") end end end
#encoding: utf-8 require 'spec_helper' describe "Bancos" do before do @user = Factory(:user) integration_sign_in(@user) @etiqueta = "Banco Galicia" end it "link de acceso" do visit home_path response.should have_selector("a", :href => bancos_path, :content => "Bancos") click_link "Bancos" response.should render_template('bancos/index') end describe "Asociación con empresa" do before do @empresa1 = Empresa.create!(:detalle => "TAESA") @empresa2 = Empresa.create!(:detalle => "Chantaco") @empresa3 = Empresa.create!(:detalle => "SuperFito") @empresas = [@empresa1, @empresa2, @empresa3] visit new_banco_path end it "debe haber la misma cantidad de checkbox como empresas" do response.should have_selector("input", :type => "checkbox", :count => @empresas.length) end it "debe tener los nombres correspondientes" do response.should have_selector("label", :content => "#{@empresa1[:detalle]}") response.should have_selector("label", :content => "#{@empresa2[:detalle]}") response.should have_selector("label", :content => "#{@empresa3[:detalle]}") end it "debe tener el identificador correspondiente" do @empresas.each do |empresa| response.should have_selector("input#empresa_#{empresa.id}") end end it "deben listarse solo las empresas activas" do @empresa2.anular @empresa2.save! @empresa2.reload visit new_banco_path response.should have_selector("label", :content => "#{@empresa1[:detalle]}") response.should_not have_selector("label", :content => "#{@empresa2[:detalle]}") response.should have_selector("label", :content => "#{@empresa3[:detalle]}") end it "alta de banco sin detalle" do lambda do visit new_banco_path fill_in :banco_detalle, :with => "" click_button response.should render_template('bancos/new') response.should have_selector("div#error_explanation") end.should_not change(Banco, :count) end it "alta de banco sin empresas" do lambda do visit new_banco_path fill_in :banco_detalle, :with => @etiqueta click_button response.should render_template('bancos/show') response.should have_selector("p", :content => @etiqueta) end.should change(Banco, :count).by(1) end describe "comprobación de la asociación" do it "alta de banco con empresas" do lambda do visit new_banco_path fill_in :banco_detalle, :with => @etiqueta check @empresa1.detalle check @empresa3.detalle click_button response.should render_template('bancos/show') response.should have_selector("p", :content => @etiqueta) end.should change(Banco, :count).by(1) end it "Dar de alta una cuenta representada por un saldo" do lambda do visit new_banco_path fill_in :banco_detalle, :with => @etiqueta check @empresa1.detalle check @empresa3.detalle click_button end.should change(SaldoBancario, :count).by(2) end end end describe "vista edición" do before do @banco = Banco.create!(:detalle => @etiqueta) @empresa1 = Empresa.create!(:detalle => "TAESA") @empresa2 = Empresa.create!(:detalle => "Chantaco") @empresa3 = Empresa.create!(:detalle => "SuperFito") @empresas = [@empresa1, @empresa2, @empresa3] end it "debe haber la misma cantidad de checkbox como empresas" do visit edit_banco_path(@banco) response.should have_selector("input", :type => "checkbox", :count => @empresas.length) end it "debe tener los nombres correspondientes" do visit edit_banco_path(@banco) response.should have_selector("label", :content => "#{@empresa1[:detalle]}") response.should have_selector("label", :content => "#{@empresa2[:detalle]}") response.should have_selector("label", :content => "#{@empresa3[:detalle]}") end it "debe tener el identificador correspondiente" do visit edit_banco_path(@banco) @empresas.each do |empresa| response.should have_selector("input#empresa_#{empresa.id}") end end it "editación de banco sin detalle" do lambda do visit edit_banco_path(@banco) fill_in :banco_detalle, :with => "" click_button response.should render_template('bancos/edit') response.should have_selector("div#error_explanation") end.should_not change(Banco, :count) end it "deben listarse solo las empresas activas" do @empresa2.anular @empresa2.save! @empresa2.reload visit edit_banco_path(@banco) response.should have_selector("label", :content => "#{@empresa1[:detalle]}") response.should_not have_selector("label", :content => "#{@empresa2[:detalle]}") response.should have_selector("label", :content => "#{@empresa3[:detalle]}") end it "deben listarse solo las empresas activas no asignadas" do @empresa2.anular @empresa2.save! @empresa2.reload @banco.saldos_bancario.create!(:empresa_id => @empresa3.id, :user_id => @user, :valor => 4) visit edit_banco_path(@banco) response.should have_selector("label", :content => "#{@empresa1[:detalle]}") response.should_not have_selector("label", :content => "#{@empresa2[:detalle]}") response.should_not have_selector("input#empresa_#{@empresa3.id}") end it "Dar de alta un un saldo bancario" do lambda do visit edit_banco_path(@banco) check @empresa1.detalle check @empresa3.detalle click_button end.should change(SaldoBancario, :count).by(2) end it "debe estar asociado con las empresas seleccionadas" do visit new_banco_path fill_in :banco_detalle, :with => "Banco Galicia" check @empresa1.detalle check @empresa3.detalle click_button @banco = assigns(:banco) visit edit_banco_path(@banco) response.should have_selector("th", :content => "Cuentas activas") response.should have_selector("td", :content => "#{@empresa1[:detalle]}") response.should have_selector("td", :content => "#{@empresa3[:detalle]}") end it "debe mostrar los links de deshabilitar las empresas" do @banco = Banco.create!(:detalle => @etiqueta) @sb = @banco.saldos_bancario.create!(:empresa_id => @empresa1.id, :user_id => @user, :valor => 4) visit edit_banco_path(@banco) response.should have_selector("a", :href => saldo_bancario_path(@sb), :content => "Deshabilitar") click_link "Deshabilitar" response.should render_template('bancos/edit') end it "debe mostrar los links de habilitar las empresas" do @banco = Banco.create!(:detalle => @etiqueta) @sb = @banco.saldos_bancario.create!(:empresa_id => @empresa1.id, :user_id => @user, :valor => 4) @sb.anular @sb.save! visit edit_banco_path(@banco) response.should have_selector("a", :href => activar_saldo_bancario_path(@sb), :content => "Habilitar") click_link "Habilitar" response.should render_template('bancos/edit') end it "no debe mostrar ningun saldo bancario, si no se encuentra asociado" do @banco = Banco.create!(:detalle => @etiqueta) visit edit_banco_path(@banco) response.should_not have_selector("th", :content => "Cuentas activas") response.should_not have_selector("th", :content => "Cuentas deshabilitadas") response.should_not have_selector("a", :content => "Deshabilitar") response.should_not have_selector("a", :content => "Habilitar") end it "no debe mostrar las cuentas activas" do @banco = Banco.create!(:detalle => @etiqueta) @sb = @banco.saldos_bancario.create!(:empresa_id => @empresa1.id, :user_id => @user, :valor => 4) @sb.anular @sb.save! visit edit_banco_path(@banco) response.should_not have_selector("th", :content => "Cuentas activas") response.should_not have_selector("a", :content => "Deshabilitar") end it "no debe mostrar las cuentas deshabilitadas" do @banco = Banco.create!(:detalle => @etiqueta) @sb = @banco.saldos_bancario.create!(:empresa_id => @empresa1.id, :user_id => @user, :valor => 4) visit edit_banco_path(@banco) response.should_not have_selector("th", :content => "Cuentas deshabilitadas") response.should_not have_selector("a", :content => "Habilitar") end end describe "vista detalle" do it "debe mostrarse el detalle del banco" do @banco = Banco.create!(:detalle => @etiqueta) visit banco_path(@banco) response.should have_selector("p", :content => "#{@banco[:detalle]}") end it "debe mostrar solo las empresas asociadas" do @empresa1 = Empresa.create!(:detalle => "TAESA") @empresa2 = Empresa.create!(:detalle => "Chantaco") @empresa3 = Empresa.create!(:detalle => "SuperFito") @empresas = [@empresa1, @empresa2, @empresa3] @empresa4 = Empresa.create!(:detalle => "GonzaEmpresa") @banco = Banco.create!(:detalle => @etiqueta) @empresas.each { |empresa| @banco.saldos_bancario.create!(:empresa_id => empresa.id, :user_id => @user, :valor => 4) } visit banco_path(@banco) response.should have_selector("ul") do |n| n.should have_selector("li", :content => "#{@empresa1[:detalle]}") n.should have_selector("li", :content => "#{@empresa2[:detalle]}") n.should have_selector("li", :content => "#{@empresa3[:detalle]}") n.should_not have_selector("li", :content => "#{@empresa4[:detalle]}") end end it "no debe mostrar ninguna empresa, si no esta asociado" do @empresa1 = Empresa.create!(:detalle => "TAESA") @empresa2 = Empresa.create!(:detalle => "Chantaco") @empresa3 = Empresa.create!(:detalle => "SuperFito") @empresas = [@empresa1, @empresa2, @empresa3] @empresa4 = Empresa.create!(:detalle => "GonzaEmpresa") @banco = Banco.create!(:detalle => @etiqueta) visit banco_path(@banco) response.should have_selector("ul") do |n| n.should_not have_selector("li", :content => "#{@empresa1[:detalle]}") n.should_not have_selector("li", :content => "#{@empresa2[:detalle]}") n.should_not have_selector("li", :content => "#{@empresa3[:detalle]}") n.should_not have_selector("li", :content => "#{@empresa4[:detalle]}") end end end end