text
stringlengths
10
2.61M
# ============================================================================= # # MODULE : test/test_group_concurrent_queue.rb # PROJECT : DispatchQueue # DESCRIPTION : # # Copyright (c) 2016, Marc-Antoine Argenton. All rights reserved. # ============================================================================= require '_test_env.rb' require 'timeout' module DispatchQueue describe "DispatchGroup with ConcurrentQueue" do let( :target_queue ) { ConcurrentQueue.new } let( :group ) { DispatchGroup.new } it "leaves group when task completes, with single task on idle queue " do target_queue.dispatch_async( group:group ) { sleep( 0.002 ) } assert_must_timeout( 0.001 ) { group.wait() } assert_wont_timeout( 0.002 ) { group.wait() } end it "leaves group when task completes, with enquened tasks" do (1..10).each do target_queue.dispatch_async( group:group ) { sleep( 0.002 ) } end assert_must_timeout( 0.001 ) { group.wait() } assert_wont_timeout( 0.020 ) { group.wait() } end it "leaves group when task completes, with barrier tasks only" do (1..4).each do target_queue.dispatch_barrier_async( group:group ) { sleep( 0.002 ) } end assert_must_timeout( 0.001 ) { group.wait() } assert_wont_timeout( 0.010 ) { group.wait() } end it "leaves group when task completes, with mix of barrier and non-barrier tasks" do target_queue.dispatch_async( group:group ) { sleep( 0.002 ) } (1..10).each do target_queue.dispatch_async( group:group ) { sleep( 0.001 ) } end target_queue.dispatch_barrier_async( group:group ) { sleep( 0.001 ) } (1..10).each do target_queue.dispatch_async( group:group ) { sleep( 0.002 ) } end target_queue.dispatch_barrier_async( group:group ) { sleep( 0.001 ) } assert_must_timeout( 0.001 ) { group.wait() } assert_wont_timeout( 0.030 ) { group.wait() } end it "completes immediatly after a last synchronous barrier" do target_queue.dispatch_async( group:group ) { sleep( 0.002 ) } (1..10).each do target_queue.dispatch_async( group:group ) { sleep( 0.001 ) } end target_queue.dispatch_barrier_async( group:group ) { sleep( 0.001 ) } (1..10).each do target_queue.dispatch_async( group:group ) { sleep( 0.002 ) } end assert_must_timeout( 0.001 ) { group.wait() } target_queue.dispatch_barrier_sync( group:group ) { sleep( 0.001 ) } assert_wont_timeout( 0.001 ) { group.wait() } end end # DispatchGroup with ConcurrentQueue end # module DispatchQueue
Hogwarts::Application.routes.draw do root to: 'houses#index' resources :houses do end resources :students do end end
module JsonWord module ToInclude def check_valid w = Word.find(:first, :conditions => ["stem=? and pos=?", stem, pos]) if w self.relevant = w.relevant else if count > 10 self.relevant = true else self.relevant = false end end self.save! end def pos_string if pos == "NC" "Sustantivo" elsif pos == "Adj" "Adjetivo" else "Verbo" end end def to_hash h = { :stem => stem, :pos => pos, :literal => literal, :lemma => lemma, :count => count } if date h[:date] = date end h end end module ToExtend def parse_date(data) if data["date"] y, m, d =data["date"].split(".") data["date"] = Date.new(y.to_i,m.to_i,d.to_i) end data end def parse_words(to_merge,words) words.each do |w| w = parse_date(w) self.new(w.merge(to_merge)).save! end end end end
class LandmarksController < ApplicationController # Question mark after the trailing slash means that slash is optional get '/landmarks/?' do if params[:order] == "alpha" @landmarks = Landmark.all.order(:name) else @landmarks = Landmark.all end erb :"/landmarks/index" end get '/landmarks/new/?' do @books = Book.all erb :"/landmarks/new" end get '/landmarks/:id/?' do landmark_id = params[:id] @landmark = Landmark.find_by(id: landmark_id) erb :"/landmarks/show" end post '/landmarks' do p params new_landmark = Landmark.new(params[:landmark]) if new_landmark.save if params[:visit] && params[:visit][:reflection] new_visit = Visit.new(params[:visit]) new_visit.landmark = new_landmark new_visit.save end redirect "/landmarks/#{new_landmark.id}" else @books = Book.all @errors = new_landmark.errors.full_messages erb :"/landmarks/new" end end get "/info/?" do # We could totally have our app return a list of all navigable routes, if we wanted to. This route is not named according to REST conventions, it's more of a "user-facing" name. "ROUTES: /landmarks to see all, /landmarks/{MY LANDMARK ID} to see one...etc" end end
# ========================================================================== # Project: Lebowski Framework - The SproutCore Test Automation Framework # License: Licensed under MIT license (see License.txt) # ========================================================================== module Lebowski module Foundation module Mixins # # Mixin containing a set of commonly performed user actions. Mix this into any # class that is able to perform these set of actions. # module UserActions include PositionedElement include KeyCheck include StallSupport def mouse_move_at(x, y) @driver.sc_mouse_move_at action_target, x, y, *action_locator_args stall :mouse_move end def mouse_up_at(x, y) @driver.sc_mouse_up_at action_target, x, y, *action_locator_args stall :mouse_up end def mouse_down_at(x, y) scroll_to_visible @driver.sc_mouse_down_at action_target, x, y, *action_locator_args stall :mouse_down end def right_mouse_down_at(x, y) scroll_to_visible @driver.sc_right_mouse_down_at action_target, x, y, *action_locator_args stall :right_mouse_down end def right_mouse_up_at(x, y) @driver.sc_right_mouse_up_at action_target, x, y, *action_locator_args stall :right_mouse_up end def click_at(x, y) mouse_down_at x, y mouse_up_at x, y stall :click end def double_click_at(x, y) scroll_to_visible @driver.sc_double_click_at action_target, x, y, *action_locator_args stall :double_click end def right_click_at(x, y) right_mouse_down_at x, y right_mouse_up_at x, y stall :right_click end def mouse_move() @driver.sc_mouse_move action_target, *action_locator_args stall :mouse_move end # # Used to perform a mouse down on this view in the remote application # def mouse_down() mouse_down_at :center, :center end # # Used to perform a mouse up on this view in the remote application # def mouse_up() mouse_up_at :center, :center end # # Used to perform a mouse down with right button on this view in the remote application # def right_mouse_down() right_mouse_down_at :center, :center end # # Used to perform a mouse up with right button on this view in the remote application # def right_mouse_up() right_mouse_up_at :center, :center end # # Used to perform a double click on this view in the remote application # def double_click() double_click_at :center, :center end # # Used to perform a single click on this view in the remote application # def click() mouse_down mouse_up stall :click end # # Used to perform a single right click on this view in the remote application # def right_click() right_mouse_down right_mouse_up stall :right_click end # # Used to perform a single basic click on this view in the remote application # def basic_click() scroll_to_visible @driver.sc_basic_click action_target, *action_locator_args stall :click end # # Used to perform a mouse wheel action on the x-axis # def mouse_wheel_delta_x(delta) @driver.sc_mouse_wheel_delta_x action_target, delta, *action_locator_args stall :mouse_wheel end # # Used to perform a mouse wheel action on the y-axis # def mouse_wheel_delta_y(delta) @driver.sc_mouse_wheel_delta_y action_target, delta, *action_locator_args stall :mouse_wheel end # # Used to perform a key down on this view in the remote application # # You can either type a printable character or a function key. If you want to type a printable # character then the 'key' parameter just has to be a string, such as 'a'. If you want to type # a function key such as F1, then the 'key' parameter must be the corresponding symbol. # # Example: # # view.key_down 'a' # key down for printable character 'a' # view.key_down :delete # key down for function key delete # view.key_down :meta_key # key down for the meta key # def key_down(key) focus @driver.sc_key_down action_target, key, *action_locator_args stall :key_down end # # Used to perform a key up on this view in the remote application # # You can either type a printable character or a function key. If you want to type a printable # character then the 'key' parameter just has to be a string, such as 'a'. If you want to type # a function key such as F1, then the 'key' parameter must be the corresponding symbol. # # Example: # # view.key_up 'a' # key up for printable character 'a' # view.key_up :delete # key up for function key delete # view.key_up :meta_key # key up for the meta key # def key_up(key) focus @driver.sc_key_up action_target, key, *action_locator_args stall :key_up end # # Used to type a key on this view in the remote application. This will cause a key down followed # by a key up # # You can either type a printable character or a function key. If you want to type a printable # character then the 'key' parameter just has to be a string, such as 'a'. If you want to type # a function key such as F1, then the 'key' parameter must be the corresponding symbol. # # Example: # # view.type_key 'a' # type printable character 'a' # view.type_key :delete # type function key delete # def type_key(key) focus @driver.sc_type_key action_target, key, *action_locator_args stall :type_key end def type(text) focus @driver.sc_type action_target, text, *action_locator_args stall :type_key end def focus() @driver.sc_focus action_target, *action_locator_args end def drag(x, y, *params) if (not x.kind_of? Integer) or (not y.kind_of? Integer) raise ArgumentError.new "Must supply valid x-y coordinates: x = #{x}, y = #{y}" end relative_to = nil mouse_offset_x = 0 mouse_offset_y = 0 if params.length > 0 and params[0].kind_of?(Hash) relative_to = params[0][:relative_to] mouse_offset_x = get_mouse_offset(params[0][:mouse_offset_x], :x) mouse_offset_y = get_mouse_offset(params[0][:mouse_offset_y], :y) end # First be sure to disable autoscrolling in the application. This needs # to be done so that autoscrolling will not interfere with our drag # and drop user action @driver.sc_disable_all_autoscrolling mouse_down_at mouse_offset_x, mouse_offset_y # Need to incoporate an intentional sleep so sproutcore # has enough time to do its thing sleep 0.2 mouse_move_at mouse_offset_x, mouse_offset_y # Make sure the element we are dragging relative to is visible relative_to.scroll_to_visible if relative_to.kind_of? PositionedElement rel_pos = relative_position(x, y, relative_to) mouse_move_at rel_pos.x, rel_pos.y rel_pos = relative_position(x, y, relative_to) mouse_up_at rel_pos.x, rel_pos.y # Enable autoscrolling and mouse move events since we have completed the # drag and drop operation @driver.sc_enable_all_autoscrolling @driver.sc_enable_mouse_move_event end def drag_to(source, offset_x=nil, offset_y=nil, *params) if not (source.kind_of? PositionedElement or source == :window) raise ArgumentError.new "source must be an positioned element: #{source.class}" end offset_x = offset_x.nil? ? 0 : offset_x offset_y = offset_y.nil? ? 0 : offset_y params2 = { :relative_to => source } if params.length > 0 and params[0].kind_of? Hash params2[:mouse_offset_x] = params[0][:mouse_offset_x] params2[:mouse_offset_y] = params[0][:mouse_offset_y] end drag offset_x, offset_y, params2 end def drag_on_to(source) drag_to source, 1, 1 end def drag_before(item) assert_item_has_collection_item_view_support(item, 'item') return if not item.can_drag_before? item.apply_drag_before self end def drag_after(item) assert_item_has_collection_item_view_support(item, 'item') return if not item.can_drag_after? item.apply_drag_after self end def drag_to_start_of(view) assert_is_collection_view(view, 'view'); return if not view.can_drag_to_start_of? view.apply_drag_to_start_of self end def drag_to_end_of(view) assert_is_collection_view(view, 'view'); return if not view.can_drag_to_end_of? view.apply_drag_to_end_of self end protected # # Override this to supply the target, which can either be one of the following: # # :view # :core_query_element # def action_target() end # # Override this to supply the arguments to generate the locator # def action_locator_args() end private def relative_position(x, y, relative_to) rel_x = 0 rel_y = 0 if not relative_to.nil? position = self.position rel_x += position.x * -1 rel_y += position.y * -1 if relative_to.kind_of? PositionedElement position = relative_to.position rel_x += position.x rel_y += position.y elsif relative_to == :window else raise ArgumentError.new "relative to source must be a positioned element: #{relative_to.class}" end end rel_x += x rel_y += y return Lebowski::Coords.new rel_x, rel_y end def assert_is_collection_view(value, name) if not value.kind_of? Lebowski::Foundation::Views::CollectionView raise ArgumentInvalidTypeError.new name, value, Lebowski::Foundation::Views::CollectionView end end def assert_item_has_collection_item_view_support(value, name) if not value.respond_to? :has_collection_item_view_support raise ArgumentError.new "#{name} must have collection item view support (#{CollectionItemViewSupport})" end end def get_mouse_offset(offset, coord) return 0 if offset.nil? if offset == :center return (width / 2).floor if (coord == :x) return (height / 2).floor if (coord == :y) end return offset if (offset.kind_of? Integer and offset >= 0) raise ArgumentError.new "Invalid offset value: #{offset}" end end end end end
require 'test_helper' class ImageHelperView include Lotus::View include Lotus::Helpers::AssetTagHelpers attr_reader :params def initialize(params) @params = Lotus::Action::Params.new(params) end end describe Lotus::Helpers::AssetTagHelpers do let(:view) { ImageHelperView.new(params) } let(:params) { Hash[] } describe 'image' do it 'render an img tag' do view.image('application.jpg').to_s.must_equal %(<img src=\"/assets/application.jpg\" alt=\"Application\">) end it 'custom alt' do view.image('application.jpg', alt: 'My Alt').to_s.must_equal %(<img alt=\"My Alt\" src=\"/assets/application.jpg\">) end it 'custom data attribute' do view.image('application.jpg', 'data-user-id' => 5).to_s.must_equal %(<img data-user-id=\"5\" src=\"/assets/application.jpg\" alt=\"Application\">) end end describe '#favicon' do it 'renders' do view.favicon.to_s.must_equal %(<link href="/assets/favicon.ico" rel="shortcut icon" type="image/x-icon">) end it 'renders with HTML attributes' do view.favicon('favicon.png', rel: 'icon', type: 'image/png').to_s.must_equal %(<link rel="icon" type="image/png" href="/assets/favicon.png">) end end describe '#video' do it 'renders' do tag = view.video('movie.mp4') tag.to_s.must_equal %(<video src="/assets/movie.mp4"></video>) end it 'renders with html attributes' do tag = view.video('movie.mp4', autoplay: true, controls: true) tag.to_s.must_equal %(<video autoplay="autoplay" controls="controls" src="/assets/movie.mp4"></video>) end it 'renders with fallback content' do tag = view.video('movie.mp4') do "Your browser does not support the video tag" end tag.to_s.must_equal %(<video src="/assets/movie.mp4">\nYour browser does not support the video tag\n</video>) end it 'renders with tracks' do tag = view.video('movie.mp4') do track kind: 'captions', src: view.asset_path('movie.en.vtt'), srclang: 'en', label: 'English' end tag.to_s.must_equal %(<video src="/assets/movie.mp4">\n<track kind="captions" src="/assets/movie.en.vtt" srclang="en" label="English">\n</video>) end it 'renders with sources' do tag = view.video do text "Your browser does not support the video tag" source src: view.asset_path('movie.mp4'), type: 'video/mp4' source src: view.asset_path('movie.ogg'), type: 'video/ogg' end tag.to_s.must_equal %(<video>\nYour browser does not support the video tag\n<source src="/assets/movie.mp4" type="video/mp4">\n<source src="/assets/movie.ogg" type="video/ogg">\n</video>) end it 'raises an exception when no arguments' do -> {view.video()}.must_raise ArgumentError end it 'raises an exception when no src and no block' do -> {view.video(content: true)}.must_raise ArgumentError end end end
#!/usr/bin/env ruby # # Read several bib files and merge into one # # check the values of: # date-written-via-bibdump # date-modified # $:.unshift(File.dirname(__FILE__)) require 'bib_library.rb' require 'papers_library.rb' require 'getoptlong' require 'kconv' require 'date' $stdout.set_encoding("EUC-JP", "UTF-8") # # main # if __FILE__ == $0 require 'optparse' opts = { # default options :mode => "plain", :draft => false, :encoding => "UTF-8", :output_encoding => "UTF-8", :key_file => "", # if it's null string, try to generate file by basename :bib_dir => "./bib", :force => false, :timestamp => true, :add => false, :overwrite => false, :group => nil, :dep_dump => false } ARGV.options do |o| o.banner = "ruby #{$0} [options] BIB_File bib_keys..." o.separator "Options:" o.on("--utf-8", "-u", "Set both i/o encoding to UTF-8") {|x| opts[:encoding] = "UTF-8" ; opts[:output_encoding] = opts[:encoding] } o.on("--euc-jp", "-e", "Set both i/o encoding to EUC-JP") {|x| opts[:encoding] = "EUC-JP" ; opts[:output_encoding] = opts[:encoding] } o.on("--sjis", "-s", "Set both i/o encoding to Shift_JIS") {|x| opts[:encoding] = "Shift_JIS" ; opts[:output_encoding] = opts[:encoding] } o.on("--output-utf-8", "Set output encoding to UTF-8") {|x| opts[:output_encoding] = "UTF-8" } o.on("--output-euc-jp", "Set output encoding to EUC-JP") {|x| opts[:output_encoding] = "EUC-JP" } o.on("--output-sjis", "Set output encoding to Shift_JIS") {|x| opts[:output_encoding] = "Shift_JIS" } o.on("--bib-dir", "-B DIR", "Set bib dir (currently ./bib)") {|x| opts[:bib_dir] = x } o.on("--force", "-f", "Force to overwrite files") {|x| opts[:force] = true } o.on("--no-time-stamp", "-t", "don't add bibdump date") {|x| opts[:timestamp] = false } o.on("--add", "-a", "Add to primary if missing") {|x| opts[:add] = true } o.on("--overwrite", "-o", "Do overwrite if needed") {|x| opts[:overwrite] = true } o.on("--dump-mismatch", "-d", "Dump mismatched entries") {|x| opts[:dump_mismatch] = true } o.on("--group GROUP", "-G GROUP", "Configure group mode") {|x| opts[:group] = x } o.on("--dep-dump", "-p", "Dump dependencies") {|x| opts[:dep_dump] = true } o.parse! end if ARGV.size >= 1 if opts[:dep_dump] == true blib = BibLibrary.new(nil, opts) ARGV.each do |f| bibfile = blib.mkbibpath(f) if bibfile == nil STDERR.puts "#{f} not found" else puts bibfile end end else blib = BibLibrary.new(ARGV.shift, opts) ARGV.each do |f| bibfile = blib.mkbibpath(f) if bibfile == nil STDERR.puts "#{f} not found" else new_blib = BibLibrary.new(bibfile, opts) blib.merge(new_blib) end end blib.out(STDOUT) end end end
class Player attr_accessor :life, :name @@player_count = 1 def initialize(life = 3) print "Player #{@@player_count}, enter your name: " @name = gets.chomp @life = life @@player_count += 1 end def wrong_answer @life -= 1 end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the 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) require 'csv' require 'awesome_print' CSV.read('db/media_seeds.csv', headers: true, header_converters: :symbol).each do |line| work = Work.new(line.to_h) work.user = User.find(1) if !work.save puts "Unable to save #{work.title}: #{work.errors.messages}" else puts "Work: #{work.title} saved" end end
require 'sinatra' require 'haml' require 'zipruby' require 'rufus-scheduler' require 'securerandom' require 'logger' require File.expand_path '../lib/vk.rb', __FILE__ class VkPhotos < Sinatra::Base configure :development, :production do enable :logging, :sessions disable :run end not_found { redirect '/' } error { redirect '/error?msg=неведомая ошибка' } before /auth|auth\/vk|download/ do @vk = VK.new(ENV['APP_ID'], ENV['APP_SECRET']) @vk.permissions = ["photos"] @vk.redirect_uri = "#{ENV['DOMAIN_NAME']}/auth/vk" end get('/') do haml :index end get '/auth' do if token_valid? redirect '/download' else clear_session redirect @vk.auth_url end end get '/auth/vk' do if params[:code] begin response = @vk.auth(params[:code]) rescue redirect '/error?msg=ошибка соединения' end if response["access_token"] set_session(response) redirect '/download' elsif response[:error] redirect "/error?msg=#{response["error"]}" end elsif params[:error] redirect "/error?msg=#{params[:error].gsub('_', ' ')}" else redirect "/error?msg=неведомая ошибка" end end get '/download' do photos = @vk.get_photos_with(session[:token], session[:uid]) urls = photos.map{|photo| photo["url"]} filename = "#{session[:uid]}_#{Time.now.to_i}.zip" dir = "#{File.dirname(__FILE__)}/public/tmp/" info = zip_from_urls urls, dir+filename schedule_deletion(dir+filename) redirect "/photos?count=#{info[:count]}&skipped=#{info[:skipped]}&password=#{info[:password]}&filename=#{'/tmp/'+filename}" end get '/photos' do @count = params[:count].to_i @skipped = params[:skipped].to_i @password = params[:password] @file_url = params[:filename] haml :photos end get '/error' do @msg = params[:msg] haml :error end private def zip_from_urls urls, filename count, skipped = 0, 0 password = SecureRandom.hex(4) Zip::Archive.open(filename, Zip::CREATE) do |archive| urls.each do |url| name = url[/[^\/]+\.[\w]+$/] begin buffer = open(url).read count += 1 rescue skipped += 1 next end archive.add_buffer(name, buffer) end archive.encrypt(password) end {count: count, skipped: skipped, password: password} end def schedule_deletion file logger = Logger.new('log/app.log') Thread.new do filename = File.basename(file) scheduler = Rufus::Scheduler.new scheduler.in '1h' do begin File.delete(file) logger.info("'#{filename}' successfully deleted") rescue => e logger.error("'#{filename}' deletion failed: e.message") end end logger.info "deletion scheduled for '#{filename}'" end if File.exist?(file) end def token_valid? session[:token] and (session[:expires] > Time.now.to_i) end def set_session response session[:token] = response["access_token"] session[:uid] = response["user_id"] session[:expires] = Time.now.to_i + response["expires_in"] end def clear_session session[:token] = nil session[:uid] = nil session[:expires] = nil end end
class SharedPlace < ApplicationRecord belongs_to :place belongs_to :friend, class_name: 'User' end
require 'csv' require 'benchmark' require_relative 'sort.rb' lengths = [1, 2, 5, 10, 20, 30, 50, 75, 100, 150, 250, 500, 750, 1000, 2500, 5000, 7500, 10000] methods = ["bubblesort", "gnomesort", "selectionsort", "insertionsort", "shellsort", "radixsortlsd", "quicksort"] seperator = "," header = "Random#{seperator}" + methods.collect{|m|m.capitalize}.join(seperator) + "\n" File.open("../csv/random.csv", "w+") do |line| t = Time.now line << header lengths.each do |length| output = [length] array = [] (length).times {array << rand(length*10)} methods.each do |method| time = Benchmark.realtime {10.times{send(method, array)}} output << ((time/10)*1000).round(8) end output[-1] = "#{output[-1]}\n" line << output.join(",") end t = Time.now - t p t end
module Smite class Competitor < Smite::Object def initialize(data) data['Queue'] = data['name'] super @data = DataTransform.transform_items(@data) @data = DataTransform.transform_match_achievements(@data) @data = DataTransform.transform_match_summary(@data) end def to_player Smite::Game.player(player_id) end def partied? party_id != 0 end def winner? win_status == 'Winner' end def loser? !winner? end def inspect "#<Smite::Competitor '#{match}' '#{player_name}'>" end end end
Rails.application.routes.draw do root "leagues#index" devise_for :users resources :leagues end
module Rounders module Handlers class Handler include Rounders::Plugins::Pluggable include Topping::Configurable::Branch attr_reader :matches, :rounder class << self class Event attr_reader :matcher, :method_name, :event_class def initialize(event_class, method_name, matcher) @event_class = event_class @matcher = matcher @method_name = method_name end def call(mail, rounder) matches = match(mail) return if matches.nil? trigger(mail, rounder, matches) end private def match(mail) matcher.match(mail) end def trigger(mail, rounder, matches) event_class.new(rounder).public_send(method_name, mail, matches) end end def inherited(klass) super Rounders.handlers << klass end def dispatch(rounder, mails) mails.map do |mail| events.each { |event| event.call(mail, rounder) } end end def on(option, method_name) matcher = Rounders::Matchers::Matcher.build(option) events << Event.new(self, method_name, matcher) end private def events @events ||= [] end end def initialize(rounder) @rounder = rounder end end end end
class Admin::ProvidersController < AdminController load_and_authorize_resource def index @providers = Kaminari.paginate_array(@providers).page params[:page] end def new end def create @provider = Provider.new(provider_params) if @provider.save redirect_to admin_provider_path(@provider) else render 'new' end end def update if @provider.update(provider_params) flash[:sucess] = "Accompagnement mis à jour" redirect_to admin_providers_path else render 'edit' end end def destroy @provider.destroy redirect_to admin_providers_path end private def provider_params params.require(:provider).permit(:nom, :reference, :siret, :email,:phone,:address,:product_ids => [], product_providers_attributes: [:id, :price_cents, :product_name, :product_reference, :product_id,:_destroy]) end end
require 'calculator' require 'ostruct' describe Dodecaphony::Calculator do it "initializes with a row" do row = Dodecaphony::Row.new %w[a b b- c c# d d# e f gb g g#] calc = Dodecaphony::Calculator.new row expect(calc).to be_kind_of(Dodecaphony::Calculator) end it "can provide the original row" do row = Dodecaphony::Row.new %w[a b b- c c# d d# e f gb g g#] calc = Dodecaphony::Calculator.new row expect(calc.p0).to eq row.to_a end it "can provide p1" do row = Dodecaphony::Row.new %w[ bb b c c# d f e eb g gb a ab ] p1_row = %w[ b c c# d eb gb f e ab g bb a ] calc = Dodecaphony::Calculator.new row expect(calc.p1).to eq p1_row.to_a end it "can give p7" do row = Dodecaphony::Row.new %w[ d c# a b- f eb e c ab g f# b ] prime7 = %w[ a ab e f c b- b g eb d c# f# ] calc = Dodecaphony::Calculator.new row expect(calc.p7).to eq prime7 end it "can give i0" do row = Dodecaphony::Row.new %w[ A ab a# b c c# d eb e f gb g ] new_row = %w[ A a# ab g gb f e eb d c# c b ] calc = Dodecaphony::Calculator.new row expect(calc.i0).to eq new_row end it "can give i8" do row = Dodecaphony::Row.new %w[ A ab a# b c c# d eb e f gb g ] new_row = %w[ f gb e eb d c# c b a# A ab g ] calc = Dodecaphony::Calculator.new row expect(calc.i8).to eq new_row end it "can give r0" do row = Dodecaphony::Row.new %w[ a f# g ab e f b bb d c# c eb ] new_row = %w[ eb c c# d bb b f e ab g f# a ] calc = Dodecaphony::Calculator.new row expect(calc.r0).to eq new_row end it "can give r9" do row = Dodecaphony::Row.new %w[ a f# g ab e f b bb d c# c eb ] new_row = %w[ c a bb b g ab d c# f e eb f# ] calc = Dodecaphony::Calculator.new row expect(calc.r9).to eq new_row end it "can give ri0" do row = Dodecaphony::Row.new %w[ a f# g ab e f b bb d c# c eb ] new_row = %w[eb f# f e ab g c# d bb b c a ] calc = Dodecaphony::Calculator.new row expect(calc.ri0).to eq new_row end it "can give ri11" do row = Dodecaphony::Row.new %w[ a f# g ab e f b bb d c# c eb ] new_row = %w[ c# e eb d f# f b c ab a bb g ] calc = Dodecaphony::Calculator.new row expect(calc.ri10).to eq new_row end end
require 'rails_helper' RSpec.describe Event, type: :model do describe '.processed' do let!(:unproccessed) { create :event } let!(:processed) { create :event, :processed } it do expect(described_class.processed).to match_array(processed) end end describe '.with_type' do let!(:event_type1) { create :event, email_type: 'Foo' } let!(:event_type2) { create :event, email_type: 'Bar' } it do expect(described_class.with_type('Foo')).to match_array(event_type1) end end end
# spec/support/models/edge.rb class Edge < Struct.new(:color) include ActiveModel::Validations validates :color, :presence => true end # class
require 'spec_helper' describe Estatic::Generator do let(:generator) { described_class.new } describe '.initialize' do it 'should respond to run' do expect(generator).to respond_to(:run) end it 'should create an `estatic_site` directory' do generator expect(File.directory?(estatic_site_path)).to be_truthy end end describe '.run' do before do Estatic.configure do |c| c.featured = 'featured' c.categories = ['sample_1', 'sample_2'] c.project_path = fixtures_path end generator.run end it 'generates home page' do home_page = Dir.glob("#{Estatic.root}/estatic_site/index.html").first expect(home_page).to be_truthy end it 'creates a subfolder for each category' do expect(File.directory?(estatic_sample_1_path)).to be_truthy end end end
class AddDisagreementCommentToCandidateProfile < ActiveRecord::Migration def change add_column :candidate_profiles, :disagreement_comment, :string end end
require 'cinch' require 'yaml' require 'byebug' require_relative 'util.rb' require 'ostruct' require 'json' class Hash # https://stackoverflow.com/a/45851976 def to_o JSON.parse to_json, object_class: OpenStruct end end class PluginMan include Cinch::Plugin def initialize(*args) super @list = [] @cfg = YAML.safe_load(open('conf.yml')) Usagi.settings.cfg = @cfg @adimns = @cfg['admins'] load_plugins end match /reload(.*)/, method: :reload_plugins match 'list', method: :list_plugins # alias old_reg __register # def __register(*args) # @bot.loggers.debug '[Pluginman init]' # old_reg(*args) # end def load_plugins files = Dir.entries('plugins') @list = [] @status = [] files.grep(/^\w+\.rb/) do |file| @bot.loggers.debug '[PluginMan] loading ' + file @status << { name: file.chomp('.rb') } begin class_name = file.chomp('.rb').split('_').collect(&:capitalize).join if @cfg['blacklist'].include? file.chomp('.rb') @bot.loggers.debug "[PluginMan] #{file} skipping" @status.last[:status] = :disabled elsif load "plugins/#{file}" plugin = Kernel.const_get(class_name) # plugin.db = @db if defined?(plugin.db=1) @list << plugin @status.last[:status] = :ok else @bots.loggers.debug "[PluginMan] #{file} failed to load" @status.last[:status] = :fail end rescue StandardError => e @status.last[:status] = :error @bot.loggers.debug "Exception loading plugin: #{file}" @bot.loggers.debug "Exception class: #{e.class.name}" @bot.loggers.debug "Exception message: #{e.message}" @bot.loggers.debug "Exception backtrace: #{e.backtrace.join("\n")}" end end @bot.plugins.register_plugins(@list) end def unload_plugins @bot.plugins.each do |plugin| unless plugin == self plugin.unregister @bot.loggers.debug "[PluginMan] successfully unloaded #{plugin}" end end end def status_message c = { ok: :green, error: :red, fail: :red, disabled: :yellow } @status.reduce([]) { |m, i| m << Format(c[i[:status]], :black, "[#{i[:name]}]") }.join('') end def reload_plugins(m, msg) @cfg = YAML.safe_load(open('conf.yml')) Usagi.settings.cfg = @cfg # return unless check_user(m.user) unload_plugins load_plugins # m.reply "Reloaded #{@list.size} plugins." failed = @status.count { |i| i[:status] == :failed || i[:status] == :error } disabled = @status.count { |i| i[:status] == :disabled } response = "Reloaded: #{@status.count { |i| i[:status] == :ok }}" response << ', failed: %d' % failed if failed > 0 response << ', disabled: %d' % disabled if disabled > 0 response << ' ' + status_message if msg[/-v/] m.reply response end def check_user(user) user.refresh @admins.include?(user.authname) end def list_plugins(m) # names = [] # @list.each {|p| names << p.class.name } m.reply status_message end end bot = Cinch::Bot.new do configure do |c| cfg = YAML.safe_load(open('conf.yml')) c.server = cfg['server'] c.channels = cfg['channels'] c.nick = cfg['nick'] c.plugins.plugins = [PluginMan] c.plugins.prefix = /^#{Regexp.escape cfg['prefix']}/ || /^!/ if cfg['sasl'] c.sasl.username = cfg['sasl']['username'] || cfg['nick'] c.sasl.password = cfg['sasl']['password'] end # c.plugins.plugins = [JoinPart,Search,DasMew] end end bot.start
require "focuslight" require "focuslight/config" require "focuslight/data" require "sqlite3" module Focuslight::Init def self.run datadir = Focuslight::Config.get(:datadir) FileUtils.mkdir_p(datadir) data = Focuslight::Data.new number_type = data.number_type graphs_create = <<"SQL" CREATE TABLE IF NOT EXISTS graphs ( id INTEGER NOT NULL PRIMARY KEY, service_name VARCHAR(255) NOT NULL, section_name VARCHAR(255) NOT NULL, graph_name VARCHAR(255) NOT NULL, number #{number_type} NOT NULL DEFAULT 0, mode VARCHAR(255) NOT NULL DEFAULT 'gauge', description VARCHAR(255) NOT NULL DEFAULT '', sort UNSIGNED INT NOT NULL DEFAULT 0, gmode VARCHAR(255) NOT NULL DEFAULT 'gauge', color VARCHAR(255) NOT NULL DEFAULT '#00CC00', ulimit #{number_type} NOT NULL DEFAULT 1000000000000000, llimit #{number_type} NOT NULL DEFAULT 0, sulimit #{number_type} NOT NULL DEFAULT 100000, sllimit #{number_type} NOT NULL DEFAULT 0, type VARCHAR(255) NOT NULL DEFAULT 'AREA', stype VARCHAR(255) NOT NULL DEFAULT 'AREA', meta TEXT, created_at UNSIGNED INT NOT NULL, updated_at UNSIGNED INT NOT NULL, UNIQUE (service_name, section_name, graph_name) ) SQL prev_graphs_create = <<"SQL" CREATE TABLE IF NOT EXISTS prev_graphs ( graph_id INT NOT NULL, number #{number_type} NOT NULL DEFAULT 0, subtract #{number_type}, updated_at UNSIGNED INT NOT NULL, PRIMARY KEY (graph_id) ) SQL prev_short_graphs_create = <<"SQL" CREATE TABLE IF NOT EXISTS prev_short_graphs ( graph_id INT NOT NULL, number #{number_type} NOT NULL DEFAULT 0, subtract #{number_type}, updated_at UNSIGNED INT NOT NULL, PRIMARY KEY (graph_id) ) SQL complex_graphs_create = <<"SQL" CREATE TABLE IF NOT EXISTS complex_graphs ( id INTEGER NOT NULL PRIMARY KEY, service_name VARCHAR(255) NOT NULL, section_name VARCHAR(255) NOT NULL, graph_name VARCHAR(255) NOT NULL, number #{number_type} NOT NULL DEFAULT 0, description VARCHAR(255) NOT NULL DEFAULT '', sort UNSIGNED INT NOT NULL DEFAULT 0, meta TEXT, created_at UNSIGNED INT NOT NULL, updated_at UNSIGNED INT NOT NULL, UNIQUE (service_name, section_name, graph_name) ) SQL data.transaction do |conn| conn.execute(graphs_create) conn.execute(prev_graphs_create) conn.execute(prev_short_graphs_create) conn.execute(complex_graphs_create) end end end
class Measurement < ActiveRecord::Base belongs_to :room, dependent: :destroy end
module Hypixel class Session attr_reader :json, :game_type, :id, :players, :server def self.from_json(json) Session.new(json['session']) end private def initialize(json) @json = json @game_type = GameType.from_string json['gameType'] @id = json['_id'] @players = json['players'] ||= [] @server = json['server'] end end end
class SubscriptionsController < ApplicationController def hook if params["type"] == "invoice.payment_succeeded" user = User.where(email: params["receipt_email"]).first user.update_attributes(:role, 'paid') end head :ok end end
class RemoveModFromInstructors < ActiveRecord::Migration[5.2] def change remove_column :instructors, :mod end end
# coding: utf-8 $LOAD_PATH.unshift File.expand_path("../lib", __FILE__) require 'rubygems' require 'bundler/setup' desc 'Default: run unit tests.' task :default => :spec require "rspec/core/rake_task" RSpec::Core::RakeTask.new(:spec) require 'rake/rdoctask' desc 'Generate documentation for the acts_as_optimistic_lock plugin.' Rake::RDocTask.new(:rdoc) do |rdoc| rdoc.rdoc_dir = 'rdoc' rdoc.title = 'ActsAsOptimisticLock' rdoc.options << '--line-numbers' << '--inline-source' rdoc.rdoc_files.include('README') rdoc.rdoc_files.include('lib/**/*.rb') end
class CreateNotificationRecipients < ActiveRecord::Migration def change create_table :notification_recipients do |t| t.integer :notification_id t.integer :user_id t.string :state t.timestamps end add_index :notification_recipients, :notification_id add_index :notification_recipients, [:notification_id, :user_id], unique: true end end
require_relative 'game' require_relative 'guest' require_relative 'settings' class GameMenu include Settings GUEST_TURN_MENU = ['1 - Еще', '2 - Себе', '3 - Вскрываемся', '0 - Закончить партию'].freeze ROUND_MENU = ['1 - Новая партия', '0 - Выход из игры'].freeze GAME_MENU = ['1 - Начать новую игру', '0 - Выход из игры'].freeze GUEST_TURN_MENU_METHODS = { 1 => :guest_hit, 2 => :dealer_turn, 3 => :open_cards }.freeze ROUND_MENU_METHODS = { 1 => :new_round }.freeze GAME_MENU_METHODS = { 1 => :new_game }.freeze attr_reader :game def initialize(game) @game = game new_round end def new_round puts '________________________' puts "#{@game.guest.name}, у вас на счету #{@game.guest.money}$, ставка #{BET}$." puts 'Дилер раздает карты...' sleep(0.5) @game.new_round puts "У вас на руках #{@game.guest_hand}" puts "У дилера #{@game.dealer_hand}" # после того как ставки сделаны первым ходит игрок guest_turn_menu rescue RuntimeError => e puts "Невозможно продолжить игру. #{e.inspect}" end def new_game_menu print GAME_MENU.join(', ').to_s puts user_input = gets.chomp.to_i send GAME_MENU_METHODS[user_input] || abort end def round_menu loop do print ROUND_MENU.join(', ').to_s puts input = gets.chomp.to_i send ROUND_MENU_METHODS[input] || abort end end def guest_turn_menu loop do puts "Ваш ход, #{@game.guest.name}. Выберите действие:" print GUEST_TURN_MENU.join(', ').to_s puts input = gets.chomp.to_i send GUEST_TURN_MENU_METHODS[input] || break end end def guest_hit puts 'Дилер кладет карту...' sleep(0.5) @game.guest_hit puts @game.guest.last_card puts "У вас на руках: #{@game.guest_hand}" puts 'Ход переходит к дилеру' dealer_turn end def dealer_turn puts 'Дилер ходит' @game.dealer_turn puts '________________________' showdown if @game.showdown? end def open_cards @game.guest_open_cards showdown if @game.showdown? end def showdown puts 'Карты на стол... Подсчитаем...' puts "У вас на руках: #{@game.guest.show_hand}" puts "У дилера на руках: #{@game.dealer.show_hand}" @game.declare_winner if @game.guest_won? puts "Вы выиграли #{BET}$. У вас на счету #{@game.guest.money}$" elsif @game.dealer_won? puts "Вы проиграли #{BET}$. У вас на счету #{@game.guest.money}$" else puts "Ничья. У вас на счету #{@game.guest.money}$" end round_menu end end
# frozen_string_literal: true # rubocop:todo all require 'spec_helper' describe 'On-demand AWS Credentials' do require_libmongocrypt include_context 'define shared FLE helpers' include_context 'with AWS kms_providers' let(:client) { ClientRegistry.instance.new_local_client(SpecConfig.instance.addresses) } let(:client_encryption_opts) do { kms_providers: { aws: {} }, kms_tls_options: kms_tls_options, key_vault_namespace: key_vault_namespace } end let(:client_encryption) do Mongo::ClientEncryption.new( client, client_encryption_opts ) end context 'when credentials are available' do it 'authenticates successfully' do expect do client_encryption.create_data_key('aws', data_key_options) end.not_to raise_error end end context 'when credentials are not available' do it 'raises an error' do expect_any_instance_of( Mongo::Auth::Aws::CredentialsRetriever ).to receive(:credentials).with(no_args).once.and_raise( Mongo::Auth::Aws::CredentialsNotFound ) expect do client_encryption.create_data_key('aws', data_key_options) end.to raise_error(Mongo::Error::CryptError, /Could not locate AWS credentials/) end end end
FactoryGirl.define do factory :activity, :class => Refinery::Activities::Activity do sequence(:name) { |n| "refinery#{n}" } end end
class UsersController < ApplicationController require 'uri' before_action :not_self_page, only: :show before_action :set_period, only: :show def show @data_xxx_days = PowerLevel.get_target_period_array(@period, params[:id]) @user = User.find(params[:id]) end def rank case @period = params[:period] || 'total' when 'total' @users = User.power_rank.total_period when 'week' @users = User.power_rank.week_period when 'day' @users = User.power_rank.day_period end @ranks = @users.page(params[:page]).per(25) end def my_rank case @period = params[:period] || 'total' when 'total' @users = User.power_rank.total_period when 'week' @users = User.power_rank.week_period when 'day' @users = User.power_rank.day_period end @ranks = @users.page(params[:page]).per(25) redirect_to ranking_path(view_context.my_rank_query) end # FIXME:コントローラ内でURLの設定はしたくないので、concerns等の他の場所に退避する # その際に、link_toから戦闘力、キャラ名を受け取るのではなく、直接取得出来るようにすることが望ましい def set_share_url tweet_url = URI.encode( "http://twitter.com/intent/tweet?" + "&text=" + "わたしのTwitter戦闘力は…【 #{params[:power]} 】!!!\nこの戦闘力から導き出されたキャラクターは…【 #{params[:character]} 】!!!\n" + "毎日測ってTwitter戦闘力を上げていこう!!!\n" + "#Scoutter\n#Twitter戦闘力\n" + "&url=" + "#{view_context.root_url}" ) redirect_to tweet_url end private def not_self_page redirect_to root_path if current_user&.id != params[:id].to_i end def set_period # デフォルトの期間は30日 @period = case params[:period] when 'week' then 7 when 'month' then 30 when 'quarter' then 90 when 'year' then 365 else 30 end end end
class ApplicationController < ActionController::Base protect_from_forgery private before_filter :set_locale def set_locale I18n.locale = extract_locale_from_subdomain || I18n.default_locale end def extract_locale_from_subdomain parsed_locale = request.subdomains.first I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil end def confirm_logged_in unless session[:staff_user_id] flash[:notice] = "Please log in." redirect_to(:action => 'login', :controller => 'staff_access') return false # halts the before filter else return true end end def confirm_customer_logged_in unless session[:customer_account_id] flash[:notice] = "Please log in." redirect_to(:action => 'login', :controller => 'customer_access') return false # halts the before filter else return true end end def current_agency @current_agency ||= Agency.find(session[:agency_id]) end def current_user current_user ||= StaffUser.find(session[:staff_user_id]) end rescue_from CanCan::AccessDenied do |exception| redirect_to :back, :alert => 'You do not have sufficient rights for that action.' end def find_program search_text = params[:search_text] @programs = current_agency.class_sessions.includes(:program).where("class_sessions.season_id = ? AND (programs.name like ? OR programs.code = ? OR programs.id = ?)", params[:season_id], "%#{search_text}%", search_text, params[:program_id]).collect @seasons = Season.find(:all) end def find_account if params[:account_id] @customers = Customer.includes(:account).where("accounts.id = ?", params[:account_id]) else search_text = params[:search_text] if search_text.respond_to?(:to_str) last_name = search_text else last_name = "" end if search_text.match /^\d+(?:-\d+)*$/ phone = search_text phone = phone.sub!(/-/, '') phone = phone.sub!(/./, '') #phone = phone.sub!(/(/, '') #phone = phone.sub!(/)/, '') else phone = "" end @customers = current_agency.customers.includes(:account).where("customers.last_name like ? OR accounts.home_phone = ?", "%#{last_name}%", phone).order("account_id", "last_name", "first_name") end end def headshot_custom_file_path file_name = "headshot_capture_#{rand(10000)}_#{Time.now.to_i}.jpg" File.join(Rails.root, 'public', 'headshots_images', file_name) end end
xml.instruct! xml.declare! :DOCTYPE, :yml_catalog, :SYSTEM, "shops.dtd" xml.yml_catalog( date: "#{Date.today.to_s} 0:01") do xml.shop do xml.name "Теплицы Медалак" xml.company "ИП Кузовлев Сергей Владимирович" xml.url "http://teplicy.medalak.ru/" xml.currencies do xml.currency(id:"RUR", rate: "1") end xml.categories do xml.category("Товары для дома и дачи", id: "54422") xml.category("Дача, сад и огород", id: "54495", parentId: "54422") xml.category("Товары для садоводства и озеленения", id: "60699", parentId: "54495") xml.category("Теплицы и парники", id: "55099", parentId: "60699") end xml.offers do products = Product.where(system_name: ['dvushka', 'treshka', 'strelka', 'strelka3']) products.each do |product| # каркас product.length.split(', ').each_with_index do |size, idx| xml.offer(id: "#{product.id}0#{idx}0", available: "true") do xml.url product_detail_url(product, option: "#{product.url_name(idx)}-#{product.id}-0-#{idx}-0") xml.price "#{product.full_base_price(idx)}" xml.currencyId "RUR" xml.categoryId "55099" xml.picture image_url(product.image) xml.picture image_url(product.image_2) xml.name "#{product.full_name(idx)}" xml.model "#{product.system_name}-#{product.id}-0-#{idx}-0" xml.vendor "Воля" xml.description "#{product.name}. ширина: #{product.width} м, высота: #{product.height} м, длина: #{size} м. Покрытие приобретается отдельно!" xml.age "0" xml.delivery "false" xml.pickup "true" xml.sales_notes "бесплатная доствка по Москве и московской области" xml.manufacturer_warranty "true" xml.country_of_origin "Россия" end end # каркас + полик product.sheets.each do |sheet| product.length.split(', ').each_with_index do |size, idx| xml.offer(id: "#{product.id}#{sheet.id}#{idx}0", available: "true") do xml.url product_detail_url(product, option: "#{product.url_name(idx, sheet)}-#{product.id}-#{sheet.id}-#{idx}-0") xml.price "#{product.full_product_price(idx, sheet)}" xml.currencyId "RUR" xml.categoryId "55099" xml.picture image_url(product.image) xml.picture image_url(product.image_2) xml.name "#{product.full_name(idx, sheet)}" xml.model "#{product.system_name}-#{product.id}-#{sheet.id}-#{idx}-0" xml.vendor "Воля" xml.description "#{product.name}. ширина: #{product.width} м, высота: #{product.height} м, длина: #{size} м. Покрытие: поликарбонат #{sheet.short_name}" xml.age "0" xml.delivery "false" xml.pickup "true" xml.sales_notes "бесплатная доствка по Москве и московской области" xml.manufacturer_warranty "true" xml.country_of_origin "Россия" end end end end end end end
class Player < ActiveRecord::Base attr_accessible :title belongs_to :game has_many :moves has_many :rounds, through: :moves validates_uniqueness_of :title, scope: 'game_id' after_initialize :set_defaults def set_defaults self.points = points.presence || 0 end end
require 'test_helper' class SocialMediaPostsControllerTest < ActionDispatch::IntegrationTest setup do @social_media_post = social_media_posts(:one) end test "should get index" do get social_media_posts_url, as: :json assert_response :success end test "should create social_media_post" do assert_difference('SocialMediaPost.count') do post social_media_posts_url, params: { social_media_post: { social_media_id: @social_media_post.social_medium_id, text_content: @social_media_post.text_content, topic_id: @social_media_post.topic_id } }, as: :json end assert_response 201 end test "should show social_media_post" do get social_media_post_url(@social_media_post), as: :json assert_response :success end test "should update social_media_post" do patch social_media_post_url(@social_media_post), params: { social_media_post: { social_medium_id: @social_media_post.social_media_id, text_content: @social_media_post.text_content, topic_id: @social_media_post.topic_id } }, as: :json assert_response 200 end test "should destroy social_media_post" do assert_difference('SocialMediaPost.count', -1) do delete social_media_post_url(@social_media_post), as: :json end assert_response 204 end end
# frozen_string_literal: true register_block { name 'block_1' byte_size 128 comment <<~COMMENT this is block_1. this block includes six registers. COMMENT register_file { name 'register_file_0' offset_address 0x00 register { name 'register_0' offset_address 0x00 comment [ 'this is register_0.', 'bit_field_0 is within this register.' ] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 8; type :rw; initial_value 0 } } register { name 'register_1' offset_address 0x04 bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 8; type :rw; initial_value 0 } } } register_file { name 'register_file_1' offset_address 0x10 register { name 'register_0' offset_address 0x00 size [2] type [ :indirect, 'register_file_0.register_0.bit_field_0', ['register_file_0.register_1.bit_field_0', 0] ] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 8; type :rw; initial_value 0 } } register { name 'register_1' offset_address 0x00 size [2] type [ :indirect, 'register_file_0.register_0.bit_field_0', ['register_file_0.register_1.bit_field_0', 1] ] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 8; type :rw; initial_value 0 } } } register_file { name 'register_file_2' offset_address 0x20 size [2, step: 32] register_file { name 'register_file_0' register { name 'register_0' offset_address 0x00 size [2, 3] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 4, sequence_size: 2; type :rw; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 4, sequence_size: 2; type :rwe; initial_value 0; reference 'register_file_0.register_0.bit_field_0' } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, width: 4, sequence_size: 2; type :rwl; initial_value 0; reference 'register_file_2.register_file_0.register_1.bit_field_0' } } register { name 'register_1' offset_address 0x18 bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 1, sequence_size: 2; type :rw; initial_value 0 } } } } }
module OauthCookieHelper def env_domain domain = ENV['COOKIE_DOMAIN'] || 'localhost' Rails.logger.error("trying to set cookie for #{domain}") domain == "localhost" ? :all : domain end def set_user_cookie(user) cookies[:so_auth] = { :value => user.id, :domain => env_domain } end def remove_user_cookie cookies.delete(:so_auth, :domain => env_domain) end end
require 'test/unit' require 'checkersGame.rb' class Test_checkersGame < Test::Unit::TestCase def test_Square_error #test a failure assert_raise(ArgumentError)\ {mysquare=CheckersGame::Square.new('*',false)} end def test_Square_initialization #test correct initialization assert_nothing_raised(ArgumentError)\ {mysquare=CheckersGame::Square.new(CheckersGame::Square::BLACK,false)} mysquare=CheckersGame::Square.new(CheckersGame::Square::BLACK,false) assert_equal(CheckersGame::Square::BLACK,mysquare.color) assert_equal(false,mysquare.kinged) assert_equal('Black',mysquare.to_s) assert_equal('b',mysquare.to_c) end #test test to_s def test_to_s mygame=CheckersGame.new assert_not_nil(mygame,'Failed to instantiate a game') assert_equal(\ " +---+---+---+---+---+---+---+---+\n"+\ "h | | r | | r | | r | | r | \n"+\ " +---+---+---+---+---+---+---+---+\n"+\ "g | r | | r | | r | | r | | \n"+\ " +---+---+---+---+---+---+---+---+\n"+\ "f | | r | | r | | r | | r | \n"+\ " +---+---+---+---+---+---+---+---+\n"+\ "e | . | | . | | . | | . | | \n"+\ " +---+---+---+---+---+---+---+---+\n"+\ "d | | . | | . | | . | | . | \n"+\ " +---+---+---+---+---+---+---+---+\n"+\ "c | b | | b | | b | | b | | \n"+\ " +---+---+---+---+---+---+---+---+\n"+\ "b | | b | | b | | b | | b | \n"+\ " +---+---+---+---+---+---+---+---+\n"+\ "a | b | | b | | b | | b | | \n"+\ " +---+---+---+---+---+---+---+---+\n"+\ " 1 2 3 4 5 6 7 8 \n",mygame.to_s) end #test [] operator. def test_indexing_errors mygame=CheckersGame.new #test incorrect coordinates labels #first label illegal assert_raise(IndexError){mygame['*','2']} #second label illegal assert_raise(IndexError){mygame['a','*']} #both labels illegal assert_raise(IndexError){mygame['*','*']} end def test_indexing #test each square mygame=CheckersGame.new b=CheckersGame::Square::BLACK r=CheckersGame::Square::RED x=CheckersGame::Square::BLANK init_gameboard=[ [b, nil, b, nil, b, nil, b, nil], \ [nil, b, nil, b, nil, b, nil, b], \ [b, nil, b, nil, b, nil, b, nil], \ [nil, x, nil, x, nil, x, nil, x], \ [x, nil, x, nil, x, nil, x, nil], \ [nil, r, nil, r, nil, r, nil, r], \ [r, nil, r, nil, r, nil, r, nil], \ [nil, r, nil, r, nil, r, nil, r]] row_labels=CheckersGame::ROW_LOOKUP.keys.sort column_labels=CheckersGame::COLUMN_LOOKUP.keys.sort for i in 0...8 for j in 0...8 if (init_gameboard[i][j]) assert_equal(init_gameboard[i][j],mygame[row_labels[i],column_labels[j]].to_c) else assert_nil(mygame[row_labels[i],column_labels[j]]) end end end end def test_equality assert_equal(CheckersGame.new,CheckersGame.new) end def test_inequality mygame=CheckersGame.new mygame.move('c3','d4') assert_not_equal(CheckersGame.new,mygame) end def test_remove assert_equal(CheckersGame::Square::BLANK,CheckersGame.new.remove('c','3')['c','3'].color) end def test_place assert_equal(CheckersGame::Square::RED,\ CheckersGame.new.place('c','3',CheckersGame::Square::RED,false)['c','3'].color) end #Since remove is just a call to place, this tests errors for both functions def test_remove_errors #test error case assert_raise(IndexError){CheckersGame.new.remove('c','*')} assert_raise(IndexError){CheckersGame.new.remove('*','3')} end def test_first_legal_moves_black black_columns=%w[1 3 5 7] #Test some initial moves for Black for i in 0...4 mygame=CheckersGame.new assert_equal(\ CheckersGame.new.remove('c',black_columns[i]).\ place('d',String(Integer(black_columns[i])+1),\ CheckersGame::Square::BLACK,false).toggle_turn,\ mygame.move('c'+black_columns[i],'d'+String(Integer(black_columns[i])+1))) end end #Test some counter moves for Red for one of the black openings def test_first_legal_moves_red red_columns=%w[2 4 6 8] for i in 0...4 mygame=CheckersGame.new mygame.move('c3','d4') #Game now looks like: # +---+---+---+---+---+---+---+---+ #h | | r | | r | | r | | r | # +---+---+---+---+---+---+---+---+ #g | r | | r | | r | | r | | # +---+---+---+---+---+---+---+---+ #f | | r | | r | | r | | r | # +---+---+---+---+---+---+---+---+ #e | . | | . | | . | | . | | # +---+---+---+---+---+---+---+---+ #d | | . | | b | | . | | . | # +---+---+---+---+---+---+---+---+ #c | b | | . | | b | | b | | # +---+---+---+---+---+---+---+---+ #b | | b | | b | | b | | b | # +---+---+---+---+---+---+---+---+ #a | b | | b | | b | | b | | # +---+---+---+---+---+---+---+---+ # 1 2 3 4 5 6 7 8 assert_equal(\ CheckersGame.new.move('c3','d4').remove('f',red_columns[i]).\ place('e',String(Integer(red_columns[i])-1),\ CheckersGame::Square::RED,false).toggle_turn,\ mygame.move('f'+red_columns[i],'e'+String(Integer(red_columns[i])-1))) end end #test coordinate legality testing def test_erroneous_moves_IndexError_1 #neither illegal assert_nothing_raised(IndexError,ArgumentError){CheckersGame.new.move('c1','d2')} end def test_erroneous_moves_IndexError_2 mygame=CheckersGame.new assert_raise(IndexError){mygame.move('*1','d2')} assert_equal(CheckersGame.new,mygame) end def test_erroneous_moves_IndexError_3 mygame=CheckersGame.new assert_raise(IndexError){mygame.move('c*','d2')} assert_equal(CheckersGame.new,mygame) end def test_erroneous_moves_IndexError_4 mygame=CheckersGame.new assert_raise(IndexError){mygame.move('c1','*2')} assert_equal(CheckersGame.new(),mygame) end def test_erroneous_moves_IndexError_5 mygame=CheckersGame.new assert_raise(IndexError){mygame.move('c1','d*')} assert_equal(CheckersGame.new,mygame) end def test_erroneous_moves_IndexError_6 #both illegal mygame=CheckersGame.new assert_raise(IndexError){mygame.move('c*','d*')} assert_equal(CheckersGame.new,mygame) end def test_erroneous_moves_IndexError_7 #test testing for playing only on black squares #From coordinates: mygame=CheckersGame.new for i in 1..8 if((i-1)%2==1) assert_raise(IndexError){mygame.move('c'+String(i),'d4')} assert_equal(CheckersGame.new,mygame) end end end def test_erroneous_moves_IndexError_8 #test testing for playing only on black squares #To coordinates: for i in 1..8 mygame=CheckersGame.new if(i%2==1) assert_raise(IndexError){mygame.move('c1','d'+String(i))} assert_equal(CheckersGame.new,mygame) end end end def test_erroneous_moves_IndexError_9 #test testing for playing only on black squares #Both coordinates: for i in 1..7 mygame=CheckersGame.new if((i-1)%2==1) assert_raise(IndexError){mygame.move('c'+String(i),'d'+String(i+1))} assert_equal(CheckersGame.new,mygame) end end end def test_erroneous_moves_ArgumentError_1 #Test testing that From coordinates contain player's piece #Contains correct color mygame=CheckersGame.new assert_nothing_raised(ArgumentError){mygame.move('c5','d6')} assert_equal(CheckersGame.new.remove('c','5').\ place('d','6',CheckersGame::Square::BLACK,false).toggle_turn,mygame) end def test_erroneous_moves_ArgumentError_2 #Test testing that From coordinates contain player's piece #Contains other player's color mygame=CheckersGame.new assert_raise(ArgumentError){mygame.move('f4','e5')} assert_equal(CheckersGame.new,mygame) end def test_erroneous_moves_ArgumentError_3 #Test testing that From coordinates contain player's piece #Square is blank mygame=CheckersGame.new assert_raise(ArgumentError){mygame.move('d6','e7')} assert_equal(CheckersGame.new,mygame) end def test_erroneous_moves_ArgumentError_4 #Test testing that To coordinates are unoccupied #Unoccupied case: mygame=CheckersGame.new assert_nothing_raised(ArgumentError){mygame.move('c1','d2')} assert_nothing_raised(ArgumentError){mygame.move('f4','e3')} end def test_erroneous_moves_ArgumentError_5 mygame=CheckersGame.new.move('c1','d2').move('f4','e3') #Trying to move to a space occupied by opponent assert_raise(ArgumentError){mygame.move('d2','e3')} end def test_erroneous_moves_ArgumentError_6 mygame=CheckersGame.new.move('c1','d2').move('f4','e3') #Trying to move to a space occupied by self assert_raise(ArgumentError){mygame.move('c3','d2')} end def test_erroneous_moves_illegal_move #Test testing move legality #We've already had plenty of positive cases go through #Here are some negative cases mygame=CheckersGame.new assert_raise(ArgumentError){mygame.move('c1','e3')} assert_raise(ArgumentError){mygame.move('c3','d6')} assert_raise(ArgumentError){mygame.move('c5','e5')} assert_raise(ArgumentError){mygame.move('c7','d2')} end #Test detection of a single capture move def test_single_capture mygame=CheckersGame.new mygame.move('c3','d4').move('f6','e5') # +---+---+---+---+---+---+---+---+ # h | | r | | r | | r | | r | # +---+---+---+---+---+---+---+---+ # g | r | | r | | r | | r | | # +---+---+---+---+---+---+---+---+ # f | | r | | r | | . | | r | # +---+---+---+---+---+---+---+---+ # e | . | | . | | r | | . | | # +---+---+---+---+---+---+---+---+ # d | | . | | b | | . | | . | # +---+---+---+---+---+---+---+---+ # c | b | | . | | b | | b | | # +---+---+---+---+---+---+---+---+ # b | | b | | b | | b | | b | # +---+---+---+---+---+---+---+---+ # a | b | | b | | b | | b | | # +---+---+---+---+---+---+---+---+ # 1 2 3 4 5 6 7 8 mygame.move('d4','f6') #assert_equal(CheckersGame.new.remove('c','3').place('f','6',CheckersGame::Square::BLACK,false).toggle_turn,mygame) end end
json.array!(@modulo_remitentes) do |modulo_remitente| json.extract! modulo_remitente, :id, :paciente_id, :nombre, :nombre_entidad, :tipo_entidad, :cargo, :ciudad, :departamento, :direccion, :telefono, :email, :fecha_solicitud json.url modulo_remitente_url(modulo_remitente, format: :json) end
class Picture < ActiveRecord::Base belongs_to :Post has_attached_file :image, :storage => :dropbox, :dropbox_credentials => "#{Rails.root}/config/dropbox_config.yml", :dropbox_options => { :path => proc { |style| "#{style}/#{id}_#{image.original_filename}"}, :unique_filename => true } validates_attachment_content_type :image, :content_type => [ "image/png", "image/jpeg", "image/gif", "application/pdf","application/ppt","application/pptx","application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/msword","application/zip", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "text/plain"] validates_attachment :image, :size => { :in => 0..1000.megabytes } end
#!/bin/env ruby require 'bundler/setup' require '../../config/environment.rb' require 'rest-client' require '../config.rb' require 'logger' require 'rest-client' PROCESSOR_SCHEDY_URL = "http://schedy-server:3000" @log = Logger.new(STDOUT) def lock_resource(params) @task_id = params["task_id"] @status = params["status"] @log.info "PCAP postprocessing for task #{@task_id} has started." @log.info "Prepared payload : #{payload.to_s}" processor_request_response = RestClient.post(processor_endpoint,payload) @log.info "Requested an execution for artifacts. Result: #{processor_request_response.code}." end task_id = ARGV[0] status = ARGV[1] FILTER_REGEXP = Regexp.new /pcap/ params = Hash.new("") @log.info "Received event from Task ID: #{task_id}, Status: #{status}" params["task_id"] = task_id params["status"] = status params["filter_regexp"] = FILTER_REGEXP params["proxy"] = "https://http-proxy" @log.info "Sending request: #{params.to_s}" pcap_post_processing(params)
# # Cookbook Name:: nginx # Recipe:: tcp_proxy # # Author:: Luka Zakrajsek (<luka@koofr.net>) # # Copyright 2012, Koofr # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # nginx_version = node[:nginx][:version] bash "add_tcp_proxy_module" do cwd Chef::Config[:file_cache_path] code <<-EOH if [[ -d "nginx_tcp_proxy_module" ]]; then cd nginx_tcp_proxy_module && git pull cd #{Chef::Config[:file_cache_path]} else env GIT_SSL_NO_VERIFY=true git clone https://github.com/yaoweibin/nginx_tcp_proxy_module.git fi cd nginx-#{nginx_version} && patch -p1 < ../nginx_tcp_proxy_module/tcp.patch EOH end node.run_state['nginx_configure_flags'] = node.run_state['nginx_configure_flags'] | ["--add-module=../nginx_tcp_proxy_module"]
class Client < ActiveRecord::Base def self.search(query) if query find(:all, :conditions => ['full_name LIKE ?', "%#{query}%"]).first else nil end end end
# https://github.com/kylecronin/boggle-ruby/blob/master/board.rb class Board def initialize(state) @xmax = state.size @ymax = state[0].size state.each do |row| raise "Board rows are of varying lengths" if row.size != @ymax end @state = state end def [](a, b) @state[a][b] end def each() for x in 0...@xmax for y in 0...@ymax yield x, y end end end def neighbor_iter(x, y) temp = @state[x][y] @state[x][y] = nil xrange = ([x-1, 0].max)..([x+1, @xmax-1].min) yrange = ([y-1, 0].max)..([y+1, @ymax-1].min) for i in xrange for j in yrange yield i, j if @state[i][j] end end @state[x][y] = temp end end
class Crmcomment < ActiveRecord::Base unloadable belongs_to :commentable, polymorphic: true belongs_to :user validates :commentable, presence: true validates :user, presence: true validates :dtime, :comment, presence: true def self.to_csv(items) CSV.generate(col_sep: Setting.plugin_redmine_crm['csv_delimiter']) do |csv| csv << column_names items.each do |item| csv << item.attributes.values_at(*column_names) end end end def self.import(file) CSV.foreach(file.path, headers: true, encoding: "#{Setting.plugin_redmine_crm['csv_encoding']}:utf8", col_sep: Setting.plugin_redmine_crm['csv_delimiter']) do |row| crm_comment = find_by_id(row['id']) || new crm_comment.attributes = row.to_hash crm_comment.id = row['id'] crm_comment.save end end end
require 'active_support/concern' module TeamValidations extend ActiveSupport::Concern included do validates_presence_of :name validates_presence_of :slug validates_format_of :slug, with: /\A[[:alnum:]-]+\z/, message: :slug_format validates :slug, length: { in: 4..63 } validates :slug, uniqueness: true validate :slug_is_not_reserved validates :logo, size: true validate :slack_webhook_format validate :language_format validate :languages_format validate :fieldsets_format validate :list_columns_format end end
class Glow < FPM::Cookery::Recipe description 'Render markdown on the CLI, with pizzazz!' name 'glow' version '0.2.0' revision '1' homepage 'https://github.com/charmbracelet/glow' source "https://github.com/charmbracelet/glow/releases/download/v#{version}/glow_#{version}_linux_x86_64.tar.gz" sha256 'ea3b158c1c3f3f9ce63a701817ffc9023bbcf2c5375f21a5890ddda7d57554c5' def build end def install bin.install 'glow' end end
class Mechanic attr_reader :name, :specialty @@all = [] def initialize(name, specialty) @name = name @specialty = specialty @@all << self end def self.all @@all end def cars Car.all.select { |mech| mech.mechanic == self } end def car_owners cars.map do |car| car.car_owner end end def list_of_names_of_car_owners_who_have_same_mechanic car_owners.map { |car| puts car.name } #binding.pry end end
class Teacher < User #has_and_belongs_to_many :courses, :join_table => 'users_courses', :foreign_key => 'user_id', :uniq => true #has_many :users, :through => :courses, :uniq => true, :source => :user def students my_students = [] courses.each do |course| my_students += course.students end my_students.uniq end end
require 'rest-client' require 'json' require 'addressable/uri' require 'addressable/template' require 'nokogiri' require 'sanitize' class QueryProcessor def self.validate(name, value) return !!(value =~ /^[\w ]+$/) if name == "query" return true end def self.transform(name, value) return value.gsub(/ /, "+") if name == "query" return value end end def get_key(api_filename) File.readlines(api_filename).first.chomp end def query_uri(address_str) uri = Addressable::Template.new( "http://maps.googleapis.com/maps/api/geocode/json?address={query}&sensor=false" ).expand( {"query" => address_str}, QueryProcessor ).to_str end def get_coordinates(address) uri = query_uri(address) response = JSON.parse(RestClient.get(uri)) response["results"].first["geometry"]["location"].values end def search_nearby(lat, long, types="food", keyword="icecream") uri = Addressable::URI.new( scheme: "https", host: "maps.googleapis.com", path: "maps/api/place/nearbysearch/json", query_values: {location: "#{lat},#{long}", radius: 500, types: "#{types}", sensor: "false", keyword: "#{keyword}", key: get_key('APIkey.txt')}).display_uri.to_s results = JSON.parse(RestClient.get(uri))["results"] end def display_location(index, location_hash) puts "[#{index}] #{location_hash['name']}" puts "Rating: #{location_hash['rating']}" unless location_hash['rating'].nil? puts location_hash['vicinity'] puts "" end def get_directions(origin, dest) uri = Addressable::URI.new( scheme: "https", host: "maps.googleapis.com", path: "/maps/api/directions/json", query_values: {origin: "#{origin[0]},#{origin[1]}", destination: "#{dest[0]},#{dest[1]}", sensor: "false"}).display_uri.to_s legs = JSON.parse(RestClient.get(uri))["routes"].first["legs"] puts "DRIVING DIRECTIONS" legs.each do |leg| leg["steps"].each do |step| puts Nokogiri::HTML(step["html_instructions"]).text end end end def main print "Enter you address > " address = gets.chomp.sub(",", "") curr_lat, curr_long = get_coordinates(address) search_results = search_nearby(curr_lat, curr_long) search_results[0..9].each_with_index do |result, i| display_location(i+1, result) end dest_index = nil until (0..9).include?(dest_index) print "Enter the number of your destination > " dest_index = gets.chomp.to_i - 1 end end_lat, end_long = search_results[dest_index]["geometry"]["location"].values get_directions([curr_lat, curr_long], [end_lat, end_long]) end main
require 'rails_helper' describe EquipmentInfo do describe '#create' do context 'can save' do it 'is valid with all items' do expect(build(:equipment_info)).to be_valid end it 'is valid without a building_name' do expect(build(:equipment_info, building_name: nil)).to be_valid end end context 'can not save' do it 'is invalid without a postal_code' do equipment_info = build(:equipment_info, postal_code: nil) equipment_info.valid? expect(equipment_info.errors[:postal_code]).to include('郵便番号を入力してください。') end it 'is invalid with a postal_code that has more than 7 digits' do equipment_info = build(:equipment_info, postal_code: '12345678') equipment_info.valid? expect(equipment_info.errors[:postal_code]).to include('郵便番号は不正な値です。') end it 'is invalid with a postal_code that has less than 7 digits' do equipment_info = build(:equipment_info, postal_code: '123456') equipment_info.valid? expect(equipment_info.errors[:postal_code]).to include('郵便番号は不正な値です。') end it 'is invalid without a prefecture' do equipment_info = build(:equipment_info, prefecture: nil) equipment_info.valid? expect(equipment_info.errors[:prefecture]).to include('都道府県を入力してください。') end it 'is invalid without a city_name' do equipment_info = build(:equipment_info, city_name: nil) equipment_info.valid? expect(equipment_info.errors[:city_name]).to include('市区町村を入力してください。') end it 'is invalid without a street_name' do equipment_info = build(:equipment_info, street_name: nil) equipment_info.valid? expect(equipment_info.errors[:street_name]).to include('町名・番地を入力してください。') end it 'is invalid without a latitude' do expect(build(:equipment_info, latitude: nil)).not_to be_valid end it 'is invalid without a longitude' do expect(build(:equipment_info, longitude: nil)).not_to be_valid end it 'is invalid without an access' do equipment_info = build(:equipment_info, access: nil) equipment_info.valid? expect(equipment_info.errors[:access]).to include('アクセスを入力してください。') end it 'is invalid without a phone_number' do equipment_info = build(:equipment_info, phone_number: nil) equipment_info.valid? expect(equipment_info.errors[:phone_number]).to include('電話番号を入力してください。') end it 'is invalid with a phone_number that has less than 10 digits' do equipment_info = build(:equipment_info, phone_number: '012345678') equipment_info.valid? expect(equipment_info.errors[:phone_number]).to include('電話番号は不正な値です。') end it 'is invalid with a phone_number that has more than 11 digits' do equipment_info = build(:equipment_info, phone_number: '012345678901') equipment_info.valid? expect(equipment_info.errors[:phone_number]).to include('電話番号は不正な値です。') end it 'is invalid without an equipment_type' do equipment_info = build(:equipment_info, equipment_type: nil) equipment_info.valid? expect(equipment_info.errors[:equipment_type]).to include('施設の種類を入力してください。') end end end end
require File.dirname(__FILE__) + '/text_analyzer.rb' =begin Your text analyzer will provide the following basic statistics: Character count Character count (excluding spaces) Line count Word count Sentence count Paragraph count Average number of words per sentence Average number of sentences per paragraph =end =begin doctest: TextAnalyzer test suite >> ta = TextAnalyzer.new() >> ta.analyze( 'text.txt' ) => {:chars=>6044, :chars_no_spaces=>5055, :lines=>121, :words=>1114, :sentences=>44, :paragraphs=>18, :wps=>25.318181818181817, :spp=>2.4444444444444446} =end
# frozen_string_literal: true RSpec.describe Jsonschema::Generator::Draft07 do subject(:generator) { described_class.new(json).call } let(:json) { {}.to_json } describe 'Success' do context 'when json is array' do let(:json) do [ { id: '1', name: 'John', roles: [ { id: '1000', name: 'admin', }, ], }, { id: '2', name: 'Doe', roles: [ { id: '1111', name: 'moderator', }, ], }, ].to_json end let(:expected_schema) do { 'title' => 'Root', 'type' => 'array', 'minItems' => 2, 'maxItems' => 2, 'items' => { 'type' => 'object', 'properties' => { 'id' => { 'type' => 'string', }, 'name' => { 'type' => 'string', }, 'roles' => { 'type' => 'array', 'minItems' => 1, 'maxItems' => 1, 'items' => { 'type' => 'object', 'properties' => { 'id' => { 'type' => 'string', }, 'name' => { 'type' => 'string', }, }, 'required' => %w[id name], }, }, }, 'required' => %w[id name roles], }, } end it 'generates schema correctly' do expect(generator).to match expected_schema end end context 'with simple case' do let(:json) do { first: 'first', second: 2, third: 'third', }.to_json end let(:expected_schema) do { 'title' => 'Root', 'type' => 'object', 'properties' => { 'first' => { 'type' => 'string', }, 'second' => { 'type' => 'integer', }, 'third' => { 'type' => 'string', }, }, 'required' => %w[first second third], } end it 'generates schema correctly' do expect(generator).to match expected_schema end end context 'with nested hash' do let(:json) do { nested1: { nested2: { nested3: { nested4: { nested5: '1', }, }, }, }, }.to_json end let(:expected_schema) do { 'title' => 'Root', 'type' => 'object', 'required' => %w[nested1], 'properties' => { 'nested1' => { 'type' => 'object', 'required' => %w[nested2], 'properties' => { 'nested2' => { 'type' => 'object', 'required' => %w[nested3], 'properties' => { 'nested3' => { 'type' => 'object', 'required' => %w[nested4], 'properties' => { 'nested4' => { 'type' => 'object', 'required' => %w[nested5], 'properties' => { 'nested5' => { 'type' => 'string', }, }, }, }, }, }, }, }, }, }, } end it 'generates schema correctly' do expect(generator).to match expected_schema end end context 'with complex case' do let(:json) do { _id: '5c4774c4192e39a7585275fd', index: 0, guid: 'fb233eda-9a74-446f-865d-6901e5da117a', isActive: true, balance: '$1,524.98', picture: 'http://placehold.it/32x32', age: 28, eyeColor: 'green', name: 'Perkins Harvey', gender: 'male', company: 'KOFFEE', email: 'perkinsharvey@koffee.com', phone: '+1 (841) 535-2493', address: '241 Madison Street, Templeton, Virginia, 1537', about: 'Incididunt in consequat est aliquip nulla et. '\ 'Eu laborum dolore magna et amet sint ad nulla ut '\ 'eu nostrud. Anim proident non officia ipsum aliqua '\ 'officia ex deserunt. Anim enim reprehenderit proident '\ 'consequat. Occaecat id anim nulla ut cupidatat deserunt '\ 'eu Lorem. Mollit ea nisi amet magna incididunt magna tempor '\ "duis in consectetur Lorem.\r\n", registered: '2018-07-06T04:30:17 -03:00', latitude: 13.765856, longitude: -9.772866, tags: %w[ est labore consectetur proident officia sit duis ], friends: [ { id: 0, name: 'Brandy Taylor', }, { id: 1, name: 'Toni Francis', }, { id: 2, name: 'Frieda Owen', }, ], nested: { object: { in: { other: { object: '1', }, }, }, }, greeting: 'Hello, Perkins Harvey! You have 2 unread messages.', favoriteFruit: 'apple', }.to_json end let(:expected_schema) do { 'title' => 'Root', 'type' => 'object', 'required' => %w[ _id index guid isActive balance picture age eyeColor name gender company email phone address about registered latitude longitude tags friends nested greeting favoriteFruit ], 'properties' => { '_id' => { 'type' => 'string', }, 'index' => { 'type' => 'integer', }, 'guid' => { 'type' => 'string', }, 'isActive' => { 'type' => 'boolean', }, 'balance' => { 'type' => 'string', }, 'picture' => { 'type' => 'string', }, 'age' => { 'type' => 'integer', }, 'eyeColor' => { 'type' => 'string', }, 'friends' => { 'type' => 'array', 'minItems' => 3, 'maxItems' => 3, 'items' => { 'type' => 'object', 'required' => %w[id name], 'properties' => { 'id' => { 'type' => 'integer', }, 'name' => { 'type' => 'string', }, }, }, }, 'name' => { 'type' => 'string', }, 'gender' => { 'type' => 'string', }, 'company' => { 'type' => 'string', }, 'email' => { 'type' => 'string', }, 'phone' => { 'type' => 'string', }, 'address' => { 'type' => 'string', }, 'about' => { 'type' => 'string', }, 'registered' => { 'type' => 'string', }, 'latitude' => { 'type' => 'number', }, 'longitude' => { 'type' => 'number', }, 'tags' => { 'type' => 'array', 'minItems' => 7, 'maxItems' => 7, 'items' => { 'type' => 'string', }, }, 'favoriteFruit' => { 'type' => 'string', }, 'greeting' => { 'type' => 'string', }, 'nested' => { 'type' => 'object', 'required' => ['object'], 'properties' => { 'object' => { 'required' => ['in'], 'type' => 'object', 'properties' => { 'in' => { 'required' => ['other'], 'type' => 'object', 'properties' => { 'other' => { 'required' => ['object'], 'type' => 'object', 'properties' => { 'object' => { 'type' => 'string', }, }, }, }, }, }, }, }, }, }, } end it 'generates schema correctly' do expect(generator).to match expected_schema end end end describe 'Fail' do context 'when input is not json' do let(:json) { { key: :value } } it 'raises error' do expect { generator } .to raise_error Jsonschema::Generator::Error, 'Invalid Input. JSON expected' end end end end
class VoteOption < ActiveRecord::Base has_many :votes, dependent: :destroy has_many :users, through: :votes belongs_to :poll validates :title, presence: true end
class Service < ApplicationRecord belongs_to :barber, class_name: 'User' has_many :appointments validates :title, :duration, :price, presence: true validates :title, length: { maximum: 150 } end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception # need to include the helper manually for a controller # this gives us access to all session helpers such as logged_in? include SessionsHelper end
module Ticketing module Invoice class EntityRepository < ::BaseRepository def paids dataset.where(:payment_ids.ne => []) end private def entity ::Ticketing::Invoice::Entity end end end end
class MoviesController < ApplicationController before_action :retrieve_movie, only: %i[show edit update destroy] def index redirect_to root_path end def show end def new @movie = Movie.new authorize @movie, :create? end def create @movie = Movie.new(movie_params.merge(:user_id => current_user.id)) authorize @movie, :create? if @movie.save redirect_to @movie else flash.now[:alert] = 'Could not create movie. Please try again.' render 'new' end end def update authorize @movie, :update? if @movie.update(movie_params) redirect_to @movie else flash.now[:alert] = 'Could not update movie. Please try again.' render 'edit' end end def edit authorize @movie, :update? end def destroy authorize @movie, :destroy? @movie.destroy redirect_to root_path end private def movie_params params.require(:movie).permit(:title, :text, :category_id) end def movie_param_name :id end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the 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) CmnPropertyType.find_or_create_by( title:'住所・郵便番号', description: '都道府県、住所、郵便番号はaddressモデルからの取得とする', property_datatype: :class_id, data_class: 'address' ) CmnPropertyType.find_or_create_by( title:'生年月日', description: '誕生日の場合、年については0000', property_datatype: :date ) privGroup=PrivilegeGroup.find_or_create_by( title: 'system admin', descriptions: 'サイト管理スタッフ' ) ControlPrivilege.find_or_create_by( privilege_group_id: privGroup.id, controller_name: 'home', privilege_type: :allow_all ) privGroup=PrivilegeGroup.find_or_create_by( title: 'biz admin', descriptions: '企業ユーザー' ) ControlPrivilege.find_or_create_by( privilege_group_id: privGroup.id, controller_name: 'home', privilege_type: :allow_all ) privGroup=PrivilegeGroup.find_or_create_by( title: 'usr', descriptions: 'エンジニア' ) ControlPrivilege.find_or_create_by( privilege_group_id: privGroup.id, controller_name: 'home', privilege_type: :allow_all ) Dir.glob("#{Rails.root}/db/seeds/*.yml").each do |yaml_filename| puts yaml_filename targetmodel=File.basename(yaml_filename,".yml").classify.constantize ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{targetmodel.table_name} CASCADE") File.open(yaml_filename) do |load_target_yaml| records = YAML.load(load_target_yaml) records.each do |record| puts record if record.has_key? "sql" ActiveRecord::Base.connection.execute(record["sql"]) else model = targetmodel.create(record) model.save! end end end end
require "./node" class BinaryTree def initialize(data=nil) unless data.nil? build_tree(data) else @root = nil end end # inserts all of the given data into this tree def build_tree(data) @root = Node.new(data[0]) data.shift data.each { |value| @root.insert(value) } end def breadth_first_search(value) search(value) { |list| list.shift } end def depth_first_search(value) search(value) { |list| list.pop } end def dfs_rec(value) dfs_rec_help(value, @root) end def print_tree unless @root.nil? puts @root.to_s else puts "nil" end end private # searches the tree in the order, according to the given block def search(value, &block) work_list = [@root] while !work_list.empty? curr_node = yield(work_list) unless curr_node.value == value work_list << curr_node.left_child unless curr_node.left_child.nil? work_list << curr_node.right_child unless curr_node.right_child.nil? else return curr_node end end return nil end def dfs_rec_help(value, node) if node.nil? || node.value == value return node else result = dfs_rec_help(value, node.right_child) result = dfs_rec_help(value, node.left_child) if result.nil? return result end end end
# frozen_string_literal: true class Product < ApplicationRecord scope :producible, -> { where(producible: true) } scope :orderable, -> { where(orderable: true) } has_many :inventory_lines, dependent: :destroy has_many :product_providers, dependent: :destroy has_many :external_entities, through: :product_providers accepts_nested_attributes_for :product_providers, allow_destroy: true has_many :product_recipes, dependent: :destroy has_one_attached :image def credit_to_line(inventory_line, inv_map) if product_recipes.any? product_recipes.each { |r| r.credit_to_line(inventory_line, inv_map) } elsif inv_map.key?(id) credit_quantity = [inventory_line.quantity_remaining, inv_map[id]].min inv_map[id] -= credit_quantity inventory_line.quantity_present += credit_quantity inventory_line.save! end end def debit_from_line(inventory_line, inv_map) if product_recipes.any? product_recipes.each { |r| r.debit_from_line(inventory_line, inv_map) } elsif inv_map.key?(id) debit_quantity = [inventory_line.quantity_present, inv_map[id]].min inv_map[id] -= debit_quantity inventory_line.quantity_present -= debit_quantity inventory_line.save! end end end
class RemoveContentsFromRssEntries < ActiveRecord::Migration def change remove_column :rss_entries, :contents end end
module ApplicationHelper class NoParagraphRenderer < ::Redcarpet::Render::XHTML def paragraph(text) text end end def self.image require 'redcarpet' AutoHtml.add_filter(:image).with({:alt => ''}) do |text, options| r = Redcarpet::Markdown.new(NoParagraphRenderer) alt = options[:alt] options[:proxy] ||= "" text.gsub(/(?<!src=")https?:\/\/.+?\.(jpg|jpeg|bmp|gif|png)(\?\S+)?/i) do |match| r.render("![#{alt}](#{options[:proxy]}#{match})") end end end def self.youtube AutoHtml.add_filter(:youtube).with(:width => 420, :height => 315, :frameborder => 0, :wmode => nil, :autoplay => false, :hide_related => false) do |text, options| regex = /(https?:\/\/)?(www.)?(youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/watch\?feature=player_embedded&v=)([A-Za-z0-9_-]*)(\&\S+)?(\?\S+)?/ text.gsub(regex) do youtube_id = $4 width = options[:width] height = options[:height] frameborder = options[:frameborder] wmode = options[:wmode] autoplay = options[:autoplay] hide_related = options[:hide_related] src = "//www.youtube.com/embed/#{youtube_id}" params = [] params << "wmode=#{wmode}" if wmode params << "autoplay=1" if autoplay params << "rel=0" if hide_related src += "?#{params.join '&'}" unless params.empty? %{<div class="video youtube"><iframe width="#{width}" height="#{height}" src="#{src}" frameborder="#{frameborder}" allowfullscreen></iframe></div>} end end end def self.simple_format AutoHtml.add_filter(:simple_format).with({}) do |text, html_options| require 'action_view' args = [text, {}, {:sanitize => false}] begin ActionView::Base.new.simple_format(*args) rescue ArgumentError # Rails 2 support args.pop retry end end end end
# frozen_string_literal: true require 'rake' require 'faker' require 'sendgrid-ruby' require 'sinatra/activerecord' require 'sinatra/activerecord/rake' require_relative './lib/jobs/topic_job' # require the model(s) Dir.glob(File .join(File.expand_path(__dir__), 'db', 'models', '*.rb')).each { |file| require file } namespace :micro_learn do desc 'Setup MicroLearn App Database.' task setup_database: %w[db:migrate db:seed] desc 'Send Out Topics To Enroled Users' task :send_topic do send_user_courses = TopicJob.new send_user_courses.start end end
class Company < ActiveRecord::Base has_many :contacts, inverse_of: :company validates :name, uniqueness: true, presence: true end
# frozen_string_literal: true module AgileAllianceService def self.check_member(email) url = "#{Figaro.env.agile_alliance_api_host}/check_member/#{email}" response = HTTParty.get(url, headers: { 'AUTHORIZATION' => Figaro.env.agile_alliance_api_token }) response.present? && JSON.parse(response.body)['member'] rescue JSON::ParserError, URI::InvalidURIError false end end
require 'spec_helper' describe 'consul_template' do RSpec.configure do |c| c.default_facts = { :architecture => 'x86_64', :operatingsystem => 'Ubuntu', :osfamily => 'Debian', :operatingsystemrelease => '10.04', :operatingsystemmajrelease => '10.04', :kernel => 'Linux', :lsbdistrelease => '10.04', :staging_http_get => 'curl', :path => '/usr/bin:/bin:/usr/sbin:/sbin', } end # Installation Stuff context 'On an unsupported arch' do let(:facts) {{ :architecture => 'bogus' }} let(:params) {{ :install_method => 'package' }} it { expect { should compile }.to raise_error(/Unsupported kernel architecture:/) } end context 'by default, location should be localhost' do it { should contain_file('consul-template config.json') \ .with_content(/"consul":"localhost:8500"/) \ .with( 'ensure' => 'present', 'path' => '/etc/consul-template/config/config.json' ) } end context 'directories should be created' do it { should contain_file('/etc/consul-template').with(:ensure => 'directory') } it { should contain_file('/etc/consul-template/config').with(:ensure => 'directory') } it { should contain_file('/etc/consul-template/templates').with(:ensure => 'directory') } end context 'When not specifying whether to purge config' do it { should contain_file('/etc/consul-template').with(:purge => true,:recurse => true) } it { should contain_file('/etc/consul-template/templates').with(:purge => true,:recurse => true) } end context 'When passing a non-bool as purge_config_dir' do let(:params) {{ :purge_config_dir => 'hello' }} it { expect { should compile }.to raise_error(/is not a boolean/) } end context 'When passing a non-bool as manage_service' do let(:params) {{ :manage_service => 'hello' }} it { expect { should compile }.to raise_error(/is not a boolean/) } end context 'When disable config purging' do let(:params) {{ :purge_config_dir => false }} it { should contain_class('consul_template::config').with(:purge => false) } end context 'consul_template::config should notify consul_template::service' do it { should contain_class('consul_template::config').that_notifies(['Class[consul_template::service]']) } end context 'consul_template::config should not notify consul_template::service on config change' do let(:params) {{ :restart_on_change => false }} it { should_not contain_class('consul_template::config').that_notifies(['Class[consul_template::service]']) } end context 'When requesting to install via a package with defaults' do let(:params) {{ :install_method => 'package' }} it { should contain_package('consul-template').with(:ensure => 'latest') } end context 'By default, a user and group should be installed' do it { should contain_user('consul-template').with(:ensure => :present) } it { should contain_group('consul-template').with(:ensure => :present) } end context 'By default, the service should be running and enabled' do it { should contain_service('consul-template').with( 'ensure' => 'running', 'enable' => true )} end context 'Unless darwin, install tar' do it { should contain_package('tar') } end context 'The max stale setting is set' do let(:params) {{ :config_hash => { 'max_stale' => '10m' } }} it { should contain_file('consul-template config.json').with_content(/"max_stale":"10m"/) } end context 'When asked not to manage the user' do let(:params) {{ :manage_user => false }} it { should_not contain_user('consul-template') } end context "When asked not to manage the group" do let(:params) {{ :manage_group => false }} it { should_not contain_group('consul-template') } end context "When asked not to manage the service" do let(:params) {{ :manage_service => false }} it { should_not contain_service('consul-template') } end context "With a custom username" do let(:params) {{ :user => 'custom_consul_template_user', :group => 'custom_consul_template_group', }} it { should contain_user('custom_consul_template_user').with(:ensure => :present) } it { should contain_group('custom_consul_template_group').with(:ensure => :present) } it { should contain_file('/etc/init/consul-template.conf').with_content(/setuid custom_consul_template_user/) } it { should contain_file('/etc/init/consul-template.conf').with_content(/setgid custom_consul_template_group/) } end context "On a redhat 7 based OS" do let(:facts) {{ :operatingsystem => 'CentOS', :operatingsystemmajrelease => '7' }} it { should contain_class('consul_template').with_init_style('systemd') } it { should contain_file('/lib/systemd/system/consul-template.service').with_content(/consul-template/) } end context "On an Amazon based OS" do let(:facts) {{ :operatingsystem => 'Amazon', :operatingsystemrelease => '3.10.34-37.137.amzn1.x86_64' }} it { should contain_class('consul_template').with_init_style('sysv') } it { should contain_file('/etc/init.d/consul-template').with_content(/CONSUL_TEMPLATE=\/usr\/local\/bin\/consul-template/) } end context "When installing via URL by default" do it { should contain_class('consul_template::install') } it { should contain_class('staging') } it { should contain_class('staging::params') } it { should contain_staging__file('consul-template_0.11.0.zip').with(:source => 'https://releases.hashicorp.com/consul-template/0.11.0/consul-template_0.11.0_linux_amd64.zip') } it { should contain_file('/opt/staging/consul-template-0.11.0').with(:ensure => 'directory') } it { should contain_file('/opt/staging').with(:ensure => 'directory') } it { should contain_file('/opt/staging/consul_template').with(:ensure => 'directory') } it { should contain_file('/usr/local/bin/consul-template').that_notifies('Class[consul_template::service]') } end context "Specifying consul location" do let(:params) {{ :config_hash => { 'consul' => 'my.consul.service:8500' } }} it { should contain_file('consul-template config.json').with_content(/"consul":"my.consul.service:8500"/) } end end
class ApplicationController < ActionController::Base before_action :authenticate_request protect_from_forgery with: :null_session attr_reader :current_user include ExceptionHandler private def authenticate_request @current_user = AuthorizeApiRequest.call(request.headers).result render json: { errors: 'Not Authorized' }, status: 401 unless @current_user end end
# frozen_string_literal: true Renalware::Diaverum::Engine.routes.draw do defaults format: :xml do get "/hospital_units/:unit_id/patients", to: "patients#index", as: :diaverum_patients get "/hospital_units/:unit_id/patients/:id", to: "patients#show", as: :diaverum_patient end end
require 'amberbit-config/version' require 'amberbit-config/errors' require 'amberbit-config/config' require 'amberbit-config/hash_struct' require 'amberbit-config/engine' if defined?(::Rails::Engine) module AmberbitConfig # Initialize AppConfig variable with default file path and custom file path if it wasn't set yet. def self.initialize(default_file, config_file) return unless File.exist?(default_file) return if defined?(AppConfig) config = Config.new default_file, config_file Object.const_set 'AppConfig', HashStruct.create(config.data) end # Run initialze with default file names within root_path def self.initialize_within(root_path) initialize path_from(root_path, 'app_config_default.yml'), path_from(root_path, 'app_config.yml') end # Gets path from root_path and file name, i.e. # <tt>path_from File.dirname(__FILE__), 'app_config.yml'</tt> def self.path_from(root_path, file) File.expand_path File.join(File.dirname(root_path), 'config', file) end end
module ApplicationHelper # Returns the full title on a per-page basis. def full_title(page_title = "") base_title = "Ruby on Rails Tutorial Sample App" if page_title.empty? base_title else page_title + " | " + base_title end end # Downcase and remove spaces from email addresses. def process_email_address (email) email.strip.downcase end end
class CreateJoinTableOfficerRso < ActiveRecord::Migration[5.0] def change create_join_table :officers, :rsos do |t| t.index [:officer_id, :rso_id] end end end
require "spec_helper" module LabelGen describe NumberRecord do context "with an empty db" do before :each do DataMapper.auto_migrate! end it "has a max number used as specified in the configuration" do expect(NumberRecord.max_number_used).to eq LabelGen.configuration.max_number_used end it "has no records" do expect(NumberRecord.count).to eq 0 end end # context "with an empty db" describe "using a number" do let(:number){1} before :each do DataMapper.auto_migrate! @n = NumberRecord.put_used(number) end it "affirms the number" do expect(@n).to eq number end it "has a record" do expect(NumberRecord.first(:number => number)).to_not be_nil expect(NumberRecord.first(:number => number).number).to eq number end it "is used" do expect(NumberRecord.used?(number)).to be_true end it "makes the table non-empty" do expect(NumberRecord.count).to be_> 0 end it "is not max confirmed" do expect(NumberRecord.max_number_confirmed).to_not eq number end it "has nil for confirmed_at" do expect(NumberRecord.all(:number => number)).to_not be_nil expect(NumberRecord.first(:number => number).confirmed_at).to be_nil end context "which is larger than the max number" do let(:number_max){NumberRecord.max_number_confirmed + 1} before :each do DataMapper.auto_migrate! NumberRecord.put_used(number_max) end it "is the max number used" do expect(NumberRecord.max_number_used).to eq number_max end describe "is confirmed" do let(:confirmed_max){NumberRecord.max_number_confirmed + 1} before :each do DataMapper.auto_migrate! @bln_put = NumberRecord.put_used(confirmed_max) @bln_ret = NumberRecord.confirm_used(confirmed_max) unless confirmed_max.nil? end it "is used" do expect(NumberRecord.first(:number => confirmed_max)).to be_used end it "has DateTime for confirmed_at" do expect(NumberRecord.first(:number => confirmed_max).confirmed_at).to_not be_nil end it "has succuess confirming" do expect(@bln_ret).to be_true end it "has succuess putting" do expect(@bln_put).to be_true end it "can be verified as confirmed" do expect(NumberRecord.max_number_confirmed).to eq confirmed_max end end # describe "is confirmed" end # context "which is larger than the max number" end # describe "using a number" describe "using a previously used, unconfirmed, number" do let(:number){1} before :each do DataMapper.auto_migrate! @n = NumberRecord.put_used(number) end it "returns the number" do expect(NumberRecord.put_used(number)).to eq number end it "does not add a new record" do expect(NumberRecord.all(:number => number).count).to eq 1 end end # describe "using a previously used, unconfirmed, number" do describe "putting a previously confirmed number" do let(:number){1} before :each do DataMapper.auto_migrate! NumberRecord.put_used(number) NumberRecord.confirm_used(number) end it "returns nil" do expect(NumberRecord.put_used(number)).to be_nil end end # describe "using a previously confirmed number" describe "confirming an unused number" do let(:number){1} before :each do DataMapper.auto_migrate! NumberRecord.create(number) end it "is not successull" do expect(NumberRecord.confirm_used(number)).to_not be_true end end # describe "confirming an unused number" describe "confirming numbers" do context "that have been used" do context "when some numbers are already confirmed" do let(:pre_confirmed_max){NumberRecord.max_number_confirmed + 10} let(:max_to_confirm){NumberRecord.max_number_confirmed + 55} before :each do DataMapper.auto_migrate! (NumberRecord.max_number_confirmed..pre_confirmed_max).each do |n| NumberRecord.put_used(n) NumberRecord.confirm_used(n) end (NumberRecord.max_number_confirmed..max_to_confirm).each do |n| NumberRecord.put_used(n) end end it "indicates the pre_confirmed max as the max_number_confirmed" do expect(NumberRecord.max_number_confirmed).to eq pre_confirmed_max end it "confirms each number in the series" do (NumberRecord.max_number_confirmed..max_to_confirm).each do |n| expect(NumberRecord.confirm_used(n)).to be_true end end end # context "when some numbers are already confirmed" end # context "that have been used" end # describe "confirming printed numbers" end # describe NumberRecord end # module LabelGen
class Apply < ApplicationRecord belongs_to :user belongs_to :job has_one :company, through: :job enum status: {Not_receive: 0, Received: 1} scope :newest_apply, ->{order :created_at} end
require 'curb' require 'json' require_relative '../functions' namespace :juvenile do desc "Perform a backup" task :backup, :app do |t, args| # Get the app app = args[:app] # Load the config config = Functions.load_config # if there is no app, or it's nil, run all tasks if !app || app == nil config['apps'].each do |app, settings| Functions.upload(app, settings) end else # Get the settings for this app settings = config['apps'][app] if !settings # No app, likely puts "App not found" else Functions.upload(app, settings) end end end end
require 'mina/bundler' require 'mina/rails' require 'mina/git' set :domain, '94.23.0.49' set :port, 22 set :repository, 'https://github.com/sgmap/sirene_as_api.git' set :branch, 'master' set :deploy_to, '/var/www/sirene_as_api' set :user, 'deploy' # Username in the server to SSH to. set :rails_env, 'production' # Manually create these paths in shared/ (eg: shared/config/database.yml) in your server. # They will be linked in the 'deploy:link_shared_paths' step. set :shared_paths, [ 'log', 'bin', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'tmp/files', 'public/system', 'public/uploads', 'config/database.yml', 'config/environments/production.rb', 'config/secrets.yml', 'solr' ] # This task is the environment that is loaded for most commands, such as # `mina deploy` or `mina rake`. set_default :ruby_version, "ruby-2.3.1" # Put any custom mkdir's in here for when `mina setup` is ran. # For Rails apps, we'll make some of the shared paths that are shared between # all releases. task :setup => :environment do queue! %[mkdir -p "#{deploy_to}/shared/log"] queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/log"] queue! %[mkdir -p "#{deploy_to}/shared/bin"] queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/bin"] queue! %[mkdir -p "#{deploy_to}/shared/tmp/pids"] queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/tmp/pids"] queue! %[mkdir -p "#{deploy_to}/shared/tmp/cache"] queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/tmp/cache"] queue! %[mkdir -p "#{deploy_to}/shared/tmp/files"] queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/tmp/files"] queue! %[mkdir -p "#{deploy_to}/shared/tmp/sockets"] queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/tmp/sockets"] queue! %[mkdir -p "#{deploy_to}/shared/public/system"] queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/public/system"] queue! %[mkdir -p "#{deploy_to}/shared/public/uploads"] queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/public/uploads"] queue! %[mkdir -p "#{deploy_to}/shared/config"] queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/config"] queue! %[mkdir -p "#{deploy_to}/shared/solr"] queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/solr"] end desc "Deploys the current version to the server." task :deploy => :environment do deploy do # Put things that will set up an empty directory into a fully set-up # instance of your project. invoke :'git:clone' invoke :'deploy:link_shared_paths' invoke :'bundle:install' invoke :'rails:db_migrate' # invoke :'rails:assets_precompile' to :launch do queue "touch #{deploy_to}/current/tmp/restart.txt" end end end
class User < ActiveRecord::Base after_create :send_mail private def send_mail TestMailer.sidekiq_delay_for(10.minutes, :retry => false, :queue => "low").new_user id end end
require("./lib/anagram.rb") require("rspec") require("pry") describe "String#anagram" do it("Recognizes if two words are not anagrams.") do expect("ruby".anagram("hard")).to(include("This is not an anagram")) end it("Recognizes if two words are anagrams.") do expect("ruby".anagram("bury")).to(include("These words are anagrams")) end it("Returns false if the length is not equal") do expect("ruby".anagram("burrito")).to(include("This is not an anagram")) end it("Accounts for the possibility that words w/ different cases are still anagrams") do expect("RuBy".anagram("bUrY")).to(include("These words are anagrams")) end it("Returns a note if anagrams are not palindromes") do expect("ruby".anagram("bury")).to(include(" but the first word is not a palindrome")) end it("Returns a note if anagrams are indeed palindromes") do expect("hannah".anagram("nnaahh")).to(include(" and the first word is also a palindrome!")) end it("Returns an error if anagrams do not include vowels") do expect("ruby".anagram("rrrr")).to(eq("This is not a word because it has no vowels!")) end it("Doesn't care about non-letter characters for word1") do expect("ru by!".anagram("bury")).to(include("These words are anagrams")) end it("Doesn't care about non-letter characters for word2") do expect("ruby!".anagram("bu ry")).to(include("These words are anagrams")) end it("Returns false for repeat vowels") do expect("ruby".anagram("uuuu")).to(include("This is not an anagram")) end it("Does not recognize two of the same words as anagrams") do expect("ruby".anagram("ruby")).to(include("This is not an anagram")) end end
class Category < ActiveRecord::Base has_many :decks, through: :categorizations end
# # Cookbook Name:: chef-secrets # Spec:: default # # Copyright (c) 2016 Criteo, All Rights Reserved. require 'spec_helper' describe 'chef-secrets::default' do context 'When all attributes are default, on an unspecified platform' do let(:chef_run) do runner = ChefSpec::ServerRunner.new(platform: 'centos', version: '7.7.1908') runner.node.default['cookbook']['user'] = 'plaintext' runner.node.chef_secret_attribute_set(%w(cookbook pass), 'secret') runner.node.secret['cookbook']['sugar'] = 'value' runner.node.chef_secret_attribute_clear(%w(cookbook pass)) runner.node.chef_secret_attribute_clear(%w(cookbook sugar)) runner.converge(described_recipe) end it 'converges without errors' do expect { chef_run }.to_not raise_error end it 'contains the default attribute' do expect(chef_run.node['cookbook']['user']).to eq('plaintext') end it 'has memorised the attributes set with a secret' do expect( chef_run.run_context.node.instance_variable_get('@chef_secret_attributes') ).to eq([%w(cookbook pass), %w(cookbook sugar)]) end it 'has cleared the attribute with a secret' do expect(chef_run.node['cookbook']['pass']).to eq('SECRET') end it 'works with syntax sugar' do expect(chef_run.node['cookbook']['sugar']).to eq('SECRET') end # Note: # The ChefSpec::ServerRunner fails with a "stack level too deep" error, # so we can't test the save method in ChefSpec :( end end
# == Schema Information # # Table name: template_packs # # id :integer not null, primary key # zip_container_file_name :string(255) # zip_container_content_type :string(255) # zip_container_file_size :integer # zip_container_updated_at :datetime # template_id :integer # created_at :datetime # updated_at :datetime # require 'spec_helper' describe TemplatePack do it { should belong_to :template } end
module Refinery module Portfolio class Item < ActiveRecord::Base translates :title, :caption class Translation attr_accessible :locale end attr_accessible :title, :caption, :image_id, :gallery_id, :position validates :gallery_id, :numericality => {:allow_nil => true} validates :image_id, :presence => true, :numericality => true belongs_to :image, :class_name => 'Refinery::Image' belongs_to :gallery, :class_name => 'Refinery::Portfolio::Gallery' class << self def per_page 1000 end def root_items where(:gallery_id => nil) end alias_method :orphaned, :root_items end end end end
require 'rails_helper' RSpec.feature 'Sign-up', type: :feature do scenario 'can visit sign-up page' do visit '/users/new' expect(page).to have_content('Sign up with your email address') end scenario 'fill-in form and submit' do name = 'Rick' email = 'rick@c137.com' password = 'science' visit '/users/new' fill_in('user[name]', with: name) fill_in('user[email]', with: email) fill_in('user[password]', with: password) click_button('Sign up') expect(page).to have_selector("input[type=submit][value='Log in']") end end
class MessageCustomizations < ActiveRecord::Migration include Enumerable @opts = [ :homepage_ticket_sales_text, 'Homepage message that will take customer to Buy Tickets page; if blank, link to Tickets page won\'t be displayed', 'Buy Tickets', :string, :homepage_subscription_sales_text, 'Homepage message that will take customer to Buy Subscriptions page; if blank, link to Subscriptions page won\'t be displayed', 'Subscribe Now!', :string, :subscription_purchase_email_notes, 'Additional text included in purchase confirmation screen and email when a new or renewal subscription is PURCHASED. Can include basic HTML tags and CSS information. It is automatically rendered inside <div id="subscription_purchase_notices"> and converted to plain text for confirmation email.', '', :text, :display_email_opt_out, 'If set to any nonzero value, an email opt-out box will appear whenever customers edit their contact info. If set to zero, this opt-out box will not appear. NOTE: if set to zero, you MUST ensure that you provide your customers some other way to opt out of email in order to comply with CAN-SPAM.', 0, :integer, :encourage_email_opt_in, 'Brief message encouraging customers who have opted out of email to opt back in. Use plain text only. If present, will be displayed along with a link to an opt-back-in page for customers who have a valid email address on file but have opted out. If blank, or if customer has no email address on file, no message or link will be displayed.', 'We miss having you on our email list!', :string ] def self.up id = 3070 @opts.each_slice(4) do |opt| name, description, value, typ = opt newopt = Option.create!(:grp => 'Web Site Messaging', :name => name.to_s, :value => value.to_s, :description => description, :typ => typ) ActiveRecord::Base.connection.execute("UPDATE options SET id=#{id} WHERE id=#{newopt.id}") id += 1 end newopt = Option.create!( :grp => 'External Integration', :name => 'enable_facebook_connect', :value => '1', :description => 'Set to zero (0) to COMPLETELY DISABLE Facebook integration, including "Login with your Facebook account" and Facebook-related social features. Set to any nonzero value to ENABLE Facebook integration. NOTE: This change may take up to an hour to take effect.', :typ => :integer) ActiveRecord::Base.connection.execute("UPDATE options SET id=4070 WHERE id=#{newopt.id}") end def self.down @opts.each_slice(4) do |opt| Option.find_by_name(opt[0]).destroy end Option.find_by_name(:enable_facebook_connect).destroy end end
Pod::Spec.new do |s| s.name = "CleverTap-iOS-SDK" s.version = "3.1.6" s.summary = "The CleverTap iOS SDK for App Personalization and Engagement." s.description = <<-DESC CleverTap is the next generation app engagement platform. It enables marketers to identify, engage and retain users and provides developers with unprecedented code-level access to build dynamic app experiences for multiple user groups. CleverTap includes out-of-the-box prescriptive campaigns, omni-channel messaging, uninstall data and the industry’s largest FREE messaging tier. DESC s.homepage = "https://github.com/CleverTap/clevertap-ios-sdk" s.license = { :type => 'Commercial', :text => 'Please refer to https://github.com/CleverTap/clevertap-ios-sdk/blob/master/LICENSE'} s.author = { "CleverTap" => "http://www.clevertap.com" } s.source = { :git => "https://github.com/CleverTap/clevertap-ios-sdk.git", :tag => s.version.to_s } s.documentation_url = 'http://support.clevertap.com/' s.requires_arc = true s.xcconfig = { 'FRAMEWORK_SEARCH_PATHS' => '$(inherited)' } s.tvos.deployment_target = '9.0' s.ios.deployment_target = '8.0' s.watchos.deployment_target = '2.0' s.default_subspec = 'Main' s.subspec 'Main' do |ss| ss.platform = :ios, '8.0' ss.frameworks = 'SystemConfiguration', 'CoreTelephony', 'UIKit', 'CoreLocation' ss.ios.vendored_frameworks = 'CleverTapSDK.framework' end s.subspec 'HostWatchOS' do |ss| ss.platform = :ios, '8.0' ss.frameworks = 'WatchConnectivity', 'WatchKit' ss.dependency "CleverTap-iOS-SDK/Main" end s.subspec 'AppEx' do |ss| ss.platform = :ios, '8.0' ss.frameworks = 'SystemConfiguration', 'UIKit', 'CoreLocation' ss.ios.vendored_frameworks = 'CleverTapAppEx.framework' end s.subspec 'tvOS' do |ss| ss.platform = :tvos, '9.0' ss.frameworks = 'SystemConfiguration', 'UIKit', 'Foundation' ss.vendored_frameworks = 'CleverTapTVOS.framework' end end
require 'test_helper' class AsteroidesControllerTest < ActionController::TestCase setup do @asteroide = asteroides(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:asteroides) end test "should get new" do get :new assert_response :success end test "should create asteroide" do assert_difference('Asteroide.count') do post :create, asteroide: { Asteroide: @asteroide.Asteroide, Tamano: @asteroide.Tamano } end assert_redirected_to asteroide_path(assigns(:asteroide)) end test "should show asteroide" do get :show, id: @asteroide assert_response :success end test "should get edit" do get :edit, id: @asteroide assert_response :success end test "should update asteroide" do patch :update, id: @asteroide, asteroide: { Asteroide: @asteroide.Asteroide, Tamano: @asteroide.Tamano } assert_redirected_to asteroide_path(assigns(:asteroide)) end test "should destroy asteroide" do assert_difference('Asteroide.count', -1) do delete :destroy, id: @asteroide end assert_redirected_to asteroides_path end end
# frozen_string_literal: true class Tagging < ApplicationRecord belongs_to :activity belongs_to :tag end
require_relative 'generators/fibonacci.rb' require_relative 'evaluators/is_even.rb' class ConditionalValuesAggregator def self.aggregate(upto) new.aggregate(upto) end def aggregate(max_value, generator = Generators::Fibonacci.new, evaluator = Evaluators::IsEven.new) do_aggregate(0, max_value, generator, evaluator) end private def do_aggregate(sum, max_value, generator, evaluator) next_value = generator.next_number return sum if next_value >= max_value sum += next_value if evaluator.true_for?(next_value) do_aggregate(sum, max_value, generator, evaluator) end end
class Player < ActiveRecord::Base attr_accessor :slack_username has_many :team_players has_many :elos, dependent: :destroy scope :player, -> { where(type: nil) } def pro? elos.any? { |elo| elo.rating >= Elo::PRO_RATING } end def starter? elos.size < Elo::STARTER_BOUNDRY end def member_name(members) member = members.detect{ |m| m["id"] == self.username } member.present? ? member["name"] : "unknown" end def games_played(from = nil) _elos = elos.all _elos = _elos.where("created_at >= ?", from) if from.present? _elos.count - (from.present? ? 0 : 1) end def won(from = nil) Game.find_by_player(self, from).select { |g| g.winner.player == self rescue false }.length end def lost(from = nil) Game.find_by_player(self, from).select { |g| g.loser.player == self rescue false }.length end def drawn(from = nil) Game.find_by_player(self, from).select { |g| g.drawn? }.length end def teams_statistics team_players = TeamPlayer.where(player: self).group_by(&:team) all_tp = team_players.values.flatten.length teams = Hash[ team_players.map { |team, tp| [team.name, ((tp.length.to_f / all_tp.to_f)*100).round(2)] } ] teams.sort_by { |team, score| score } end def largest_victory games = Game.find_by_player(self) largest_score = 0 largest_score_game = nil games.each do |game| diff = 0 if game.team_player1.player == self diff = game.team_player1.score - game.team_player2.score else diff = game.team_player2.score - game.team_player1.score end if diff > largest_score largest_score = diff largest_score_game = game end end largest_score_game end def opponent_statistics response = {} Player.player.each do |player| rate = win_rate_against(player) response[player.username] = rate unless rate.nil? end response.sort_by { |username, score| score } end def win_rate_against(opponent) games = Game.find_with_players(self, opponent) return nil if games.empty? won = games.select { |game| game.winner.present? and game.winner.player == self }.length ((won.to_f / games.length.to_f).round(2) * 100) end def k_factor if pro? return Elo::K_FACTOR_PRO elsif starter? return Elo::K_FACTOR_STARTER else return Elo::K_FACTOR_OTHER end end def rating(from = nil) return Elo::INITIAL_RATING if elos.empty? base = from.present? ? rating_at(from) : 0 elos.last.rating - base end def rating_at(date) elos.where("created_at <= ?", date).last.rating rescue Elo::INITIAL_RATING end def compute_new_rating(result, opponent_rating) new_rating = rating + (k_factor.to_f * (result.to_f - Elo.expected(rating, opponent_rating))).to_i Elo.create(player: self, rating: new_rating) end # returns the ratio (wins - loses) / #games against another player def compare(player) # fetch all matches between both players games = Game.find_with_players(self, player) total = 0 games.each do |game| next if game.drawn? total += 1 if game.winner.player == self total -= 1 if game.winner.player == player end (total.to_f / games.length.to_f) end def goals_scored(from = nil) team_players = TeamPlayer.where(player: self) team_players = team_players.where("created_at >= ?", from) if from.present? team_players.inject(0) { |sum, tp| sum + tp.score } end def goals_conceded(from = nil) games = Game.find_by_player(self, from) games.inject(0) { |sum, game| sum + (game.team_player1.player == self ? game.team_player2.score : game.team_player1.score) } end # initialize a new player with the initial elo rating after_create do |player| Elo.create(player: player, rating: Elo::INITIAL_RATING) end end
describe PersonSpecie do describe "associations" do it { is_expected.to belong_to :person } it { is_expected.to belong_to :specie } end end
# require 'rails_helper' # # RSpec.describe VolunteersController, type: :controller do # include Devise::Test::ControllerHelpers # # before(:each) do # @request.env["devise.mapping"] = Devise.mappings[:user] # @current_user = create(:user) # sign_in @current_user # end # # describe "GET #index" do # it "returns http success" do # get :index # expect(response).to have_http_status(:success) # end # end # # describe "GET #show" do # context "volunteer exists" do # it "returns http success" do # volunteer = create(:volunteer) # get :show, params: {id: volunteer.id} # expect(response).to have_http_status(:success) # end # end # # context "volunteer doesn't exist" do # it "redirects to volunteers index" do # volunteer_attributes = attributes_for(:volunteer) # get :show, params: {id: 100} # expect(response).to have_http_status(:not_found) # end # end # end # # describe "POST #create" do # before(:each) do # @vol_attributes = attributes_for(:volunteer, user: @current_user) # post :create, params: {volunteer: @vol_attributes} # end # # context "valid volunteer" do # it "redirects to volunteer" do # expect(response).to have_http_status(:found) # expect(response).to redirect_to("/volunteers/#{Volunteer.last.id}") # end # # it "with right arguments" do # expect(Volunteer.last.user).to eql(@current_user) # expect(Volunteer.last.name).to eql(@vol_attributes.name) # expect(Volunteer.last.city).to eql(@vol_attributes.city) # end # end # end # # # describe "PATCH #update" do # # it "returns http created" do # # volunteer = FactoryGirl.create(:volunteer) # # patch :update, params: {id: volunteer.id} # # expect(response).to have_http_status(:created) # # end # # end # # # describe "DELETE #destroy" do # # it "returns http deleted" do # # volunteer = FactoryGirl.create(:volunteer) # # delete :destroy, params: {id: volunteer.id} # # expect(response).to have_http_status(:destroyed) # # end # # end # # end
require 'rails_helper' RSpec.describe "devise/registration/new.html.erb", type: :feature do describe "User sign in" do describe "Valid signin data" do it "Login and Logout" do user = build(:user, username: "username", password: "somepassword", password_confirmation: "somepassword") visit new_user_registration_path signup user expect(current_path).to eq("/") expect(page).to have_content "username" click_link "Sign out" expect(current_path).to eq(new_user_session_path) expect(page).to have_css("h2", text: "Log in") expect(page).not_to have_content "Awesome_twitter" end end describe "Invalid signin data" do it "password doesn't match" do user = build(:user, username: "username", password: "somepassword", password_confirmation: "anotherpassword") visit new_user_registration_path signup user expect(current_path).to eq(user_registration_path) expect(page).to have_content "Password confirmation doesn't match" #expect(page).to have_css("h2", text: "Log in") end end end private def signup(user) fill_in "First name", with: user.first_name fill_in "Last name", with: user.last_name fill_in "Username", with: user.username fill_in "Email", with: user.email fill_in "Password", with: user.password fill_in "Password confirmation", with: user.password_confirmation click_button "Sign up" end end
=begin Using the following code, add an instance method named #rename that renames kitty when invoked. class Cat attr_accessor :name def initialize(name) @name = name end end kitty = Cat.new('Sophie') kitty.name kitty.rename('Chloe') kitty.name Expected output: Sophie Chloe =end class Cat attr_accessor :name def initialize(name) @name = name end def rename(new_name) self.name = new_name end end kitty = Cat.new('Sophie') puts kitty.name kitty.rename('Chloe') puts kitty.name
require 'spec_helper' include Church describe 'CHR' do it "should return its argument's corresponding character" do expect(CHR[83]).to eq 83.chr end end describe 'ORD' do it "should return its argument's corresponding ordinal value" do expect(ORD['q']).to be 'q'.ord end end describe 'CHARS' do it "should return an array of the string's characters" do expect(CHARS['Ruby']).to eq %w[R u b y] end end describe 'JOIN' do it "should join a string on a delimiter" do expect(JOIN[[1, 2, 3], ',']).to eq '1,2,3' end it "should be able to join on an empty delimeter" do expect(JOIN[[1, 2, 3], '']).to eq '123' end end describe 'TO_I' do it "should convert its argument to a number" do expect(TO_I['0']).to be 0 expect(TO_I['12345']).to be 12345 end end describe 'PRINT' do it "should write its argument to standard output" do expect(capture_stdout { PRINT['Alonzo'] }).to eq 'Alonzo' end end describe 'PUTS' do it "should write its argument to standard output with a newline" do expect(capture_stdout { PUTS['Church'] }).to eq "Church\n" end end
class CheckoutService CART_ATTRIBUTES = %w(customer_id items total total_discount) def add_item(customer_id, product_sku, product_price) cart = Cart.find_or_create_by(customer_id: customer_id) cart.items ||= [] cart.items << {sku: product_sku, price: product_price} cart.total += product_price guard do cart.save! to_serializable cart end end # TODO find better way to maintain input validation (cart existence for passed customer) def check_for_offers(customer_id) valid_offers = [] # Get customer cart cart = Cart.find_by(customer_id: customer_id) if cart # init services offer_service = OfferService.new price_rule_service = PriceRuleService.new # call offer service to get all valid customer's offers offer_service.get_valid_offers(customer_id).each do |offer| # call price rule service for each offer to validate which offer apply to the items in the cart valid_offers << offer if price_rule_service.price_rule_valid?(offer['price_rule_id'], cart.items) end end valid_offers end # TODO find better way to maintain input validation (cart and offer existence for passed customer and offer) def apply_offer(customer_id, offer_id) cart = Cart.find_by(customer_id: customer_id) if cart offer_service = OfferService.new offer = offer_service.get_offer_by_id(offer_id) unless offer[:error] price_rule_service = PriceRuleService.new total_discount, items = price_rule_service.evaluate_price_rule(offer['price_rule_id'], cart.items) return guard do cart.update!(total_discount: total_discount, items: items) to_serializable cart end end end guard { to_serializable cart } end def delete_all_carts guard { !!Cart.destroy_all } end private def to_serializable(customer_model) customer_model.serializable_hash.slice *CART_ATTRIBUTES end def guard ActiveRecord::Base.connection_pool.with_connection do begin yield rescue ActiveRecord::RecordNotFound => e { error: {code: 101, message: e.message} } rescue ActiveRecord::RecordInvalid => e { error: {code: 100, message: e.message} } end end end end
require 'test_helper' class FoldersControllerTest < ActionController::TestCase setup do @folder = folders(:one) @user = users(:one) sign_in @user end test "should get index" do skip('Will implement folders in the future') get :index assert_response :success assert_not_nil assigns(:folders) end test "should get new" do skip('Will implement folders in the future') get :new assert_response :success end test "should create folder" do skip('Will implement folders in the future') assert_difference('Folder.count') do post :create, params: { folder: { created_by: @folder.created_by, deleted_by: @folder.deleted_by, description: @folder.description, owner: @folder.owner, parent: @folder.parent, status_id: @folder.status_id, title: @folder.title, updated_by: @folder.updated_by, visibility_id: @folder.visibility_id } } end assert_redirected_to folder_path(assigns(:folder)) end test "should show folder" do skip('Will implement folders in the future') get :show, id: @folder assert_response :success end test "should get edit" do skip('Will implement folders in the future') get :edit, id: @folder assert_response :success end test "should update folder" do skip('Will implement folders in the future') patch :update, params: { id: @folder, folder: { created_by: @folder.created_by, deleted_by: @folder.deleted_by, description: @folder.description, owner: @folder.owner, parent: @folder.parent, status_id: @folder.status_id, title: @folder.title, updated_by: @folder.updated_by, visibility_id: @folder.visibility_id } } assert_redirected_to folder_path(assigns(:folder)) end test "should destroy folder" do skip('Will implement folders in the future') assert_difference('Folder.count', -1) do delete :destroy, params: { id: @folder } end assert_redirected_to folders_path end end
class Courier # twilio webapp api attr_reader :messages attr :client, :messages def initialize(client: Twilio::REST::Client.new(ENV['ACCOUNT_SID'], ENV['AUTH_TOKEN'])) @client = client end def send_message(to: "6507418502", body: "Hello there!") @message = client.messages.create( :from => '+16506514480', :to => to, body: body ) end def send_text_message(to: "6507418502", body: "Hello there!", from: '+16506514480') message = client.messages.create( from: self.sanitize(from), to: self.sanitize(to), body: body ) end def sanitize(number) "+1" + number.gsub(/$1|\+|\s|\(|\)|\-|\./, '') end end
require './../lib/connect_four.rb' describe "Board" do board = Board.new it "is always 7 wide" do expect(board.board.length).to eql(7) end it "is always 6 high" do expect(board.board[0].length).to eql(6) end describe "#place" do it "places a piece in a specified location" do board.board[0][0] = nil board.place(0, "red") expect(board.board[0][0]).to eql("red") end it "places a piece on top of another" do board.board[0][0] = "blue" board.place(0, "red") expect(board.board[0][1]).to eql("red") end it "only lets pieces be put in open spaces" do board.board[0].fill("red") expect(board.place(0,"red")).to eql("Please enter a valid location") end end describe "#check_win" do it "checks for horizontal win" do board = Board.new i = 0 4.times do board.place(i, "red") i += 1 end expect(board.check_win).to eql(true) end it "checks for vertical win" do board = Board.new 4.times do board.place(0, "red") end expect(board.check_win).to eql(true) end it "checks for diagonal-up win" do board = Board.new i = 0 4.times do board.board[i][i] = "red" i += 1 end expect(board.check_win).to eql(true) end it "checks for diagonal-down win" do board = Board.new column = 0 row = 3 4.times do board.board[column][row] = "red" column += 1 row -= 1 end expect(board.check_win).to eql(true) end end end