text
stringlengths
10
2.61M
require 'pry' require 'tty-prompt' require_relative '../../bin/globalvariable' class CLI def initialize @prompt = TTY::Prompt.new @font = TTY::Font.new(:doom) @pastel = Pastel.new # @user = [] end def welcome system("clear") puts @pastel.magenta.bold(@font.write("ASTEROIDS".center(30), letter_spacing: 4)) # displays game title sleep(1) # input a delay before displaying the menu/selection screen below selection = @prompt.select("\n".center(185)) do |menu| menu.choice 'Create Account'.center(180), 1 menu.choice 'Sign In'.center(180), 2 menu.choice 'Exit'.center(180), 3 end if selection == 1 new_acc elsif selection == 2 login_acc elsif selection == 3 close end end def new_acc u_input = @prompt.ask('Please enter a username:', required: true) username = User.find_by(username: u_input) system('clear') sleep(1) email_input = @prompt.ask('Please enter your email address:') { |q| q.validate :email } email = User.find_by(email_address: email_input) system("clear") if username == nil pass = @prompt.mask('Please enter a password:', required: true) system("clear") @user = User.create(username: u_input, email_address: email_input, password: pass) system("clear") puts "Your account has been created. Welcome to ASTEROIDS, #{u_input}." sleep(1) else puts "That username is already taken, please try again." sleep(2) welcome end menu end def login_acc system("clear") u_input = @prompt.ask('Please enter a username:') e_user = User.find_by(username: u_input) system("clear") sleep(1) if e_user == nil puts "User not found, please try again!".center(175) sleep(2) welcome else pass = @prompt.mask('Please enter a password:', required: true) @user = User.find_by(username: u_input, password: pass) system("clear") sleep(1) if @user == nil puts "Incorrect password, please sign in again!".center(175) sleep(1) welcome else puts "Welcome back #{e_user.username}!" end end menu end def menu puts "Main Menu\n\n".center(180) # add new line char selection = @prompt.select("Select an option:\n".center(180)) do |menu| menu.choice 'Game Start'.center(175), 1 menu.choice 'Choose Difficulty'.center(175), 2 menu.choice 'Profile'.center(175), 3 menu.choice "Leaderboard".center(176), 4 menu.choice 'Choose Players'.center(175), 5 menu.choice 'Back'.center(175), 6 menu.choice 'Exit'.center(175), 7 end case selection when 1 game = Game.create(difficulty: $DIFFICULTY, players: $PLAYERS, start_timer: $FPS * 3, started: false, finish_flag: 0) # change to Game.new(2) for two player game ๐Ÿš€ = [] ๐Ÿš€ << Ship.create(user_id: @user.id, game_id: game.id, hp: 5, scores: 0, position_x: 16, position_y: 20, start_time: Time.now, player_option: 0) if game.players == 2 # if players == 2 set coords to 2 player position ๐Ÿš€ << Ship.create(user_id: @user2.id, game_id: game.id, hp: 5, scores: 0, position_x: 11, position_y: 20, start_time: Time.now, player_option: 1) ๐Ÿš€[0].position_x = 22 ๐Ÿš€[0].position_y = 20 end ๐ŸŽ‡ = [] ๐ŸŒ‘ = [] ๐ŸŒ‘ << Asteroid.create(rock_x: rand($GRID_WIDTH), rock_y: rand(3), reached_end: false, collided: false) $MUSIC.play game.run(๐Ÿš€, ๐ŸŽ‡, ๐ŸŒ‘, @user) # menu when 2 difficulty # user able to change difficulty of game when 3 profile when 4 leaderboard # leaderboard when 5 players when 6 system('clear') welcome when 7 close else raise ArgumentError, "bad selection #{selection}" end end def login_acc2 system("clear") u_input = @prompt.ask('Please enter a username:') e_user = User.find_by(username: u_input) system("clear") sleep(1) if e_user == nil puts "User not found, please try again!".center(175) sleep(2) welcome else pass = @prompt.mask('Please enter a password:', required: true) @user2 = User.find_by(username: u_input, password: pass) system("clear") sleep(1) if @user2 == nil puts "Incorrect password, please sign in again!".center(175) sleep(1) welcome else puts "Welcome back #{e_user.username}!" end end end def players amount = @prompt.select("") do |menu| menu.choice 'One Player'.center(175), 1 menu.choice 'Two Players'.center(175), 2 end case amount when 1 $PLAYERS system('clear') sleep(1) puts 'Playing with one player'.center(175) sleep(1) system('clear') menu when 2 $PLAYERS = 2 system('clear') sleep(1) login_acc2 puts 'Playing with two players'.center(175) sleep(1) system('clear') menu end end def difficulty diff = @prompt.select("") do |menu| menu.choice 'Easy'.center(175), 1 menu.choice 'Medium'.center(175), 2 menu.choice "Hard\n".center(175), 3 menu.choice 'Back'.center(175), 4 end case diff when 1 $FPS $DIFFICULTY system('clear') sleep(1) puts 'Difficulty changed to Easy'.center(175) sleep(1) system('clear') menu when 2 $FPS = 20 $DIFFICULTY = "Medium" system('clear') sleep(1) puts 'Difficulty changed to Medium'.center(175) sleep(1) system('clear') menu when 3 $FPS = 25 $DIFFICULTY = "Hard" system('clear') sleep(1) puts 'Difficulty changed to Hard'.center(175) sleep(1) system('clear') menu when 4 menu end end def leaderboard puts "===================".center(175) puts "Ship 1".center(175) puts "Score: \n".center(175) puts "===========".center(175) puts "Ship 2".center(175) puts "Score: \n".center(175) puts "===================".center(175) sleep(2) selection = @prompt.select("") do |menu| menu.choice 'Return to Main Menu'.center(175), 1 end if selection == 1 system('clear') menu end end def profile selection = @prompt.select("") do |menu| menu.choice 'Change Password'.center(175), 1 menu.choice 'Delete Account'.center(175), 2 menu.choice "High Score\n".center(175), 3 menu.choice 'Return to Main Menu'.center(175), 4 menu.choice 'Exit'.center(175), 5 end case selection when 1 passinput = @prompt.mask("Please enter a new password:", required: true) @user.update(password: passinput) # Currently changes all users pass system("clear") puts "You successfully changed your password!\n".center(175) sleep(2) self.menu when 2 User.delete(@user) system("clear") puts "Your account was deleted. Returning to login screen.".center(175) sleep(2) welcome when 3 # check personal score of player when 4 system('clear') self.menu when 5 close end end def close system("clear") sleep(1) puts "Thank you for playing, see you again!".center(175) puts "by Shevaughn and Eitan".center(175) exit end end # class
# frozen_string_literal: true class User def initialize(fio) @fio = fio end attr_reader :fio end
# frozen_string_literal: true require 'sidekiq' module SidekiqSimpleDelay # Worker that handles the simple_delayed functionality for ActionMailers class SimpleDelayedMailer include Sidekiq::Worker def perform(args) target_klass = Object.const_get(args.fetch('target_klass')) method_name = args['m'] method_args = args['args'] msg = target_klass.__send__(method_name, *method_args) # The email method can return nil, which causes ActionMailer to return # an undeliverable empty message. raise "#{target.name}##{method_name} returned an undeliverable mail object" unless msg deliver(msg) end private def deliver(msg) if msg.respond_to?(:deliver_now) # Rails 4.2/5.0 msg.deliver_now else # Rails 3.2/4.0/4.1 msg.deliver end end end end
require 'yt/config' require 'yt/models/account' require 'yt/models/content_owner' RSpec.configure do |config| # Create one global test account to avoid having to refresh the access token # at every request config.before :all do attrs = {refresh_token: ENV['YT_TEST_DEVICE_REFRESH_TOKEN']} $account = Yt::Account.new attrs end # Don't use authentication from env variables unless specified with a tag config.before :all do Yt.configure do |config| config.client_id = nil config.client_secret = nil config.api_key = nil end end config.before :all, device_app: true do Yt.configure do |config| config.client_id = ENV['YT_TEST_DEVICE_CLIENT_ID'] config.client_secret = ENV['YT_TEST_DEVICE_CLIENT_SECRET'] config.log_level = ENV['YT_LOG_LEVEL'] end end config.before :all, server_app: true do Yt.configure do |config| config.api_key = ENV['YT_TEST_SERVER_API_KEY'] config.log_level = ENV['YT_LOG_LEVEL'] end end config.before :all, partner: true do Yt.configure do |config| config.client_id = ENV['YT_TEST_PARTNER_CLIENT_ID'] config.client_secret = ENV['YT_TEST_PARTNER_CLIENT_SECRET'] config.log_level = ENV['YT_LOG_LEVEL'] end # Create one Youtube Partner channel, authenticated as the content owner attrs = {refresh_token: ENV['YT_TEST_CONTENT_OWNER_REFRESH_TOKEN']} attrs[:owner_name] = ENV['YT_TEST_CONTENT_OWNER_NAME'] $content_owner = Yt::ContentOwner.new attrs end end
require_relative "./open_source_stats/version.rb" require_relative "./open_source_stats/user" require_relative "./open_source_stats/organization" require_relative "./open_source_stats/event" require 'active_support' require 'active_support/core_ext/numeric/time' require 'octokit' require 'dotenv' Dotenv.load class OpenSourceStats # Authenticated Octokit client instance def self.client @client ||= Octokit::Client.new :access_token => ENV["GITHUB_TOKEN"] end # Returns a Ruby Time instance coresponding to the earliest possible event timestamp def self.start_time @start_time ||= Time.now - 24.hours end # Helper method to overide the timestamp def self.start_time=(time) @start_time = time end def team @team ||= client.team ENV["GITHUB_TEAM_ID"] end # Returns an array of Users from the given team def users @users ||= begin users = client.team_members ENV["GITHUB_TEAM_ID"], :per_page => 100 while client.last_response.rels[:next] && client.rate_limit.remaining > 0 users.concat client.get client.last_response.rels[:next].href end users.map { |u| User.new u[:login] } end end # Returns an array of Events across all Users def user_events @user_events ||= users.map { |u| u.events }.flatten end # Returns an array of Organizations from the specified list of organizations def orgs @orgs ||= ENV["GITHUB_ORGS"].split(/, ?/).map { |o| Organization.new(o) } end # Returns an array of Events across all Organziations def org_events @org_events ||= orgs.map { |o| o.events }.flatten end # Returns an array of unique Events accross all Users and Organizations def events @events ||= user_events.concat(org_events).uniq end # Returns the calculated stats hash def stats(events=events) { :repositories_created => event_count(events, :type =>"CreateEvent"), :issue_comments => event_count(events, :type =>"IssueCommentEvent"), :issues_opened => event_count(events, :type =>"IssuesEvent", :action => "opened"), :issues_closed => event_count(events, :type =>"IssuesEvent", :action => "closed"), :repos_open_sourced => event_count(events, :type =>"PublicEvent"), :pull_requests_opened => event_count(events, :type =>"PullRequestEvent", :action => "opened"), :pull_requests_merged => event_count(events, :type =>"PullRequestEvent", :action => "closed", :merged => true), :versions_released => event_count(events, :type =>"ReleaseEvent", :action => "published"), :pushes => event_count(events, :type =>"PushEvent"), :commits => events.map { |e| e.commits }.flatten.inject{|sum,x| sum + x }, :total_events => event_count(events) } end private # Helper method to count events by set conditions # # Options: # :type - the type of event to filter by # :action - the payload action to filter by # :merged - whether the pull request has been merged # # Returns an integer reflecting the resulting event count def event_count(events, options={}) events = events.select { |e| e.type == options[:type] } if options[:type] events = events.select { |e| e.payload[:action] == options[:action] } if options[:action] events = events.select { |e| e.payload[:pull_request][:merged] == options[:merged] } if options[:merged] events.count end # Helper method to reference the client stored on the class and DRY things up a bit def client OpenSourceStats.client end end
require 'nokogiri' require 'open-uri' require 'json' require './websites' # This module is for converting our data to a json file module DataExporter class << self # We take in a hash and output json def data_to_json(data) return JSON.pretty_generate(data) end # We output our json to output.json def export_data(json) output = File.open('output.json', 'w') output << json return true end end end # Example usage: # DataExporter.export_data(DataExporter.data_to_json(WebsiteScraper.scrape_all))
require "rails_helper" RSpec.describe TrialPresenter do before do define_description_list_items end describe "#to_s" do it "returns trial title" do title = "Trial title" trial = build(:trial, title: title) trial_presenter = TrialPresenter.new(trial) expect(trial_presenter.to_s). to eq title end end describe "description_as_markup" do it "identifies list item content and wraps <li>" do trial = build(:trial, description: original_text) trial_presenter = TrialPresenter.new(trial) expect(trial_presenter.description_as_markup).to eq expected_text end end describe "detailed_description_as_markup" do it "identifies list item content and wraps <li>" do trial = build(:trial, detailed_description: original_text) trial_presenter = TrialPresenter.new(trial) expect(trial_presenter.detailed_description_as_markup).to eq expected_text end end describe "criteria_as_markup" do it "identifies list item content and wraps <li>" do trial = build(:trial, criteria: original_text) trial_presenter = TrialPresenter.new(trial) expect(trial_presenter.criteria_as_markup).to eq expected_text end it "wraps inclusion/exclusion with header tag" do trial = build(:trial, criteria: original_criteria) trial_presenter = TrialPresenter.new(trial) expect(trial_presenter.criteria_as_markup).to eq expected_criteria end end describe "#age_range" do context "max age is less than MAX_AGE" do it "returns min and max age" do trial = build( :trial, minimum_age_original: "15 years", maximum_age_original: "99 years", maximum_age: 99 ) trial_presenter = TrialPresenter.new(trial) expect(trial_presenter.age_range).to eq "15 years - 99 years" end end context "max age is greater than MAX_AGE" do it "returns min and max age" do trial = build( :trial, minimum_age_original: "15 years", maximum_age_original: "150 years", maximum_age: 150 ) trial_presenter = TrialPresenter.new(trial) expect(trial_presenter.age_range).to eq "15 years and Over" end end context "max age is N/A" do it "returns min and max age" do trial = build( :trial, minimum_age_original: "15 years", maximum_age_original: "N/A", maximum_age: 120 ) trial_presenter = TrialPresenter.new(trial) expect(trial_presenter.age_range).to eq "15 years and Over" end end end describe "#healthy_volunteers_as_yes_no" do context "healthy_volunteers is 'Accepts Healthy Volunteers'" do it "returns 'Yes'" do trial = build(:trial, healthy_volunteers: "Accepts Healthy Volunteers") trial_presenter = TrialPresenter.new(trial) expect(trial_presenter.healthy_volunteers_as_yes_no).to eq "Yes" end end context "healthy_volunteers is 'No'" do it "returns 'No'" do trial = build(:trial, healthy_volunteers: "No") trial_presenter = TrialPresenter.new(trial) expect(trial_presenter.healthy_volunteers_as_yes_no).to eq "No" end end context "healthy_volunteers is ''" do it "returns 'Unknown'" do trial = build(:trial, healthy_volunteers: "") trial_presenter = TrialPresenter.new(trial) expect(trial_presenter.healthy_volunteers_as_yes_no).to eq "Unknown" end end end def original_criteria <<-DESCRIPTION Inclusion Criteria: Item 1 Exclusion Criteria: Item 1 DESCRIPTION end def expected_criteria <<-DESCRIPTION <h2>Inclusion Criteria:</h2> Item 1 <h2>Exclusion Criteria:</h2> Item 1 DESCRIPTION end def original_text <<-DESCRIPTION Primary Objectives: - #{list_1} - #{list_2} Inbetween text. (1) #{list_3} (2) #{list_4} Inbetween text. I. #{list_5} II. #{list_6} III. #{list_7} IV. #{list_8} V. #{list_9} VI. #{list_10} VII. #{list_11} VIII. #{list_12} IX. #{list_13} X. #{list_14} Inbetween text. DESCRIPTION end def expected_text <<-DESCRIPTION Primary Objectives: <ul><li>- #{list_1_expected}</li></ul><ul><li>- #{list_2_expected}</li></ul>Inbetween text. <ul><li>(1) #{list_3_expected}</li></ul><ul><li>(2) #{list_4_expected}</li></ul>Inbetween text. <ul><li>I. #{list_5_expected}</li></ul><ul><li>II. #{list_6_expected}</li></ul><ul><li>III. #{list_7_expected}</li></ul><ul><li>IV. #{list_8_expected}</li></ul><ul><li>V. #{list_9_expected}</li></ul><ul><li>VI. #{list_10_expected}</li></ul><ul><li>VII. #{list_11_expected}</li></ul><ul><li>VIII. #{list_12_expected}</li></ul><ul><li>IX. #{list_13_expected}</li></ul><ul><li>X. #{list_14_expected}</li></ul>Inbetween text. DESCRIPTION end def define_description_list_items 1.upto(14).map do |number| self.class.send( :define_method, "list_#{number}", proc { "List vs. St. Jude e.g. 9.5 i.e. Item Number #{number}." } ) self.class.send( :define_method, "list_#{number}_expected", proc { "List vs&#46; St&#46; Jude e&#46;g&#46; 9&#46;5 i&#46;e&#46; Item Number #{number}." } ) end end def expect_description_list_items_as_list(list_items) list_items.each do |list| expect(page).to have_css "li", text: send(list) end end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| # boxes at https://vagrantcloud.com/search. config.vm.box_check_update = false config.vm.define "jenkins", primary:true do |jenkins| jenkins.vm.box = "centos/7" jenkins.vm.hostname = 'node4' jenkins.vm.network "forwarded_port", guest: 8080, host: 8080 jenkins.vm.synced_folder "./ansible", "/opt/ansible", type: "smb" jenkins.vm.provider "virtualbox" do |vb| vb.customize ['modifyvm', :id, '--nictype1', '82540EM'] vb.customize ["modifyvm", :id, "--natdnshostresolver1", "on"] vb.name = "jenkis" vb.gui = false vb.memory = "2048" end jenkins.vm.provision "shell", inline: <<-SHELL yum --enablerepo=base clean metadata yum -y --nogpgcheck update yum -y --nogpgcheck install git vim mc curl wget epel-release yum -y --nogpgcheck install ansible yum -y --nogpgcheck install java-1.8.0-openjdk cd /opt/ansible && git clone https://github.com/lean-delivery/ansible-role-jenkins.git cp /vagrant/ansible/playbook.yml /opt/ansible cd /opt/ansible && ansible-playbook ./playbook.yml SHELL end end
class PotzsController < ApplicationController # GET /potzs # GET /potzs.json def index @potzs = Potz.all respond_to do |format| format.html # index.html.erb format.json { render json: @potzs } end end # GET /potzs/1 # GET /potzs/1.json def show @potz = Potz.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @potz } end end # GET /potzs/new # GET /potzs/new.json def new @potz = Potz.new respond_to do |format| format.html # new.html.erb format.json { render json: @potz } end end # GET /potzs/1/edit def edit @potz = Potz.find(params[:id]) end # POST /potzs # POST /potzs.json def create @potz = Potz.new(params[:potz]) respond_to do |format| if @potz.save format.html { redirect_to @potz, notice: 'Potz was successfully created.' } format.json { render json: @potz, status: :created, location: @potz } else format.html { render action: "new" } format.json { render json: @potz.errors, status: :unprocessable_entity } end end end # PUT /potzs/1 # PUT /potzs/1.json def update @potz = Potz.find(params[:id]) respond_to do |format| if @potz.update_attributes(params[:potz]) format.html { redirect_to @potz, notice: 'Potz was successfully updated.' } format.json { head :ok } else format.html { render action: "edit" } format.json { render json: @potz.errors, status: :unprocessable_entity } end end end # DELETE /potzs/1 # DELETE /potzs/1.json def destroy @potz = Potz.find(params[:id]) @potz.destroy respond_to do |format| format.html { redirect_to potzs_url } format.json { head :ok } end end end
class Budgets::MonthlyEarningsController < ApplicationController before_action :authenticate_guest! def index @home_bg = 'budget-bg' @title = 'Budget - Monthly Earnings' @monthly_earnings = current_guest.budgets_monthly_earnings.order("updated_at ASC") @monthly_earning = Budgets::MonthlyEarning.new end def show end def new respond_to do |format| format.html format.js end end def create @monthly_earning = current_guest.budgets_monthly_earnings.new(me_params) respond_to do |format| if @monthly_earning.save format.html { redirect_to budgets_monthly_earnings_path, notice: 'New monthly earning added.' } else format.html { render :index, alert: 'Error adding new earning.' } end end end def edit @monthly_earning = current_guest.budgets_monthly_earnings.find(params[:id].to_i) respond_to do |format| format.html format.js end end def update monthly_earning = current_guest.budgets_monthly_earnings.find(params[:id].to_i) if monthly_earning.update_attributes(me_params) redirect_to index end end def destroy end private def me_params params.require(:budgets_monthly_earning).permit(:monthyear, :earning) end end
require_relative '../lib/chess.rb' ### fix tests describe Chess do let(:game) { Chess.new } let(:plr1) { game.plr1 } let(:plr2) { game.plr2 } let(:active_player) { game.active_player } let(:opposing_player) { game.opposing_player } let(:update) { game.implement_changes } describe '#can_castle?' do it 'returns false when the game starts' do expect(game.can_castle?).to eql false end context 'on empty board' do it 'returns true with just king and rook' do active_player.pieces = [ King.new(:white, [0,4]), Rook.new(:white, [0,7], :king) ] update expect(game.can_castle?).to eql true end it 'returns false when king moved' do king = King.new(:white, [0,4]) king.instance_variable_set(:@moved, true) active_player.pieces = [ Rook.new(:white, [0,7], :king), king ] update expect(game.can_castle?).to eql false end it 'returns false when rook moved' do rook = Rook.new(:white, [0,7], :king) rook.instance_variable_set(:@moved, true) active_player.pieces = [ King.new(:white, [0,4]), rook ] update expect(game.can_castle?).to eql false end it 'returns false with piece inbetween' do active_player.pieces = [ King.new(:white, [0,4]), Pawn.new(:white, [0,5]), Rook.new(:white, [0,7], :king) ] update expect(game.can_castle?).to eql false end it 'returns false when king is in check' do active_player.in_check = true active_player.pieces = [ King.new(:white, [0,4]), Pawn.new(:white, [0,5]), Rook.new(:white, [0,7], :king) ] update expect(game.can_castle?).to eql false end it 'returns false when kingside is under attack' do active_player.pieces = [ King.new(:white, [0,4]), Rook.new(:white, [0,7], :king) ] opposing_player.pieces = [ Pawn.new(:black, [1,6]) ] update expect(game.can_castle?).to eql false end it 'returns false when queenside is under attack' do active_player.pieces = [ King.new(:white, [0,4]), Rook.new(:white, [0,0], :queen) ] opposing_player.pieces = [ Pawn.new(:black, [1,3]) ] update expect(game.can_castle?).to eql false end it 'returns true when queenside rook is under attack on ' do active_player.pieces = [ King.new(:white, [0,4]), Rook.new(:white, [0,0], :queen) ] opposing_player.pieces = [ Rook.new(:black, [1,1]) ] update expect(game.can_castle?).to eql true end end end end describe Player do describe '#castle' do let(:game) { Chess.new } let(:player) { game.plr1 } context 'when kingside' do it do king = King.new(:white, [0,4]) rook = Rook.new(:white, [0,7], :king) player.pieces = [ king, rook ] expect { player.castle(:king) }.to change{ king.position }.from([0,4]).to([0,6]) end it do king = King.new(:white, [0,4]) rook = Rook.new(:white, [0,7], :king) player.pieces = [ king, rook ] expect { player.castle(:king) }.to change{ rook.position }.from([0,7]).to([0,5]) end end context 'when queenside' do it do king = King.new(:white, [0,4]) rook = Rook.new(:white, [0,0], :queen) player.pieces = [ king, rook ] expect { player.castle(:queen) }.to change{ king.position }.from([0,4]).to([0,2]) end it do king = King.new(:white, [0,4]) rook = Rook.new(:white, [0,0], :queen) player.pieces = [ king, rook ] expect { player.castle(:queen) }.to change{ rook.position }.from([0,0]).to([0,3]) end end end end
# encoding: utf-8 require 'inspec/resource' require 'plugins/inspec-init/lib/inspec-init/renderer' module InspecPlugins module ResourcePack class GenerateCLI < Inspec.plugin(2, :cli_command) subcommand_desc 'generate resource_pack', 'Create an InSpec profile that is resource pack' # The usual rhythm for a Thor CLI file is description, options, command method. # Thor just has you call DSL methods in sequence prior to each command. # Let's make a command, 'do_something'. This will then be available # as `inspec my-command do-something # (Change this method name to be something sensible for your plugin.) # First, provide a usage / description. This will appear # in `inspec help my-command`. # As this is a usage message, you should write the command as it should appear # to the user (if you want it to have dashes, use dashes) desc 'resource_pack NAME', 'Create a custom resource pack' option :overwrite, type: :boolean, default: false, desc: 'Overwrites existing directory' def resource_pack(new_resource_pack_name) base_templates_path = File.absolute_path(File.join(__FILE__,'..','..','templates')) resource_pack_template = 'resource_pack' render_opts = { templates_path: base_templates_path, overwrite: options[:overwrite] } renderer = InspecPlugins::Init::Renderer.new(ui, render_opts) vars = { name: new_resource_pack_name } renderer.render_with_values(resource_pack_template, 'resource pack', vars) # ui.exit(:success) # or :usage_error ui.exit end end end end
# Write a method that takes a string argument, and returns true if all of the # alphabetic characters inside the string are uppercase, false otherwise. # Characters that are not alphabetic should be ignored. def uppercase?(str) is_true = true str.each_char do |char| if char =~ /[[:alpha:]]/ is_true = false if char == char.downcase end end is_true end p uppercase?('t') == false p uppercase?('T') == true p uppercase?('Four Score') == false p uppercase?('FOUR SCORE') == true p uppercase?('4SCORE!') == true p uppercase?('') == true
# frozen_string_literal: true class BooksController < ApplicationController def index @books = Book.paginate(:page => params[:page]) end def show if storable_location? store_user_location! end @book = Book.find params[:id] # If the bib record has "n" or "e" in the "Bib Code 3 field" we should not show the "View in catalog" link on the book show page. render json: { :book => @book.as_json, :teacher_sets => @book.teacher_sets.as_json, :show_catalog_link => !%w[n e].include?(@book.bib_code_3) } end def create Book.create(book_params) end def book_details; end private # Strong parameters: protect object creation and allow mass assignment. def book_params params.permit(:call_number, :cover_uri, :description, :details_url, :format, :id, :isbn, :notes, :physical_description, :primary_language, :publication_date, :statement_of_responsibility, :sub_title, :title, :catalog_choice, :bnumber) end end
class TagsController < ApplicationController def index @page_title = "All Video Links" @tags = Tag.all.sort authorize @tags end def show @tag = Tag.find(params[:id]) name = @tag.tag @page_title = "Video Links for #{name}" authorize @tag end end
require 'test_helper' class SwimsetsControllerTest < ActionController::TestCase setup do @swimset = swimsets(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:swimsets) end test "should get new" do get :new assert_response :success end test "should create swimset" do assert_difference('Swimset.count') do post :create, swimset: { comment: @swimset.comment, distance: @swimset.distance, practice_id: @swimset.practice_id, qty: @swimset.qty, rest: @swimset.rest, rori: @swimset.rori } end assert_redirected_to swimset_path(assigns(:swimset)) end test "should show swimset" do get :show, id: @swimset assert_response :success end test "should get edit" do get :edit, id: @swimset assert_response :success end test "should update swimset" do patch :update, id: @swimset, swimset: { comment: @swimset.comment, distance: @swimset.distance, practice_id: @swimset.practice_id, qty: @swimset.qty, rest: @swimset.rest, rori: @swimset.rori } assert_redirected_to swimset_path(assigns(:swimset)) end test "should destroy swimset" do assert_difference('Swimset.count', -1) do delete :destroy, id: @swimset end assert_redirected_to swimsets_path end end
class AddPersonRefToUser < ActiveRecord::Migration def change add_reference :users, :person, index: true, foreign_key: true end end
When /^I am on the (.*) page$/ do |page_description| path = path_for(page_description) visit path end Then /^(.+) within the (.+)$/ do |step_content, context| locator = locator_for(context) within(locator){step(step_content)} end Then /^I should see "([^"]+)"$/ do |content| expect(page).to have_content(content) end When /^I fill in "([^"]+)" with "([^"]+)"$/ do |locator, content| fill_in locator, with: content end When /^I click "([^"]+)"$/ do |locator| click_on locator end When /^I click the (.*) button$/ do |button_description| selector = ".#{description_to_id(button_description)}-button" button = page.find(selector) button.click end When /^I select "([^"]+)" from the "([^"]+)" list$/ do |value, locator| select value, from: locator end Then /^I should see the following (.*) table$/ do |description, expected_table| id = "##{description_to_id(description)}-table" html_table = find(id) actual_table = parse_table(html_table) expected_table.diff! actual_table end Given /^today is (#{DATE})$/ do |date| Timecop.freeze(date) end
# # Copyright 2011 National Institute of Informatics. # # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. module ProposalsHelper def line_number(str) str.scan(/\n/).size end def convert_to_html_tag(str) html_escape(str).gsub(/\n/, "<br/>").gsub(/ /, "&nbsp;") end end
class Api::V1::MonthsController < ApplicationController # respond_to :json # def update # month = Month.find(params[:id]) # # month.update_attributes(month_params) # month.save # end def update month = Month.find(params[:id]) if month.update(month_params) render json: month else render 'Invalid Update', status: 400 end end private def month_params params.permit(:method, :date, :meeting, :name) end end
require 'spec_helper' describe QuestionsController do describe "GET index" do it "renders the index template" do get :index expect(response).to render_template("index") end it "assigns @questions to be an array of questions" do new_question = Question.create(title: "test", content: "test") get :index expect(assigns(:questions)).to eql([new_question]) end end describe "GET new" do before { get :new } it "assigns @question" do expect(assigns(:question)).to be_a_new(Question) end it "renders new template" do expect(response).to render_template("new") end end describe "POST create" do before { @question_parameter = { :title => "test", :content => "test" } } it "creates a Question" do expect { post :create, :question => @question_parameter }.to change{ Question.count }.by(1) end it "assigns @question using params" do post :create, :question => @question_parameter expect(assigns(:question)).to be_a Question end it "redirects to question show" do post :create, :question => @question_parameter question = assigns(:question) response.should redirect_to(question_path(question)) end end describe "GET show" do before { @question = Question.create(:title => "test", :content => "test") } before { get :show, :id => @question.id } it "assigns @question" do assigns(:question).should be_an_instance_of Question end it "renders the show template" do expect(response).to render_template("show") end end describe "GET edit" do before { @question = Question.create(:title => "test", :content => "test") } before { get :edit, :id => @question.id } it "renders the edit template" do expect(response).to render_template("edit") end it "assigns @question" do assigns(:question).should be_an_instance_of Question assigns(:question).id.should eql @question.id end end describe "PUT update" do let (:original_question) { Question.create(:title => "test", :content => "test") } let (:new_question_parameter) { { :title => "new", :content => "new" } } let (:successful_params) { { :id => original_question.id, :question => new_question_parameter } } it "redirects to @question" do put :update, successful_params question = assigns(:question) question.should be_an_instance_of Question response.should redirect_to(question_path(question)) end it "updates the question" do puts new_question_parameter expect { put :update, successful_params }.to change { original_question.reload.title }.from('test').to('new') end end describe "DELETE destroy" do let!(:to_be_deleted) { Question.create(:title => "test", :content => "test") } it "deletes the question" do expect { delete :destroy, :id => to_be_deleted.id }.to change { Question.count }.by(-1) end it "redirects to root" do delete :destroy, :id => to_be_deleted.id response.should redirect_to(root_path) end # it "redirects" end end
class ItemsController < ApplicationController before_action :require_user_logged_in include ParseHtmlHelper def new @item = Item.new @user = current_user api_url = api_item_create_url user_id_str = @user.id.to_s @bookmarklet = 'javascript:void ((function(b){var a=new XMLHttpRequest();a.open("POST","'+api_url+'",true);a.setRequestHeader("Content-Type","application/x-www-form-urlencoded");a.send("id='+user_id_str+'&url="+encodeURIComponent(location.href))})());' end def manual_new() @item = Item.new end def edit() @item = Item.find(params[:id]) end def update() item = Item.find(params[:id]) if item.update(manual_item_params) flash[:success] = 'ๅ•†ๅ“ใฏๆญฃๅธธใซๆ›ดๆ–ฐใ•ใ‚Œใพใ—ใŸ' redirect_to user_path(id: current_user.id) else flash.now[:danger] = 'ๅ•†ๅ“ใฏๆ›ดๆ–ฐใ•ใ‚Œใพใ›ใ‚“ใงใ—ใŸ' render :edit end end def create if params[:manual_new] # ใƒžใƒ‹ใƒฅใ‚ขใƒซ็™ป้Œฒ item = Item.new(user: current_user, url: manual_item_params[:url], name: manual_item_params[:name], price: manual_item_params[:price].to_i, image_url: manual_item_params[:image_url]) else # URLใ‹ใ‚‰่‡ชๅ‹•็™ป้Œฒ url = item_params[:url] parsed_params = parse_html(url) case parsed_params when 1 # URLๆœชๅ…ฅๅŠ›ใฎใ‚จใƒฉใƒผ้€š็Ÿฅ flash[:danger] = 'ๅ•†ๅ“URLใŒๆœชๅ…ฅๅŠ›ใงใ™ใ€‚' redirect_back(fallback_location: root_path) return when 2 # ใƒ‘ใƒผใ‚นๅคฑๆ•—ใฎ้€š็Ÿฅ flash[:danger] = 'ๅ•†ๅ“ใƒšใƒผใ‚ธใฎๅ–ๅพ—ใซๅคฑๆ•—ใ—ใพใ—ใŸใ€‚' redirect_back(fallback_location: root_path) return end item = Item.new(user: current_user, url: url, **parsed_params) end if item.save flash[:success] = 'ๅ•†ๅ“ใ‚’่ฒทใ„็‰ฉใƒชใ‚นใƒˆใซ่ฟฝๅŠ ใ—ใพใ—ใŸใ€‚' else flash[:danger] = 'ใƒ‡ใƒผใ‚ฟใƒ™ใƒผใ‚นใธใฎ่ฟฝๅŠ ใซๅคฑๆ•—ใ—ใพใ—ใŸใ€‚' + item.errors.full_messages.to_s end session[:item_id] = item.id redirect_to current_user end def destroy item = Item.find(params[:id]) if item.destroy flash[:success] = 'ๅ•†ๅ“ใ‚’่ฒทใ„็‰ฉใƒชใ‚นใƒˆใ‹ใ‚‰้™คๅค–ใ—ใพใ—ใŸใ€‚' end redirect_back(fallback_location: root_path) end private def item_params params.require(:item).permit(:url) end def manual_item_params params.require(:item).permit(:url, :name, :price ,:image_url) end end
require File.expand_path(File.join(File.dirname(__FILE__), '../', 'test_helper' )) class EventsTest < ActionController::IntegrationTest def setup factory_scenario :site_with_calendar factory_scenario :calendar_with_event Factory :calendar_event, :title => 'Miles Davis Live', :section => @section @calendar_path = '/' + @section.permalink end test "01 GET :index without any events" do @section.events.published.update_all(:published_at => nil) visit @calendar_path assert_template 'events/index' assert_select '.empty' assert assigns['events'].empty? end test "02 search for a query and apply filters" do %w(tags title body).each do |filter| %(upcoming elapsed recently_added).each do |scope| visit @calendar_path fill_in :filterlist, :with => filter fill_in :time_filterlist, :with => scope click_button 'Search' assert_response :success assert assigns['events'] end end end test "03 GET :index for a date" do end test "04 show event" do visit @calendar_path assert ! assigns['events'].empty? assert_template 'events/index' click_link assigns['events'].first.title assert_response :success assert_template 'events/show' assert assigns['event'] end test "05 try event that's not published" do calendar_event = @section.events.published.first calendar_event.update_attribute(:published_at, nil) visit @calendar_path + '/events/' + calendar_event.permalink assert_response 404 assert_nil assigns['event'] end end
module Base module Step def self.included(base) base.extend ClassMethods # base.singleton_class.extend Forwardable # base.singleton_class.def_delegators base, :Transaction end def run res = nil pending_steps = self.class.steps.filter(&:present?) pending_steps.each do |step| return res = _run_array_step(step) if step.is_a? Array res = _run_normal_step(step) end res end def _run_array_step(step) ActiveRecord::Base.transaction do step_dup = step.dup last_step = step_dup.pop step_dup.each do |step_item| res = send(step_item.name) @result = res @results[step_item.name] = res end send(last_step.name) end rescue StandardError => e @errors << e.message nil end def _run_normal_step(step) res = send(step.name) @result = res @results[step.name] = res res rescue StandardError => e @errors << e.message nil end module ClassMethods def self.extended(_base) @steps = [] @transaction_steps = [] end def step(name) @steps = [] if @steps.nil? return @steps << activity.new(name, false) if name.is_a? Symbol @steps << name end def transaction_step(name) @transaction_steps = [] if @transaction_steps.nil? @transaction_steps << activity.new(name, true) end def steps @steps end def transaction_steps @transaction_steps end def Transaction @transaction_steps = [] # reset transacion step from previous step # Change step method to transaction steps def self.step(name) transaction_step(name) end yield # Revert step method to actual steps def self.step(name) super(name) end transaction_steps end def activity Struct.new(:name, :transaction) end end end end
require 'net/http' class Net::HTTP alias :create :initialize def initialize(*args) logger = Rails.logger def logger.<< log info "HTTP_LOG:#{log}" end create(*args) self.set_debug_output logger end end
class Entry < ActiveRecord::Base include ActionView::Helpers::SanitizeHelper belongs_to :feed # Besure to always destory, not delete to call this. has_many :entry_users, :dependent => :destroy has_many :users, through: :entry_users validates :url, :uniqueness => {:scope => :guid} validates_presence_of :url validates_presence_of :feed_id attr_accessible :author, :categories, :content, :feed_id, :published, :summary, :title, :url, :guid def reading_time html = self.content words = sanitize(html).split.size time = (words/200)*60 minutes = (time/60).to_i seconds = (time % 60).to_i if minutes == 0 return "less than a minute" elsif seconds > 45 return "almost #{minutes+1} minutes" elseif minutes == 1 return "about a minute" else return "almost #{minutes} minutes" end end end
Rails.application.routes.draw do devise_for :users root to: redirect('/products') # sitemap get "sitemap", controller: "sitemaps", action: "show", format: "xml" post "payment", controller: "pages", action: "payment", format: "json" # error pages get "/404", to: "errors#not_found" get "/422", to: "errors#unacceptable" get "/500", to: "errors#internal_error" # concerns concern :paginatable do get '(page/:page)', action: :index, on: :collection, :as => '' match 'search/page/:page', action: :search, on: :collection, via: [:get, :post], as: :search_page end concern :searchable do match 'search', action: :search, on: :collection, via: [:get, :post], as: :search end # /api/... namespace :api, defaults: {format: 'json'} do resources :brands resources :employees resources :events resources :products, concerns: [:paginatable] do collection do get "changed_since/:date", action: "changed_since", as: "recently_changed" get "changed_since/:date/page/:page", action: "changed_since" get "stock_changed_since/:date", action: "stock_changed_since", as: "recently_changed_stock" get "stock_changed_since/:date/page/:page", action: "stock_changed_since" end end resources :product_categories resources :product_categorizations resources :properties resources :sizes resources :stocks resources :stores end # /admin/... namespace :admin do resources :events end # /... resources :api_keys resources :categorizations resources :categories, except: "index" resources :events resources :posts, concerns: [:paginatable, :searchable] resources :properties resources :stocks resources :stores do member do post :get_directions end end resources :brands resources :product_images resources :product_categories resources :sizes resources :products, concerns: [:paginatable, :searchable] do get "featured" => "products#show_featured", :as => "featured" collection do get "tags/:tags", action: "index", as: :tag match '/tags/:tags/search', action: :search, via: [:get, :post], as: :tagged_search get "sale", action: "index_on_sale", as: "on_sale" end resources :product_images resources :properties member do get :edit_product_images get :edit_properties patch :save_properties end end resources :tags # custom routes get "contact", controller: "contact_form", action: "new" post "contact", controller: "contact_form", action: "create" get "gutschein", controller: "pages", action: "gutschein" get "jobs", controller: "pages", action: "jobs" get "privacy_policy", controller: "pages", action: "privacy_policy" get "docs/api", controller: "pages", action: "api_docs" get "retoure", controller: "pages", action: "retoure" get "terms", controller: "pages", action: "terms" get "lockdown", controller: "pages", action: "lockdown" get "beratungstermine", to: redirect("https://www.lunge.de/termine/") get "groessentabelle", controller: "pages", action: "groessentabelle" # frontend routes direct :frontend_root do "https://www.lunge.de" end direct :frontend_appointments do "https://www.lunge.de/termine/" end direct :frontend_stores do "https://www.lunge.de/filialen/" end direct :frontend_blog do "https://www.lunge.de/posts/" end direct :frontend_contact do "https://www.lunge.de/kontakt/" end direct :frontend_jobs do "https://www.lunge.de/jobs/" end end
class SessionsController < ApplicationController skip_before_action :ensure_authenticated_user, only: %w( new create ) def new @user = User.new end def destroy unauthenticate_user redirect_to new_session_url end end
class StylesheetsController < ApplicationController before_action :set_stylesheet, only: [:show, :edit, :update, :destroy] # GET /stylesheets # GET /stylesheets.json def index @stylesheets = Stylesheet.all end # GET /stylesheets/1 # GET /stylesheets/1.json def show end # GET /stylesheets/new def new @stylesheet = Stylesheet.new end # GET /stylesheets/1/edit def edit end # POST /stylesheets # POST /stylesheets.json def create @stylesheet = Stylesheet.new(stylesheet_params) respond_to do |format| if @stylesheet.save format.html { redirect_to @stylesheet, notice: 'Stylesheet was successfully created.' } format.json { render :show, status: :created, location: @stylesheet } else format.html { render :new } format.json { render json: @stylesheet.errors, status: :unprocessable_entity } end end end # PATCH/PUT /stylesheets/1 # PATCH/PUT /stylesheets/1.json def update respond_to do |format| if @stylesheet.update(stylesheet_params) format.html { redirect_to @stylesheet, notice: 'Stylesheet was successfully updated.' } format.json { render :show, status: :ok, location: @stylesheet } else format.html { render :edit } format.json { render json: @stylesheet.errors, status: :unprocessable_entity } end end end # DELETE /stylesheets/1 # DELETE /stylesheets/1.json def destroy @stylesheet.destroy respond_to do |format| format.html { redirect_to @stylesheet.project, notice: 'Stylesheet was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_stylesheet @stylesheet = Stylesheet.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def stylesheet_params params.require(:stylesheet).permit(:name, :description, :body, :project_id) end end
require "test_helper" describe OrganizationCategory do let(:organization_category) { OrganizationCategory.new } it "must be valid" do value(organization_category).must_be :valid? end end
module StatusesHelper def generate_hl7(status) wp_patient = status.wound.patient wp_wound = status.wound run_parser(wp_patient, wp_wound, status) end private def run_parser(patient,wound,status) container = [build_MSH, build_PID(patient), build_PV1, build_OBX] first_msgs = container.inject(:+).map { |string| string.gsub(/\s/, '^') } front_string = first_msgs.join("\r") first_msgs + build_NTE(wound, status) end #HELPERS# def hl7_time DateTime.now.strftime("%y%m%d%R").gsub(/:/,"") end def format_bday(dobtime) dobtime.to_s.gsub(/\s.+$/,"").gsub(/-/,"") end #BUILDERS# def build_MSH ["MSH|^~\&|WA|WAMS|#{hl7_time}|ORU-R01|{recv_app}|{recv_facility}|{message_control_id_here}|{processing_id}|{version_id}"] end def build_PID(patient) ["PID||{patient_identifier_list}|#{patient.name}|#{format_bday(patient.birthdate)}||#{patient.sex}"] end def build_PV1 ["PV1||{patient_class}|{assigned_patient_location}|{attending_doctor}"] end def build_OBX #http://www.interfaceware.com/hl7-standard/hl7-segment-OBX.html ["OBX||{observation_identifier}|{observation_value}|{observation_result_status}|{responsible_observer}|{performing_org}"] end def build_NTE(wound, status) link_NTE_statuses(wound, status).map.with_index(1) do |item, index| "NTE||#{index}|#{item}" end end def link_NTE_statuses(wound, status) [ "Location: #{wound.location}", "Stage: #{status.stage}", "Stage Desc: #{status.stage_description}", "Appearance: #{status.appearance}", "Drainage: #{status.drainage}", "Odor: #{status.odor}", "Color: #{status.color}", "Treatment Response: #{status.treatment_response}", "Treatment: #{status.treatment}", "Length: #{status.length}", "Width: #{status.width}", "Depth: #{status.depth}", "Tunnel: #{status.tunnel}", "Pain: #{status.pain}", "Note: #{status.note}" ] end end
class RemoveFieldsIdsFromGroups < ActiveRecord::Migration def change remove_column :groups, :field_id_1, :integer remove_column :groups, :field_id_2, :integer remove_column :groups, :field_id_3, :integer end end
require File.expand_path('../../../helpers/compute/data_helper', __FILE__) module Fog module Compute class ProfitBricks class Share < Fog::Models::ProfitBricks::Base include Fog::Helpers::ProfitBricks::DataHelper identity :id # properties attribute :edit_privilege, :aliases => 'editPrivilege' attribute :share_privilege, :aliases => 'sharePrivilege' attribute :group_id, :aliases => 'groupId' attribute :resource_id, :aliases => 'resourceId' attr_accessor :options def initialize(attributes = {}) super end def save requires :group_id, :resource_id options = {} options[:editPrivilege] = edit_privilege if edit_privilege options[:sharePrivilege] = share_privilege if share_privilege data = service.add_share(group_id, resource_id, options).body data['group_id'] = group_id data['resource_id'] = resource_id merge_attributes(flatten(data)) true end def update requires :group_id, :resource_id options = {} options[:editPrivilege] = edit_privilege if edit_privilege options[:sharePrivilege] = share_privilege if share_privilege data = service.update_share(group_id, resource_id, options) merge_attributes(flatten(data.body)) true end def delete requires :group_id, :resource_id service.delete_share(group_id, resource_id) true end end end end end
require 'backlog' require 'thor' require 'xmlrpc/client' require 'yaml' require 'pp' module Backlog class Command < Thor @@config = YAML.load_file(File.join(__dir__, '../../config.yaml')) @@proxy = XMLRPC::Client.new_from_hash({ "host" => @@config['backlog']['space'] + ".backlog.jp", "path" => "/XML-RPC", "port" => 443, "use_ssl" => true, "user" => @@config['backlog']['user'], "password" => @@config['backlog']['password'], }) desc "init", "backlog setting." method_option :space, :required => true, :aliases => "-s", :type => :string method_option :user, :required => true, :aliases => "-u", :type => :string method_option :password, :required => true, :aliases => "-p", :type => :string def init @@config['backlog']['space'] = options[:space] @@config['backlog']['user'] = options[:user] @@config['backlog']['password'] = options[:password] open(File.join(__dir__, '../../config.yaml'),"w") do |f| YAML.dump(@@config,f) end puts 'sucusess!!' end desc "project", "get puroject data" method_option :key , :aliases => "-k", :type => :string method_option :id, :aliases => "-i", :type => :numeric def project projects = [] if options[:key] project = @@proxy.call("backlog.getProject", options[:key]) projects.push(project) elsif options[:id] project = @@proxy.call("backlog.getProject", options[:id]) projects.push(project) else projects = @@proxy.call("backlog.getProjects") end # pp projects projects.each do |proj| puts "#{proj['id']} | #{proj['key']} | #{proj['name']} | #{proj['url']}" end end desc "find", "find issue" method_option :projectId, :required => true, :type => :numeric method_option :issueType, :type => :string method_option :milestoneId, :type => :numeric method_option :statusId, :type => :numeric method_option :priorityId, :type => :numeric method_option :assignerId, :type => :numeric def find params = {} options.each do |key, param| puts "param: #{param} , key: #{key}" params[key] = param end issue = @@proxy.call("backlog.findIssue", params) issue.each do |row| milestones = ( row['milestones'] && row['milestones'][0] ) ? "#{row['milestones'][0]['name']}(#{row['milestones'][0]['id']})" : '' assigner = ( row['assigner'] ) ? "#{row['assigner']['name']}(#{row['assigner']['id']})" : '' puts "#{row['id']} | #{row['key']} | #{row['issueType']['name']} | #{row['status']['name']} | #{row['priority']['name']} | #{assigner} | #{milestones} | #{row['summary']} | #{row['start_date']} | #{row['due_date']} | #{row['estimated_hours']} | #{row['actual_hours']} | #{row['url']}" end end desc "issue", "get issuse data" method_option :key, :required => true, :aliases => "-k", :type => :string method_option :update, :aliases => "-U", :type => :boolean, :default => false method_option :summary, :type => :string method_option :parent_issue_id, :type => :numeric method_option :description, :type => :string method_option :start_date, :type => :string method_option :due_date, :type => :string method_option :estimated_hours, :type => :string method_option :actual_hours, :type => :string method_option :issueTypeId, :type => :numeric method_option :issueType, :type => :string method_option :componentId, :type => :numeric method_option :component, :type => :string method_option :versionId, :type => :numeric method_option :version, :type => :string method_option :milestoneId, :type => :numeric method_option :milestone, :type => :string method_option :priorityId, :type => :numeric method_option :priority, :type => :string method_option :assignerId, :type => :numeric method_option :resolutionId, :type => :numeric method_option :comment, :type => :string def issue if options[:update] params = {} options.each do |key, param| puts "param: #{param} , key: #{key}" params[key] = param end issue = @@proxy.call("backlog.updateIssue", params) else issue = @@proxy.call("backlog.getIssue", options[:key]) end puts "ID : #{issue['id']}" puts "Key : #{issue['key']}" puts "Title : #{issue['summary']}" puts "Status : #{issue['status']['name']}" puts "Issue Type : #{issue['issueType']['name']}" puts "ใƒžใ‚คใƒซใ‚นใƒˆใƒผใƒณ: #{issue['milestones'][0]['name']}" puts "้–‹ๅง‹ๆ—ฅ : #{issue['start_date']}" puts "็ต‚ไบ†ๆ—ฅ : #{issue['due_date']}" puts "ไบˆๅฎšๆ™‚้–“ : #{issue['estimated_hours']}" puts "ๅฎŸ็ธพๆ™‚้–“ : #{issue['actual_hours']}" puts "ๆ‹…ๅฝ“่€… : #{issue['assigner']['name']}" end desc "status", "get/update issue status" method_option :key, :required => true, :aliases => "-k", :type => :string method_option :update, :aliases => "-U", :type => :boolean, :default => false method_option :status_id, :type => :numeric method_option :assign_id, :type => :numeric def status if options[:update] return puts "required --status_id optons." if !options[:status_id] params = { :key => options[:key], :statusId => options[:status_id] } params[:assignerId] = options[:assign_id] if options[:assign_id] status = @@proxy.call("backlog.switchStatus", params) end status = @@proxy.call("backlog.getIssue", options[:key]) puts "#{status['key']} #{status['summary']} : #{status['assigner']['name']} (#{status['assigner']['id']}) => #{status["status"]["name"]} " end desc "users", "get project users" method_option :project_id, :required => true, :aliases => "-p", :type => :numeric def users users = @@proxy.call("backlog.getUsers", options[:project_id]) users.each do |user| puts " #{user['id']}:#{user['name']}" end end end end
class CreateRatingCaches < ActiveRecord::Migration[5.1] def change create_table :rating_caches do |t| t.string :cacheable_type t.integer :cacheable_id t.float :avg t.integer :qty t.string :dimension t.timestamps end end end
# frozen_string_literal: true FactoryBot.define do factory :zombie do name 'Peter' hit_points 1000 brains_eaten 3 speed 10 turn_date '08/05/2018'.to_date end end
module Movement def get_sliding_moves (vector, pos, board) x, y = pos[0], pos[1] possible_pos = [[x + vector, y + 1],[x + vector, y - 1]] possible_pos.select! do |pos| (pos.all?{ |val| within_boundaries?(val) }) && pos_empty?(pos) end possible_pos end def within_boundaries?(num) num.between?(0,7) end def pos_empty?(pos) board[pos].empty? end def get_jumping_moves (vector, pos, board, color) x, y = pos[0], pos[1] possible_pos = [[x + vector, y + 2],[x + vector, y - 2]] possible_pos.select! do |position| inter = get_intermediate_pieces(pos, position) position.all?{ |val| within_boundaries?(val)} && pos_empty?(position) &&\ (board[inter].color != board[pos].color && !board[inter].empty?) end possible_pos end def get_intermediate_pieces(pos, possible_pos) [(possible_pos.first + pos.first)/2, (possible_pos.last + pos.last)/2] end end
module Rightboat class SitemapHelper # note: it appears that items order in xml doesn't matter, what matters is priority attribute def self.boats_with_makemodel_slugs Boat.active.order('id DESC').joins(:manufacturer, :model) .select('boats.id, boats.slug, boats.updated_at, manufacturers.slug manufacturer_slug, models.slug model_slug') end def self.active_manufacturer_slugs Manufacturer.joins(:boats).where(boats: {status: :active}) .group('manufacturers.slug').order('COUNT(*) DESC') .pluck('manufacturers.slug') end def self.active_makemodel_slugs Model.joins(:boats).where(boats: {status: :active}) .joins(:manufacturer) .group('manufacturers.slug, models.slug').order('COUNT(*) DESC') .pluck('manufacturers.slug, models.slug') end end end
class AddIndexToBook < ActiveRecord::Migration[5.2] def change add_index :books, :order_id add_index :books, :user_id end end
require_relative '../models/address_book' require 'bloc_record' require_relative 'integrate' class MenuController < BlocRecord attr_reader :address_book include Integrate def main_menu set unless @set_up puts "Main Menu - #{self.count('entry')} entries" puts "0 - View an address book" puts "1 - View all entries" puts "2 - Create an entry" puts "3 - Search for an entry" puts "4 - Import entries from a CSV" puts "5 - Exit" print "Enter your selection: " selection = gets.to_i case selection when 0 system "clear" view_address_book main_menu when 1 system "clear" view_all_entries main_menu when 2 system "clear" create_entry main_menu when 3 system "clear" search_entries main_menu when 4 system "clear" read_csv main_menu when 5 puts "Good-bye!" exit(0) when 666 drop_tables system "clear" main_menu else system "clear" puts "Sorry, that is not a valid input" main_menu end end def view_address_book(j = 0) puts "Which Address Book would you like to see?\n" books = get_table('address_book') books.each_with_index do |book, i| puts "#{i}. #{book[1]}" end ab = gets.to_i puts ab = find("address_book", "name", books[ab][1])[0] res = conventional_join_where('entry', ['address_book'], "entry.address_book_id = #{ab}") for i in j...res.length system 'clear' puts "Name: #{res[i][2]}\nPhone Number: #{res[i][3]}\nEmail: #{res[i][4]}\nAddress Book: #{res[i][6]}" gets end system "clear" puts "End of entries" main_menu end def view_all_entries(j = 0) res = conventional_join('entry', ['address_book']) for i in j...res.length system 'clear' puts "Name: #{res[i][2]}\nPhone Number: #{res[i][3]}\nEmail: #{res[i][4]}\nAddress Book: #{res[i][6]}" entry_submenu(res[i][0]) end system "clear" puts "End of entries" main_menu end def create_entry system "clear" puts "New AddressBloc Entry" print "Name: " name = gets.chomp print "Phone number: " phone = gets.chomp print "Email: " email = gets.chomp print "Address Book: " address_book = gets.chomp begin ab = find("address_book", "name", address_book)[0] rescue self.insert("address_book", {name: address_book}) ab = find("address_book", "name", address_book)[0] end self.insert('entry',{ address_book_id: ab, name: name, phone_number: phone, email: email }) system "clear" puts "New entry created" end def search_entries print "Search by name: " name = gets.chomp res = self.find('name', name) if res.size == 0 puts "Sorry, #{name} isn't in this address book" elsif res.size == 1 puts "Name: #{res[0][2]}\nPhone Number: #{res[0][3]}\nEmail: #{res[0][4]}" search_submenu(res[0][0]) else puts "There are #{res.size} results for #{name}, you need a better system" end end def read_csv print "Enter CSV file to import: " file_name = gets.chomp if file_name.empty? system "clear" puts "No CSV file read" main_menu end begin entry_count = address_book.import_from_csv(file_name).count system "clear" puts "#{entry_count} new entries added from #{file_name}" rescue puts "#{file_name} is not a valid CSV file, please enter the name of a valid CSV file" read_csv end end def entry_submenu(entry_id) puts '-' puts "n - next entry" puts "d - delete entry" puts "e - edit this entry" puts "m - return to main menu" selection = gets.chomp case selection when "n" when "d" delete_entry(entry_id) when "e" edit_entry(entry_id) # entry_submenu(entry_id) when "m" system "clear" main_menu else # system "clear" # puts "#{selection} is not a valid input" # entry_submenu(entry) end end def delete_entry(entry_id) begin self.delete_by_id(entry_id) puts "Deleted" rescue => e puts e end end def edit_entry(entry_id) print "Updated name: " name = gets.chomp print "Updated phone number: " phone_number = gets.chomp print "Updated email: " email = gets.chomp print "Address Book: " address_book = gets.chomp data = {} data['name'] = name if name.length > 0 data['phone_number'] = phone_number if phone_number.length > 0 data['email'] = email if email.length > 0 if address_book.length > 0 begin ab = find("address_book", "name", address_book)[0] rescue self.insert("address_book", {name: address_book}) ab = find("address_book", "name", address_book)[0] end data['address_book_id'] = ab end self.update('entry', entry_id, data) system "clear" puts "Updated entry:" view_all_entries(entry_id) end def search_submenu(entry_id) puts "-\nd - delete entry" puts "e - edit this entry" puts "m - return to main menu" selection = gets.chomp case selection when "d" system "clear" delete_entry(entry_id) main_menu when "e" edit_entry(entry_id) system "clear" main_menu when "m" system "clear" main_menu else system "clear" puts "#{selection} is not a valid input" puts entry.to_s search_submenu(entry_id) end # end end end
module Builder class << self def parse_test(config = 'config.ru') parse(config, 'test') end def parse_development(config = 'config.ru') parse(config, 'development') end def parse_production(config = 'config.ru') parse(config, 'production') end def parse(config, environment) # Set the `RACK_ENV` variable. ENV['RACK_ENV'] = environment # Parse config file. require 'rack' Rack::Builder.parse_file(config) end end end
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require File.expand_path(File.dirname(__FILE__) + '/../facebook_spec_helper') module ProfileSpecHelper def valid_attributes(options={}) options end end describe Profile do include ProfileSpecHelper before(:each) do @member = create_member @profile = new_profile(:member => @member) end it "should not be valid without parent member" do new_profile(:member => nil).should_not be_valid @profile.should be_valid end describe "with facebook data" do include FacebookSpecHelper before(:each) do @profile = create_profile(:member => @member) @fb_profile = {:test => {:test => @member}} end it "should serialize facebook data on write" do @profile.facebook_data = @fb_profile @profile.save @profile.reload.facebook_data[:test][:test].should == @member end describe "synching data" do before(:each) do @fb_user = create_facebook_user end it "should not raise error on sync" do lambda { @profile.sync_with_facebook(@fb_user, :political => 'foo') }.should_not raise_error end it "should sync work history" do lambda { @profile.sync_with_facebook(@fb_user, {}) }.should change(@profile.careers, :count).by(@fb_user.work_history.size) end it "should not duplicate existing work history" do @profile.sync_with_facebook(@fb_user, {}) lambda { @profile.sync_with_facebook(@fb_user, {}) }.should_not change(@profile.careers, :count) end end end end
# -*- coding: utf-8 -*- # ใ‚ฆใ‚ฃใƒณใƒ‰ใ‚ฆใƒ‘ใƒผใƒ„้šŽๅฑคๆง‹้€ ใฎๅญ module Plugin::GUI::HierarchyChild class << self def included(klass) if klass.include?(Plugin::GUI::HierarchyParent) raise "Plugin::GUI::HierarchyChild must be included before the Plugin::GUI::HierarchyParent." end klass.extend(Extended) end end attr_reader :parent # ่ฆชใ‚’ _parent_ ใซ่จญๅฎš # ==== Args # [parent] ่ฆช # ==== Return # self def set_parent(parent) type_strict parent => @parent_class return self if @parent == parent @parent.remove(self) if @parent @parent = parent if self.class.set_parent_event Plugin.call(self.class.set_parent_event, self, parent) end self end def active_class_of(klass) self if is_a? klass end # ๅ…ˆ็ฅ–ใฎใ†ใกใ€ _klass_ ใจ is_a? ้–ขไฟ‚ใซใ‚ใ‚‹ใ‚‚ใฎใ‚’่ฟ”ใ™ # ==== Args # [klass] ๆŽขใ™ใ‚ฏใƒฉใ‚น # ==== Return # ใƒžใƒƒใƒใ—ใŸใ‚ฆใ‚ฃใ‚ธใ‚งใƒƒใƒˆใ‹false def ancestor_of(klass) if self.is_a? klass self elsif @parent.is_a? Plugin::GUI::HierarchyChild @parent.ancestor_of(klass) else @parent.is_a? klass @parent end end # ่ฆชใ‚’ๅ†ๅธฐ็š„ใซ่พฟใ‚Šใ€selfใ‚’ใ‚ขใ‚ฏใƒ†ใ‚ฃใƒ–ใซ่จญๅฎšใ™ใ‚‹ # ==== Args # [just_this] ๅ†ๅธฐ็š„ใซๅ‘ผใณๅ‡บใ•ใ‚ŒใŸใฎใงใฏใชใใ€็›ดๆŽฅใ“ใ‚Œใ‚’ใ‚ขใ‚ฏใƒ†ใ‚ฃใƒ–ใซๆŒ‡ๅฎšใ•ใ‚ŒใŸใชใ‚‰็œŸ # [by_toolkit] UIใƒ„ใƒผใƒซใ‚ญใƒƒใƒˆใฎๅ…ฅๅŠ›ใงใ‚ขใ‚ฏใƒ†ใ‚ฃใƒ–ใซใชใฃใŸๅ ดๅˆ็œŸ # ==== Return # self def active!(just_this=true, by_toolkit=false) @parent.set_active_child(self, by_toolkit).active!(false, by_toolkit) self end module Extended attr_reader :parent_class # set_parentใŒๅ‘ผใฐใ‚ŒใŸๆ™‚ใซ็™บ็”Ÿใ•ใ›ใ‚‹ใ‚คใƒ™ใƒณใƒˆใ‚’่จญๅฎšใ™ใ‚‹ def set_parent_event(event = nil) if event @set_parent_event = event else @set_parent_event end end # ่ฆชใ‚ฏใƒฉใ‚นใ‚’่จญๅฎšใ™ใ‚‹ใ€‚่ฆชใซใฏใ“ใฎใ‚ฏใƒฉใ‚นใฎใ‚คใƒณใ‚นใ‚ฟใƒณใ‚นไปฅๅค–่ชใ‚ใชใ„ # ==== Args # [klass] ่ฆชใ‚ฏใƒฉใ‚น def set_parent_class(klass) @parent_class = klass end # ่ฆชใ‚ฏใƒฉใ‚นใ‚’ๅ†ๅธฐ็š„ใซใŸใฉใฃใฆใ„ใฃใฆใ€ไธ€็•ชไธŠใฎ่ฆชใ‚ฏใƒฉใ‚นใ‚’่ฟ”ใ™ def ancestor if @parent_class.respond_to? :ancestor @parent_class.ancestor else @parent_class end end # ็พๅœจใ‚ขใ‚ฏใƒ†ใ‚ฃใƒ–ใชใ‚คใƒณใ‚นใ‚ฟใƒณใ‚นใ‚’่ฟ”ใ™ # ==== Return # ใ‚ขใ‚ฏใƒ†ใ‚ฃใƒ–ใชใ‚คใƒณใ‚นใ‚ฟใƒณใ‚นๅˆใฏnil def active widget = ancestor.active widget.active_class_of(self) if widget end end end
puts 'Seeding PSP0.1 postmortem script' psp00 = Script.where(name: "PSP0.1 Postmortem Script", level_number: LevelNumber.find(2)).first_or_create! psp00.purpose = 'To Guide the PSP postmortem process' psp00.entry_criteria = <<-HTML <ul> <li>Problem description and <a href="./edit">requirements statement</a></li> <li>PSP0.1 <a href="./">Project Plan Summary</a> form with program size and development time data</li> <li>Completed <a href="time_logs">Time</a> and <a href="defects">Defect</a> recording logs </li> <li>A tested and running program that conforms to the <a href="/coding_standard">Coding standard</a> and size counting standards </li> </ul> HTML psp00.exit_criteria = <<-HTML <ul> <li>A thoroughly tested program that conforms to the <a href="/coding_standard">Coding standard</a> and size counting standards</li> <li>Completed <a href="./">Project Plan Summary</a> form</li> <li>Completed <a href="time_logs">Time Recording log</a></li> <li>Completed <a href="pip_form">PIP forms</a> improvement suggestions, and lessons learned</li> </ul> HTML psp00.save psp00step1 = Step.new(number: 1, activity: 'Defect Recording') psp00step1.description = <<-HTML <ul> <li>Review the <a href="./">Project Plan Summary</a> to verify that all of the defects found in each phase were recorded.</li> <li>Using your best recollection, record any omitted defects.</li> </ul> HTML psp00step1.save psp00step2 = Step.new(number: 2, activity: 'Defect Data Consistency') psp00step2.description = <<-HTML <ul> <li>Check that the data on every defect in the <a href="defects">Defect Recording log</a> are accurate and complete.</li> <li>Verify that the numbers of defects injected and removed per phase are reasonable and correct.</li> <li>Using your best recollection, correct any missing or incorrect defect data.</li> </ul> HTML psp00step2.save psp00step3 = Step.new(number: 3, activity: 'Size') psp00step3.description = <<-HTML <ul> <li>Count the size of the completed program.</li> <li>Determine the size of the base, deleted, modified, reused, total, and new reusable code.</li> <li>Enter these data in the <a href="./">Project Plan Summary</a> form.</li> </ul> HTML psp00step3.save psp00step4 = Step.new(number: 4, activity: 'Time') psp00step4.description = <<-HTML <ul> <ul> <li>Review the completed <a href="time_logs">Time Recording log</a> for errors or omissions.</li> <li>Using your best recollection, correct any missing or incomplete time data.</li> </ul> HTML psp00step4.save psp00.steps = [psp00step1,psp00step2,psp00step3,psp00step4]
json.array!(@reviews) do |review| json.extract! review, :id, :gig_id, :user_id, :subject, :body, :communication_rating, :service_rating, :recommend_rating json.url review_url(review, format: :json) end
require 'test_helper' class PublicSuffixTest < Minitest::Unit::TestCase def test_self_parse_a_domain_with_tld_and_sld domain = PublicSuffix.parse("example.com") assert_instance_of PublicSuffix::Domain, domain assert_equal "com", domain.tld assert_equal "example", domain.sld assert_equal nil, domain.trd domain = PublicSuffix.parse("example.co.uk") assert_instance_of PublicSuffix::Domain, domain assert_equal "co.uk", domain.tld assert_equal "example", domain.sld assert_equal nil, domain.trd end def test_self_parse_a_domain_with_tld_and_sld_and_trd domain = PublicSuffix.parse("alpha.example.com") assert_instance_of PublicSuffix::Domain, domain assert_equal "com", domain.tld assert_equal "example", domain.sld assert_equal "alpha", domain.trd domain = PublicSuffix.parse("alpha.example.co.uk") assert_instance_of PublicSuffix::Domain, domain assert_equal "co.uk", domain.tld assert_equal "example", domain.sld assert_equal "alpha", domain.trd end def test_self_parse_a_domain_with_tld_and_sld_and_4rd domain = PublicSuffix.parse("one.two.example.com") assert_instance_of PublicSuffix::Domain, domain assert_equal "com", domain.tld assert_equal "example", domain.sld assert_equal "one.two", domain.trd domain = PublicSuffix.parse("one.two.example.co.uk") assert_instance_of PublicSuffix::Domain, domain assert_equal "co.uk", domain.tld assert_equal "example", domain.sld assert_equal "one.two", domain.trd end def test_self_parse_a_fully_qualified_domain_name domain = PublicSuffix.parse("www.example.com.") assert_instance_of PublicSuffix::Domain, domain assert_equal "com", domain.tld assert_equal "example", domain.sld assert_equal "www", domain.trd end def test_private_domains_are_enabled_by_default domain = PublicSuffix.parse("www.example.blogspot.com") assert_equal "blogspot.com", domain.tld end def test_disable_support_for_private_domains begin PublicSuffix::List.private_domains = false domain = PublicSuffix.parse("www.example.blogspot.com") assert_equal "com", domain.tld ensure PublicSuffix::List.private_domains = true end end def test_self_parse_a_domain_with_custom_list list = PublicSuffix::List.new list << PublicSuffix::Rule.factory("test") domain = PublicSuffix.parse("www.example.test", list) assert_equal "test", domain.tld assert_equal "example", domain.sld assert_equal "www", domain.trd end def test_self_parse_raises_with_invalid_domain error = assert_raises(PublicSuffix::DomainInvalid) { PublicSuffix.parse("example.qqq") } assert_match %r{example\.qqq}, error.message end def test_self_parse_raises_with_unallowed_domain error = assert_raises(PublicSuffix::DomainNotAllowed) { PublicSuffix.parse("example.ke") } assert_match %r{example\.ke}, error.message end def test_self_raises_with_uri error = assert_raises(PublicSuffix::DomainInvalid) { PublicSuffix.parse("http://google.com") } assert_match %r{http://google\.com}, error.message end def test_self_valid assert PublicSuffix.valid?("google.com") assert PublicSuffix.valid?("www.google.com") assert PublicSuffix.valid?("google.co.uk") assert PublicSuffix.valid?("www.google.co.uk") end # Returns false when domain has an invalid TLD def test_self_valid_with_invalid_tld assert !PublicSuffix.valid?("google.qqq") assert !PublicSuffix.valid?("www.google.qqq") end def test_self_valid_with_fully_qualified_domain_name assert PublicSuffix.valid?("google.com.") assert PublicSuffix.valid?("google.co.uk.") assert !PublicSuffix.valid?("google.qqq.") end end
#============================================================================== # ** Game_Map #------------------------------------------------------------------------------ # This class handles maps. It includes scrolling and passage determination # functions. The instance of this class is referenced by $game_map. #============================================================================== class Game_Map #-------------------------------------------------------------------------- # * Overwrite: Frame Update #-------------------------------------------------------------------------- alias update_gamemap_lapse update def update(main = false) return update_tactic(main) if SceneManager.tactic_enabled? return update_timestop if SceneManager.time_stopped? return update_gamemap_lapse(main) end #-------------------------------------------------------------------------- # * Frame Update # tag: tactic(game_map update) #-------------------------------------------------------------------------- def update_tactic(main = false) refresh if @need_refresh update_interpreter if main update_scroll update_parallax @screen.update end #-------------------------------------------------------------------------- def update_timestop refresh if @need_refresh update_scroll update_parallax @screen.update update_drops unless $game_system.time_stopper.nil? $game_system.time_stopper.update $game_system.time_stopper.update_battler end @timestop_timer += 1 if @timestop_timer >= $game_system.timestop_duration $game_system.resume_time @timestop_timer = 0 end end #-------------------------------------------------------------------------- end
module Api module V1 class AgentsController < ApplicationController def index render json: Agent.all end def show render json: Agent.find(params[:id]) end def create agent = Agent.new(params.require(:agent).permit(:alias,:barcode)) if agent.save render json: {message: "Created Agent!", status: 200} else render json: {message: agent.errors.full_messages, status: 500} end end end end end
class Image < ApplicationRecord mount_uploader :image_file, ImageFileUploader # Direct associations has_many :comments, :foreign_key => "photo_id", :dependent => :destroy has_many :likes, :foreign_key => "photo_id", :dependent => :destroy belongs_to :posting_user, :class_name => "User", :counter_cache => true # Indirect associations has_many :fans, :through => :liking_users, :source => :following has_many :followers, :through => :posting_user, :source => :following has_many :liking_users, :through => :likes, :source => :liking_user has_many :commenting_users, :through => :comments, :source => :commenting_user # Validations end
RSpec.describe Game do let(:player1) { spy :player } let(:player2) { spy :player } subject(:game) { Game.new(player1, player2)} describe '#player 1' do it 'creates an array of players' do expect(game.player1).to be player1 end end describe '#player 2' do it 'creates an array of players' do expect(game.player2).to be player2 end end describe '#attack_on' do it 'causes player to attack other player' do game.attack expect(player2).to have_received(:hurt) end end end
class API def search(q) require 'GiphyClient' urls = [] api_instance = GiphyClient::DefaultApi.new api_key = "dc6zaTOxFJmzC" # Giphy API Key. opts = { limit: 10, # The maximum number of records to return. offset: 0, # An optional results offset. Defaults to 0. rating: "pg", # Filters results by specified rating. lang: "en", # Specify default country for regional content; use a 2-letter ISO 639-1 country code. See list of supported languages <a href = \"../language-support\">here</a>. fmt: "json" # Used to indicate the expected response format. Default is Json. } begin result = api_instance.gifs_search_get(api_key, q, opts).to_hash items = result[:data] items.each do |i| urls << i[:images][:original][:url] end rescue GiphyClient::ApiError => e puts "Exception when calling DefaultApi->gifs_search_get: #{e}" end urls end end
class ActIndicatorRelation < ActiveRecord::Base belongs_to :user belongs_to :act, foreign_key: :act_id, touch: true belongs_to :indicator, foreign_key: :indicator_id, touch: true belongs_to :unit, foreign_key: :unit_id belongs_to :relation_type has_many :measurements, dependent: :destroy validates_with EndDateValidator accepts_nested_attributes_for :measurements, allow_destroy: true def self.get_dates(act, indicator) @dates = where(act_id: act.id, indicator_id: indicator.id).pluck(:start_date, :end_date, :deadline) @dates.flatten.map { |d| d.to_date.to_formatted_s(:long).to_s rescue nil } if @dates.present? end def target_unit_symbol unit.symbol end def target_unit_name unit.name end end
FactoryBot.define do factory :user do name { Faker::Name.name.truncate(16) } email { Faker::Internet.unique.email } password { Faker::Internet.password } admission_year { Faker::Number.between(90, 120) } factory :test_user do name { :test } email { 'test@plus.nctu' } password { 'youshallnotpass' } end factory :admin_user do name { :admin } email { 'admin@plus.nctu' } password { 'superpowerfulpassword' } role { 1 } end end end
require 'spec_helper' feature "searching for coffee shops" do before do visit root_path end context "with a valid post code" do before do fill_in "search-input", :with => "E2 8RS" click_button "search-submit" end scenario "show results", :vcr do expect(page).to have_css("#shop-table tbody tr") expect(page).to have_css("div#map") end scenario "sort by nearest", :vcr do distance1 = page.all(:css, 'td.distance').first.text.to_i distance2 = page.all(:css, 'td.distance').last.text.to_i expect(distance1).to be < distance2 end scenario "sort by popular", :vcr do click_link "btn-popular" rating1 = page.all(:css, 'td.rating').first.text.to_i rating2 = page.all(:css, 'td.rating').last.text.to_i expect(rating1).to be > rating2 end end context "with an invalid post code" do scenario "show no results", :vcr do fill_in "search-input", :with => "Nothing" click_button "search-submit" expect(page).to have_content("No results found") end end end
module DLMSTrouble class ActionResult VALUES = { 0 => :success, 1 => :hardware_fault, 2 => :temporary_failure, 3 => :read_write_denied, 4 => :object_undefined, 9 => :object_class_inconsistent, 11 => :object_unavailable, 12 => :type_unmatched, 13 => :scope_of_access_violated, 14 => :data_block_unavailable, 15 => :long_action_aborted, 16 => :no_long_action_in_progress, 250 => :other_reason } def self.decode(input) result = VALUES[input.read(1).unpack("C")] if result.nil? raise end self.new(result) end def initialize(value) if !VALUES.include? value raise end @value = value end def encode [VALUES.values.detect{|v|v == @value}].pack("C") end end end
FactoryGirl.define do factory :operation do invoice_num "Anynumber" invoice_date DateTime.now amount 25 operation_date DateTime.now kind "anything1;anything2" status "anystatus" association :company end end
module HideFromBullet def skip_bullet if defined?(Bullet) previous_value = Bullet.enable? Bullet.enable = false end yield ensure Bullet.enable = previous_value if defined?(Bullet) end end
control 'node exporter should be installed' do describe file('/opt/prometheus//bin/node_exporter') do it { should be_file } it { should be_executable } end end control 'it should be running under ssystemd' do describe file('/etc/systemd/system/prometheus-node_exporter.service') do it { should be_file } its(:content) { should match /MAINPID/ } end describe file('/etc/default/prometheus-node_exporter') do it { should be_file } its(:content) {should match /ARGS/ } end end
class InvitationsController < ApplicationController before_action :set_company before_action :check_admin # GET /invitations/new def new @invitation = Invitation.new end # POST /invitations # POST /invitations.json def create @invitation = Invitation.new(invitation_params) respond_to do |format| if @invitation.save @invitation.update_attribute(:company_id, @company.id) # Send email notification ExampleMailer.new_invitation(@invitation).deliver format.html { redirect_to root_path, notice: 'Invitation was successfully created.' } format.json { render :new, status: :created, location: @invitation } else format.html { render :new } format.json { render json: @invitation.errors, status: :unprocessable_entity } end end end private def set_company @company = Company.find(params[:id]) end # Check if the current user is an admin or the admin of the company def check_admin if !(current_user.company_admin? && current_user.company == @company) && !current_user.admin? redirect_to projects_path, :alert => "You can not invite people to this company." and return end end # Never trust parameters from the scary internet, only allow the white list through. def invitation_params params.require(:invitation).permit(:company_id, :email) end end
# frozen_string_literal: true class SlackIdImporter def initialize(user) @user = user end SLACK_API_URL = 'https://slack.com/api/users.lookupByEmail?email=' def perform if @user.slack_id.blank? url = "#{SLACK_API_URL}#{@user.email}&token=#{ENV['SLACK_OAUTH_TOKEN']}" uri = URI(url) response = Net::HTTP.get(uri) output = JSON.parse(response) @user.update(slack_id: output['user']['id']) end end end
CarrierWave.configure do |config| config.fog_credentials = { provider: 'AWS', # required aws_access_key_id: ENV["S3_ID"], # required aws_secret_access_key: ENV["S3_SecretKey"], # required endpoint:'http://s3-us-west-2.amazonaws.com', region: 'us-west-2' } config.fog_directory = ENV["S3_Bucket"] # required end
require 'commander' require_relative "edit" module ClusterFsck module Commands class Create include ClusterFsckEnvArgumentParser def run_command(args, options = {}) raise ArgumentError, "must provide a project name" if args.empty? set_cluster_fsck_env_and_key_from_args(args) obj = s3_object(key) raise ConflictError, "#{key} already exists!" if obj.exists? obj.write('') Edit.new.run_command(args) end end end end
require 'soap/lc/wsdl/parser' require 'soap/lc/request' module SOAP class WSDL attr_reader :parse def initialize(uri, binding) #:nodoc: @parse = SOAP::WSDL::Parser.new(uri) @binding = binding end # Call a method for the current WSDL and get the corresponding SOAP::Request # # Example: # wsdl = SOAP::LC.new.wsdl("http://...") # request = wsdl.myMethod(:param1 => "hello") # # => #<SOAP::Request:0xNNNNNN> def method_missing(id, *args) request(@binding).call(id.id2name, args[0]) end # Return available SOAP operations def operations request(@binding).operations end # Call a method for the current WSDL and get the corresponding SOAP::Request # # Example: # wsdl = SOAP::LC.new.wsdl("http://...") # request = wsdl.call("myMethod", { :param1 => "hello" }) # # => #<SOAP::Request:0xNNNNNN> def call(name, args = {}) request(@binding).call(name, args) end # Get a SOAP::Request object for the current WSDL # # Example: # wsdl = SOAP::LC.new.wsdl("http://...") # request = wsdl.request # # => #<SOAP::Request:0xNNNNNN> def request(binding = nil) SOAP::Request.new(@parse, binding) end end end
FactoryBot.define do factory :dealer do name { Faker::Name.name } sf_id { SecureRandom.uuid } category { Dealer::CATEGORIES[:point_of_sale] } end end
class Api::CompaniesController < ApplicationController def index if params[:page] render_companies_by_page(Company.order(:name), params[:page]) return end render_companies_by_page(Company.order(:name), 1) end # Using json style guide https://google.github.io/styleguide/jsoncstyleguide.xml def show company = Company.find_by_id(params[:id]) if company.blank? render( json: { error: { code: 404, message: "Company not found", errors: { message: "Company not found" } } }) return end render json: { data: { kind: Company.name, id: company.id, company: company.as_json(include: :industry) } } end def search query = params[:q] page = params[:page] or 1 if query.blank? render_companies_by_page(Company.order(:name), 1) return end company_query = Company.where('name ILIKE ?', "%#{query}%").order('id DESC') # TODO: this search sucks since we grab a bunch of rando companies. # Disable this for now # external_companies = Api::CompaniesHelper.search_external_companies(query) # total_companies = companies + external_companies render_companies_by_page(company_query, page) end def render_companies_by_page(company_query, page) if company_query.page(page).out_of_range? render json: { error: { code: 400, message: "Page out of range", errors: { message: "Page out of range" } } } return end requested_page = company_query.page(page) items_per_page = requested_page.limit_value next_page = requested_page.next_page prev_page = requested_page.prev_page total_pages = requested_page.total_pages current_item_count = requested_page.count render json: { data: { kind: Company.name, items: requested_page.map { |c| c.as_json(include: :industry) }, current_item_count: current_item_count, items_per_page: items_per_page, start_index: 1, page_index: page, next_page: next_page, prev_page: prev_page, total_pages: total_pages } } end end
module Sandra module Indices module ClassMethods #index_on :latitude, :group_by => :sector, :sub_group => :longitude # by_index :latitude, :sector => "0/0", :longitude => {:from => 0.1, :to => 0.2}, # by_index :latitude, :sector => ["0/0", "0/1"], :longitude => 0.1, :latitude => {:from => ... # # by_index :latitude, :longitude => 0.1, :latitude => {:from => ... # by_index :latitude, :longitude => {:from => ...} ... # by_index :name, :name => "Blah" # by_index :name, :name => {:from => "blah", :to => "Blubb"} # @indices << {index_key => {:key => key, :sup_col => sup_col, :column_attr => column_attr}} def by_index(index_name, options = {}) puts "Search by range" time = Time.now index = self.indices[index_name] raise "Index #{index_name} not existant" unless index family_name = "#{self.to_s}Index#{index_name.to_s.camelcase}" key = index[:key].nil? ? nil : options[index[:key]] sup_col = index[:sup_col].nil? ? nil : options[index[:sup_col]] column_attr = options[index[:column_attr]] count = options[:count] if index[:sup_col] type = @attribute_types[index[:sup_col].to_s] if sup_col.is_a? Hash start = pack(sup_col[:from], type) finish = pack(sup_col[:to], type) elsif sup_col start = finish = pack(sup_col, type) else start = finish = nil end else type = @attribute_types[index[:column_attr].to_s] if column_attr.is_a? Hash start = pack(column_attr[:from], type) finish = pack(column_attr[:to], type) elsif column_attr start = finish = pack(column_attr, type) else start = finish = nil end end puts "Before request: #{Time.now - time}" if key # Perform multi_get unless key.is_a? Array key = [key] end puts "Performing multi_get, type #{type}" result = connection.multi_get(family_name, key, :start => start, :finish => finish, :batch_size => 50, :type => type, :keys_at_once => 1000, :count => nil, :no_hash_return => true).values.compact else # Perform get_range over all keys puts "Performing get_range" result = connection.get_range(family_name, :start => start, :finish => finish, :key_count => count, :batch_size => 50).values.compact end puts "After request: #{Time.now - time}" if index[:sup_col] if column_attr.is_a? Hash start = column_attr[:from] finish = column_attr[:to] elsif column_attr start = finish = column_attr else start = finish = nil end result = result.collect(&:values).flatten end puts "Got #{result.count} results" puts "Until manual filtering: #{Time.now - time}" if start puts "Perform manual filtering" type = @attribute_types[index[:column_attr].to_s] result.reject!{|entry| (start and unpack(entry.keys.first, type) < start) or (finish and unpack(entry.keys.first, type) > finish)} end puts "After manual filtering: #{Time.now - time}" if options[:index_data_only] result.inject({}) {|hash,v| hash.merge(Marshal.load(v.values.first))} #result.collect{|r| Marshal.load(r.values.first)} elsif self.super_column_name raise "Not supported yet" else result_keys = result.collect{|r| Marshal.load(r.values.first).values.collect{|v| v[:key]}}.flatten.compact result = [] multi_get(result_keys, :keys_at_once => 1000, :batch_size => 30) end end def index_on(index_key, options = {}, &block) key = options[:group_by] sup_col = options[:sub_group] column_attr = index_key raise "Index attribute #{index_key} does not exist in #{self.to_s}" unless self.method_defined? column_attr raise "Index subgroup #{sup_col} does not exist in #{self.to_s}" unless sup_col.nil? or self.method_defined? sup_col raise "Index group #{key} does not exist in #{self.to_s}" unless key.nil? or self.method_defined? key validates(index_key, :presence => true) validates(key, :presence => true) if key validates(sup_col, :presence => true) if sup_col index_name = options[:name] || index_key @indices[index_name] = {:key => key, :sup_col => sup_col, :column_attr => column_attr} if block_given? @indices[index_name][:block] = block end end end module InstanceMethods def drop_index_info(col_family = nil) ind_ind_cf = "#{self.class.to_s}Indices" if self.class.super_column_name self.class.connection.remove(ind_ind_cf, attributes[self.class.key.to_s].to_s, attributes[self.class.super_column_name.to_s].to_s, (col_family.nil? ? nil : [col_family.to_s])) else self.class.connection.remove(ind_ind_cf, attributes[self.class.key.to_s].to_s, (col_family.nil? ? nil : col_family.to_s)) end end def load_index_info(col_family = nil) ind_ind_cf = "#{self.class.to_s}Indices" data = if self.class.super_column_name self.class.connection.get(ind_ind_cf, attributes[self.class.key.to_s].to_s, attributes[self.class.super_column_name.to_s].to_s, (col_family.nil? ? nil : [col_family.to_s])) else self.class.connection.get(ind_ind_cf, attributes[self.class.key.to_s].to_s, (col_family.nil? ? nil : col_family.to_s)) end if col_family Marshal.load(data) else index_info = {} data.each do |k,v| index_info[k] = Marshal.load(v) end index_info end end def write_index_info(col_family, key, sup_col, column, entry_id) ind_ind_cf = "#{self.class.to_s}Indices" ind_ind_entry = Marshal.dump({ :key => key, :sup_col => sup_col, :column => column, :entry_id => entry_id }).to_s if self.class.super_column_name self.class.connection.insert(ind_ind_cf, attributes[self.class.key.to_s].to_s, attributes[self.class.super_column_name.to_s].to_s, {col_family.to_s => ind_ind_entry}) else self.class.connection.insert(ind_ind_cf, attributes[self.class.key.to_s].to_s, {col_family.to_s => ind_ind_entry}) end end #indices << {:key => key, :sup_col => sup_col, :column_attr => column_attr} def create_index_entry destroy_index_entry self.class.indices.each do |k,index| # Create index data data = {} data[:key] = attributes[self.class.key.to_s].to_s if self.class.super_column_name data[:super_column] = attributes[self.class.super_column_name.to_s].to_s end if index[:block] data = index[:block].call(self).merge(data) end # Set index family parameters column_attr = (attributes[index[:column_attr].to_s] || self.send(index[:column_attr].to_s)).to_s col_family = "#{self.class.to_s}Index#{k.to_s.camelcase}" key = index[:key].nil? ? SimpleUUID::UUID.new.to_s : (attributes[index[:key].to_s] || self.send(index[:key].to_s)).to_s sup_col = index[:sup_col].nil? ? nil : (attributes[index[:sup_col].to_s] || self.send(index[:sup_col].to_s)).to_s # Handle possible ambigous index entries if index[:key] # Load existing index entry oldentry = if sup_col self.class.connection.get(col_family, key, sup_col, column_attr) else self.class.connection.get(col_family, key, column_attr) end oldentry = oldentry.nil? ? {} : Marshal.load(oldentry) # Append new entry entry_id = SimpleUUID::UUID.new.to_s oldentry[entry_id] = data entry = {column_attr => Marshal.dump(oldentry)} else # Just create new entry entry_id = nil entry = {column_attr => Marshal.dump(data)} end # Save index entry if sup_col self.class.connection.insert(col_family, key, {sup_col => entry}) else self.class.connection.insert(col_family, key, entry) end # Store index metainfo write_index_info col_family, key, sup_col, column_attr, entry_id end end def destroy_index_entry metadata = load_index_info metadata.each do |k,v| index_cf = k.to_sym key = v[:key] column = v[:column] sup_column = v[:sup_col] entry_id = v[:entry_id] req_sup_col, req_col = (sup_column ? [sup_column, column] : [column, nil]) if entry_id data = self.class.connection.get(index_cf, key, req_sup_col, req_col) next unless data data = Marshal.load(data) data.delete(entry_id) data = (data.empty? ? nil : Marshal.dump(data)) if data.nil? self.class.connection.remove(index_cf, key, req_sup_col, req_col) else if sup_column self.class.connection.insert(index_cf, key, sup_column, {column => data}) else self.class.connection.insert(index_cf, key, {column => data}) end end else self.class.connection.remove index_cf, key, req_sup_col, req_col end end drop_index_info end end end end
class AddAccessTokenToAdminUsers < ActiveRecord::Migration[5.2] def change add_column :admin_users, :access_token, :string, default: nil end end
class WoPart < ActiveRecord::Base belongs_to :workorder belongs_to :inventory after_create :remove_part_from_the_stock def remove_part_from_the_stock inv = self.inventory inv.qty_in_stock -= self.qty_used inv.save! end end
class UserInfoType < ActiveRecord::Base belongs_to :user def self.info_types_of_logon_user(user) user.user_info_types end def self.info_type_ids_of_logon_user(user) return user.user_info_types.collect{|user_info_type| user_info_type.info_type_id} end def self.update_user_info_types(user,user_select_info_type_ids) #่Žทๅ–็”จๆˆท็Žฐๆœ‰็š„ๅบ”็”จ user_info_type_ids = UserInfoType.info_type_ids_of_logon_user(user) #่Žทๅ–้œ€่ฆๅˆ ้™ค็š„ๅบ”็”จๅ’Œ้œ€่ฆๆ–ฐๅปบ็š„ๅบ”็”จใ€‚ user_info_type_ids_create = user_select_info_type_ids - user_info_type_ids user_info_type_ids_delete = user_info_type_ids - user_select_info_type_ids #ๆ–ฐๅปบ็”จๆˆทๅบ”็”จๅ…ณ็ณป user_info_type_ids_create.each{|info_type_id| UserInfoType.create(:user_id=>user.id,:info_type_id=>info_type_id)} unless user_info_type_ids_create.blank? #ๅˆ ้™ค็”จๆˆทๅบ”็”จๅ…ณ็ณป user_info_type_ids_delete.each{|info_type_id| UserInfoType.find_by_user_id_and_info_type_id(user.id,info_type_id).destroy} unless user_info_type_ids_delete.blank? end end
module Interpreter class Formatter private_class_method :new class << self def output(value) case value when NilClass then 'null' when String then "\"#{value}\"" when Numeric then format_numeric value when SdArray then format_sd_array value else value.to_s end end def interpolated(value) case value when TrueClass then 'ใฏใ„' when FalseClass then 'ใ„ใ„ใˆ' when Numeric then format_numeric value when SdArray then format_sd_array value else value.to_s end end private def format_numeric(value) value.to_i == value ? value.to_i.to_s : value.to_s end def format_sd_array(value) "{#{value.map { |k, v| "#{output k.numeric? ? k.to_f : k}: #{output v}" } .join ', '}}" end end end end
class Community < ApplicationRecord extend FriendlyId friendly_id :name, use: :slugged has_many :posts belongs_to :user end
class AddThroughForAffiliateCertification < ActiveRecord::Migration def change add_column :affiliate_certifications, :affiliate_id, :integer add_column :affiliate_certifications, :certificat_id, :integer end end
#orange_tree.rb require_relative 'tree' class OrangeTree < Tree attr_reader :oranges def initialize super @max_growable_age = 15 @death_age = 20 @annual_growth = 10 @min_growable_age = 5 end def add_fruit 10.times do @fruits << Orange.new end end end
# frozen_string_literal: true # typed: false require 'spec_helper' describe AlphaCard::Attribute do class User include AlphaCard::Attribute attribute :name attribute :activated, values: [true, false] attribute :role, default: 'user', writable: false end class Moderator < User attribute :id, type: Integer, default: 11 attribute :status, default: 'global', writable: false attribute :role, default: 'moderator', writable: false end class Admin < Moderator attribute :role, default: 'admin', types: [String, Symbol] attribute :birthday, format: /^\d{2}-\d{2}-\d{4}$/ attribute :created_at, required: true remove_attribute :status end context 'User' do it 'must set attributes from arguments on initialization' do user = User.new(name: 'John', activated: true) expect(user.name).to eq('John') expect(user.activated).to be_truthy end it 'must ignore non-writable attributes on initialization' do user = User.new(role: 'test') expect(user.role).to eq('user') end it 'must set default values' do expect(User.new.role).to eq('user') end it 'must not create writers for non-writable attributes' do expect { User.new.role = '111' }.to raise_error(NoMethodError) end it 'must raise an error on wrong values' do expect { User.new(activated: 'wrong') }.to raise_error(AlphaCard::InvalidAttributeValue) end end context 'Moderator' do it 'must inherit attributes' do moderator = Moderator.new(name: 'John', activated: true) expect(moderator.attributes).to eq(name: 'John', activated: true, id: 11, role: 'moderator', status: 'global') end it 'must override attributes default values' do expect(Moderator.new.role).to eq('moderator') end it 'must validate typed attributes' do expect { Moderator.new.id = '123' }.to raise_error(AlphaCard::InvalidAttributeType) end end context 'Admin' do it 'must inherit superclass attributes' do admin = Admin.new(name: 'John', activated: true) expect(admin.name).to eq('John') expect(admin.id).to eq(11) expect(admin.activated).to be_truthy end it 'must override superclass attributes default values' do expect(Admin.new.role).to eq('admin') end it 'must override superclass attributes options (make writable)' do admin = Admin.new admin.role = 'something_new' expect(admin.role).to eq('something_new') end it 'must override superclass attributes options (make typable)' do expect(Admin.new(role: 'admin').role).to eq('admin') expect(Admin.new(role: :admin).role).to eq(:admin) expect { Admin.new(role: 123) }.to raise_error(AlphaCard::InvalidAttributeType) end it 'must remove attributes' do expect { Admin.new.status = 'local' }.to raise_error(NoMethodError) end it 'must require attributes' do expect(Admin.new.required_attributes?).to be_falsey expect(Admin.new(created_at: Date.today).required_attributes?).to be_truthy end it 'must validate attribute format' do error_msg = "'local' does not match the '/^\\d{2}-\\d{2}-\\d{4}$/' format" expect { Admin.new.birthday = 'local' }.to raise_error(AlphaCard::InvalidAttributeFormat, error_msg) end it 'must not allow to add invalid attributes' do expect do Admin.class_eval <<-RUBY.strip attribute :some, values: 10 RUBY end.to raise_error(ArgumentError) expect do Admin.class_eval <<-RUBY.strip attribute :some, values: [] RUBY end.to raise_error(ArgumentError) expect do Admin.class_eval <<-RUBY.strip attribute :some, format: 10 RUBY end.to raise_error(ArgumentError) end end end
class Category < ActiveRecord::Base has_many :sub_categories has_many :event_masters has_many :event_category_mappings, through: :event_masters end
# # Author:: Joshua Timberman <joshua@opscode.com> # Copyright (c) 2013, Opscode, Inc. <legal@opscode.com> # License:: Apache License, Version 2.0 # # 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. # # These attributes are passed into the s3cfg resource which are # rendered in the s3cfg.erb template. default['s3cfg']['config'] = { "access_key" => "", "acl_public" => "False", "bucket_location" => "US", "cloudfront_host" => "cloudfront.amazonaws.com", "cloudfront_resource" => "/2010-07-15/distribution", "default_mime_type" => "binary/octet-stream", "delete_removed" => "False", "dry_run" => "False", "encoding" => "UTF-8", "encrypt" => "False", "force" => "False", "get_continue" => "False", "gpg_command" => "/usr/bin/gpg", "gpg_decrypt" => "%(gpg_command)s -d --verbose --no-use-agent --batch --yes --passphrase-fd %(passphrase_fd)s -o %(output_file)s %(input_file)s", "gpg_encrypt" => "%(gpg_command)s -c --verbose --no-use-agent --batch --yes --passphrase-fd %(passphrase_fd)s -o %(output_file)s %(input_file)s", "gpg_passphrase" => "", "guess_mime_type" => "True", "host_base" => "s3.amazonaws.com", "host_bucket" => "%(bucket)s.s3.amazonaws.com", "human_readable_sizes" => "False", "list_md5" => "False", "preserve_attrs" => "True", "progress_meter" => "True", "proxy_host" => "", "proxy_port" => "0", "recursive" => "False", "recv_chunk" => "4096", "secret_key" => "", "send_chunk" => "4096", "simpledb_host" => "sdb.amazonaws.com", "skip_existing" => "False", "urlencoding_mode" => "normal", "use_https" => "True", "verbosity" => "WARNING" }
require_relative 'sequence_generator' require_relative 'sequence' require_relative 'guess_builder' require_relative 'sequence_matcher' require_relative 'guess' require_relative 'guess_printer' class Game attr_reader :guess_history, :sequence, :turns, :game_over, :guess_builder def initialize(code_length, colors) cl = code_length @colors = colors @guess_history = [] @game_over = false @sequence ||= SequenceGenerator.new(cl, colors).generate.sequence @guess_builder = GuessBuilder.new end def turns @guess_history.length end def time time = -(@guess_history[0].time - @guess_history[-1].time) end def new_guess(input) sequence_length = @sequence.length guess = @guess_builder.build(input, sequence_length) if guess guess.results = SequenceMatcher.new(guess, @sequence).get_result add_guess(guess) guess else false end end def guess_printer GuessPrinter.new(@guess_history) end def add_guess(guess) @guess_history << guess if guess.results.fetch :full_match game_over @game_over = true end end def game_over system('clear') puts "Excellent work! You guessed my secret code in #{turns} turns." puts "That shit took you #{(time/60).to_i} minutes and #{((time - (time/60)) % 60).to_i} seconds." @game_over = true puts "Play again? (y/n)" end def game_over? @game_over end end if __FILE__ == $0 blah = Game.new blah.sequence blah.new_guess("rgby") # raise blah.guess_history.inspect # ~> RuntimeError: [#<Guess:0x0000010114a800 @guess=["r", "g", "b", "y"], @time=2014-06-18 13:21:49 -0600, @results={:full_match=>false, :correct_color=>3, :correct_position=>1}>] end
class CreateSales < ActiveRecord::Migration def change create_table :sales do |t| t.string :site_name t.string :url t.string :staff_name t.string :email t.string :address t.string :phone_number t.timestamps null: false t.index :email end end end
class UserRolesController < ApplicationController before_action :set_user_role, only: [:show, :edit, :update] before_action :authenticate_user! # GET /user_roles # GET /user_roles.json def index @user_roles = UserRole.all end # GET /user_roles/1 # GET /user_roles/1.json def show end # GET /user_roles/new def new @user_role = UserRole.new end # GET /user_roles/1/edit def edit end # POST /user_roles # POST /user_roles.json def create @user_role = UserRole.new(role_id: 2, user_id: params[:id]) respond_to do |format| if @user_role.save format.html {redirect_back(fallback_location: super_admin_home_path); flash[:success] = 'Succesfully promoted to admin.'} format.json {render :show, status: :created, location: @user_role} else format.html {redirect_back(fallback_location: super_admin_home_path); flash[:danger] = 'User is already admin.'} format.json {render json: @user_role.errors, status: :unprocessable_entity} end end end # PATCH/PUT /user_roles/1 # PATCH/PUT /user_roles/1.json def update respond_to do |format| if @user_role.update(user_role_params) format.html {redirect_to @user_role, notice: 'User role was successfully updated.'} format.json {render :show, status: :ok, location: @user_role} else format.html {render :edit} format.json {render json: @user_role.errors, status: :unprocessable_entity} end end end # DELETE /user_roles/1 # DELETE /user_roles/1.json def destroy @user_role = UserRole.where(user_id: params[:id], role_id: 2).first respond_to do |format| if @user_role.destroy format.html {redirect_back(fallback_location: super_admin_home_path); flash[:success] = 'Succesfully demoted.'} else format.html {redirect_back(fallback_location: super_admin_home_path); flash[:danger] = 'Error demoting admin.'} end end end private # Use callbacks to share common setup or constraints between actions. def set_user_role @user_role = UserRole.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def user_role_params params.require(:user).permit(:role, :user) end end
# jekyll-i18n # โ€” A simple plugin for multilingual Jekyll sites # Author: Liam Edwards-Playne <liamz.co> # License: GPLv3 require 'i18n' require 'pathname' module Jekyll I18n.load_path += Dir['_i18n/*.yml'] class TranslateTag < Liquid::Tag def initialize(tag_name, text, tokens) super @text = text end # Gets a translation of a key according to the page.lang def render(context) # See https://www.iana.org/assignments/language-subtag-registry for full list of tags I18n.locale = context.registers[:page]['lang'].intern if context[@text.strip] then I18n.t(context[@text.strip]) else I18n.t(@text.strip) end end end # Necessary filter when you need multi-language site variables (e.g. menus) module TranslateFilter def translate(input) I18n.locale = @context.registers[:page]['lang'].intern I18n.t(input.strip) end alias_method :t, :translate end class Document # Enhances original by applying /LANG/URL. alias_method :_post_read, :post_read # Enhances the original method to extract the language from the extension. # Then adds it as a tag def post_read # puts path rv = _post_read() lang = (basename.split '.')[1] if lang == 'mul' or I18n.available_locales.include? lang.intern data['lang'] = lang else data['lang'] = 'und' if not self.is_a? Jekyll::Layout end # Add the language as a tag. data['tags'] ||= [] data['tags'] << data['lang'] # puts lang rv end alias_method :_url, :url # Enhances original by applying /LANG/URL. def url @url = _url lang = data['lang'] # For 'mul' we generate multiple pages โ€” inappropriate to have a url here. # For 'und' there is no language โ€” return. if lang == 'mul' or lang == 'und'or lang == nil return @url end # Gets filename name = Pathname.new(@url).basename.to_s # this could be bad if the directory has the same name as the file. # XXX substitute the last occurance in a string, not the first. nameWithoutLang = @url.sub(name, name.sub('.'+lang, '')) nameWithoutLang == '/index/' ? "/#{lang}/index.html" : "/#{lang}/"+nameWithoutLang end end module Convertible alias_method :_read_yaml, :read_yaml # Enhances the original method to extract the language from the extension. # Then adds it as a tag def read_yaml(base, name) rv = _read_yaml(base, name) # Infer language from first dot in filename. lang = (name.split '.')[1] if lang == 'mul' or I18n.available_locales.include? lang.intern data['lang'] = lang else # Default language is undefined. # If we are procesing a layout, we don't set a language/ # This is so when we do render_liquid, we don't override the page's lang. data['lang'] = 'und' if not self.is_a? Jekyll::Layout end # Add the language as a tag. data['tags'] ||= [] data['tags'] << data['lang'] rv end alias_method :_render_liquid, :render_liquid def render_liquid(content, payload, info, path = nil) info[:registers][:page]['lang'] = data['lang'] _render_liquid(content, payload, info) end end class Page alias_method :_url, :url # Enhances original by applying /LANG/URL. def url @url = _url lang = data['lang'] # For 'mul' we generate multiple pages โ€” inappropriate to have a url here. # For 'und' there is no language โ€” return. if lang == 'mul' or lang == 'und' return @url end # Gets filename name = Pathname.new(@url).basename.to_s # this could be bad if the directory has the same name as the file. # XXX substitute the last occurance in a string, not the first. nameWithoutLang = @url.sub(name, name.sub('.'+lang, '')) nameWithoutLang == '/index/' ? "/#{lang}/index.html" : "/#{lang}/"+nameWithoutLang end end end Liquid::Template.register_tag('t', Jekyll::TranslateTag) Liquid::Template.register_filter(Jekyll::TranslateFilter)
class VVrite def initialize(filename) @filename = filename end def slug @slug ||= @filename.gsub(VVriter.config.vvrites_extension, '') end def title @title ||= begin File.open(full_path, &:readline).gsub(/^[\wะฐ-ัะ-ะฏ]+/, '').strip rescue StandardError return nil end end def full_path @full_path ||= File.join(Storage::STORAGE_PATH, @filename) end end
class AddTideField < ActiveRecord::Migration def self.up add_column :weather_locations, :tide_key, :string end def self.down remove_column :weather_locations, :tide_key end end
# frozen_string_literal: true # rubocop:todo all module Mongo module CRUD # Represents a CRUD specification test. class Spec # Instantiate the new spec. # # @param [ String ] test_path The path to the file. # # @since 2.0.0 def initialize(test_path) @spec = ::Utils.load_spec_yaml_file(test_path) @description = File.basename(test_path) @data = BSON::ExtJSON.parse_obj(@spec['data']) @tests = @spec['tests'] # Introduced with Client-Side Encryption tests @json_schema = BSON::ExtJSON.parse_obj(@spec['json_schema']) @key_vault_data = BSON::ExtJSON.parse_obj(@spec['key_vault_data']) @encrypted_fields = BSON::ExtJSON.parse_obj(@spec['encrypted_fields'], mode: :bson) @requirements = if run_on = @spec['runOn'] run_on.map do |spec| Requirement.new(spec) end elsif Requirement::YAML_KEYS.any? { |key| @spec.key?(key) } [Requirement.new(@spec)] else nil end end # @return [ String ] description The spec description. # # @since 2.0.0 attr_reader :description attr_reader :requirements # @return [ Hash ] The jsonSchema collection validator. attr_reader :json_schema # @return [ Array<Hash> ] Data to insert into the key vault before # running each test. attr_reader :key_vault_data # @return [ Hash ] An encryptedFields option that should be set on the # collection (using createCollection) before each test run. attr_reader :encrypted_fields def collection_name # Older spec tests do not specify a collection name, thus # we provide a default here @spec['collection_name'] || 'crud_spec_test' end def bucket_name @spec['bucket_name'] end def database_name @spec['database_name'] end # Get a list of Test instances, one for each test definition. def tests @tests.map do |test| Mongo::CRUD::CRUDTest.new(self, @data, test) end end end end end
require 'scripts/models/map' require 'scripts/entity_system/component' module Components class Level < Base register :level field :map, type: Models::Map, default: nil end end
require 'capybara/poltergeist' Capybara.register_driver :poltergeist do |app| Capybara::Poltergeist::Driver.new(app, :inspector => true) end Capybara.javascript_driver = :poltergeist # The lines like "The microcosm HAS..." are not behavior driven. When("print body") do print body end Given("there is a microcosm {string}") do |name| @the_microcosm = Microcosm.create!(:name => name, :key => name.downcase, :members_count => 0, lat: 38.9, lon:-77.03, min_lat: 38.516 * 10**7, max_lat: 39.472 * 10**7, min_lon: -77.671 * 10**7, max_lon: -76.349 * 10**7) end Given("the microcosm has a member {string}") do |name| @the_microcosm.members.create(user: User.create(name: name)) end Given("the microcosm has a member {string} with uid {string} at provider {string}") do |name, uid, provider| u = User.find_or_initialize_by(uid: uid) do |u| u.name = name end @the_microcosm.members.create(user: u) # visit "/users/new" # fill_in "Name", with: "Brian DeRocher" # click_button # visit "/members/new" # fill_in "Microcosm", with: '1' # fill_in "User", with: '1' # click_button end Given("the microcosm has a changeset {string} by {string} {string}") do |chid, display_name, user_id| u = User.find_or_create_by(uid: user_id) do |u| u.uid = user_id u.name = display_name end @the_microcosm.microcosm_changesets.create!(changeset_id: chid, review_num: 0, user_id: u.id) end Given("the microcosm has an organizer {string} with uid {string}") do |name, uid| @the_microcosm.organizers.create(user: User.create!(name: name, uid: uid)) end Given("the microcosm has a {string} event") do |title| @the_microcosm.events.create(title: title) end Given("the microcosm has facebook page {string}") do |fb| @the_microcosm.facebook = fb @the_microcosm.save end Given("the microcosm has twitter account {string}") do |acct| @the_microcosm.twitter = acct @the_microcosm.save end Given("I am on the microcosm {string} page") do |name| visit "/microcosms/" + name.downcase end Given("I am on the home page") do visit "/" end Given("I click {string}") do |link| click_link link end Given("I sign in as {string}") do |name| @the_user = User.find_by(name: name) OmniAuth.config.add_mock(:osm, {:uid => @the_user.uid, :provider => @the_user.provider, :info => {:name => name}}) visit "/" click_link "Sign in" click_link "Sign in with OSM" end Then("I should see the microcosm {string} name") do |name| expect(page).to have_content(name) end Then("I should see the microcosm has {string} members") do |count| expect(page).to have_content(count) end Then("I should see {string} in the list of members") do |name| within '#Members' do expect(page).to have_content('Members') expect(page).to have_content(name) end end Then("I should see {string} in the list of organizers of this microcosm") do |name| expect(page).to have_content('Organizers') within '.organizers' do expect(page).to have_content(name) end end Then("I should see the {string} event in the list of events") do |title| within '#Events' do expect(page).to have_content('Events') expect(page).to have_content(title) end end Then("I should see the {string} link to {string}") do |title, href| expect(page).to have_link(title, :href => href) end Then("I should see a map of the microcosm centered at their AOI") do expect(page).to have_css('#Map') expect(page).to have_css('.leaflet-container') coords = page.evaluate_script("window.map.getCenter()") expect(coords['lat']).to eq(@the_microcosm.lat) expect(coords['lng']).to eq(@the_microcosm.lon) end Then("I should see {string}") do |msg| expect(page).to have_content(msg) end
class Order < ActiveRecord::Base has_many :items, :class_name => 'OrderItem' def add(product) items << items.build(:product => product, :quantity => 1) end class << self def next_in_queue first end end end
require 'spec_helper' describe "RSpec Configuration" do describe "configuring Capybara without Cucumber" do it "should not set the driver to selenium_with_firebug by default" do Capybara.current_driver.should_not == :selenium_with_firebug end it "should set the driver to selenium_with_firebug when tagged", :firebug => true do Capybara.current_driver.should == :selenium_with_firebug end end end
class ImagesController < ApplicationController before_action :set_image, except: [:create, :index] def index @images = Image.all end def create @image = Image.new(image_params) respond_to do |format| if @image.save format.html {redirect_to images_path, notice: "Image Successfully Uploaded"} else format.html {render :new } format.json { @image.errors status: :unprocessable_entity} end end end def update end def destroy end private def set_image @image = Image.find(params[:id]) end def image_params params.require(:image).permit(:image) end end
require 'rails_helper' RSpec.describe Api::V1::PlayersController, :type => :controller do let(:game) { build(:game, :id => 10) } let(:player) { build(:player, :game => game) } let(:user) { player.user } describe 'PATCH /games/:game_id/player' do subject { patch :update, {game_id: 10, organization_id: 20} } it_behaves_like 'an authenticated only action' it 'updates the player data in the game' do allow(Game).to receive(:find).with('10').and_return(game) allow(game).to receive(:player).with(user).and_return(player) expect(player).to receive(:update!).with(organization_id: '20') api_user user expect(subject.body).to serialize_object(game).with(GameSerializer, { :scope => user, :include => 'players,trivia,trivia.options' }) end end end
#!/usr/bin/env ruby # vim: noet module Fuzz module Error class FuzzError < StandardError end # Raised by Fuzz::Parser when results # are accessed before they have been # built (by calling Fuzz::Parser#parse) class NotParsedYet < FuzzError end end end
class BubbleSortService attr_reader :array def initialize array @array = array end def perform return array if array.size <= 1 swapped = true while swapped do swapped = false 0.upto(array.size-2) do |i| if array[i] > array[i+1] array[i], array[i+1] = array[i+1], array[i] swapped = true end end end array end end
Mock Test Examples A bunch of code snippets to analyze. None of them has any description, but most demonstrate one specific concept from RB101. I would normally copy 5โ€“10 into a separate doc in Boostnote, and describe them there. num = 5 if (num < 10) puts "small number" else puts "large number" end [1, 2, 3].map do |num| if num > 1 puts num else num end end [2, 5, 3, 4, 1].sort do |a, b| b <=> a end def select_vowels(str) selected_chars = '' counter = 0 loop do current_char = str[counter] if 'aeiouAEIOU'.include?(current_char) selected_chars << current_char end counter += 1 break if counter == str.size end selected_chars end arr1 = ["a", "b", "c"] arr2 = arr1.dup arr2.map! do |char| char.upcase end arr1 arr2 arr1 = ["a", "b", "c"].freeze arr2 = arr1.dup arr2 << "d" arr2 arr1 def some_method(a) puts a end some_method(5) fruits = ['apple', 'banana', 'pear'] transformed_elements = [] counter = 0 loop do current_element = fruits[counter] transformed_elements << current_element + 's' # appends transformed string into array counter += 1 break if counter == fruits.size end transformed_elements [[8, 13, 27], ['apple', 'banana', 'cantaloupe']].map do |arr| arr.select do |item| if item.to_s.to_i == item # if it's an integer item > 13 else item.size < 6 end end end # => ? arr = [['1', '8', '11'], ['2', '6', '13'], ['2', '12', '15'], ['1', '8', '9']] arr.sort_by do |sub_arr| sub_arr.map do |num| num.to_i end end def some_method a = 1 5.times do puts a b = 2 end puts a puts b end some_method objects = ['hello', :key, 10, []] counter = 0 loop do break if counter == objects.size puts objects[counter].class counter += 1 end USERNAME = 'Batman' def authenticate puts "Logging in #{USERNAME}" end authenticate [1, 2, 3].select do |num| num > 5 'hi' end counter = 0 loop do counter += 1 next if counter.odd? puts counter break if counter > 5 end ['ant', 'bear', 'cat'].each_with_object({}) do |value, hash| hash[value[0]] = value end loop do MY_TEAM = "Phoenix Suns" break end puts MY_TEAM [1, 2, 3].each do |num| puts num end str = 'How do you get to Carnegie Hall?' arr = str.split arr.join long, short = { a: "ant", b: "bear", c: "cat" }.partition do |key, value| value.size > 3 end long.to_h short.to_h [1, 2, 3].each { |num| puts num } arr = [1, 2, 3, 4, 5] counter = 0 loop do arr[counter] += 1 counter += 1 break if counter == arr.size end arr def greetings(str) puts "Goodbye" end word = "Hello" greetings(word) counter = 0 loop do break if counter == 0 puts 'Hello!' counter += 1 end def add_name(arr, name) arr << name end names = ['bob', 'kim'] add_name(names, 'jim') puts names.inspect arr = [3, 'd', nil] arr[2] # => nil arr[3] loop do b = 1 break end puts b def double_numbers(numbers) doubled_numbers = [] counter = 0 loop do break if counter == numbers.size current_number = numbers[counter] doubled_numbers << current_number * 2 counter += 1 end doubled_numbers end my_numbers = [1, 4, 3, 7, 2, 6] double_numbers(my_numbers) def rolling_buffer1(buffer, max_buffer_size, new_element) buffer << new_element buffer.shift if buffer.size > max_buffer_size buffer end def rolling_buffer2(input_array, max_buffer_size, new_element) buffer = input_array + [new_element] buffer.shift if buffer.size > max_buffer_size buffer end def factors(number) divisor = number factors = [] begin factors << number / divisor if number % divisor == 0 divisor -= 1 end until divisor == 0 factors end a = 1 loop do puts a a = a + 1 break end puts a def greetings puts "Goodbye" end word = "Hello" greetings do puts word end n = 10 [1, 2, 3].each do |n| puts n end def greetings yield puts "Goodbye" end word = "Hello" greetings do puts word end if false puts 'hi' else puts 'goodbye' end numbers = [1, 2, 2, 3] numbers.uniq puts numbers a = 'hi' def some_method puts a end some_method def add_name(arr, name) arr = arr << name end names = ['bob', 'kim'] add_name(names, 'jim') puts names.inspect a = 1 loop do b = 2 loop do c = 3 puts a puts b puts c break end puts a puts b puts c break end puts a puts b puts c def change_name(name) name = 'severus' end name = 'ron' change_name(name) puts name numbers = [1, 2, 3, 4, 5] numbers.delete_at(1) numbers.delete(1) def cap(str) str.capitalize! end name = "harry" cap(name) puts name a = "hello" [1, 2, 3].map { |num| a } def add_eight(number) number + 8 end number = 2 how_deep = "number" 5.times { how_deep.gsub!("number", "add_eight(number)") } p how_deep answer = 42 def mess_with_it(some_number) some_number += 8 end new_answer = mess_with_it(answer) p answer - 8 def rps(fist1, fist2) if fist1 == "rock" (fist2 == "paper") ? "paper" : "rock" elsif fist1 == "paper" (fist2 == "scissors") ? "scissors" : "paper" else (fist2 == "rock") ? "rock" : "scissors" end end puts rps(rps(rps("rock", "paper"), rps("rock", "scissors")), "rock") if false greeting = โ€œhello worldโ€ end greeting def foo(param = "no") "yes" end def bar(param = "no") param == "no" ? "yes" : "no" end bar(foo) greetings = { a: 'hi' } informal_greeting = greetings[:a] informal_greeting << ' there' puts informal_greeting # => "hi there" puts greetings def select_letter(sentence, character) selected_chars = '' counter = 0 loop do break if counter == sentence.size current_char = sentence[counter] if current_char == character selected_chars << current_char end counter += 1 end selected_chars end select_letter(question, 'a').size select_letter(question, 't').size select_letter(question, 'z').size [1, 2, 3].select do |num| num.odd? end def mess_with_vars(one, two, three) one = two two = three three = one end one = "one" two = "two" three = "three" mess_with_vars(one, two, three) puts "one is: #{one}" puts "two is: #{two}" puts "three is: #{three}" str = 'abcdefghi' str[2] [1, 2, 3].each_with_object([]) do |num, array| array << num if num.odd? end def mess_with_vars(one, two, three) one.gsub!("one","two") two.gsub!("two","three") three.gsub!("three","one") end one = "one" two = "two" three = "three" mess_with_vars(one, two, three) puts "one is: #{one}" puts "two is: #{two}" puts "three is: #{three}" [1, 2, 3].map do |num| num.odd? puts num end arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] arr[2, 3] arr[2, 3][0] { a: 'ant', b: 'bear' }.map do |key, value| if value.size > 3 value end end
class WamSms require 'httparty' include HTTParty # Disable SSL Verification on CA since # its failing on this particular vendor # until futher investigation on the issue # verification of the CA is disabled, # security risk is 'LOW' default_options.update(verify: false) # debug_output $stderr base_uri "https://messaging.wamsms.com" def initialize(username, password) @params = { user: username, password: password } end def send_sms(senderid, to, message) @params[:senderid] = senderid @params[:mobiles] = to @params[:sms] = message options = { query: @params, headers: { "User-Agent" => "Swiftch Scorecard 0.0.1" } } Rails.logger.info "Sending SMS: to: #{@params[:mobiles]} text: #{@params[:sms]}" process_response self.class.get("/sendsms.jsp", options) end private def process_response data response = data["smslist"] unless response.has_key?("error") Rails.logger.info "SMS Sent with Message ID: #{response["sms"]["messageid"]}" return true else error_mesg = response["error"] Rails.logger.info "SMS Sending failed with Error Code: #{error_mesg["error_code"]}: #{error_mesg["error_description"]}" return false end end end
class Address < ActiveRecord::Base belongs_to :country validates :first_name, :last_name, :address, :zip, :city, :phone, :country, presence: true end
module Netlink class Error < StandardError; end class DecodeError < StandardError; end # Base error class during decoding class IncompleteMessageError < DecodeError; end # Need more data to continue decoding end
require 'nested_config/version' # Simple, static, nested application configuration. # # == Example # # require 'nested_config' # # class MyApp # def self.configure # yield config # end # # def self.config # @config ||= MyConfig.new # end # # class MyConfig < NestedConfig # end # end # # MyApp.configure do |config| # config.coins = 1000 # config.user do |user| # user.max = 5 # end # config.queue do |queue| # queue.workers do |workers| # workers.max = 2 # workers.timeout = 60.seconds # end # end # end # class NestedConfig autoload :EvaluateOnce, 'nested_config/evaluate_once' def initialize @hash = {} end def [](name, *args) @hash[name.to_s] end def []=(name, value) @hash[name.to_s] = value end def __hash__ @hash end def __hash__=(hash) @hash = hash end # Define a config with special names # # Example: # config = NestedConfig.new.tap do |config| # config._ "mix & match" do |mix_and_match| # mix_and_match.name = "Mix & match" # # ... # end # end # # config["mix & match"].name # => Mix & match def _(name) raise ArgumentError, "provide missing block" unless block_given? config = self[name] ||= self.class.new yield config end def method_missing(name, *args, &block) if block_given? _(name, &block) else key = name.to_s index = key.rindex('='.freeze) if index key = key[0, index] self[key] = args.first else self[key, *args] end end end def respond_to_missing?(name, include_private=false) __hash__.key?(name.to_s) || super end end
require 'spec_helper' describe "partners/edit" do before(:each) do @partner = assign(:partner, stub_model(Partner, :people_type => "MyString", :partner_receives_email => false, :partner_receives_sms => false, :customer_receives_email => false, :customer_receives_sms => false, :observation => "MyText", :active => false, :plan => 1, :title_partner => nil, :service_type => nil, :record_active => false )) end it "renders the edit partner form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form[action=?][method=?]", partner_path(@partner), "post" do assert_select "input#partner_people_type[name=?]", "partner[people_type]" assert_select "input#partner_partner_receives_email[name=?]", "partner[partner_receives_email]" assert_select "input#partner_partner_receives_sms[name=?]", "partner[partner_receives_sms]" assert_select "input#partner_customer_receives_email[name=?]", "partner[customer_receives_email]" assert_select "input#partner_customer_receives_sms[name=?]", "partner[customer_receives_sms]" assert_select "textarea#partner_observation[name=?]", "partner[observation]" assert_select "input#partner_active[name=?]", "partner[active]" assert_select "input#partner_plan[name=?]", "partner[plan]" assert_select "input#partner_title_partner[name=?]", "partner[title_partner]" assert_select "input#partner_service_type[name=?]", "partner[service_type]" assert_select "input#partner_record_active[name=?]", "partner[record_active]" end end end
# The base class for direction module Direction class BaseDirection # Make a left turn from current direction. # To be implemented by sub classes. # ====== Returns # - the new direction after left turn def turnLeft raise NotImplementedError, 'BaseDirection is not intended to be used directly.' end # Make a right turn from current direction. # To be implemented by sub classes. # ====== Returns # - the new direction after right turn def turnRight raise NotImplementedError, 'BaseDirection is not intended to be used directly.' end # Move horizontally forward from current postion. # To be implemented by sub classes. # ====== Parameters # - +x+:: the current x position # - +y+:: the current y position # ====== Returns # - the new x and y position after move def move(x, y) raise NotImplementedError, 'BaseDirection is not intended to be used directly.' end end end
class Evaluator < ActiveRecord::Base has_many :evaluations, inverse_of: :evaluator, dependent: :restrict_with_error has_many :workers, through: :evaluations has_many :instruments, through: :evaluations def name first_name.to_s + ' ' + last_name.to_s end end
module Test class Client < Evil::Client settings do param :subdomain, type: Dry::Types["strict.string"] option :version, type: Dry::Types["coercible.int"], default: proc { 1 } option :user, type: Dry::Types["strict.string"] option :password, type: Dry::Types["coercible.string"], optional: true option :token, type: Dry::Types["coercible.string"], optional: true end base_url do |settings| "https://#{settings.subdomain}.example.com/api/v#{settings.version}/" end end end