text
stringlengths
10
2.61M
class AddActivitiesRefToSteps < ActiveRecord::Migration[5.2] def change remove_column :steps, :activity_id add_reference :steps, :activity end end
class Api::V1::CausesController < Api::V1::ApiController def index current_page = causes.page(page_number).per(page_size) render json: current_page end def create current_user.causes = Cause.find(params[:id]) render json: current_user.causes, status: :created rescue ActiveRecord::ActiveRecordError render json: {}, status: :not_found end private def causes return Cause.ransack(params[:search]).result if params[:search].present? Cause end def page_size params[:page].try(:[], :size) || 20 end def page_number params[:page].try(:[], :number) end end
ActionController::Routing::Routes.draw do |map| map.devise_for :users map.root :controller => :meetings, :action => :index map.resources :meetings end
# A grid that overrides the `get_data` endpoint in order to send a command to the client class GridWithFeedbackOnDataLoad < Netzke::Basepack::Grid def configure(c) super c.model = 'Book' end endpoint :server_read do |params,this| super(params,this) this.netzke_feedback "Data loaded!" end end
# Author: Jim Noble # jimnoble@xjjz.co.uk # # Anagramalam.rb # # A program that takes a list of words and outputs an array of anagram # arrays # class Anagramalam @longest_word @input @anagrams @output # * Find the longest word in the dictionary. # # * Create an array of arrays, one for every possible length of word # plus one, so that a word's length can act as its index. # # * Add each word in the dictionary to an array using word length as # an index. # def initialize(words) @longest_word = 0 IO.foreach(words) do |w| if (w.chomp.length > @longest_word) @longest_word = w.length end end @input = Array.new(@longest_word + 1) {Array.new} IO.foreach(words) do |w| w.chomp! @input[w.length] << w end combine_anagrams end # * Take a word and turn it into a lowercase alphabetically sorted symbol. def make_hash_key(str) str.downcase.chars.sort.join.to_sym end # * Create a hash. # * Create lowercase alphabetically sorted word symbols from each word and use them as hash keys. # * Collect anagrams in arrays referenced by these keys. # * Store the arrays in the output array. def combine_anagrams @anagrams = Hash.new @input.each do |a| a.each do |str| key = make_hash_key(str) if @anagrams.has_key?(key) @anagrams[key] << str else @anagrams[key] = Array.new << str end end end @output = @anagrams.values end def print_array @output.each {|a| puts a.to_s} end def print_hash @anagrams.each {|a| puts a.to_s} end # * Print the word or words with the most anagrams in the dictionary def print_most_interesting most_interesting = 0 @output.each do |a| if a.length > most_interesting then most_interesting = a.length end end @output.each do |a| if a.length == most_interesting then puts a.to_s end end end # * Don't bother printing words without anagrams. def print_only_anagrams @output.each do |a| if a.length > 1 then puts a.to_s end end end end
require 'rails_helper' RSpec.describe Site, type: :model do before { @site = build(:site) } subject { @site } it { should respond_to(:name) } it { should respond_to(:address) } it { should be_valid } describe 'when name is not present' do before { @site.name = ' ' } it { should_not be_valid } end describe 'when name is too long' do before { @site.name = 'a' * 16 } it { should_not be_valid } end describe 'when name is too short' do before { @site.name = 'a' } it { should_not be_valid } end describe 'when address is not present' do before { @site.address = ' ' } it { should_not be_valid } end describe 'when address is too long' do before { @site.address = 'a' * 254 } it { should_not be_valid } end describe 'when address is not correct' do before { @site.address = 'asdf' } it { should_not be_valid } end describe 'when address is correct' do before { @site.address = 'http://google.com' } it { should be_valid } end describe 'when site name is already taken' do before do site_with_same_name = @site.dup site_with_same_name.name = @site.name.upcase site_with_same_name.save end it { should_not be_valid } end end
class AddScoreAndResultToUser < ActiveRecord::Migration def change add_column :users, :score, :float add_column :users, :result, :string end end
class RestaurantMailer < ActionMailer::Base default from: 'Happy Dining <admin@happydining.fr>' def new_reservation reservation, email @reservation = reservation @time = reservation.time.strftime("%d/%m/%Y, à %H:%M") @user = reservation.user @phone = reservation.phone @user_contribution = @reservation.user_contribution @restaurant = reservation.restaurant mail to: email, subject: "Nouvelle réservation de la part de Happy Dining" end def reservation_validation(booking_name, email) @booking_name = booking_name mail to: email, subject: "montant de l'addition" end def invoice_email invoice, email params = {} params[:start_date] = invoice.start_date params[:end_date] = invoice.end_date params[:restaurant_id] = invoice.restaurant_id params[:commission_only] = invoice.commission_only @invoice = Restaurant.calculate_information_for_invoice params mail to: email, subject: "Happy Dining Facture #{invoice.start_date.to_date.strftime("%d/%m/%Y")} à #{invoice.end_date.to_date.strftime("%d/%m/%Y")}" end end
class Roadtrip < ActiveRecord::Base #attr_accessible :title belongs_to :user validates :title, :presence => true, :length => { :maximum => 140 } validates :user_id, :presence => true end
class Post < ApplicationRecord has_many :comments belongs_to :user has_attached_file :image, styles: { large: '600x 600>', medium: '300x300>', thumb: '150x150#' } validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/ def self.search(search) if search where('title LIKE ?', "%#{search}%") else unscoped end end end
FactoryGirl.define do factory :trivia, :class => 'Trivia' do sequence(:question) {|n| "Question #{n}"} category { build(:category) } trait :with_options do options { build_list :trivia_option, 3 } correct_option { options.first } end end end
# frozen_string_literal: true class Permission < ApplicationRecord belongs_to :role belongs_to :operation end
class TwoBucket class Error < StandardError def initalize(msg = "Source cannot be empty while other is full !") super end end class Bucket attr_accessor :quantity, :size, :name def initialize(size, name) @size = size @name = name @quantity = 0 end def full? @quantity == @size end def empty? @quantity == 0 end def fill! @quantity = @size end def empty! @quantity = 0 end def space_left @size - @quantity end def has_free_space? @size > @quantity end def pour_into(other) if other.space_left >= @quantity other.quantity += @quantity empty! else @quantity -= other.space_left other.fill! end end end def initialize(size_1, size_2, target, source) b1 = Bucket.new(size_1, "one") b2 = Bucket.new(size_2, "two") @source = source == "one" ? b1 : b2 @other = source == "one" ? b2 : b1 @source.fill! @target = target @counter = 1 @has_computed_moves = false end def moves # No need to put in the loop since this is an edge case # that can be detected from the beginning fill_other! if other_is_same_size_as_target? while target_not_reached? check_rule! if other_is_full? empty_other! elsif can_pour_from_source? pour_source_into_other! elsif source_has_free_space? fill_source! else raise Error.new("No action available !") end @counter += 1 end @has_computed_moves = true @counter end def goal_bucket raise Error.new("Must call the #moves method first") unless @has_computed_moves [@source, @other].find { _1.quantity == @target }.name end def other_bucket raise Error.new("Must call the #moves method first") unless @has_computed_moves [@source, @other].find { _1.quantity != @target }.quantity end private def can_pour_from_source? source_not_empty? && other_has_free_space? && rule_allows_pouring? end def check_rule! raise Error if @source.empty? && @other.full? end def debug! puts "Source".ljust(15) + "|" + "Other".rjust(10) puts "---------------------------------" puts "Size:".ljust(14) + @source.size.to_s + "|" + @other.size.to_s puts "Quantity".ljust(14) + @source.quantity.to_s + "|" + @other.quantity.to_s puts end def empty_other! @other.empty! end def fill_other! @other.fill! @counter += 1 end def fill_source! @source.fill! end def other_is_full? @other.full? end def other_has_free_space? @other.space_left > 0 end def pour_source_into_other! @source.pour_into(@other) end def rule_allows_pouring? @other.space_left != @source.quantity end def source_has_free_space? @source.space_left > 0 end def source_not_empty? !@source.empty? end def target_not_reached? @source.quantity != @target && @other.quantity != @target end def other_is_same_size_as_target? @other.size == @target && @other.empty? end end
# encoding: utf-8 describe Faceter::Functions, ".ungroup" do let(:arguments) { [:ungroup, :baz, Selector.new(options)] } it_behaves_like :transforming_immutable_data do let(:options) { {} } let(:input) do [{ qux: :QUX, baz: [{ foo: :FOO, bar: :FOO }, { foo: :BAR, bar: :BAR }] }] end let(:output) do [{ qux: :QUX, foo: :FOO, bar: :FOO }, { qux: :QUX, foo: :BAR, bar: :BAR }] end end it_behaves_like :transforming_immutable_data do let(:options) { { only: [:foo, :bar] } } let(:input) do [{ qux: :QUX, baz: [{ foo: :FOO, bar: :FOO }, { foo: :BAR, bar: :BAR }] }] end let(:output) do [{ qux: :QUX, foo: :FOO, bar: :FOO }, { qux: :QUX, foo: :BAR, bar: :BAR }] end end it_behaves_like :transforming_immutable_data do let(:options) { { only: :foo } } let(:input) do [{ qux: :QUX, baz: [{ foo: :FOO, bar: :FOO }, { foo: :BAR, bar: :BAR }] }] end let(:output) do [ { qux: :QUX, foo: :FOO, baz: [{ bar: :FOO }] }, { qux: :QUX, foo: :BAR, baz: [{ bar: :BAR }] } ] end end it_behaves_like :transforming_immutable_data do let(:options) { { only: :foo } } let(:input) do [{ qux: :QUX, baz: [{ foo: :FOO, bar: :FOO }, { foo: :FOO, bar: :BAR }] }] end let(:output) do [{ qux: :QUX, foo: :FOO, baz: [{ bar: :FOO }, { bar: :BAR }] }] end end it_behaves_like :transforming_immutable_data do let(:options) { { only: [:foo, :bar] } } let(:input) do [ { qux: :QUX, foo: :QUX, baz: [{ foo: :FOO, bar: :FOO }, { foo: :BAR, bar: :BAR }] } ] end let(:output) do [{ qux: :QUX, foo: :FOO, bar: :FOO }, { qux: :QUX, foo: :BAR, bar: :BAR }] end end it_behaves_like :transforming_immutable_data do let(:options) { {} } let(:input) do [{ qux: :QUX, baz: [] }] end let(:output) do [{ qux: :QUX }] end end end # describe Faceter::Functions.ungroup
require 'rails_helper' describe AuditFieldsController do describe '#index' do let!(:field1) do create(:audit_field, name: 'first field', value_type: 'integer') end let!(:field2) do create(:audit_field, name: 'second field', value_type: 'picker') end let!(:enumeration1) do create(:field_enumeration, audit_field: field2, value: 'option1', display_order: 1) end let!(:enumeration2) do create(:field_enumeration, audit_field: field2, value: 'option2', display_order: 2) end it 'responds with a success status code without wegowise_id set' do get :index expect(response.status).to eq(200) end it 'returns a list of available fields' do expect(AuditField).to receive(:uniq) .and_return(double(order: [field1, field2])) get :index, wegowise_id: 3 expect(JSON.parse(response.body)['audit_fields']) .to eq([{'name' => 'first field', 'api_name' => 'first_field', 'value_type' => 'integer', 'options' => [] }, {'name' => 'second field', 'api_name' => 'second_field', 'value_type' => 'picker', 'options' => %w[option1 option2] }]) end end end
require 'simplecov' SimpleCov.start 'rails' do add_filter '/channels/' add_filter '/mailers/' end SimpleCov.minimum_coverage 85 require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' require 'vcr' ENV['RAILS_ENV'] = 'test' OmniAuth.config.test_mode = true VCR.configure do |config| config.cassette_library_dir = 'test/fixtures/vcr_cassettes' config.hook_into :webmock end class ActiveSupport::TestCase include FactoryBot::Syntax::Methods def mock_bnet_omniauth(uid:, battletag:) OmniAuth.config.mock_auth[:bnet] = OmniAuth::AuthHash.new( provider: 'bnet', uid: uid, info: { battletag: battletag } ) end def sign_in_as(account) mock_bnet_omniauth(uid: account.uid, battletag: account.battletag) post '/users/auth/bnet/callback', params: { battletag: account.battletag } end def sign_out delete logout_path end end
# == Schema Information # # Table name: pictures # # id :integer not null, primary key # slug :string # description :string default("") # lesson_id :integer # created_at :datetime not null # updated_at :datetime not null # file_file_name :string # file_content_type :string # file_file_size :integer # file_updated_at :datetime # class Picture < ActiveRecord::Base include Sluggable belongs_to :lesson validates :lesson, presence: true validates :description, length: { maximum: 250 } has_attached_file :file, { url: "/system/pictures/files/:hash.:extension", hash_secret: "S68_uA3aUVX5SXFBn7UCaL1L-O89uoi2ASzkY3XdVZHQ-1-r85pH0888Vk-3", styles: { large: '1200x1200>', big: '800x800>', medium: '600x600>', small: '200x200>' } } validates_attachment :file, presence: true, content_type: { content_type: /\Aimage\/.*\Z/ } private def method_missing(method, *arguments, &block) self.file.send(method, *arguments, &block) rescue super end def respond_to_missing?(method, include_private=false) file.respond_to?(method, include_private) || super end end
class EloAdjustment def initialize(victor:, loser:, matches:) @victor = victor @loser = loser @victor_player = Elo::Player.new(rating: victor.elo, games_played: matches.merge(victor.matches).count) @loser_player = Elo::Player.new(rating: loser.elo, games_played: matches.merge(loser.matches).count) end def adjust! calculate victor.elo = victor_player.rating loser.elo = loser_player.rating victor.save! loser.save! end def victor_elo_change calculate victor_player.rating - victor.elo end def loser_elo_change calculate loser_player.rating - loser.elo end private attr_reader :victor, :loser, :victor_player, :loser_player def calculate @calculate ||= victor_player.wins_from(loser_player) end end
## -*- Ruby -*- ## XML::DOM::Visitor ## 1998 by yoshidam ## ## Oct 23, 1998 yoshidam Fix each ## =begin = XML::DOM::Visitor == Module XML =end module XML =begin == Module XML::DOM (XML::SimpleTree) =end module DOM =begin == Class XML::DOM::Visitor Skelton class of Visitor. You can override the following methods and implement the other "visit_TYPE" methods. You should implement some "visit_name_NAME" methods and "method_missing" method for accept_name. =end ## Skeleton visitor class Visitor ## You can override the following methods and implement the other ## "visit_TYPE" methods. ## You should implement some "visit_name_NAME" methods and ## "method_missing" method for accept_name. =begin === Methods --- Visitor#visit_Document(grove, *rest) callback method. =end def visit_Document(grove, *rest) grove.children_accept(self, *rest) end =begin --- Visitor#visit_Element(element, *rest) callback method. =end def visit_Element(element, *rest) element.children_accept(self, *rest) end =begin --- Visitor#visit_Text(text, *rest) callback method. =end def visit_Text(text, *rest) end =begin --- Visitor#visit_CDATASection(text, *rest) callback method. =end def visit_CDATASection(text, *rest) end =begin --- Visitor#visit_Comment(comment, *rest) callback method. =end def visit_Comment(comment, *rest) end =begin --- Visitor#visit_ProcessingInstruction(pi, *rest) callback method. =end def visit_ProcessingInstruction(pi, *rest) end end =begin == Class XML::DOM::Node XML::Grove::Visitor like interfaces. =end class Node =begin --- Node#accept(visitor, *rest) call back visit_* method. =end ## XML::Grove::Visitor like interfaces def accept(visitor, *rest) typename = self.class.to_s.sub(/.*?([^:]+)$/, '\1') visitor.send("visit_" + typename, self, *rest) end =begin --- Node#accept_name(visitor, *rest) call back visit_name_* method. =end def accept_name(visitor, *rest) if nodeType == ELEMENT_NODE name_method = "visit_name_" + nodeName visitor.send(name_method, self, *rest) else self.accept(visitor, *rest) end end =begin --- Node#children_accept(visitor, *rest) for each children, call back visit_* methods. =end def children_accept(visitor, *rest) ret = [] @children && @children.each { |node| ret.push(node.accept(visitor, *rest)) } ret end =begin --- Node#children_accept_name(visitor, *rest) for each children, call back visit_name_* method. =end def children_accept_name(visitor, *rest) ret = [] @children && @children.each { |node| ret.push(node.accept_name(visitor, *rest)) } ret end =begin --- Node#each iterator interface. =end ## Iterator interface include Enumerable def each sibstack = [] siblings = [ self ] while true if siblings.length == 0 break if sibstack.length == 0 siblings = sibstack.pop next end node = siblings.shift yield(node) children = node.childNodes if !children.nil? sibstack.push(siblings) siblings = children.to_a.dup end end end end end end
class Service < ActiveRecord::Base belongs_to :company validates_presence_of :name, :company_id, :price_in_cents validates_presence_of :duration, :if => :duration_required? validates_presence_of :capacity validates_numericality_of :capacity validates_inclusion_of :duration, :in => 1..(7.days), :message => "must be a non-zero reasonable value", :if => :duration_required? validates_inclusion_of :mark_as, :in => %w(free work), :message => "can only be scheduled as free or work" validates_uniqueness_of :name, :scope => :company_id has_many :appointments has_many :service_providers, :dependent => :destroy has_many :user_providers, :through => :service_providers, :source => :provider, :source_type => 'User', :after_add => :after_add_provider, :after_remove => :after_remove_provider has_many :resource_providers, :through => :service_providers, :source => :provider, :source_type => 'Resource', :after_add => :after_add_provider, :after_remove => :after_remove_provider before_save :titleize_name # name constants AVAILABLE = "Available" UNAVAILABLE = "Unavailable" # find services by mark as type Appointment::MARK_AS_TYPES.each { |s| named_scope s, :conditions => {:mark_as => s} } # find services with at least 1 service provider named_scope :with_providers, { :conditions => ["providers_count > 0"] } named_scope :with_provider, lambda { |pid| {:joins => :service_providers, :conditions => ["services.providers_count > 0 and service_providers.provider_id = ?", pid]} } def self.nothing(options={}) r = Service.new do |o| o.name = options[:name] || "" o.send(:id=, 0) o.duration = 0 o.allow_custom_duration = false end end # return true if its the special service 'nothing' def nothing? self.id == 0 end def tableize self.class.to_s.tableize end # Virtual attribute for use in the UI - entering the lenght of the service is done in minutes rather than seconds. This converts in both directions def duration_in_minutes (self.duration.to_i / 60).to_i end def duration_in_minutes=(duration_in_minutes) duration_will_change! self.duration = duration_in_minutes.to_i.minutes end # find all polymorphic providers through the company_providers collection def providers self.service_providers(:include => :provider).collect(&:provider) end # return true if the service is provided by the specfied provider def provided_by?(o) self.providers.include?(o) end def free? self.mark_as == Appointment::FREE end def work? self.mark_as == Appointment::WORK end private # durations are required for work services def duration_required? return true if work? false end def titleize_name self.name = self.name.titleize end def after_add_provider(provider) end def after_remove_provider(provider) # the decrement counter cache doesn't work, so decrement here Service.decrement_counter(:providers_count, self.id) if provider end end
module Octopress module Date # Returns a datetime if the input is a string def datetime(date) if date.class == String date = Time.parse(date) end date end # Returns an ordidinal date eg July 22 2007 -> July 22nd 2007 def ordinalize(date) date = datetime(date) "#{date.strftime('%b')} #{ordinal(date.strftime('%e').to_i)}, #{date.strftime('%Y')}" end # Returns an ordinal number. 13 -> 13th, 21 -> 21st etc. def ordinal(number) if (11..13).include?(number.to_i % 100) "#{number}<span>th</span>" else case number.to_i % 10 when 1; "#{number}<span>st</span>" when 2; "#{number}<span>nd</span>" when 3; "#{number}<span>rd</span>" else "#{number}<span>th</span>" end end end end end module Jekyll class Post include Octopress::Date attr_accessor :date_formatted # Convert this post into a Hash for use in Liquid templates. # # Returns <Hash> def to_liquid format = self.site.config['date_format'] if format.nil? || format.empty? || format == "ordinal" date_formatted = ordinalize(self.date) else date_formatted = self.date.strftime(format) end self.data.deep_merge({ "title" => self.data["title"] || self.slug.split('-').select {|w| w.capitalize! || w }.join(' '), "url" => self.url, "date" => self.date, # Monkey patch "date_formatted" => date_formatted, "id" => self.id, "categories" => self.categories, "next" => self.next, "previous" => self.previous, "tags" => self.tags, "content" => self.content }) end end end
# -*- mode: ruby -*- # vi: set ft=ruby : # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. Vagrant.configure("2") do |config| # The most common configuration options are documented and commented below. # For a complete reference, please see the online documentation at # https://docs.vagrantup.com. # Every Vagrant development environment requires a box. You can search for # boxes at https://vagrantcloud.com/search. config.vm.box = "centos/7" config.vm.provider :libvirt do |libvirt,override| libvirt.host = "192.168.1.12" libvirt.connect_via_ssh = true libvirt.username = "aylingw" #libvirt.password - leave blank, because using SSH to login with private key #libvirt.id_ssh_key_file - leave blank which assumes the default ${HOME}/.ssh/id_rsa libvirt.cpus = 1 libvirt.memory = 1024 libvirt.machine_virtual_size = 8 libvirt.autostart = true #libvirt.mgmt_attach = false #override.ssh.proxy_command = "ssh server -l vagrant nc -q0 %h %p" end config.vm.define :test_vm do |test_vm| test_vm.vm.box = "centos/7" #test.vm.hostname = "test.wozitech.local" test_vm.vm.network :private_network, ip: "10.0.0.10", libvirt__network_name: "DMZ", libvirt__netmask: "255.255.255.0", nictype: "virtio", libvirt__domain_name: "wozitech.local" test_vm.vm.provider :libvirt do |domain| domain.memory = 2048 #domain.storage :file, :size => "20G", :type => "qcow2" end test_vm.vm.provision "ansible" do |ansible| ansible.playbook = "playbook.yml" end end end
require 'formula' class Cdrtools < Formula homepage 'http://cdrecord.org/' stable do url "https://downloads.sourceforge.net/project/cdrtools/cdrtools-3.00.tar.bz2" bottle do sha1 "497614205a68d26bcbefce88c37cbebd9e573202" => :yosemite sha1 "d5041283713c290cad78f426a277d376a9e90c49" => :mavericks sha1 "434f1296db4fb7c082bed1ba25600322c8f31c78" => :mountain_lion end sha1 "6464844d6b936d4f43ee98a04d637cd91131de4e" patch :p0 do url "https://trac.macports.org/export/104091/trunk/dports/sysutils/cdrtools/files/patch-include_schily_sha2.h" sha1 "6c2c06b7546face6dd58c3fb39484b9120e3e1ca" end end devel do url "https://downloads.sourceforge.net/project/cdrtools/alpha/cdrtools-3.01a27.tar.bz2" version "3.01~a27" sha1 "cd923377bd7ef15a08aa3bb1aff4e6604c7be7cd" patch :p0, :DATA end depends_on 'smake' => :build conflicts_with 'dvdrtools', :because => 'both dvdrtools and cdrtools install binaries by the same name' def install system "smake", "INS_BASE=#{prefix}", "INS_RBASE=#{prefix}", "install" # cdrtools tries to install some generic smake headers, libraries and # manpages, which conflict with the copies installed by smake itself (include/"schily").rmtree %w[libschily.a libdeflt.a libfind.a].each do |file| (lib/file).unlink end (lib/"profiled").rmtree man5.rmtree end test do system "#{bin}/cdrecord", "-version" end end __END__ --- include/schily/sha2.h.orig 2010-08-27 10:41:30.000000000 +0000 +++ include/schily/sha2.h @@ -104,10 +104,12 @@ #ifdef HAVE_LONGLONG extern void SHA384Init __PR((SHA2_CTX *)); +#ifndef HAVE_PRAGMA_WEAK extern void SHA384Transform __PR((UInt64_t state[8], const UInt8_t [SHA384_BLOCK_LENGTH])); extern void SHA384Update __PR((SHA2_CTX *, const UInt8_t *, size_t)); extern void SHA384Pad __PR((SHA2_CTX *)); +#endif extern void SHA384Final __PR((UInt8_t [SHA384_DIGEST_LENGTH], SHA2_CTX *)); extern char *SHA384End __PR((SHA2_CTX *, char *));
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable belongs_to :coloc has_many :carotte_cards has_many :tasks_to_do, -> { where(status: 'To be done') }, class_name: 'UserTask' has_many :user_tasks, dependent: :destroy has_many :tasks, through: :user_tasks has_many :consommations, dependent: :destroy has_many :fun_cards, through: :consommations end
# frozen_string_literal: true # This is a prepend intended to be used with AttachFilesToWorkJob. # Removes each queued file after it is added to the work. module PrependedJobs::WithQueuedFiles def perform(work, uploaded_files) super QueuedFile.where(work_id: work.id).destroy_all end end
class FavoritesController < ApplicationController before_action :authenticate_user_admin! before_action :set_shop, only: %i[create destroy] def index if user_signed_in? @shops = current_user .favorite_shops .order('favorites.updated_at DESC') .page(params[:page]) .per(SHOP_PER) @shop_count = current_user.favorite_shops.count elsif admin_signed_in? @shops = current_admin .favorite_shops .order('favorites.updated_at DESC') .page(params[:page]) .per(SHOP_PER) @shop_count = current_admin.favorite_shops.count end end def create if user_signed_in? @favorite = Favorite.create(user_id: current_user.id, shop_id: @shop.id) elsif admin_signed_in? @favorite = Favorite.create(admin_id: current_admin.id, shop_id: @shop.id) end end def destroy if user_signed_in? @favorite = Favorite.find_by(user_id: current_user.id, shop_id: @shop.id) @favorite.destroy elsif admin_signed_in? @favorite = Favorite.find_by(admin_id: current_admin.id, shop_id: @shop.id) @favorite.destroy end end private def set_shop @shop = Shop.find(params[:shop_id]) end end
#-- # Copyright (c) 2007 by Mike Mondragon (mikemondragon@gmail.com) # # Please see the README.txt file for licensing information. #++ module Hurl PATH = File.expand_path("#{File.dirname(__FILE__)}/../") ## # we are defining our own Hurl#render rather than Hurl::Views#layout # so that we can support Erb rendering def render(kind = :html, template = nil) template = /([_,-,0-9,a-z,A-Z]+)/.match(env.PATH_INFO)[1] rescue "index" if template.nil? @title = "hurl it" @base_url = base_url @content = ERB.new(IO.read("#{PATH}/templates/#{template}.#{kind}.erb") ).result(binding) # if one has google analytics javascript put it in the urchin.txt file @urchin = IO.read("#{PATH}/templates/urchin.txt") rescue '' if kind == :html ERB.new(IO.read("#{PATH}/templates/layout.#{kind}.erb")).result(binding) end end =begin Normally Hurl::Views and a layout would be here =end
describe Metacrunch::ULBD::Transformations::AlephMabNormalization::AddIsbn do transformation = transformation_factory(described_class) context "secondary forms isbns" do context "for a RDA record" do subject do mab_xml = mab_xml_builder do datafield("649", ind2: "1") do subfield("z", "3-8155-0186-5") end datafield("649", ind2: "1") do subfield("z", "3-930673-19-3") subfield("z", "978-3-8273-2478-8") end end transformation.call(mab_xml)["isbn"] end it { is_expected.to eq(["3-8155-0186-5", "3-930673-19-3", "978-3-8273-2478-8"]) } end end define_field_test '001705215', isbn: ["978-3-89710-549-2", "978-3-374-03418-5", "978-3-89710-549-5"] end
class Exercise < ActiveRecord::Base has_many :exercise_workouts has_many :workouts, :through => :exercise_workouts, dependent: :destroy def name_of_exercise "#{name}" end end
log 'Installing log4j' do level :info end # Define variables for attributes account_username = node['vnc']['account_username']; account_home = "/home/#{account_username}"; jar_filename = 'log4j-1.2.17.jar' tarball_filename= 'log4j.tar.gz' tarball_filepath = "#{Chef::Config['file_cache_path']}/#{tarball_filename}" selenium_home = "#{account_home}/selenium" log4j_properties_file = 'hub.log4j.properties' # Create selenium folder directory selenium_home do owner account_username group account_username mode 00755 recursive true action :create end # Download tarball remote_file tarball_filepath do source node['selenium_node']['log4j']['url'] owner 'root' group 'root' mode 00644 end # Extract and place the jar bash 'extract_jar' do cwd ::File.dirname(selenium_home) code <<-EOH tar xzf #{tarball_filepath} -C #{selenium_home} pushd #{selenium_home} mv */#{jar_filename} . chown #{account_username}:#{account_username} #{jar_filename} EOH not_if { ::File.exists?("#{selenium_home}/#{jar_filename}") } end # http://www.devopsnotes.com/2012/02/how-to-write-good-chef-cookbook.html log 'Finished installing log4j.' do level :info end
class DishesController < ApplicationController def index @dishes = Dish.all.page(params[:page]) end end
# frozen_string_literal: true class CommonComponents::EditButton < ViewComponent::Base def initialize(identifier:, path:, tooltip_content:) @identifier = identifier @path = path @tooltip_content = tooltip_content end end
require_relative '../spec_helper' describe InvestmentEntry do before(:each) do @investment_entry = InvestmentEntry.new # this enables us to use the same piece of code inside our # test. So I dont have to create a new cart everytime inside # my it blocks end describe 'associations' do it 'belongs to a user' do @investment_entry = InvestmentEntry.create user = User.create(:username => "test 123", :email => "test123@aol.com", :password => "test") user.investment_entries << @investment_entry expect(@investment_entry.user).to eq(user) end end end
$LOAD_PATH.unshift(File.expand_path('../', __FILE__)) require 'spec_helper' require 'netlink' class TestAttribute < Netlink::Attribute::Base def encode_value(value) value end def decode_value(raw_value) raw_value end end describe Netlink::Attribute::Base do describe '#initialize' do it 'should allow users to specify any of {:type, :len, :value}' do attr = TestAttribute.new(:type => 2, :len => 8, :value => "HI") attr.header.type.should == 2 attr.header.len.should == 8 attr.value.should == "HI" end end describe '#write' do it 'should update the len header field to reflect the encoded value' do attr = TestAttribute.new(:value => "HI") attr.header.len.should == 4 # Calls into write w/ StringIO attr.encode attr.header.len.should == attr.header.num_bytes + attr.value.length end it 'should pad the output on a 32bit boundary' do attr = TestAttribute.new(:value => "HI") encoded = attr.encode encoded.length.should == 8 end end describe '#read' do it 'should decode encoded attributes' do attr = TestAttribute.new(:value => "HI", :type => 5) encoded = attr.encode # Calls into read w/ StringIO dec_attr = TestAttribute.decode(encoded) dec_attr.header.type == attr.header.type dec_attr.header.len == attr.header.type dec_attr.value == attr.value end it 'should skip padding bytes' do attr = TestAttribute.new(:value => "HI", :type => 5) io = StringIO.new(attr.encode) attr.header.len.should == 6 TestAttribute.read(io) io.pos.should == 8 end end end describe Netlink::Attribute::String do describe '#encode_value' do it 'should encode the value as a binary string' do encoded = Netlink::Attribute::String.new.encode_value("HI") encoded.should == "HI" end end describe '#decode_value' do it 'should decode the value as a binary string' do decoded = Netlink::Attribute::String.new.decode_value("HI\x00") decoded.should == "HI\x00" end end end describe Netlink::Attribute::StringZ do describe '#encode_value' do it 'should encode the value as a binary string with a null terminator' do encoded = Netlink::Attribute::StringZ.new.encode_value("HI\x00") encoded.should == "HI\x00\x00" end end describe '#decode_value' do it 'should decode the value as a binary string' do decoded = Netlink::Attribute::String.new.decode_value("HI\x00") decoded.should == "HI\x00" end end end describe Netlink::Attribute::UInt8 do describe '#encode_value' do it 'should encode the value as a single byte' do encoded = Netlink::Attribute::UInt8.new.encode_value(10) encoded.should == 10.chr end end describe '#decode_value' do it 'should decode the value from a single byte' do decoded = Netlink::Attribute::UInt8.new.decode_value(10.chr) decoded.should == 10 end end end describe Netlink::Attribute::UInt16 do describe '#encode_value' do it 'should encode the value as a uint16' do encoded = Netlink::Attribute::UInt16.new.encode_value(10) encoded.should == [10].pack('S') end end describe '#decode_value' do it 'should decode the value from a uint16' do packed = [10].pack('S') decoded = Netlink::Attribute::UInt16.new.decode_value(packed) decoded.should == 10 end end end describe Netlink::Attribute::UInt32 do describe '#encode_value' do it 'should encode the value as a uint32' do encoded = Netlink::Attribute::UInt32.new.encode_value(200_000) encoded.should == [200_000].pack('L') end end describe '#decode_value' do it 'should decode the value from a uint32' do packed = [200_000].pack('L') decoded = Netlink::Attribute::UInt32.new.decode_value(packed) decoded.should == 200_000 end end end describe Netlink::Attribute::UInt64 do describe '#encode_value' do it 'should encode the value as a uint64' do encoded = Netlink::Attribute::UInt64.new.encode_value(10_000_000_000) encoded.should == [10_000_000_000].pack('Q') end end describe '#decode_value' do it 'should decode the value from a uint64' do packed = [10_000_000_000].pack('Q') decoded = Netlink::Attribute::UInt64.new.decode_value(packed) decoded.should == 10_000_000_000 end end end
require 'spec_helper' describe SubCategory do fixtures :businesses, :sub_categories, :businesses_sub_categories, :categories_sub_categories, :categories before(:each) do @valid_attributes = { :sub_category => "chemist"} end it "should create a new instance given valid attributes" do SubCategory.create!(@valid_attributes) end it "should require a valid sub-category name" do SubCategory.new(:sub_category => " ").should_not be_valid end it "should have a associated category" do @sub_category = SubCategory.find(sub_categories(:sub_categories_012)) @sub_category.categories.should_not be_empty end end
class MerchantName < ActiveRecord::Base self.table_name = "merchant" include AnuBase class<<self def search name MerchantName.where("MATCH(mname) AGAINST ('*#{name}*' IN BOOLEAN MODE) ").select('mname').distinct().limit(50).pluck(:mname) end end end
require 'rails_helper' RSpec.describe Condition, type: :model do describe 'condition登録機能' do before do user = FactoryBot.create(:user) group = FactoryBot.create(:group, owner_id: user.id) @pet = FactoryBot.create(:pet, group_id: group.id) end context '入力機能' do it "is valid with a name, icon, rating" do wrap = Wrap.new( precaution_title: 'rspec', precaution_content: 'rspec', start_time: '2020/01/01', pet_id: @pet.id ) Condition.new( start_time: '0200', weight: '10.5', temperature: '38.5', memo: 'test_memo', wrap_id: wrap.id ) expect(wrap).to be_valid end end context 'バリデーションにかかる場合' do it "is invalid with weight >0" do wrap = Wrap.new( precaution_title: 'rspec', precaution_content: 'rspec', start_time: '2020/01/01', pet_id: @pet.id ) condition = Condition.new( start_time: '0200', weight: '-10.5', temperature: '38.5', memo: 'test_memo', wrap_id: wrap.id ) condition.valid? expect(condition.errors[:weight]).to include("は'0'以上でご入力ください") end end context 'バリデーションにかかる場合' do it "is invalid with temperature >0" do wrap = Wrap.new( precaution_title: 'rspec', precaution_content: 'rspec', start_time: '2020/01/01', pet_id: @pet.id ) condition = Condition.new( start_time: '0200', weight: '10.5', temperature: '-38.5', memo: 'test_memo', wrap_id: wrap.id ) condition.valid? expect(condition.errors[:temperature]).to include("は'0'以上でご入力ください") end end end end
class CreateCards < ActiveRecord::Migration def change create_table :cards do |t| t.text :name t.text :civilization t.integer :cost t.integer :mana_val t.string :avatar t.string :type t.boolean :shield_trigger t.integer :power t.text :race t.boolean :evolution t.string :effects, array: true, :default => [] t.timestamps null: false end end end
# frozen_string_literal: true class ProjectsController < ApplicationController before_action :set_project, only: %i[show edit update destroy] before_action :set_company require 'date' load_and_authorize_resource def set_company Project.set_company(@company.short_name) end # GET /projects # GET /projects.json def index respond_to do |format| format.html @search = Project.order(created_at: :desc).includes(:customer).ransack(params[:q]) @total = @search.result(distinct: true).sum(:total_gross) @projects = @search.result(distinct: true).paginate(page: params[:page], per_page: 30) format.pdf do @search = Project.order(date: :asc).ransack(params[:q]) @projects = @search.result(distinct: true) @total_gross = @projects.sum(:total_gross) @total = @projects.sum(:total) render pdf: t('invoice_report'), page_size: 'A4', enable_local_file_access: true, template: 'layouts/pdf/report/projects.html.haml', layout: 'pdf/layout', encoding: 'utf8', show_as_html: false, margin: { bottom: 15, top: 15, left: 15, right: 15 }, footer: { html: { template: 'layouts/pdf/report/footer.html.erb' } } end end end def refresh_content respond_to do |format| format.js end end # GET /projects/1 # GET /projects/1.json def show @project = scope.find(params[:id]) @one_project = true if params[:method] == 'label' print_label return true end @machine = @project.machine if @company.use_machines respond_to do |format| format.html format.pdf do case @company.mode when 'Plusview' render pdf: "#{@company.name.downcase}-devis#{@project.id}", page_size: 'A4', enable_local_file_access: true, template: 'layouts/pdf/quote/template.html.haml', layout: 'pdf/layout', encoding: 'utf8', show_as_html: params.key?('debug'), margin: { bottom: 23, top: 15, left: 15, right: 15 }, footer: { html: { template: 'layouts/pdf/quote/plusview_footer.html.erb' } } when 'Greday' render pdf: "#{display_quote_id(@project.id)}_#{@project.customer.name.upcase.tr(' ', '_')}_#{@project.name .upcase.tr(' ', '_')}", page_size: 'A4', enable_local_file_access: true, template: 'layouts/pdf/quote/template.html.haml', layout: 'pdf/layout', orientation: 'Portrait', encoding: 'utf8', show_as_html: params.key?('debug'), zoom: 1, dpi: 75, margin: { bottom: 23, top: 15, left: 15, right: 15 }, footer: { html: { template: 'layouts/pdf/quote/greday_footer.html.erb' } } else #empty end end end end def print_label respond_to do |format| format.html format.pdf do render pdf: t('quotation') + "_#{@project.id}", page_size: nil, page_height: '3.6cm', page_width: '8.9cm', template: 'layouts/pdf/label/template.html.haml', layout: 'pdf/layout', orientation: 'Portrait', encoding: 'utf8', margin: { bottom: 4, top: 4, left: 4, right: 4 }, show_as_html: params.key?('debug'), dpi: 75 end end end def duplicate respond_to do |format| @clone = @project.dup @clone.status = 0 @clone.date = Date.today @clone.invoice_id = nil @project.project_extra_lines.each do |project_extra_lines| @clone.project_extra_lines.push(project_extra_lines.dup) end @project.services.each do |services| @clone.services.push(services.dup) end @project.wares.each do |wares| @clone.wares.push(wares.dup) end if @clone.save! format.html { redirect_to project_path(@clone), notice: t('project_update_success') } format.json { render :show, status: :ok, location: @project } else format.html { render :edit } format.json { render json: @project.errors, status: :unprocessable_entity } end end end # GET /projects/new def new @project = Project.new respond_to(&:js) end def scope ::Project.all end # GET /projects/1/edit def edit; end # POST /projects # POST /projects.json def create @project = Project.new(project_params) respond_to do |format| if @project.save @project.invoice&.update_totals_invoice(@project.invoice, @project.invoice.projects) @project.update_totals_project(@project) format.html { redirect_to request.env['HTTP_REFERER'], notice: t('project_add_success') } format.json { render :show, status: :created, location: @project } else format.html { render :new } format.json { render json: @project.errors, status: :unprocessable_entity } end end end # PATCH/PUT /projects/1 # PATCH/PUT /projects/1.json def update respond_to do |format| if @project.update(project_params) @project.invoice&.update_totals_invoice(@project.invoice, @project.invoice.projects) @project.update_totals_project(@project) format.html { redirect_to request.env['HTTP_REFERER'], notice: t('project_update_success') } format.json { render :show, status: :ok, location: @project } else format.html { render :edit } format.json { render json: @project.errors, status: :unprocessable_entity } end end end # DELETE /projects/1 # DELETE /projects/1.json def destroy @project.destroy respond_to do |format| format.html { redirect_to request.env['HTTP_REFERER'], notice: t('project_destroy_success') } format.json { head :no_content } end end def bin respond_to do |format| if @project.update(status: 6) @project.invoice&.update_totals_invoice(@project.invoice, @project.invoice.projects) format.html { redirect_to request.env['HTTP_REFERER'], notice: t('project_update_success') } format.json { render :show, status: :ok, location: @project } else format.html { render :edit } format.json { render json: @project.errors, status: :unprocessable_entity } end end end def totals_project_once @once_projects = Project.all @once_projects.each do |project| project.update_totals_project(project) end end private def set_cache_headers response.headers['Cache-Control'] = 'no-cache, no-store' response.headers['Pragma'] = 'no-cache' response.headers['Expires'] = Time.now end # Use callbacks to share common setup or constraints between actions. def set_project @project = Project.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def project_params params.require(:project).permit(:invoice_id, :quotation_id, :customer_id, :name, :status, :wielding, :machining, :karcher, :total, :total_gross, :date, :description, :no_vat, :machine_id, :po, :applicant, :comment, :services_recap, :services_recap_text, :displacement_recap, :machine_history, :hide_services_hours) end end
require 'test_helper' class UserTest < ActiveSupport::TestCase test "new user" do orig_count = User.count u = User.new(:email => "foo@example.com", :password => SecureRandom.uuid, :username => "foobar") u.skip_confirmation! assert u.save, "User should have saved! #{u.errors.messages}" assert User.count > orig_count end end
# frozen_string_literal: true module Saucer class Options W3C = %i[browser_name browser_version platform_name accept_insecure_certs page_load_strategy proxy set_window_rect timeouts strict_file_interactability unhandled_prompt_behavior].freeze SAUCE = %i[access_key appium_version avoid_proxy build capture_html chromedriver_version command_timeout crmuxdriver_version custom_data disable_popup_handler extended_debugging firefox_adapter_version firefox_profile_url idle_timeout iedriver_version max_duration name parent_tunnel passed prerun prevent_requeue priority proxy_host public record_logs record_screenshots record_video restricted_public_info screen_resolution selenium_version source tags time_zone tunnel_identifier username video_upload_on_pass].freeze VALID = W3C + SAUCE attr_accessor :url, :scenario attr_reader :data_center, :remaining def initialize(opts = {}) create_instance_variables(opts) validate_credentials @browser_name ||= 'firefox' @platform_name ||= 'Windows 10' @browser_version ||= 'latest' @selenium_version ||= '3.141.59' @iedriver_version ||= '3.141.59' if @browser_name == 'internet explorer' opts.key?(:url) ? @url = opts[:url] : self.data_center = :US_WEST @scenario = opts.delete(:scenario) @remaining = opts end def create_instance_variables(opts) VALID.each do |option| self.class.__send__(:attr_accessor, option) next unless opts.key?(option) instance_variable_set("@#{option}", opts.delete(option)) end end def capabilities w3c = W3C.each_with_object({}) do |option, hash| value = instance_variable_get("@#{option}") next if value.nil? hash[option] = value end sauce = SAUCE.each_with_object({}) do |option, hash| value = instance_variable_get("@#{option}") next if value.nil? hash[option] = value end w3c.merge('sauce:options' => sauce).merge(remaining) end alias to_h capabilities def data_center=(data_center) @url = case data_center when :US_WEST 'https://ondemand.saucelabs.com:443/wd/hub' when :US_EAST 'https://us-east-1.saucelabs.com:443/wd/hub' when :EU_VDC 'https://ondemand.eu-central-1.saucelabs.com:443/wd/hub' else raise ::ArgumentError, "#{data_center} is an invalid data center; specify :US_WEST, :US_EAST or :EU_VDC" end @data_center = data_center end private def validate_credentials @username ||= ENV['SAUCE_USERNAME'] msg = "No valid username found; either pass the value into `Options#new` or set with ENV['SAUCE_USERNAME']" raise AuthenticationError, msg if @username.nil? @access_key ||= ENV['SAUCE_ACCESS_KEY'] return unless @access_key.nil? msg = "No valid access key found; either pass the value into `Options#new` or set with ENV['SAUCE_ACCESS_KEY']" raise AuthenticationError, msg end end end
require 'csv' class Baby < ApplicationRecord SEVERE_STUNTED_HEIGHT = [43,48,51,52.5,54.5,57.5,59,60.5,62,63,64,65,66,67,68,69,70,71,72,73,73.5,75,76,76.5,77,77.5,78,78.5,79.5,80,80.5,81,82,82.5,83,83.5,84,84.5,85,85.5,86,86.5,87,87.5,88,88.5,89,89,90,90.5,91,91.5,92,92.5,93,93.5,94,94,94.5,95] MODERATE_STUNTED_HEIGHT = [46,50,53,55.5,58,59.5,61,62.5,64,65,66.5,67.5,67,70,71,72,73,74,75,76,76.5,77.5,78,79,80,80,80.5,81.5,82,83,83.5,84,85,85.5,86,86.5,87,88,88.5,89,89.5,90,90.5,91,92,92.5,93,93.5,94,94.5,95,95.5,96,96.5,97,97.5,98,98.5,99,99,99.5] NORMAL = [49,54,57,58.5,62,64,65.5,67,68.5,70,70,72.5,74,75,76,77,78,79,80,80.5,82.5,83,84,85,86,86,87,88,88.5,89.5,90,91,92,92.5,93,94,94.5,95,96,96.5,97,98,98.5,99,100,100.5,101,101.5,102,103,103.5,104,104.5,105,105.5,106,106.5,107,108,108.5,109] NORMAL2 = [53,58,61,64,66.5,68.5,70,72,73.5,75,76,77.5,79,80,81.5,83,84,85,86,86.5,88.5,89.5,91,92,93,93,94,95,96,96.5,97.5,98.5,99,100,101,101.5,102.5,103,104,104.5,105.5,106,106.5,107.5,108,109,110,110.5,111,111.5,112,113,113.5,114,115,115.5,116,117,117.5,118,118.5] POSSIBLE_VERY_TALL = [55,60,63,66,68.5,70.5,72.5,74,75.5,77,79,80,81.5,83,84.5,85.5,87,88,88.5,90.5,91.5,92.5,94,95,96,96,97.5,98.5,99,100,101,102,103,103.5,104.5,105.5,106,107,108,108.5,109.5,110,111,115.5,112.5,113,114,114.5,115,116,116.5,117.5,118,119,119.5,120,120.5,121,122,122.5,123] SEVERE_UNDER_WEIGHT = [2,2.6,3.5,4,4.4,4.8,5,5.4,5.6,5.8,6,6.2,6.3,6.4,6.6,6.8,6.9,7,7.2,7.4,7.6,7.7,7.8,8,8.1,8.2,8.4,8.5,8.6,8.8,8.9,9,9.2,9.3,9.4,9.6,9.7,9.8,9.9,10,10.1,10.2,10.3,10.4,10.5,10.6,10.7,10.8,10.9,11,11.1,11.2,11.3,11.4,11.5,11.6,11.8,11.9,12,12,12.1] MODERATE_UNDER_WEIGHT = [2.4,3.2,4,4.6,5,5.4,5.8,6,6.2,6.4,6.6,6.8,7,7.2,7.4,7.6,7.8,8.9,8.1,8.3,8.4,8.6,8.8,8.9,9.1,9.2,9.4,9.6,9.7,9.8,10,10.1,10.2,10.4,10.6,10.7,10.8,11,11.1,11.2,11.4,11.5,11.6,11.8,11.9,12,12.1,12.2,12.4,12.5,12.6,12.7,12.8,12.9,13,13.2,13.3,13.4,13.6,13.6,13.7] NORMAL_WEIGHT = [3.2,4.2,5,5.8,6.4,6.8,7.2,7.6,7.8,8.2,8.4,8.6,8.8,9,9.2,9.4,9.8,10,10.2,10.4,10.6,10.8,11,11.2,11.4,11.4,11.8,12,12.2,12.4,12.6,12.8,13,13.2,13.4,13.6,13.8,14,14.1,14.2,14.3,14.6,14.8,15,15.2,15.4,15.6,15.8,16,16.2,16.4,16.5,16.8,16.9,17.1,17.2,17.4,17.6,17.8,17.9,18] POSSIBLE_OVERWEIGHT = [4.2,5.4,6.6,7.6,8.2,8.8,9.4,9.8,10.2,10.6,10.9,11.2,11.4,11.8,12,12.4,12.6,12.9,13.2,13.4,13.8,14,14.2,14.6,14.8,15,15.4,15.6,16,16.2,16.4,16.8,17.2,17.3,17.6,17.8,18,18.4,18.6,19,19.2,19.4,19.8,20,20.2,20.6,20.8,21.1,21.4,21.6,22,22.2,22.4,22.8,23,23.2,23.8,24,24.2,24.4,24.8] CHECK_WEIGHT_FOR_HEIGHT = [4.8,6.2,7.6,8.6,9.4,10,10.7,11,11.6,12,12.2,12.8,13,13.4,13.8,14.2,14.4,14.8,15.2,15.4,15.6,16,16.2,16.6,17,17.2,17.6,18,18.2,18.6,19,19.2,19.6,19.9,20.2,20.4,20.8,21.2,21.4,22,22.2,22.4,22.8,23.2,23.6,24,24.4,24.6,25,25.4,25.8,26,26.4,26.8,27.2,27.4,27.8,28.2,28.6,29,29.2] has_many :healths, inverse_of: :baby has_many :baby_risk_factors, inverse_of: :baby has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\z/ belongs_to :hospital belongs_to :user, optional: true has_one :mother has_one :father has_many :baby_vaccinations has_many :vitamin_as has_many :risk_factors, through: :baby_risk_factors has_many :baby_infant_feedings has_many :baby_cares validates :first_name, presence: true validates :last_name, presence: true validates :date_of_birth, presence: true validates :sex, presence: true accepts_nested_attributes_for :baby_cares, allow_destroy: true, reject_if: proc {|attributes| (attributes.has_key?("care_month_id") && attributes["care_month_id"].to_i == 0) || (attributes.has_key?("description") && attributes["description"].blank?) || (attributes.has_key?("comment") && attributes["comment"].blank?)} accepts_nested_attributes_for :baby_infant_feedings, allow_destroy: true, reject_if: proc {|attributes| attributes['infant_feeding_label_id'].to_i == 0 || (attributes.has_key?("infant_feeding_month_id") && attributes["infant_feeding_month_id"].to_i == 0) || (attributes.has_key?("description") && attributes["description"].blank?)} accepts_nested_attributes_for :father, allow_destroy: true accepts_nested_attributes_for :mother, allow_destroy: true accepts_nested_attributes_for :healths, allow_destroy: true accepts_nested_attributes_for :baby_risk_factors, allow_destroy: true, reject_if: proc { |attributes| attributes['risk_factor_id'].to_i == 0 } has_attached_file :avatar validates_attachment_file_name :avatar, :matches => [/png\Z/, /jpe?g\Z/, /gif\Z/] def unpermit_vitamin(min_age, max_age) age.to_i < min_age.to_i || age.to_i > max_age.to_i end def unpermit_age(_age) age.to_i != _age.to_i end def permit_age_in_week(min_age, max_age) age_in_week.to_i < min_age.to_i || age_in_week.to_i >= max_age.to_i end def age_in_week current_date = Time.new birth_date = Time.parse(date_of_birth) seconds = current_date - birth_date days = seconds/(3600*24) week = days/7 end def full_name [first_name, middle_name, last_name].join(" ") end def import CSV.generate do |csv| csv << ["BabyId", id] csv << ["BabyName", full_name] csv << ["Gender", sex] age_arr = ["age(month)"] (0..60).each{|age| age_arr << age} csv << age_arr height_arr = ["Height(cm)"] (0..60).each{|age| height_arr << healths.find_by(age: age).try(:height)} csv << height_arr weight_arr = ["Weight(cm)"] (0..60).each{|age| weight_arr << healths.find_by(age: age).try(:weight)} csv << weight_arr end end end
class AssistanceValue ASSISTANCE = "asistencia" ABSENCE = "inasistencia" ALLOWED = "permiso mesa directiva" JUSTIFIED = "justificada" IN_COMISSON = "oficial comision" DOCUMENT = "cedula" def self.to_i(string) if string.to_s.to_i > 0 value = new(string.to_i) else value = case string.to_s when ASSISTANCE then new(1) when ABSENCE then new(2) when ALLOWED then new(3) when JUSTIFIED then new(4) when IN_COMISSON then new(5) when DOCUMENT then new(6) else new(0) end end value.to_i end def initialize(number) @number = number end def to_s case @number when 1 then ASSISTANCE when 2 then ABSENCE when 3 then ALLOWED when 4 then JUSTIFIED when 5 then IN_COMISSON when 6 then DOCUMENT else "" end end def to_sym self.to_s.to_sym end def to_i @number end end
module Haenawa class Command include ::Encryptor COMMANDS = { assertConfirmation: Haenawa::Commands::NilCommand, chooseCancelOnNextConfirmation: Haenawa::Commands::NilCommand, chooseOkOnNextConfirmation: Haenawa::Commands::NilCommand, doubleClick: Haenawa::Commands::NilCommand, mouseDown: Haenawa::Commands::NilCommand, mouseUp: Haenawa::Commands::NilCommand, mouseDownAt: Haenawa::Commands::NilCommand, mouseMoveAt: Haenawa::Commands::NilCommand, mouseUpAt: Haenawa::Commands::NilCommand, mouseOver: Haenawa::Commands::NilCommand, mouseOut: Haenawa::Commands::NilCommand, select: Haenawa::Commands::NilCommand, selectAndWait: Haenawa::Commands::NilCommand, webdriverChooseCancelOnVisibleConfirmation: Haenawa::Commands::NilCommand, webdriverChooseOkOnVisibleConfirmation: Haenawa::Commands::NilCommand, check: Haenawa::Commands::Check, uncheck: Haenawa::Commands::Check, click: Haenawa::Commands::Click, clickAndWait: Haenawa::Commands::Click, open: Haenawa::Commands::Open, close: Haenawa::Commands::Close, pause: Haenawa::Commands::Pause, runScript: Haenawa::Commands::RunScript, selectFrame: Haenawa::Commands::SelectFrame, selectWindow: Haenawa::Commands::Window, sendKeys: Haenawa::Commands::SendKeys, setWindowSize: Haenawa::Commands::SetWindowSize, type: Haenawa::Commands::Type, waitForElementPresent: Haenawa::Commands::Wait, waitForPopUp: Haenawa::Commands::Wait, haenawaRubyEval: Haenawa::Commands::HaenawaRubyEval, }.freeze COMMAND_NAMES = Command::COMMANDS.keys.map(&:to_s).freeze VALID_STRATEGIES = %w(id xpath css link linkText name haenawaLabel).freeze class << self def create_from_step(step) klass = COMMANDS[step.command.to_sym] || Haenawa::Commands::Unsupported klass.new(step) end end def initialize(step) @step = step end def options @options ||= begin options = {} prev_command = @step.higher_item&.command case prev_command when 'chooseOkOnNextConfirmation' options[:accept_confirm] = true when 'chooseCancelOnNextConfirmation' options[:dismiss_confirm] = true end options end end def command @step.command end def target @step.target end def value if @step.encrypted_value.present? decrypt_and_verify(@step.encrypted_value) else @step.value end end def interpolated_value I18n.interpolate_hash(value, interpolation_hash) end def step_no @step.step_no end def validate raise NotImplementedError end def render raise NotImplementedError end def render_unsupported_target message = "サポートしていない対象エレメントです。| #{command} | #{target} | #{value} |" append_partial("raise \"#{escape_ruby(message)}\"") end protected def interpolation_hash @interpolation_hash ||= begin steppable = @step.steppable build_history = steppable.is_a?(BuildHistory) ? steppable : nil scenario = steppable&.scenario project = scenario&.project { build_sequence_code: build_history&.build_sequence_code, project_id: project&.id, project_name: project&.name, scenario_id: scenario&.id, scenario_name: scenario&.name, scenario_no: scenario&.scenario_no, step_id: @step.id, step_no: @step.step_no, build_history_id: build_history&.id, build_history_device: build_history&.device, } end end def interpolated_locator I18n.interpolate_hash(locator, interpolation_hash) end def ensure_capture ret = [] ret << "" ret << "begin" ret += append_partial(yield).split("\n") if block_given? ret << "ensure" ret << " $device.save_screenshot(self, :step_no => #{step_no}, :save_dir => ENV['SCREENSHOT_DIR'])" ret << "end" ret << "" append_partial(ret) end def handle_confirm ret = [] if options[:accept_confirm] ret << "accept_confirm do" ret << append_partial(yield) if block_given? ret << "end" elsif options[:dismiss_confirm] ret << "dismiss_confirm do" ret << append_partial(yield) if block_given? ret << "end" else ret << yield if block_given? end ret.join("\n") end def escape_ruby(string) string.to_s.gsub('\\', '\\\\').gsub('"', '\"') end def append_partial(partial) ret = [] if partial indent = ' ' * 2 if partial.is_a?(Array) partials = partial else partials = partial.split("\n") end partials.each do |line| ret << "#{indent}#{line}" end end ret.join("\n") end def split_target case target when %r[\A//] ['xpath', target] when /(.+?)=(.+)/ [$1, $2] else [nil, nil] end end def strategy split_target.first end def locator split_target.last end def find_target method_name = "find_by_#{strategy.underscore}" if !respond_to?(method_name, true) raise Haenawa::Exceptions::Unsupported::TargetType end send(method_name, interpolated_locator) end def find_by_id(id) "first(:id, #{id.dump})" end def find_by_xpath(xpath) # Selenium IDEは `//options[5]` のような、 # 必ずしも一意に決まらないxpath locatorを生成するが # Capybaraのfindメソッドだと一意に決まらなかった場合は # Capybara::Ambiguousのエラーを発火するのでここは # firstメソッドを使うことにした。 "first(:xpath, #{xpath.dump})" end def find_by_css(selector) "first(:css, #{selector.dump})" end def find_by_link(link) # linkからexact:プレフィックスを取り除く処理は過去のコードにあった。 # Selenium IDEのドキュメンターションには見当たらないが、ソースコードには # exact:、glob:、regexp:などのlocatorのmatching strategyを決める # プレフィックスの付与・参照するコードがあったので、部分的な対応にはなるが # 念のため以下のように対応する。 # 参考: # https://github.com/SeleniumHQ/selenium-ide/blob/cad55f1de6645dde2719f245f251f8d4a075b0df/packages/selenium-ide/src/content/targetSelector.js#L20-L31 # https://github.com/SeleniumHQ/selenium-ide/blob/cad55f1de6645dde2719f245f251f8d4a075b0df/packages/selenium-ide/src/content/PatternMatcher.js#L64-L69 link = link.sub(/\Aexact:/, '') "first(:link, #{link.dump})" end alias_method :find_by_link_text, :find_by_link def find_by_name(name) "first(:css, '[name=#{name.dump}]')" end def find_by_haenawa_label(label) "first(:field, #{label.dump})" end end end
require('rspec') require('dealership') require('bicycle') describe(Dealership) do before() do Dealership.clear() end describe('#name') do it('it returns the name of the dealership') do test_dealership = Dealership.new("Recycled Cycles") expect(test_dealership.name()).to(eq("Recycled Cycles")) end end describe('#id') do it('returns the id of the dealership') do test_dealership = Dealership.new("Recycled Cycles") expect(test_dealership.id()).to(eq(1)) end end describe('#bikes') do it('initially returns an empty array of bicycles for the dealership') do test_dealership = Dealership.new("Recycled Cycles") expect(test_dealership.bikes()).to(eq([])) end end describe('#save') do it('add a dealership to the array of saved dealerships') do test_dealership = Dealership.new("Recycled Cyles") test_dealership.save() expect(Dealership.all()).to(eq([test_dealership])) end end describe('.all') do it('it is empty at first') do expect(Dealership.all()).to(eq([])) end end describe('.find') do it('returns a dealership by its id number') do test_dealership = Dealership.new("Recycled Cyles") test_dealership.save() test_dealership2 = Dealership.new("Rivelo") test_dealership2.save() expect(Dealership.find(test_dealership.id())).to(eq(test_dealership)) end end describe('#add_bike') do it('adds a bike to a dealership') do test_dealership = Dealership.new("Recycled Cycles") test_bike = Bicycle.new("Rivendell", "Hunqapillar", 2012) test_dealership.add_bike(test_bike) expect(test_dealership.bikes()).to(eq([test_bike])) end end end
class Admin::BaseController < Common::LoginSystemBaseController before_filter :check_redirect_login_page def check_redirect_login_page redirect_to login_url unless check_admin_login? end #检查是否是管理员用户 def check_admin_login? admin_user = login_user return false if admin_user.nil?||!admin_user if Admin::BaseController.admin_user_names.include? admin_user.user_name return true else return false end end #获得管理员用户名 def self.admin_user_names ["admin"] end end
require 'spec_helper' RSpec.describe Indocker::Launchers::ContainerRunner do before { setup_indocker(debug: true) } subject { Indocker::Launchers::ContainerRunner.new( Indocker.logger ) } it "runs containers" do expect(Indocker::Docker).to receive(:run).once subject.run(configuration: Indocker.configuration, container_name: :good_container, force_restart: true) end end
# The is_bad_version API is already defined for you. # @param {Integer} version # @return {boolean} whether the version is bad # def is_bad_version(version): # @param {Integer} n # @return {Integer} def first_bad_version(n) binSearch(1, n) end def binSearch(left, right) return left if is_bad_version(left) m = (left + right) / 2 if is_bad_version(m) binSearch(left, m) else binSearch(m + 1, right) end end
%w[rubygems sinatra json haml librmpd dm-core].each { |lib| require lib } %w[models/album models/song models/nomination models/vote].each { |model| require model } require 'lib/mpd_proxy' require 'config' # ----------------------------------------------------------------------------------- # Helpers # ----------------------------------------------------------------------------------- def execute_on_nomination(id, &block) nomination = Nomination.get(id.to_i) yield(nomination) if nomination render_upcoming end def json_status current = Nomination.current status = { :playing => MpdProxy.playing?, :volume => MpdProxy.volume } status = status.merge(:current_album => current.album.to_s, :force_score => current.force_score, :forceable => current.can_be_forced_by?(request.ip)) if MpdProxy.playing? status.to_json end def render_upcoming @nominations = Nomination.active haml :_upcoming, :layout => false end helpers do def score_class(score); score > 0 ? "positive" : (score < 0 ? "negative" : "") end end # ----------------------------------------------------------------------------------- # Actions # ----------------------------------------------------------------------------------- get "/" do haml :index end get "/embed" do haml :index, :layout => :embed end get "/list/:type" do |list_type| @albums = Album.send(list_type); @value_method = Album.value_method_for(list_type) haml :_list, :layout => false end get "/search" do @albums = Album.search(params[:q]) haml :_list, :layout => false end get "/upcoming" do render_upcoming end get "/status" do json_status end post "/add/:id" do |album_id| album = Album.get(album_id.to_i) album.nominations.create(:status => "active", :created_at => Time.now, :nominated_by => request.ip) if album render_upcoming end post "/up/:id" do |nomination_id| execute_on_nomination(nomination_id) { |nomination| nomination.vote 1, request.ip } end post "/down/:id" do |nomination_id| execute_on_nomination(nomination_id) { |nomination| nomination.vote -1, request.ip } end post "/remove/:id" do |nomination_id| execute_on_nomination(nomination_id) { |nomination| nomination.remove request.ip } end post "/force" do Nomination.current.force request.ip json_status end post "/control/:action" do |action| MpdProxy.execute action.to_sym json_status end post "/volume/:value" do |value| MpdProxy.change_volume_to value.to_i end post "/play" do MpdProxy.play_next unless MpdProxy.playing? json_status end
class Playedgame < ActiveRecord::Base self.per_page = 30 belongs_to :player, counter_cache: true belongs_to :game, counter_cache: true scope :by_name, -> { joins(:game).order('games.name') } scope :by_achievement_count, -> { joins(:game).order('games.achievements_count DESC')} scope :by_time_played, -> { order('playedtime DESC')} def update_time_played self.player.update_time_played end end
require 'spec_helper' describe FactorSelection do it {should belong_to(:user)} it {should belong_to(:factor)} it {should validate_presence_of(:factor_id)} it {should validate_presence_of(:user_id)} end
# require gems require 'sinatra' require 'sqlite3' db = SQLite3::Database.new("students.db") db.results_as_hash = true # write a basic GET route # add a query parameter # GET / get '/' do "#{params[:name]} is #{params[:age]} years old." end # write a GET route with # route parameters get '/about/:person' do person = params[:person] "#{person} is a programmer, and #{person} is learning Sinatra." end get '/:person_1/loves/:person_2' do "#{params[:person_1]} loves #{params[:person_2]}" end # write a GET route that retrieves # all student data get '/students' do students = db.execute("SELECT * FROM students") response = "" students.each do |student| response << "ID: #{student['id']}<br>" response << "Name: #{student['name']}<br>" response << "Age: #{student['age']}<br>" response << "Campus: #{student['campus']}<br><br>" end response end # write a GET route that retrieves # a particular student get '/students/:id' do student = db.execute("SELECT * FROM students WHERE id=?", [params[:id]])[0] student.to_s end # write a GET route that displays and address get '/contact/' do "My address is:<br>#{params[:number]} #{params[:name]} St.<br>#{params[:city]}, #{params[:state]} #{params[:zip]}" end # http://localhost:9393/contact/?number=1307&name=Hayes&city=San%20Francisco&state=CA&zip=94117 # space in HTTP request is %20 # write a GET route # IF a person's name is provided, tell that person 'great job' # ELSE a name is not provided, just say 'great job' get '/great_job/' do person = params[:name] if person "Great Job, #{person}!" else "Great Job!" end end # http://localhost:9393/great_job/?person=Sarah # http://localhost:9393/great_job # write a GET route that adds two integers # provide two integers in HTTP request # convert integers provided in HTTP as string to integers and add # return response with string representing addition problem. get '/:number1/plus/:number2' do number1 = params[:number1] number2 = params[:number2] sum = number1.to_i + number2.to_i "#{number1} + #{number2} = #{sum}" end
class Api::V4::TeleconsultationMedicalOfficerTransformer class << self include Memery memoize def to_response(medical_officer) medical_officer .slice("id", "full_name") .merge(teleconsultation_phone_number: medical_officer.full_teleconsultation_phone_number) end end end
class CreateBadgesFeats < ActiveRecord::Migration def self.up create_table :badges_feats do |t| t.integer "badge_id" t.integer "feat_id" t.integer "threshold" t.timestamps end add_index :badges_feats, :badge_id add_index :badges_feats, :feat_id end def self.down drop_table :badges_feats remove_index :badges_feats, :badge_id remove_index :badges_feats, :feat_id end end
module Baison class Params attr_accessor :site, :key, :secret, :format, :v, :sign_method, :page_size, :shop_code def initialize(key, secret, shop_code) @site = "http://openapi.baotayun.com/openapi/webefast/web/?app_act=openapi/router" @format = "json" # @timestamp = Time.now.strftime('%Y-%m-%d %H:%M:%S') @v = "2.1" @sign_method = "md5" @page_size = 20 @key = key @secret = secret @shop_code = shop_code if @key.nil? or @secret.nil? or @shop_code.nil? raise ArgumentError, "key,secret,shop_code are required" end end end end
require 'spec_helper' describe Listen::Adapter::Linux do if linux? let(:listener) { double(Listen::Listener) } let(:adapter) { described_class.new(listener) } describe ".usable?" do it "returns always true" do expect(described_class).to be_usable end end describe '#initialize' do it 'requires rb-inotify gem' do described_class.new(listener) expect(defined?(INotify)).to be_true end end # workaround: Celluloid ignores SystemExit exception messages describe "inotify limit message" do let(:adapter) { described_class.new(listener) } let(:expected_message) { described_class.const_get('INOTIFY_LIMIT_MESSAGE') } before do allow_any_instance_of(INotify::Notifier).to receive(:watch).and_raise(Errno::ENOSPC) allow(listener).to receive(:directories) { [ 'foo/dir' ] } end it "should be show before calling abort" do expect(STDERR).to receive(:puts).with(expected_message) # Expect RuntimeError here, for the sake of unit testing (actual # handling depends on Celluloid supervisor setup, which is beyond the # scope of adapter tests) expect{adapter.start}.to raise_error RuntimeError, expected_message end end end if darwin? it "isn't usable on Darwin" do expect(described_class).to_not be_usable end end if windows? it "isn't usable on Windows" do expect(described_class).to_not be_usable end end if bsd? it "isn't usable on BSD" do expect(described_class).to_not be_usable end end end
class RequestsController < ApplicationController authorize_resource before_action :set_request, only: [:show, :edit, :update, :destroy] respond_to :html, :json def index @requests = Request.all respond_with(@requests) end def show respond_with(@request) end def new @request = Request.new respond_with(@request) end def edit end def create @request = Request.new(request_params) @request.create_request respond_with(@request) end def update @request.update(request_params) respond_with(@request) end def destroy @request.destroy respond_with(@request) end def accept @request = Request.find(params[:id]) @request.accept_request render "change_status.json" end def reject @request = Request.find(params[:id]) @request.reject_request render "change_status.json" end private def set_request @request = Request.find(params[:id]) end def request_params params.require(:request).permit(:source_name, :source_email, :source_text, :user_id, :visible, :status) end end
class AddBillStreetPrefixToBills < ActiveRecord::Migration def change add_column :bills, :bill_streetprefix, :string end end
Given(/^Open the homepage as usual$/) do @homepage = HomePage.new @homepage.load sleep 2 end Given(/^Click the delete button behind the first bookmark$/) do @bookmark = @homepage.titleText @homepage.deleteBookmark end Given(/^Search the bookmark which you deleted$/) do @homepage.search @bookmark end Given(/^Get (\d+) result$/) do |expect| expect(@homepage.result).to eq expect.to_i end
require_relative 'formats' class OrderItem def initialize(input) props = input.match(/(?<quantity>\d+) (?<format>\w+)/) raise StandardError, 'Invalid input' unless props @quantity = Integer(props[:quantity]) @format = props[:format].downcase raise StandardError, 'Invalid format' unless FORMATS[@format] @bundles = FORMATS[@format] end attr_reader :quantity attr_reader :format attr_reader :bundles def to_s "#{@quantity} #{format.upcase}" end def process return [] unless @bundles return [] if @quantity < @bundles.keys.min find_exact_smallest_bundle(matches).map do |quantity, amount| { bdl_qty: quantity, amount: amount, price: amount * @bundles[quantity] } end end def matches combos = [] # get all possible combinations of numbers to get target @bundles.keys.each do |num| partials = {} partials[num] = @quantity / num # stop if exact match to the target quantity already if (@quantity % num).zero? combos.push(compute_combo_info(partials)) next end partials = process_subset( @bundles.keys - partials.keys, @quantity, partials ) combos.push(compute_combo_info(partials)) end combos end def compute_combo_info(partials) { bundles: partials, sum: multiplier_sum(partials), bundle_count: partials.values.reduce(0, :+) } end def process_subset(numbers, target, partials = {}) return partials if numbers.empty? sum = multiplier_sum(partials) return partials if sum >= target difference = target - sum return partials if difference < numbers.min numbers.each do |num| partials[num] = difference / num return process_subset( numbers - partials.keys, target, partials ) end end def multiplier_sum(values) sum = 0 values.each do |quantity, multiplier| sum += (quantity * multiplier) end sum end def find_exact_smallest_bundle(combos) combos.sort_by! { |c| c[:bundle_count] } # prioritize exact matches with the smallest bundle count best = combos .select { |c| c[:sum] == @quantity } .first best ||= combos.first best[:bundles] 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. # # # **************************************************************************** require '../../util/assert.rb' # also what could we pass to the block argument? it is necessary # the rule is: # - &arg is optional, either specify it or skip it. # - proc is not taken as block argument, &proc works def method block_given? end empty = lambda {} assert_equal(method, false) x = method {} assert_equal(x, true) x = method(&empty) assert_equal(x, true) assert_raise(ArgumentError) { method(empty) } def method_with_1_arg arg block_given? end assert_equal(method_with_1_arg(1), false) x = method_with_1_arg(1) {} assert_equal(x, true) x = method_with_1_arg(1, &empty) assert_equal(x, true) assert_raise(ArgumentError) { method_with_1_arg(1, empty) } assert_equal(method_with_1_arg(empty), false) def method_with_explict_block &p l = 1 if p == nil l += 10 else l += 100 end if block_given? l += 1000 else l += 10000 end l end assert_equal(method_with_explict_block, 10011) assert_raise(ArgumentError) { method_with_explict_block(1) } x = method_with_explict_block {} assert_equal(x, 1101) x = method_with_explict_block(&empty) assert_equal(x, 1101) assert_raise(ArgumentError) { method_with_explict_block(empty) }
require 'pry' class Triangle attr_reader :length_one, :length_two, :length_three def initialize (length_one, length_two, length_three) @length_one = length_one.to_f @length_two = length_two.to_f @length_three = length_three.to_f @lengths = [@length_one, @length_two, @length_three].sort end def kind if !self.is_valid raise TriangleError elsif is_equilateral :equilateral elsif is_isosceles :isosceles else :scalene end end def is_equilateral length_one == length_two && length_one == length_three end def is_isosceles has_equal_sides = length_one == length_two || length_one == length_three || length_two == length_three has_equal_sides && !is_equilateral end def is_valid if !has_sides || @lengths[2] >= @lengths[0] + @lengths[1] false else true end end def has_sides @lengths.each do |length| if length <= 0 return false end end end class TriangleError < StandardError end end # t = Triangle.new(1,2,2) # t.is_valid
# frozen_string_literal: true require "rails_helper" # rubocop:disable Metrics/BlockLength RSpec.describe DeliveriesController, type: :routing do describe "routing" do it "routes to #index" do expect(get: "/deliveries").to route_to("deliveries#index") end it "routes to #new" do expect(get: "/deliveries/new").to route_to("deliveries#new") end it "routes to #show" do expect(get: "/deliveries/1").to route_to("deliveries#show", id: "1") end it "routes to #edit" do expect(get: "/deliveries/1/edit").to route_to("deliveries#edit", id: "1") end it "routes to #create" do expect(post: "/deliveries").to route_to("deliveries#create") end it "routes to #update via PUT" do expect(put: "/deliveries/1").to route_to("deliveries#update", id: "1") end it "routes to #update via PATCH" do expect(patch: "/deliveries/1").to route_to("deliveries#update", id: "1") end it "routes to #destroy" do expect(delete: "/deliveries/1").to route_to("deliveries#destroy", id: "1") end end end # rubocop:enable Metrics/BlockLength
namespace :migrations do # desc "For migration: update trust to be 10x what it was before" # task update_trust: :environment do # User.all.each { |u| u.update(trust: u.trust * 10)} # Question.all.each { |q| q.update(vote_total: q.vote_total * 10) } # Answer.all.each { |a| a.update(vote_total: a.vote_total * 10) } # QuestionVote.all.each { |qv| qv.update(trust: qv.trust * 10)} # AnswerVote.all.each { |av| av.update(trust: av.trust * 10)} # end # # desc "For migration" # task create_trust_events: :environment do # [ # Question.all.unscoped, # Answer.all.unscoped, # QuestionVote.all.unscoped, # AnswerVote.all.unscoped # ].flatten.sort { |a,b| a.created_at <=> b.created_at }.each do |object| # event = object.send(:create_trust_event) # event.update(created_at: object.created_at) # end # end # # desc "For migration ReviseTrustEvents: add object type to ever trust_event" # task add_object_to_trust_events: :environment do # TrustEvent.all.each do |te| # te.update(object_type: te.event_object_type) # end # end end
class HomeController < BaseController def index @current_user = current_user @root = true end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception helper_method :current_user,:current_user?,:current_account def require_authantication if current_user.nil? || current_account.nil? redirect_to new_employee_sessions_url end end def tab_name params[:controller] end def current_user? current_user.present? ? true : false end private def current_user @current_user ||= Employee.find_by_id(session[:emp_id]) if session[:emp_id] end def current_account @current_account ||= Location.find_by_id(session[:location_id]) if session[:location_id] end end
ChildSupport::Application.routes.draw do # authenticated :user do # root :to => 'home#index' # end root to: 'home#index' devise_for :users get "/pages/*id" => 'pages#show', as: :page, format: false namespace :api, default: {format: :json} do resources :genders, only: [:index] resources :record_types, only: [:index] resources :clients do resources :client_records end get '/support_schedule' => 'support_schedule#show' end end
class CreateNonUserParticipants < ActiveRecord::Migration[5.0] def change create_table :non_user_participants do |t| t.date :date_of_birth t.string :gender t.string :recruitment_method t.date :recruitment_date, null: false t.belongs_to :study, index: true t.timestamps end end end
class ReviewForwardsAddSenderFields < ActiveRecord::Migration def self.up add_column :review_forwards, :sender_email, :string, :null => true, :limit => ReviewForward::SENDER_EMAIL_MAX_LENGTH add_column :review_forwards, :sender_name, :string, :null => true, :limit => ReviewForward::SENDER_NAME_MAX_LENGTH end def self.down remove_column :review_forwards, :sender_email remove_column :review_forwards, :sender_name end end
require "formula" class Argus < Formula homepage "http://qosient.com/argus/" url "http://qosient.com/argus/src/argus-3.0.8.tar.gz" sha1 "fe9833c7f8ea4cdf7054b37024e5d007613f9571" bottle do cellar :any sha1 "5b8ca09efc8f4f84d78883f3f866628da061928b" => :yosemite sha1 "c96587d47409a7cb961450ade0b76558c1bf3f9c" => :mavericks sha1 "13a6e2c690d830adddb45bce4b8b0b24a01c9249" => :mountain_lion end def install system "./configure", "--prefix=#{prefix}" system "make" system "make", "install" end end
class AddDepthToCallForward < ActiveRecord::Migration def change rename_column :call_forwards, :hops, :depth end end
class CreateHorariosorteots < ActiveRecord::Migration[5.0] def change create_table :horariosorteots do |t| t.string :nombre t.datetime :lunes t.datetime :martes t.datetime :miercoles t.datetime :jueves t.datetime :viernes t.datetime :sabado t.datetime :domingo t.timestamps end end end
module AssetGallery class HomeController < ::AssetGallery::ApplicationController def index @sets = AssetGallery::Set.published.is_public.page(params[:page] || 1).per(12) end end end
require File.join(File.dirname(__FILE__), "..", 'spec_helper.rb') describe Authentication::Session do before(:all) do Merb::CookieSession.send(:include, Authentication::Session) end before(:each) do @session = Merb::CookieSession.new( "", "sekrit") end def clear_strategies Authentication.login_strategies.clear! end describe "module methods" do before(:each) do @m = mock("mock") clear_strategies end after(:all) do clear_strategies end describe "login_strategies" do it "should provide access to these strategies" do Authentication.login_strategies.should be_a_kind_of(Authentication::StrategyContainer) end it "should allow adding a find strategy" do Authentication.login_strategies.add(:salted_login){ @m.salted_login } @m.should_receive(:salted_login) Authentication.login_strategies[:salted_login].call end end # login_strategies describe "store_user" do it{@session._authentication_manager.should respond_to(:store_user)} it "should raise a NotImplemented error by default" do pending "How to spec this when we need to overwrite it for the specs to work?" lambda do @session._authentication_manager.store_user("THE USER") end.should raise_error(Authentication::NotImplemented) end end describe "fetch_user" do it{@session._authentication_manager.should respond_to(:fetch_user)} it "should raise a NotImplemented error by defualt" do pending "How to spec this when we need to overwrite it for the specs to work?" lambda do @session._authentication_manager.fetch_user end.should raise_error(Authentication::NotImplemented) end end end describe "user" do it "should call fetch_user with the session contents to load the user" do @session[:user] = 42 @session._authentication_manager.should_receive(:fetch_user).with(42) @session.user end it "should set the @user instance variable" do @session[:user] = 42 @session._authentication_manager.should_receive(:fetch_user).and_return("THE USER") @session.user @session._authentication_manager.assigns(:user).should == "THE USER" end it "should cache the user in an instance variable" do @session[:user] = 42 @session._authentication_manager.should_receive(:fetch_user).once.and_return("THE USER") @session.user @session._authentication_manager.assigns(:user).should == "THE USER" @session.user end it "should set the ivar to nil if the session is nil" do @session[:user] = nil @session.user.should be_nil end end describe "user=" do before(:each) do @user = mock("user") @session._authentication_manager.stub!(:fetch_user).and_return(@user) end it "should call store_user on the session to get the value to store in the session" do @session._authentication_manager.should_receive(:store_user).with(@user) @session.user = @user end it "should set the instance variable to nil if the return of store_user is nil" do @session._authentication_manager.should_receive(:store_user).and_return(nil) @session.user = @user @session.user.should be_nil end it "should set the instance varaible to nil if the return of store_user is false" do @session._authentication_manager.should_receive(:store_user).and_return(false) @session.user = @user @session.user.should be_nil end it "should set the instance variable to the value of user if store_user is not nil or false" do @session._authentication_manager.should_receive(:store_user).and_return(42) @session.user = @user @session.user.should == @user @session[:user].should == 42 end end describe "abandon!" do before(:each) do @user = mock("user") @session._authentication_manager.stub!(:fetch_user).and_return(@user) @session._authentication_manager.stub!(:store_user).and_return(42) @session[:user] = 42 @session.user end it "should delete the session" do @session.should_receive(:delete) @session.abandon! end it "should not have a user after it is abandoned" do @session.user.should == @user @session.abandon! @session.user.should be_nil end end describe "Authentication Manager" do it "Should be hookable" do Authentication::Manager.should include(Extlib::Hook) end end end
class Ability include CanCan::Ability def initialize(user) @user = user || User.new if user.has_role? :administrator can :manage, :all end ############################################## if user.has_role? :admission_manager can :manage, Student end if user.has_role? :student_viewer can :read, Student end ############################################# ############################################# if user.has_role? :academic_support can :manage, Ticket end if user.has_role? :complaint_manager can :manage, Ticket , :employee_department_id => user.employee.employee_department_id end if user.has_role? :complaint_staff can :manage, Ticket, :employee_id => user.employee.id end if user.has_role? :complaint_assigner can :manage, Ticket, :employee_id => nil end if user.has_role? :complainer can :create, Ticket can :read, Ticket, :user_id => user.id end ############################################ if user.has_role? :academic_advisor can :manage, GuidanceAdvisor, :employee_id => user.employee.id end end # Define abilities for the passed in user here. For example: # # user ||= User.new # guest user (not logged in) # if user.admin? # can :manage, :all # else # can :read, :all # end # # The first argument to `can` is the action you are giving the user # permission to do. # If you pass :manage it will apply to every action. Other common actions # here are :read, :create, :update and :destroy. # # The second argument is the resource the user can perform the action on. # If you pass :all it will apply to every resource. Otherwise pass a Ruby # class of the resource. # # The third argument is an optional hash of conditions to further filter the # objects. # For example, here the user can only update published articles. # # can :update, Article, :published => true # # See the wiki for details: # https://github.com/ryanb/cancan/wiki/Defining-Abilities end
# -*- encoding: utf-8 -*- require './lib/s3mpi/version' Gem::Specification.new do |s| s.name = 's3mpi' s.version = S3MPI::VERSION::STRING.dup s.summary = 'Upload and download files to S3 using a very convenient API.' s.description = %(Passing objects between Ruby consoles can be cumbersome if the user has performed some serialization and deserialization procedure. S3MPI aims to enable simple reading and writing to S3 buckets without the typical overhead of the AWS gem. ).strip.gsub(/\s+/, " ") s.authors = ["Robert Krzyzanowski"] s.email = 'rkrzyzanowski@gmail.com' s.homepage = 'http://github.com/robertzk' s.license = 'MIT' s.homepage = 'https://github.com/robertzk/s3mpi-ruby' s.platform = Gem::Platform::RUBY s.require_paths = %w[lib] s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.add_runtime_dependency 'aws-sdk-s3', '~> 1' s.add_development_dependency 'rake', '~> 10.1.0' s.add_development_dependency 'rspec', '~> 3.4' s.add_development_dependency 'pry', '~> 0.10.4' s.extra_rdoc_files = ['README.md', 'LICENSE'] end
class AddIndexToComparsionsUserId < ActiveRecord::Migration[6.0] def change add_index :comparsions, :user_id end end
module Jshint::Reporters # Outputs a basic lint report suitable for STDOUT class Default # @return [String] the report output attr_reader :output # Sets up the output string for the final report # # @param results [Hash] Key value pairs containing the filename and associated errors def initialize(results = {}) @results = results @output = '' end # Loops through all the errors and generates the report # # @example # foo/bar/baz.js: line 4, col 46, Bad operand. # foo/bar/baz.js: line 39, col 7, Missing semicolon. # # 2 errors # # @return [String] The default report def report len = 0 @results.each do |file, errors| len += errors.length print_errors_for_file(file, errors) end if output print_footer(len) output end end # Appends new error strings to the Report output # # @example # foo/bar/baz.js: line 4, col 46, Bad operand. # foo/bar/baz.js: line 39, col 7, Missing semicolon. # # @param file [String] The filename containing the errors # @param errors [Array] The errors for the file # @return [void] def print_errors_for_file(file, errors) errors.map do |error| output << "#{file}: line #{error['line']}, col #{error['character']}, #{error['reason']}\n" unless error.nil? end end # Appends a footer summary to the Report output # # @example # 1 error # 3 errors # # @param len [Fixnum] The number of errors in this Report # @return [void] def print_footer(len) output << "\n#{len} error#{len === 1 ? nil : 's'}" end end end
require_relative "piece" require_relative "slideable" class Bishop < Piece include Slideable def symbol "B" end def moves_dirs diagonal_dirs end end
#coding: utf-8 class Sequence < ActiveRecord::Base validates :value, uniqueness: {scope: :name} class<<self def gen seq_prefix, corp_code day = Time.now.strftime '%y%m%d' "#{seq_prefix}#{corp_code.to_s.rjust 4, '0'}#{day}#{Sequence.next "#{corp_code.to_s.rjust 4, '0'}-#{seq_prefix}-#{day}", 4}" end def next name, length=nil Sequence.transaction do v = Sequence.where(name: name).maximum(:value).to_i v += 1 if length.to_i >0 config = {name: name, value: v, category: 'string', capacity: length} v = "#{v.to_s.rjust config[:capacity], '0'}" if length.to_i >0 else config = {name: name, value: v} end Sequence.create! config v end end end end
# n Place a value n in the "register". Do not modify the stack. # PUSH Push the register value on to the stack. Leave the value in the register. # ADD Pops a value from the stack and adds it to the register value, storing the result in the register. # SUB Pops a value from the stack and subtracts it from the register value, storing the result in the register. # MULT Pops a value from the stack and multiplies it by the register value, storing the result in the register. # DIV Pops a value from the stack and divides it into the register value, storing the integer result in the register. # MOD Pops a value from the stack and divides it into the register value, storing the integer remainder of the division in the register. # POP Remove the topmost item from the stack and place in register # PRINT Print the register value # rules: # register is current value # stack is list of values that grows and shrinks dynamically # perform operation using popped value from stack with register value, store result back in register # data structure: array for stack, integer for register # algorithm: # initialize register to 0 # initialize stack to [] # split commands into an array of strings # iterate through commands # use case statements for input commands # if integer, re-assign register to value # do same when statements for commands above def minilang(commands) register = 0 stack = [] commands_arr = commands.split commands_arr.each do |command| case when command.to_i.to_s == command register = command.to_i when command == 'PUSH' stack << register when command == 'ADD' register += stack.pop when command == 'SUB' register -= stack.pop when command == 'MULT' register *= stack.pop when command == 'DIV' register /= stack.pop when command == 'MOD' register %= stack.pop when command == 'POP' register = stack.pop when command == 'PRINT' puts register end end end p minilang('PRINT') # 0 p minilang('5 PUSH 3 MULT PRINT') # 15 p minilang('5 PRINT PUSH 3 PRINT ADD PRINT') # 5 # 3 # 8 p minilang('5 PUSH POP PRINT') # 5 p minilang('3 PUSH 4 PUSH 5 PUSH PRINT ADD PRINT POP PRINT ADD PRINT') # 5 # 10 # 4 # 7 p minilang('3 PUSH PUSH 7 DIV MULT PRINT ') # 6 p minilang('4 PUSH PUSH 7 MOD MULT PRINT ') # 12 p minilang('-3 PUSH 5 SUB PRINT') # 8 p minilang('6 PUSH') # (nothing printed; no PRINT commands)
class CLI attr_accessor:game_mode, :token def greeting puts "" puts "Welcome to Tic Tac Toe!" puts "Enter 1 to play against another human." puts "Enter 2 to play against the computer." puts "Enter 3 or wargames to pit two computer players against each other." puts "Enter exit to quit." end def get_mode @game_mode = gets.strip end def get_token @token = gets.strip.upcase end def validate_mode while !@game_mode.to_i.between?(1, 3) && @game_mode != "wargames" && @game_mode != "exit" puts "I don't recognize that. Please enter 1, 2, 3, or wargames." get_mode end end def human_vs_human puts "X goes first! Are you ready?" game = Game.new(Players::Human.new("X"), Players::Human.new("O"), Board.new) game.play end def human_vs_ai puts "X or O?" get_token while @token != "X" && @token != "O" puts "I don't recognize that. X or O?" get_token end game = nil if @token == "X" game = Game.new(Players::Human.new("X"), Players::Computer.new("O"), Board.new) else game = Game.new(Players::Computer.new("X"), Players::Human.new("O"), Board.new) end game.play end def ai_vs_ai puts "Get ready to watch the battle unfold!" puts "" sleep 1.5 game = Game.new(Players::Computer.new("X"), Players::Computer.new("O"), Board.new) game.play end def wargames won_count = 0 100.times do game = Game.new(Players::Computer.new("X"), Players::Computer.new("O"), Board.new) outcome = game.play if outcome != nil won_count += 1 end end puts "" puts "Wargames complete!" puts "#{won_count} out of 100 games had a winner." end def call while @game_mode != "exit" greeting get_mode validate_mode case when @game_mode == "1" human_vs_human when @game_mode == "2" human_vs_ai when @game_mode == "3" ai_vs_ai when @game_mode == "wargames" wargames end end puts "See you next time!" end end
class ChangeUpSources < ActiveRecord::Migration def up remove_index :sources, :abbr remove_column :sources, :abbr add_column :sources, :url, :string, null: false, default: 0 change_column :sources, :url, :string, null: false add_index :sources, :url, unique: true end def down raise ActiveRecord::IrreversibleMigration, "Can't recover the deleted columns and indexes" end end
class CatRentalRequest < ActiveRecord::Base STATUSES = [ "PENDING", "APPROVED", "DENIED" ] validates :cat_id, :start_date, :end_date, :status, presence: true validates :status, inclusion: STATUSES validate :overlapping_approved_requests, unless: :denied? validate :dates_in_correct_order belongs_to :cat after_initialize :status_pending def approve! raise "Status must be PENDING" if self.status != "PENDING" transaction do overlapping_requests.each(&:deny!) self.status = "APPROVED" save! end end def deny! self.status = "DENIED" save! end private def overlapping_requests overlapping_requests = CatRentalRequest .where(cat_id: cat_id) .where("id != ?", id) .where(<<-SQL, start_date: start_date, end_date: end_date) (start_date BETWEEN :start_date AND :end_date OR end_date BETWEEN :start_date AND :end_date) OR (start_date < :start_date AND end_date > :end_date) SQL end def overlapping_approved_requests if overlapping_requests.where(status: "APPROVED").any? errors[:start_date] << "overlaps with another request" end end def status_pending self.status ||= "PENDING" end def denied? status == "DENIED" end def dates_in_correct_order if start_date > end_date errors[:start_date] << "must come before end date" end end end
class UsersController < ApplicationController before_action :logged_in_user, only: [:edit, :update] def index @users = User.all end def new @user = User.new end def show @user = User.find(params[:id]) @courses = @user.courses end def create @user = User.new(user_params) if @user.save flash.now[:success] = "Sign up successfully!" redirect_to course_home_url else errors = ["Please correct following errors:","Name cant be blank","Name is too short(minimum is 4)","Email cannot be blank","Email is too short(minimum is 4)","Email registration is only for RMIT staff","Pass word cant be blank","Password must contain at least one uppercase letter, one lowercase letter, one number, one special character and 8+characters"] flash.now[:danger] = errors.join("<br>").html_safe render 'new' end end def destroy @user = User.find(params[:id]) @user.destroy redirect_to end def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) if @user.update_attributes(user_params) flash[:success] = "Profile updated" redirect_to @user else errors = ["Please correct following errors:","Name cant be blank","Name is too short(minimum is 4)","Email cannot be blank","Email is too short(minimum is 4)","Email registration is only for RMIT staff","Pass word cant be blank","Password must contain at least one uppercase letter, one lowercase letter, one number, one special character and 8+characters"] flash.now[:danger] = errors.join("<br>").html_safe render 'edit' end end private def user_params params.require(:user).permit(:name, :email, :password, :password_confirmation) end def logged_in_user unless logged_in? flash[:danger] = "Please log in." redirect_to login_url end end # Confirms the correct user. def correct_user @user = User.find(params[:id]) redirect_to(root_url) unless current_user?(@user) end end
# Create a route to DEFAULT_WEB, if such is specified; also register a generic route def connect_to_web(map, generic_path, generic_routing_options) if defined? DEFAULT_WEB explicit_path = generic_path.gsub(/:web\/?/, '') explicit_routing_options = generic_routing_options.merge(:web => DEFAULT_WEB) map.connect(explicit_path, explicit_routing_options) end map.connect(generic_path, generic_routing_options) end # :id's can be arbitrary junk id_regexp = /.+/ ActionController::Routing::Routes.draw do |map| map.connect 'create_system', :controller => 'admin', :action => 'create_system' map.connect 'create_web', :controller => 'admin', :action => 'create_web' map.connect 'delete_web', :controller => 'admin', :action => 'delete_web' map.connect 'delete_files', :controller => 'admin', :action => 'delete_files' map.connect 'web_list', :controller => 'wiki', :action => 'web_list' connect_to_web map, ':web/edit_web', :controller => 'admin', :action => 'edit_web' connect_to_web map, ':web/remove_orphaned_pages', :controller => 'admin', :action => 'remove_orphaned_pages' connect_to_web map, ':web/remove_orphaned_pages_in_category', :controller => 'admin', :action => 'remove_orphaned_pages_in_category' connect_to_web map, ':web/file/delete/:id', :controller => 'file', :action => 'delete', :requirements => {:id => /[-._\w]+/}, :id => nil connect_to_web map, ':web/files/pngs/:id', :controller => 'file', :action => 'blahtex_png', :requirements => {:id => /[-._\w]+/}, :id => nil connect_to_web map, ':web/files/:id', :controller => 'file', :action => 'file', :requirements => {:id => /[-._\w]+/}, :id => nil connect_to_web map, ':web/file_list/:sort_order', :controller => 'wiki', :action => 'file_list', :sort_order => nil connect_to_web map, ':web/import/:id', :controller => 'file', :action => 'import' connect_to_web map, ':web/login', :controller => 'wiki', :action => 'login' connect_to_web map, ':web/web_list', :controller => 'wiki', :action => 'web_list' connect_to_web map, ':web/show/diff/:id', :controller => 'wiki', :action => 'show', :mode => 'diff', :requirements => {:id => id_regexp} connect_to_web map, ':web/revision/diff/:id/:rev', :controller => 'wiki', :action => 'revision', :mode => 'diff', :requirements => { :rev => /\d+/, :id => id_regexp} connect_to_web map, ':web/revision/:id/:rev', :controller => 'wiki', :action => 'revision', :requirements => { :rev => /\d+/, :id => id_regexp} connect_to_web map, ':web/source/:id/:rev', :controller => 'wiki', :action => 'source', :requirements => { :rev => /\d+/, :id => id_regexp} connect_to_web map, ':web/list/:category', :controller => 'wiki', :action => 'list', :requirements => { :category => /.*/}, :category => nil connect_to_web map, ':web/recently_revised/:category', :controller => 'wiki', :action => 'recently_revised', :requirements => { :category => /.*/}, :category => nil connect_to_web map, ':web/:action/:id', :controller => 'wiki', :requirements => {:id => id_regexp} connect_to_web map, ':web/:action', :controller => 'wiki' connect_to_web map, ':web', :controller => 'wiki', :action => 'index' if defined? DEFAULT_WEB map.connect '', :controller => 'wiki', :web => DEFAULT_WEB, :action => 'index' else map.connect '', :controller => 'wiki', :action => 'index' end end
class CreateStocks < ActiveRecord::Migration def change create_table :stocks do |t| t.integer :total_quantity t.decimal :total_price, :null => false t.references :purchase t.references :product t.timestamps end add_index :stocks, :purchase_id add_index :stocks, :product_id end end
# frozen_string_literal: true require_relative '../csv_parsing/csv_parser.rb' require './csv_parsing/length_determinant.rb' # Class to create lines for console output class LinesBuilder < LengthDeterminant def max_length_hash define_max_length end def count_length_line chars_count = 0 (0..max_length_hash.length - 1).each do |i| chars_count += max_length_hash[i] end chars_count end def create_first_line chars_count = count_length_line first_line = '+'.dup (1..(chars_count + max_length_hash.length - 1)).each do first_line.concat('-') end first_line.concat('+') end def create_last_line last_line = '+'.dup (0..max_length_hash.length - 1).each do |i| (1..max_length_hash[i]).each do last_line.concat('-') end last_line.concat('+') end last_line end end
In Ruby, strings are objects of the String class, which defines a powerful set of operations and methods for manipulating text (e.g., indexing, searching, modifying, etc.). Here are a few easy ways to create Strings: my_string = "Hello." # create a string from a literal my_empty_string = String.new # create an empty string my_copied_string = String.new(my_string) # copy a string to a new variable Until Ruby , Strings were nothing but a collection of bytes. Data was indexed by byte count, size was in terms of number of bytes, and so on. Since Ruby , Strings have additional encoding information attached to the bytes which provides information on how to interpret them. For example, this code: str = "With ♥!" print("My String's encoding: ", str.encoding.name) print("\nMy String's size: ", str.size) print("\nMy String's bytesize: ", str.bytesize) produces this output: My String's encoding: UTF-8 My String's size: 7 My String's bytesize: 9 You can make the following observations about the above code: The string literal creates an object which has several accessible methods. The string has attached encoding information indicating it's an UTF-8 string. A String's size corresponds to the umber of characters we see. A String's bytesize corresponds to the actual space taken by the characters in memory (the ♥ symbol requires bytes instead of ). Although is the most popular (and recommended) encoding style for content, Ruby supports other encodings (try for the full list). With this in mind, we should learn how to convert between different encodings. Task In this challenge, we practice setting the encoding information for some string of text using Ruby's Encoding methods. Write a function named transcode which takes a encoded string as a parameter, converts it to an encoded string, and returns the result. Input Format Our hidden code checker will call your function, passing it an encoded string as an argument. Constraints Your function must be named transcode. Output Format Your function must return an UTF-8 encoded string. def transcode(str) str = str.force_encoding(Encoding::UTF_8) return str end
require 'syro' require_relative '../service/anagrams' require_relative '../service/anagrams_plus' # Guideline: Return an empty array when possible for sad cases class AnagramsAdapter < Syro::Deck def self._ensure_anagrams unless @anagrams raise "Need to add words before we can make anagram magic." end end def self.add_words(word_list) @anagrams ||= Anagrams.new @anagrams.add_words(word_list) self end def self.find_anagrams_for(word, options = {}) self._ensure_anagrams @anagrams.find_anagrams_for(word, options) end def self.delete_all @anagrams = Anagrams.new end def self.delete_word(word) self._ensure_anagrams @anagrams.delete_word(word) self end def self.delete_word_and_anagrams(word) self._ensure_anagrams @anagrams.delete_word_and_anagrams(word) end def self.count @anagrams.words.count end def self.stats self._ensure_anagrams AnagramsPlus.stats(@anagrams.words) end def self.assert_are_anagrams(word1, word2) self._ensure_anagrams if @anagrams.words.include?(word1) and @anagrams.words.include?(word2) self.find_anagrams_for(word1).include?(word2) else false end end end __END__ Q: How should operations before a Anagram is created be handled? A: Throw an exception, API layers should be explicit.
class Card < ApplicationRecord #validates :name, presence: { strict:true, message:"admin"} #validates_presence_of(:name,:number,:message=>"姓名和账号不能为空") #validates_uniqueness_of(:name,:message=>"名称不能重复") #validates_size_of(:name,:maximum=>4,:message=>"长了") #validate :validate #validates_format_of(:number,with:/\A\d{5,16}\z/,message:"格式有误") def before_delete return false end #validates_numericality_of(:money,:odd=>true, :greater_than_or_equal_to=>300,:message=>"钱有问题") def validate if number.blank? errors.add(:number, "用户账号不能为空!") end if not number.match(/\A\d{6,16}\z/) errors.add(:number, "账号格式有误!") end end end
class AccountingType < ActiveRecord::Base has_many :accounting_categories end
class CreateSubcontractEquipmentDetails < ActiveRecord::Migration def change create_table :subcontract_equipment_details do |t| t.integer :article_id t.string :description t.string :brand t.string :series t.string :model t.date :date_in t.integer :year t.float :price_no_igv t.integer :rental_type_id t.string :minimum_hours t.integer :amount_hours t.float :contracted_amount t.timestamps end end end
feature 'new' do scenario 'you can add a new listing' do visit '/' click_on 'Sign up' fill_in('first_name', with: 'Theodore') fill_in('last_name', with: 'Humpernickle') fill_in('username', with: 'ttotheh') fill_in('email', with: 'theodore@humpernickle.com') fill_in('password', with: 'ilovesweeties') fill_in('confirm', with: 'ilovesweeties') click_button 'Submit' click_button 'Add listing' expect(page).to have_content 'Name' expect(page).to have_content 'City' expect(page).to have_content 'Country' expect(page).to have_content 'Sleeps' expect(page).to have_content 'Bedrooms' expect(page).to have_content 'Bathrooms' expect(page).to have_content 'Description' expect(page).to have_content 'Type' expect(page).to have_content 'Price' end end
# encoding: UTF-8 require 'forwardable' module MongoMapper module Plugins module Querying module PluckyMethods extend Forwardable def_delegators :query, :where, :filter, :fields, :ignore, :only, :limit, :paginate, :per_page, :skip, :offset, :sort, :order, :reverse, :count, :distinct, :last, :first, :find_one, :all, :find_each, :find, :find!, :exists?, :exist? end end end end
class AddAvatarsCacheToUsers < ActiveRecord::Migration def up add_column :users, :easy_avatar, :string, {:length => 255, :null => true} end def down remove_column :users, :easy_avatar end end
puts ":seedling: Seeding spices..." # Seed your database here # This will delete any existing rows from the game and User tables # so you can run the seed file multiple times without having duplicate entries in your database puts "Deleting old data..." Game.destroy_all User.destroy_all GameLibrary.destroy_all puts "Creating users..." user1 = User.create(name: "Tina") user2 = User.create(name: "Gabriel Miranda") user3 = User.create(name: "Gabe") user4 = User.create(name: "Francisco") puts "Creating games..." game1 = Game.create(game_title: "New World", price: 39.99, game_developer: "Amazon Game Studios", genre:"MMO, RPG", description: "Gabe likes this") game2 = Game.create(game_title: "Slay the Spire", price: 20.00, game_developer: "Mega Crit Games", genre:"Roguelike, Deck-building game, Strategy video game", description: "Gabe likes this") game3 = Game.create(game_title: "Stardew Valley", price: 5, game_developer: "Eric Barone", genre: "Simulation, Casual, Role-Playing, Indie", description: "Tina likes this") game4 = Game.create(game_title: "God of War", price: 50, game_developer: "Santa Monica Studios", genre: "Hack and slash, Action-Adventure", description: "Francisco likes this") # t.integer :game_id # t.integer :user_id # t.date :timestamp puts "Creating game libraries..." game_library1 = GameLibrary.create(game_id: game1.id, user_id: user1.id) game_library2 = GameLibrary.create(game_id: game2.id, user_id: user2.id) game_library3 = GameLibrary.create(game_id: game3.id, user_id: user2.id) game_library4 = GameLibrary.create(game_id: game3.id, user_id: user3.id) #profile3 = Profile.create(game_id: 3, user_id: 1) puts ":white_check_mark: Done seeding!"
# frozen_string_literal: true require 'json' require 'rest-client' require 'timeout' class GemnasiumClient attr_reader :api def initialize api_key = Settings.GEMNASIUM_API_TOKEN @api = "https://X:#{api_key}@api.gemnasium.com/v1" end def all_projects_and_counts advisories = {} all_projects.each do |slug| alerts = fetch_api("#{api}/projects/#{slug}/alerts") advisories[slug] = alerts.count end advisories end def all_dependencies gems = {} all_projects.each do |slug| gems[slug] = [] fetch_api("#{api}/projects/#{slug}/dependencies").each do |gem| next unless gem['package']['type'] == 'Rubygem' dep = { 'name' => gem['package']['name'], 'version' => gem['locked'] } gems[slug].push(dep) end end gems end private def all_projects slugs = [] url = "#{api}/projects" projects = fetch_api(url) projects['owned'].each do |project| next unless project['monitored'] slugs.push(project['slug']) end slugs end # rubocop:disable MethodLength def fetch_api(url) attempts = 0 data = {} success = false while attempts <= 3 begin Timeout.timeout(30) do data = JSON.parse(RestClient.get(url, method: 'get', ssl_verion: 'TLSv1', ssl_ciphers: ['RC4-SHA'])) success = true end rescue Timeout::Error, Net::HTTPRetriableError, OpenSSL::SSL::SSLError, RestClient::SSLCertificateNotVerified sleep(10) end break if success attempts += 1 end data end # rubocop:enable MethodLength end
class SummaryController < ApplicationController def show @riders_count = Rider.count @stages = StageDecorator.decorate_collection(Stage.order("id")) # Stage results stage = Stage.last_stage || Stage.order("number").first if stage.nil? redirect_to :action => :not_found and return end @stage = stage.decorate @stage_players = sort_players_by_stage_points(PlayerDecorator.decorate_collection(Player.active), @stage).shift(10) @stage_riders = sort_riders_by_stage_points(RiderDecorator.decorate_collection(Rider.active), @stage).shift(10) # Overall results @players = PlayerDecorator.decorate_collection(Player.active.order("points DESC").limit(10)) @riders = RiderDecorator.decorate_collection(Rider.active.order("points DESC").limit(10)) # Selected player player = Player.find_by_id(params[:player_id]) || current_player || @stage_players.first @player = player.decorate end def not_found end end
# # Cookbook:: managed_directory # Recipe:: test # # A simple demonstration of managed_directory, also used by chefspec. testdir = '/tmp/bar' # Setup the test. # 1. Create the directory for our test files, during the compile phase. directory testdir do action :nothing end.run_action(:create) # 2. Put some files in it, without using Chef, before convergence unless defined?(ChefSpec) %w(a b c).each do |d| Chef::Log.warn("Creating test directory #{testdir}/#{d}_dir") ::Dir.mkdir("#{testdir}/#{d}_dir") unless ::Dir.exist?("#{testdir}/#{d}_dir") end # stuff some files into c_dir %w(a b c).each do |f| Chef::Log.warn("Creating test file #{testdir}/c_dir/#{f}") ::File.new("#{testdir}/c_dir/#{f}", 'w+') unless ::File.exist?("#{testdir}/c_dir/#{f}") end end # Create a directory resource for 'a_dir' directory "#{testdir}/a_dir" do action :create end # Define the managed_directory and have it clean directories, too managed_directory testdir do action :clean clean_directories true clean_files false end # Create a directory resource for 'b_dir' # Note that the order of resources doesn't matter - managed_directory will # not clean up this file. directory "#{testdir}/b_dir" do action :create end # At the end of a Chef run containing this recipe, /tmp/foo should contain # subdirectories "a_dir" and "b_dir". Subdirectory "c_dir" should have been # removed.