text
stringlengths
10
2.61M
# Uncomment the next line to define a global platform for your project platform :ios, '9.0' target 'jumpit' do # Comment the next line if you don't want to use dynamic frameworks # use_frameworks! # Pods for jumpit # Required by RNFirebase pod 'Firebase/Core', '~> 6.3.0' pod 'GoogleIDFASupport', '~> 3.14.0' pod 'Firebase/Messaging', '~> 6.3.0' pod 'Firebase/Storage', '~> 6.3.0' pod 'RNDeviceInfo', :path => '../node_modules/react-native-device-info' pod 'React', :path => '../node_modules/react-native' # Explicitly include Yoga if you are using RN >= 0.42.0 pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga' # React-Native is not great about React double-including from the Podfile pod 'rn-fetch-blob', :path => '../node_modules/rn-fetch-blob' post_install do |installer| installer.pods_project.targets.each do |target| if target.name == "React" target.remove_from_project end # It removes React & Yoga from the Pods project, as it is already included in the main project. targets_to_ignore = %w(React yoga) if targets_to_ignore.include? target.name target.remove_from_project end end end target 'jumpitTests' do inherit! :search_paths # Pods for testing end end target 'jumpit-tvOS' do # Comment the next line if you don't want to use dynamic frameworks use_frameworks! # Pods for jumpit-tvOS target 'jumpit-tvOSTests' do inherit! :search_paths # Pods for testing end end
class BookAssignment < ApplicationRecord belongs_to :user belongs_to :book, polymorphic: true has_many :feeds, dependent: :destroy has_many :subscriptions, dependent: :destroy has_many :delayed_job_for_emails, through: :feeds has_many :delayed_job_for_webpushs, through: :feeds scope :by_unpaid_users, -> { joins(:user).where(users: { plan: 'free' }) } scope :upcoming, -> { where("? <= end_date", Date.current) } validates :start_date, presence: true validates :end_date, presence: true validate :delivery_should_start_after_trial # トライアル開始前の配信予約は不可 validate :end_date_should_come_after_start_date validate :delivery_period_should_not_overlap # 同一チャネルで期間が重複するレコードが存在すればinvalid validate :end_date_should_not_be_too_far # 12ヶ月以上先の予約は禁止 def count (end_date - start_date).to_i + 1 end def create_and_schedule_feeds feed_ids = create_feeds Feed.find(feed_ids).map(&:schedule) end def create_feeds feeds = [] contents = self.book.contents(count: count) delivery_date = self.start_date contents.each.with_index(1) do |content, index| title = self.book.title feeds << { title: title, content: content, delivery_date: delivery_date, book_assignment_id: self.id } delivery_date += 1.day end res = Feed.insert_all feeds res.rows.flatten # 作成したfeedのid一覧を配列で返す end # メール配信対象 ## 公式チャネルのときは有料会員全員。それ以外のときはEmailのSubscription def send_to user.admin? ? User.basic_plan.pluck(:email) : subscriptions.deliver_by_email.preload(:user).map(&:user).pluck(:email) end def status if Date.current < start_date "配信予定" elsif Date.current > end_date "配信終了" else "配信中" end end def status_color case status when "配信予定" "blue" when "配信中" "orange" when "配信終了" "gray" end end def twitter_short_url begin Bitly.call(path: 'shorten', params: { long_url: self.twitter_long_url }) rescue => e logger.error "[Error] Bitly API failed: #{e}" end end def twitter_long_url "https://twitter.com/intent/tweet?url=https%3A%2F%2Fbungomail.com%2F&hashtags=ブンゴウメール,青空文庫&text=#{start_date.month}月は%20%23#{book.author_name}%20%23#{book.title}%20を配信中!" end private # 同一チャネルで期間が重複するレコードが存在すればinvalid(Freeプランのみ) def delivery_period_should_not_overlap return if user.basic_plan? # Basicプランは重複許可 overlapping = BookAssignment.where.not(id: id).where(user_id: user_id).where("end_date >= ? and ? >= start_date", start_date, end_date) errors.add(:base, "予約済みの配信と期間が重複しています") if overlapping.present? end def end_date_should_come_after_start_date errors.add(:base, "配信終了日は開始日より後に設定してください") if end_date < start_date end def end_date_should_not_be_too_far errors.add(:base, "配信終了日は現在から12ヶ月以内に設定してください") if end_date > Date.current.since(12.months) end def delivery_should_start_after_trial errors.add(:base, "配信開始日は無料トライアルの開始日以降に設定してください") if user.trial_start_date && start_date < user.trial_start_date end end
# Copyright (c) 2015 - 2020 Ana-Cristina Turlea <turleaana@gmail.com> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # WickedPDF Global Configuration # # Use this to set up shared configuration options for your entire application. # Any of the configuration options shown here can also be applied to single # models by passing arguments to the `render :pdf` call. # # To learn more, check out the README: # # https://github.com/mileszs/wicked_pdf/blob/master/README.md WickedPdf.config = { # Path to the wkhtmltopdf executable: This usually isn't needed if using # one of the wkhtmltopdf-binary family of gems. # exe_path: '/usr/local/bin/wkhtmltopdf', # or # exe_path: Gem.bin_path('wkhtmltopdf-binary', 'wkhtmltopdf') # Layout file to be used for all PDFs # (but can be overridden in `render :pdf` calls) # layout: 'pdf.html', }
require "colorize" module Lib class Scenario class << self # # [ITERATION] # $schd: omi schedule delete schedule=$ # def get_pkey key = ARGV.select{ |a| a.start_with?("pkey_") }.first key end def get_skey key = ARGV.select{ |a| a.start_with?("skey_") }.first key end def all_scenarios Dir["/usr/local/etc/omi/scenario/*"] end def choose_scenario(scenarios) if scenarios.size == 1 return scenarios[0] end puts scenarios.each_with_index do |s, i| puts "[#{i}] #{File.basename(s)}" end puts print("[q: quit e\\s\\d+: edit n: new] ") input = $stdin.gets.chomp if input == "n" print "[New Scenario Name]: " file = "/usr/local/etc/omi/scenario/" + $stdin.gets.chomp + ".story" system "vim #{file}" choose_scenario(scenarios) elsif /^e\s+\d+$/ =~ input index = /\d+/.match(input).to_s.strip.to_i if scenarios.size > index file = scenarios[index] system "vim #{file}" else puts "Index is Out of Range".red end choose_scenario(scenarios) elsif /^\d+$/ =~ input scenarios[input.to_i] elsif input == "q" abort else regex = Regexp.new(input.gsub(" ", ".+")) scenarios = scenarios.select{|s| regex =~ s} choose_scenario(scenarios.empty? ? all_scenarios : scenarios) end end def get_story_path choose_scenario(all_scenarios) end def process_echo(instruction) if instruction.start_with?("echo ") puts("\n---------------------------------------------------\n\n") puts(instruction.gsub("echo ", "").chomp.blue) puts("\n---------------------------------------------------") end end def process_loop_omi(instruction, hash, result) if /\$.+\:\s+omi\s+.+/ =~ instruction prefix = /\$[^\:]+/.match(instruction).to_s value = hash[prefix] instruction = instruction.gsub("#{prefix}:", "").strip if value.class == String value = [value] end value.each do |x| command = instruction.gsub("$", x) puts command system command end end end def assert(instruction, result) if instruction.start_with?("assert ") regex = Regexp.new(instruction.gsub("assert ", "").strip.gsub(" ", ".+")) print("ASSERT #{regex.to_s}: [") if regex =~ result print("OK".green) else print("NG".red) end puts("]") end end def process_shell(instruction) if instruction.start_with?("shell:") system instruction.gsub("shell:", "") end end def process_omi(instruction, hash, result) ask = true if instruction.start_with?("omi ") if instruction.include?("--no-ask") instruction = instruction.gsub("--no-ask", "") ask = false end hash.each do |k, v| unless k.strip.include?(" ") return result if v.class == Array instruction = instruction.gsub(k, v) end end if ask print(instruction.chomp) print(" [Y/n]: ") input = $stdin.gets.chomp.downcase abort if input == "n" end result = `#{instruction}`.split("[Result]") command = result[0] response = result[1] puts command print("[response]> ") if ask $stdin.gets.chomp end puts(response) result = response end result end def assign(instruction, result, hash) if /\$.+=.+/ =~ instruction isp = instruction.split("=").map{ |x| x.strip.chomp } variable = isp[0] regex = Regexp.new(isp[1].gsub("_", "\\_") + "[^\"\/]+") if /{.+}/ =~ variable variable = variable.gsub("{", "").gsub("}", "") match = result .split("\n") .select { |line| regex =~ line } .map { |line| regex.match(line).to_s } .uniq else match = regex.match(result).to_s end hash[variable] = match puts "ASSIGNED: #{variable} => #{match}" end hash end def execute(story_path=get_story_path) result = "" hash = {} File.open(story_path, "r").each do |instruction| if instruction.strip == "abort" abort end if !(instruction.start_with?("#") && instruction.strip.chomp) process_shell(instruction) process_echo(instruction) result = process_omi(instruction, hash, result) hash = assign(instruction, result, hash) assert(instruction, result) process_loop_omi(instruction, hash, result) end end puts "\n[Scenario Completed]\n".magenta execute end end end end
class FavouritesController < ApplicationController before_action :find_recipe, except: :user_favourites before_action :authenticate_user! def create @favourite = Favourite.new(myrecipe: @myrecipe) @favourite.user = current_user if @favourite.save redirect_to @myrecipe, notice: 'this recipe is saved to your favourites.' else redirect_to @myrecipe, alert: @favourite.errors.full_messages.join(", ") end end def destroy @favourite = Favourite.find_by(myrecipe_id: current_user.favourite_recipes.find(@myrecipe.id)) if @favourite.destroy redirect_to @myrecipe, notice: 'this recipe has been removed from your favourites.' else redirect_to @myrecipe, alert: @favourite.errors.full_messages.join(", ") end end # def user_favourites # @favourite_recipes = current_user.favourite_recipes # end # def index # end # def show # redirect_to 'myrecipes/show' # end private def find_recipe @myrecipe = Myrecipe.find(params[:myrecipe_id]) end end
module WLang class Parser # # Encapsulates all state information of a WLang parser # class State # The attached parser attr_accessor :parser # The parent state attr_accessor :parent # The current hosted language attr_accessor :hosted # The current template attr_accessor :template # The current dialect attr_accessor :dialect # The current offset in template's source code attr_accessor :offset # The current scope attr_accessor :scope # The current output buffer attr_accessor :buffer # Creates a new state instance for a given parser and optional # parent. def initialize(parser, parent = nil) @parser, @parent = parser, parent end # Checks internals def check raise "WLang::Parser::State fatal: invalid parser #{parser}" unless ::WLang::Parser===parser raise "WLang::Parser::State fatal: invalid hosted #{hosted}" unless ::WLang::HostedLanguage===hosted raise "WLang::Parser::State fatal: missing template #{template}" unless ::WLang::Template===template raise "WLang::Parser::State fatal: missing dialect #{dialect}" unless ::WLang::Dialect===dialect raise "WLang::Parser::State fatal: missing offset #{offset}" unless Integer===offset raise "WLang::Parser::State fatal: missing scope #{scope}" unless ::WLang::HashScope===scope raise "WLang::Parser::State fatal: missing buffer #{buffer}" unless buffer.respond_to?(:<<) self end # # Branches this state. # # Branching allows creating a child parser state of this one. Options are: # - :hosted => a new hosted language # - :template => a new template # - :dialect => a new dialect # - :offset => a new offset in the template # - :shared => :all, :root or :none (which scoping should be shared) # - :scope => a Hash of new pairing to push on the new scope # - :buffer => a new output buffer to use # def branch(opts = {}) child = State.new(parser, self) child.hosted = opts[:hosted] || hosted child.template = opts[:template] || template child.dialect = opts[:dialect] || child.template.dialect child.offset = opts[:offset] || offset child.buffer = opts[:buffer] || child.dialect.factor_buffer child.scope = case opts[:shared] when :all, NilClass scope.branch(opts[:scope]) when :root scope.root.branch(opts[:scope]) when :none ::WLang::HashScope.new(opts[:scope]) else raise ArgumentError, "Invalid ParserState.branch option :shared #{opts[:shared]}" end child.check end # Returns a friendly location for this parser state def where template ? template.where(offset) : "Source template tree" end # Returns a friendly wlang backtrace as an array def backtrace parent ? parent.backtrace.unshift(where) : [where] end end # class State end # class Parser end # module WLang
require 'bundler' require 'pp' require 'csv' require_relative 'conf_loader/override_reconciliation.rb' require_relative 'conf_loader/group_hash.rb' class ConfLoader attr_reader :overrides, :file_path $overrides_count = Hash.new $group_name = nil GROUP_PATTERN = /^\[[^\]\r\n]+\](?:\r?\n(?:[^\[\r\n].*)?)*/ ENABLED_VALUES = ['1', 'yes', 'true'] DISABLED_VALUES = ['0', 'no', 'false'] def initialize(file_path, overrides=[]) @file_path = file_path @overrides = overrides end def process rank_overrides(overrides) # Initially i thought about loading the file into memory # After i read the requirements few times I decided it might not be a good idea # Decided to use this route after reading http://stackoverflow.com/a/5546681/396850 File.foreach(file_path) do |line| unless line next end parse(line) end load_from_config_store(config_store) pp config_store end # if overrides are passed in, creates a hash of overrides to its index # in the array, this is to ensure that override with maximum index # value is prioritized in reconciliation def rank_overrides(overrides) $overrides_count= Hash[overrides.each_with_index.map {|x,i| [x.to_s, i+1]}] end # core business logic resides in this method. # The idea is to parse each line, figure if it has a [config] associated # if so parse its properties and finally based on the overrides passed in # reconcile the correct value to those properties if any of them has multiple # configurations. # Modularized and delegated this to additional helper methods for readability. def parse(line) line.strip! line = remove_comments_from_line(line) if line.empty? return end if (parsedGroupName = parse_group_name(line)) $group_name = parsedGroupName elsif (kv_pair_obj = parse_key_value(line)) k,v=kv_pair_obj parse_and_reconcile_overridden_values(k,v,$group_name) else raise 'unrecognized format' << line end end # replace anything starting with ; with white space def remove_comments_from_line(line) line.gsub(/;.*$/, '') end # pattern match a line to see if it has the GROUP_PATTERN # e.g [FTP] def parse_group_name(line) groupPattern = line.match(GROUP_PATTERN) unless groupPattern return nil end group = groupPattern[0] group = group[1..group.length - 2] if group =~ /\s/ raise 'Illegal Character: Group name contains whitespace ' << group end group end # this does a simple split based on '=' # once key and values are split it trims the quotes around them # if they are strings. def parse_key_value(line) parts = line.split('=') return nil if parts.length != 2 k, v = parts.map(&:strip) v = CSV.parse_line(v).map{|s| removeQuotes(s) } v = v.first if v.length == 1 [k, v] end # used by parse_key_value() method to trim the quotes def removeQuotes(str) str.gsub(/^[\'\"]/, '').gsub(/[\'\"]$/, '') end # If not for overrides the logic is relatively small. # This method checks for existence for Config<Overridden> # if there is no override value is simply stored into the # OverrideReconciliation object's value field into the bucket of groupName. # if there is an override present the reconciliation is done # by using the overrides_count hash which was preprocessed earlier # and the OverrideReconciliation # object's override and overridden_value are updated accordingly # and it's stored of the form below # [:group]=>[:propertyKey]=>[OverrideReconciliationObject] is stored in memory def parse_and_reconcile_overridden_values(key,value,group) key, override = parse_key_with_override(key) extractedValue = extract_value(value) override_reconciliation = get_value(key,group) if override_reconciliation if override if override_reconciliation.has_new_override_more_priority(override, $overrides_count) override_reconciliation.override = override override_reconciliation.overridden_value = extractedValue end else override_reconciliation.value = extractedValue end else set_value(key, OverrideReconciliation.new(extractedValue, override, extractedValue),group) end end # Looks for PropertyKey<Override> to extract key # and the override individually def parse_key_with_override(str) pattern = /(?<name>\w+)(\<(?<override>\w+)\>)?/ matcher = pattern.match(str) raise "unrecognized key format: #{str.inspect}" unless matcher [matcher[:name], matcher[:override]].compact end def extract_value(val) if val.is_a?(Array) return val end if ENABLED_VALUES.include?(val) return true end if DISABLED_VALUES.include?(val) return false end int = val.to_i if int.to_s == val return int end val end # Recursive helper to extract the # [:group]=>[:propertyKey]=>[OverrideReconciliationObject] # into a config object which can be queried. # The logic ascertains if its a Hash or an Object if it's an hash # its value is passed recursively or if its an OverrideReconciliation # object its overridden value is extracted. def load_from_config_store(hash) hash.each_with_object(GroupHash.new) do |(key, value), memo| memo[key.to_sym] = case value when Hash load_from_config_store(value) when OverrideReconciliation value.overridden_value else raise "unexpected value when converting: #{value}" end end end def config_store @memory ||= Hash.new { |hash, key| hash[key] = {} } end def get_value(key,group) config_store[group][key] end def set_value(key, value,group) config_store[group][key] = value end end
require 'spec_helper' RSpec.describe "Rate", type: :feature, vcr: true do context "find" do it "is successful with existing items" do VCR.use_cassette("rate_find") do response = Shipwire::Rate.new.find(payload) expect(response.ok?).to be_truthy expect(response.body["resource"]["rates"].count).to be >= 1 end end it "fails with non existing items" do VCR.use_cassette("rate_find_fail") do bad_payload = payload bad_payload[:order][:items][0][:sku] = 'FAKE-PRODUCT' response = Shipwire::Rate.new.find(bad_payload) expect(response.ok?).to be_falsy expect(response.validation_errors.first).to include( "message" => "unknown SKU 'FAKE-PRODUCT'" ) end end def payload { options: { currency: "USD", groupBy: "all" }, order: { shipTo: { address1: "540 West Boylston St.", city: "Worcester", postalCode: "01606", region: "MA", country: "US" }, items: [{ sku: "TEST-PRODUCT", quantity: 1 }] } } end end end
# Read about factories at http://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :area_code do sequence(:name) { |n| "AreaCode #{n}" } sequence(:area_code) { |n| "#{n}" } association :country end end
require 'rake/testtask' require 'rdoc/task' require 'fileutils' GEMSPEC = 'ivar_encapsulation.gemspec' Rake::TestTask.new do |t| t.pattern = 'test/test_*.rb' end Rake::RDocTask.new do |rd| rd.rdoc_dir = 'doc/' rd.main = "README.rdoc" rd.rdoc_files.include("README.rdoc", "lib/**/*.rb") rd.title = 'ivar_encapsulation' rd.options << '--line-numbers' rd.options << '--all' end def gemspec @gemspec ||= eval(File.read(GEMSPEC), binding, GEMSPEC) end namespace :gem do desc "Validate the gemspec" task :validate_gemspec do gemspec.validate end desc "Build the gem" task :build => :validate_gemspec do sh "gem build #{GEMSPEC}" FileUtils.mkdir_p 'pkg' FileUtils.mv "#{gemspec.name}-#{gemspec.version}.gem", 'pkg' end desc "Install the gem locally" task :install => :build do sh "gem install pkg/#{gemspec.name}-#{gemspec.version}.gem" end end task :default => [:test]
class ResourcesController < ApplicationController before_filter :authorize, :except => [:list, :new, :create, :show] layout "nosidebar" def list @title = "Indonesian Language Resources" @resources = Resource.reviewed render :layout => 'resource' end # GET /resources # GET /resources.xml def index @title = "Indonesian Language Resources" @resources = Resource.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @resources } end end # GET /resources/1 # GET /resources/1.xml def show @resource = Resource.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @resource } end end # GET /resources/new # GET /resources/new.xml def new @resource = Resource.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @resource } end end # GET /resources/1/edit def edit @resource = Resource.find(params[:id]) end # POST /resources # POST /resources.xml def create @resource = Resource.new(params[:resource]) @resource.status = User.find_by_id(session[:user_id]) ? "reviewed" : "draft" respond_to do |format| if @resource.save if User.find_by_id(session[:user_id]) flash[:notice] = 'Resource was successfully created.' else notify_resource_added(@resource, request) flash[:notice] = 'Thank you for adding the resource. It will appear in the resource list after we have reviewed it.' end format.html { redirect_to(@resource) } format.xml { render :xml => @resource, :status => :created, :location => @resource } else format.html { render :action => "new" } format.xml { render :xml => @resource.errors, :status => :unprocessable_entity } end end end # PUT /resources/1 # PUT /resources/1.xml def update @resource = Resource.find(params[:id]) respond_to do |format| if @resource.update_attributes(params[:resource]) flash[:notice] = 'Resource was successfully updated.' format.html { redirect_to(@resource) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @resource.errors, :status => :unprocessable_entity } end end end # DELETE /resources/1 # DELETE /resources/1.xml def destroy @resource = Resource.find(params[:id]) @resource.destroy respond_to do |format| format.html { redirect_to(resources_url) } format.xml { head :ok } end end protected # def authorize # unless User.find_by_id(session[:user_id]) # session[:original_uri] = request.request_uri # flash[:notice] = "Please log in" # redirect_to :controller => 'admin' , :action => 'login' # end # end def notify_resource_added(resource, request) email = OrderMailer.create_resource_added(resource, request) Thread.new(email) do |e| OrderMailer.deliver(email) end end end
class AddColumnBreakToPractiAvail < ActiveRecord::Migration def change add_column :practi_avails, :all_break, :text end end
namespace :statuses do desc "Tasks for pre-loading default status data." # Colors taken from here http://www.bbc.co.uk/gel/guidelines/how-to-design-infographics task seed: :environment do #Danger! Status.destroy_all #now create Status.create!([{ name: "Not started", description: "We haven't started working on this, yet.", ordinal: 0, hex_color: '#566' }, { name: "On track", description: "Confidence above 70%.", ordinal: 1, hex_color: '#5a8c3e' }, { name: "At risk", description: "Confidence 40", ordinal: 3, hex_color: '#FC0' }, { name: "In trouble", description: "Confidence below 40%", ordinal: 3, hex_color: '#9d1c1f' }, { name: "Finished", description: "Done! Or at least, as done as it's going to get. No further work planned on this goal. Check narrative for final state and 'Lessons Learned'.", ordinal: 4, require_learnings: true, hex_color: '#4a777c' }, { name: "Cancelled", description: "We've stopped work on this goal for some reason and don't plan to restart. Check narrative and lessons learned for detail.", ordinal: 5, require_learnings: true, hex_color: '#000' }]) p "Created default statuses" end end
require 'rails_helper' RSpec.describe Auth::Slack do describe 'POST /api/v1/auth/slack' do it 'returns an auth token' do auth_double = instance_double( SlackAuth, user_info: { 'name' => 'John Doe', 'email' => 'foo@bar.com' } ) expect(SlackAuth).to receive(:new).with('AUTH_CODE').and_return(auth_double) expect(AuthToken).to receive(:encode) .and_return('AUTH_TOKEN') post '/api/v1/auth/slack', code: 'AUTH_CODE' expect(response.code).to eq '201' expect(JSON.parse(response.body)['auth_token']).to eq 'AUTH_TOKEN' expect(User.count).to eq 1 end end end
#Create a class called Deli that has one instance variable: line. #In our deli, we should be able to call "take a number" that takes a customer's name, appends their number to their name and #adds them to the line. #The line could look like this: ["1. Ashley", "2. Steve", "3. Blake"] #Additionally we should be able to call a method called "now_serving" that #removes the customer who is first in line and #returns their name. #Write a test and then write the class. class Deli def initialize @line = [] end def take_a_number(name) num = @line.length + 1 @line << "#{num}. #{name}" #this is where test needs access to array end def now_serving #find index[0] puts "Now serving #{@line[0]}" unless @line.empty? == true return @line.slice!(0) end end deli_name = Deli.new deli_name.take_a_number("Tessa") deli_name.take_a_number("Jim") deli_name.now_serving deli_name.now_serving deli_name.now_serving puts deli_name
class ApplicationController < ActionController::Base add_flash_types :success, :warning, :danger, :info protect_from_forgery with: :exception rescue_from CanCan::AccessDenied do |exception| redirect_to root_url, alert: exception.message end end
FactoryGirl.define do factory :comment do sequence :description do |n| "the contribution to the event test ##{n}" end end end
module Crawlers module Dia class UpdateCrawler < Crawlers::ApplicationCrawler DIA_PRODUCTS = Product.where(market_name: 'dia') class << self def execute update_dia_products end private def update_dia_products DIA_PRODUCTS.each do |product_model| begin product_html = Nokogiri::HTML(open(product_model.url)) # Update title update_title(product_model, product_html) # Update price update_price(product_model, product_html) rescue # TODO: Implement availability attribute # NOTE: THERE IS NOT YET A WAY TO CHECK # THE PRODUCT AVAILABILITY AT DIA puts "URL ZUADA: #{product_model.name} (#{product_model.market.name})" end end end # check if price changed # do nothing if it did not def update_price(product_model, product_html) price = product_html.css('.line.price-line p.bestPrice span.val') .text.gsub('R$', '').gsub(',', '.') .strip.to_f if !price.zero? && product_model.price != price # if it changed, create a new price history and add it to the product new_price = PriceHistory.create(old_price: product_model.price, current_price: price, product: product_model) product_model.update(price: price) puts "PREÇO ATUALIZADO. #{product_model.name}: #{product_model.price_histories.order(:created_at).last.old_price} -> #{product_model.price_histories.order(:created_at).last.current_price}" end end # Update title def update_title(product_model, product_html) product_name = product_html.css('h1.nameProduct').text.strip # Fix product name if it has wrong encoding # So it is not updated incorrectly product_name = Applications::NurseBot.treat_product_name(product_name) if is_sick?(product_name) if product_name.present? && product_model.name != product_name puts "NOME ATUALIZADO. #{product_model.name} -> #{product_name}" product_model.update(name: product_name) end end end end end end
Vagrant.configure("2") do |config| config.vm.box = "centos/7" config.vm.box_check_update = false config.vm.provider 'virtualbox' do |box| box.cpus = 1 box.memory = "512" end config.vm.provision :shell, :preserve_order => true, :inline => "echo $(hostname -a); echo $(hostname -I)" config.vm.define :server do |box| box.vm.hostname = "dhcp" box.vm.network :private_network, :ip => "192.168.60.4", :virtualbox__intnet => true box.vm.provision :shell, :preserve_order => true, :inline => <<-SCRIPT sudo yum install -y dhcp tcpdump > /dev/null 2>&1 sudo cp /vagrant/dhcp.conf /etc/dhcp/dhcpd.conf sudo systemctl start dhcpd SCRIPT end config.vm.define :client_mac do |box| box.vm.hostname = "dhcp-client-mac" box.vm.network :private_network, :type => "dhcp", :mac => "5CA1AB1E0001", :virtualbox__intnet => true end config.vm.define :client_dyn_ip do |box| box.vm.hostname = "dhcp-client-ip" box.vm.network :private_network, :type => "dhcp", :virtualbox__intnet => true end end
Given /^I am logged into the mobile website$/ do visit(HomePage) do |page| page.mainmenu_button page.login_button end on(LoginPage) do |page| page.login_with(ENV["MEDIAWIKI_USER"], ENV["MEDIAWIKI_PASSWORD"]) if page.text.include? "There is no user by the name " puts ENV["MEDIAWIKI_USER"] + " does not exist... trying to add user" on(HomePage).create_account_element.when_present.click on(LoginPage) do |page| page.username_element.element.when_present.set ENV["MEDIAWIKI_USER"] page.signup_password_element.element.when_present.set ENV["MEDIAWIKI_PASSWORD"] page.confirm_password_element.element.when_present.set ENV["MEDIAWIKI_PASSWORD"] page.signup_submit_element.element.when_present.click page.text.should include "Welcome, " + ENV["MEDIAWIKI_USER"] + "!" #Can't get around captcha in order to create a user end end end end Given /^I am in beta mode$/ do visit(BetaPage) do |page| page.beta_element.click page.save_settings end end Given /^I am not logged in$/ do # nothing to do here, user in not logged in by default end When /^I go to random page$/ do visit(RandomPage) end
# frozen_string_literal: true require_relative './spec_helper.rb' describe 'Rubygems_call specifications' do before do VCR.insert_cassette RUBYGEMS_CASSETTE_FILE, record: :new_episodes @object = ApiCall::RubyGemsCall.new(ENV['GEM_NAME']) end after do VCR.eject_cassette end it 'should be able new a ApiCall::RubyGemsCall object' do @object.must_be_instance_of ApiCall::RubyGemsCall end it 'should be able to get response from the total_download_trend' do @object.version_downloads.wont_be_nil end end
class WorkfileName def self.resolve_name_for!(workfile) if Workfile.exists?(:file_name => workfile.file_name, :workspace_id => workfile.workspace_id) index = workfile.file_name.rindex(".") length = workfile.file_name.length base_file_name = workfile.file_name[0..(index - 1)] extension = workfile.file_name[(index +1), length] workfile_names = Workfile.where("workspace_id = #{workfile.workspace_id} AND file_name LIKE '#{base_file_name}%#{extension}' ").pluck(:file_name) n = 1 while workfile_names.include?("#{base_file_name}_#{n}.#{extension}") do n += 1 end workfile.file_name = "#{base_file_name}_#{n}.#{extension}" end end end
require './src/tokenizer/lexer' require './src/tokenizer/errors' require './spec/contexts/lexer' RSpec.describe Tokenizer::Lexer, 'error handling' do include_context 'lexer' describe '#next_token' do it 'raises an error for declaring a variable with a reserved name' do mock_reader( "空は 10\n" ) expect_error Tokenizer::Errors::VariableNameReserved end it 'raises an error for declaring a parameter with a reserved name' do mock_reader( "空を 測るとは\n" \ " ・・・\n" ) expect_error Tokenizer::Errors::VariableNameReserved end end end
class AddRankingToCompetitionRosters < ActiveRecord::Migration[4.2] def change add_column :competition_rosters, :ranking, :integer, null: true end end
class Part < ActiveRecord::Base include UUIDRecord attr_accessible :description, :name, :program_order, :program_uuid, :uuid belongs_to :program, primary_key: 'uuid', foreign_key: 'program_uuid' has_many :steps, primary_key: 'uuid', foreign_key: 'part_uuid' validates :program_uuid, presence: true # todo: guarantee program_order is correct end
class AddCompleteToMustdos < ActiveRecord::Migration def change add_column :mustdos, :complete, :boolean, default: false end end
s = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." # asignar a la variable p un array generado por split (que es un método para strings) p = s.split #iteramos los valores de p e imprimimos un string con la palabra interpolada --signo gato+llaves = #{o}-- p.each{|o | puts "encontro la palabra #{o}"} ## iteracion encontrar occtaetac p.each do |o| puts "encontro #{o}" if o == "occaecat" end ## iteracion encontrar si es que detecta elementos en variable "claves" claves = ["consectetur", "elit", "incididunt", "labore"] palabras_encontradas = [] p.each do |o| if claves.include?(o) puts "encontro #{o}" #agregamos elementos encontrados al array palabras encontradas. palabras_encontradas << o end end palabras_encontradas ## lo mismo p.each{|o| puts "encontro #{o}" if claves.include?(o) } ## un hash a = {"ropero"=>{} }. Para construir un hash y arrays con categorías y subcategorías (diccionarios de datos) a = {} # inicializamos el hash usando llave, se pone el concepto entre comillas y se encierra en corchete) a["ropero"] a["ropero"] = 1 a["ropero"] a["ropero"].class a["ropero"] = {} a a["ropero"]["cajones"] = [1,2,3,4,5,6,78] a a["ropero"]["cajones"][0] a["ropero"]["cajones"][0] = {:calcetines=>["rojo", "verde"]}
require 'pry' class MP3Importer attr_accessor :path # @@all = [] def initialize(path) @path = path # @@all << self end def files file_list = Dir.entries(@path) file_list.select do |file| file.chars.last(4).join == ".mp3" end # file_list.collect do |file| # file.split('.')[0] # end end def import files.each do |song_file| Song.new_by_filename(song_file) end end end
class InStorePromotersController < ApplicationController layout 'admin' before_action :confirm_logged_in def index @in_store_promoters = InStorePromoter.sorted end def show @in_store_promoter = InStorePromoter.find(params[:id]) end def new @in_store_promoter = InStorePromoter.new({:firstname => 'Default'}) end def create Rails.logger.debug in_store_promoter_params.inspect @in_store_promoter = InStorePromoter.new(in_store_promoter_params) if @in_store_promoter.save flash[:notice] = "in_store_promoter created successfully." redirect_to(in_store_promoters_path) else render('new') end end def edit @in_store_promoter = InStorePromoter.find(params[:id]) end def update @in_store_promoter = InStorePromoter.find(params[:id]) if @in_store_promoter.update_attributes(in_store_promoter_params) flash[:notice] = "in_store_promoter updated successfully." redirect_to(in_store_promoter_path(@in_store_promoter)) else render('edit') end end def delete @in_store_promoter = InStorePromoter.find(params[:id]) end def destroy @in_store_promoter = InStorePromoter.find(params[:id]) @in_store_promoter.destroy flash[:notice] = "ISP '#{@in_store_promoter.firstname} #{@in_store_promoter.lastname}' removed from database forever" redirect_to(in_store_promoters_path) end private def in_store_promoter_params params.require(:in_store_promoter).permit(:firstname, :lastname, :territory_id, :marketing_manager_id, :leads_per_hour, :active) end end
require 'bitwrap/graph' require 'bitwrap/matrix' module Bitwrap class StateVector include Matrix attr_accessor :transitions, :places def initialize(schema) @graph = Graph.new @places = [] @transitions = {} nodes schema['nodes'] edges schema['edges'] reindex refactor end def initial @places.collect { |i| i.last } end def decorate(vector) return if vector.nil? {}.tap do |places| @places.each_with_index do |(label, initial_val), i| places[label] = vector[i] end end end def lookup(pattern) key = pattern.is_a?(Array) ? :value : :label tx = @transitions.find { |i, t| t[key] == pattern } Array(tx)[1] end def transform(vector, tx) return [] unless t = lookup(tx) vadd(t[:value], vector).tap { |vsum| vsum = [] unless valid?(vsum) } end def valid_transitions(vector) @transitions.collect { |i, t| t if valid?(vadd(t[:value], vector)) }.compact end def inhibit(vector, flag=0) [].tap do |vout| decorate(vector).each do |label, value| vout.push (@graph.inhibitors[label].nil?) ? value.to_i : flag end end end def uninhibit(vector) inhibit(vector, 1) end def nodes(nodes) nodes.each do |n| case n['attributes'].delete('type') when 'Place' @graph.place n when 'Transition' @graph.transition n end end end def edges(edges) edges.each do |n| case n['attributes'].delete('type') when 'Arc' @graph.arc n when 'InhibitorArc' @graph.inhibitor_arc n end end end def reindex @graph.transitions.each_with_index do |tx, i| operand = {} vector = [] @graph.arcs.each do |arc| case tx['id'] when arc['target'] arc['source'].tap do |t| operand[t] ||= {} @graph.weights.keys.each do |wgt| operand[t][wgt] = operand[t][wgt].to_i - arc['attributes'][wgt].to_i end end when arc['source'] arc['target'].tap do |t| operand[t] ||= {} @graph.weights.keys.each do |wgt| operand[t][wgt] = operand[t][wgt].to_i + arc['attributes'][wgt].to_i end end end end @graph.places.each do |id, p| @graph.colors.each do |color, total| @places.push([p['label'], p['attributes'][color].to_i]) vector.push((operand[p['id']] || {} )[@graph.color_to_weight(color)].to_i) end end @transitions[i] = { label: tx['label'], value: vector } end end def refactor # prunes unused places used_places = [] @places = [].tap do |places| @transitions.collect {|i, tx| tx[:value] }.tap do |matrix| matrix.transpose.each_with_index do |vector, i| vector.each do |scalar| next if scalar == 0 used_places << i places.push @places[i] break end end end end @transitions.each do |i, tx| tx[:value] = used_places.collect { |id| tx[:value][id] } end end end end
require "rails_helper" RSpec.describe Booking, type: :model do let!(:bill) {FactoryBot.create :bill} let!(:booking){FactoryBot.create :booking, bill: bill} let!(:booking2){FactoryBot.create :booking, bill: bill} let!(:booking3){FactoryBot.create :booking} let(:booking4){FactoryBot.build :booking, price: " "} describe "Validations" do it "valid all field" do expect(booking3.valid?).to eq true end it "invalid any field" do expect(booking4.valid?).to eq false end end describe "Associations" do it "has many booking_services" do is_expected.to have_many(:booking_services).dependent :destroy end it "be long to bill" do is_expected.to belong_to :bill end it "be long to room" do is_expected.to belong_to :room end end describe "Nested attributes" do it "booking services" do is_expected.to accept_nested_attributes_for(:booking_services).allow_destroy true end end describe ".by_bill_id" do context "when valid param" do it "should return record" do expect(Booking.by_bill_id booking.bill_id).to include booking, booking2 end end context "when nil param" do it "return all record" do expect(Booking.by_bill_id(nil).size).to eq 3 end end end end
require 'test_helper' class ContactTest < ActiveSupport::TestCase def setup @contact = Contact.new(name: "Example User", email: "user@example.com", message: "This is a message") end test "should be valid" do assert @contact.valid? end test "email should be present" do @contact.email = " " assert_not @contact.valid? end test "message should be present" do @contact.message = " " assert_not @contact.valid? end end
require "test_helper" describe OrdersController do before do @orders = Order.all end describe "index" do it "sends a success response when there are many orders" do @orders.count.must_be :>, 0 get orders_path must_respond_with :success end it "sends a success response when there are no orders" do Order.destroy_all @orders.count.must_equal 0 get orders_path must_respond_with :success end end describe "update" do it "takes customer information and changes status to paid" do product = Product.first order_item = {product_id: product.id, quantity: product.stock} post order_items_path, params: {order_item: order_item} order_id = Order.last.id order_data = { cc_name: "Sarah Parker", email: "jackson@petsy.com", cc_num: "12345678901234567", cc_cvv: "980", cc_exp: "01/22", mail_adr: "2615 233rd Ave SE, Sammamish", bill_zip: "98075", status: "pending" } patch order_path(order_id), params: {order: order_data} must_redirect_to order_path Order.last.status.must_equal "paid" end it "does not procees the order if the customer data is incomplete" do orderitem = {product_id: Product.first.id, quantity: Product.first.stock} post order_items_path, params: {order_item: orderitem} order_data = { email: "jackson@petsy.com", cc_num: "12345678901234567", cc_cvv: "980", cc_exp: "01/22", mail_adr: "2615 233rd Ave SE, Sammamish", bill_zip: "98075", status: "pending" } patch order_path(session[:order_id]), params: {order: order_data} must_respond_with :found Order.last.status.must_equal "pending" session[:order_id].must_equal OrderItem.last.order_id end end end
require 'happymapper' module DublinBikes class ApiStation include HappyMapper tag 'station' element :available, Integer element :free, Integer element :total, Integer element :ticket, Integer element :open, Integer element :updated, Integer element :connected, Integer end end
include Java import java.awt.Color import java.awt.BasicStroke import java.awt.geom.GeneralPath require 'scorched_earth/renders/trajectory' module ScorchedEarth module Renders class Shot attr_reader :shot def initialize(shot) @shot = shot end def call(graphics, *_args) ScorchedEarth::Renders::Trajectory.new(shot.trajectory).call(graphics, *_args) end end end end
class Api::SettingsController < ApplicationController before_action :login_required before_action :find_fluentd before_action :set_config before_action :set_target_element, only: [:show, :update, :destroy] helper_method :element_id def index respond_to do |format| format.json end end def update label_name = params[:label] coming = Fluent::Config::V1Parser.parse(params[:content], @fluentd.config_file) coming_element = coming.elements.first unless @target_element render_404 return end @target_element.elements = coming_element.elements @target_element.merge(coming_element) @config.write_to_file redirect_to api_setting_path(id: element_id(label_name, @target_element), label: label_name, pluginType: params[:pluginType]) end def destroy if params[:label] == "ROOT" || params[:pluginType] == "source" name = params[:pluginType] arg = params[:arg] else name = "label" arg = params[:label] end if @config.delete_element(name, arg, @target_element) @config.write_to_file head :no_content # 204 else render_404 end end private def set_config @config = Fluentd::Setting::Config.new(@fluentd.config_file) end def set_target_element id = params[:id] plugin_type = params[:pluginType] label_name = params[:label] return unless id elements = @config.group_by_label.dig(label_name, element_type(plugin_type)) @target_element = elements.find do |elm| element_id(label_name, elm) == id end end def element_id(label_name, element) element_type = element_type(element.name) elements = @config.group_by_label.dig(label_name, element_type) index = elements.index(element) "#{"%06d" % index}#{Digest::MD5.hexdigest(element.to_s)}" end def element_type(name) case name when "source" :sources when "filter" :filters when "match" :matches end end def render_404 render nothing: true, status: 404 end end
# frozen_string_literal: true class ChangeTeachQuideToTeachingGuideOnChapters < ActiveRecord::Migration[5.2] def change rename_column :exploding_dots_chapters, :teaching_quide, :teaching_guide end end
require "spec_helper" describe Fuzzy::Finder do let(:fuzzyfinder) { described_class } before :all do @collection = [ "django_migration.py", "main_group.rb", "api_user.rb", "user_doc.rb", "migration.rb", "admin.rb", "admin22.rb" ] end describe ".find" do let(:user_input) { "mig" } it "returns a list with matching results" do result = fuzzyfinder.find(user_input, @collection) expect(result).to be_a(Array) expect(result).not_to be_empty end context "the closest matching result" do let(:user_input_one) { "djm" } let(:user_input_two) { "user" } it "and returns a list with the first item as the closest result" do result = fuzzyfinder.find(user_input_one, @collection) expect(result[0]).to eq("django_migration.py") result = fuzzyfinder.find(user_input_two, @collection) expect(result[0]).to eq("user_doc.rb") end end context "receives a integer from user input" do let(:user_input_number) { 22 } it "returns a list with matching results" do result = fuzzyfinder.find(user_input_number, @collection) expect(result).to be_a(Array) expect(result).not_to be_empty end end end end
# Install command-line tools using Homebrew # Usage: `brew bundle Brewfile` tap thoughtbot/formulae install rcm # Make sure we’re using the latest Homebrew update # Upgrade any already-installed formulae upgrade # Install GNU core utilities (those that come with OS X are outdated) # Don’t forget to add `$(brew --prefix coreutils)/libexec/gnubin` to `$PATH`. install coreutils # Install GNU `find`, `locate`, `updatedb`, and `xargs`, `g`-prefixed install findutils # Install GNU `sed`, overwriting the built-in `sed` install gnu-sed --default-names # Install Bash # Note: don’t forget to add `/usr/local/bin/bash` to `/etc/shells` before running `chsh`. install bash install bash-completion # Install ZSH # Note: don't forget to add `/usr/local/bin/zsh` to `/etc/shells` before running `chsh` install zsh install zsh-completions # Install wget with IRI support install wget # Install more recent versions of some OS X tools install macvim --override-system-vim # Install other useful binaries install ack install the_silver_searcher install imagemagick install ghostscript install ctags # Version Control install git install git-flow-avh install git-extras install tig # Web Applications install postgresql install freeimage install ghostscript install imagemagick install qt install chromedriver install memcached install redis install heroku-toolbelt install phantomjs install node # Pairing Utilities install mobile-shell --HEAD install tmux install wemux install pow install reattach-to-user-namespace install ngrok # Ruby install rbenv install rbenv-gem-rehash install ruby-build # Python install python # Remove outdated versions from the cellar cleanup
module Language # Prepends an a/an to the beginning of the string if it starts with a vowel. def a_an string string.downcase.match(/^[aeiou]/) ? "an #{string}" : "a #{string}" end # Prepends an A/An to the beginning of the string if it starts with a vowel. def cap_a_an string string.downcase.match(/^[aeiou]/) ? "An #{string}" : "A #{string}" end def all_both number raise "Number (#{number}) must be > 1" unless number > 1 (number > 2) ? "all" : "both" end # Returns a number from one to twenty one in English. If an :or option is # specified then that is returned for "one" in cases where "a" or "an" would # sound better in a phrase. def number_to_english number, options = {} if number == 1 && options[:or].present? return options[:or] end case number when 0 then "zero" when 1 then "one" when 2 then "two" when 3 then "three" when 4 then "four" when 5 then "five" when 6 then "six" when 7 then "seven" when 8 then "eight" when 9 then "nine" when 10 then "ten" when 11 then "eleven" when 12 then "twelve" when 13 then "thirteen" when 14 then "fourteen" when 15 then "fifteen" when 16 then "sixteen" when 17 then "seventeen" when 18 then "eighteen" when 19 then "nineteen" when 20 then "twenty" when 21 then "twenty one" else raise "This needs more numbers! [#{number}]" end end # This is a rather complex method that takes a measurement and returns a # phrase describing that measurement in inches or feet. # # Number: The number of inches # Part: A number 0-9, represents a tenth of an inch. # Plural: Use feet and inches, or foot and inch. # # This is used mostly my the CockDescriber, but I could see it being used # elsewhere too. # def rational_number_to_standard_units number, part, plural inch = (plural && number != 1) ? "inches" : "inch" foot = (plural && number != 12) ? "feet" : "foot" if part > 6 inch = "inches" if inch == "inch" && plural end if number == 0 return "three quarters of an inch" if part > 6 return "a half an inch" if part > 4 return "a quarter of an inch" if part > 1 return "a fraction of an inch" end if number < 6 return "#{number_to_english(number)} and three quarter #{inch}" if part > 6 return "#{number_to_english(number)} and a half #{inch}" if part > 4 return "#{number_to_english(number)} and a quarter #{inch}" if part > 1 return "#{number_to_english(number)} #{inch}" end if number < 12 return "#{number_to_english(number)} and a half #{inch}" if part > 4 return "#{number_to_english(number)} #{inch}" end if number == 12 && Roll.random(1,2) == 1 return "one foot" end if number < 18 return "#{number_to_english(number)} and a half #{inch}" if part > 4 return "#{number_to_english(number)} #{inch}" end return Roll.random_from([ "eighteen #{inch}", "foot and a half" ]) if number == 18 && !plural return Roll.random_from([ "eighteen #{inch}", "a foot and a half" ]) if number == 18 if number >= 21 && number < 24 return "#{number} #{inch}" end return Roll.random_from([ "#{number} #{inch}", "two #{foot}" ]) if number == 24 return Roll.random_from([ "#{number} #{inch}", "two and a half #{foot}" ]) if number == 30 return Roll.random_from([ "#{number} #{inch}", "three #{foot}" ]) if number == 36 "#{number} #{inch}" end # Because you sometimes need to compare the size of round things. def width_comparator width if width < 0.2 return Roll.random_from ["pea","peanut","pearl"] end if width >= 0.2 && width < 0.5 return Roll.random_from ["olive","acorn","cherry","grape","marble","cranberry"] end if width < 0.5 return Roll.random_from ["olive","acorn","cherry","grape"] end if width >= 0.5 && width < 1 return Roll.random_from ["walnut","cherry tomato"] end if width >= 1 && width < 1.5 return Roll.random_from ["strawberry","marshmallow"] end if width >= 1.5 && width < 2 return Roll.random_from ["golf ball","lime","small tomato","chicken egg"] end if width >= 2 && width < 2.5 return Roll.random_from ["tennis ball","pool ball","plum","tomato"] end if width >= 2.5 && width < 3 return Roll.random_from ["baseball","small fist","large tomato"] end if width >= 3 && width < 3.5 return Roll.random_from ["peach","lemon","fist"] end if width >= 3.5 && width < 4 return Roll.random_from ["softball","small apple","big fist"] end if width >= 4 && width < 5 return Roll.random_from ["orange","apple","small onion"] end if width >= 5 && width < 6 return Roll.random_from ["onion","large apple","bell pepper"] end if width >= 6 && width < 7 return Roll.random_from ["mango","large onion","grapefruit"] end if width >= 7 && width < 8 return Roll.random_from ["large grapefruit","football"] end if width >= 8 && width < 9 return Roll.random_from ["volleyball","bowling ball","soccer ball"] end if width >= 9 && width < 10 return Roll.random_from ["basketball","cabbage"] end if width >= 10 && width < 12 return Roll.random_from ["cantaloupe","small melon","small coconut"] end if width >= 12 && width < 15 return Roll.random_from ["head of lettuce","coconut"] end if width >= 15 && width < 18 return Roll.random_from ["pineapple","large coconut"] end if width >= 18 && width < 22 return Roll.random_from ["honeydew melon","small watermelon"] end if width >= 22 && width < 30 return Roll.random_from ["pumpkin","watermelon"] end if width >= 30 return Roll.random_from ["beach ball"] end end # Because you sometimes need to compare the size of round things... in plural! # I wish I could think of a better way to do this rather than just copying and # editing the list, but plurals like "heads of lettuce" make it tricky. def width_comparator_plural width if width < 0.2 return Roll.random_from ["peas","peanuts","pearls"] end if width >= 0.2 && width < 0.5 return Roll.random_from ["olives","acorns","cherries","grapes","marbles","cranberries"] end if width >= 0.5 && width < 1 return Roll.random_from ["walnuts","cherry tomatoes"] end if width >= 1 && width < 1.5 return Roll.random_from ["strawberries","marshmallows"] end if width >= 1.5 && width < 2 return Roll.random_from ["golf balls","limes","small tomatoes","chicken eggs"] end if width >= 2 && width < 2.5 return Roll.random_from ["tennis balls","pool balls","plums","tomatoes"] end if width >= 2.5 && width < 3 return Roll.random_from ["baseballs","small fists","large tomatoes"] end if width >= 3 && width < 3.5 return Roll.random_from ["peaches","lemons","fists"] end if width >= 3.5 && width < 4 return Roll.random_from ["softballs","small apples","big fists"] end if width >= 4 && width < 5 return Roll.random_from ["oranges","apples","small onions"] end if width >= 5 && width < 6 return Roll.random_from ["onions","large apples","bell peppers"] end if width >= 6 && width < 7 return Roll.random_from ["mangoes","large onions","grapefruits"] end if width >= 7 && width < 8 return Roll.random_from ["large grapefruits","footballs"] end if width >= 8 && width < 9 return Roll.random_from ["volleyballs","bowling balls","soccer balls"] end if width >= 9 && width < 10 return Roll.random_from ["basketballs","cabbages"] end if width >= 10 && width < 12 return Roll.random_from ["cantaloupes","small melons","small coconuts"] end if width >= 12 && width < 15 return Roll.random_from ["heads of lettuce","coconuts"] end if width >= 15 && width < 18 return Roll.random_from ["pineapples","large coconuts"] end if width >= 18 && width < 22 return Roll.random_from ["honeydew melons","small watermelons"] end if width >= 22 && width < 30 return Roll.random_from ["pumpkins","watermelons"] end if width >= 30 return Roll.random_from ["beach balls"] end end end
FactoryGirl.define do factory :event, :class => AuthForum::Event do |f| f.sequence(:name) { |n| "Event #{n}"} f.sequence(:title) { |n| "Product event #{n}"} f.sequence(:description) { |n| "Sample event #{n} for test"} association :product, factory: :product end end
require 'test_helper' class ImageTest < ActiveSupport::TestCase def test_image__valid image_valid = Image.new(imagelink: 'https://images.pexels.com/photos/33053/dog-young-dog-small-dog-maltese.jpg?cs=srgb&dl=animal-dog-maltese-33053.jpg&fm=jpg', tag_list: 'foo') # rubocop:disable Metrics/LineLength assert_predicate image_valid, :valid? end def test_image__invalid_if_url_is_invalid image_invalid = Image.new(imagelink: 'adsfgg', tag_list: 'bar') assert_not_predicate image_invalid, :valid? assert_equal 'is not a valid URL', image_invalid.errors[:imagelink].first end def test_image__invalid_if_url_is_blank image_invalid2 = Image.new(imagelink: '', tag_list: 'bar') assert_not_predicate image_invalid2, :valid? assert_equal "can't be blank", image_invalid2.errors[:imagelink].first end def test_image__invalid_if_no_tag image_invalid3 = Image.new(imagelink: 'https://images.pexels.com/photos/33053/dog-young-dog-small-dog-maltese.jpg?cs=srgb&dl=animal-dog-maltese-33053.jpg&fm=jpg') assert_not_predicate image_invalid3, :valid? assert_equal "can't be blank", image_invalid3.errors[:tag_list].first end def test_image__taggable image = Image.new image.tag_list.add('awesome', 'perfect') assert_equal image.tag_list, %w[awesome perfect] image.tag_list.remove('awesome') assert_equal image.tag_list, ['perfect'] end end
# 汎用メソッド用クラス class Utility #----------------------------# # self.error_message_replace # #----------------------------# # エラーメッセージ置換 def self.error_message_replace( args ) message = args[:message] message = message.gsub( "errors prohibited this user from being saved", "エラー" ) message = message.gsub( "error prohibited this user from being saved", "エラー" ) message = message.gsub( "There were problems with the following fields:", "以下の項目にエラーがあります。" ) message = message.gsub( "Login", "ログインID" ) message = message.gsub( "Password", "パスワード" ) return message end #--------------# # self.f_round # #--------------# # 小数点四捨五入演算 def self.f_round( args ) precision = "1" 1.upto( args[:precision] ){ precision += "0" } args[:number] = ( args[:number].to_f * precision.to_i ).round / precision.to_f return args[:number] end #----------------------# # self.digit_delimiter # #----------------------# # 桁区切り def self.digit_delimiter( args ) args[:number].to_s.reverse.gsub(/(\d{#{args[:digit]}})(?=\d)/, ('\1' + args[:delimiter])).reverse end end
class Relationship < ApplicationRecord #followモデルはこの場で作った架空のモデル # belongs_to :followerだけだと、followモデルが見つからないというエラーになるので # class_name:"User"と定義することで、Userテーブルのレコードを参照してくれる belongs_to :follower, class_name:"User" #followedモデルは存在しないので、userモデルにbelongs_to belongs_to :followed, class_name:"User" end
module Paperclip class StringioAdapter < AbstractAdapter def self.register Paperclip.io_adapters.register self do |target| StringIO === target end end def initialize(target, options = {}) super cache_current_values end attr_writer :content_type private def cache_current_values self.original_filename = @target.original_filename if @target.respond_to?(:original_filename) self.original_filename ||= "data" @tempfile = copy_to_tempfile(@target) @content_type = ContentTypeDetector.new(@tempfile.path).detect @size = @target.size end def copy_to_tempfile(source) while data = source.read(16 * 1024) destination.write(data) end destination.rewind destination end end end Paperclip::StringioAdapter.register
class Piece def initialize end def inspect "P" end end class NullPiece def initialize end def inspect " " end end
require 'spec_helper' describe Turn do before(:each) do @player = Player.new(1) end describe "#start" do it "scores 0 when a user eventually fails to roll any scoring dices" do turn = Turn.new(@player) turn.stub(:gets).and_return("roll") turn.start expect(turn.score()).to eq(0) end it "player is marked as in the game on scores above 300 for first time" do while(true) turn = Turn.new(@player) turn.stub(:gets).and_return("roll","end") turn.start if turn.score() >= 300 break end end expect(turn.score()).to be >= 300 expect(@player.score()).to be >= 300 expect(@player.in_the_game).to be_true end it "updates the player's score" do @player.in_the_game = true old_score = @player.score while(true) turn = Turn.new(@player) turn.stub(:gets).and_return("end") turn.start if turn.score() >= 0 break end expect(@player.score).to be > old_score end end end end
require 'test_helper' class DummyNode < Node end class NodeTest < ActiveSupport::TestCase test 'must have a type' do node = Node.new assert !node.save assert node.errors[:type].present? end test 'must have name' do node = DummyNode.new :name => nil assert !node.save assert node.errors[:name].present? end test 'must have a unique name' do foo = DummyNode.create! :name => 'foo' foo2 = DummyNode.new :name => 'foo' assert !foo2.save assert foo2.errors[:name].present? end test 'must have a unique name from the same parent' do parent = DummyNode.create! :name => 'parent' foo = DummyNode.create! :name => 'foo', :parent_id => parent.id foo2 = DummyNode.new :name => 'foo', :parent_id => parent.id assert !foo2.save assert foo2.errors[:name].present? end test 'can have the same name if parent is not the same' do parent = DummyNode.create! :name => 'parent' parent2 = DummyNode.create! :name => 'parent2' foo = DummyNode.create! :name => 'foo', :parent_id => parent.id foo2 = DummyNode.new :name => 'foo', :parent_id => parent2.id assert foo2.save end test 'can have a parent' do assert_kind_of Folder, nodes(:subfolder1).parent end test 'parent would be nil if top level' do assert_nil nodes(:root_folder_1).parent end test 'can have children' do assert !nodes(:root_folder_1).children.empty? assert nodes(:root_folder_1).children.all? { |folder| folder.is_a?(Folder) } end test 'can have empty children' do assert nodes(:subsubfolder1).children.empty? end end
require File.dirname(__FILE__) + '/../test_helper' require 'line_items_controller' # Re-raise errors caught by the controller. class LineItemsController; def rescue_action(e) raise e end; end class LineItemsControllerTest < Test::Unit::TestCase fixtures :line_items, :orders, :products def setup @controller = LineItemsController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @rails = products(:rails_book) @rails_order = orders(:rails_book_order) end def test_should_get_index get :index assert_response :success assert assigns(:line_items) end def test_should_get_new get :new assert_response :success end def test_should_create_line_item old_count = LineItem.count post :create, :line_item => {:product_id => @rails, :order_id => @rails_order, :quantity => 2, :total_price => 1111 } assert_equal old_count+1, LineItem.count assert_redirected_to line_item_path(assigns(:line_item)) end def test_should_show_line_item get :show, :id => 1 assert_response :success end def test_should_get_edit get :edit, :id => 1 assert_response :success end def test_should_update_line_item put :update, :id => 1, :line_item => {:product_id => @rails, :order_id => @rails_order, :quantity => 2, :total_price => 1111 } assert_redirected_to line_item_path(assigns(:line_item)) end def test_should_destroy_line_item old_count = LineItem.count delete :destroy, :id => 1 assert_equal old_count-1, LineItem.count assert_redirected_to line_items_path end end
Rails.application.routes.draw do devise_for :users, controllers: {registrations: "users/registrations", sessions: "users/sessions"} # Static Page # =========== get "/private", to: "static_pages#private", as: "private_page" get '/rejected', to: "static_pages#invalid_auth", as: "invalid_auth" # System # ====== root 'static_pages#welcome' end
class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable validates :first_name, presence: true validates :last_name, presence: true validates :city, presence: true validates :state, presence: true validates :phone, presence: true has_many :responses has_many :events, through: :responses has_many :created_events, class_name: "Event", foreign_key: "creator_id" has_many :attendees, class_name: "User", foreign_key: "creator_id" belongs_to :creator, class_name: "User", optional: true def admin? role == "admin" end end
# t.string :title # t.string :slug # t.attachment :cover # t.text :short_description # t.text :description # t.boolean :published # t.integer :position # t.boolean :main # t.date :start_date # t.date :date_of class Promotion < ActiveRecord::Base # self.table_name = :promotions attr_accessible *attribute_names attr_accessible :cover has_attached_file :cover, styles: { large: "1449x549>", medium: "720x400>" }, convert_options: { large: "-quality 94 -interlace Plane", medium: "-quality 94 -interlace Plane"}, default_url: "/images/:style/missing.png" validates_attachment_content_type :cover, content_type: /\Aimage\/.*\Z/ before_save { save_slug(title, slug) } def set_start_date self.start_date ||= Date.today end def random_date_in_year(year) return rand(Date.civil(year.min, 1, 1)..Date.civil(year.max, 12, 31)) if year.kind_of?(Range) rand(Date.civil(year, 1, 1)..Date.civil(year, 12, 31)) end def set_date_of self.date_of ||= random_date = random_date_in_year(2016..2020) end before_save :set_start_date, :set_date_of has_and_belongs_to_many :windowsills, join_table: :table_windowsills_promotions attr_accessible :windowsill_ids has_one :seo, as: :seo_poly attr_accessible :seo accepts_nested_attributes_for :seo, allow_destroy: true attr_accessible :seo_attributes rails_admin do navigation_label 'Інше' label 'Акційна пропозиція' label_plural 'Акційні пропозиції' edit do field :published do label 'Чи публікувати?' end field :main do label 'Вибрана?' end field :title do label 'Назва:' end field :cover, :paperclip do label 'Зображення:' end field :short_description do html_attributes rows: 10, cols: 100 label 'Короткий опис:' end field :description, :ck_editor do label 'Опис:' help 'Використовувати теги h3, h4, h5, h6, p, blockquote, <ul or ol> <li> <span>text</span></li></ul or /ol>' end field :start_date do label 'Дата початку:' end field :date_of, :date do label 'Дата завершення:' end field :position do label 'Позиція:' end field :windowsills do label 'Підвіконня:' end field :seo do label 'SEO' end end end scope :with_date, -> { where("date_of > ?", Date.today).order('created_at desc')} # scope :published, where(published: 't').order(position: :desc) searchable do text :title, :short_description, :description end end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html # write routes, combination of method and paths # VERB(method) + PATH => (which controllers and which action) # get "/squeaks", to: "squeaks#index" #standard way of writing routes # get "/squeaks/:id", to: "squeaks#show" # post "/squeaks", to: "squeaks#create" # patch "/squeaks/:id", to: "squeaks#update" # put "/squeaks/:id", to: "squeaks#update" # delete "/squeaks/:id", to: "squeaks#destroy" # :wildcard (ex. :id) after :, anything can come afterwards but id is most common # why some need id some don't # - line 6 only cares about one single squeak unlike line 5 which wants all squeaks(no point of having wildcard) # - Therefore, for patch and put delete, you need to indicate which squeak you are exactly want to patch, put or delete # send to controller Squeaks's index action(a method named with action) #simple way of writing routes #resources + controller + (only) + array of symbol actions # resources(:squeaks, only: [:index, :show, :new, :create, :edit, :update, :destroy]) # resource is a method to generate routes based on the arguments # #resources(controller, list of actions) # if you don't give the list of actions, it will generate all actions by default # you will have an error if you don't have routes set up for your controller actions. # get "/set_cookie", to:"squeaks#set_cookie" # get "/get_cookie", to:"squeaks#get_cookie" # resource :session, only: [:new, :create, :destroy] # resources :users, only: [:new, :create] root to: 'static_pages#root' namespace :api, defaults: {format: :json} do resources :squeaks, only: [:index, :show, :new, :create, :edit, :update, :destroy] resource :session, only: [:new, :create, :destroy] resources :users, only: [:new, :create] end end
require 'rails_helper' RSpec.describe "Artists API" do let!(:user) { create(:user) } let!(:member_source_type) { create(:member_source_type)} let!(:member_type) { create(:member_type) } let!(:account_status_type) { create(:account_status_type)} let!(:member) { create(:member, member_source_type_id:member_source_type.id, member_type_id: member_type.id, account_status_type_id: account_status_type.id, user_id: user.id) } let!(:country) { create(:country) } let!(:state) { create(:state, country_id: country.id) } let!(:city) { create(:city, state_id: state.id)} let!(:bank_account) { create(:bank_account)} let!(:company) { create(:company)} let!(:superannuation) { create(:superannuation)} let!(:tax_type) { create(:tax_type) } let!(:tax) { create(:tax, tax_type_id: tax_type.id)} let!(:artist) { create(:artist, member_id: member.id, bank_account_id: bank_account.id, company_id: company.id, passport_country_id: country.id, superannuation_id: superannuation.id, tax_id: tax.id )} let!(:artist_city) { create(:artist_city, artist_id: artist.id, city_id: city.id)} let(:member_id) { member.id } let(:artist_id) { artist.id } describe 'GET /artists/:id' do before { get "/artists/#{artist_id}" } context 'when artist exists' do it "return status code 200" do expect(response).to have_http_status(200) end it 'return artist' do expect(json).not_to be_empty expect(json['member']['first_name']).to eq(member.first_name) expect(json['bank_account']['bank_name']).to eq(bank_account.bank_name) expect(json['artist_city'][0]['city_full_name']).not_to be_empty end end context 'when artist not exists' do let(:artist_id) { 0 } it 'return status code 404' do expect(response).to have_http_status(404) end it 'returns a not found message' do expect(response.body).to include("Couldn't find") end end end describe 'PUT /artists/:id' do let(:valid_attributes) {{ dob: '1982-04-01', is_dob_visible: true, primary_occupation: 'programer', passport_country_id: country.id, passport_number: '1234', age_to: 30, age_from: 12, member_id: member_id, bank_account: { bank_name: 'AZD', bank_swift_code: '123', bank_location: 'vic', account_name: 'leon', account_number: '456', }, tax: { juristiction: 'test', number: '123', tax_type_id: tax_type.id, }, company: { name: 'test', number: '123', company_type: 'test' }, superannuation: { company: 'test2', number: '123', social_security_number: '456' }, cities:[ city.id ] }} context 'The request is valid' do before { put "/artists/#{artist_id}", params: valid_attributes} it 'returns status code 200' do expect(response).to have_http_status(200) end it 'returns artist data' do expect(json['bank_account']['bank_name']).to eq('AZD') expect(json['superannuation']['number']).to eq('123') expect(json['tax']['juristiction']).to eq('test') expect(json['company']['name']).to eq('test') expect(json['artist_city'].size).to eq(1) end end end end
module Fog module Hetznercloud class Compute class ServerType < Fog::Model identity :id attribute :name attribute :description attribute :cores attribute :memory attribute :disk attribute :prices attribute :storage_type end end end end
# Documentation class Persona attr_accessor :name, :lastname, :identificacion, :telefono, :productos def initialize(name, lastname, identificacion, telefono) @name = name @lastname = lastname @identificacion = identificacion @telefono = telefono @productos = [] end end
child @items => "items" do attributes :id , :name, :category_id, :category_name, :menu_id node(:rating){|r| r.avg_rating} child :item_photos => "item_images" do node :image do |v| v.photo.fullpath if v.photo end end #child :item_keys => "item_keys" do # attributes :id, :name, :description,:image #end #attribute :type end child @servers => "servers" do attributes :id, :avatar, :name, :rating end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) user = User.first || User.create(email: 'test@test.com', password: 'password', password_confirmation: 'password') posts = [ { title: 'My first post', content: 'The start of something special' }, { title: 'My second post', content: 'This is really getting good' }, { title: 'Oh my god, Yeah!!!', content: 'Enough said.' } ] posts.each do |post_hash| user.posts.create(post_hash) end
#!/usr/bin/env ruby require File.expand_path(File.join(File.dirname(__FILE__), %w(.. lib tenacious_g))) location = GRATR.location unless File.exist?(location) puts "There are no graphs to delete. Exiting." exit end puts "This will remove all graphs stored in #{location} \nAre you sure you want to do this? (yN)" response = gets.chomp if response == "y" `rm #{location}` puts "Graphs deleted." else puts "Command aborted, nothing deleted." end
class AddPasswordDigestToUsers < ActiveRecord::Migration #This adds the password HASH column to the database def change #adding a password column to the database migration add_column :users, :password_digest, :string end end
# frozen_string_literal: true module RakutenWebService module StringSupport refine String do def to_snake gsub(/([a-z]+)([A-Z]{1})/, '\1_\2').downcase end def to_camel gsub(/([a-z]{1})_([a-z]{1})/) do |matched| matched = matched.split('_') matched[0] + matched[1].capitalize end end end end end
module Shipwire class ParamConverter attr_reader :params def initialize(params) if params.is_a?(Array) @params = params.each_with_object([]) do |item, hsh| hsh << recursively_struct(item) end else @params = recursively_struct(params) end end def to_h if params.is_a?(Array) params.each_with_object([]) do |item, hsh| hsh << with_object(item) end else with_object(params) end end private def recursively_struct(item) RecursiveOpenStruct.new(item, recurse_over_arrays: true).to_h end def with_object(item) item.each_with_object({}) do |(original_key, value), hsh| key = Utility.camelize(original_key.to_s, :lower).to_sym hsh[key] = value.is_a?(Hash) ? with_object(value) : value end end end end
class DispatchLink < ActiveRecord::Base # Relationships belongs_to :dispatch, :foreign_key => :dispatch_id has_many :clicks, :class_name => "DispatchLinkClick" default_scope { order("clicks_count DESC") } # Validations # validates_presence_of :uri # validates_presence_of :dispatch # validates_uniqueness_of :position, :scope => :dispatch_id # open up everything for mass assignment attr_protected end
# require 'rspec' # require_relative '../../libraries/chef_graphite_carbon_config_converter' # describe ChefGraphite::CarbonConfigConverter do # let(:config) { [] } # let(:converter) { ChefGraphite::CarbonConfigConverter.new(config) } # describe '#to_hash' do # it 'takes a nil config has and returns an empty hash' do # expect(ChefGraphite::CarbonConfigConverter.new(nil).to_hash).to eq({}) # end # it 'takes an empty config array and returns an empty hash' do # expect(converter.to_hash).to eq({}) # end # it 'returns section keys sorted alphabetically' do # config.concat([ # { type: 'beta', name: 'b', config: {} }, # { type: 'alpha', name: 'a', config: {} }, # { type: 'beta', name: 'g', config: {} }, # ]) # expect(converter.to_hash.keys).to eq(['alpha:a', 'beta:b', 'beta:g']) # end # it "remove section keys named 'default'" do # config.concat([ # { type: 'beta', name: 'b', config: {} }, # { type: 'alpha', name: 'a', config: {} }, # { type: 'beta', name: 'default', config: {} }, # ]) # expect(converter.to_hash.keys).to eq(['alpha:a', 'beta', 'beta:b']) # end # context 'for config' do # let(:config) do # [ # { type: 'beta', name: 'b', config: { 'A_KEY' => [true, '#.blah', 4] } }, # { type: 'alpha', name: 'a', config: { another_key: 'something' } }, # { type: 'beta', name: 'default', config: { 'is_frog' => true } }, # ] # end # it 'normalizes string key names to uppercase' do # expect(converter.to_hash['beta'].keys).to eq(['IS_FROG']) # end # it 'normalizes symbol key names to uppercase' do # expect(converter.to_hash['alpha:a'].keys).to eq(['ANOTHER_KEY']) # end # it 'normalizes ruby boolean values to capitalized strings' do # expect(converter.to_hash['beta']['IS_FROG']).to eq('True') # end # it 'normalizes ruby array elements to strings' do # expect(converter.to_hash['beta:b']['A_KEY']).to eq('True, #.blah, 4') # end # end # end # end
require 'rails_helper' describe 'Record type', type: :feature do let(:record_type) { create(:record_type) } before :each do AuthHelper.new.login(record_type.user) visit new_record_type_path end context 'creating' do context 'with valid data' do it 'creates a new record' do fill_in 'Name', with: record_type.name click_button 'Save' expect(page).to have_content('Record type was successfully created.') end end context 'gets an error when' do it 'has an empty Name' do fill_in 'Name', with: nil click_button 'Save' expect(page).to have_content('Name can\'t be blank') end it 'has Name greater than 30 sym' do fill_in 'Name', with: FFaker::Lorem.characters(31) click_button 'Save' expect(page).to have_content('Name is too long') end it 'has Name with fewer than 2 sym' do fill_in 'Name', with: FFaker::Lorem.characters(1) click_button 'Save' expect(page).to have_content('Name is too short') end end end context 'editing' do context 'with valid data' do it 'updates the record type' do visit edit_record_type_path(record_type) fill_in 'Name', with: FFaker::Lorem.characters(10) click_button 'Save' expect(page).to have_content('Record type was successfully updated.') end end end end
class CreateStyles < ActiveRecord::Migration def change create_table :styles do |t| t.string :name t.text :description t.timestamps end reversible do |dir| dir.up do ["Weizen", "Lager", "Pale ale", "IPA", "Porter"].each do |style| Style.create name: style, description: "Coming soon!" end rename_column :beers, :style, :old_style add_column :beers, :style_id, :integer Beer.all.each do |beer| beer.style = Style.find_by(name:beer.old_style) beer.save end remove_column :beers, :old_style end dir.down do add_column :beers, :old_style, :string Beer.all.each do |beer| if beer.style.nil? beer.old_style = "Lager" else beer.old_style = beer.style.name end beer.save end rename_column :beers, :old_style, :style remove_column :beers, :style_id end end end end
class AddColumnToTransactionsProducts < ActiveRecord::Migration def change add_column :transaction_products, :product_id, :integer add_column :transaction_products, :transaction_id, :integer end end
class Gate def initialize @parking = [] end def available? parking.empty? end def dock plane raise 'This gate is already occupied' unless available? parking << plane end def undock raise 'This gate has no plane' if available? parking.delete_at(0) end private attr_accessor :parking end
require_relative 'test_helper' require './lib/computer_player' require './lib/game_board' require './lib/coordinates' class ComputerPlayerTest < Minitest::Test def test_it_exists_and_initializes_with_game_board board = GameBoard.new ai_player = ComputerPlayer.new(board) assert_instance_of ComputerPlayer, ai_player assert_instance_of GameBoard, ai_player.computer_board end def test_it_can_randomly_choose_first_coordinate board = GameBoard.new ai_player = ComputerPlayer.new(board) coordinate = ai_player.choose_first_coordinate assert ['A','B','C','D'].include?(coordinate[0]) assert ['1', '2', '3', '4'].include?(coordinate[1]) end def test_it_can_list_all_possible_coordinates_from_first_coordinate board = GameBoard.new ai_player = ComputerPlayer.new(board) square = ai_player.computer_board.find_game_square('B2') assert_equal ['B3', 'C2', 'B1', 'A2'], ai_player.list_possible_coordinates(square, 1) square = ai_player.computer_board.find_game_square('D3') assert_equal ['D1', 'B3'], ai_player.list_possible_coordinates(square, 2) end def test_it_can_find_indices_of_game_square board = GameBoard.new ai_player = ComputerPlayer.new(board) square = ai_player.computer_board.find_game_square('A4') assert_equal [0,3], ai_player.find_indices(square) square = ai_player.computer_board.find_game_square('D1') assert_equal [3,0], ai_player.find_indices(square) end def test_it_can_name_next_coordinates_in_row_and_column board = GameBoard.new ai_player = ComputerPlayer.new(board) square = ai_player.computer_board.find_game_square('B1') assert_equal ['B2', 'C1'], ai_player.next_coordinates(square, 1) end def test_it_can_name_next_coordinate_in_row board = GameBoard.new ai_player = ComputerPlayer.new(board) assert_equal 'C3', ai_player.next_coordinate_in_row([2,1], 1) assert_equal 'B3', ai_player.next_coordinate_in_row([1,0], 2) end def test_it_can_name_next_coordinate_in_column board = GameBoard.new ai_player = ComputerPlayer.new(board) assert_equal 'D2', ai_player.next_coordinate_in_column([2,1], 1) assert_equal 'C2', ai_player.next_coordinate_in_column([0,1], 2) end def test_it_can_name_previous_coordinates_in_row_and_column board = GameBoard.new ai_player = ComputerPlayer.new(board) square = ai_player.computer_board.find_game_square('C3') assert_equal ['C2', 'B3'], ai_player.previous_coordinates(square, 1) assert_equal ['C1', 'A3'], ai_player.previous_coordinates(square, 2) end def test_it_can_name_previous_coordinate_in_row board = GameBoard.new ai_player = ComputerPlayer.new(board) assert_equal 'B1', ai_player.previous_coordinate_in_row([1,1], 1) assert_equal 'D1', ai_player.previous_coordinate_in_row([3,2], 2) end def test_it_can_name_previous_coordinate_in_column board = GameBoard.new ai_player = ComputerPlayer.new(board) assert_equal 'A2', ai_player.previous_coordinate_in_column([1,1], 1) assert_equal 'B3', ai_player.previous_coordinate_in_column([3,2], 2) end def test_it_can_name_coordinates_of_two_unit_ship board = GameBoard.new ai_player = ComputerPlayer.new(board) coordinates = ai_player.choose_ship_coordinates(1) assert coordinates[1] == coordinates[0].next end def test_it_can_name_coordinates_of_three_unit_ship board = GameBoard.new ai_player = ComputerPlayer.new(board) coordinates = ai_player.choose_ship_coordinates(2) checker = Coordinates.new(coordinates) assert_equal 2, checker.count_coordinate_range end end
Rails.application.routes.draw do get 'dashboard/index' resources :departments resources :stores resources :staff_requests namespace :api do namespace :v1 do namespace :statistics do get :chart get :summary get :compared_sales end namespace :employees do get :table get :index get :staff end get 'employees/:id/calendar_shift', to: 'employees#calendar_shift', as: 'employee_calendar_shift' get 'employees/:id/achievements_chart', to: 'employees#achievements_chart', as: 'employee_achievements_chart' namespace :periods do get :filter_period end namespace :filters do get :compared_stores end namespace :shifts do get :employees_calendar_shifts get :all end end end namespace :statistics do get :sales get :hours get :efficiency get :productivity end namespace :config do get :plan_change end namespace :optimizer do get :show end resources :employees, only: [:index, :show] do collection do get :staff get :staff_planning get :departments_staff end end devise_for :users, controllers: { registrations: 'users/registrations', sessions: 'users/sessions' }, path_prefix: 'my' root 'dashboard#index' end
require 'omf_base/lobject' require 'omf_base/exec_app' require 'digest/sha1' module OMF::JobService module Scheduler class SimpleScheduler < OMF::Base::LObject POLL_PERIOD = 5 # period in second when the scheduler should wake up SUPPORTED_RESOURCE_TYPES = [ :node, :resource ] def initialize(opts) @available_resources = opts[:resources] @hard_timeout = opts[:hard_timeout] debug "Available resource: #{@available_resources}" @started = false @running_jobs = [] end def start return if @started @started = true EM.add_periodic_timer(POLL_PERIOD) do # DEBUG ONLY # all_jobs = OMF::JobService::Resource::Job.all() # all_jobs.each { |j| debug ">>> Job - '#{j.name}' - '#{j.status}'" } # refresh the list of pending jobs from the database pending_jobs = OMF::JobService::Resource::Job.prop_all(status: 'pending') next if pending_jobs.empty? # Refresh the list of available resources # TODO: in this simple example, for now just get a test list of known fixed resources # (some more code to be placed here to get the list of available resource!) debug "Available resource: #{@available_resources}" res = @available_resources schedule(res, pending_jobs.first) end end def on_new_job(job) debug "Received new job '#{job}'" # Periodic scheduler is taking care of it end def supported_types?(t) # TODO: put some more fancy checking here in the future # Potentially by querying some external module or entity? SUPPORTED_RESOURCE_TYPES.include?(t) end def schedule(resources, job) return if resources.empty? || job.nil? # Try to allocate resources to this job # If it has all its requested resources fully allocated then run it if alloc_resources(resources, job) info "Running job '#{job.name}' with resource(s) #{job.resources.to_s}" # Start the job EM.next_tick do if @hard_timeout EM.add_timer(@hard_timeout) { job.abort_job } end job.run { dealloc_resources_for_job(job) } end end end def alloc_resources(res, job) failed = false alloc_res = job.resources.map do |e| next nil if failed # no point trying anymore res = alloc_resource(e) unless res debug "Job '#{job.name}'. Not enough free resources to run this job now, will try again later." failed = true end res end.compact if failed # TODO: Free allocate resources return false end job.resources.each_with_index do |e, i| e.resource_name = alloc_res[i] e.save job.save end return true end def alloc_resource(descr) type = descr.resource_type unless supported_types?(type) error "requests a resource of type '#{type}' not supported by this scheduler" end res = @available_resources.delete_at(0) end def dealloc_resources_for_job(job) job.resources.each { |r| @available_resources << r.resource_name } end end end end
require "accepts_nested_serialized_attributes/version" module AcceptsNestedSerializedAttributes module ActiveModel::Serialization alias_method :original_serializable_hash, :serializable_hash def serializable_hash(options = nil) original_serializable_hash(options).tap do |hash| hash.symbolize_keys! self.class.nested_attributes_options.keys.each do |nested_attributes_key| if (records = hash.delete nested_attributes_key) hash["#{nested_attributes_key}_attributes".to_sym] = records end end end end end end
# frozen_string_literal: true class IconsController < ApplicationController caches_page :inline, :notification_icon def inline width = params[:width].to_i icon = ChunkyPNG::Image.from_file("#{Rails.root}/app/assets/images/rjjk_logo_notext.png") data = icon.resample_bilinear(width, width).to_blob send_data(data, disposition: 'inline', type: 'image/png', filename: "icon-#{width}x#{width}.png") end COLORS = { ChunkyPNG::Color.parse('030303FF') => ChunkyPNG::Color::WHITE, ChunkyPNG::Color.parse('FFFFFFFF') => ChunkyPNG::Color::TRANSPARENT, ChunkyPNG::Color.parse('E10916FF') => ChunkyPNG::Color::TRANSPARENT, ChunkyPNG::Color.parse('FFB403FF') => ChunkyPNG::Color::WHITE, ChunkyPNG::Color.parse('026CB6FF') => ChunkyPNG::Color::TRANSPARENT, ChunkyPNG::Color.parse('03145CFF') => ChunkyPNG::Color::WHITE, }.freeze def notification_icon width = 320 icon = ChunkyPNG::Image.from_file("#{Rails.root}/public/favicon.ico") icon.width.times do |x| icon.height.times do |y| icon[x, y] = if ChunkyPNG::Color.a(icon[x, y]) < 0x40 ChunkyPNG::Color::TRANSPARENT else color = ChunkyPNG::Color.opaque!(icon[x, y]) COLORS.min_by { |c, _t| ChunkyPNG::Color.euclidean_distance_rgba(c, color) }[1] end end end send_data(icon.to_blob, disposition: 'inline', type: 'image/png', filename: "notification_icon-#{width}x#{width}.png") end end
require 'minitest/autorun' require 'minitest/pride' require './calculator' class CalculatorTest < Minitest::Test def test_it_adds calc = Calculator.new result = calc.add(5, 6) assert_equal 11, result end def test_it_adds_with_a_negative calc = Calculator.new result = calc.add(5, -6) assert_equal -1, result end def test_it_subtracts calc = Calculator.new result = calc.subtract(10, 6) assert_equal 4, result end def test_it_squares calc = Calculator.new result = calc.square(10) assert_equal 100, result end # Next Tests def test_it_divides calc = Calculator.new result = calc.division(10,5) assert_equal 2, result end def test_it_multiplies calc = Calculator.new result = calc.multiply(10,5) assert_equal 50, result end def test_it_raises_to_a_power calc = Calculator.new result = calc.power(2,2) assert_equal 4, result end def test_it_records_the_last_result calc = Calculator.new result = calc.add(10,5) result = calc.add(2,2) result = calc.last_result assert_equal 15, result end def test_it_clears calc = Calculator.new result = calc.add(10,5) result = calc.add(2,2) result = calc.last_result result = calc.clear assert_equal 0, result end end
require 'spec_helper' describe Immutable::Vector do describe '#each_index' do let(:vector) { V[1,2,3,4] } context 'with a block' do it 'yields all the valid indices into the vector' do result = [] vector.each_index { |i| result << i } result.should eql([0,1,2,3]) end it 'returns self' do vector.each_index {}.should be(vector) end end context 'without a block' do it 'returns an Enumerator' do vector.each_index.class.should be(Enumerator) vector.each_index.to_a.should eql([0,1,2,3]) end end context 'on an empty vector' do it "doesn't yield anything" do V.empty.each_index { fail } end end [1, 2, 10, 31, 32, 33, 1000, 1024, 1025].each do |size| context "on a #{size}-item vector" do it 'yields all valid indices' do V.new(1..size).each_index.to_a.should == (0..(size-1)).to_a end end end end end
require "spec_helper" describe Event do let(:event_prototype) { build :event_prototype } let(:event) { Event.new event_prototype:event_prototype } it "has the event duration" do event.duration.should == event_prototype.duration end it "has a duration of 0 when no duration is specified" do datum = build(:event_prototype, duration:nil) event = Event.new event_prototype:datum event.duration.should == 0 end it "has the template" do event.template.should == event_prototype.template end end
class List < ApplicationRecord validates :name, presence: true has_many :movie_lists has_many :movies, through: :movie_lists end
# frozen_string_literal: true require 'spec_helper' RSpec.describe CatalogController, type: :controller do describe 'index action customizations' do context 'hierarchy view' do it 'does not start a search_session' do allow(controller).to receive(:search_results) session[:history] = [] get :index, params: { q: 'foo', view: 'hierarchy' } expect(session[:history]).to be_empty end it 'does not store a preferred_view' do allow(controller).to receive(:search_results) session[:preferred_view] = 'list' get :index, params: { q: 'foo', view: 'hierarchy' } expect(session[:preferred_view]).to eq 'list' end end context 'online_contents view' do it 'does not start a search_session' do allow(controller).to receive(:search_results) session[:history] = [] get :index, params: { q: 'foo', view: 'online_contents' } expect(session[:history]).to be_empty end it 'does not store a preferred_view' do allow(controller).to receive(:search_results) session[:preferred_view] = 'list' get :index, params: { q: 'foo', view: 'online_contents' } expect(session[:preferred_view]).to eq 'list' end end context 'any other view' do it 'starts a search_session' do allow(controller).to receive(:search_results) session[:history] = [] get :index, params: { q: 'foo', view: 'list' } expect(session[:history]).not_to be_empty end it 'stores a preferred_view' do allow(controller).to receive(:search_results) session[:preferred_view] = 'list' get :index, params: { q: 'foo', view: 'gallery' } expect(session[:preferred_view]).to eq 'gallery' end end end end
# # Cookbook Name:: tomcatinstallation # Recipe:: default # # Copyright 2017, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # puts "Installing Tomacat7!!" cookbook_file "/tmp/tomcat7.sh" do source "tomcat7.sh" owner "root" group "root" mode 0755 end execute "tomcat7.sh" do user "root" command "sh /tmp/tomcat7.sh" end
class VideoQueue < Formula desc "Download, Split & Queue Videos on your computer. For productivity" homepage "https://www.github.com/seyonv/video_queue" url "https://www.github.com/seyonv/video_queue/archive/1.0.63.tar.gz" sha256 "862d01132eecffe8e8fdca310a7d7d9d4ff99557825d33ad39b1967b5d2dd86c" depends_on :x11 depends_on "youtube-dl" def install ENV.deparallelize system "make", "all", "PREFIX=#{prefix}" end test do system "false" end end
#!/usr/bin/env ruby require './Graph' # Random graph - Erdoes/Renyi G(n,p) # n is the number of vertices; n_edges is the number of edges to be added # at random. I have a lame condition not to connect a node to itself (the graph # code does not worry about that). # I find that for n = 30, for 60 edges, p = .26 or so, with 8-9/10 likelihood # of being connected. I don't know what 'very likely' means. # 70 edges, p = .3 or so, is almost always connected. # Now I found something on the Web that says that 2 * N(edges) / N is a key # parameter, where percolation begins about 1. # One problem is that I am not checking whether the random numbers create # a pair which we've already had; and if that happens, the edge isn't added, # and so in that case the graph ends up with a smaller value of p. n = ARGV[0].to_i n_edges = ARGV[1].to_i num_connected = 0 (1..10).each do |k| g = Graph.new (1..n).each { |a| g.add_vertex(a) } (1..n_edges).each do |a| u = rand(n) v = rand(n) g.add_edge(u,v) end p = 2.0 * g.edges.size / (n * (n-1)) num_connected += 1 if g.is_connected? p p end p num_connected
class Email < ActiveRecord::Base validates :to, presence: true end
class RemoveNationalityToUser < ActiveRecord::Migration[5.0] def change remove_column :users, :nationality end end
class Rate < ApplicationRecord RATE_PARAMS = %w(room_id user_id score).freeze belongs_to :user belongs_to :room validates :score, presence: true, numericality: {only_integer: true, other_than: 0} scope :by_room_id, ->(room_id){where room_id: room_id} end
require "spec_helper" describe Sro::Mock::ActiveRecordModel do subject { Sro::Mock::ActiveRecordModel.new } it "inherits from ActiveRecord::Base" do klass = subject.class ancestors = klass.ancestors expect(ancestors).to include(ActiveRecord::Base) end context "#inject_getter" do it "adds method to the object" do subject.inject_getter("hello") subject.instance_variable_set("@hello", "world") hello = subject.hello expect(hello).to eq("world") end end context "#inject_setter" do it "adds method to the object" do subject.inject_setter(:hello) subject.hello = "world" hello = subject.instance_variable_get("@hello") expect(hello).to eq("world") end end context "#set_getter" do it "generates getter" do getter = subject.set_getter(:hello) expect(getter).to eq("def hello; @hello ; end;") end end context "#set_setter" do it "generates setter" do getter = subject.set_setter(:hello) expect(getter).to eq("def hello=(value); @hello=value; end;") end end context "#set_value" do it "sets instance variable" do subject.set_value(:hello, "world") hello = subject.instance_variable_get("@hello") expect(hello).to eq("world") end end context "#run" do it "creates getters and setters from input" do subject.run(hello: "world", seeya: nil) expect(subject.hello).to eq("world") expect(subject.seeya).to eq(nil) subject.seeya = "later" expect(subject.seeya).to eq("later") end end end
class V1::ProductsController < V1::ApiController before_action :require_user, only: [:create, :update, :destroy] before_action :require_vendor, only: [:create, :update, :destroy] before_action :set_product, only: [:show, :edit, :update, :destroy] # GET /products # GET /products.json def index @products = Product.all render json: @products end # GET /products/1 # GET /products/1.json def show render json: @product end # GET /products/new def new @product = Product.new end # GET /products/1/edit def edit end # POST /products # POST /products.json def create @product = Product.create(product_params) if @product.save render json: { status: :created, product: @product } else render json: { status: 500 } end end # PATCH/PUT /products/1 # PATCH/PUT /products/1.json def update if @product.update(product_params) render json: { status: :updated, product: @product } else render json: { status: 500 } end end # DELETE /products/1 # DELETE /products/1.json def destroy CartItem.where(product_id: @product.id).delete_all if @product.destroy render json: { status: :deleted } else render json: { status: 500 } end end def search query = params[:product_name] if query == "" @products = nil else @products = Product.where("#{:name} LIKE ?", "%#{query}%") end if @products || @products == nil render json: @products else render json: @products end end private # Use callbacks to share common setup or constraints between actions. def set_product @product = Product.find_by(slug: params[:slug]) end # Only allow a list of trusted parameters through. def product_params params.permit(:name, :description, :price, :in_stock, images: []) end end
require 'test_helper' class EventTest < Test::Unit::TestCase def new_event @event = AASM::SupportingClasses::Event.new(@name, {:success => @success}) do transitions :to => :closed, :from => [:open, :received] end end context 'event' do setup do @name = :close_order @success = :success_callback end should 'set the name' do assert_equal @name, new_event.name end should 'set the success option' do assert_equal @success, new_event.success end should 'create StateTransitions' do mock(AASM::SupportingClasses::StateTransition).new({:to => :closed, :from => :open}) mock(AASM::SupportingClasses::StateTransition).new({:to => :closed, :from => :received}) new_event end context 'when firing' do should 'raise an AASM::InvalidTransition error if the transitions are empty' do event = AASM::SupportingClasses::Event.new(:event) obj = OpenStruct.new obj.aasm_current_state = :open assert_raise AASM::InvalidTransition do event.fire(obj) end end should 'return the state of the first matching transition it finds' do event = AASM::SupportingClasses::Event.new(:event) do transitions :to => :closed, :from => [:open, :received] end obj = OpenStruct.new obj.aasm_current_state = :open assert_equal :closed, event.fire(obj) end end end end
require 'spec_helper' RSpec.describe Bouncer::Session do let(:last_checked_at) { Time.now } let(:session) { Fabricate(:session, checked_at: last_checked_at) } context 'complete, current, recently verified sessions' do it 'is current' do expect(session.current?).to be_truthy end it 'is refreshable' do expect(session.refreshable?).to be_truthy end end context 'a session outside the grace period' do let(:last_checked_at) { 3.hours.ago } it 'is no longer current' do stub_request(:get, "http://localhost:3000/oauth/token/info.json"). to_return(status: 404) expect(session.current?).to be_falsey end end end
module Outputs class ContactType < Types::BaseObject implements Types::ActiveRecord field :walter_id, Integer, null: true field :first_name, String, null: true field :last_name, String, null: true field :full_name, String, null: true field :phone_number, String, null: false field :identity, String, null: false, description: <<~DESC The way the contact is identified to the user. If the contact has a name then identity is the name. If the contact doesn't have a name then identity is the phone number. DESC field :email, String, null: true field :company, String, null: true field :occupation, String, null: true field :hiring_authority, Boolean, null: false field :notes, String, null: true field :conversation, ConversationType, null: true field :calls, CallType.connection_type, null: false field :recordings, RecordingType.connection_type, null: false field :voicemails, VoicemailType.connection_type, null: false field :saved, Boolean, null: false field :last_contact_at, GraphQL::Types::ISO8601DateTime, null: true, description: <<~DESC Date and time of the last communication that has been received from this contact via incoming calls and incoming messages DESC def conversation Loaders::AssociationLoader.for(Contact, :conversation).load(@object) end def calls Loaders::AssociationLoader.for(Contact, :calls).load(@object) end def recordings Loaders::AssociationLoader.for(Contact, :recordings).load(@object) end def voicemails Loaders::AssociationLoader.for(Contact, :voicemails).load(@object) end end end
Gem::Specification.new do |s| s.name = 'myprecious_python' s.version = '0.0.6' s.date = '2019-02-13' s.summary = "Your precious python dependencies!" s.description = "A simple, markdown generated with information about your python dependencies" s.authors = ["Balki Kodarapu"] s.email = 'balki.kodarapu@gmail.com' s.files = ["lib/myprecious_python.rb"] s.executables << 'myprecious_python' s.add_runtime_dependency 'byebug', '~> 9.0', '>= 9.0.6' s.add_runtime_dependency 'httparty', '~> 0.16', '>= 0.16.4' s.add_runtime_dependency 'json', '~> 2.3.0', '>= 2.3' s.add_runtime_dependency 'rest-client', '~> 2.0.2', '>= 2.0' s.homepage = 'http://rubygems.org/gems/myprecious_python' s.license = 'MIT' end
class ChangeDefaultsMovie < ActiveRecord::Migration[5.1] def change change_column :movies, :seen, :boolean, default: false change_column :movies, :favorite, :boolean, default: false end end
Gem::Specification.new do |spec| spec.name = "rake-contrib" spec.version = "1.0.0" spec.authors = ["SHIBATA Hiroshi"] spec.email = ["hsbt@ruby-lang.org"] spec.summary = %q{Additional libraries for Rake} spec.description = %q{Additional libraries for Rake} spec.homepage = "https://github.com/ruby/rake-contrib" spec.license = "MIT" spec.files = Dir["lib/**/*.rb", "README.md", "LICENSE.txt"] spec.require_paths = ["lib"] spec.add_dependency "rake" spec.add_development_dependency "bundler" spec.add_development_dependency "minitest" end
# + - Addition, adds values on either side of the operator # - - Subtraction, subtracts one side from the other # % - Modulus Divides the left side by the right sife of it and returns the remainder # ** - Exponent, peerforms exponential calculation on operators # These are the more obscure operators, we will take notes on more later on in the course
Rails.application.routes.draw do # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html root 'posts#index', as: 'home' get 'about' => 'pages#about', as: 'about' get 'history' => 'pages#history', as: 'history' get 'photos' => 'pages#photos', as: 'photos' get 'posts' => 'posts#new', as: 'create_post' get 'search' => 'posts#search', as: 'search_page' resources :posts end
require 'spec_helper' require 'rspec/expectations' describe TicTacToeRZ::Core::Players::Minimax do let(:ai) { new_ai } def new_ai TicTacToeRZ::Core::Players::Minimax.new.tap do |ai| ai.set_marks(TicTacToeRZ::Core::Game::X, TicTacToeRZ::Core::Game::O) end end describe 'wins when it has two in a row' do it 'on the left' do board = TicTacToeRZ::Core::Board.from([" ", "X", "X", " ", " ", " ", " ", " ", " "]) expect(ai.get_move(board)).to eq(0) end it 'in the center' do board = TicTacToeRZ::Core::Board.from(["X", " ", "X", " ", " ", " ", " ", " ", " "]) expect(ai.get_move(board)).to eq(1) end it 'on the right' do board = TicTacToeRZ::Core::Board.from(["X", "X", " ", " ", " ", " ", " ", " ", " "]) expect(ai.get_move(board)).to eq(2) end end describe 'blocks when the opponent would win' do it 'on the left' do board = TicTacToeRZ::Core::Board.from([" ", "O", "O", " ", "O", "X", "X", "X", "O"]) expect(ai.get_move(board)).to eq(0) end it 'in the center' do board = TicTacToeRZ::Core::Board.from(["O", " ", "O", "O", " ", "X", "X", "O", "X"]) expect(ai.get_move(board)).to eq(1) end it 'on the right' do board = TicTacToeRZ::Core::Board.from(["O", "O", " ", "O", "X", " ", "X", "X", "O"]) expect(ai.get_move(board)).to eq(2) end end describe 'creates forks' do it 'in the center' do board = TicTacToeRZ::Core::Board.from(["X", "X", "O", " ", " ", " ", " ", " ", " "]) expect(ai.get_move(board)).to eq(4) end it 'on the side' do board = TicTacToeRZ::Core::Board.from(["X", " ", " ", " ", "X", " ", " ", " ", "O"]) expect(ai.get_move(board)).to eq(1) end it 'in the corner' do board = TicTacToeRZ::Core::Board.from(["X", " ", " ", " ", "O", " ", " ", " ", "X"]) expect(ai.get_move(board)).to eq(2) end it 'in the corner' do board = TicTacToeRZ::Core::Board.from(["X", " ", "O", " ", "O", " ", " ", " ", "X"]) expect(ai.get_move(board)).to eq(6) end it 'in the center' do board = TicTacToeRZ::Core::Board.from(["X", "O", " ", "O", " ", " ", "X", " ", " "]) expect(ai.get_move(board)).to eq(4) end it 'in the corner or on the side' do board = TicTacToeRZ::Core::Board.from(["X", "O", " ", " ", "X", " ", " ", " ", "O"]) expect(ai.get_move(board)).to eq(3).or eq(6) end end describe 'blocks opponents forks' do RSpec::Matchers.define :be_any_of do |a, b| match do |actual| actual == a or actual == b end end RSpec::Matchers.define :be_any_of do |a, b, c| match do |actual| actual == a or actual == b or actual == c end end RSpec::Matchers.define :be_any_of do |a, b, c, d| match do |actual| actual == a or actual == b or actual == c or actual == d end end it 'on the side' do board = TicTacToeRZ::Core::Board.from([" ", " ", "O", " ", "X", " ", "O", " ", " "]) expect(ai.get_move(board)).to be_any_of(1, 3, 5, 7) end it 'in the center' do board = TicTacToeRZ::Core::Board.from(["O", "O", "X", " ", " ", " ", " ", " ", " "]) expect(ai.get_move(board)).to be_any_of(4, 5) end it 'on either side' do board = TicTacToeRZ::Core::Board.from(["O", " ", " ", " ", "O", " ", " ", " ", "X"]) expect(ai.get_move(board)).to be_any_of(2, 6) end end describe 'plays second correctly' do it 'from a corner opening' do board = TicTacToeRZ::Core::Board.from(["O", " ", " ", " ", " ", " ", " ", " ", " "]) expect(ai.get_move(board)).to eq(4) end it 'from a center opening' do board = TicTacToeRZ::Core::Board.from([" ", " ", " ", " ", "O", " ", " ", " ", " "]) expect(ai.get_move(board)).to be_any_of(0, 2, 6, 8) end it 'from a side opening' do board = TicTacToeRZ::Core::Board.from([" ", "O", " ", " ", " ", " ", " ", " ", " "]) expect(ai.get_move(board)).to be_any_of(4, 0, 2, 7) end end describe 'negamax' do it 'scores an immediate loss as -100' do board = TicTacToeRZ::Core::Board.from(["O", "O", "O", " ", " ", " ", " ", " ", " "]) expect(ai.negamax({1 => "X", -1 => "O"}, board, 10, -100, 100, 1)).to eq([-1, -100]) end it 'scores an immediate win as 100' do board = TicTacToeRZ::Core::Board.from(["X", "X", "X", " ", " ", " ", " ", " ", " "]) expect(ai.negamax({1 => "X", -1 => "O"}, board, 10, -100, 100, 1)).to eq([-1, 100]) end end end
class JsonApiFormFactory InvalidPayload = Class.new(StandardError) def self.build(form_klass, params) form_klass.new( ActiveModelSerializers::Deserialization.jsonapi_parse!( params.with_indifferent_access ) ) rescue ActiveModelSerializers::Adapter::JsonApi::Deserialization::InvalidDocument raise InvalidPayload end end
class WelcomeMailer < ActionMailer::Base add_template_helper(ApplicationHelper) default from: "example@example.com" def welcome_email(account) @account = account @user = account.users.first mail(to: @user.email, subject: 'Welcome to Swapz') end end
# Stores the column information class Redpear::Schema::Collection < Array # @param [Class] klass # @param [multiple] args the column definition. # @see Redpear::Schema::Column#initialize def store(klass, *args) reset! klass.new(*args).tap do |col| self << col end end # @return [Array] the names of the columns def names @names ||= lookup.keys end # @return [Hash] the column lookup, indexed by name def lookup @lookup ||= inject({}) {|r, c| r.update c.to_s => c } end # @return [Array] only the index columns def indicies @indicies ||= to_a.select {|i| i.is_a?(Redpear::Schema::Index) } end # @param [String] name the column name # @return [Boolean] if name is part of the collection def include?(name) lookup.key?(name.to_s) end # @param [String] name the column name # @return [Redpear::Schema::Column] the column for the given name def [](name) lookup[name.to_s] end # Resets indexes and lookups def reset! instance_variables.each do |name| instance_variable_set name, nil end end end
# frozen_string_literal: true require './lib/proforma/html_renderer/version' Gem::Specification.new do |s| s.name = 'proforma-html-renderer' s.version = Proforma::HtmlRenderer::VERSION s.summary = 'Proforma renderer plugin for generating HTML.' s.description = <<-DESCRIPTION Proforma is a virtual document object model. This library allows you to output HTML for a virtual Proforma document. DESCRIPTION s.authors = ['Matthew Ruggio'] s.email = ['mruggio@bluemarblepayroll.com'] s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.bindir = 'exe' s.executables = %w[] s.homepage = 'https://github.com/bluemarblepayroll/proforma-html-renderer' s.license = 'MIT' s.metadata = { 'bug_tracker_uri' => 'https://github.com/bluemarblepayroll/proforma-html-renderer/issues', 'changelog_uri' => 'https://github.com/bluemarblepayroll/proforma-html-renderer/blob/master/CHANGELOG.md', 'documentation_uri' => 'https://www.rubydoc.info/gems/proforma-html-renderer', 'homepage_uri' => s.homepage, 'source_code_uri' => s.homepage } s.required_ruby_version = '>= 2.3.8' s.add_dependency('proforma', '~>1') s.add_development_dependency('guard-rspec', '~>4.7') s.add_development_dependency('pry', '~>0') s.add_development_dependency('rake', '~> 13.0') s.add_development_dependency('rspec', '~> 3.8') s.add_development_dependency('rubocop', '~>0.79.0') s.add_development_dependency('simplecov', '~>0.17.0') s.add_development_dependency('simplecov-console', '~>0.6.0') end
class User < ActiveRecord::Base attr_accessible :first_name, :phone validates :first_name, :presence => true validates :phone, :presence => true end