text
stringlengths
10
2.61M
class AddFlagImageIdToRefineryLocations < ActiveRecord::Migration def change add_column :refinery_locations, :flag_image_id, :integer end end
class ClientMailer < ActionMailer::Base default from: "mirafloristeresina@gmail.com" def thanks_registration(client) @client = client @url = "http://mirafloris.com/login" mail(:to => client.email, :subject => "#{client.first_name} Obrigado por comecar seu futuro!") end end
class AddCompanyNameToUsersTable < ActiveRecord::Migration[5.2] def change change_table :users do |t| t.string :company_name, index: true t.string :full_name, index: true t.string :phone end end end
# -*- coding: utf-8 -*- require 'sinatra' get '/' do puts 'GET "/"' end post '/' do puts 'POST "/"' end put '/' do puts 'PUT "/"' end patch '/' do puts 'PATCH "/"' end delete '/' do puts 'DELETE "/"' end options '/' do puts 'OPTIONS "/"' end link '/' do puts 'LINK "/"' end unlink '/' do puts 'UNLINK "/"' end get '/foo' do # 不能匹配 GET /foo/ puts 'GET "/foo"' end get '/hello/:name' do # 匹配 GET /hello/sapeu 和 GET /hello/paul # params[:name] 是参数sapeu 和paul "Hello #{params[:name]}" end get '/yoyo/:name' do |n| # 匹配 GET /hello/sapeu 和 GET /hello/paul # params['name'] 是 sapeu 和 paul # n stores params['name'] "Yo! Yo! #{n}" end get '/say/*/to/*' do # matches /say/hello/to/world p params params['splat'] # => ['hello', 'world'] end get '/download/*.*' do # matches /download/path/to/file.xml p params params[:splat] # => ['path/to/file', 'xml'] end get '/new_download/*.*' do |path, ext| [path, ext] # => ['path/to/file', 'xml'] end get /\/match\_hello\/([\w]+)/ do p params "Match: Hello, #{params[:captures].first}!" end get %r{/new_match_hello/([\w]+)} do |c| p params "Match: Hello, #{c}!" end get '/posts' do # matches GET /posts?title=foo&author=bar p params title = params[:title] author = params['author'] "#{title}-#{author}" end get '\A/new\_posts\z', mustermann_opts: { type: :regexp, check_anchors: false } do # matches /new_posts exactly, with explicit anchoring "If you match an anchored pattern clap your hands!" 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 rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) user = User.new user.id = 1 user.name = 'admin' user.password = '123456' user.password_confirmation = '123456' user.email = 'admin@tvshows.com' user.admin = true user.save! user = User.new user.id = 2 user.name = 'benja' user.password = '123456' user.password_confirmation = '123456' user.email = 'benja@tvshows.com' user.admin = false user.save! user = User.new user.id = 3 user.name = 'ale' user.password = '123456' user.password_confirmation = '123456' user.email = 'ale@tvshows.com' user.admin = false user.save! user = User.new user.id = 4 user.name = 'santi' user.password = '123456' user.password_confirmation = '123456' user.email = 'santi@tvshows.com' user.admin = false user.save! for i in 0..15 show = TvShow.new show.name =Faker::Book.title #por alguna razon el nombre queda como nil... show.genre = Faker::Book.genre show.country = Faker::Address.country show.language = Faker::Lorem.word show.actors = Faker::Name.name show.director = Faker::Name.name show.seasons = Faker::Number.between(1,15) show.user_id = 1 show.save! end for i in 1..3 for j in 2..4 show = TvShow.new show.name =Faker::Book.title #por alguna razon el nombre queda como nil... show.genre = Faker::Book.genre show.country = Faker::Address.country show.language = Faker::Lorem.word show.actors = Faker::Name.name show.director = Faker::Name.name show.seasons = Faker::Number.between(1,15) show.user_id = j show.save! end end
json.array!(@categorizations) do |categorization| json.extract! categorization, :id, :post_id, :category_id json.url categorization_url(categorization, format: :json) end
require 'digest/md5' require 'open-uri' require 'fileutils' class Radio < ActiveRecord::Base belongs_to :radio_station def self.create_or_update_with_radios(radios) radios.each do |radio| create_or_update_with_radio(radio) end end def self.create_or_update_with_radio(radio) if radio.blank? or radio[:name].blank? or radio[:description].blank? or radio[:url].blank? or radio[:image_url].blank? or radio[:published_at].blank? or radio[:radio_station].blank? return end Radio.find_or_initialize_by(name: radio[:name], published_at: radio[:published_at]).update_attributes( name: radio[:name], description: radio[:description], url: radio[:url], image_url: download_image_if_needed(radio[:image_url]), published_at: radio[:published_at], radio_station: radio[:radio_station], ) end def self.download_image_if_needed(image_url) md5 = Digest::MD5.new.update(image_url).to_s public_dir = "#{Rails.root}/public" path = "/uploads/#{md5.slice(0, 2)}/#{md5}" return path if File.exist?(public_dir + path) begin FileUtils.mkdir_p(File.dirname(public_dir + path)) IO.copy_stream(open(image_url), public_dir + path) path rescue Exception => e image_url end end def self.all_to_json(num) num = num.to_i - 1 json = [] for i in (num * 7)..(num * 7 + 6) datetime = DateTime.now - i.day radios = Radio.includes(:radio_station).references(:radio_stations).order(published_at: :desc) .where('published_at BETWEEN ? AND ?', datetime.beginning_of_day, datetime.end_of_day).all.map(&:to_json) next if radios.length == 0 json << { date: datetime.beginning_of_day.iso8601, radios: radios } end json end def to_json if self.radio_station.id == 3 self.url = self.url.gsub('http://www.onsen.ag/?pid=', 'http://www.onsen.ag/#') end { id: self.id, name: self.name, url: self.url, image_url: "#{Rails.application.config.base_uri}#{self.image_url}", description: self.description, published_at: self.published_at.iso8601, radio_station_id: self.radio_station_id, station: { id: self.radio_station.id, name: self.radio_station.name, url: self.radio_station.url, } } end end
class User < ApplicationRecord has_secure_password has_many :visions has_many :goals has_one :squad has_many :projects end
class Admin::HappeningsController < Admin::BaseController before_action :_set_happening, except: %i[index new create parse_url] def index @happenings = Happening.all end def show; end def new @happening = Happening.new( club_id: params[:club_id] ) render partial: 'form', layout: false end def edit render partial: 'form', layout: false end def edit_recurrence @recurrence_form = RecurrenceForm.new( happening: @happening, ) render partial: 'recurrence_form', layout: false end def update_recurrence @recurrence_form = RecurrenceForm.new( *_recurrence_form_params.merge( happening: @happening, ) ) return if params[:button] == 'preview' update_and_render_or_redirect_in_js( @recurrence_form, _recurrence_form_params, admin_happening_path(@happening), 'recurrence_form', helpers.t_notice_count('successfully_created', Happening, @recurrence_form.take_dates.size), ) end # JS def create @happening = Happening.new( club_id: params[:club_id] ) update_and_render_or_redirect_in_js @happening, _happening_params, ->(happening) { admin_happening_path(happening) } end # JS def update update_and_render_or_redirect_in_js @happening, _happening_params, admin_happening_path(@happening) end def destroy @happening.destroy! redirect_to admin_happenings_path, notice: helpers.t_notice('successfully_deleted', Happening) end def _set_happening @happening = Happening.find params[:id] end def _happening_params params.require(:happening).permit( *Happening::FIELDS, :existing_or_new_venue, venue_attributes: Venue::FIELDS, ) end def _recurrence_form_params params.require(:recurrence_form).permit(*RecurrenceForm::FIELDS) end end
require 'test_helper' class FoosControllerTest < ActionDispatch::IntegrationTest setup do @foo = create(:foo) end test 'should get index' do get foos_url assert_response :success foos = parse_json_response foos.each { |o| assert_equal foo_json(@foo), o } end test 'should create foo' do @foo.name = 'Non unique name' assert_difference('Foo.count') do post foos_url, params: { foo: { name: @foo.name } } end assert_response :success assert_equal foo_json(Foo.last), parse_json_response end test 'should show foo' do get foo_url(@foo) assert_response :success assert_equal foo_json(@foo), parse_json_response end test 'should update foo' do @foo.name = 'another name' patch foo_url(@foo), params: { foo: { name: @foo.name } } assert_response :success updated_foo = Foo.find(@foo.id) @foo.updated_at = updated_foo.updated_at assert_equal foo_json(@foo), parse_json_response end test 'should destroy foo' do assert_difference('Foo.count', -1) do delete foo_url(@foo) end assert_response :success assert_equal foo_json(@foo), parse_json_response end end
class Journey def initialize(name, zone) @journey = {} @name = name @zone = zone end def see_journey @journey end def see_name @name end def see_zone @zone end end
Then(/^user is on Login page$/) do Pages::LoginPage.new.await end And(/^user taps Sign in button$/) do Pages::LoginPage.new.await.tap_sign_in_button end Then(/^successful sign in message is shown$/) do page = Pages::LoginPage.new.await Wait.until(timeout_message: "Successful sign in confirmation message should be shown") { page.sign_in_confirmation == Constants::Login::SIGN_IN_CONFIRMATION } end And(/^(.+) error message is shown$/) do |error_type| ERROR_MESSAGES = { "Empty email and password" => Constants::Errors::EMPTY_CREDENTIALS, "Empty password" => Constants::Errors::EMPTY_PASSWORD, "Empty email" => Constants::Errors::EMPTY_EMAIL, "Invalid email" => Constants::Errors::INVALID_EMAIL, "Incorrect email" => Constants::Errors::INCORRECT_EMAIL, "Incorrect password" => Constants::Errors::INCORRECT_PASSWORD, } page = Pages::LoginPage.new.await expected = ERROR_MESSAGES.fetch(error_type) actual = page.error_message_text Assertions.assert_equal(expected, actual, "Error message is incorrect") end And(/^user enters (.*) email$/) do |email| Pages::LoginPage.new.await.enter_email(email) end And(/^user enters (.*) password$/) do |password| Pages::LoginPage.new.await.enter_password(password) end And(/^user delete email$/) do Pages::LoginPage.new.await.delete_email end
require 'spec_helper' require 'yt/models/asset' describe Yt::Asset do subject(:asset) { Yt::Asset.new data: data } describe '#id' do context 'given fetching a asset returns an id' do let(:data) { {"id"=>"A123456789012345"} } it { expect(asset.id).to eq 'A123456789012345' } end end describe '#type' do context 'given fetching a asset returns an type' do let(:data) { {"type"=>"web"} } it { expect(asset.type).to eq 'web' } end end end
class ShopsController < ApplicationController before_action :authenticate_admin!, except: %i[index show] before_action :set_shop, only: %i[edit update destroy show] before_action :user_can_edit?, only: %i[edit update destroy] def index @shops = Shop.order(updated_at: 'DESC').page(params[:page]).per(SHOP_PER) @shop_count = Shop.all.count end def new @shop = Shop.new end def confirm @shop = Shop.new(shop_params) render :new if @shop.invalid? end def create @shop = Shop.new(shop_params) render :new and return if params[:back] || !@shop.save flash[:notice] = "#{@shop.name}を作成しました" redirect_to shop_path(@shop) end def edit end def update render :edit and return unless @shop.update(shop_params) flash[:notice] = "#{@shop.name}を編集しました" redirect_to shop_path(@shop) end def destroy @shop.destroy flash[:notice] = "#{@shop.name}を削除しました" redirect_to root_path end def show @message = Message.new @item_per = ITME_PER end def my @shops = Shop .where(admin_id: current_admin[:id]) .order(updated_at: 'DESC') .page(params[:page]) .per(SHOP_PER) @shop_count = Shop.where(admin_id: current_admin[:id]).count end private def shop_params shop_params = params .require(:shop) .permit( :name, :prefecture_id, :location, :phone_number, :opening_time, :closing_time, :parking_id, :credit_card_id, :electronic_money_id, :shop_image, :shop_image_cache ) .merge(admin_id: current_admin[:id]) # 全角とハイフンの処理 Shop.phone_number_converter(shop_params) end def set_shop @shop = Shop.find(params[:id]) end def user_can_edit? return redirect_to root_path unless @shop.admin.id == current_admin.id end end
class Series def initialize(numbers) @numbers = numbers.split('').map(&:to_i) end def slices(count) raise ArgumentError if count > @numbers.size @numbers.each_cons(count).to_a end end
class CreateAttachments < ActiveRecord::Migration def up create_table :attachments do |t| t.string 'uuid' t.integer 'business_user_id' t.string 'attachment_type' t.attachment t.timestamps end end def down drop_table :attachments end end
# Copyright (c) 2006, 2007 Ruffdogs Software, Inc. # Authors: Adam Lebsack <adam@holonyx.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License. # # This program 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 General Public License for more details. module Restore::Module::Agent class ObjectLog < ActiveRecord::Base set_table_name 'agent_object_logs' belongs_to :object, :class_name => 'Restore::Module::Agent::Object::Base', :foreign_key => 'object_id' belongs_to :snapshot, :class_name => 'Restore::Snapshot::Base', :foreign_key => 'snapshot_id' belongs_to :target, :class_name => 'Restore::Target::Base', :foreign_key => 'target_id' # serialize :extra, Hash def before_create self.target_id = target.id if target end cattr_accessor :object_handles class << self @@object_handles ||= {} end def storage self.class.object_handles[self.id] ||= snapshot.storage.get_file_handle(object.id.to_s) end # def prune # removed = 0 # begin # storage.unlink # removed = local_size rescue 0 # update_attributes(:pruned => true, :extra => nil, :local_size => 0) # rescue Errno::ENOTEMPTY # # pass silently # rescue => e # logger.info e.to_s # end # snapshot.update_attributes(:local_size => (snapshot.local_size - removed)) # end end end
require 'spec_helper' require_relative '../../lib/kuhsaft/page_tree' require_relative '../../app/models/kuhsaft/page' # TODO: THESE SPECS ONLY WORK WHEN THE FULL SUITE IS RUN. FIX THAT! module Kuhsaft describe PageTree do let(:page_tree) do { '0' => { 'id' => '1', 'children' => { '0' => { 'id' => '2' } } }, '1' => { 'id' => '3' } } end before :each do @page1 = FactoryGirl.create(:page, id: 1, position: 10) @page2 = FactoryGirl.create(:page, id: 2, position: 10) @page3 = FactoryGirl.create(:page, id: 3, position: 10) end describe 'update' do it 'sets the correct position of the root nodes' do PageTree.update(page_tree) expect(@page1.reload.position).to eq(0) expect(@page2.reload.position).to eq(0) expect(@page3.reload.position).to eq(1) end it 'sets the correct parent attribute for the nodes' do PageTree.update(page_tree) expect(@page1.reload.parent_id).to be_nil expect(@page2.reload.parent_id).to eq(1) expect(@page3.reload.parent_id).to be nil end end end end
class CsvFilePresenter < Presenter delegate :contents, :id, to: :model def to_hash { :id => id, :contents => File.readlines(contents.path).map{ |line| line.gsub(/\n$/, '') }[0..99] } rescue => e model.errors.add(:contents, :FILE_INVALID) raise ActiveRecord::RecordInvalid.new(model) end def complete_json? true end end
require 'MiqVm/MiqVm' require 'disk/modules/AzureBlobDisk' require 'disk/modules/AzureManagedDisk' require 'disk/modules/miq_disk_cache' class MiqAzureVm < MiqVm def initialize(azure_handle, args) @azure_handle = azure_handle @uri = nil @disk_name = nil @resource_group = args[:resource_group] @managed_image = args[:managed_image] raise ArgumentError, "MiqAzureVm: missing required arg :name" unless (@name = args[:name]) if args[:image_uri] @uri = args[:image_uri] elsif args[:managed_image] @disk_name = args[:managed_image] elsif args[:resource_group] && args[:name] vm_obj = vm_svc.get(@name, @resource_group) os_disk = vm_obj.properties.storage_profile.os_disk if vm_obj.managed_disk? # # Use the Smartstate SNAPSHOT Added by the Provider # raise ArgumentError, "MiqAzureVm: missing required arg :snapshot for Managed Disk" unless (@disk_name = args[:snapshot]) else # # Non-Managed Disk Snapshot handling # @uri = os_disk.vhd.uri @uri << "?snapshot=#{args[:snapshot]}" if args[:snapshot] end else raise ArgumentError, "MiqAzureVm: missing required args: :image_uri or :resource_group" end super(getCfg) end def getCfg cfg_hash = {} cfg_hash['displayname'] = @name file_name = @uri ? @uri : @disk_name $log.debug("MiqAzureVm#getCfg: disk = #{file_name}") tag = "scsi0:0" cfg_hash["#{tag}.present"] = "true" cfg_hash["#{tag}.devicetype"] = "disk" cfg_hash["#{tag}.filename"] = file_name cfg_hash end def openDisks(diskFiles) p_volumes = [] $log.debug("openDisks: #{diskFiles.size} disk files supplied.") # # Build a list of the VM's physical volumes. # diskFiles.each do |dtag, df| $log.debug "openDisks: processing disk file (#{dtag}): #{df}" d_info = open_disks_info(dtag, df) begin if @uri d = MiqDiskCache.new(AzureBlobDisk.new(sa_svc, @uri, d_info), 100, 128) elsif @managed_image d = MiqDiskCache.new(AzureManagedDisk.new(disk_svc, @disk_name, d_info), 200, 512) else d = MiqDiskCache.new(AzureManagedDisk.new(snap_svc, @disk_name, d_info), 200, 512) end rescue => err $log.error("#{err}: Couldn't open disk file: #{df}") $log.debug err.backtrace.join("\n") @diskInitErrors[df] = err.to_s next end @wholeDisks << d p = d.getPartitions if p.empty? # # If the disk has no partitions, the whole disk can be a single volume. # p_volumes << d else # # If the disk is partitioned, the partitions are physical volumes, # but not the whild disk. # p_volumes.concat(p) end end p_volumes end # def openDisks def open_disks_info(disk_tag, disk_file) disk_info = OpenStruct.new disk_info.fileName = disk_file disk_info.hardwareId = disk_tag disk_format = @vmConfig.getHash["#{disk_tag}.format"] disk_info.format = disk_format unless disk_format.blank? disk_info.rawDisk = true disk_info.resource_group = @resource_group disk_info end def vm_svc @vm_svc ||= Azure::Armrest::VirtualMachineService.new(@azure_handle) end def sa_svc @sa_svc ||= Azure::Armrest::StorageAccountService.new(@azure_handle) end def snap_svc @snap_svc ||= Azure::Armrest::Storage::SnapshotService.new(@azure_handle) end def disk_svc @disk_svc ||= Azure::Armrest::Storage::DiskService.new(@azure_handle) end end
require 'redis' require 'active_support/core_ext' require 'rails-pipeline/protobuf/encrypted_message.pb' # Pipeline forwarder base class that # - reads from redis queue using BRPOPLPUSH for reliable queue pattern # - keeps track of failed tasks in the in_progress queue # - designed to be used with e.g. IronmqPublisher $redis = ENV["REDISCLOUD_URL"] || ENV["REDISTOGO_URL"] || "localhost:6379" module RailsPipeline class RedisForwarder if RailsPipeline::HAS_NEWRELIC include ::NewRelic::Agent::MethodTracer end def initialize(key) _trap_signals @redis = nil @stop = false @queue = key @in_progress_queue = _in_progress_queue @processed = 0 @blocking_timeout = 2 @failure_check_interval = 30 @message_processing_limit = 10 # number of seconds before a message is considered failed @failure_last_checked = Time.now - @failure_check_interval.seconds # TODO: randomize start time? end def _trap_signals trap('SIGTERM') do puts 'Exiting (SIGTERM)' stop end trap('SIGINT') do puts 'Exiting (SIGINT)' stop end end # Blocking right pop from the queue # - use BRPOPLPUSH to tenporarily mark the message as "in progress" # - delete from the in_prgress queue on success # - restore to the main queue on failure def process_queue # pop from the queue and push onto the in_progress queue data = _redis.brpoplpush(@queue, @in_progress_queue, timeout: @blocking_timeout) if data.nil? # Timed-out with nothing to process return end begin encrypted_data = RailsPipeline::EncryptedMessage.parse(data) RailsPipeline.logger.debug "Processing #{encrypted_data.uuid}" # re-publish to wherever (e.g. IronMQ) topic_name = encrypted_data.topic if topic_name.nil? RailsPipeline.logger.error "Damaged message, no topic name" return end publish(topic_name, data) @processed += 1 # Now remove this message from the in_progress queue removed = _redis.lrem(@in_progress_queue, 1, data) if removed != 1 RailsPipeline.logger.warn "OHNO! Didn't remove the data I was expecting to: #{data}" end rescue Exception => e RailsPipeline.logger.info e RailsPipeline.logger.info e.backtrace.join("\n") if !data.nil? RailsPipeline.logger.info "Putting message #{encrypted_data.uuid} back on main queue" _put_back_on_queue(data) end end end add_method_tracer :process_queue, "Pipeline/RedisForwarder/process_queue" if RailsPipeline::HAS_NEWRELIC # note in redis that we are processing this message def report(uuid) _redis.setex(_report_key(uuid), @message_processing_limit, _client_id) end # Search the in-progress queue for messages that are likely to be abandoned # and re-queue them on the main queue def check_for_failures # Lock in_progress queue or return num_in_progress = _redis.llen(@in_progress_queue) if num_in_progress == 0 RailsPipeline.logger.debug "No messages in progress, skipping check for failures" return end RailsPipeline.logger.debug "Locking '#{@in_progress_queue}' for #{num_in_progress} seconds" # Attempt to lock this queue for the next num_in_progress seconds lock_key = "#{@in_progress_queue}__lock" locked = _redis.set(lock_key, _client_id, ex: num_in_progress, nx: true) if !locked RailsPipeline.logger.debug "in progress queue is locked" return end # Go through each message, see if there's a 'report' entry. If not, # requeue! in_progress = _redis.lrange(@in_progress_queue, 0, num_in_progress) in_progress.each do |message| enc_message = EncryptedMessage.parse(message) owner = _redis.get(_report_key(enc_message.uuid)) if owner.nil? RailsPipeline.logger.info "Putting timed-out message #{enc_message.uuid} back on main queue" _put_back_on_queue(message) else RailsPipeline.logger.debug "Message #{uuid} is owned by #{owner}" end end end add_method_tracer :check_for_failures, "Pipeline/RedisForwarder/check_for_failures" if RailsPipeline::HAS_NEWRELIC # Function that runs in the loop def run process_queue RailsPipeline.logger.info "Queue: '#{@queue}'. Processed: #{@processed}" if Time.now - @failure_last_checked > @failure_check_interval @failure_last_checked = Time.now check_for_failures end end # Main loop def start while true begin if @stop RailsPipeline.logger.info "Finished" if RailsPipeline::HAS_NEWRELIC RailsPipeline.logger.info "Shutting down NewRelic" ::NewRelic::Agent.shutdown end break end run rescue Exception => e RailsPipeline.logger.info e RailsPipeline.logger.info e.backtrace.join("\n") end end end def stop puts "stopping..." @stop = true end def _redis if !@redis.nil? return @redis end if $redis.start_with?("redis://") @redis = Redis.new(url: $redis) else host, port = $redis.split(":") @redis = Redis.new(host: host, port: port) end return @redis end def _processed return @processed end def _in_progress_queue "#{@queue}_in_progress" end # The redis key at which we 'claim' the message when we start processing it. def _report_key(uuid) "#{@queue}__#{uuid}" end def _client_id self.class.name end # Atomically remove a message from the in_progress queue and put it back on # the main queue def _put_back_on_queue(message) future = nil _redis.multi do _redis.rpush(@queue, message) future = _redis.lrem(@in_progress_queue, 1, message) end removed = future.value if removed !=1 RailsPipeline.logger.error "ERROR: Didn't remove message from in_progress queue?!!!" end end end end
namespace :products do desc "seed products" task :seed => [ :environment ] do puts "seeding products..." 50.times do fake_country = Faker::Address.country origin_country = [fake_country, fake_country, fake_country, "USA"] Product.create!(name: Faker::Food.ingredient, origin: origin_country.sample, cost: rand(2..17)) end puts "seeding users..." 100.times do User.create!(username: Faker::LordOfTheRings.character, email: Faker::Internet.email, password: "password", password_confirmation: "password") end puts "seeding reviews..." 250.times do Review.create!(product_id: rand(1..50), user_id: rand(1..100), rating: rand(1..5), content_body: Faker::Lorem.paragraph_by_chars(rand(50..250), false)) end end end
require 'spec_helper' feature 'User can manage Todo items' do let(:authed_user) { create_logged_in_user } scenario 'by accessing the Todo index' do visit todos_path(authed_user) expect(page).to have_content("My List") end scenario 'Can see the Todo list headers' do visit todos_path(authed_user) expect(page).to have_content('Description') expect(page).to have_content('Days left') expect(page).to have_content('Complete') end end feature 'User creates Todo item' do let(:authed_user) { @user = create_logged_in_user @todo = Todo.create(description: 'Test my app') } scenario 'Successfully' do visit todos_path(authed_user) expect{ fill_in 'todo_description', with: 'Meet up with the team' click_button 'Save' }.to change(Todo, :count).by (1) expect(page).to have_content('Meet up with the team') expect(page).to have_content('days') end scenario 'sees \'SUCCESS\' message when saved' do visit todos_path(authed_user) fill_in 'Description', with: 'Meet up with the team' click_button 'Save' expect(page).to have_content('Your new TODO was saved.') end scenario 'invalid with \'Description\' missing' do visit todos_path(authed_user) expect{click_button 'Save'}.to change(Todo, :count).by (0) expect(page).to have_content("can't be blank") end end
class SetFinancialQuarterOnTransactions < ActiveRecord::Migration[6.0] def up Transaction.where.not(date: nil).find_each do |transaction| financial_quarter = FinancialQuarter.for_date(transaction.date) transaction.update_columns( financial_quarter: financial_quarter.quarter, financial_year: financial_quarter.financial_year.start_year ) end end end
class ChangeCartTotalInCarts < ActiveRecord::Migration[5.0] def change change_column :carts, :cart_total, :integer end end
class User < ActiveRecord::Base has_secure_password has_many :groups, :through => :memberships has_many :memberships validates :username, presence: true validates :password_digest, presence: true validates :email, presence: true def status_check errors.add(:status, ": Your account has been deactivated. Please contact a site administrator") unless (self.status == true) end def password_check(pw) errors.add(:password, ": Your password is incorrect. Please try again.") unless (self.password == pw) end end
class PcrInspection < ApplicationRecord validates :subject_id, presence: true validates :clinic_id, presence: true validates :result, presence: true end
FactoryGirl.define do factory :transfer_notification do notice_type 1 amount "9.99" smx_transaction nil notified_by nil end end
require 'minitest/unit' require 'page_cell' MiniTest::Unit.autorun class Env attr_accessor :name def initialize @name = 'abc' end end class PageCellTest < MiniTest::Unit::TestCase def setup @env = Env.new end def render(source, options = {}, &block) tmpl = PageCell::Template.new(options[:file], options) { source } #TODO: just for debugging...will remove later # #puts '*'*40,tmpl.precompiled_template tmpl.render(options[:scope] || @env, &block) end def assert_cell(source,html) assert_equal html,render(source) end def test_call #puts PageCell::Template.new([:multi,[:pagecell,:code,"aaa", "bbb as aa"]]) assert_cell "aaaa", "aaaa" assert_cell "aaaa ## {{name}} aa", "aaaa ## abc aa" assert_cell "aaaa ## {%#name%} aa", "aaaa ## aa" assert_cell "aaaa ## {%#name aa", "aaaa ## {%#name aa" assert_cell 'aaaa #{%if name%} aa', "aaaa #not support aa" assert_cell 'aaaa {%render name%} aa', "aaaa render <name> aa" end end
require "rails_helper" RSpec.describe 'TOC', js: true do let!(:article) { NewsArticle.create!({ title: 'first title', body: 'first body', subtitle: 'first subtitle', background_image_url: 'http://lvh.me/testing.png' }) } before do visit "/" end include_examples "layout" include_examples "header" it "page should contains quote of president" do expect(page.find('div.quote')) end it "page should contains sbergile transform statistics" do expect(page.find('div.statistics')) end it "page should contains news list" do expect(page.find('div.article')) end it "page should contains list to news page" do expect(page.find('a.mdl-button')) expect(page).to have_content("ЧИТАТЬ ДАЛЬШЕ") end it "news article should contain title" do expect(page.find(".article .article__title")) end it "news article should contain subtitle" do expect(page.find(".article .article__subtitle")) end it "news articles should contain header" do expect(page.find("h3.articles__head")) end it "news more link lead us to read news page" do page.find("a.article__more").click expect(page).to have_content("first body") end end
require 'spec_helper' require_relative '../../lib/paths' using StringExtension module Jabverwock RSpec.describe 'css test' do subject(:img){IMG.new} it "single List" do expect(img.name ).to eq "img" end it "A tag" do ans = img.press expect(ans).to eq "<img>" end it "content add" do img.content = "test" ans = img.press expect(ans).to eq "<img>test" end it "add label case: ignore content with variable" do img.content = "test" + "a".variable ans = img.press expect(ans).to eq "<img>test" end it "href add" do img.tagManager .tagAttr(:href, "http://www") ans = img.press expect(ans).to eq"<img href=\"http://www\">" end it "src add" do img.tagManager .tagAttr(:src, "http://www") ans = img.press expect(ans).to eq"<img src=\"http://www\">" end end end
require 'dm-gen/generators/plugin_generator' module DMGen class Is < Templater::Generator include PluginGenerator desc <<-eos Generates an 'is' plugin for DataMapper, such as dm-is-list. Use like dm-gen is plugin This generates the full plugin structure with skeleton code and specs, as well as a Rakefile. All it needs is a README and some real functionality. eos def gem_name "dm-is-#{snake_name}" end end add :is, Is end
# frozen_string_literal: true module Mutations class Login < GraphQL::Function argument :email, !types.String, 'Email of the user logging in' argument :password, !types.String, 'Password for user authentication' description 'Login given a successful email and password' type ::Types::LoginType def call(_obj, args, _ctx) user = User.find_by! email: args[:email] return OpenStruct.new token: nil, uid: nil, user: user unless user.authenticate args[:password] token = user.authentication_tokens.create! OpenStruct.new token: token.body, uid: user.email, user: user end end end
class AddActiveUsersTable < ActiveRecord::Migration def change create_table :active do |t| end add_reference :active, :user add_reference :active, :channel end end
module SectionsHelper def edit_section(section) if admin? link_to('Edit', edit_section_path(section)) else '' end end def delete_section_link(section) if admin? link_to 'Delete section', section, method: 'delete' else '' end end def render_section_content(section) render_markdown(section.content).html_safe end end
# input: string with uppercase, lowercase and neither # output: hash with keys for lowercase and uppercase characters as well as neither ones with their values as their respective percentages # integers count as neither # spaces count as neither # symbols count as neither # values of hash are percentages and can be floats # percentages are calculated by dividing the count of key with the total character amount of the input string # string will always contain one character # data structure: hash # algorithm: # initialize a variable and assign it to total integer count of input string # initialize variable and assign it to empty hash # count cases for lowercase, uppercase and neither in input string # convert into floats and divide with total count of input string and add them into hash def letter_percentages(string) total_count = string.size character_hash = {} character_hash[:lowercase] = (string.count("a-z").to_f / total_count) * 100 character_hash[:uppercase] = (string.count("A-Z").to_f / total_count) * 100 character_hash[:neither] = (string.count("^a-zA-Z").to_f / total_count) * 100 character_hash end
class Rating < ActiveRecord::Base attr_accessible :value, :duser_id, :event_id belongs_to :event belongs_to :duser validates :value, presence: true end
class MembersController < ApplicationController def index members = Member.where(user_id: params[:user_id]) render json: members end def create member = Member.create(member_params) render json: member if member.save! end def update member = Member.find(params[:id]) member.update(member_params) render json: member end def destroy member = Member.find(params[:id]) member.destroy end end private def member_params params.require(:member).permit( :first_name, :last_name, :birthday, :diet, :shoe_size, :gifts, :items, :color, :notes, :user_id ) end
# frozen_string_literal: true class Room < ApplicationRecord has_and_belongs_to_many :users has_many :messages end
class ProductReviewsController < ApplicationController before_action :authenticate def new @product = Product.find(params[:product_id]) @product_review = ProductReview.new end def create @product = Product.find(params[:product_id]) if current_user @product_review = ProductReview.new(product_review_params) @product_review.user_id = current_user.id @product_review.product_id = @product.id if !@product_review.valid? render :new else @product_review.save redirect_to reviews_path, notice: "Review was successfully created." end else redirect_to login_path, notice: "User must be logged in to review products." end end def edit @product = Product.find(params[:product_id]) @product_review = @product.product_reviews.find(params[:id]) end def update @product = Product.find(params[:product_id]) @product_review = @product.product_reviews.find(params[:id]) if !@product_review.valid? render :edit else if @product_review.update(product_review_params) redirect_to reviews_path, notice: "Review was successfully updated." else render :edit end end end private def authenticate if !@current_user redirect_to root_path, notice: "You must be logged in to review products." end end def product_review_params params.require(:product_review).permit(:title, :description, :rating) end end
class DispatcherController < ApplicationController #show all dispatchers route get '/dispatchers' do if logged_in? @dispatchers = Dispatcher.all erb :"dispatchers/show_all" else erb :"dispatchers/login" end end #dispatcher signup route get '/dispatchers/signup' do if logged_in? erb :"dispatchers/error_already_login" end erb :"dispatchers/signup" end #receiving from singup form and creating new dispatcher post '/dispatchers' do if !params[:team][:name].empty? @team = Team.create(params[:team]) @dispatcher = Dispatcher.create( name: params[:dispatcher][:name], team_id: @team.id, password: params[:dispatcher][:password], email: params[:dispatcher][:email], username: params[:dispatcher][:username], ) session[:user_id] = @dispatcher.id # binding.pry redirect to "/dispatchers/#{@dispatcher.id}" else @dispatcher = Dispatcher.create(params[:dispatcher]) session[:user_id] = @dispatcher.id redirect to "/dispatchers/#{@dispatcher.id}" end end # #new dispatcher # get '/dispatchers/new' do # erb :"/dispatchers/new" # end # post #show page for single dispatcher get '/dispatchers/:id' do @dispatcher = Dispatcher.find_by_id(params[:id]) @team = Team.find_by(id: @dispatcher.team_id) @loads = @dispatcher.loads erb :"dispatchers/show" end #edit get '/dispatchers/:id/edit' do if current_user.id == params[:id].to_i @dispatcher = Dispatcher.all.find_by(id: params[:id]) erb :"dispatchers/edit" else erb :"dispatchers/error_access_denied" end end patch '/dispatchers/:id' do @dispatcher = Dispatcher.all.find_by(id: params[:id]) @dispatcher.update(params[:dispatcher]) redirect to "dispatchers/#{@dispatcher.id}" end #delete #this needs to be fixt get '/dispatchers/:id/delete' do # binding.pry if current_user.id == params[:id].to_i @dispatcher = Dispatcher.find_by(id: params[:id]) @dispatcher.delete session.clear redirect to "/" else erb :"dispatchers/error_access_denied" end end end
class ImagesController < ApplicationController def destroy @image = Image.find(params[:id]) @image.destroy redirect_to edit_product_path(@image.product.id) end end
$LOAD_PATH.push File.expand_path('../lib', __FILE__) # Maintain your gem's version: require 'ehonda/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = 'ehonda' s.version = Ehonda::VERSION s.authors = ['Lee Henson'] s.email = ['lee.m.henson@gmail.com'] s.homepage = 'https://github.com/musicglue/ehonda' s.summary = 'Addons for phstc/shoryuken' s.description = 'Addons for phstc/shoryuken' s.license = 'MIT' s.files = Dir['{app,bin,config,db,lib}/**/*', 'MIT-LICENSE', 'Rakefile', 'README.rdoc'] s.test_files = Dir['test/**/*'] s.require_paths = ['lib'] s.add_runtime_dependency 'activesupport' s.add_runtime_dependency 'aws-sdk-resources' s.add_runtime_dependency 'retryable' s.add_runtime_dependency 'shoryuken', '>= 1.0.1' s.add_development_dependency 'active_attr' s.add_development_dependency 'awesome_print' s.add_development_dependency 'bundler', '~> 1.6' s.add_development_dependency 'guard' s.add_development_dependency 'guard-minitest' s.add_development_dependency 'guard-rubocop' s.add_development_dependency 'minitest' s.add_development_dependency 'minitest-focus' s.add_development_dependency 'minitest-rg' s.add_development_dependency 'mocha' s.add_development_dependency 'pry-byebug' s.add_development_dependency 'rake' end
class AddTeamsToPlayerIds < ActiveRecord::Migration def change add_column :player_ids, :teams, :text end end
module AdminHelper TIME_FORMATS = {long: '%B %-d, %Y %l:%M %P %Z', short: '%m/%d/%y %l:%M %P'} def alert_class(type) case type.to_s when 'info' # Blue. 'alert-info' when 'error', 'alert' # Red. 'alert-danger' else # Yellow. 'alert-warning' end end def link_to_google_maps(text, lat, lon, options = {}) link_to text, "https://www.google.com/maps/search/#{lat},#{lon}", options end def admin_timestamp(datetime, options = {}) return datetime unless datetime format = TIME_FORMATS[options[:format] || :long] str = datetime.in_time_zone('Eastern Time (US & Canada)') str = str.strftime(format) str += " (#{time_ago_in_words datetime} ago)" if options[:time_ago] str end end
require './spec/spec_helper' require './lib/gate.rb' require './lib/ticket.rb' RSpec.describe 'Gate Test' do it 'is OK' do def test_gate umeda = Gate.new(:umeda) juso = Gate.new(:juso) ticket = Ticket.new(150) umeda.enter(ticket) expect(juso.exit(ticket)).to be_truthy end end describe 'Umeda to Mikuni' do it 'is NG' do def fare_in_not_enough umeda = Gate.new(:umeda) mikuni = Gate.new(:mikuni) ticket = Ticket.new(150) umeda.enter(ticket) expect(mikuni.exit(ticket)).to be falsey end end end end # require './spec/spec_helper' # require './lib/gate' # require './lib/ticket' # # RSpec.describe 'Gate' do # let(:umeda) { Gate.new(:umeda) } # let(:juso) { Gate.new(:juso) } # let(:mikuni) { Gate.new(:mikuni) } # # describe 'Umeda to Juso' do # it 'is OK' do # ticket = Ticket.new(150) # umeda.enter(ticket) # expect(juso.exit(ticket)).to be_truthy # end # end # # describe 'Umeda to Mikuni' do # context 'fare is not enough' do # it 'is NG' do # ticket = Ticket.new(150) # umeda.enter(ticket) # expect(mikuni.exit(ticket)).to be_falsey # end # end # context 'fare is enough' do # it 'is OK' do # ticket = Ticket.new(190) # umeda.enter(ticket) # expect(mikuni.exit(ticket)).to be_truthy # end # end # end # # describe 'Juso to Mikuni' do # it 'is OK' do # ticket = Ticket.new(150) # juso.enter(ticket) # expect(mikuni.exit(ticket)).to be_truthy # end # end # end
require "rails_helper" describe MergeCall, type: :model do describe "#call" do it "moves participants from one call to another" do call_from = create(:incoming_call, :initiated) participant = create(:participant, call: call_from) call_to = create(:incoming_call) fake_connector = stub_const( "ConnectCallToConference", spy(success?: true, connected: [participant.sid], failed: []) ) result = MergeCall.new(to: call_to, from: call_from).call expect(result.success?).to be(true) expect(call_to.participants.count).to eq(1) expect(fake_connector).to have_received(:new).with( call: call_to, sids: [call_from.participants.first.sid] ) expect(fake_connector).to have_received(:call) expect(call_from.completed?).to be(true) end it "returns failure when it failed to connect a participant" do call_from = create(:incoming_call) participant = create(:participant, call: call_from) call_to = create(:incoming_call) fake_connector = stub_const( "ConnectCallToConference", spy(success?: false, connected: [], failed: [participant.sid]) ) result = MergeCall.new(to: call_to, from: call_from).call expect(result.success?).to be(false) expect(call_to.participants.count).to eq(0) expect(fake_connector).to have_received(:new).with( call: call_to, sids: [call_from.participants.first.sid] ) expect(fake_connector).to have_received(:call) end end end
require 'spec_helper' # The hypothetical API is accessible via a standard HTTP GET request. For example: # http://not_real.com/customer_scoring?income=50000&zipcode=60201&age=35 # A successful request to the API will return a JSON response resembling the following: # { # "propensity": 0.26532, # "ranking": "C" # } describe LfoApi::Client do let(:url){LfoApi::Client.new} it 'has a version number' do expect(LfoApi::VERSION).not_to be nil end it 'should return json as the resulting value' do result = url.results expect(results).to respond_with_content_type(:json) end it 'should search by propensity' do result = url.search("propensity","0.26532") result = result[0]["propensity"] expect(result).to eq("0.26532") end it 'should search by ranking' do result = url.search("ranking","C") result = result[0]["ranking"] expect(result).to eq("C") end it 'should search by income' do result = url.search("income", "50000") expect(result).to respond_with_content_type(:json) end it 'should search by zipcode' do result = url.search("zipcode", "60201") expect(result).to respond_with_content_type(:json) end it 'should search by age' do result = url.search("age", "35") expect(result).to respond_with_content_type(:json) end it 'should search by results and result in an array' do result = url.results expect(result).to respond_with_content_type(:json) end it 'should search by income, zipcode, age and result in an Array' do result = url.income_zipcode_age("50000", "60201", "35") expect(result).to respond_with_content_type(:json) end end
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :login, :null => false t.string :encrypted_password t.string :encrypted_password_salt t.string :encrypted_password_iv t.string :username, :null => false, :default => '' t.integer :department_id t.boolean :admin, :default => false t.timestamps null: false end end end
module Settings module Game NAME = 'Pingpong' WIDTH = 1366 HEIGHT = 768 end module Court BG_COLOR = '#000000' LINE_COLOR = '#FFFFFF' WALL_THICKNESS = 10 CENTER_THICKNESS = 4 end module Ball COLOR = '#FFFFFF' RADIUS = 25 SPEED = 7 # pixels every 1/60 of second end module Paddle COLOR = '#FFFFFF' WIDTH = 15 HEIGHT = 150 EDGE_DISTANCE = 50 SPEED = 12 end end
require('pry') require('pg') require_relative('../db/sql_runner.rb') class Album attr_reader :id, :artist_id attr_accessor :title, :genre def initialize(album_hash) @title = album_hash['title'] @genre = album_hash['genre'] @artist_id = album_hash['artist_id'].to_i @id = album_hash['id'].to_i if album_hash['id'] end def save_album_to_db() sql = " INSERT INTO albums (title, genre, artist_id) VALUES ($1, $2, $3) RETURNING id; " values = [@title, @genre, @artist_id] result_array = SqlRunner.run(sql, values) @id = result_array[0]["id"] end def self.list_all_albums sql = "SELECT * FROM albums;" result_array = SqlRunner.run(sql) albums_objs = result_array.map { |album| Album.new(album) } albums_list = albums_objs.map { |album| album.title } return albums_list end def self.list_albums_by_artist(artist) sql = " SELECT * FROM albums WHERE artist_id = $1; " values = [artist.id] #or artist.id? result_array = SqlRunner.run(sql, values) albums_list = result_array.map { |album| Album.new(album) } album_titles = albums_list.map { |album| album.title } end # def get_artist_id() # sql = "SELECT artist_id FROM albums WHERE title = $1 LIMIT 1;" # values = [@title] # result_array = SqlRunner.run(sql, values) # artist_id = result_array.map { |artist| artist } # binding.pry # return artist_id[0]['artist_id'] # end def get_artist_name() sql = " SELECT * FROM artists WHERE id = $1; " values = [@artist_id] result_array = SqlRunner.run(sql, values) artist_objs = result_array.map { |artist| Artist.new(artist) } return artist_objs[0].name end def self.delete_all_albums() sql = "DELETE FROM albums;" SqlRunner.run(sql) end def update_album() sql = " UPDATE albums SET (title, genre, artist_id) = ($1, $2, $3) WHERE id = ($4); " values = [@title, @genre, @artist_id, @id] SqlRunner.run(sql, values) end def self.find_album(id) string_id = id.to_s sql = " SELECT * FROM albums WHERE id = $1;" values = [string_id] result_array = SqlRunner.run(sql, values) album_objs = result_array.map { |album| Album.new(album) } return album_objs[0].title end end
class AddTitleLevelIndexToTest < ActiveRecord::Migration[5.2] def change # Composite Index # used for - validates :title, uniqueness: { scope: :level } add_index :tests, [:title, :level], unique: true end end
module RobotSimulator class TableTop def initialize(x_width, y_width) @x_width = x_width @y_width = y_width end def is_valid_position?(position) (position.x_axis.between?(0, @x_width-1) and position.y_axis.between?(0, @y_width-1)) ? true : false end def within_x_edge?(x) x.between?(0, @x_width-1) ? true : false end def within_y_edge?(y) y.between?(0, @y_width-1) ? true : false end end end
class BaseJob < Struct.new(:params) def send_message_using_message_pub(subject, body, protocol, address) logger.debug("*** #{Time.now}: *** sending message pub #{protocol} to: #{address}, subject: #{subject}, body: #{body}") # create notification notification = MessagePub::Notification.new(:body => body, :subject => subject, :escalation => 0, :recipients => {:recipient => [{:position => 1, :channel => protocol, :address => address}]}) notification.save end end
require 'test_helper' class CrmCasesControllerTest < ActionController::TestCase setup do @crm_case = crm_cases(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:crm_cases) end test "should get new" do get :new assert_response :success end test "should create crm_case" do assert_difference('CrmCase.count') do post :create, crm_case: { isClosed: @crm_case.isClosed, tenant: @crm_case.tenant, title: @crm_case.title } end assert_redirected_to crm_case_path(assigns(:crm_case)) end test "should show crm_case" do get :show, id: @crm_case assert_response :success end test "should get edit" do get :edit, id: @crm_case assert_response :success end test "should update crm_case" do put :update, id: @crm_case, crm_case: { isClosed: @crm_case.isClosed, tenant: @crm_case.tenant, title: @crm_case.title } assert_redirected_to crm_case_path(assigns(:crm_case)) end test "should destroy crm_case" do assert_difference('CrmCase.count', -1) do delete :destroy, id: @crm_case end assert_redirected_to crm_cases_path end end
require 'rails_helper' feature 'User delete recipe' do scenario 'successfully' do user = User.create!(email: 'carinha@mail.com', password: '123456') recipe_type = RecipeType.create(name: 'Sobremesa') recipe = Recipe.create(title: 'Bolo de cenoura', difficulty: 'Médio', recipe_type: recipe_type, cuisine: 'Brasileira', cook_time: 50, ingredients: 'Farinha, açucar, cenoura', cook_method: 'Cozinhe a cenoura, corte em pedaços pequenos, misture com o restante dos ingredientes', user: user) visit root_path click_on 'Entrar' within('.formulario') do fill_in 'Email', with: user.email fill_in 'Senha', with: '123456' click_on 'Entrar' end click_on 'Bolo de cenoura' click_on 'Deletar Receita' expect(page).not_to have_content('Bolo de cenoura') end scenario 'and cant find button to delete others recipes' do user = User.create!(email: 'carinha@mail.com', password: '123456') other_user = User.create!(email: 'email@mail.com', password: '123456') recipe_type = RecipeType.create(name: 'Sobremesa') recipe = Recipe.create(title: 'Bolo de cenoura', difficulty: 'Médio', recipe_type: recipe_type, cuisine: 'Brasileira', cook_time: 50, ingredients: 'Farinha, açucar, cenoura', cook_method: 'Cozinhe a cenoura, corte em pedaços pequenos, misture com o restante dos ingredientes', user: user) visit root_path click_on 'Entrar' within('.formulario') do fill_in 'Email', with: other_user.email fill_in 'Senha', with: '123456' click_on 'Entrar' end click_on 'Bolo de cenoura' expect(page).not_to have_content('Deletar Receita') end end
# frozen_string_literal: true require 'support/entities/secret' # @note Integration spec for Stannum::Entities::Associations. # - Tests a :one association with no foreign key or inverse. RSpec.describe Spec::Secret do subject(:secret) { described_class.new(**attributes, **associations) } shared_context 'when the secret has a room' do let(:room) { Spec::Room.new(name: 'Old Room') } let(:associations) { super().merge(room: room) } end let(:attributes) { { difficulty: 10 } } let(:associations) { {} } describe '#assign_associations' do let(:value) { { room: Spec::Room.new(name: 'New Room') } } let(:expected) { { 'room' => value[:room] } } it 'should update the associations' do expect { secret.assign_associations(value) } .to change(secret, :associations) .to be == expected end wrap_context 'when the secret has a room' do it 'should update the associations' do expect { secret.assign_associations(value) } .to change(secret, :associations) .to be == expected end end end describe '#assign_properties' do let(:value) { { room: Spec::Room.new(name: 'New Room') } } let(:expected) do { 'difficulty' => 10, 'room' => value[:room] } end it 'should update the properties' do expect { secret.assign_properties(value) } .to change(secret, :properties) .to be == expected end wrap_context 'when the secret has a room' do it 'should update the properties' do expect { secret.assign_properties(value) } .to change(secret, :properties) .to be == expected end end end describe '#associations' do let(:expected) { { 'room' => nil } } it { expect(secret.associations).to be == expected } wrap_context 'when the secret has a room' do let(:expected) { super().merge('room' => room) } it { expect(secret.associations).to be == expected } end end describe '#associations=' do let(:value) { { room: Spec::Room.new(name: 'New Room') } } let(:expected) { { 'room' => value[:room] } } it 'should update the associations' do expect { secret.associations = value } .to change(secret, :associations) .to be == expected end wrap_context 'when the secret has a room' do it 'should update the associations' do expect { secret.associations = value } .to change(secret, :associations) .to be == expected end end end describe '#properties' do let(:expected) do { 'difficulty' => 10, 'room' => nil } end it { expect(secret.properties).to be == expected } wrap_context 'when the secret has a room' do let(:expected) { super().merge('room' => room) } it { expect(secret.properties).to be == expected } end end describe '#properties=' do let(:value) { { room: Spec::Room.new(name: 'New Room') } } let(:expected) do { 'difficulty' => nil, 'room' => value[:room] } end it 'should update the properties' do expect { secret.properties = value } .to change(secret, :properties) .to be == expected end wrap_context 'when the secret has a room' do it 'should update the properties' do expect { secret.properties = value } .to change(secret, :properties) .to be == expected end end end describe '#room' do it { expect(secret.room).to be nil } wrap_context 'when the secret has a room' do it { expect(secret.room).to be room } end end describe '#room=' do describe 'with a value' do let(:value) { Spec::Room.new(name: 'New Room') } it 'should set the association' do expect { secret.room = value } .to change(secret, :room) .to be value end end wrap_context 'when the secret has a room' do describe 'with nil' do it 'should clear the association' do expect { secret.room = nil } .to change(secret, :room) .to be nil end end describe 'with a value' do let(:value) { Spec::Room.new(name: 'New Room') } it 'should set the association' do expect { secret.room = value } .to change(secret, :room) .to be value end end end end end
class User < ActiveRecord::Base validates_presence_of :email, :name before_validation :setup_token, on: :create has_many :orders def admin? self.level == 'admin' end def self.from_omniauth(auth_hash) user = where( fb_uid: auth_hash[:uid] ).first_or_initialize user.name = auth_hash[:info][:name] user.email = auth_hash[:info][:email] if auth_hash[:credentials] user.fb_token = auth_hash[:credentials][:token] user.fb_expires_at = Time.at(auth_hash[:credentials][:expires_at]) end user.save! user end def self.verify_facebook_token(access_token) conn = Faraday.new(url: 'https://graph.facebook.com/me') response = conn.get "/me", { access_token: access_token } data = JSON.parse(response.body) if response.status == 200 data else Rails.logger.warn(data) nil end end def setup_token(options={}) self.token = Digest::SHA1.hexdigest("--#{SecureRandom.hex}--#{Time.now.to_s}--#{self.id.to_s}")[0,32] end end
# lib/active_model/sleeping_king_studios/validations/relations/many.rb require 'active_model/sleeping_king_studios/validations/relations/base' module ActiveModel::SleepingKingStudios::Validations::Relations # The base validator for validating a one-to-many relation. class Many < ActiveModel::SleepingKingStudios::Validations::Relations::Base # Checks the validity of the related models and merges any errors into the # primary model's #errors object. # # @param record [Object] An object extending ActiveModel::Validations and # with the specified relation. def validate record record.send(relation_name).each.with_index do |relation, index| next if relation.errors.blank? && relation.valid? relation.errors.each do |attribute, message| record.errors.add error_key(relation, index, attribute), message end # each end # each end # method validate private def error_key relation, index, attribute serializer.serialize relation_name, index, *serializer.deserialize(attribute) end # method relation_key def relation_name :relations end # method relation_name end # class end # module
class CreateClubs < ActiveRecord::Migration[5.0] def change create_table :clubs do |t| t.string :iaru_region t.string :country t.string :callsign t.string :name t.string :website t.string :email t.string :phone t.string :contact_person t.string :contact_callsign t.string :contact_email t.point :location t.timestamps end end end
require 'rails_helper' # Specs in this file have access to a helper object that includes # the CommentsHelper. For example: # # describe CommentsHelper do # describe "string concat" do # it "concats two strings with spaces" do # expect(helper.concat_strings("this","that")).to eq("this that") # end # end # end RSpec.describe TweetsHelper, type: :helper do describe 'initialize_remains_body_characters' do it '典型的なユーザー名' do expect(helper.initialize_remains_body_characters('@user1')).to eq(134) end it 'ユーザー名入力がなかった場合' do expect(helper.initialize_remains_body_characters('')).to eq(140) end end end
class AddCoverUrlToBooks < ActiveRecord::Migration[5.2] def change add_column :books, :cover_url, :text, null: false end end
# == Schema Information # # Table name: release_order_application_with_versions # # id :integer not null, primary key # release_order_id :integer # application_with_version_id :integer # class ReleaseOrderApplicationWithVersion < ActiveRecord::Base belongs_to :release_order belongs_to :application_with_version has_many :release_order_application_with_version_envs, dependent: :destroy has_many :envs, through: :release_order_application_with_version_envs def serializable_hash(_options = {}) envs = release_order_application_with_version_envs.map(&:env).map do |env| { 'id': env.id, 'name': env.name } end result = { application_with_version: application_with_version, envs: envs } result end end
feature 'add bookmark' do scenario 'user fills in form to add new bookmark' do visit('/') click_link('Bookmarks') fill_in('title', with: 'Goal') fill_in('url', with: 'http://www.goal.com') click_button('Submit') expect(page).to have_link('Goal', href: 'http://www.goal.com') end scenario 'user tries to submit invalid url' do visit('/') click_link('Bookmarks') fill_in('title', with: 'Fake News Media') fill_in('url', with: 'fakenewsmedia') click_button('Submit') expect(page).not_to have_link('Fake News Media', href: 'fakenewsmedia') end end
require 'spec_helper' Sequel.extension :mysql_json_ops describe 'Sequel::Mysql::JSONOp' do before do @db = Sequel.connect('mock://mysql2') @j = Sequel.mysql_json_op(:j) @l = proc{|o| @db.literal(o)} end it 'should have #extract accept a path selector' do @l[@j.extract('.foo')].must_equal "JSON_EXTRACT(j, '$.foo')" @l[@j.extract('[0].foo')].must_equal "JSON_EXTRACT(j, '$[0].foo')" end it 'should have #[] accept an Integer as selector for arrays' do @l[@j[1]].must_equal "JSON_EXTRACT(j, '$[1]')" end it 'should have #[] accept a String or Symbol as selector for object attributes' do @l[@j[:foo]].must_equal "JSON_EXTRACT(j, '$.foo')" end it 'should have #[] merge nested JSON_EXTRACT functions calls into a single one' do @l[@j[:items][1][:name]].must_equal "JSON_EXTRACT(j, '$.items[1].name')" @l[@j[42][:key]].must_equal "JSON_EXTRACT(j, '$[42].key')" end end
module Puffer class Fields < Array def field *args push Field.new(*args) last end def searchable @searchable ||= map { |f| f if f.column && [:text, :string, :integer, :decimal, :float].include?(f.column.type) }.compact end def searches query searchable.map { |f| "#{f.query_column} like '%#{query}%'" if f.query_column.present? }.compact.join(' or ') if query end def boolean @boolean ||= reject { |f| f.type != :boolean } end def includes @includes ||= map {|f| f.path unless f.native?}.compact.to_includes end end end
require 'test_helper' class Admin::Api::BuyerAccountPlansTest < ActionDispatch::IntegrationTest def setup @provider = FactoryBot.create :provider_account, :domain => 'provider.example.com' @buyer = FactoryBot.create(:buyer_account, :provider_account => @provider) @buyer.buy! @provider.default_account_plan @buyer.reload @not_plan = FactoryBot.create :application_plan, :issuer => @provider.default_service host! @provider.admin_domain end test 'account plans listing' do get admin_api_account_buyer_account_plan_path(:account_id => @buyer.id, :format => :xml), :provider_key => @provider.api_key assert_response :success #TODO: dry plan xml assertion into a helper #testing xml response xml = Nokogiri::XML::Document.parse(@response.body) assert xml.xpath('.//plan/id').children.first.to_s == @buyer.bought_account_plan.id.to_s assert xml.xpath('.//plan/name').children.first.to_s == @buyer.bought_account_plan.name.to_s assert xml.xpath('.//plan/type').children.first.to_s == @buyer.bought_account_plan.class.to_s.underscore assert xml.xpath(".//plans/plan[@id='#{@not_plan.id}']").empty? end test 'account plans for an inexistent buyer replies 404' do get admin_api_account_buyer_account_plan_path(0, :format => :xml), :provider_key => @provider.api_key assert_xml_404 end test 'security wise: buyers account plans is access denied in buyer side' do host! @provider.domain get admin_api_account_buyer_account_plan_path(@buyer, :format => :xml), :provider_key => @provider.api_key assert_response :forbidden end end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2017-2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo module Protocol # MongoDB Wire protocol Msg message (OP_MSG), a bi-directional wire # protocol opcode. # # OP_MSG is only available in MongoDB 3.6 (maxWireVersion >= 6) and later. # # @api private # # @since 2.5.0 class Msg < Message include Monitoring::Event::Secure # The identifier for the database name to execute the command on. # # @since 2.5.0 DATABASE_IDENTIFIER = '$db'.freeze # Keys that the driver adds to commands. These are going to be # moved to the end of the hash for better logging. # # @api private INTERNAL_KEYS = Set.new(%w($clusterTime $db lsid signature txnNumber)).freeze # Creates a new OP_MSG protocol message # # @example Create a OP_MSG wire protocol message # Msg.new([:more_to_come], {}, { hello: 1 }, # { type: 1, payload: { identifier: 'documents', sequence: [..] } }) # # @param [ Array<Symbol> ] flags The flag bits. Currently supported # values are :more_to_come and :checksum_present. # @param [ Hash ] options The options. # @param [ BSON::Document, Hash ] main_document The document that will # become the payload type 0 section. Can contain global args as they # are defined in the OP_MSG specification. # @param [ Protocol::Msg::Section1 ] sequences Zero or more payload type 1 # sections. # # @option options [ true, false ] validating_keys Whether keys should be # validated for being valid document keys (i.e. not begin with $ and # not contain dots). # This option is deprecated and will not be used. It will removed in version 3.0. # # @api private # # @since 2.5.0 def initialize(flags, options, main_document, *sequences) if flags flags.each do |flag| unless KNOWN_FLAGS.key?(flag) raise ArgumentError, "Unknown flag: #{flag.inspect}" end end end @flags = flags || [] @options = options unless main_document.is_a?(Hash) raise ArgumentError, "Main document must be a Hash, given: #{main_document.class}" end @main_document = main_document sequences.each_with_index do |section, index| unless section.is_a?(Section1) raise ArgumentError, "All sequences must be Section1 instances, got: #{section} at index #{index}" end end @sequences = sequences @sections = [ {type: 0, payload: @main_document} ] + @sequences.map do |section| {type: 1, payload: { identifier: section.identifier, sequence: section.documents.map do |doc| CachingHash.new(doc) end, }} end @request_id = nil super end # Whether the message expects a reply from the database. # # @example Does the message require a reply? # message.replyable? # # @return [ true, false ] If the message expects a reply. # # @since 2.5.0 def replyable? @replyable ||= !flags.include?(:more_to_come) end # Return the event payload for monitoring. # # @example Return the event payload. # message.payload # # @return [ BSON::Document ] The event payload. # # @since 2.5.0 def payload # Reorder keys in main_document for better logging - see # https://jira.mongodb.org/browse/RUBY-1591. # Note that even without the reordering, the payload is not an exact # match to what is sent over the wire because the command as used in # the published event combines keys from multiple sections of the # payload sent over the wire. ordered_command = {} skipped_command = {} command.each do |k, v| if INTERNAL_KEYS.member?(k.to_s) skipped_command[k] = v else ordered_command[k] = v end end ordered_command.update(skipped_command) BSON::Document.new( command_name: ordered_command.keys.first.to_s, database_name: @main_document[DATABASE_IDENTIFIER], command: ordered_command, request_id: request_id, reply: @main_document, ) end # Serializes message into bytes that can be sent on the wire. # # @param [ BSON::ByteBuffer ] buffer where the message should be inserted. # @param [ Integer ] max_bson_size The maximum bson object size. # # @return [ BSON::ByteBuffer ] buffer containing the serialized message. # # @since 2.5.0 def serialize(buffer = BSON::ByteBuffer.new, max_bson_size = nil, bson_overhead = nil) validate_document_size!(max_bson_size) super add_check_sum(buffer) buffer end # Compress the message, if the command being sent permits compression. # Otherwise returns self. # # @param [ String, Symbol ] compressor The compressor to use. # @param [ Integer ] zlib_compression_level The zlib compression level to use. # # @return [ Message ] A Protocol::Compressed message or self, # depending on whether this message can be compressed. # # @since 2.5.0 # @api private def maybe_compress(compressor, zlib_compression_level = nil) compress_if_possible(command.keys.first, compressor, zlib_compression_level) end # Reverse-populates the instance variables after deserialization sets # the @sections instance variable to the list of documents. # # TODO fix deserialization so that this method is not needed. # # @api private def fix_after_deserialization if @sections.nil? raise NotImplementedError, "After deserializations @sections should have been initialized" end if @sections.length != 1 raise NotImplementedError, "Deserialization must have produced exactly one section, but it produced #{sections.length} sections" end @main_document = @sections.first @sequences = [] @sections = [{type: 0, payload: @main_document}] end def documents [@main_document] end # Possibly encrypt this message with libmongocrypt. Message will only be # encrypted if the specified client exists, that client has been given # auto-encryption options, the client has not been instructed to bypass # auto-encryption, and mongocryptd determines that this message is # eligible for encryption. A message is eligible for encryption if it # represents one of the command types allow-listed by libmongocrypt and it # contains data that is required to be encrypted by a local or remote json schema. # # @param [ Mongo::Server::Connection ] connection The connection on which # the operation is performed. # @param [ Mongo::Operation::Context ] context The operation context. # # @return [ Mongo::Protocol::Msg ] The encrypted message, or the original # message if encryption was not possible or necessary. def maybe_encrypt(connection, context) # TODO verify compression happens later, i.e. when this method runs # the message is not compressed. if context.encrypt? if connection.description.max_wire_version < 8 raise Error::CryptError.new( "Cannot perform encryption against a MongoDB server older than " + "4.2 (wire version less than 8). Currently connected to server " + "with max wire version #{connection.description.max_wire_version}} " + "(Auto-encryption requires a minimum MongoDB version of 4.2)" ) end db_name = @main_document[DATABASE_IDENTIFIER] cmd = merge_sections enc_cmd = context.encrypter.encrypt(db_name, cmd) if cmd.key?('$db') && !enc_cmd.key?('$db') enc_cmd['$db'] = cmd['$db'] end Msg.new(@flags, @options, enc_cmd) else self end end # Possibly decrypt this message with libmongocrypt. Message will only be # decrypted if the specified client exists, that client has been given # auto-encryption options, and this message is eligible for decryption. # A message is eligible for decryption if it represents one of the command # types allow-listed by libmongocrypt and it contains data that is required # to be encrypted by a local or remote json schema. # # @param [ Mongo::Operation::Context ] context The operation context. # # @return [ Mongo::Protocol::Msg ] The decrypted message, or the original # message if decryption was not possible or necessary. def maybe_decrypt(context) if context.decrypt? cmd = merge_sections enc_cmd = context.encrypter.decrypt(cmd) Msg.new(@flags, @options, enc_cmd) else self end end # Whether this message represents a bulk write. A bulk write is an insert, # update, or delete operation that encompasses multiple operations of # the same type. # # @return [ Boolean ] Whether this message represents a bulk write. # # @note This method was written to support client-side encryption # functionality. It is not recommended that this method be used in # service of any other feature or behavior. # # @api private def bulk_write? inserts = @main_document['documents'] updates = @main_document['updates'] deletes = @main_document['deletes'] num_inserts = inserts && inserts.length || 0 num_updates = updates && updates.length || 0 num_deletes = deletes && deletes.length || 0 num_inserts > 1 || num_updates > 1 || num_deletes > 1 end def maybe_add_server_api(server_api) conflicts = {} %i(apiVersion apiStrict apiDeprecationErrors).each do |key| if @main_document.key?(key) conflicts[key] = @main_document[key] end if @main_document.key?(key.to_s) conflicts[key] = @main_document[key.to_s] end end unless conflicts.empty? raise Error::ServerApiConflict, "The Client is configured with :server_api option but the operation provided the following conflicting parameters: #{conflicts.inspect}" end main_document = @main_document.merge( Utils.transform_server_api(server_api) ) Msg.new(@flags, @options, main_document, *@sequences) end # Returns the number of documents returned from the server. # # The Msg instance must be for a server reply and the reply must return # an active cursor (either a newly created one or one whose iteration is # continuing via getMore). # # @return [ Integer ] Number of returned documents. def number_returned if doc = documents.first if cursor = doc['cursor'] if batch = cursor['firstBatch'] || cursor['nextBatch'] return batch.length end end end raise NotImplementedError, "number_returned is only defined for cursor replies" end private # Validate that the documents in this message are all smaller than the # maxBsonObjectSize. If not, raise an exception. def validate_document_size!(max_bson_size) max_bson_size ||= Mongo::Server::ConnectionBase::DEFAULT_MAX_BSON_OBJECT_SIZE contains_too_large_document = @sections.any? do |section| section[:type] == 1 && section[:payload][:sequence].any? do |document| document.to_bson.length > max_bson_size end end if contains_too_large_document raise Error::MaxBSONSize.new('The document exceeds maximum allowed BSON object size after serialization') end end def command @command ||= if @main_document @main_document.dup.tap do |cmd| @sequences.each do |section| cmd[section.identifier] ||= [] cmd[section.identifier] += section.documents end end else documents.first end end def add_check_sum(buffer) if flags.include?(:checksum_present) #buffer.put_int32(checksum) end end # Encapsulates a type 1 OP_MSG section. # # @see https://github.com/mongodb/specifications/blob/master/source/message/OP_MSG.rst#sections # # @api private class Section1 def initialize(identifier, documents) @identifier, @documents = identifier, documents end attr_reader :identifier, :documents def ==(other) other.is_a?(Section1) && identifier == other.identifier && documents == other.documents end alias :eql? :== end # The operation code required to specify a OP_MSG message. # @return [ Fixnum ] the operation code. # # @since 2.5.0 OP_CODE = 2013 KNOWN_FLAGS = { checksum_present: true, more_to_come: true, exhaust_allowed: true, } # Available flags for a OP_MSG message. FLAGS = Array.new(16).tap do |arr| arr[0] = :checksum_present arr[1] = :more_to_come arr[16] = :exhaust_allowed end.freeze # @!attribute # @return [Array<Symbol>] The flags for this message. field :flags, BitVector.new(FLAGS) # The sections that will be serialized, or the documents have been # deserialized. # # Usually the sections contain OP_MSG-compliant sections derived # from @main_document and @sequences. The information in @main_document # and @sequences is duplicated in the sections. # # When deserializing Msg instances, sections temporarily is an array # of documents returned in the type 0 section of the OP_MSG wire # protocol message. #fix_after_deserialization method mutates this # object to have sections, @main_document and @sequences be what # they would have been had the Msg instance been constructed using # the constructor (rather than having been deserialized). # # @return [ Array<Hash> | Array<BSON::Document> ] The sections of # payload type 1 or 0. # @api private field :sections, Sections Registry.register(OP_CODE, self) end end end
require 'active_support/core_ext/object/blank' module Hydramata module Works # Responsible for negotiating an object from persistence into memory module FromPersistence module_function def call(options = {}) pid = options.fetch(:pid) Hydramata.configuration.work_from_persistence_coordinator.call(pid: pid) end end end end
# encoding: utf-8 class AddIndexToppageContents < ActiveRecord::Migration def up add_index :toppage_contents, :recommend_recipe_id end def down remove_index :toppage_contents, :recommend_recipe_id end end
class Hotel < ApplicationRecord geocoded_by :address after_validation :geocode, if: :address_changed? # GEM PARANOIA acts_as_paranoid # END GEM PARANOIA #cloudiary photo has_attachment :photo # VALIDATIONS AND ASSOCIATIONS has_many :services, dependent: :destroy has_many :rooms, dependent: :destroy has_many :locations, dependent: :destroy has_many :stays, dependent: :destroy has_many :users, through: :stays has_many :messages, through: :stays belongs_to :user validates :name, :address, :city, presence: true validates :name, uniqueness: { scope: [:address, :city] } # END VALIDATIONS AND ASSOCIATIONS def can_manage?(current_user) self.user_id and self.user == current_user end end
class CreateDenominaciones < ActiveRecord::Migration def change create_table :denominaciones do |t| t.string :nombre t.text :descripcion, :historia, :descripcion_tipos_uva end end end
class Vendy attr_reader :transaction_balance, :cash_balance def initialize @transaction_balance = 0 @cash_balance = 0 end def insert(coin_value) @transaction_balance += coin_value end def issue_refund refund = @transaction_balance @transaction_balance = 0 return refund end def sufficient_funds?(item) return transaction_balance >= item.price end def purchase(item) if !sufficient_funds?(item) return "Insufficient Funds" elsif !item.has_stock? return "Out of Stock" else @transaction_balance -= item.price @cash_balance += item.price item.reduce_stock_count(1) issue_refund end end end
class Category < ActiveRecord::Base validates :name, presence: true has_many :categorizations has_many :items, through: :categorizations scope :main_categories, -> { where(name: %w(Breakfast Appetizers Lunch Dinner Dessert)) } scope :special_categories, -> { where.not(name: %w(Breakfast Appetizers Lunch Dinner Dessert)) } end
require File.join( File.dirname( __FILE__ ), "spec_helper" ) describe ProcessPool do before :each do @dummy_node = mock( "yutaro_node", :name => "yutaro_node" ) @ppool = ProcessPool.new end it "should dispatch a code block as a new sub-process" do Kernel.stub!( :fork ).and_yield.and_return( "PID" ) Process.should_receive( :waitpid2 ).with( "PID" ).and_return( [ "PID", status0 ] ) @ppool.dispatch( @dummy_node ) do | node | node.name.should == "yutaro_node" end @ppool.shutdown end it "should raise if sub-process exitted abnormally" do Kernel.stub!( :fork ).and_return( "PID" ) Process.should_receive( :waitpid2 ).with( "PID" ).and_return( [ "PID", status1 ] ) @ppool.dispatch( @dummy_node ) {} lambda do @ppool.shutdown end.should raise_error( RuntimeError ) end it "should ignore if ECHILD raised" do Kernel.stub!( :fork ).and_return( "PID" ) Process.stub!( :waitpid2 ).with( "PID" ).and_raise( Errno::ECHILD ) @ppool.dispatch( @dummy_node ) {} lambda do @ppool.shutdown end.should_not raise_error end it "should kill all sub-processes" do Kernel.stub!( :fork ).and_return( "PID1", "PID2", "PID3" ) Process.stub!( :waitpid2 ).and_return( [ "PID", status0 ] ) Process.should_receive( :kill ).with( "TERM", "PID1" ).ordered Process.should_receive( :kill ).with( "TERM", "PID2" ).ordered Process.should_receive( :kill ).with( "TERM", "PID3" ).ordered @ppool.dispatch( @dummy_node ) {} @ppool.dispatch( @dummy_node ) {} @ppool.dispatch( @dummy_node ) {} @ppool.killall end def status0 status = "STATUS" status.stub!( :exitstatus ).and_return( 0 ) status end def status1 status = "STATUS" status.stub!( :exitstatus ).and_return( 1 ) status end end ### Local variables: ### mode: Ruby ### coding: utf-8-unix ### indent-tabs-mode: nil ### End:
class Aluno < ActiveRecord::Base validates :nome, :data_nasc, :local_nasc, :mae, presence: true has_many :notas end
require 'base64' # Base Controller class Ng::V1::BaseController < ApplicationController before_action :authenticate_user private def authenticate_user basic = ActionController::HttpAuthentication::Basic email, password = basic.decode_credentials(request).split(':') render_unauthorized and return unless (@current_user = User.authenticated?(email, password)) end def authenticate_admin render json: { message: 'You are not Authorized' }, status: :forbidden unless @current_user.admin? end def render_unauthorized render json: { error_message: 'Email or Password is invalid' }, status: :unauthorized end end
class Bicycle attr_reader :color, :size, :style, :tire_width, :price include Discountable def initialize(input_options) @color = input_options[:color] @size = input_options[:size] @style = input_options[:style] @tire_width = input_options[:tire_width] @price = input_options[:price] end def show_info "This is a #{@size}, #{@color}, #{style} bike with #{tire_width} mm tires and costs $#{price}." end end
Given(/^I navigate to the login page with query string parameters=(.*)$/) do |query_string| puts 'Processing ' + query_string login_page_url = on(LoginPage).login_page_url @browser.goto(login_page_url + query_string) end When(/^I login with a user type of (.*)$/) do |user_type| perform_login(get_user_data(user_type)) end Then(/^I land on the url containing (.*)$/) do |destination_url| begin on(StatementsPage).wait_until do @browser.windows.last.url.include? destination_url end rescue puts 'Expected ' + @browser.windows.last.url + ' to contain ' + destination_url raise end end
class Auction attr_reader :items def initialize @items = [] end def add_item(item) @items << item end def item_names @items.map do |item| item.name end end def unpopular_items @items.find_all do |item| item.bids.empty? end end def potential_revenue @items.reduce(0) do |sum, item| current_high_bid = item.current_high_bid item.bids.each do |attendee, price| sum += current_high_bid end end end def bidders bidders_names = [] @items.each do |item| item.bids.each_key do |key| bidders_names << key.name end end bidders_names.uniq end def bidder_info bidder_info_hash = {} @items.each do |item| item.bids.each do |key, value| bidder_info_hash[key] = {} end end @items.each do |item| item.bids.each do |key, value| bidder_info_hash[key] = { budget: key.budget, items: [item] } end end bidder_info_hash end end
class Message < ApplicationRecord belongs_to :group belongs_to :user validates :body,presence: true validates :body, length: { maximum: 1000 } mount_uploader :image, ImageUploader end
require 'spec_helper' describe JobsController do fixtures :jobs, :job_templates, :job_steps let(:get_job_response) { { 'id' => '1234', 'stepsCompleted' => '1', 'status' => 'running' } } let(:create_response) { { 'id' => '1234' } } let(:fake_dray_client) do double(:fake_dray_client, get_job: get_job_response, create_job: create_response, delete_job: nil ) end before do allow(PanamaxAgent::Dray::Client).to receive(:new).and_return(fake_dray_client) end describe '#index' do it 'returns an array' do get :index, format: :json expect(JSON.parse(response.body)).to be_an Array end it 'includes a Total-Count header with the job count' do get :index, format: :json expect(response.headers['Total-Count']).to eq(1) end end describe '#show' do it 'returns a specific job' do get :show, id: Job.first.key, format: :json expect(response.body).to eq(JobSerializer.new(Job.first).to_json) end end describe '#create' do let(:new_job) { Job.new(job_template: job_templates(:cluster_job_template)) } before do allow(JobBuilder).to receive(:create).and_return(new_job) end it 'returns a job' do post :create, template_id: job_templates(:cluster_job_template).id, format: :json expect(response.body).to eq(JobSerializer.new(new_job).to_json) end it 'calls start_job on the job' do expect(new_job).to receive(:start_job) post :create, template_id: job_templates(:cluster_job_template).id, format: :json end end describe '#destroy' do let(:job) { Job.first } before do allow(Job).to receive(:find_by_key).with(Job.first.key).and_return(job) end it 'destroys the job model' do expect do delete :destroy, id: Job.first.key, format: :json end.to change(Job, :count).by(-1) end end describe '#log' do let(:log) { { 'lines' => [] } } before do allow_any_instance_of(Job).to receive(:log).with(3).and_return(log) end it 'returns the log data' do get :log, id: Job.first.key, index: 3, format: :json expect(response.body).to eq(log.to_json) end end end
require 'benchmark' # Returns true if the given char arg is a letter. def letter?(lookAhead) lookAhead =~ /[[:alpha:]]/ end # Finds all triangle words inside the given file. def triangle_words # Generates the triangle sequence where t(n) = 1/2(n)(n+1). # The first 10 triangle numbers are: # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55. triangle = Enumerator.new do |yielder| n = 1 loop do yielder << n * (n + 1) / 2 n += 1 end end # Initialize a new hash that returns false on invalid keys. lookup_table = Hash.new(false) # Put the first 1000 triangle numbers in our lookup table as keys. # This is probably overkill, but it's better to be safe than sorry lel # If accessed with a key that isn't a triangle, it returns false. 1000.times { lookup_table[triangle.next] = true } triangle_words = [] File.foreach("p042_words.txt", ",") do |word| # Get the values of the letters according to their position in the # alphabet, using the letter's ASCII value. word.upcase! # In case there are lowercase letters in the file. characters = word.chars.delete_if { |char| not letter?(char) } values = characters.map { |char| char.ord - 64 } triangle_words << word if lookup_table[values.inject(:+)] end return triangle_words end time = Benchmark.measure do puts "There are #{triangle_words.length} triangle words in the file" end puts "Time elapsed (in seconds): #{time}"
require 'rails_helper' RSpec.describe User, type: :model do it "validates presence of email" do user = User.new user.email = '' user.valid? expect(user.errors[:email]).to include("can't be blank") user.email = "test@test.com" user.valid? expect(user.errors[:email]).to_not include("can't be blank") end it "validates uniqueness of email" do User.create(email: "test@test.com", password: "123456") user = User.new(email: "test@test.com") user.valid? expect(user.errors[:email]).to include("has already been taken") end it "validates presence of password" do user = User.new user.password = "" user.valid? expect(user.errors[:password]).to include("can't be blank") user.password = "123456" user.valid? expect(user.errors[:password]).to_not include("can't be blank") end end
module DiscrepancyDetectors class SubscriberCount def self.get_discrepancies(channel_matrix:, normalized_channel:, account_email_subscriber_count:) result = [] existing_account_email_subscriber_count = channel_matrix[normalized_channel] unless existing_account_email_subscriber_count.nil? existing_email = existing_account_email_subscriber_count.account_email new_email = account_email_subscriber_count.account_email existing_subscriber_count = existing_account_email_subscriber_count.subscriber_count new_subscriber_count = account_email_subscriber_count.subscriber_count if (existing_email == new_email) && (existing_subscriber_count != new_subscriber_count) result = [existing_email] end end result end end class ChannelOwnership def self.get_discrepancies(channel_matrix:, normalized_channel:, account_email_subscriber_count:) result = [] existing_account_email_subscriber_count = channel_matrix[normalized_channel] unless existing_account_email_subscriber_count.nil? existing_email = existing_account_email_subscriber_count.account_email new_email = account_email_subscriber_count.account_email if existing_email != new_email result = [existing_email, new_email] end end result end end end
include_recipe 'rbenv::system' template '/etc/profile.d/rbenv.sh' do owner 'root' group 'root' mode '644' end
class EasyPageTemplateTab < ActiveRecord::Base belongs_to :page_template_definition, :class_name => "EasyPageTemplate", :foreign_key => 'page_template_id' acts_as_list scope :page_template_tabs, lambda { |page_template, entity_id| { :conditions => EasyPageTemplateTab.tab_condition(page_template.id, entity_id), :order => "#{EasyPageTemplateTab.table_name}.position"}} def self.tab_condition(page_template_id, entity_id) cond = "#{EasyPageTemplateTab.table_name}.page_template_id = #{page_template_id}" cond << (entity_id.blank? ? " AND #{EasyPageTemplateTab.table_name}.entity_id IS NULL" : " AND #{EasyPageTemplateTab.table_name}.entity_id = #{entity_id}") cond end private # Overrides acts_as_list - scope_condition def scope_condition EasyPageTemplateTab.tab_condition(self.page_template_id, self.entity_id) end end
require 'rails_helper' feature 'Linking structures to physical structures', :js do let!(:user) { create(:user) } let!(:audit) { create(:audit, user: user) } let!(:organization) do create(:organization, owner: user) end let!(:building_type) do create(:building_audit_strc_type, parent_structure_type: audit.audit_structure.audit_strc_type) end let!(:building) do create(:building, cloned: false, nickname: '201 South Street', wegowise_id: 42) end before do organization.buildings << building organization.save! sign_in visit audits_path click_audit audit.name end scenario 'with an existing building' do click_structure_type 'Building', action: 'Add' fill_in 'Name', with: 'My temporary building' click_button 'Create' click_structure_row 'My temporary building', action: 'Link' search_for 'foo' expect(page).to have_content 'No buildings found that match "foo".' search_for 'south' expect(page).to have_unchecked_field '201 South Street' choose '201 South Street' click_button 'Link' expect(page).to have_structure_row '201 South Street' end scenario 'is unavailable when the audit is locked' do audit.update(locked_by: user.id) visit current_path expect(page).to_not have_structure_action 'Link' end def search_for(query) fill_in 'q', with: query find(:css, 'button.js-submit-search').click end end
# encoding: utf-8 require File.join(File.dirname(__FILE__),'../lib/twitter_card') require 'spec_helper' describe TwitterCard do before(:each) do @twcard = TwitterCard.new end it "should have a name" do @twcard.title = "pepepe" @twcard.title.should == "pepepe" end it "should have a codename" do @twcard.description = "pepepe" @twcard.description.should == "pepepe" end it "should have a tagline" do @twcard.image_url = "pepepe" @twcard.image_url.should == "pepepe" end it "should have a description" do @twcard.site = "@peepepe" @twcard.site.should == "@peepepe" end it "should have a order" do @twcard.creator = "@peepepe" @twcard.creator.should == "@peepepe" end end
class InventoryItemPhoto < ApplicationRecord belongs_to :inventory_item belongs_to :photo end
require "minitest/autorun" require_relative "../scanner/scanner" class TestScanner < Minitest::Test def test_it_skips_whitespace scanner = Scheme::Scanner.new(" hello") first_token = scanner.get_next_token assert_equal first_token.type, :IDENT end def test_it_skips_comments input = %Q( ; Ignored.... hello ) scanner = Scheme::Scanner.new(input) first_token = scanner.get_next_token assert_equal first_token.type, :IDENT end def test_it_scans_strings_correctly scanner = Scheme::Scanner.new('"I am a string"') first_token = scanner.get_next_token assert_equal first_token.type, :STRING assert_equal first_token.get_string_val, "I am a string" end def test_it_detects_special_characters scanner = Scheme::Scanner.new("' ( ) .") assert_equal scanner.get_next_token.type, :QUOTE assert_equal scanner.get_next_token.type, :LPAREN assert_equal scanner.get_next_token.type, :RPAREN assert_equal scanner.get_next_token.type, :DOT end def test_it_detects_both_boolean_constants scanner = Scheme::Scanner.new("#f #t") assert_equal scanner.get_next_token.type, :FALSE assert_equal scanner.get_next_token.type, :TRUE end def test_it_scans_integers_correctly scanner = Scheme::Scanner.new("234") token = scanner.get_next_token assert_equal token.type, :INTEGER assert_equal token.get_integer_val, 234 end def test_it_scans_identifiers_correctly scanner = Scheme::Scanner.new("hello") token = scanner.get_next_token assert_equal token.type, :IDENT assert_equal token.get_name, "hello" end end
require "UnitTest" require "Proto_Auto_Call" class McallLEUserOptions attr_accessor :nb_calls, :dial_number, :call_duration end class Proto_Auto_Multi_Call_LE < UnitTest ##################################### # DEFAULT PARAMETERS # ##################################### @@DEFAULT_DIAL_NUMBER= "666" @@DEFAULT_NB_CALLS= 2 @@DEFAULT_CALL_DURATION= 4 ##################################### # TEST DESCRIPTION # ##################################### @@TEST_NAME = "Proto Auto Multi Call Light Edition Test" @@VERSION = "1.0" @@ENVIRONEMENT = "PROTO" @@TYPE = "AUTO" @@PREREQUISITE = "MS must be camped on Tester or Network" @@DESCRIPTION = "Performs N :nb_calls calls with the given call number :number. For each call the test records messages from API task to MMI task and updates a state machine with connected / disconnected state. The test compares this state with the expected one and gives a result. If one call fails the test fails." @@PARAMETERS=[ ["nb_calls","#{@@DEFAULT_NB_CALLS}","Number of calls to be performed."], ["dial_number","#{@@DEFAULT_DIAL_NUMBER}","Called phone number"], ["call_duration","#{@@DEFAULT_CALL_DURATION}","Duration of each call in seconds"] ] @@RESULTS ="Pass or Fail. If failed, you got a log of messages from API task to MMI task." @@EXAMPLE ="puts Proto_Auto_Multi_Call_LE.new( {:nb_calls=>12, number=>'112'} ).process <br /> Call emergency." @@AUTHOR ="Laurent" TestsHelp.addTestHelpEntry( @@TEST_NAME, @@VERSION, @@ENVIRONEMENT, @@TYPE, @@PREREQUISITE, @@PARAMETERS, @@DESCRIPTION, @@RESULTS, @@EXAMPLE, @@AUTHOR ) ##################################### # TEST DESCRIPTION END # ##################################### ##################################### # Private section # ##################################### private #Constants TIMEOUT_SIGNALING_ON = 10 TIMEOUT_MS_SYNC = 15 TIMEOUT_CALL_ESTABLISHED = 15 # Call Object. @myCall # userOptions. @userOptions def BuildParams(nb_calls,dial_number,call_duration) @userOptions.nb_calls = nb_calls @userOptions.dial_number = dial_number @userOptions.call_duration = call_duration end ##################################### # Public section # ##################################### public def initialize(params) # CAREFUL ! # Do not call the super method "initialize" since this test is not an embedded one ! # Call to a UnitTest method : # Intialize html report to be compatible with CoolWatcher. initializeReport # Initialize user options. @userOptions = McallLEUserOptions.new BuildParams( params[:nb_calls]|| @@DEFAULT_NB_CALLS, params[:dial_number]|| @@DEFAULT_DIAL_NUMBER, params[:call_duration]|| @@DEFAULT_CALL_DURATION) end def changeParams( params ) BuildParams( params[:nb_calls]|| @userOptions.nb_calls, params[:dial_number]|| @userOptions.dial_number, params[:call_duration]|| @@DEFAULT_CALL_DURATION) end def start @test_succeeded = true for cur_call in 1..@userOptions.nb_calls # Initialize, start a Call and register the log informations in call_log. #puts "Initiate MO call #%d ..." % cur_call @html_report<< "Initiate MO call #%d ..." % cur_call + "<br /> " @myCall = Proto_Auto_Call.new( {:timeout=>10, :start=>1, :number=>@userOptions.dial_number} ) @myCall.process if (@myCall.call_success == false) @test_succeeded = false #puts "MO call failed !" @html_report<< "MO call failed !" + "<br /> " @html_report<< @myCall.call_log break else # Wait for call_duration. sleep(@userOptions.call_duration) # Hang up #puts "...Hang up" @html_report<< "...Hang up" + "<br /> " @myCall = Proto_Auto_Call.new( {:timeout=>5, :start=>0} ) @myCall.process sleep(2) if (@myCall.call_success == false) @test_succeeded = false #puts "Hanging up call failed !" + "<br /> " @html_report<< "Hanging up call failed !" + "<br /> " @html_report<< @myCall.call_log break end end end end def process start results end def results super @html_report<< CoolTester.reportAddTitleResults if @test_succeeded == true @html_report<< "<font color='green'>"+" PASSED !"+"</font>" else @html_report<< "<font color='red'>"+" FAILED !"+"</font>" end return @html_report end end
# encoding: utf-8 require 'open-uri' require 'awesome_print' require 'nokogiri' require 'json' class SenScraper Fields = ["Nombre", "Entidad", "Partido", "Foto"] BaseURL = "http://www.senado.gob.mx/index.php?ver=int&mn=4&sm=10&id=SENADOR" def initialize len = 128 senadores = (1..len).map do |i| url = BaseURL.sub("SENADOR", i.to_s) doc = Nokogiri::HTML open(url) tds = doc.css 'td' data = {} tds.each do |td| if td.content.strip.match /.*?(Por|Lista)/ data["Entidad"] = td.content.split(" ").join(" ").sub("Por el estado de", "").strip end if td.content.strip.match /^Sen\./ data["Nombre"] = td.content.strip end imgs = doc.css "img" imgs.each do |img| src = img["src"] if src.match /senadores/ data["Foto"] = src end if src.match /cuerpo/ and src.index("lcom") == nil data["Partido"] = src.match(/img\/cuerpo\/(.+?)\./)[1] end end end coms = doc.css "td td td td" data["Comisiones"] = [] coms.each do |td| if td.content.match /.*?(\(Presidente\)|\(Secretario\)|\(Integrante\))/ data["Comisiones"] << td.content.gsub(" ", "") end end data end puts senadores.to_json end end SenScraper.new
# Create partial estimation table class CreatePartialEstimations < ActiveRecord::Migration[5.0] def change create_table :partial_estimations do |t| t.float :estimation t.timestamps end end end
require 'rails_helper' RSpec.describe "pages/about.html.erb", type: :view do it "have content Этапы проведения СП" do render expect(response.body).to match("Этапы проведения СП") end end
# frozen_string_literal: true # https://adventofcode.com/2019/day/2 require 'pry' require './boilerplate' require './intcode' def run_with(noun, verb) memory = input.split(',') memory[1] = noun memory[2] = verb program = Intcode.new(memory.join(',')) program.run(nil) program end def run(instructions) program = Intcode.new(instructions) program.run(nil) program end part 1 do assert_call_on(run("1,0,0,0,99"), [2,0,0,0,99] , :program) assert_call_on(run("2,3,0,3,99"), [2,3,0,6,99] , :program) assert_call_on(run("2,4,4,5,99,0"), [2,4,4,5,99,9801] , :program) assert_call_on(run("1,1,1,4,99,5,6,0,99"), [30,1,1,4,2,5,6,0,99] , :program) log_call_on(run_with(12, 2).memory, :[], 0) # 4576384 end part 2 do expected = 19690720 # there must be a non-brute force way to achieve this. pattern in the program # which is passed in perhaps? (0..99).each do |noun| (0..99).each do |verb| memory = run_with(noun, verb).program if memory[0] == expected puts " #{'-'.yellow} 100 * #{noun.to_s.green}(noun) + #{verb.to_s.green}(verb) = #{(100 * noun + verb).to_s.green}(answer)" return end end end end
class User < ActiveRecord::Base has_many :posts has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy has_many :passive_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy has_many :following, through: :active_relationships, source: :followed has_many :followers, through: :passive_relationships devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable validates_presence_of :username, :first_name def follow(other_user) active_relationships.create(followed_id: other_user.id) end def unfollow(other_user) active_relationships.find_by(followed_id: other_user.id).destroy end def following?(other_user) following.include?(other_user) end def get_followers followers.all end def get_following following.all end end
class TodosController < ApplicationController before_filter :authenticate_user! load_and_authorize_resource :except => [:create, :destroy] def index @todos=current_user.todos.order("position") # @todos=Todo.order("position").joins(:project) end def create @todo=Todo.create(todo_params) @todo.save respond_to do |format| format.html { redirect_to todos_url, notice: 'To do item was successfully created.' } format.js end authorize! :create, @todo end def show @todo = Todo.find(params[:id]) end def new @todo=Todo.create end def destroy @todo=Todo.find(params[:id]) authorize! :destroy, @todo @todo.destroy respond_to do |format| format.html { redirect_to projects_url, notice: 'project was removed' } format.js end #authorize! :destroy, @todo end def edit @todo = Todo.find(params[:id]) @deadline = @todo.deadline end def update #debugger @todo = Todo.find(params[:id]) @todo.update_attributes(todo_params) respond_to do |format| format.html { redirect_to todos_url, notice: 'Todo item was updated.' } format.js end end def sort params[:todo].each_with_index do |id, index| Todo.update_all({position: index+1}, {id: id}) end render nothing: true end def toggle_done @todo = Todo.find(params[:id]) if @todo.deadline @todo.deadline.toggle(:done) @todo.deadline.save else @todo.build_deadline @todo.deadline.toggle(:done) @todo.deadline.save end respond_to do |format| format.html { redirect_to todos_url, notice: 'Task was successfully updated.' } format.js end end private def force_request_format_to_html request.format = :html end def todo_params params.require(:todo).permit(:name, :description, :status, :position, :project_id, :project_name, deadline_attributes: [:id, :deadlineable_id, :deadlineable_type, :active, :date, :done]) end end
require 'spec_helper' describe V1::DashboardController do let(:user) { create(:user) } before do sign_in user end describe "GET 'index'" do before { get :index } it { should respond_with(:success) } it { should render_template(:dashboard) } end end
# **************************************************************************** # # Copyright (c) Microsoft Corporation. # # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of this distribution. If # you cannot locate the Apache License, Version 2.0, please send an email to # ironruby@microsoft.com. By using this source code in any fashion, you are agreeing to be bound # by the terms of the Apache License, Version 2.0. # # You must not remove this notice, or any other, from this software. # # # **************************************************************************** # status: complete require '../../util/assert.rb' # access const from singleton class class C100 S101 = 1 class NC S102 = 2 end module NM S103 = 3 end end x = C100.new singleton = class << x S111 = 11 class NC S112 = 12 end module NM S113 = 13 end def self::check assert_raise(NameError) { C100::S111 } assert_raise(NameError) { NC::S102 } assert_raise(NameError) { C100::NC::S112 } assert_raise(NameError) { NM::S103 } assert_raise(NameError) { C100::NM::S113} [ S101, self::S101, C100::S101, S111, self::S111, C100::NC::S102, NC::S112, self::NC::S112, C100::NM::S103, NM::S113, self::NM::S113, ] end self end assert_equal(singleton::S101, 1) assert_raise(NameError) { singleton::NC::S102 } assert_raise(NameError) { singleton::NM::S103 } assert_equal(singleton::S111, 11) assert_equal(singleton::NC::S112, 12) assert_equal(singleton::NM::S113, 13) assert_equal(singleton::check, [1, 1, 1, 11, 11, 2, 12, 12, 3, 13, 13]) ## class C200 S101 = 1 def C200::m1; 1; end def m2; 2; end end singleton = class << C200 S111 = 11 def C200::m3; 3; end def m4; 4; end def self::m5; 5; end self end assert_raise(NameError) { singleton::S101 } assert_equal(singleton::S111, 11) assert_raise(NoMethodError) { singleton::m3 } assert_raise(TypeError) { singleton.new } #.m4 assert_equal(singleton::m5, 5)